diff --git a/config/spotless/formatting.xml b/config/spotless/formatting.xml index 564744fe8aa..4be3da5e7b4 100644 --- a/config/spotless/formatting.xml +++ b/config/spotless/formatting.xml @@ -415,8 +415,8 @@ - - + + diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddApiKeySource.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddApiKeySource.java index 923568d013b..ee3e7fe33ae 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddApiKeySource.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddApiKeySource.java @@ -25,17 +25,17 @@ public List getApiTypes() { @Override public OpenApi after(Context context, OpenApi openApi) { return context.getService() - .getTrait(ApiKeySourceTrait.class) - .map(trait -> { - LOGGER.fine( - () -> String.format( - "Adding %s trait to %s", - EXTENSION_NAME, - context.getService().getId() - ) - ); - return openApi.toBuilder().putExtension(EXTENSION_NAME, trait.getValue()).build(); - }) - .orElse(openApi); + .getTrait(ApiKeySourceTrait.class) + .map(trait -> { + LOGGER.fine( + () -> String.format( + "Adding %s trait to %s", + EXTENSION_NAME, + context.getService().getId() + ) + ); + return openApi.toBuilder().putExtension(EXTENSION_NAME, trait.getValue()).build(); + }) + .orElse(openApi); } } diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddAuthorizers.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddAuthorizers.java index f8975bd7df7..8a4469963bb 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddAuthorizers.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddAuthorizers.java @@ -61,14 +61,14 @@ public List getApiTypes() { @Override public Map> updateSecurity( - Context context, - Shape shape, - SecuritySchemeConverter converter, - Map> requirement + Context context, + Shape shape, + SecuritySchemeConverter converter, + Map> requirement ) { // Only modify requirements that exactly match the updated scheme. if (requirement.size() != 1 - || !requirement.keySet().iterator().next().equals(converter.getOpenApiAuthSchemeName())) { + || !requirement.keySet().iterator().next().equals(converter.getOpenApiAuthSchemeName())) { return requirement; } @@ -76,19 +76,19 @@ public Map> updateSecurity( AuthorizerIndex authorizerIndex = AuthorizerIndex.of(context.getModel()); return authorizerIndex.getAuthorizer(service, shape) - // Remove the original scheme authentication scheme from the operation if found. - // Add a new scheme for this operation using the authorizer name. - .map(authorizer -> MapUtils.of(authorizer, requirement.values().iterator().next())) - .orElse(requirement); + // Remove the original scheme authentication scheme from the operation if found. + // Add a new scheme for this operation using the authorizer name. + .map(authorizer -> MapUtils.of(authorizer, requirement.values().iterator().next())) + .orElse(requirement); } @Override public OperationObject updateOperation( - Context context, - OperationShape shape, - OperationObject operation, - String httpMethodName, - String path + Context context, + OperationShape shape, + OperationObject operation, + String httpMethodName, + String path ) { ServiceShape service = context.getService(); AuthorizerIndex authorizerIndex = AuthorizerIndex.of(context.getModel()); @@ -111,21 +111,21 @@ public OperationObject updateOperation( } return operation.toBuilder() - .addSecurity(MapUtils.of(operationAuth, ListUtils.of())) - .build(); + .addSecurity(MapUtils.of(operationAuth, ListUtils.of())) + .build(); } private boolean usesApiGatewayApiKeys(ServiceShape service, String operationAuth) { // Get the authorizer for this operation if it has no "type" or // "customAuthType" set, as is required for API Gateway's API keys. Optional definitionOptional = service.getTrait(AuthorizersTrait.class) - .flatMap( - authorizers -> authorizers.getAuthorizer(operationAuth) - .filter( - authorizer -> !authorizer.getType().isPresent() - && !authorizer.getCustomAuthType().isPresent() - ) - ); + .flatMap( + authorizers -> authorizers.getAuthorizer(operationAuth) + .filter( + authorizer -> !authorizer.getType().isPresent() + && !authorizer.getCustomAuthType().isPresent() + ) + ); if (!definitionOptional.isPresent()) { return false; @@ -140,15 +140,15 @@ private boolean usesApiGatewayApiKeys(ServiceShape service, String operationAuth @Override public OpenApi after(Context context, OpenApi openapi) { return context.getService() - .getTrait(AuthorizersTrait.class) - .map(authorizers -> addComputedAuthorizers(context, openapi, authorizers)) - .orElse(openapi); + .getTrait(AuthorizersTrait.class) + .map(authorizers -> addComputedAuthorizers(context, openapi, authorizers)) + .orElse(openapi); } private OpenApi addComputedAuthorizers( - Context context, - OpenApi openApi, - AuthorizersTrait trait + Context context, + OpenApi openApi, + AuthorizersTrait trait ) { OpenApi.Builder builder = openApi.toBuilder(); ComponentsObject.Builder components = openApi.getComponents().toBuilder(); @@ -172,19 +172,19 @@ private OpenApi addComputedAuthorizers( } private boolean isAuthConverterMatched( - Context context, - SecuritySchemeConverter converter, - ShapeId scheme + Context context, + SecuritySchemeConverter converter, + ShapeId scheme ) { return converter.getAuthSchemeId().equals(scheme) - && context.getService().hasTrait(converter.getAuthSchemeType()); + && context.getService().hasTrait(converter.getAuthSchemeType()); } private SecurityScheme convertAuthScheme( - Context context, - SecuritySchemeConverter converter, - AuthorizerDefinition authorizer, - String authorizerName + Context context, + SecuritySchemeConverter converter, + AuthorizerDefinition authorizer, + String authorizerName ) { T authTrait = context.getService().expectTrait(converter.getAuthSchemeType()); SecurityScheme createdScheme = converter.createSecurityScheme(context, authTrait); @@ -203,27 +203,27 @@ private SecurityScheme convertAuthScheme( } ObjectNode authorizerNode = Node.objectNodeBuilder() - .withOptionalMember("type", authorizer.getType().map(Node::from)) - .withOptionalMember("authorizerUri", authorizer.getUri().map(Node::from)) - .withOptionalMember("authorizerCredentials", authorizer.getCredentials().map(Node::from)) - .withOptionalMember( - "identityValidationExpression", - authorizer.getIdentityValidationExpression().map(Node::from) - ) - .withOptionalMember("identitySource", authorizer.getIdentitySource().map(Node::from)) - .withOptionalMember( - "authorizerResultTtlInSeconds", - authorizer.getResultTtlInSeconds().map(Node::from) - ) - .withOptionalMember( - "authorizerPayloadFormatVersion", - authorizer.getAuthorizerPayloadFormatVersion().map(Node::from) - ) - .withOptionalMember( - "enableSimpleResponses", - authorizer.getEnableSimpleResponses().map(Node::from) - ) - .build(); + .withOptionalMember("type", authorizer.getType().map(Node::from)) + .withOptionalMember("authorizerUri", authorizer.getUri().map(Node::from)) + .withOptionalMember("authorizerCredentials", authorizer.getCredentials().map(Node::from)) + .withOptionalMember( + "identityValidationExpression", + authorizer.getIdentityValidationExpression().map(Node::from) + ) + .withOptionalMember("identitySource", authorizer.getIdentitySource().map(Node::from)) + .withOptionalMember( + "authorizerResultTtlInSeconds", + authorizer.getResultTtlInSeconds().map(Node::from) + ) + .withOptionalMember( + "authorizerPayloadFormatVersion", + authorizer.getAuthorizerPayloadFormatVersion().map(Node::from) + ) + .withOptionalMember( + "enableSimpleResponses", + authorizer.getEnableSimpleResponses().map(Node::from) + ) + .build(); if (authorizerNode.size() != 0) { schemeBuilder.putExtension(EXTENSION_NAME, authorizerNode); } diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddBinaryTypes.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddBinaryTypes.java index f793ba39dc3..7548a357d96 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddBinaryTypes.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddBinaryTypes.java @@ -48,14 +48,14 @@ public OpenApi after(Context context, OpenApi openApi) { if (!binaryTypes.isEmpty()) { LOGGER.fine(() -> "Adding recognized binary types to model: " + binaryTypes); return openApi.toBuilder() - .putExtension( - EXTENSION_NAME, - Stream.concat(binaryTypes.stream(), Stream.of(DEFAULT_BINARY_TYPE)) - .distinct() - .map(Node::from) - .collect(ArrayNode.collect()) - ) - .build(); + .putExtension( + EXTENSION_NAME, + Stream.concat(binaryTypes.stream(), Stream.of(DEFAULT_BINARY_TYPE)) + .distinct() + .map(Node::from) + .collect(ArrayNode.collect()) + ) + .build(); } return openApi; @@ -68,26 +68,26 @@ private Stream supportedMediaTypes(Context context) { // Find the media types defined on all request and response bindings. return topDownIndex.getContainedOperations(context.getService()) - .stream() - .flatMap( - operation -> Stream.concat( - OptionalUtils.stream( - binaryMediaType(model, httpBindingIndex.getRequestBindings(operation)) - ), - OptionalUtils.stream( - binaryMediaType(model, httpBindingIndex.getResponseBindings(operation)) - ) - ) - ); + .stream() + .flatMap( + operation -> Stream.concat( + OptionalUtils.stream( + binaryMediaType(model, httpBindingIndex.getRequestBindings(operation)) + ), + OptionalUtils.stream( + binaryMediaType(model, httpBindingIndex.getResponseBindings(operation)) + ) + ) + ); } private Optional binaryMediaType(Model model, Map httpBindings) { return httpBindings.values() - .stream() - .filter(binding -> binding.getLocation().equals(HttpBinding.Location.PAYLOAD)) - .map(HttpBinding::getMember) - .flatMap(member -> OptionalUtils.stream(member.getMemberTrait(model, MediaTypeTrait.class))) - .map(MediaTypeTrait::getValue) - .findFirst(); + .stream() + .filter(binding -> binding.getLocation().equals(HttpBinding.Location.PAYLOAD)) + .map(HttpBinding::getMember) + .flatMap(member -> OptionalUtils.stream(member.getMemberTrait(model, MediaTypeTrait.class))) + .map(MediaTypeTrait::getValue) + .findFirst(); } } diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsPreflightIntegration.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsPreflightIntegration.java index 239a227a62f..deb46a7c596 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsPreflightIntegration.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsPreflightIntegration.java @@ -72,16 +72,16 @@ public List getApiTypes() { @Override public PathItem updatePathItem(Context context, String path, PathItem pathItem) { return context.getService() - .getTrait(CorsTrait.class) - .map(corsTrait -> addPreflightIntegration(context, path, pathItem, corsTrait)) - .orElse(pathItem); + .getTrait(CorsTrait.class) + .map(corsTrait -> addPreflightIntegration(context, path, pathItem, corsTrait)) + .orElse(pathItem); } private static PathItem addPreflightIntegration( - Context context, - String path, - PathItem pathItem, - CorsTrait corsTrait + Context context, + String path, + PathItem pathItem, + CorsTrait corsTrait ) { // Filter out any path for which an OPTIONS handler has already been defined if (pathItem.getOptions().isPresent()) { @@ -92,15 +92,15 @@ private static PathItem addPreflightIntegration( LOGGER.fine(() -> "Adding CORS-preflight OPTIONS request and API Gateway integration for " + path); Map headers = deduceCorsHeaders(context, path, pathItem, corsTrait); return pathItem.toBuilder() - .options(createPreflightOperation(context, path, pathItem, headers)) - .build(); + .options(createPreflightOperation(context, path, pathItem, headers)) + .build(); } private static Map deduceCorsHeaders( - Context context, - String path, - PathItem pathItem, - CorsTrait corsTrait + Context context, + String path, + PathItem pathItem, + CorsTrait corsTrait ) { Map corsHeaders = new HashMap<>(); corsHeaders.put(CorsHeader.MAX_AGE, String.valueOf(corsTrait.getMaxAge())); @@ -120,8 +120,8 @@ private static Map deduceCorsHeaders( // Sets additional allowed headers from the API Gateway config. Set additionalAllowedHeaders = context.getConfig() - .getExtensions(ApiGatewayConfig.class) - .getAdditionalAllowedCorsHeadersSet(); + .getExtensions(ApiGatewayConfig.class) + .getAdditionalAllowedCorsHeadersSet(); headerNames.addAll(additionalAllowedHeaders); headerNames.addAll(findAllHeaders(path, pathItem)); @@ -134,8 +134,8 @@ private static Map deduceCorsHeaders( Model model = context.getModel(); TopDownIndex topDownIndex = TopDownIndex.of(model); Map operations = topDownIndex.getContainedOperations(context.getService()) - .stream() - .collect(Collectors.toMap(o -> o.getId().getName(), o -> o)); + .stream() + .collect(Collectors.toMap(o -> o.getId().getName(), o -> o)); for (OperationObject operationObject : pathItem.getOperations().values()) { if (operationObject.getOperationId().isPresent()) { OperationShape operationShape = operations.get(operationObject.getOperationId().get()); @@ -144,12 +144,12 @@ private static Map deduceCorsHeaders( } LOGGER.fine( - () -> String.format( - "Adding the following %s headers to `%s`: %s", - CorsHeader.ALLOW_HEADERS, - path, - headerNames - ) + () -> String.format( + "Adding the following %s headers to `%s`: %s", + CorsHeader.ALLOW_HEADERS, + path, + headerNames + ) ); corsHeaders.put(CorsHeader.ALLOW_HEADERS, String.join(",", headerNames)); @@ -157,8 +157,8 @@ private static Map deduceCorsHeaders( } private static Set getSecuritySchemeRequestHeaders( - Context context, - SecuritySchemeConverter converter + Context context, + SecuritySchemeConverter converter ) { T t = context.getService().expectTrait(converter.getAuthSchemeType()); return converter.getAuthRequestHeaders(context, t); @@ -167,19 +167,19 @@ private static Set getSecuritySchemeRequestHeaders( private static Collection findAllHeaders(String path, PathItem pathItem) { // Get all "in" = "header" parameters and gather up their "name" properties. return pathItem.getOperations() - .values() - .stream() - .flatMap(operationObject -> operationObject.getParameters().stream()) - .filter(parameter -> parameter.getIn().filter(in -> in.equals("header")).isPresent()) - .map( - parameter -> parameter.getName() - .orElseThrow( - () -> new OpenApiException( - "OpenAPI header parameter is missing a name in " + path - ) - ) - ) - .collect(Collectors.toList()); + .values() + .stream() + .flatMap(operationObject -> operationObject.getParameters().stream()) + .filter(parameter -> parameter.getIn().filter(in -> in.equals("header")).isPresent()) + .map( + parameter -> parameter.getName() + .orElseThrow( + () -> new OpenApiException( + "OpenAPI header parameter is missing a name in " + path + ) + ) + ) + .collect(Collectors.toList()); } private static String getAllowMethods(PathItem item) { @@ -187,20 +187,20 @@ private static String getAllowMethods(PathItem item) { } private static OperationObject createPreflightOperation( - Context context, - String path, - PathItem pathItem, - Map headers + Context context, + String path, + PathItem pathItem, + Map headers ) { return OperationObject.builder() - .tags(ListUtils.of("CORS")) - .security(Collections.emptyList()) - .description("Handles CORS-preflight requests") - .operationId(createOperationId(path)) - .putResponse("200", createPreflightResponse(headers)) - .parameters(findPathParameters(pathItem)) - .putExtension(INTEGRATION_EXTENSION, createPreflightIntegration(context, headers, pathItem)) - .build(); + .tags(ListUtils.of("CORS")) + .security(Collections.emptyList()) + .description("Handles CORS-preflight requests") + .operationId(createOperationId(path)) + .putResponse("200", createPreflightResponse(headers)) + .parameters(findPathParameters(pathItem)) + .putExtension(INTEGRATION_EXTENSION, createPreflightIntegration(context, headers, pathItem)) + .build(); } private static List findPathParameters(PathItem pathItem) { @@ -221,24 +221,24 @@ private static List findPathParameters(PathItem pathItem) { private static String createOperationId(String path) { // Make the operationId all alphanumeric camel case characters. return CaseUtils.toCamelCase("Cors" + path, true, '{', '}', '/', '?', '&', '=') - .replaceAll("[^A-Z0-9a-z_]", "_"); + .replaceAll("[^A-Z0-9a-z_]", "_"); } private static ResponseObject createPreflightResponse(Map headers) { // The preflight response just returns all of the computed CORS headers. ResponseObject.Builder builder = ResponseObject.builder() - .description("Canned response for CORS-preflight requests"); + .description("Canned response for CORS-preflight requests"); ParameterObject headerParameter = ParameterObject.builder() - .schema(Schema.builder().type("string").build()) - .build(); + .schema(Schema.builder().type("string").build()) + .build(); headers.forEach((name, value) -> builder.putHeader(name.toString(), Ref.local(headerParameter))); return builder.build(); } private static ObjectNode createPreflightIntegration( - Context context, - Map headers, - PathItem pathItem + Context context, + Map headers, + PathItem pathItem ) { IntegrationResponse.Builder responseBuilder = IntegrationResponse.builder().statusCode("200"); @@ -249,13 +249,13 @@ private static ObjectNode createPreflightIntegration( boolean isPreflightSynced = Boolean.TRUE.equals(context.getConfig().getSyncCorsPreflightIntegration()); MockIntegrationTrait.Builder integration = MockIntegrationTrait.builder() - // See https://forums.aws.amazon.com/thread.jspa?threadID=256140 - .contentHandling("CONVERT_TO_TEXT") - // Passthrough behavior "never" will fail the request with unsupported content type more appropriately. - // https://docs.aws.amazon.com/apigateway/latest/developerguide/integration-passthrough-behaviors.html - .passThroughBehavior(isPreflightSynced ? "never" : "when_no_match") - .putResponse("default", responseBuilder.build()) - .putRequestTemplate(API_GATEWAY_DEFAULT_ACCEPT_VALUE, PREFLIGHT_SUCCESS); + // See https://forums.aws.amazon.com/thread.jspa?threadID=256140 + .contentHandling("CONVERT_TO_TEXT") + // Passthrough behavior "never" will fail the request with unsupported content type more appropriately. + // https://docs.aws.amazon.com/apigateway/latest/developerguide/integration-passthrough-behaviors.html + .passThroughBehavior(isPreflightSynced ? "never" : "when_no_match") + .putResponse("default", responseBuilder.build()) + .putRequestTemplate(API_GATEWAY_DEFAULT_ACCEPT_VALUE, PREFLIGHT_SUCCESS); if (isPreflightSynced) { // Adds request template for every unique Content-Type supported by all path operations. @@ -265,12 +265,12 @@ private static ObjectNode createPreflightIntegration( // example {"statusCode":200}. for (OperationObject operation : pathItem.getOperations().values()) { ObjectNode extensionNode = operation.getExtension(INTEGRATION_EXTENSION) - .flatMap(Node::asObjectNode) - .orElse(Node.objectNode()); + .flatMap(Node::asObjectNode) + .orElse(Node.objectNode()); Set mimeTypes = extensionNode.getObjectMember(REQUEST_TEMPLATES_KEY) - .map(ObjectNode::getStringMap) - .map(Map::keySet) - .orElse(SetUtils.of()); + .map(ObjectNode::getStringMap) + .map(Map::keySet) + .orElse(SetUtils.of()); mimeTypes.forEach(mimeType -> integration.putRequestTemplate(mimeType, PREFLIGHT_SUCCESS)); } } diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsResponseHeaders.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsResponseHeaders.java index 5848485dbc2..a6de197e3ec 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsResponseHeaders.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsResponseHeaders.java @@ -40,35 +40,35 @@ public List getApiTypes() { @Override public OperationObject postProcessOperation( - Context context, - OperationShape shape, - OperationObject operation, - String method, - String path + Context context, + OperationShape shape, + OperationObject operation, + String method, + String path ) { return context.getService() - .getTrait(CorsTrait.class) - .map(trait -> addCorsHeadersToResponses(context, shape, operation, method, trait)) - .orElse(operation); + .getTrait(CorsTrait.class) + .map(trait -> addCorsHeadersToResponses(context, shape, operation, method, trait)) + .orElse(operation); } private OperationObject addCorsHeadersToResponses( - Context context, - OperationShape shape, - OperationObject operationObject, - String method, - CorsTrait trait + Context context, + OperationShape shape, + OperationObject operationObject, + String method, + CorsTrait trait ) { OperationObject.Builder builder = operationObject.toBuilder(); for (Map.Entry entry : operationObject.getResponses().entrySet()) { ResponseObject updated = createUpdatedResponseWithCorsHeaders( - context, - shape, - operationObject, - method, - trait, - entry.getValue() + context, + shape, + operationObject, + method, + trait, + entry.getValue() ); builder.putResponse(entry.getKey(), updated); } @@ -77,12 +77,12 @@ private OperationObject addCorsHeadersToResponses( } private ResponseObject createUpdatedResponseWithCorsHeaders( - Context context, - OperationShape operation, - OperationObject operationObject, - String method, - CorsTrait trait, - ResponseObject response + Context context, + OperationShape operation, + OperationObject operationObject, + String method, + CorsTrait trait, + ResponseObject response ) { // Determine which headers have been added to the response. List headers = new ArrayList<>(); @@ -177,8 +177,8 @@ private ResponseObject createUpdatedResponseWithCorsHeaders( for (String headerName : headers) { if (!response.getHeader(headerName).isPresent()) { ParameterObject headerParam = ParameterObject.builder() - .schema(headerSchema) - .build(); + .schema(headerSchema) + .build(); builder.putHeader(headerName, Ref.local(headerParam)); } } diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsToGatewayResponses.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsToGatewayResponses.java index 349461557aa..05aeb6400b3 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsToGatewayResponses.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsToGatewayResponses.java @@ -42,16 +42,16 @@ final class AddCorsToGatewayResponses implements ApiGatewayMapper { * TODO: Does this need to be made protocol-specific? */ private static final ObjectNode DEFAULT_GATEWAY_RESPONSE = Node.objectNode() - .withMember( - "responseTemplates", - Node.objectNode() - .withMember("application/json", "{\"message\":$context.error.messageString}") - ); + .withMember( + "responseTemplates", + Node.objectNode() + .withMember("application/json", "{\"message\":$context.error.messageString}") + ); private static final ObjectNode DEFAULT_GATEWAY_RESPONSES = Node.objectNodeBuilder() - .withMember("DEFAULT_4XX", DEFAULT_GATEWAY_RESPONSE) - .withMember("DEFAULT_5XX", DEFAULT_GATEWAY_RESPONSE) - .build(); + .withMember("DEFAULT_4XX", DEFAULT_GATEWAY_RESPONSE) + .withMember("DEFAULT_5XX", DEFAULT_GATEWAY_RESPONSE) + .build(); private static final String GATEWAY_RESPONSES_EXTENSION = "x-amazon-apigateway-gateway-responses"; private static final String HEADER_PREFIX = "gatewayresponse.header."; @@ -65,21 +65,21 @@ public List getApiTypes() { @Override public OpenApi after(Context context, OpenApi openapi) { return context.getService() - .getTrait(CorsTrait.class) - .map(corsTrait -> updateModel(context, openapi, corsTrait)) - .orElse(openapi); + .getTrait(CorsTrait.class) + .map(corsTrait -> updateModel(context, openapi, corsTrait)) + .orElse(openapi); } private OpenApi updateModel(Context context, OpenApi openapi, CorsTrait corsTrait) { // Update the existing gateway responses if present, or inject a default one if not. Node extension = openapi.getExtension(GATEWAY_RESPONSES_EXTENSION) - .map(node -> node.expectObjectNode(GATEWAY_RESPONSES_EXTENSION + " must be an object")) - .map(node -> updateGatewayResponses(context, corsTrait, node)) - .orElse(updateGatewayResponses(context, corsTrait)); + .map(node -> node.expectObjectNode(GATEWAY_RESPONSES_EXTENSION + " must be an object")) + .map(node -> updateGatewayResponses(context, corsTrait, node)) + .orElse(updateGatewayResponses(context, corsTrait)); // Add the gateway responses the `x-amazon-apigateway-gateway-responses` OpenAPI extension. return openapi.toBuilder() - .putExtension(GATEWAY_RESPONSES_EXTENSION, extension) - .build(); + .putExtension(GATEWAY_RESPONSES_EXTENSION, extension) + .build(); } private Node updateGatewayResponses(Context context, CorsTrait trait) { @@ -88,9 +88,9 @@ private Node updateGatewayResponses(Context context, CorsTrait } private Node updateGatewayResponses( - Context context, - CorsTrait trait, - ObjectNode gatewayResponses + Context context, + CorsTrait trait, + ObjectNode gatewayResponses ) { Map corsHeaders = new HashMap<>(); corsHeaders.put(CorsHeader.ALLOW_ORIGIN, trait.getOrigin()); @@ -102,22 +102,22 @@ private Node updateGatewayResponses( } return gatewayResponses.getMembers() - .entrySet() - .stream() - .collect(ObjectNode.collect(Map.Entry::getKey, entry -> { - return updateGatewayResponse(context, trait, corsHeaders, entry.getValue().expectObjectNode()); - })); + .entrySet() + .stream() + .collect(ObjectNode.collect(Map.Entry::getKey, entry -> { + return updateGatewayResponse(context, trait, corsHeaders, entry.getValue().expectObjectNode()); + })); } private ObjectNode updateGatewayResponse( - Context context, - CorsTrait trait, - Map sharedHeaders, - ObjectNode gatewayResponse + Context context, + CorsTrait trait, + Map sharedHeaders, + ObjectNode gatewayResponse ) { ObjectNode responseParameters = gatewayResponse - .getObjectMember(RESPONSE_PARAMETERS_KEY) - .orElse(Node.objectNode()); + .getObjectMember(RESPONSE_PARAMETERS_KEY) + .orElse(Node.objectNode()); // Track all CORS headers of the gateway response. Map headers = new TreeMap<>(sharedHeaders); diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsToRestIntegrations.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsToRestIntegrations.java index f06aeb17985..f34c4b781ee 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsToRestIntegrations.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddCorsToRestIntegrations.java @@ -47,11 +47,11 @@ public List getApiTypes() { @Override public OperationObject updateOperation( - Context context, - OperationShape shape, - OperationObject operationObject, - String httpMethod, - String path + Context context, + OperationShape shape, + OperationObject operationObject, + String httpMethod, + String path ) { CorsTrait cors = context.getService().getTrait(CorsTrait.class).orElse(null); @@ -60,37 +60,37 @@ public OperationObject updateOperation( } return operationObject.getExtension(AddIntegrations.INTEGRATION_EXTENSION_NAME) - .flatMap(Node::asObjectNode) - .map(integrationObject -> updateOperation(context, shape, operationObject, cors, integrationObject)) - .orElse(operationObject); + .flatMap(Node::asObjectNode) + .map(integrationObject -> updateOperation(context, shape, operationObject, cors, integrationObject)) + .orElse(operationObject); } private OperationObject updateOperation( - Context context, - OperationShape shape, - OperationObject operationObject, - CorsTrait cors, - ObjectNode integrationObject + Context context, + OperationShape shape, + OperationObject operationObject, + CorsTrait cors, + ObjectNode integrationObject ) { ObjectNode updated = updateIntegrationWithCors( - context, - operationObject, - shape, - integrationObject, - cors + context, + operationObject, + shape, + integrationObject, + cors ); return operationObject.toBuilder() - .putExtension(AddIntegrations.INTEGRATION_EXTENSION_NAME, updated) - .build(); + .putExtension(AddIntegrations.INTEGRATION_EXTENSION_NAME, updated) + .build(); } private ObjectNode updateIntegrationWithCors( - Context context, - OperationObject operationObject, - OperationShape shape, - ObjectNode integrationNode, - CorsTrait cors + Context context, + OperationObject operationObject, + OperationShape shape, + ObjectNode integrationNode, + CorsTrait cors ) { ObjectNode responses = integrationNode.getObjectMember(RESPONSES_KEY).orElse(Node.objectNode()); @@ -106,55 +106,55 @@ private ObjectNode updateIntegrationWithCors( } LOGGER.finer( - () -> String.format( - "Adding the following CORS headers to the API Gateway integration of %s: %s", - shape.getId(), - corsHeaders - ) + () -> String.format( + "Adding the following CORS headers to the API Gateway integration of %s: %s", + shape.getId(), + corsHeaders + ) ); Set deducedHeaders = CorsHeader.deduceOperationResponseHeaders(context, operationObject, shape, cors); LOGGER.fine( - () -> String.format( - "Detected the following headers for operation %s: %s", - shape.getId(), - deducedHeaders - ) + () -> String.format( + "Detected the following headers for operation %s: %s", + shape.getId(), + deducedHeaders + ) ); // Update each response by adding CORS headers. responses = responses.getMembers() - .entrySet() - .stream() - .peek( - entry -> LOGGER.fine( - () -> String.format( - "Updating integration response %s for `%s` with CORS", - entry.getKey(), - shape.getId() - ) + .entrySet() + .stream() + .peek( + entry -> LOGGER.fine( + () -> String.format( + "Updating integration response %s for `%s` with CORS", + entry.getKey(), + shape.getId() + ) + ) ) - ) - .map( - entry -> Pair.of( - entry.getKey(), - updateIntegrationResponse( - shape, - corsHeaders, - deducedHeaders, - entry.getValue().expectObjectNode() - ) + .map( + entry -> Pair.of( + entry.getKey(), + updateIntegrationResponse( + shape, + corsHeaders, + deducedHeaders, + entry.getValue().expectObjectNode() + ) + ) ) - ) - .collect(ObjectNode.collect(Pair::getLeft, Pair::getRight)); + .collect(ObjectNode.collect(Pair::getLeft, Pair::getRight)); return integrationNode.withMember(RESPONSES_KEY, responses); } private ObjectNode updateIntegrationResponse( - OperationShape shape, - Map corsHeaders, - Set deduced, - ObjectNode response + OperationShape shape, + Map corsHeaders, + Set deduced, + ObjectNode response ) { Map responseHeaders = new HashMap<>(corsHeaders); ObjectNode responseParams = response.getObjectMember(RESPONSE_PARAMETERS_KEY).orElseGet(Node::objectNode); @@ -163,11 +163,11 @@ private ObjectNode updateIntegrationResponse( Set headersToExpose = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); headersToExpose.addAll(deduced); responseParams.getStringMap() - .keySet() - .stream() - .filter(parameterName -> parameterName.startsWith(HEADER_PREFIX)) - .map(parameterName -> parameterName.substring(HEADER_PREFIX.length())) - .forEach(headersToExpose::add); + .keySet() + .stream() + .filter(parameterName -> parameterName.startsWith(HEADER_PREFIX)) + .map(parameterName -> parameterName.substring(HEADER_PREFIX.length())) + .forEach(headersToExpose::add); String headersToExposeString = String.join(",", headersToExpose); // If there are exposed headers, then add a new header to the integration @@ -175,12 +175,12 @@ private ObjectNode updateIntegrationResponse( if (!headersToExposeString.isEmpty()) { responseHeaders.put(CorsHeader.EXPOSE_HEADERS, headersToExposeString); LOGGER.fine( - () -> String.format( - "Adding `%s` header to `%s` with value of `%s`", - CorsHeader.EXPOSE_HEADERS, - shape.getId(), - headersToExposeString - ) + () -> String.format( + "Adding `%s` header to `%s` with value of `%s`", + CorsHeader.EXPOSE_HEADERS, + shape.getId(), + headersToExposeString + ) ); } diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddDefaultConfigSettings.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddDefaultConfigSettings.java index ff178551ede..6c2ba5869c5 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddDefaultConfigSettings.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddDefaultConfigSettings.java @@ -33,10 +33,10 @@ public void updateDefaultSettings(Model model, OpenApiConfig openApiConfig) { ApiGatewayConfig config = openApiConfig.getExtensions(ApiGatewayConfig.class); if (config.getApiGatewayDefaults() == null) { LOGGER.warning( - String.format( - "`apiGatewayDefaults` configuration not set for openapi plugin. Assuming %s.", - DEFAULT_VERSION - ) + String.format( + "`apiGatewayDefaults` configuration not set for openapi plugin. Assuming %s.", + DEFAULT_VERSION + ) ); config.setApiGatewayDefaults(DEFAULT_VERSION); } diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddIntegrations.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddIntegrations.java index ef3bd78b21e..0b0c7fabfe9 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddIntegrations.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddIntegrations.java @@ -37,23 +37,23 @@ public List getApiTypes() { @Override public OperationObject updateOperation( - Context context, - OperationShape shape, - OperationObject operation, - String httpMethod, - String path + Context context, + OperationShape shape, + OperationObject operation, + String httpMethod, + String path ) { IntegrationTraitIndex index = IntegrationTraitIndex.of(context.getModel()); return index.getIntegrationTrait(context.getService(), shape) - .map( - trait -> operation.toBuilder() - .putExtension(INTEGRATION_EXTENSION_NAME, createIntegration(context, shape, trait)) - .build() - ) - .orElseGet(() -> { - LOGGER.warning("No API Gateway integration trait found for " + shape.getId()); - return operation; - }); + .map( + trait -> operation.toBuilder() + .putExtension(INTEGRATION_EXTENSION_NAME, createIntegration(context, shape, trait)) + .build() + ) + .orElseGet(() -> { + LOGGER.warning("No API Gateway integration trait found for " + shape.getId()); + return operation; + }); } static ObjectNode createIntegration(MockIntegrationTrait integration) { @@ -63,9 +63,9 @@ static ObjectNode createIntegration(MockIntegrationTrait integration) { } private static ObjectNode createIntegration( - Context context, - OperationShape shape, - Trait integration + Context context, + OperationShape shape, + Trait integration ) { ObjectNode integrationNode; if (integration instanceof MockIntegrationTrait) { @@ -81,28 +81,28 @@ private static ObjectNode createIntegration( Optional passthroughBehavior = integrationNode.getMember(INCORRECT_PASSTHROUGH_BEHAVIOR); if (passthroughBehavior.isPresent()) { integrationNode = integrationNode - .withoutMember(INCORRECT_PASSTHROUGH_BEHAVIOR) - .withMember(PASSTHROUGH_BEHAVIOR, passthroughBehavior.get()); + .withoutMember(INCORRECT_PASSTHROUGH_BEHAVIOR) + .withMember(PASSTHROUGH_BEHAVIOR, passthroughBehavior.get()); } return integrationNode; } private static void validateTraitConfiguration( - IntegrationTrait trait, - Context context, - OperationShape operation + IntegrationTrait trait, + Context context, + OperationShape operation ) { // For HTTP APIs, API Gateway requires that the payloadFormatVersion is set on integrations. // https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions-integration.html // If the payloadFormatVersion has not been set on an integration and the apiGatewayType has been set to "HTTP", // the conversion fails. ApiGatewayConfig.ApiType apiType = context.getConfig() - .getExtensions(ApiGatewayConfig.class) - .getApiGatewayType(); + .getExtensions(ApiGatewayConfig.class) + .getApiGatewayType(); if (!trait.getPayloadFormatVersion().isPresent() && apiType.equals(ApiGatewayConfig.ApiType.HTTP)) { throw new OpenApiException( - "When the 'apiGatewayType' OpenAPI conversion setting is 'HTTP', a " - + "'payloadFormatVersion' must be set on the aws.apigateway#integration trait." + "When the 'apiGatewayType' OpenAPI conversion setting is 'HTTP', a " + + "'payloadFormatVersion' must be set on the aws.apigateway#integration trait." ); } } diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddRequestValidators.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddRequestValidators.java index b9083954952..918ad261896 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddRequestValidators.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddRequestValidators.java @@ -37,14 +37,14 @@ final class AddRequestValidators implements ApiGatewayMapper { private static final String REQUEST_VALIDATOR = "x-amazon-apigateway-request-validator"; private static final String REQUEST_VALIDATORS = "x-amazon-apigateway-request-validators"; private static final Map KNOWN_VALIDATORS = MapUtils.of( - "params-only", - Node.objectNode().withMember("validateRequestParameters", Node.from(true)), - "body-only", - Node.objectNode().withMember("validateRequestBody", Node.from(true)), - "full", - Node.objectNode() - .withMember("validateRequestParameters", Node.from(true)) - .withMember("validateRequestBody", Node.from(true)) + "params-only", + Node.objectNode().withMember("validateRequestParameters", Node.from(true)), + "body-only", + Node.objectNode().withMember("validateRequestBody", Node.from(true)), + "full", + Node.objectNode() + .withMember("validateRequestParameters", Node.from(true)) + .withMember("validateRequestBody", Node.from(true)) ); @Override @@ -54,27 +54,27 @@ public List getApiTypes() { @Override public OperationObject updateOperation( - Context context, - OperationShape shape, - OperationObject operation, - String httpMethod, - String path + Context context, + OperationShape shape, + OperationObject operation, + String httpMethod, + String path ) { return shape.getTrait(RequestValidatorTrait.class) - .map(RequestValidatorTrait::getValue) - .map(value -> operation.toBuilder().putExtension(REQUEST_VALIDATOR, value).build()) - .orElse(operation); + .map(RequestValidatorTrait::getValue) + .map(value -> operation.toBuilder().putExtension(REQUEST_VALIDATOR, value).build()) + .orElse(operation); } @Override public OpenApi after(Context context, OpenApi openapi) { // Find each known request validator on operation shapes. Set validators = context.getModel() - .shapes(OperationShape.class) - .flatMap(shape -> OptionalUtils.stream(shape.getTrait(RequestValidatorTrait.class))) - .map(RequestValidatorTrait::getValue) - .filter(KNOWN_VALIDATORS::containsKey) - .collect(Collectors.toSet()); + .shapes(OperationShape.class) + .flatMap(shape -> OptionalUtils.stream(shape.getTrait(RequestValidatorTrait.class))) + .map(RequestValidatorTrait::getValue) + .filter(KNOWN_VALIDATORS::containsKey) + .collect(Collectors.toSet()); // Check if the service has a request validator. String serviceValidator = null; diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/ApiGatewayExtension.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/ApiGatewayExtension.java index f722c09253b..04ba4230471 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/ApiGatewayExtension.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/ApiGatewayExtension.java @@ -15,31 +15,31 @@ public final class ApiGatewayExtension implements Smithy2OpenApiExtension { @Override public List getOpenApiMappers() { return ListUtils.of( - ApiGatewayMapper.wrap(new AddDefaultConfigSettings()), - ApiGatewayMapper.wrap(new AddDefaultRestConfigSettings()), - ApiGatewayMapper.wrap(new AddApiKeySource()), - ApiGatewayMapper.wrap(new AddAuthorizers()), - ApiGatewayMapper.wrap(new AddBinaryTypes()), - ApiGatewayMapper.wrap(new AddIntegrations()), + ApiGatewayMapper.wrap(new AddDefaultConfigSettings()), + ApiGatewayMapper.wrap(new AddDefaultRestConfigSettings()), + ApiGatewayMapper.wrap(new AddApiKeySource()), + ApiGatewayMapper.wrap(new AddAuthorizers()), + ApiGatewayMapper.wrap(new AddBinaryTypes()), + ApiGatewayMapper.wrap(new AddIntegrations()), - // CORS For REST APIs - ApiGatewayMapper.wrap(new AddCorsToRestIntegrations()), - ApiGatewayMapper.wrap(new AddCorsResponseHeaders()), - ApiGatewayMapper.wrap(new AddCorsPreflightIntegration()), - ApiGatewayMapper.wrap(new AddCorsToGatewayResponses()), + // CORS For REST APIs + ApiGatewayMapper.wrap(new AddCorsToRestIntegrations()), + ApiGatewayMapper.wrap(new AddCorsResponseHeaders()), + ApiGatewayMapper.wrap(new AddCorsPreflightIntegration()), + ApiGatewayMapper.wrap(new AddCorsToGatewayResponses()), - ApiGatewayMapper.wrap(new AddRequestValidators()), - ApiGatewayMapper.wrap(new CloudFormationSubstitution()), + ApiGatewayMapper.wrap(new AddRequestValidators()), + ApiGatewayMapper.wrap(new CloudFormationSubstitution()), - // HTTP API mappers. - ApiGatewayMapper.wrap(new CorsHttpIntegration()) + // HTTP API mappers. + ApiGatewayMapper.wrap(new CorsHttpIntegration()) ); } @Override public List> getSecuritySchemeConverters() { return ListUtils.of( - new CognitoUserPoolsConverter() + new CognitoUserPoolsConverter() ); } } diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/ApiGatewayMapper.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/ApiGatewayMapper.java index 72638af9602..d2eea9972ca 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/ApiGatewayMapper.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/ApiGatewayMapper.java @@ -91,75 +91,75 @@ public void updateDefaultSettings(Model model, OpenApiConfig config) { @Override public OperationObject updateOperation( - Context context, - OperationShape shape, - OperationObject operation, - String httpMethodName, - String path + Context context, + OperationShape shape, + OperationObject operation, + String httpMethodName, + String path ) { return matchesApiType(context) - ? delegate.updateOperation(context, shape, operation, httpMethodName, path) - : operation; + ? delegate.updateOperation(context, shape, operation, httpMethodName, path) + : operation; } @Override public OperationObject postProcessOperation( - Context context, - OperationShape shape, - OperationObject operation, - String httpMethodName, - String path + Context context, + OperationShape shape, + OperationObject operation, + String httpMethodName, + String path ) { return matchesApiType(context) - ? delegate.postProcessOperation(context, shape, operation, httpMethodName, path) - : operation; + ? delegate.postProcessOperation(context, shape, operation, httpMethodName, path) + : operation; } @Override public PathItem updatePathItem(Context context, String path, PathItem pathItem) { return matchesApiType(context) - ? delegate.updatePathItem(context, path, pathItem) - : pathItem; + ? delegate.updatePathItem(context, path, pathItem) + : pathItem; } @Override public ParameterObject updateParameter( - Context context, - OperationShape operation, - String httpMethodName, - String path, - ParameterObject parameterObject + Context context, + OperationShape operation, + String httpMethodName, + String path, + ParameterObject parameterObject ) { return matchesApiType(context) - ? delegate.updateParameter(context, operation, httpMethodName, path, parameterObject) - : parameterObject; + ? delegate.updateParameter(context, operation, httpMethodName, path, parameterObject) + : parameterObject; } @Override public RequestBodyObject updateRequestBody( - Context context, - OperationShape operation, - String httpMethodName, - String path, - RequestBodyObject requestBody + Context context, + OperationShape operation, + String httpMethodName, + String path, + RequestBodyObject requestBody ) { return matchesApiType(context) - ? delegate.updateRequestBody(context, operation, httpMethodName, path, requestBody) - : requestBody; + ? delegate.updateRequestBody(context, operation, httpMethodName, path, requestBody) + : requestBody; } @Override public ResponseObject updateResponse( - Context context, - OperationShape operation, - String status, - String httpMethodName, - String path, - ResponseObject response + Context context, + OperationShape operation, + String status, + String httpMethodName, + String path, + ResponseObject response ) { return matchesApiType(context) - ? delegate.updateResponse(context, operation, status, httpMethodName, path, response) - : response; + ? delegate.updateResponse(context, operation, status, httpMethodName, path, response) + : response; } @Override @@ -171,39 +171,39 @@ public void before(Context context, OpenApi.Builder builder) { @Override public SecurityScheme updateSecurityScheme( - Context context, - Trait authTrait, - SecurityScheme securityScheme + Context context, + Trait authTrait, + SecurityScheme securityScheme ) { return matchesApiType(context) - ? delegate.updateSecurityScheme(context, authTrait, securityScheme) - : securityScheme; + ? delegate.updateSecurityScheme(context, authTrait, securityScheme) + : securityScheme; } @Override public Map> updateSecurity( - Context context, - Shape shape, - SecuritySchemeConverter converter, - Map> requirement + Context context, + Shape shape, + SecuritySchemeConverter converter, + Map> requirement ) { return matchesApiType(context) - ? delegate.updateSecurity(context, shape, converter, requirement) - : requirement; + ? delegate.updateSecurity(context, shape, converter, requirement) + : requirement; } @Override public OpenApi after(Context context, OpenApi openapi) { return matchesApiType(context) - ? delegate.after(context, openapi) - : openapi; + ? delegate.after(context, openapi) + : openapi; } @Override public ObjectNode updateNode(Context context, OpenApi openapi, ObjectNode node) { return matchesApiType(context) - ? delegate.updateNode(context, openapi, node) - : node; + ? delegate.updateNode(context, openapi, node) + : node; } }; } diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CloudFormationSubstitution.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CloudFormationSubstitution.java index c3c54c25491..ed887db9d60 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CloudFormationSubstitution.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CloudFormationSubstitution.java @@ -45,12 +45,12 @@ final class CloudFormationSubstitution implements ApiGatewayMapper { * in this list. */ private static final List PATHS = Arrays.asList( - "components/securitySchemes/*/x-amazon-apigateway-authorizer/providerARNs/*", - "components/securitySchemes/*/x-amazon-apigateway-authorizer/authorizerCredentials", - "components/securitySchemes/*/x-amazon-apigateway-authorizer/authorizerUri", - "paths/*/*/x-amazon-apigateway-integration/connectionId", - "paths/*/*/x-amazon-apigateway-integration/credentials", - "paths/*/*/x-amazon-apigateway-integration/uri" + "components/securitySchemes/*/x-amazon-apigateway-authorizer/providerARNs/*", + "components/securitySchemes/*/x-amazon-apigateway-authorizer/authorizerCredentials", + "components/securitySchemes/*/x-amazon-apigateway-authorizer/authorizerUri", + "paths/*/*/x-amazon-apigateway-integration/connectionId", + "paths/*/*/x-amazon-apigateway-integration/credentials", + "paths/*/*/x-amazon-apigateway-integration/uri" ); @Override @@ -114,11 +114,11 @@ public Node objectNode(ObjectNode node) { public Node stringNode(StringNode node) { if (SUBSTITUTION_PATTERN.matcher(node.getValue()).find() && isInPath()) { LOGGER.fine( - () -> String.format( - "Detected CloudFormation variable syntax in %s; replacing with a `Fn::Sub` " - + "CloudFormation intrinsic function block", - node.getValue() - ) + () -> String.format( + "Detected CloudFormation variable syntax in %s; replacing with a `Fn::Sub` " + + "CloudFormation intrinsic function block", + node.getValue() + ) ); return Node.objectNode().withMember(SUBSTITUTION_KEY, node); } diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CognitoUserPoolsConverter.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CognitoUserPoolsConverter.java index 07b400dcb6f..4066b05db66 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CognitoUserPoolsConverter.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CognitoUserPoolsConverter.java @@ -37,21 +37,21 @@ public Class getAuthSchemeType() { @Override public SecurityScheme createSecurityScheme(Context context, CognitoUserPoolsTrait trait) { return SecurityScheme.builder() - .type("apiKey") - .description("Amazon Cognito User Pools authentication") - .name(AUTH_HEADER) - .in("header") - .putExtension("x-amazon-apigateway-authtype", Node.from(AUTH_TYPE)) - .putExtension( - "x-amazon-apigateway-authorizer", - Node.objectNode() - .withMember("type", Node.from(AUTH_TYPE)) - .withMember( - PROVIDER_ARNS_PROPERTY, - trait.getProviderArns().stream().map(Node::from).collect(ArrayNode.collect()) - ) - ) - .build(); + .type("apiKey") + .description("Amazon Cognito User Pools authentication") + .name(AUTH_HEADER) + .in("header") + .putExtension("x-amazon-apigateway-authtype", Node.from(AUTH_TYPE)) + .putExtension( + "x-amazon-apigateway-authorizer", + Node.objectNode() + .withMember("type", Node.from(AUTH_TYPE)) + .withMember( + PROVIDER_ARNS_PROPERTY, + trait.getProviderArns().stream().map(Node::from).collect(ArrayNode.collect()) + ) + ) + .build(); } @Override diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CorsHeader.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CorsHeader.java index 0ef561af7e7..5afcc6d1404 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CorsHeader.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CorsHeader.java @@ -34,10 +34,10 @@ public String toString() { } static Set deduceOperationResponseHeaders( - Context context, - OperationObject operationObject, - OperationShape shape, - CorsTrait cors + Context context, + OperationObject operationObject, + OperationShape shape, + CorsTrait cors ) { // The deduced response headers of an operation consist of any headers // returned by security schemes, any headers returned by the protocol, diff --git a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CorsHttpIntegration.java b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CorsHttpIntegration.java index b76624280e3..46ff76d5df7 100644 --- a/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CorsHttpIntegration.java +++ b/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/CorsHttpIntegration.java @@ -73,16 +73,16 @@ public List getApiTypes() { @Override public OpenApi after(Context context, OpenApi openapi) { return context.getService() - .getTrait(CorsTrait.class) - .map(corsTrait -> addCors(context, openapi, corsTrait)) - .orElse(openapi); + .getTrait(CorsTrait.class) + .map(corsTrait -> addCors(context, openapi, corsTrait)) + .orElse(openapi); } private OpenApi addCors(Context context, OpenApi openapi, CorsTrait trait) { // Use any existing x-amazon-apigateway-cors value, if present. Node alreadySetCorsValue = openapi.getExtension(CORS_HTTP_EXTENSION) - .flatMap(Node::asObjectNode) - .orElse(null); + .flatMap(Node::asObjectNode) + .orElse(null); if (alreadySetCorsValue != null) { return openapi; @@ -93,19 +93,19 @@ private OpenApi addCors(Context context, OpenApi openapi, CorsT Set exposedHeaders = getExposedHeaders(context, trait, openapi); ObjectNode.Builder corsObjectBuilder = Node.objectNodeBuilder() - .withMember("allowOrigins", Node.fromStrings(trait.getOrigin())) - .withMember("maxAge", trait.getMaxAge()) - .withMember("allowMethods", Node.fromStrings(allowedMethodsInService)) - .withMember("exposeHeaders", Node.fromStrings(exposedHeaders)) - .withMember("allowHeaders", Node.fromStrings(allowedRequestHeaders)); + .withMember("allowOrigins", Node.fromStrings(trait.getOrigin())) + .withMember("maxAge", trait.getMaxAge()) + .withMember("allowMethods", Node.fromStrings(allowedMethodsInService)) + .withMember("exposeHeaders", Node.fromStrings(exposedHeaders)) + .withMember("allowHeaders", Node.fromStrings(allowedRequestHeaders)); if (context.usesHttpCredentials()) { corsObjectBuilder.withMember("allowCredentials", true); } return openapi.toBuilder() - .putExtension(CORS_HTTP_EXTENSION, corsObjectBuilder.build()) - .build(); + .putExtension(CORS_HTTP_EXTENSION, corsObjectBuilder.build()) + .build(); } private Set getMethodsUsedInApi(Context context, OpenApi openApi) { diff --git a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddApiKeySourceTest.java b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddApiKeySourceTest.java index b17715fb403..2fd2c690660 100644 --- a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddApiKeySourceTest.java +++ b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddApiKeySourceTest.java @@ -18,20 +18,20 @@ public class AddApiKeySourceTest { @Test public void addsApiKeySource() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("api-key-source.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("api-key-source.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.smithy#MyService")); OpenApi result = OpenApiConverter.create() - .config(config) - .classLoader(getClass().getClassLoader()) - .convert(model); + .config(config) + .classLoader(getClass().getClassLoader()) + .convert(model); String source = result.getExtension("x-amazon-apigateway-api-key-source") - .get() - .expectStringNode() - .getValue(); + .get() + .expectStringNode() + .getValue(); assertThat(source, equalTo("HEADER")); } diff --git a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddAuthorizersTest.java b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddAuthorizersTest.java index 34b471d29f4..c08e637e6b9 100644 --- a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddAuthorizersTest.java +++ b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddAuthorizersTest.java @@ -30,16 +30,16 @@ public class AddAuthorizersTest { @Test public void addsAuthorizers() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("authorizers.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("authorizers.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("ns.foo#SomeService")); OpenApi result = OpenApiConverter.create() - .config(config) - .classLoader(getClass().getClassLoader()) - .convert(model); + .config(config) + .classLoader(getClass().getClassLoader()) + .convert(model); SecurityScheme sigV4 = result.getComponents().getSecuritySchemes().get("sigv4"); assertThat(result.getComponents().getSecuritySchemes().get("aws.v4"), nullValue()); @@ -61,16 +61,16 @@ public void addsAuthorizers() { @Test public void addsOnlyAuthType() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("basic-authorizers.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("basic-authorizers.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("ns.foo#SomeService")); OpenApi result = OpenApiConverter.create() - .config(config) - .classLoader(getClass().getClassLoader()) - .convert(model); + .config(config) + .classLoader(getClass().getClassLoader()) + .convert(model); SecurityScheme sigV4 = result.getComponents().getSecuritySchemes().get("sigv4"); assertThat(result.getComponents().getSecuritySchemes().get("aws.v4"), nullValue()); @@ -84,16 +84,16 @@ public void addsOnlyAuthType() { @Test public void addsCustomAuthType() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("custom-auth-type-authorizer.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("custom-auth-type-authorizer.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("ns.foo#SomeService")); OpenApi result = OpenApiConverter.create() - .config(config) - .classLoader(getClass().getClassLoader()) - .convert(model); + .config(config) + .classLoader(getClass().getClassLoader()) + .convert(model); SecurityScheme sigV4 = result.getComponents().getSecuritySchemes().get("sigv4"); assertThat(result.getComponents().getSecuritySchemes().get("aws.v4"), nullValue()); @@ -107,16 +107,16 @@ public void addsCustomAuthType() { @Test public void emptyCustomAuthTypeNotSet() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("empty-custom-auth-type-authorizer.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("empty-custom-auth-type-authorizer.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("ns.foo#SomeService")); OpenApi result = OpenApiConverter.create() - .config(config) - .classLoader(getClass().getClassLoader()) - .convert(model); + .config(config) + .classLoader(getClass().getClassLoader()) + .convert(model); SecurityScheme apiKey = result.getComponents().getSecuritySchemes().get("api_key"); assertThat(apiKey.getType(), equalTo("apiKey")); @@ -129,20 +129,20 @@ public void emptyCustomAuthTypeNotSet() { @Test public void addsOperationLevelApiKeyScheme() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("operation-http-api-key-security.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("operation-http-api-key-security.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create() - .config(config) - .classLoader(getClass().getClassLoader()) - .convert(model); + .config(config) + .classLoader(getClass().getClassLoader()) + .convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("operation-http-api-key-security.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("operation-http-api-key-security.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -151,16 +151,16 @@ public void addsOperationLevelApiKeyScheme() { @Test public void resolvesEffectiveAuthorizersForEachOperation() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("effective-authorizers.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("effective-authorizers.smithy")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#ServiceA")); OpenApi result = OpenApiConverter.create() - .config(config) - .classLoader(getClass().getClassLoader()) - .convert(model); + .config(config) + .classLoader(getClass().getClassLoader()) + .convert(model); // The security of the service is just "foo". assertThat(result.getSecurity(), contains(MapUtils.of("foo", ListUtils.of()))); @@ -170,8 +170,8 @@ public void resolvesEffectiveAuthorizersForEachOperation() { assertThat(result.getPaths().get("/operationA").getGet().get().getSecurity(), is(Optional.empty())); // The security schemes of operationB must be "baz". assertThat( - result.getPaths().get("/operationB").getGet().get().getSecurity(), - is(Optional.of(ListUtils.of(MapUtils.of("baz", ListUtils.of())))) + result.getPaths().get("/operationB").getGet().get().getSecurity(), + is(Optional.of(ListUtils.of(MapUtils.of("baz", ListUtils.of())))) ); } } diff --git a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddBinaryTypesTest.java b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddBinaryTypesTest.java index 0b8117abeca..c8a7dc55317 100644 --- a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddBinaryTypesTest.java +++ b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddBinaryTypesTest.java @@ -20,22 +20,22 @@ public class AddBinaryTypesTest { @Test public void addsBinaryTypes() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("binary-types.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("binary-types.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.smithy#MyService")); OpenApi result = OpenApiConverter.create() - .config(config) - .classLoader(getClass().getClassLoader()) - .convert(model); + .config(config) + .classLoader(getClass().getClassLoader()) + .convert(model); List types = result.getExtension("x-amazon-apigateway-binary-media-types") - .get() - .expectArrayNode() - .getElementsAs(StringNode::getValue); + .get() + .expectArrayNode() + .getElementsAs(StringNode::getValue); assertThat(types, containsInAnyOrder("application/zip", "image/*", "application/octet-stream")); } } diff --git a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddDefaultConfigSettingsTest.java b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddDefaultConfigSettingsTest.java index 70e60d8d3a1..f4b230be536 100644 --- a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddDefaultConfigSettingsTest.java +++ b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddDefaultConfigSettingsTest.java @@ -18,17 +18,17 @@ public class AddDefaultConfigSettingsTest { @Test public void defaultsTo2023_08_11() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("default-config-settings.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("default-config-settings.smithy")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.smithy#MyService")); config.setUseIntegerType(true); ObjectNode result = OpenApiConverter.create() - .config(config) - .convertToNode(model); + .config(config) + .convertToNode(model); Node.assertEquals(result, Node.parse(IoUtils.readUtf8Resource(getClass(), "2023-08-11.openapi.json"))); } @@ -36,10 +36,10 @@ public void defaultsTo2023_08_11() { @Test public void usesVersion2023_08_11() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("default-config-settings.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("default-config-settings.smithy")) + .assemble() + .unwrap(); OpenApiConfig openApiConfig = new OpenApiConfig(); openApiConfig.setService(ShapeId.from("example.smithy#MyService")); @@ -50,8 +50,8 @@ public void usesVersion2023_08_11() { config.setApiGatewayDefaults(ApiGatewayDefaults.VERSION_2023_08_11); openApiConfig.setExtensions(mapper.serialize(config).expectObjectNode()); ObjectNode result = OpenApiConverter.create() - .config(openApiConfig) - .convertToNode(model); + .config(openApiConfig) + .convertToNode(model); Node.assertEquals(result, Node.parse(IoUtils.readUtf8Resource(getClass(), "2023-08-11.openapi.json"))); } @@ -59,10 +59,10 @@ public void usesVersion2023_08_11() { @Test public void canDisableDefaults() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("default-config-settings.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("default-config-settings.smithy")) + .assemble() + .unwrap(); OpenApiConfig openApiConfig = new OpenApiConfig(); openApiConfig.setService(ShapeId.from("example.smithy#MyService")); @@ -73,8 +73,8 @@ public void canDisableDefaults() { config.setApiGatewayDefaults(ApiGatewayDefaults.DISABLED); openApiConfig.setExtensions(mapper.serialize(config).expectObjectNode()); ObjectNode result = OpenApiConverter.create() - .config(openApiConfig) - .convertToNode(model); + .config(openApiConfig) + .convertToNode(model); Node.assertEquals(result, Node.parse(IoUtils.readUtf8Resource(getClass(), "disabled-defaults.openapi.json"))); } diff --git a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddDefaultRestConfigSettingsTest.java b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddDefaultRestConfigSettingsTest.java index 6e9c6191ba2..f1680629196 100644 --- a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddDefaultRestConfigSettingsTest.java +++ b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddDefaultRestConfigSettingsTest.java @@ -17,10 +17,10 @@ public class AddDefaultRestConfigSettingsTest { @Test public void addsDefaultConfigSettings() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("greedy-labels-for-rest.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("greedy-labels-for-rest.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); @@ -30,9 +30,9 @@ public void addsDefaultConfigSettings() { ObjectNode result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("greedy-labels-for-rest.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("greedy-labels-for-rest.openapi.json") + ) ); Node.assertEquals(result, expectedNode); diff --git a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddIntegrationsTest.java b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddIntegrationsTest.java index e3846fccbb3..1b6d2386b05 100644 --- a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddIntegrationsTest.java +++ b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddIntegrationsTest.java @@ -22,17 +22,17 @@ public class AddIntegrationsTest { @Test public void addsIntegrations() { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("integrations.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("integrations.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create().config(config).convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("integrations.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("integrations.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -41,17 +41,17 @@ public void addsIntegrations() { @Test public void addsIntegrationsWithoutCredentials() { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("integrations-without-credentials.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("integrations-without-credentials.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create().config(config).convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("integrations-without-credentials.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("integrations-without-credentials.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -61,10 +61,10 @@ public void addsIntegrationsWithoutCredentials() { public void throwsOnInvalidIntegrationTraitForHttpApi() { OpenApiException thrown = assertThrows(OpenApiException.class, () -> { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("invalid-integration-for-http-api.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("invalid-integration-for-http-api.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); ApiGatewayConfig apiGatewayConfig = new ApiGatewayConfig(); @@ -74,11 +74,11 @@ public void throwsOnInvalidIntegrationTraitForHttpApi() { }); assertThat( - thrown.getMessage(), - containsString( - "When the 'apiGatewayType' OpenAPI conversion setting is" - + " 'HTTP', a 'payloadFormatVersion' must be set on the aws.apigateway#integration trait." - ) + thrown.getMessage(), + containsString( + "When the 'apiGatewayType' OpenAPI conversion setting is" + + " 'HTTP', a 'payloadFormatVersion' must be set on the aws.apigateway#integration trait." + ) ); } } diff --git a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddRequestValidatorsTest.java b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddRequestValidatorsTest.java index 12efe0f5420..318ae975637 100644 --- a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddRequestValidatorsTest.java +++ b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/AddRequestValidatorsTest.java @@ -23,17 +23,17 @@ public class AddRequestValidatorsTest { @Test public void addsRequestValidators() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("request-validators.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("request-validators.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create() - .config(config) - .classLoader(getClass().getClassLoader()) - .convert(model); + .config(config) + .classLoader(getClass().getClassLoader()) + .convert(model); assertThat(result.getExtension("x-amazon-apigateway-request-validator").get(), equalTo(Node.from("full"))); ObjectNode validators = result.getExtension("x-amazon-apigateway-request-validators").get().expectObjectNode(); @@ -42,17 +42,17 @@ public void addsRequestValidators() { assertFalse(validators.containsMember("params-only")); Optional operation1Val = result.getPaths() - .get("/1") - .getPut() - .get() - .getExtension("x-amazon-apigateway-request-validator"); + .get("/1") + .getPut() + .get() + .getExtension("x-amazon-apigateway-request-validator"); assertFalse(operation1Val.isPresent()); Optional operation2Val = result.getPaths() - .get("/2") - .getPut() - .get() - .getExtension("x-amazon-apigateway-request-validator"); + .get("/2") + .getPut() + .get() + .getExtension("x-amazon-apigateway-request-validator"); assertThat(operation2Val.get(), equalTo(Node.from("body-only"))); } } diff --git a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/ApiGatewayMapperTest.java b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/ApiGatewayMapperTest.java index 4480126abcf..1a9c21864b9 100644 --- a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/ApiGatewayMapperTest.java +++ b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/ApiGatewayMapperTest.java @@ -21,10 +21,10 @@ public class ApiGatewayMapperTest { @Test public void onlyCallsMappersWhenApiTypeMatches() { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("cors-model.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("cors-model.json")) + .assemble() + .unwrap(); runTest(model, ApiGatewayConfig.ApiType.REST, true); runTest(model, ApiGatewayConfig.ApiType.DISABLED, false); @@ -39,8 +39,8 @@ private void runTest(Model model, ApiGatewayConfig.ApiType type, boolean present config.putExtensions(apiGatewayConfig); ObjectNode result = OpenApiConverter.create() - .config(config) - .convertToNode(model); + .config(config) + .convertToNode(model); if (present) { assertThat(result.getMember("x-amazon-apigateway-gateway-responses"), not(Optional.empty())); diff --git a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CloudFormationSubstitutionTest.java b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CloudFormationSubstitutionTest.java index 06004314d58..7dd0fd408c1 100644 --- a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CloudFormationSubstitutionTest.java +++ b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CloudFormationSubstitutionTest.java @@ -17,21 +17,21 @@ public class CloudFormationSubstitutionTest { @Test public void performsSubstitutionsByDefault() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("cloudformation-substitutions.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("cloudformation-substitutions.json")) + .assemble() + .unwrap(); ObjectNode expected = Node.parse( - IoUtils.readUtf8Resource(getClass(), "substitution-performed.json") + IoUtils.readUtf8Resource(getClass(), "substitution-performed.json") ) - .expectObjectNode(); + .expectObjectNode(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.smithy#MyService")); ObjectNode actual = OpenApiConverter.create() - .config(config) - .classLoader(getClass().getClassLoader()) - .convertToNode(model); + .config(config) + .classLoader(getClass().getClassLoader()) + .convertToNode(model); Node.assertEquals(actual, expected); } @@ -39,15 +39,15 @@ public void performsSubstitutionsByDefault() { @Test public void pluginCanBeDisabled() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("cloudformation-substitutions.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("cloudformation-substitutions.json")) + .assemble() + .unwrap(); ObjectNode expected = Node.parse( - IoUtils.readUtf8Resource(getClass(), "substitution-not-performed.json") + IoUtils.readUtf8Resource(getClass(), "substitution-not-performed.json") ) - .expectObjectNode(); + .expectObjectNode(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.smithy#MyService")); @@ -56,9 +56,9 @@ public void pluginCanBeDisabled() { config.putExtensions(apiGatewayConfig); ObjectNode actual = OpenApiConverter.create() - .classLoader(getClass().getClassLoader()) - .config(config) - .convertToNode(model); + .classLoader(getClass().getClassLoader()) + .config(config) + .convertToNode(model); Node.assertEquals(expected, actual); } diff --git a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CognitoUserPoolsConverterTest.java b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CognitoUserPoolsConverterTest.java index a3c6e9edf24..3da97d561c3 100644 --- a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CognitoUserPoolsConverterTest.java +++ b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CognitoUserPoolsConverterTest.java @@ -19,17 +19,17 @@ public class CognitoUserPoolsConverterTest { @Test public void addsAwsV4() { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("cognito-user-pools-security.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("cognito-user-pools-security.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create().config(config).convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("cognito-user-pools-security.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("cognito-user-pools-security.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -39,10 +39,10 @@ public void addsAwsV4() { public void requiresProviderArns() { Assertions.assertThrows(ValidatedResultException.class, () -> { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("invalid-cognito-user-pools-security.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("invalid-cognito-user-pools-security.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApiConverter.create().config(config).convert(model); diff --git a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CorsHttpIntegrationTest.java b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CorsHttpIntegrationTest.java index 225bc81fb91..8e3a24378e3 100644 --- a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CorsHttpIntegrationTest.java +++ b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CorsHttpIntegrationTest.java @@ -21,10 +21,10 @@ public class CorsHttpIntegrationTest { @Test public void generatesCorsForHttpApis() { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("cors-model.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("cors-model.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); ApiGatewayConfig apiGatewayConfig = new ApiGatewayConfig(); @@ -34,9 +34,9 @@ public void generatesCorsForHttpApis() { ObjectNode result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("http-api-cors.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("http-api-cors.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -49,22 +49,22 @@ public void generatesCorsForHttpApisWithNoExplicitValues() { // the conversion to "*" for the corresponding CORS headers rather // than needing to enumerate them all. Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("cors-model.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("cors-model.json")) + .assemble() + .unwrap(); ModelTransformer transformer = ModelTransformer.create(); model = transformer.mapShapes(model, shape -> { return shape.getTrait(CorsTrait.class) - .map(cors -> { - cors = cors.toBuilder() - .additionalAllowedHeaders(Collections.emptySet()) - .additionalExposedHeaders(Collections.emptySet()) - .build(); - return Shape.shapeToBuilder(shape).addTrait(cors).build(); - }) - .orElse(shape); + .map(cors -> { + cors = cors.toBuilder() + .additionalAllowedHeaders(Collections.emptySet()) + .additionalExposedHeaders(Collections.emptySet()) + .build(); + return Shape.shapeToBuilder(shape).addTrait(cors).build(); + }) + .orElse(shape); }); OpenApiConfig config = new OpenApiConfig(); @@ -75,9 +75,9 @@ public void generatesCorsForHttpApisWithNoExplicitValues() { ObjectNode result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("http-api-cors-wildcards.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("http-api-cors-wildcards.openapi.json") + ) ); Node.assertEquals(result, expectedNode); diff --git a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CorsTest.java b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CorsTest.java index 78d744c1b11..dc8ae91cec5 100644 --- a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CorsTest.java +++ b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/CorsTest.java @@ -21,17 +21,17 @@ public class CorsTest { @Test public void corsIntegrationTest() { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("cors-model.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("cors-model.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.smithy#MyService")); ObjectNode result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("cors-model.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("cors-model.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -40,17 +40,17 @@ public void corsIntegrationTest() { @Test public void skipsExplicitlyDefinedOptionsOperations() { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("cors-explicit-options.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("cors-explicit-options.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.smithy#MyService")); ObjectNode result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("cors-explicit-options.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("cors-explicit-options.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -59,10 +59,10 @@ public void skipsExplicitlyDefinedOptionsOperations() { @Test public void setsConfiguredAdditionalAllowedHeaders() { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("cors-model.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("cors-model.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.smithy#MyService")); ApiGatewayConfig apiGatewayConfig = new ApiGatewayConfig(); @@ -70,9 +70,9 @@ public void setsConfiguredAdditionalAllowedHeaders() { config.putExtensions(apiGatewayConfig); ObjectNode result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("cors-with-additional-headers.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("cors-with-additional-headers.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -88,14 +88,14 @@ public void setsConfiguredAdditionalAllowedHeaders() { @Test public void findsExistingGatewayHeaders() { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("cors-explicit-options.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("cors-explicit-options.json")) + .assemble() + .unwrap(); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("cors-with-custom-gateway-response-headers.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("cors-with-custom-gateway-response-headers.openapi.json") + ) ); OpenApiConfig config = new OpenApiConfig(); @@ -103,40 +103,43 @@ public void findsExistingGatewayHeaders() { // Create an OpenAPI model. ObjectNode result = OpenApiConverter.create() - .config(config) - .addOpenApiMapper(new OpenApiMapper() { - @Override - public byte getOrder() { - return -127; - } - - @Override - public OpenApi after(Context context, OpenApi openapi) { - // Inject a gateway response into the model. - return openapi.toBuilder() - .putExtension( - "x-amazon-apigateway-gateway-responses", - Node.objectNodeBuilder() - .withMember( - "ACCESS_DENIED", - Node.objectNode() - .withMember("statusCode", 403) - .withMember( - "responseParameters", - Node.objectNode() + .config(config) + .addOpenApiMapper(new OpenApiMapper() { + @Override + public byte getOrder() { + return -127; + } + + @Override + public OpenApi after(Context context, OpenApi openapi) { + // Inject a gateway response into the model. + return openapi.toBuilder() + .putExtension( + "x-amazon-apigateway-gateway-responses", + Node.objectNodeBuilder() .withMember( - "gatewayresponse.header.Access-Control-Allow-Origin", - "'domain.com'" + "ACCESS_DENIED", + Node.objectNode() + .withMember("statusCode", 403) + .withMember( + "responseParameters", + Node.objectNode() + .withMember( + "gatewayresponse.header.Access-Control-Allow-Origin", + "'domain.com'" + ) + .withMember( + "gatewayresponse.header.Foo", + "'baz'" + ) + ) ) - .withMember("gatewayresponse.header.Foo", "'baz'") - ) + .build() ) - .build() - ) - .build(); - } - }) - .convertToNode(model); + .build(); + } + }) + .convertToNode(model); Node.assertEquals(result, expectedNode); } @@ -144,18 +147,18 @@ public OpenApi after(Context context, OpenApi openapi) { @Test public void withPreflightIntegrationSync() { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("cors-with-multi-request-templates.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("cors-with-multi-request-templates.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.smithy#MyService")); config.setSyncCorsPreflightIntegration(true); ObjectNode result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("cors-with-preflight-sync.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("cors-with-preflight-sync.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -164,17 +167,17 @@ public void withPreflightIntegrationSync() { @Test public void withoutPreflightIntegrationSync() { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("cors-with-multi-request-templates.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("cors-with-multi-request-templates.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.smithy#MyService")); ObjectNode result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("cors-without-preflight-sync.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("cors-without-preflight-sync.openapi.json") + ) ); Node.assertEquals(result, expectedNode); diff --git a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/NonNumericFloatsTest.java b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/NonNumericFloatsTest.java index ecc13a48534..6d54a0f6654 100644 --- a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/NonNumericFloatsTest.java +++ b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/NonNumericFloatsTest.java @@ -17,18 +17,18 @@ public class NonNumericFloatsTest { @Test public void handlesNonNumericFloats() { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("non-numeric-floats.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("non-numeric-floats.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.smithy#MyService")); config.setSupportNonNumericFloats(true); ObjectNode result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("non-numeric-floats.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("non-numeric-floats.openapi.json") + ) ); Node.assertEquals(result, expectedNode); diff --git a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/PayloadsTest.java b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/PayloadsTest.java index ec0f5d166f2..98461906bfb 100644 --- a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/PayloadsTest.java +++ b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/PayloadsTest.java @@ -17,17 +17,17 @@ public class PayloadsTest { @Test public void payloadsStructureTargetTest() { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("payloads.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("payloads.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.smithy#MyService")); ObjectNode result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("payloads.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("payloads.openapi.json") + ) ); Node.assertEquals(result, expectedNode); diff --git a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/UnsupportedTraitsTest.java b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/UnsupportedTraitsTest.java index 335c64731a9..b4602c76414 100644 --- a/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/UnsupportedTraitsTest.java +++ b/smithy-aws-apigateway-openapi/src/test/java/software/amazon/smithy/aws/apigateway/openapi/UnsupportedTraitsTest.java @@ -17,10 +17,10 @@ public class UnsupportedTraitsTest { public void failsOnHttpChecksumTrait() { Exception thrown = Assertions.assertThrows(OpenApiException.class, () -> { Model model = Model.assembler(getClass().getClassLoader()) - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("unsupported-http-checksum.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("unsupported-http-checksum.smithy")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.smithy#MyService")); OpenApiConverter.create().config(config).convertToNode(model); diff --git a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizerDefinition.java b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizerDefinition.java index be132044120..8b9ece85ade 100644 --- a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizerDefinition.java +++ b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizerDefinition.java @@ -177,16 +177,16 @@ public Optional getEnableSimpleResponses() { @Override public Builder toBuilder() { return builder() - .scheme(scheme) - .type(type) - .uri(uri) - .customAuthType(customAuthType) - .credentials(credentials) - .identitySource(identitySource) - .identityValidationExpression(identityValidationExpression) - .resultTtlInSeconds(resultTtlInSeconds) - .authorizerPayloadFormatVersion(authorizerPayloadFormatVersion) - .enableSimpleResponses(enableSimpleResponses); + .scheme(scheme) + .type(type) + .uri(uri) + .customAuthType(customAuthType) + .credentials(credentials) + .identitySource(identitySource) + .identityValidationExpression(identityValidationExpression) + .resultTtlInSeconds(resultTtlInSeconds) + .authorizerPayloadFormatVersion(authorizerPayloadFormatVersion) + .enableSimpleResponses(enableSimpleResponses); } @Override @@ -206,15 +206,15 @@ public boolean equals(Object o) { AuthorizerDefinition that = (AuthorizerDefinition) o; return scheme.equals(that.scheme) - && Objects.equals(type, that.type) - && Objects.equals(uri, that.uri) - && Objects.equals(customAuthType, that.customAuthType) - && Objects.equals(credentials, that.credentials) - && Objects.equals(identitySource, that.identitySource) - && Objects.equals(identityValidationExpression, that.identityValidationExpression) - && Objects.equals(resultTtlInSeconds, that.resultTtlInSeconds) - && Objects.equals(authorizerPayloadFormatVersion, that.authorizerPayloadFormatVersion) - && Objects.equals(enableSimpleResponses, that.enableSimpleResponses); + && Objects.equals(type, that.type) + && Objects.equals(uri, that.uri) + && Objects.equals(customAuthType, that.customAuthType) + && Objects.equals(credentials, that.credentials) + && Objects.equals(identitySource, that.identitySource) + && Objects.equals(identityValidationExpression, that.identityValidationExpression) + && Objects.equals(resultTtlInSeconds, that.resultTtlInSeconds) + && Objects.equals(authorizerPayloadFormatVersion, that.authorizerPayloadFormatVersion) + && Objects.equals(enableSimpleResponses, that.enableSimpleResponses); } @Override diff --git a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizerIndex.java b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizerIndex.java index 79145cc5f92..91977e2f1f1 100644 --- a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizerIndex.java +++ b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizerIndex.java @@ -44,7 +44,7 @@ public AuthorizerIndex(Model model) { // Account for the edge case of no operations on the service. service.getTrait(AuthorizerTrait.class) - .ifPresent(trait -> serviceMap.put(service.getId(), trait.getValue())); + .ifPresent(trait -> serviceMap.put(service.getId(), trait.getValue())); for (PathFinder.Path path : finder.search(service, SELECTOR)) { String effectiveAuthorizer = null; @@ -78,7 +78,7 @@ private static String getNullableAuthorizerValue(Shape shape, String previous) { */ public Optional getAuthorizer(ToShapeId service, ToShapeId shape) { return Optional.ofNullable(authorizers.get(service.toShapeId())) - .flatMap(mappings -> Optional.ofNullable(mappings.get(shape.toShapeId()))); + .flatMap(mappings -> Optional.ofNullable(mappings.get(shape.toShapeId()))); } /** @@ -110,9 +110,9 @@ public Optional getAuthorizerValue(ToShapeId service) { */ public Optional getAuthorizerValue(ToShapeId service, ToShapeId shape) { return getAuthorizer(service, shape) - .flatMap( - name -> Optional.ofNullable(authorizerTraits.get(service.toShapeId())) - .flatMap(trait -> trait.getAuthorizer(name)) - ); + .flatMap( + name -> Optional.ofNullable(authorizerTraits.get(service.toShapeId())) + .flatMap(trait -> trait.getAuthorizer(name)) + ); } } diff --git a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizersTrait.java b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizersTrait.java index eec167efd12..94286f2aaa1 100644 --- a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizersTrait.java +++ b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizersTrait.java @@ -98,12 +98,12 @@ public Builder toBuilder() { @Override protected Node createNode() { return authorizers.entrySet() - .stream() - .sorted(Comparator.comparing(Map.Entry::getKey)) - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) - .toBuilder() - .sourceLocation(getSourceLocation()) - .build(); + .stream() + .sorted(Comparator.comparing(Map.Entry::getKey)) + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + .toBuilder() + .sourceLocation(getSourceLocation()) + .build(); } /** diff --git a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizersTraitValidator.java b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizersTraitValidator.java index 1c50c71f1d9..5545acd849a 100644 --- a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizersTraitValidator.java +++ b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/AuthorizersTraitValidator.java @@ -28,15 +28,15 @@ public final class AuthorizersTraitValidator extends AbstractValidator { @Override public List validate(Model model) { return model.shapes(ServiceShape.class) - .map(service -> validate(model, service)) - .flatMap(List::stream) - .collect(Collectors.toList()); + .map(service -> validate(model, service)) + .flatMap(List::stream) + .collect(Collectors.toList()); } private List validate(Model model, ServiceShape service) { Map authorizers = service.getTrait(AuthorizersTrait.class) - .map(AuthorizersTrait::getAuthorizers) - .orElseGet(HashMap::new); + .map(AuthorizersTrait::getAuthorizers) + .orElseGet(HashMap::new); List validationEvents = new ArrayList<>(); @@ -44,8 +44,8 @@ private List validate(Model model, ServiceShape service) { authSchemaValidation.ifPresent(validationEvents::add); Optional enableSimpleResponsesValidation = validateEnableSimpleResponsesConfig( - authorizers, - service + authorizers, + service ); enableSimpleResponsesValidation.ifPresent(validationEvents::add); @@ -57,18 +57,18 @@ private List validate(Model model, ServiceShape service) { * matches one of the schemes of the protocols of the service. */ private Optional validateAuthSchema( - Map authorizers, - Model model, - ServiceShape service + Map authorizers, + Model model, + ServiceShape service ) { Set authSchemes = ServiceIndex.of(model).getAuthSchemes(service).keySet(); String invalidMappings = authorizers.entrySet() - .stream() - .filter(entry -> !authSchemes.contains(entry.getValue().getScheme())) - .map(entry -> entry.getKey() + " -> " + entry.getValue().getScheme()) - .sorted() - .collect(Collectors.joining(", ")); + .stream() + .filter(entry -> !authSchemes.contains(entry.getValue().getScheme())) + .map(entry -> entry.getKey() + " -> " + entry.getValue().getScheme()) + .sorted() + .collect(Collectors.joining(", ")); if (invalidMappings.isEmpty()) { return Optional.empty(); @@ -76,17 +76,17 @@ private Optional validateAuthSchema( AuthorizersTrait authorizersTrait = service.getTrait(AuthorizersTrait.class).get(); return Optional.of( - error( - service, - authorizersTrait, - String.format( - "Each `scheme` of the `%s` trait must target one of the auth schemes applied to the service " - + "(i.e., [%s]). The following mappings of authorizer names to schemes are invalid: %s", - AuthorizersTrait.ID, - ValidationUtils.tickedList(authSchemes), - invalidMappings + error( + service, + authorizersTrait, + String.format( + "Each `scheme` of the `%s` trait must target one of the auth schemes applied to the service " + + "(i.e., [%s]). The following mappings of authorizer names to schemes are invalid: %s", + AuthorizersTrait.ID, + ValidationUtils.tickedList(authSchemes), + invalidMappings + ) ) - ) ); } @@ -95,17 +95,17 @@ private Optional validateAuthSchema( * should have the authorizedPayloadFormatVersion member set to 2.0. */ private Optional validateEnableSimpleResponsesConfig( - Map authorizers, - ServiceShape service + Map authorizers, + ServiceShape service ) { String invalidConfigs = authorizers.entrySet() - .stream() - .filter(entry -> entry.getValue().getEnableSimpleResponses().isPresent()) - .filter(entry -> entry.getValue().getAuthorizerPayloadFormatVersion().isPresent()) - .filter(entry -> !entry.getValue().getAuthorizerPayloadFormatVersion().get().equals("2.0")) - .map(Map.Entry::getKey) - .sorted() - .collect(Collectors.joining(", ")); + .stream() + .filter(entry -> entry.getValue().getEnableSimpleResponses().isPresent()) + .filter(entry -> entry.getValue().getAuthorizerPayloadFormatVersion().isPresent()) + .filter(entry -> !entry.getValue().getAuthorizerPayloadFormatVersion().get().equals("2.0")) + .map(Map.Entry::getKey) + .sorted() + .collect(Collectors.joining(", ")); if (invalidConfigs.isEmpty()) { return Optional.empty(); @@ -113,16 +113,16 @@ private Optional validateEnableSimpleResponsesConfig( AuthorizersTrait authorizersTrait = service.getTrait(AuthorizersTrait.class).get(); return Optional.of( - error( - service, - authorizersTrait, - String.format( - "The enableSimpleResponses member of %s is only supported when authorizedPayloadFormatVersion " - + "is 2.0. The following authorizers are misconfigured: %s", - AuthorizersTrait.ID, - invalidConfigs + error( + service, + authorizersTrait, + String.format( + "The enableSimpleResponses member of %s is only supported when authorizedPayloadFormatVersion " + + "is 2.0. The following authorizers are misconfigured: %s", + AuthorizersTrait.ID, + invalidConfigs + ) ) - ) ); } diff --git a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/IntegrationResponse.java b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/IntegrationResponse.java index 12ef3f12245..3b916df36b4 100644 --- a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/IntegrationResponse.java +++ b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/IntegrationResponse.java @@ -115,9 +115,9 @@ public Builder toBuilder() { responseTemplates.forEach(builder::putResponseTemplate); responseParameters.forEach(builder::putResponseParameter); return builder - .sourceLocation(sourceLocation) - .contentHandling(contentHandling) - .statusCode(statusCode); + .sourceLocation(sourceLocation) + .contentHandling(contentHandling) + .statusCode(statusCode); } @Override diff --git a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTrait.java b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTrait.java index 34d9da3ee07..5b50e5f56f9 100644 --- a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTrait.java +++ b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTrait.java @@ -300,21 +300,21 @@ public Optional getResponse(String statusCode) { public ObjectNode toExpandedNode(ToShapeId service, ToShapeId operation) { ObjectNode result = toNode().expectObjectNode(); result = result.withMember( - URI_KEY, - formatComponent( - service, - operation, - result.expectStringMember(URI_KEY).getValue() - ) + URI_KEY, + formatComponent( + service, + operation, + result.expectStringMember(URI_KEY).getValue() + ) ); if (result.containsMember(CREDENTIALS_KEY)) { result = result.withMember( - CREDENTIALS_KEY, - formatComponent( - service, - operation, - result.expectStringMember(CREDENTIALS_KEY).getValue() - ) + CREDENTIALS_KEY, + formatComponent( + service, + operation, + result.expectStringMember(CREDENTIALS_KEY).getValue() + ) ); } return result; @@ -330,8 +330,8 @@ public ObjectNode toExpandedNode(ToShapeId service, ToShapeId operation) { */ public static String formatComponent(ToShapeId service, ToShapeId operation, String component) { return component - .replace(SERVICE_NAME_LABEL, service.toShapeId().getName()) - .replace(OPERATION_NAME_LABEL, operation.toShapeId().getName()); + .replace(SERVICE_NAME_LABEL, service.toShapeId().getName()) + .replace(OPERATION_NAME_LABEL, operation.toShapeId().getName()); } @Override @@ -345,22 +345,22 @@ protected ObjectNode createNode() { @Override public Builder toBuilder() { return builder() - .sourceLocation(getSourceLocation()) - .type(type) - .uri(uri) - .credentials(credentials) - .httpMethod(httpMethod) - .passThroughBehavior(passThroughBehavior) - .contentHandling(contentHandling) - .timeoutInMillis(timeoutInMillis) - .connectionId(connectionId) - .connectionType(connectionType) - .cacheNamespace(cacheNamespace) - .payloadFormatVersion(payloadFormatVersion) - .requestParameters(requestParameters) - .requestTemplates(requestTemplates) - .responses(responses) - .cacheKeyParameters(cacheKeyParameters); + .sourceLocation(getSourceLocation()) + .type(type) + .uri(uri) + .credentials(credentials) + .httpMethod(httpMethod) + .passThroughBehavior(passThroughBehavior) + .contentHandling(contentHandling) + .timeoutInMillis(timeoutInMillis) + .connectionId(connectionId) + .connectionType(connectionType) + .cacheNamespace(cacheNamespace) + .payloadFormatVersion(payloadFormatVersion) + .requestParameters(requestParameters) + .requestTemplates(requestTemplates) + .responses(responses) + .cacheKeyParameters(cacheKeyParameters); } public static final class Builder extends AbstractTraitBuilder { diff --git a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTraitIndex.java b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTraitIndex.java index 48ab863aeb5..e8f81694b8f 100644 --- a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTraitIndex.java +++ b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTraitIndex.java @@ -49,8 +49,8 @@ public static IntegrationTraitIndex of(Model model) { */ public Optional getIntegrationTrait(ToShapeId service, ToShapeId shape) { return Optional.ofNullable( - traits.getOrDefault(service.toShapeId(), MapUtils.of()) - .get(shape.toShapeId()) + traits.getOrDefault(service.toShapeId(), MapUtils.of()) + .get(shape.toShapeId()) ); } @@ -79,8 +79,8 @@ private void walk(Model model, ShapeId service, EntityShape current, Trait trait for (ShapeId resource : current.getResources()) { model.getShape(resource) - .flatMap(Shape::asResourceShape) - .ifPresent(resourceShape -> walk(model, service, resourceShape, updatedTrait)); + .flatMap(Shape::asResourceShape) + .ifPresent(resourceShape -> walk(model, service, resourceShape, updatedTrait)); } for (ShapeId operation : current.getAllOperations()) { @@ -90,11 +90,11 @@ private void walk(Model model, ShapeId service, EntityShape current, Trait trait private static Trait extractTrait(Shape shape, Trait defaultValue) { return shape.getTrait(MockIntegrationTrait.class) - .map(trait -> (Trait) trait) - .orElseGet( - () -> shape.getTrait(IntegrationTrait.class) - .map(trait -> (Trait) trait) - .orElse(defaultValue) - ); + .map(trait -> (Trait) trait) + .orElseGet( + () -> shape.getTrait(IntegrationTrait.class) + .map(trait -> (Trait) trait) + .orElse(defaultValue) + ); } } diff --git a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/MockIntegrationTrait.java b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/MockIntegrationTrait.java index 241a3696b7e..34a48b3c6f9 100644 --- a/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/MockIntegrationTrait.java +++ b/smithy-aws-apigateway-traits/src/main/java/software/amazon/smithy/aws/apigateway/traits/MockIntegrationTrait.java @@ -154,12 +154,12 @@ protected ObjectNode createNode() { @Override public Builder toBuilder() { return builder() - .sourceLocation(getSourceLocation()) - .passThroughBehavior(passThroughBehavior) - .contentHandling(contentHandling) - .requestParameters(requestParameters) - .requestTemplates(requestTemplates) - .responses(responses); + .sourceLocation(getSourceLocation()) + .passThroughBehavior(passThroughBehavior) + .contentHandling(contentHandling) + .requestParameters(requestParameters) + .requestTemplates(requestTemplates) + .responses(responses); } public static final class Builder extends AbstractTraitBuilder { diff --git a/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/AuthorizerIndexTest.java b/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/AuthorizerIndexTest.java index b0f1e0d889e..27762fe3636 100644 --- a/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/AuthorizerIndexTest.java +++ b/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/AuthorizerIndexTest.java @@ -17,10 +17,10 @@ public class AuthorizerIndexTest { @Test public void computesAuthorizers() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("effective-authorizers.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("effective-authorizers.smithy")) + .assemble() + .unwrap(); AuthorizerIndex index = AuthorizerIndex.of(model); ShapeId serviceA = ShapeId.from("smithy.example#ServiceA"); @@ -37,8 +37,8 @@ public void computesAuthorizers() { // Resolves service value. assertThat(index.getAuthorizer(serviceA).get(), equalTo("foo")); assertThat( - index.getAuthorizerValue(serviceA).map(AuthorizerDefinition::getScheme), - equalTo(Optional.of(SigV4Trait.ID)) + index.getAuthorizerValue(serviceA).map(AuthorizerDefinition::getScheme), + equalTo(Optional.of(SigV4Trait.ID)) ); assertThat(index.getAuthorizer(serviceB), equalTo(Optional.empty())); assertThat(index.getAuthorizerValue(serviceB), equalTo(Optional.empty())); diff --git a/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/AuthorizersTraitTest.java b/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/AuthorizersTraitTest.java index 805cb4d8bee..637a6ca0310 100644 --- a/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/AuthorizersTraitTest.java +++ b/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/AuthorizersTraitTest.java @@ -21,21 +21,21 @@ public void registersTrait() { TraitFactory factory = TraitFactory.createServiceFactory(); ShapeId id = ShapeId.from("smithy.example#Foo"); ObjectNode node = Node.objectNodeBuilder() - .withMember( - "aws.v4", - Node.objectNodeBuilder() - .withMember("scheme", "aws.auth#sigv4") - .withMember("type", "request") - .withMember("uri", "arn:foo:baz") - .withMember("credentials", "arn:foo:bar") - .withMember("identitySource", "mapping.expression") - .withMember("identityValidationExpression", "[A-Z]+") - .withMember("resultTtlInSeconds", 100) - .withMember("authorizerPayloadFormatVersion", "format.version") - .withMember("enableSimpleResponse", true) - .build() - ) - .build(); + .withMember( + "aws.v4", + Node.objectNodeBuilder() + .withMember("scheme", "aws.auth#sigv4") + .withMember("type", "request") + .withMember("uri", "arn:foo:baz") + .withMember("credentials", "arn:foo:bar") + .withMember("identitySource", "mapping.expression") + .withMember("identityValidationExpression", "[A-Z]+") + .withMember("resultTtlInSeconds", 100) + .withMember("authorizerPayloadFormatVersion", "format.version") + .withMember("enableSimpleResponse", true) + .build() + ) + .build(); Trait trait = factory.createTrait(AuthorizersTrait.ID, id, node).get(); assertThat(trait, instanceOf(AuthorizersTrait.class)); diff --git a/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTraitIndexTest.java b/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTraitIndexTest.java index e7e5abb4855..fd14569099c 100644 --- a/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTraitIndexTest.java +++ b/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTraitIndexTest.java @@ -15,10 +15,10 @@ public class IntegrationTraitIndexTest { @Test public void resolvesTraits() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("integration-index.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("integration-index.json")) + .assemble() + .unwrap(); IntegrationTraitIndex index = IntegrationTraitIndex.of(model); ShapeId service = ShapeId.from("ns.foo#Service"); diff --git a/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTraitTest.java b/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTraitTest.java index d5fba0bba47..38f790ae975 100644 --- a/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTraitTest.java +++ b/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/IntegrationTraitTest.java @@ -14,25 +14,25 @@ public class IntegrationTraitTest { @Test public void loadsValidTrait() { IntegrationTrait trait = IntegrationTrait.builder() - .type("aws_proxy") - .uri("foo") - .httpMethod("POST") - .addCacheKeyParameter("foo") - .cacheNamespace("baz") - .connectionId("id") - .connectionType("xyz") - .contentHandling("CONVERT_TO_TEXT") - .credentials("abc") - .payloadFormatVersion("1.0") - .passThroughBehavior("when_no_templates") - .putRequestParameter("x", "y") - .build(); + .type("aws_proxy") + .uri("foo") + .httpMethod("POST") + .addCacheKeyParameter("foo") + .cacheNamespace("baz") + .connectionId("id") + .connectionType("xyz") + .contentHandling("CONVERT_TO_TEXT") + .credentials("abc") + .payloadFormatVersion("1.0") + .passThroughBehavior("when_no_templates") + .putRequestParameter("x", "y") + .build(); assertThat(trait.toBuilder().build(), equalTo(trait)); // Test round-tripping from/to node. assertThat( - new IntegrationTrait.Provider().createTrait(ShapeId.from("ns.foo#Operation"), trait.toNode()), - equalTo(trait) + new IntegrationTrait.Provider().createTrait(ShapeId.from("ns.foo#Operation"), trait.toNode()), + equalTo(trait) ); } } diff --git a/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/MockIntegrationTraitTest.java b/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/MockIntegrationTraitTest.java index f707993a073..0b54983b923 100644 --- a/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/MockIntegrationTraitTest.java +++ b/smithy-aws-apigateway-traits/src/test/java/software/amazon/smithy/aws/apigateway/traits/MockIntegrationTraitTest.java @@ -15,46 +15,46 @@ public class MockIntegrationTraitTest { @Test public void loadsValidTrait() { MockIntegrationTrait trait = MockIntegrationTrait.builder() - .contentHandling("CONVERT_TO_TEXT") - .passThroughBehavior("when_no_templates") - .putRequestParameter("x", "y") - .putRequestTemplate("application/json", "{}") - .putRequestParameter("foo", "baz") - .putResponse( - "[A-Z]+", - IntegrationResponse.builder() - .statusCode("200") - .contentHandling("CONVERT_TO_TEXT") - .build() - ) - .build(); + .contentHandling("CONVERT_TO_TEXT") + .passThroughBehavior("when_no_templates") + .putRequestParameter("x", "y") + .putRequestTemplate("application/json", "{}") + .putRequestParameter("foo", "baz") + .putResponse( + "[A-Z]+", + IntegrationResponse.builder() + .statusCode("200") + .contentHandling("CONVERT_TO_TEXT") + .build() + ) + .build(); assertThat(trait.toBuilder().build(), equalTo(trait)); // Test round-tripping from/to node. assertThat( - new MockIntegrationTrait.Provider().createTrait(ShapeId.from("com.foo#Baz"), trait.toNode()), - equalTo(trait) + new MockIntegrationTrait.Provider().createTrait(ShapeId.from("com.foo#Baz"), trait.toNode()), + equalTo(trait) ); } @Test public void loadsTraitFromModel() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(TestRunnerTest.class.getResource("errorfiles/valid-integration.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(TestRunnerTest.class.getResource("errorfiles/valid-integration.json")) + .assemble() + .unwrap(); MockIntegrationTrait trait = model.expectShape(ShapeId.from("ns.foo#Operation")) - .getTrait(MockIntegrationTrait.class) - .get(); + .getTrait(MockIntegrationTrait.class) + .get(); assertThat(trait.toBuilder().build(), equalTo(trait)); // Test round-tripping from/to node. assertThat( - new MockIntegrationTrait.Provider().createTrait(ShapeId.from("ns.foo#Operation"), trait.toNode()), - equalTo(trait) + new MockIntegrationTrait.Provider().createTrait(ShapeId.from("ns.foo#Operation"), trait.toNode()), + equalTo(trait) ); } } diff --git a/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnMutabilityTraitValidator.java b/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnMutabilityTraitValidator.java index b9edba58247..973e31377fd 100644 --- a/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnMutabilityTraitValidator.java +++ b/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnMutabilityTraitValidator.java @@ -26,15 +26,15 @@ public List validate(Model model) { // create mutabilities cannot overlap. if (shape.hasTrait(CfnAdditionalIdentifierTrait.ID) && (trait.isWrite() || trait.isCreate())) { events.add( - error( - shape, - trait, - String.format( - "Member with the mutability value of \"%s\" " - + "is also marked as an additional identifier", - trait.getValue() + error( + shape, + trait, + String.format( + "Member with the mutability value of \"%s\" " + + "is also marked as an additional identifier", + trait.getValue() + ) ) - ) ); } } diff --git a/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResource.java b/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResource.java index 21710a5b628..d1a055beb0b 100644 --- a/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResource.java +++ b/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResource.java @@ -42,9 +42,9 @@ private CfnResource(Builder builder) { if (excludedProperties.contains(shapeId)) { // Remove an excluded ShapeId for validation. CfnResourceProperty updatedDefinition = propertyDefinition.getValue() - .toBuilder() - .removeShapeId(shapeId) - .build(); + .toBuilder() + .removeShapeId(shapeId) + .build(); propertyDefinitions.put(propertyDefinition.getKey(), updatedDefinition); // Update any definition in available properties to also @@ -109,7 +109,7 @@ public Set getCreateOnlyProperties() { return getConstrainedProperties(definition -> { Set mutabilities = definition.getMutabilities(); return mutabilities.contains(CfnResourceIndex.Mutability.CREATE) - && !mutabilities.contains(CfnResourceIndex.Mutability.WRITE); + && !mutabilities.contains(CfnResourceIndex.Mutability.WRITE); }); } @@ -148,16 +148,16 @@ public Set getWriteOnlyProperties() { // Otherwise, create and update, or update only become writeOnly. return mutabilities.contains(CfnResourceIndex.Mutability.WRITE) - && !mutabilities.contains(CfnResourceIndex.Mutability.READ); + && !mutabilities.contains(CfnResourceIndex.Mutability.READ); }); } private Set getConstrainedProperties(Predicate constraint) { return getProperties().entrySet() - .stream() - .filter(property -> constraint.test(property.getValue())) - .map(Map.Entry::getKey) - .collect(Collectors.toSet()); + .stream() + .filter(property -> constraint.test(property.getValue())) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); } /** @@ -197,10 +197,10 @@ public List> getAdditionalIdentifiers() { @Override public Builder toBuilder() { return builder() - .propertyDefinitions(propertyDefinitions) - .excludedProperties(excludedProperties) - .primaryIdentifiers(primaryIdentifiers) - .additionalIdentifiers(additionalIdentifiers); + .propertyDefinitions(propertyDefinitions) + .excludedProperties(excludedProperties) + .primaryIdentifiers(primaryIdentifiers) + .additionalIdentifiers(additionalIdentifiers); } public static final class Builder implements SmithyBuilder { @@ -221,8 +221,8 @@ public Builder putPropertyDefinition(String propertyName, CfnResourceProperty de } public Builder updatePropertyDefinition( - String propertyName, - Function updater + String propertyName, + Function updater ) { CfnResourceProperty definition = propertyDefinitions.get(propertyName); diff --git a/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceIndex.java b/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceIndex.java index 7c629d3a51b..20bf56ff055 100644 --- a/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceIndex.java +++ b/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceIndex.java @@ -39,13 +39,13 @@ public final class CfnResourceIndex implements KnowledgeIndex { static final Set FULLY_MUTABLE = SetUtils.of( - Mutability.CREATE, - Mutability.READ, - Mutability.WRITE + Mutability.CREATE, + Mutability.READ, + Mutability.WRITE ); static final Set INHERITED_MUTABILITY = SetUtils.of( - Mutability.CREATE, - Mutability.READ + Mutability.CREATE, + Mutability.READ ); private final Map resourceDefinitions = new HashMap<>(); @@ -86,108 +86,108 @@ public CfnResourceIndex(Model model) { PropertyBindingIndex propertyIndex = PropertyBindingIndex.of(model); BottomUpIndex bottomUpIndex = BottomUpIndex.of(model); model.shapes(ResourceShape.class) - .filter(shape -> shape.hasTrait(CfnResourceTrait.ID)) - .forEach(resource -> { - CfnResource.Builder builder = CfnResource.builder(); - ShapeId resourceId = resource.getId(); - - Set parentResources = model.getServiceShapes() - .stream() - .map(service -> bottomUpIndex.getResourceBinding(service, resourceId)) - .flatMap(OptionalUtils::stream) - .collect(Collectors.toSet()); - - // Start with the explicit resource identifiers. - builder.primaryIdentifiers(resource.getIdentifiers().keySet()); - setIdentifierMutabilities(builder, resource, parentResources); - - // Use the read lifecycle's input to collect the additional identifiers - // and its output to collect readable properties. - resource.getRead().ifPresent(operationId -> { - OperationShape operation = model.expectShape(operationId, OperationShape.class); - StructureShape input = model.expectShape(operation.getInputShape(), StructureShape.class); - addAdditionalIdentifiers(builder, computeResourceAdditionalIdentifiers(input)); - - StructureShape output = propertyIndex.getOutputPropertiesShape(operation); - updatePropertyMutabilities( - builder, - model, - resourceId, - operationId, - output, - SetUtils.of(Mutability.READ), - this::addReadMutability - ); - }); - - // Use the put lifecycle's input to collect put-able properties. - resource.getPut().ifPresent(operationId -> { - OperationShape operation = model.expectShape(operationId, OperationShape.class); - StructureShape input = propertyIndex.getInputPropertiesShape(operation); - updatePropertyMutabilities( - builder, - model, - resourceId, - operationId, - input, - SetUtils.of(Mutability.CREATE, Mutability.WRITE), - this::addPutMutability - ); - }); - - // Use the create lifecycle's input to collect creatable properties. - resource.getCreate().ifPresent(operationId -> { - OperationShape operation = model.expectShape(operationId, OperationShape.class); - StructureShape input = propertyIndex.getInputPropertiesShape(operation); - updatePropertyMutabilities( - builder, - model, - resourceId, - operationId, - input, - SetUtils.of(Mutability.CREATE), - this::addCreateMutability - ); - }); - - // Use the update lifecycle's input to collect writeable properties. - resource.getUpdate().ifPresent(operationId -> { - OperationShape operation = model.expectShape(operationId, OperationShape.class); - StructureShape input = propertyIndex.getInputPropertiesShape(operation); - updatePropertyMutabilities( - builder, - model, - resourceId, - operationId, - input, - SetUtils.of(Mutability.WRITE), - this::addWriteMutability - ); - }); - - // Apply any members found through the trait's additionalSchemas property. - CfnResourceTrait trait = resource.expectTrait(CfnResourceTrait.class); - for (ShapeId additionalSchema : trait.getAdditionalSchemas()) { - // These shapes should be present given the @idRef failWhenMissing - // setting, but gracefully handle if they're not. - model.getShape(additionalSchema) - .flatMap(Shape::asStructureShape) - .ifPresent(shape -> { - addAdditionalIdentifiers(builder, computeResourceAdditionalIdentifiers(shape)); - updatePropertyMutabilities( + .filter(shape -> shape.hasTrait(CfnResourceTrait.ID)) + .forEach(resource -> { + CfnResource.Builder builder = CfnResource.builder(); + ShapeId resourceId = resource.getId(); + + Set parentResources = model.getServiceShapes() + .stream() + .map(service -> bottomUpIndex.getResourceBinding(service, resourceId)) + .flatMap(OptionalUtils::stream) + .collect(Collectors.toSet()); + + // Start with the explicit resource identifiers. + builder.primaryIdentifiers(resource.getIdentifiers().keySet()); + setIdentifierMutabilities(builder, resource, parentResources); + + // Use the read lifecycle's input to collect the additional identifiers + // and its output to collect readable properties. + resource.getRead().ifPresent(operationId -> { + OperationShape operation = model.expectShape(operationId, OperationShape.class); + StructureShape input = model.expectShape(operation.getInputShape(), StructureShape.class); + addAdditionalIdentifiers(builder, computeResourceAdditionalIdentifiers(input)); + + StructureShape output = propertyIndex.getOutputPropertiesShape(operation); + updatePropertyMutabilities( builder, model, resourceId, - null, - shape, - SetUtils.of(), - Function.identity() - ); - }); - } - - resourceDefinitions.put(resourceId, builder.build()); - }); + operationId, + output, + SetUtils.of(Mutability.READ), + this::addReadMutability + ); + }); + + // Use the put lifecycle's input to collect put-able properties. + resource.getPut().ifPresent(operationId -> { + OperationShape operation = model.expectShape(operationId, OperationShape.class); + StructureShape input = propertyIndex.getInputPropertiesShape(operation); + updatePropertyMutabilities( + builder, + model, + resourceId, + operationId, + input, + SetUtils.of(Mutability.CREATE, Mutability.WRITE), + this::addPutMutability + ); + }); + + // Use the create lifecycle's input to collect creatable properties. + resource.getCreate().ifPresent(operationId -> { + OperationShape operation = model.expectShape(operationId, OperationShape.class); + StructureShape input = propertyIndex.getInputPropertiesShape(operation); + updatePropertyMutabilities( + builder, + model, + resourceId, + operationId, + input, + SetUtils.of(Mutability.CREATE), + this::addCreateMutability + ); + }); + + // Use the update lifecycle's input to collect writeable properties. + resource.getUpdate().ifPresent(operationId -> { + OperationShape operation = model.expectShape(operationId, OperationShape.class); + StructureShape input = propertyIndex.getInputPropertiesShape(operation); + updatePropertyMutabilities( + builder, + model, + resourceId, + operationId, + input, + SetUtils.of(Mutability.WRITE), + this::addWriteMutability + ); + }); + + // Apply any members found through the trait's additionalSchemas property. + CfnResourceTrait trait = resource.expectTrait(CfnResourceTrait.class); + for (ShapeId additionalSchema : trait.getAdditionalSchemas()) { + // These shapes should be present given the @idRef failWhenMissing + // setting, but gracefully handle if they're not. + model.getShape(additionalSchema) + .flatMap(Shape::asStructureShape) + .ifPresent(shape -> { + addAdditionalIdentifiers(builder, computeResourceAdditionalIdentifiers(shape)); + updatePropertyMutabilities( + builder, + model, + resourceId, + null, + shape, + SetUtils.of(), + Function.identity() + ); + }); + } + + resourceDefinitions.put(resourceId, builder.build()); + }); } public static CfnResourceIndex of(Model model) { @@ -206,28 +206,28 @@ public Optional getResource(ToShapeId resource) { private boolean identifierIsInherited(String identifier, Set parentResources) { return parentResources.stream() - .anyMatch(parentResource -> parentResource.getIdentifiers().containsKey(identifier)); + .anyMatch(parentResource -> parentResource.getIdentifiers().containsKey(identifier)); } private void setIdentifierMutabilities( - CfnResource.Builder builder, - ResourceShape resource, - Set parentResources + CfnResource.Builder builder, + ResourceShape resource, + Set parentResources ) { Set defaultIdentifierMutability = getDefaultIdentifierMutabilities(resource); resource.getIdentifiers().forEach((name, shape) -> { builder.putPropertyDefinition( - name, - CfnResourceProperty.builder() - .hasExplicitMutability(true) - .mutabilities( - identifierIsInherited(name, parentResources) - ? INHERITED_MUTABILITY - : defaultIdentifierMutability - ) - .addShapeId(shape) - .build() + name, + CfnResourceProperty.builder() + .hasExplicitMutability(true) + .mutabilities( + identifierIsInherited(name, parentResources) + ? INHERITED_MUTABILITY + : defaultIdentifierMutability + ) + .addShapeId(shape) + .build() ); }); } @@ -255,8 +255,8 @@ private List> computeResourceAdditionalIdentifiers(Structur } private void addAdditionalIdentifiers( - CfnResource.Builder builder, - List> addedIdentifiers + CfnResource.Builder builder, + List> addedIdentifiers ) { if (addedIdentifiers.isEmpty()) { return; @@ -266,11 +266,11 @@ private void addAdditionalIdentifiers( for (Map addedIdentifier : addedIdentifiers) { for (Map.Entry idEntry : addedIdentifier.entrySet()) { builder.putPropertyDefinition( - idEntry.getKey(), - CfnResourceProperty.builder() - .mutabilities(SetUtils.of(Mutability.READ)) - .addShapeId(idEntry.getValue()) - .build() + idEntry.getKey(), + CfnResourceProperty.builder() + .mutabilities(SetUtils.of(Mutability.READ)) + .addShapeId(idEntry.getValue()) + .build() ); } builder.addAdditionalIdentifier(addedIdentifier.keySet()); @@ -278,17 +278,17 @@ private void addAdditionalIdentifiers( } private void updatePropertyMutabilities( - CfnResource.Builder builder, - Model model, - ShapeId resourceId, - ShapeId operationId, - StructureShape propertyContainer, - Set defaultMutabilities, - Function, Set> updater + CfnResource.Builder builder, + Model model, + ShapeId resourceId, + ShapeId operationId, + StructureShape propertyContainer, + Set defaultMutabilities, + Function, Set> updater ) { // Handle the @excludeProperty trait. propertyContainer.accept(new ExcludedPropertiesVisitor(model)) - .forEach(builder::addExcludedProperty); + .forEach(builder::addExcludedProperty); for (MemberShape member : propertyContainer.members()) { // We've explicitly set identifier mutability based on how the @@ -302,31 +302,31 @@ private void updatePropertyMutabilities( // Set the correct mutability for if this is a new property. Set mutabilities = !explicitMutability.isEmpty() - ? explicitMutability - : defaultMutabilities; + ? explicitMutability + : defaultMutabilities; if (builder.hasPropertyDefinition(memberName)) { builder.updatePropertyDefinition( - memberName, - getCfnResourcePropertyUpdater(member, explicitMutability, updater) + memberName, + getCfnResourcePropertyUpdater(member, explicitMutability, updater) ); } else { builder.putPropertyDefinition( - memberName, - CfnResourceProperty.builder() - .addShapeId(member.getId()) - .mutabilities(mutabilities) - .hasExplicitMutability(!explicitMutability.isEmpty()) - .build() + memberName, + CfnResourceProperty.builder() + .addShapeId(member.getId()) + .mutabilities(mutabilities) + .hasExplicitMutability(!explicitMutability.isEmpty()) + .build() ); } } } private Function getCfnResourcePropertyUpdater( - MemberShape member, - Set explicitMutability, - Function, Set> updater + MemberShape member, + Set explicitMutability, + Function, Set> updater ) { return definition -> { CfnResourceProperty.Builder builder = definition.toBuilder().addShapeId(member.getId()); @@ -337,7 +337,7 @@ private Function getCfnResourcePropert } else { // Handle explicit mutability from any trait location. builder.hasExplicitMutability(true) - .mutabilities(explicitMutability); + .mutabilities(explicitMutability); } return builder.build(); @@ -345,10 +345,10 @@ private Function getCfnResourcePropert } private boolean inputOperationMemberIsIdentifier( - Model model, - ShapeId resourceId, - ShapeId operationId, - MemberShape member + Model model, + ShapeId resourceId, + ShapeId operationId, + MemberShape member ) { // The operationId will be null in the case of additionalSchemas, so // we shouldn't worry if these are bound to operation identifiers. @@ -370,8 +370,8 @@ private boolean inputOperationMemberIsIdentifier( } private Set getExplicitMutability( - Model model, - MemberShape member + Model model, + MemberShape member ) { Optional traitOptional = member.getMemberTrait(model, CfnMutabilityTrait.class); if (!traitOptional.isPresent()) { diff --git a/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceProperty.java b/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceProperty.java index 6270d16ba3a..e7ac6174182 100644 --- a/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceProperty.java +++ b/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceProperty.java @@ -79,8 +79,8 @@ public Set getMutabilities() { @Override public Builder toBuilder() { return builder() - .shapeIds(shapeIds) - .mutabilities(mutabilities); + .shapeIds(shapeIds) + .mutabilities(mutabilities); } public static final class Builder implements SmithyBuilder { diff --git a/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourcePropertyValidator.java b/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourcePropertyValidator.java index 7e34669a256..27aa192557f 100644 --- a/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourcePropertyValidator.java +++ b/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourcePropertyValidator.java @@ -28,65 +28,65 @@ public List validate(Model model) { CfnResourceIndex cfnResourceIndex = CfnResourceIndex.of(model); model.shapes(ResourceShape.class) - .filter(shape -> shape.hasTrait(CfnResourceTrait.ID)) - .map(shape -> validateResource(model, cfnResourceIndex, shape)) - .forEach(events::addAll); + .filter(shape -> shape.hasTrait(CfnResourceTrait.ID)) + .map(shape -> validateResource(model, cfnResourceIndex, shape)) + .forEach(events::addAll); return events; } private List validateResource( - Model model, - CfnResourceIndex cfnResourceIndex, - ResourceShape resource + Model model, + CfnResourceIndex cfnResourceIndex, + ResourceShape resource ) { CfnResourceTrait trait = resource.expectTrait(CfnResourceTrait.class); List events = new ArrayList<>(); String resourceName = trait.getName().orElse(resource.getId().getName()); cfnResourceIndex.getResource(resource) - .map(CfnResource::getProperties) - .ifPresent(properties -> { - for (Map.Entry property : properties.entrySet()) { - validateResourceProperty(model, resource, resourceName, property).ifPresent(events::add); - } - }); + .map(CfnResource::getProperties) + .ifPresent(properties -> { + for (Map.Entry property : properties.entrySet()) { + validateResourceProperty(model, resource, resourceName, property).ifPresent(events::add); + } + }); return events; } private Optional validateResourceProperty( - Model model, - ResourceShape resource, - String resourceName, - Map.Entry property + Model model, + ResourceShape resource, + String resourceName, + Map.Entry property ) { Set propertyTargets = new TreeSet<>(); for (ShapeId shapeId : property.getValue().getShapeIds()) { model.getShape(shapeId).ifPresent(shape -> // Use the member target or identifier definition shape. OptionalUtils.ifPresentOrElse( - shape.asMemberShape(), - memberShape -> propertyTargets.add(memberShape.getTarget()), - () -> propertyTargets.add(shapeId) + shape.asMemberShape(), + memberShape -> propertyTargets.add(memberShape.getTarget()), + () -> propertyTargets.add(shapeId) )); } if (propertyTargets.size() > 1) { return Optional.of( - error( - resource, - String.format( - "The `%s` property of the generated `%s` " - + "CloudFormation resource targets multiple shapes: %s. Reusing member names that " - + "target different shapes can cause confusion for users of the API. This target " - + "discrepancy must either be resolved in the model or one of the members must be " - + "excluded from the conversion.", - property.getKey(), - resourceName, - propertyTargets + error( + resource, + String.format( + "The `%s` property of the generated `%s` " + + "CloudFormation resource targets multiple shapes: %s. Reusing member names that " + + "target different shapes can cause confusion for users of the API. This target " + + "discrepancy must either be resolved in the model or one of the members must be " + + "excluded from the conversion.", + property.getKey(), + resourceName, + propertyTargets + ) ) - ) ); } diff --git a/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceTrait.java b/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceTrait.java index b38e544a6bd..fb5c4e92abb 100644 --- a/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceTrait.java +++ b/smithy-aws-cloudformation-traits/src/main/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceTrait.java @@ -20,7 +20,7 @@ * Indicates that a Smithy resource is a CloudFormation resource. */ public final class CfnResourceTrait extends AbstractTrait - implements ToSmithyBuilder { + implements ToSmithyBuilder { public static final ShapeId ID = ShapeId.from("aws.cloudformation#cfnResource"); private final String name; diff --git a/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnDefaultValueTraitTest.java b/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnDefaultValueTraitTest.java index a3efc9f8349..cd260cf1374 100644 --- a/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnDefaultValueTraitTest.java +++ b/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnDefaultValueTraitTest.java @@ -15,15 +15,15 @@ public final class CfnDefaultValueTraitTest { @Test public void detectsDefaultValue() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("test-service.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("test-service.smithy")) + .assemble() + .unwrap(); assertTrue( - result.getShape(ShapeId.from("smithy.example#GetFooResponse$fooId")) - .flatMap(shape -> shape.getTrait(CfnDefaultValueTrait.class)) - .isPresent() + result.getShape(ShapeId.from("smithy.example#GetFooResponse$fooId")) + .flatMap(shape -> shape.getTrait(CfnDefaultValueTrait.class)) + .isPresent() ); } } diff --git a/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnMutabilityTraitTest.java b/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnMutabilityTraitTest.java index 3f0092cbdb2..37d4935bcab 100644 --- a/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnMutabilityTraitTest.java +++ b/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnMutabilityTraitTest.java @@ -23,9 +23,9 @@ public void loadsTraitWithString() { Node node = Node.from("full"); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("aws.cloudformation#cfnMutability"), - ShapeId.from("ns.qux#Foo"), - node + ShapeId.from("aws.cloudformation#cfnMutability"), + ShapeId.from("ns.qux#Foo"), + node ); assertTrue(trait.isPresent()); diff --git a/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnNameTraitTest.java b/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnNameTraitTest.java index f04deb4f4d7..2b98a260703 100644 --- a/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnNameTraitTest.java +++ b/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnNameTraitTest.java @@ -23,9 +23,9 @@ public void loadsTraitWithString() { Node node = Node.from("Text"); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("aws.cloudformation#cfnName"), - ShapeId.from("ns.qux#Foo"), - node + ShapeId.from("aws.cloudformation#cfnName"), + ShapeId.from("ns.qux#Foo"), + node ); assertTrue(trait.isPresent()); diff --git a/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceIndexTest.java b/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceIndexTest.java index c069eec5380..85ec92fb872 100644 --- a/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceIndexTest.java +++ b/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceIndexTest.java @@ -35,10 +35,10 @@ public class CfnResourceIndexTest { @BeforeAll public static void loadTestModel() { model = Model.assembler() - .discoverModels(CfnResourceIndexTest.class.getClassLoader()) - .addImport(CfnResourceIndexTest.class.getResource("test-service.smithy")) - .assemble() - .unwrap(); + .discoverModels(CfnResourceIndexTest.class.getClassLoader()) + .addImport(CfnResourceIndexTest.class.getResource("test-service.smithy")) + .assemble() + .unwrap(); cfnResourceIndex = CfnResourceIndex.of(model); } @@ -58,18 +58,18 @@ public static Collection data() { fooResource.identifiers = SetUtils.of("fooId"); fooResource.additionalIdentifiers = ListUtils.of(); fooResource.mutabilities = MapUtils.of( - "fooId", - SetUtils.of(Mutability.READ), - "fooValidFullyMutableProperty", - CfnResourceIndex.FULLY_MUTABLE, - "fooValidCreateProperty", - SetUtils.of(Mutability.CREATE), - "fooValidCreateReadProperty", - SetUtils.of(Mutability.CREATE, Mutability.READ), - "fooValidReadProperty", - SetUtils.of(Mutability.READ), - "fooValidWriteProperty", - SetUtils.of(Mutability.WRITE) + "fooId", + SetUtils.of(Mutability.READ), + "fooValidFullyMutableProperty", + CfnResourceIndex.FULLY_MUTABLE, + "fooValidCreateProperty", + SetUtils.of(Mutability.CREATE), + "fooValidCreateReadProperty", + SetUtils.of(Mutability.CREATE, Mutability.READ), + "fooValidReadProperty", + SetUtils.of(Mutability.READ), + "fooValidWriteProperty", + SetUtils.of(Mutability.WRITE) ); fooResource.createOnlyProperties = SetUtils.of("fooValidCreateProperty", "fooValidCreateReadProperty"); fooResource.readOnlyProperties = SetUtils.of("fooId", "fooValidReadProperty"); @@ -80,18 +80,18 @@ public static Collection data() { barResource.identifiers = SetUtils.of("barId"); barResource.additionalIdentifiers = ListUtils.of(SetUtils.of("arn")); barResource.mutabilities = MapUtils.of( - "barId", - SetUtils.of(Mutability.CREATE, Mutability.READ), - "arn", - SetUtils.of(Mutability.READ), - "barExplicitMutableProperty", - CfnResourceIndex.FULLY_MUTABLE, - "barValidAdditionalProperty", - SetUtils.of(), - "barImplicitReadProperty", - SetUtils.of(Mutability.READ), - "barImplicitFullProperty", - CfnResourceIndex.FULLY_MUTABLE + "barId", + SetUtils.of(Mutability.CREATE, Mutability.READ), + "arn", + SetUtils.of(Mutability.READ), + "barExplicitMutableProperty", + CfnResourceIndex.FULLY_MUTABLE, + "barValidAdditionalProperty", + SetUtils.of(), + "barImplicitReadProperty", + SetUtils.of(Mutability.READ), + "barImplicitFullProperty", + CfnResourceIndex.FULLY_MUTABLE ); barResource.createOnlyProperties = SetUtils.of("barId"); barResource.readOnlyProperties = SetUtils.of("arn", "barImplicitReadProperty"); @@ -102,20 +102,20 @@ public static Collection data() { bazResource.identifiers = SetUtils.of("barId", "bazId"); bazResource.additionalIdentifiers = ListUtils.of(); bazResource.mutabilities = MapUtils.of( - "barId", - SetUtils.of(Mutability.CREATE, Mutability.READ), - "bazId", - SetUtils.of(Mutability.READ), - "bazExplicitMutableProperty", - CfnResourceIndex.FULLY_MUTABLE, - "bazImplicitFullyMutableProperty", - CfnResourceIndex.FULLY_MUTABLE, - "bazImplicitCreateProperty", - SetUtils.of(Mutability.CREATE, Mutability.READ), - "bazImplicitReadProperty", - SetUtils.of(Mutability.READ), - "bazImplicitWriteProperty", - SetUtils.of(Mutability.CREATE, Mutability.WRITE) + "barId", + SetUtils.of(Mutability.CREATE, Mutability.READ), + "bazId", + SetUtils.of(Mutability.READ), + "bazExplicitMutableProperty", + CfnResourceIndex.FULLY_MUTABLE, + "bazImplicitFullyMutableProperty", + CfnResourceIndex.FULLY_MUTABLE, + "bazImplicitCreateProperty", + SetUtils.of(Mutability.CREATE, Mutability.READ), + "bazImplicitReadProperty", + SetUtils.of(Mutability.READ), + "bazImplicitWriteProperty", + SetUtils.of(Mutability.CREATE, Mutability.WRITE) ); bazResource.createOnlyProperties = SetUtils.of("barId", "bazImplicitCreateProperty"); bazResource.readOnlyProperties = SetUtils.of("bazId", "bazImplicitReadProperty"); @@ -128,9 +128,9 @@ public static Collection data() { @MethodSource("data") public void detectsPrimaryIdentifiers(ResourceData data) { assertThat( - String.format("Failure for resource %s.", data.resourceId), - cfnResourceIndex.getResource(data.resourceId).get().getPrimaryIdentifiers(), - containsInAnyOrder(data.identifiers.toArray()) + String.format("Failure for resource %s.", data.resourceId), + cfnResourceIndex.getResource(data.resourceId).get().getPrimaryIdentifiers(), + containsInAnyOrder(data.identifiers.toArray()) ); } @@ -138,9 +138,9 @@ public void detectsPrimaryIdentifiers(ResourceData data) { @MethodSource("data") public void detectsAdditionalIdentifiers(ResourceData data) { assertThat( - String.format("Failure for resource %s.", data.resourceId), - cfnResourceIndex.getResource(data.resourceId).get().getAdditionalIdentifiers(), - containsInAnyOrder(data.additionalIdentifiers.toArray()) + String.format("Failure for resource %s.", data.resourceId), + cfnResourceIndex.getResource(data.resourceId).get().getAdditionalIdentifiers(), + containsInAnyOrder(data.additionalIdentifiers.toArray()) ); } @@ -148,15 +148,15 @@ public void detectsAdditionalIdentifiers(ResourceData data) { @MethodSource("data") public void findsAllProperties(ResourceData data) { Map properties = cfnResourceIndex.getResource(data.resourceId) - .get() - .getProperties(); + .get() + .getProperties(); assertThat(properties.keySet(), containsInAnyOrder(data.mutabilities.keySet().toArray())); properties.forEach((name, definition) -> { assertThat( - String.format("Mismatch on property %s for %s.", name, data.resourceId), - definition.getMutabilities(), - containsInAnyOrder(data.mutabilities.get(name).toArray()) + String.format("Mismatch on property %s for %s.", name, data.resourceId), + definition.getMutabilities(), + containsInAnyOrder(data.mutabilities.get(name).toArray()) ); }); } @@ -167,9 +167,9 @@ public void findsCreateOnlyProperties(ResourceData data) { Set properties = cfnResourceIndex.getResource(data.resourceId).get().getCreateOnlyProperties(); assertThat( - String.format("Failure for resource %s.", data.resourceId), - properties, - containsInAnyOrder(data.createOnlyProperties.toArray()) + String.format("Failure for resource %s.", data.resourceId), + properties, + containsInAnyOrder(data.createOnlyProperties.toArray()) ); } @@ -179,9 +179,9 @@ public void findsReadOnlyProperties(ResourceData data) { Set properties = cfnResourceIndex.getResource(data.resourceId).get().getReadOnlyProperties(); assertThat( - String.format("Failure for resource %s.", data.resourceId), - properties, - containsInAnyOrder(data.readOnlyProperties.toArray()) + String.format("Failure for resource %s.", data.resourceId), + properties, + containsInAnyOrder(data.readOnlyProperties.toArray()) ); } @@ -191,33 +191,33 @@ public void findsWriteOnlyProperties(ResourceData data) { Set properties = cfnResourceIndex.getResource(data.resourceId).get().getWriteOnlyProperties(); assertThat( - String.format("Failure for resource %s.", data.resourceId), - properties, - containsInAnyOrder(data.writeOnlyProperties.toArray()) + String.format("Failure for resource %s.", data.resourceId), + properties, + containsInAnyOrder(data.writeOnlyProperties.toArray()) ); } @Test public void setsProperIdentifierMutability() { Map fooProperties = cfnResourceIndex.getResource(FOO) - .get() - .getProperties(); + .get() + .getProperties(); Map barProperties = cfnResourceIndex.getResource(BAR) - .get() - .getProperties(); + .get() + .getProperties(); assertThat(fooProperties.get("fooId").getMutabilities(), containsInAnyOrder(Mutability.READ)); assertThat( - barProperties.get("barId").getMutabilities(), - containsInAnyOrder(Mutability.CREATE, Mutability.READ) + barProperties.get("barId").getMutabilities(), + containsInAnyOrder(Mutability.CREATE, Mutability.READ) ); } @Test public void handlesAdditionalSchemaProperty() { Map barProperties = cfnResourceIndex.getResource(BAR) - .get() - .getProperties(); + .get() + .getProperties(); assertTrue(barProperties.containsKey("barValidAdditionalProperty")); assertTrue(barProperties.get("barValidAdditionalProperty").getMutabilities().isEmpty()); diff --git a/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceTraitTest.java b/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceTraitTest.java index 702027f576c..1df58973f90 100644 --- a/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceTraitTest.java +++ b/smithy-aws-cloudformation-traits/src/test/java/software/amazon/smithy/aws/cloudformation/traits/CfnResourceTraitTest.java @@ -19,10 +19,10 @@ public class CfnResourceTraitTest { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("cfn-resources.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("cfn-resources.smithy")) + .assemble() + .unwrap(); Shape fooResource = result.expectShape(ShapeId.from("smithy.example#FooResource")); assertTrue(fooResource.hasTrait(CfnResourceTrait.class)); @@ -41,30 +41,30 @@ public void loadsFromModel() { @Test public void handlesNameProperty() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("test-service.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("test-service.smithy")) + .assemble() + .unwrap(); assertFalse( - result.expectShape(ShapeId.from("smithy.example#FooResource")) - .expectTrait(CfnResourceTrait.class) - .getName() - .isPresent() + result.expectShape(ShapeId.from("smithy.example#FooResource")) + .expectTrait(CfnResourceTrait.class) + .getName() + .isPresent() ); assertThat( - result.expectShape(ShapeId.from("smithy.example#BarResource")) - .expectTrait(CfnResourceTrait.class) - .getName() - .get(), - equalTo("Bar") + result.expectShape(ShapeId.from("smithy.example#BarResource")) + .expectTrait(CfnResourceTrait.class) + .getName() + .get(), + equalTo("Bar") ); assertThat( - result.expectShape(ShapeId.from("smithy.example#BazResource")) - .expectTrait(CfnResourceTrait.class) - .getName() - .get(), - equalTo("Basil") + result.expectShape(ShapeId.from("smithy.example#BazResource")) + .expectTrait(CfnResourceTrait.class) + .getName() + .get(), + equalTo("Basil") ); } } diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/CfnConfig.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/CfnConfig.java index 72e74370407..d43c7b0cc82 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/CfnConfig.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/CfnConfig.java @@ -31,22 +31,22 @@ public final class CfnConfig extends JsonSchemaConfig { private boolean disableRequiredPropertyGeneration = false; private boolean disableCapitalizedProperties = false; private List externalDocs = ListUtils.of( - "Documentation Url", - "DocumentationUrl", - "API Reference", - "User Guide", - "Developer Guide", - "Reference", - "Guide" + "Documentation Url", + "DocumentationUrl", + "API Reference", + "User Guide", + "Developer Guide", + "Reference", + "Guide" ); private Map> jsonAdd = Collections.emptyMap(); private String organizationName; private String serviceName; private List sourceDocs = ListUtils.of( - "Source Url", - "SourceUrl", - "Source", - "Source Code" + "Source Url", + "SourceUrl", + "Source", + "Source Code" ); public CfnConfig() { @@ -90,8 +90,8 @@ public void setAlphanumericOnlyRefs(boolean alphanumericOnlyRefs) { // https://github.com/aws-cloudformation/cloudformation-cli/blob/master/src/rpdk/core/data/schema/provider.definition.schema.v1.json#L303 if (!alphanumericOnlyRefs) { throw new CfnException( - "CloudFormation Resource Schemas MUST use alphanumeric only " - + "references. `alphanumericOnlyRefs` value of `false` was provided." + "CloudFormation Resource Schemas MUST use alphanumeric only " + + "references. `alphanumericOnlyRefs` value of `false` was provided." ); } } @@ -218,11 +218,11 @@ public void setUseJsonName(boolean useJsonName) { // // See CfnConverter::getPropertyNamingStrategy throw new CfnException( - String.format( - "CloudFormation Resource Schemas use the `@cfnName` trait for " - + "naming JSON Schema properties for structures and unions. `useJsonName` value of `%b` was provided.", - useJsonName - ) + String.format( + "CloudFormation Resource Schemas use the `@cfnName` trait for " + + "naming JSON Schema properties for structures and unions. `useJsonName` value of `%b` was provided.", + useJsonName + ) ); } @@ -235,11 +235,11 @@ public void setMapStrategy(MapStrategy mapStrategy) { // https://github.com/aws-cloudformation/cloudformation-cli/blob/master/src/rpdk/core/data/schema/provider.definition.schema.v1.json#L166-L177 if (mapStrategy != MapStrategy.PATTERN_PROPERTIES) { throw new CfnException( - String.format( - "CloudFormation Resource Schemas require the use of " - + "`patternProperties` for defining maps in JSON Schema. `mapStrategy` value of `%s` was provided.", - mapStrategy - ) + String.format( + "CloudFormation Resource Schemas require the use of " + + "`patternProperties` for defining maps in JSON Schema. `mapStrategy` value of `%s` was provided.", + mapStrategy + ) ); } } @@ -312,11 +312,11 @@ public void setUnionStrategy(UnionStrategy unionStrategy) { // https://github.com/aws-cloudformation/cloudformation-cli/blob/master/src/rpdk/core/data/schema/provider.definition.schema.v1.json#L166 if (unionStrategy != UnionStrategy.ONE_OF) { throw new CfnException( - String.format( - "CloudFormation Resource Schemas require the use of `oneOf` " - + "for defining unions in JSON Schema. `unionStrategy` value of `%s` was provided.", - unionStrategy - ) + String.format( + "CloudFormation Resource Schemas require the use of `oneOf` " + + "for defining unions in JSON Schema. `unionStrategy` value of `%s` was provided.", + unionStrategy + ) ); } } @@ -349,8 +349,8 @@ public static CfnConfig fromNode(Node settings) { for (Map.Entry jsonAddMember : jsonAddNode.getMembers().entrySet()) { jsonAddMap.put( - ShapeId.from(jsonAddMember.getKey().getValue()), - jsonAddMember.getValue().expectObjectNode().getStringMap() + ShapeId.from(jsonAddMember.getKey().getValue()), + jsonAddMember.getValue().expectObjectNode().getStringMap() ); } @@ -372,11 +372,11 @@ public void setJsonSchemaVersion(JsonSchemaVersion schemaVersion) { // https://github.com/aws-cloudformation/cloudformation-cli/blob/master/src/rpdk/core/data/schema/provider.definition.schema.v1.json#L210 if (!schemaVersion.equals(JsonSchemaVersion.DRAFT07)) { throw new CfnException( - String.format( - "CloudFormation Resource Schemas require the use of JSON Schema" - + " version draft07. `jsonSchemaVersion` value of `%s` was provided.", - schemaVersion - ) + String.format( + "CloudFormation Resource Schemas require the use of JSON Schema" + + " version draft07. `jsonSchemaVersion` value of `%s` was provided.", + schemaVersion + ) ); } } diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnConverter.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnConverter.java index 224f654c51b..17daab865d4 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnConverter.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnConverter.java @@ -176,14 +176,14 @@ private List createConversionEnvironments(Model model) { } private ConversionEnvironment createConversionEnvironment( - Model model, - ServiceShape serviceShape, - ResourceShape resourceShape + Model model, + ServiceShape serviceShape, + ResourceShape resourceShape ) { // Prepare the JSON Schema Converter. JsonSchemaConverter.Builder jsonSchemaConverterBuilder = JsonSchemaConverter.builder() - .config(config) - .propertyNamingStrategy(getPropertyNamingStrategy()); + .config(config) + .propertyNamingStrategy(getPropertyNamingStrategy()); List mappers = new ArrayList<>(); for (Smithy2CfnExtension extension : extensions) { @@ -197,12 +197,12 @@ private ConversionEnvironment createConversionEnvironment( CfnResourceIndex resourceIndex = CfnResourceIndex.of(model); CfnResource cfnResource = resourceIndex.getResource(resourceShape) - .orElseThrow( - () -> new CfnException( - "Attempted to generate a CloudFormation resource schema " - + "not found to have resource data." - ) - ); + .orElseThrow( + () -> new CfnException( + "Attempted to generate a CloudFormation resource schema " + + "not found to have resource data." + ) + ); // Prepare a structure representing the CFN resource to be created and // add that structure to a temporary model that's used for conversion. @@ -214,13 +214,13 @@ private ConversionEnvironment createConversionEnvironment( jsonSchemaConverterBuilder.model(updatedModel); Context context = new Context( - updatedModel, - serviceShape, - resourceShape, - cfnResource, - pseudoResource, - config, - jsonSchemaConverterBuilder.build() + updatedModel, + serviceShape, + resourceShape, + cfnResource, + pseudoResource, + config, + jsonSchemaConverterBuilder.build() ); return new ConversionEnvironment(context, mappers); @@ -237,17 +237,17 @@ private PropertyNamingStrategy getPropertyNamingStrategy() { Optional propertyTrait = member.getTrait(PropertyTrait.class); if (propertyTrait.isPresent() && propertyTrait.flatMap(PropertyTrait::getName).isPresent()) { return this.config.getDisableCapitalizedProperties() - ? StringUtils.capitalize(propertyTrait.get().getName().get()) - : propertyTrait.get().getName().get(); + ? StringUtils.capitalize(propertyTrait.get().getName().get()) + : propertyTrait.get().getName().get(); } // Otherwise, respect the property capitalization setting. String name = PropertyNamingStrategy.createMemberNameStrategy() - .toPropertyName(containingShape, member, config); + .toPropertyName(containingShape, member, config); return this.config.getDisableCapitalizedProperties() - ? name - : StringUtils.capitalize(name); + ? name + : StringUtils.capitalize(name); }; } @@ -256,8 +256,8 @@ private static final class ConversionEnvironment { private final List mappers; private ConversionEnvironment( - Context context, - List mappers + Context context, + List mappers ) { this.context = context; this.mappers = mappers; @@ -267,9 +267,9 @@ private ConversionEnvironment( private ResourceSchema convertResource(ConversionEnvironment environment, ResourceShape resourceShape) { Context context = environment.context; JsonSchemaConverter jsonSchemaConverter = context.getJsonSchemaConverter() - .toBuilder() - .rootShape(context.getResourceStructure()) - .build(); + .toBuilder() + .rootShape(context.getResourceStructure()) + .build(); SchemaDocument document = jsonSchemaConverter.convert(); // Prepare the initial contents @@ -280,9 +280,9 @@ private ResourceSchema convertResource(ConversionEnvironment environment, Resour // Apply the resource's documentation if present, or default. builder.description( - resourceShape.getTrait(DocumentationTrait.class) - .map(StringTrait::getValue) - .orElse("Definition of " + typeName + " Resource Type") + resourceShape.getTrait(DocumentationTrait.class) + .map(StringTrait::getValue) + .orElse("Definition of " + typeName + " Resource Type") ); // Apply all the mappers' before methods. @@ -293,16 +293,16 @@ private ResourceSchema convertResource(ConversionEnvironment environment, Resour // Add the properties from the converted shape. document.getRootSchema().getProperties().forEach((name, schema) -> { Property property = Property.builder() - .schema(schema) - .build(); + .schema(schema) + .build(); builder.addProperty(name, property); }); // Supply all the definitions that were created. for (Map.Entry definition : document.getDefinitions().entrySet()) { String definitionName = definition.getKey() - .replace(CfnConfig.SCHEMA_COMPONENTS_POINTER, "") - .substring(1); + .replace(CfnConfig.SCHEMA_COMPONENTS_POINTER, "") + .substring(1); builder.addDefinition(definitionName, definition.getValue()); } @@ -316,8 +316,8 @@ private ResourceSchema convertResource(ConversionEnvironment environment, Resour } private String resolveResourceTypeName( - ConversionEnvironment environment, - CfnResourceTrait resourceTrait + ConversionEnvironment environment, + CfnResourceTrait resourceTrait ) { CfnConfig config = environment.context.getConfig(); ServiceShape serviceShape = environment.context.getModel().expectShape(config.getService(), ServiceShape.class); @@ -328,10 +328,10 @@ private String resolveResourceTypeName( // Services utilizing the AWS service trait default to being in the // "AWS" organization instead of requiring the configuration value. organizationName = serviceTrait - .map(t -> "AWS") - .orElseThrow( - () -> new CfnException("cloudformation is missing required property, `organizationName`") - ); + .map(t -> "AWS") + .orElseThrow( + () -> new CfnException("cloudformation is missing required property, `organizationName`") + ); } String serviceName = config.getServiceName(); @@ -340,13 +340,13 @@ private String resolveResourceTypeName( // member, so use that if present. Otherwise, default to the service // shape's name. serviceName = serviceTrait - .map(ServiceTrait::getCloudFormationName) - .orElse(serviceShape.getId().getName()); + .map(ServiceTrait::getCloudFormationName) + .orElse(serviceShape.getId().getName()); } // Use the trait's name if present, or default to the resource shape's name. String resourceName = resourceTrait.getName() - .orElse(environment.context.getResource().getId().getName()); + .orElse(environment.context.getResource().getId().getName()); return String.format("%s::%s::%s", organizationName, serviceName, resourceName); } diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/Context.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/Context.java index f0bfabdc957..d3d2c720293 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/Context.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/Context.java @@ -29,13 +29,13 @@ public final class Context { private final CfnConfig config; Context( - Model model, - ServiceShape service, - ResourceShape resource, - CfnResource cfnResource, - StructureShape resourceStructure, - CfnConfig config, - JsonSchemaConverter jsonSchemaConverter + Model model, + ServiceShape service, + ResourceShape resource, + CfnResource cfnResource, + StructureShape resourceStructure, + CfnConfig config, + JsonSchemaConverter jsonSchemaConverter ) { this.model = model; this.service = service; diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/Smithy2Cfn.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/Smithy2Cfn.java index 306a2ba467c..130b6163575 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/Smithy2Cfn.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/Smithy2Cfn.java @@ -28,10 +28,10 @@ public void execute(PluginContext context) { for (Map.Entry resourceNode : resourceNodes.entrySet()) { String filename = getFileNameFromResourceType(resourceNode.getKey()); context.getFileManifest() - .writeJson( - filename, - resourceNode.getValue() - ); + .writeJson( + filename, + resourceNode.getValue() + ); } } diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/CoreExtension.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/CoreExtension.java index 44337a00499..04533cd7ecb 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/CoreExtension.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/CoreExtension.java @@ -16,15 +16,15 @@ public final class CoreExtension implements Smithy2CfnExtension { @Override public List getCfnMappers() { return ListUtils.of( - new AdditionalPropertiesMapper(), - new DeprecatedMapper(), - new DocumentationMapper(), - new HandlerPermissionMapper(), - new IdentifierMapper(), - new JsonAddMapper(), - new MutabilityMapper(), - new RequiredMapper(), - new TaggingMapper() + new AdditionalPropertiesMapper(), + new DeprecatedMapper(), + new DocumentationMapper(), + new HandlerPermissionMapper(), + new IdentifierMapper(), + new JsonAddMapper(), + new MutabilityMapper(), + new RequiredMapper(), + new TaggingMapper() ); } } diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/DocumentationMapper.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/DocumentationMapper.java index bbfcab9f8d3..61ce267b45f 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/DocumentationMapper.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/DocumentationMapper.java @@ -53,8 +53,8 @@ private Optional getResolvedExternalDocs(ExternalDocumentationTrait trai // Get lower case keys to check for when converting. Map traitUrls = trait.getUrls(); Map lowercaseKeyMap = traitUrls.keySet() - .stream() - .collect(MapUtils.toUnmodifiableMap(this::toLowerCase, identity())); + .stream() + .collect(MapUtils.toUnmodifiableMap(this::toLowerCase, identity())); for (String externalDocKey : externalDocKeys) { // Compare the lower case name, but use the specified name. diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/HandlerPermissionMapper.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/HandlerPermissionMapper.java index 0cfe5c8a9ab..24e2d0ac859 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/HandlerPermissionMapper.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/HandlerPermissionMapper.java @@ -43,17 +43,17 @@ public void before(Context context, ResourceSchema.Builder resourceSchema) { // Start the create and update handler permission gathering. // TODO Break this out to its own knowledge index if it becomes useful in more contexts. Set createPermissions = resource.getCreate() - .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) - .orElseGet(TreeSet::new); + .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) + .orElseGet(TreeSet::new); Set updatePermissions = resource.getUpdate() - .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) - .orElseGet(TreeSet::new); + .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) + .orElseGet(TreeSet::new); // Add the permissions from the resource's put lifecycle operation // to the relevant handlers. Set putPermissions = resource.getPut() - .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) - .orElse(SetUtils.of()); + .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) + .orElse(SetUtils.of()); createPermissions.addAll(putPermissions); // Put operations without the noReplace trait are used for updates. if (!resource.hasTrait(NoReplaceTrait.class)) { @@ -71,37 +71,37 @@ public void before(Context context, ResourceSchema.Builder resourceSchema) { // Add the handler permission sets that don't need operation // permissions to be combined. resource.getRead() - .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) - .ifPresent( - permissions -> resourceSchema.addHandler( - "read", - Handler.builder() - .permissions(permissions) - .build() - ) - ); + .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) + .ifPresent( + permissions -> resourceSchema.addHandler( + "read", + Handler.builder() + .permissions(permissions) + .build() + ) + ); resource.getDelete() - .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) - .ifPresent( - permissions -> resourceSchema.addHandler( - "delete", - Handler.builder() - .permissions(permissions) - .build() - ) - ); + .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) + .ifPresent( + permissions -> resourceSchema.addHandler( + "delete", + Handler.builder() + .permissions(permissions) + .build() + ) + ); resource.getList() - .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) - .ifPresent( - permissions -> resourceSchema.addHandler( - "list", - Handler.builder() - .permissions(permissions) - .build() - ) - ); + .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) + .ifPresent( + permissions -> resourceSchema.addHandler( + "list", + Handler.builder() + .permissions(permissions) + .build() + ) + ); } static Set getPermissionsEntriesForOperation(Model model, ServiceShape service, ShapeId operationId) { @@ -110,9 +110,9 @@ static Set getPermissionsEntriesForOperation(Model model, ServiceShape s // Add the operation's permission name itself. String operationActionName = service.getTrait(ServiceTrait.class) - .map(ServiceTrait::getArnNamespace) - .orElse(service.getId().getName()) - .toLowerCase(Locale.US); + .map(ServiceTrait::getArnNamespace) + .orElse(service.getId().getName()) + .toLowerCase(Locale.US); operationActionName += ":" + operationId.getName(service); permissionsEntries.add(operationActionName); diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/IdentifierMapper.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/IdentifierMapper.java index 16100a2988a..e4486d4521b 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/IdentifierMapper.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/IdentifierMapper.java @@ -31,9 +31,9 @@ public void before(Context context, Builder builder) { // Add the primary identifier. Set primaryIdentifier = cfnResource.getPrimaryIdentifiers(); builder.primaryIdentifier( - primaryIdentifier.stream() - .map(context::getPropertyPointer) - .collect(Collectors.toList()) + primaryIdentifier.stream() + .map(context::getPropertyPointer) + .collect(Collectors.toList()) ); // Add any additional identifiers. diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/JsonAddMapper.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/JsonAddMapper.java index 329cd2a482e..f3ac43809d3 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/JsonAddMapper.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/JsonAddMapper.java @@ -48,15 +48,15 @@ public ObjectNode updateNode(Context context, ResourceSchema resourceSchema, Obj for (Map.Entry entry : add.get(resourceShapeId).entrySet()) { try { LOGGER.info( - () -> String.format( - "CloudFormation `jsonAdd` for `%s`: adding `%s`", - resourceShapeId, - entry.getKey() - ) + () -> String.format( + "CloudFormation `jsonAdd` for `%s`: adding `%s`", + resourceShapeId, + entry.getKey() + ) ); result = NodePointer.parse(entry.getKey()) - .addWithIntermediateValues(result, entry.getValue().toNode()) - .expectObjectNode(); + .addWithIntermediateValues(result, entry.getValue().toNode()) + .expectObjectNode(); } catch (IllegalArgumentException e) { throw new CfnException(e.getMessage(), e); } diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/MutabilityMapper.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/MutabilityMapper.java index 5a734641ed8..3e61327aa7a 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/MutabilityMapper.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/MutabilityMapper.java @@ -27,20 +27,20 @@ public void before(Context context, ResourceSchema.Builder builder) { // Add any createOnlyProperty entries, if present. cfnResource.getCreateOnlyProperties() - .stream() - .map(context::getPropertyPointer) - .forEach(builder::addCreateOnlyProperty); + .stream() + .map(context::getPropertyPointer) + .forEach(builder::addCreateOnlyProperty); // Add any readOnlyProperty entries, if present. cfnResource.getReadOnlyProperties() - .stream() - .map(context::getPropertyPointer) - .forEach(builder::addReadOnlyProperty); + .stream() + .map(context::getPropertyPointer) + .forEach(builder::addReadOnlyProperty); // Add any writeOnlyProperty entries, if present. cfnResource.getWriteOnlyProperties() - .stream() - .map(context::getPropertyPointer) - .forEach(builder::addWriteOnlyProperty); + .stream() + .map(context::getPropertyPointer) + .forEach(builder::addWriteOnlyProperty); } } diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/RequiredMapper.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/RequiredMapper.java index 92a6d2802c5..f5d67ee5b2a 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/RequiredMapper.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/RequiredMapper.java @@ -50,10 +50,10 @@ private boolean hasWriteOrCreateMutability(Context context, MemberShape member) String memberId = member.getId().toShapeId().getMember().get(); Optional cfnResourceProperty = cfnResource.getProperty(memberId); return cfnResourceProperty.map(CfnResourceProperty::getMutabilities) - .map( - mutabilities -> mutabilities.contains(CfnResourceIndex.Mutability.WRITE) - || mutabilities.contains(CfnResourceIndex.Mutability.CREATE) - ) - .orElse(false); + .map( + mutabilities -> mutabilities.contains(CfnResourceIndex.Mutability.WRITE) + || mutabilities.contains(CfnResourceIndex.Mutability.CREATE) + ) + .orElse(false); } } diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/TaggingMapper.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/TaggingMapper.java index 146db313e01..30084d4e3f2 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/TaggingMapper.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/TaggingMapper.java @@ -37,10 +37,10 @@ public final class TaggingMapper implements CfnMapper { @SmithyInternalApi public static void injectTagsMember( - CfnConfig config, - Model model, - ResourceShape resource, - StructureShape.Builder builder + CfnConfig config, + Model model, + ResourceShape resource, + StructureShape.Builder builder ) { String tagMemberName = getTagMemberName(config, resource); if (resource.hasTrait(TaggableTrait.class)) { @@ -50,7 +50,7 @@ public static void injectTagsMember( CfnResource cfnResource = resourceIndex.getResource(resource).get(); if (!trait.getProperty().isPresent() || !cfnResource.getProperties() - .containsKey(trait.getProperty().get())) { + .containsKey(trait.getProperty().get())) { if (trait.getProperty().isPresent()) { ShapeId definition = resource.getProperties().get(trait.getProperty().get()); builder.addMember(tagMemberName, definition); @@ -77,36 +77,36 @@ public ResourceSchema after(Context context, ResourceSchema resourceSchema) { AwsTagIndex tagsIndex = AwsTagIndex.of(model); TaggableTrait trait = resourceShape.expectTrait(TaggableTrait.class); Tagging.Builder tagBuilder = Tagging.builder() - .taggable(true) - .tagOnCreate(tagsIndex.isResourceTagOnCreate(resourceShape.getId())) - .tagProperty("/properties/" + getTagMemberName(context.getConfig(), resourceShape)) - .cloudFormationSystemTags(!trait.getDisableSystemTags()) - // Unless tag-on-create is supported, Smithy tagging means - .tagUpdatable(true); + .taggable(true) + .tagOnCreate(tagsIndex.isResourceTagOnCreate(resourceShape.getId())) + .tagProperty("/properties/" + getTagMemberName(context.getConfig(), resourceShape)) + .cloudFormationSystemTags(!trait.getDisableSystemTags()) + // Unless tag-on-create is supported, Smithy tagging means + .tagUpdatable(true); // Add the tagging permissions based on the defined tagging operations. tagsIndex.getTagResourceOperation(resourceShape) - .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) - .ifPresent(tagBuilder::addPermissions); + .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) + .ifPresent(tagBuilder::addPermissions); tagsIndex.getListTagsForResourceOperation(resourceShape) - .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) - .ifPresent(tagBuilder::addPermissions); + .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) + .ifPresent(tagBuilder::addPermissions); tagsIndex.getUntagResourceOperation(resourceShape) - .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) - .ifPresent(tagBuilder::addPermissions); + .map(operation -> getPermissionsEntriesForOperation(model, service, operation)) + .ifPresent(tagBuilder::addPermissions); return resourceSchema.toBuilder().tagging(tagBuilder.build()).build(); } private static String getTagMemberName(CfnConfig config, ResourceShape resource) { return resource.getTrait(TaggableTrait.class) - .flatMap(TaggableTrait::getProperty) - .map(property -> { - if (config.getDisableCapitalizedProperties()) { - return property; - } - return StringUtils.capitalize(property); - }) - .orElse(DEFAULT_TAGS_NAME); + .flatMap(TaggableTrait::getProperty) + .map(property -> { + if (config.getDisableCapitalizedProperties()) { + return property; + } + return StringUtils.capitalize(property); + }) + .orElse(DEFAULT_TAGS_NAME); } } diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Handler.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Handler.java index 9a8fbd62897..bba3209f104 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Handler.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Handler.java @@ -29,16 +29,16 @@ public final class Handler implements ToNode, ToSmithyBuilder { public static final String DELETE = "delete"; public static final String LIST = "list"; private static final Map HANDLER_NAME_ORDERS = MapUtils.of( - CREATE, - 0, - READ, - 1, - UPDATE, - 2, - DELETE, - 3, - LIST, - 4 + CREATE, + 0, + READ, + 1, + UPDATE, + 2, + DELETE, + 3, + LIST, + 4 ); private final Set permissions; @@ -58,7 +58,7 @@ public Node toNode() { @Override public Builder toBuilder() { return builder() - .permissions(permissions); + .permissions(permissions); } public static Builder builder() { diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Property.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Property.java index c28d965ad5e..72ae541c31d 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Property.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Property.java @@ -77,14 +77,14 @@ public static Builder builder() { public boolean isInsertionOrder() { Optional insertionOrder = schema.getExtension("insertionOrder") - .map(n -> n.toNode().expectBooleanNode().getValue()); + .map(n -> n.toNode().expectBooleanNode().getValue()); return insertionOrder.orElse(false); } public List getDependencies() { Optional> dependencies = schema.getExtension("dependencies") - .map(n -> n.toNode().expectArrayNode().getElementsAs(StringNode::getValue)); + .map(n -> n.toNode().expectArrayNode().getElementsAs(StringNode::getValue)); return dependencies.orElse(Collections.emptyList()); } diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Remote.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Remote.java index 914be8ee3a8..c5b53b5e9ef 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Remote.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Remote.java @@ -48,8 +48,8 @@ public Node toNode() { @Override public Builder toBuilder() { return builder() - .definitions(definitions) - .properties(properties); + .definitions(definitions) + .properties(properties); } public static Builder builder() { diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/ResourceSchema.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/ResourceSchema.java index 5f1aaaf6fca..23b3c26df2b 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/ResourceSchema.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/ResourceSchema.java @@ -57,11 +57,11 @@ private ResourceSchema(Builder builder) { if (builder.properties.isEmpty()) { throw new CfnException( - format( - "Expected CloudFormation resource %s to have properties, " - + "found none", - typeName - ) + format( + "Expected CloudFormation resource %s to have properties, " + + "found none", + typeName + ) ); } properties.putAll(builder.properties); @@ -142,22 +142,22 @@ public Node toNode() { @Override public Builder toBuilder() { return builder() - .typeName(typeName) - .description(description) - .sourceUrl(sourceUrl) - .documentationUrl(documentationUrl) - .definitions(definitions) - .properties(properties) - .required(required) - .readOnlyProperties(readOnlyProperties) - .writeOnlyProperties(writeOnlyProperties) - .primaryIdentifier(primaryIdentifier) - .createOnlyProperties(createOnlyProperties) - .deprecatedProperties(deprecatedProperties) - .additionalIdentifiers(additionalIdentifiers) - .handlers(handlers) - .remotes(remotes) - .tagging(tagging); + .typeName(typeName) + .description(description) + .sourceUrl(sourceUrl) + .documentationUrl(documentationUrl) + .definitions(definitions) + .properties(properties) + .required(required) + .readOnlyProperties(readOnlyProperties) + .writeOnlyProperties(writeOnlyProperties) + .primaryIdentifier(primaryIdentifier) + .createOnlyProperties(createOnlyProperties) + .deprecatedProperties(deprecatedProperties) + .additionalIdentifiers(additionalIdentifiers) + .handlers(handlers) + .remotes(remotes) + .tagging(tagging); } public static ResourceSchema fromNode(Node node) { diff --git a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Tagging.java b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Tagging.java index e1d13fb2057..195ac77d540 100644 --- a/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Tagging.java +++ b/smithy-aws-cloudformation/src/main/java/software/amazon/smithy/aws/cloudformation/schema/model/Tagging.java @@ -92,12 +92,12 @@ public Set getPermissions() { @Override public Builder toBuilder() { return builder() - .taggable(taggable) - .tagOnCreate(tagOnCreate) - .tagUpdatable(tagUpdatable) - .cloudFormationSystemTags(cloudFormationSystemTags) - .tagProperty(tagProperty) - .permissions(permissions); + .taggable(taggable) + .tagOnCreate(tagOnCreate) + .tagUpdatable(tagUpdatable) + .cloudFormationSystemTags(cloudFormationSystemTags) + .tagProperty(tagProperty) + .permissions(permissions); } public static final class Builder implements SmithyBuilder { diff --git a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnConfigTest.java b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnConfigTest.java index 6ad23086093..29ed428a63e 100644 --- a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnConfigTest.java +++ b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnConfigTest.java @@ -55,32 +55,32 @@ public void throwsOnDifferentUnionStrategy() { @Test public void handlesFromNode() { Model model = Model.assembler() - .addImport(CfnConfigTest.class.getResource("mappers/simple.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(CfnConfigTest.class.getResource("mappers/simple.smithy")) + .discoverModels() + .assemble() + .unwrap(); ObjectNode addNode = Node.objectNodeBuilder() - .withMember("/arbitrary/foo", "whoa") - .build(); + .withMember("/arbitrary/foo", "whoa") + .build(); ObjectNode configNode = Node.objectNodeBuilder() - .withMember("organizationName", "Smithy") - .withMember("service", "smithy.example#TestService") - .withMember( - "jsonAdd", - Node.objectNodeBuilder() - .withMember("smithy.example#FooResource", addNode) - .build() - ) - .build(); + .withMember("organizationName", "Smithy") + .withMember("service", "smithy.example#TestService") + .withMember( + "jsonAdd", + Node.objectNodeBuilder() + .withMember("smithy.example#FooResource", addNode) + .build() + ) + .build(); CfnConfig config = CfnConfig.fromNode(configNode); ObjectNode resourceNode = CfnConverter.create() - .config(config) - .convertToNodes(model) - .get("Smithy::TestService::FooResource"); + .config(config) + .convertToNodes(model) + .get("Smithy::TestService::FooResource"); String arbitraryFoo = NodePointer.parse("/arbitrary/foo").getValue(resourceNode).expectStringNode().getValue(); diff --git a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnConverterTest.java b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnConverterTest.java index 52c4e1bee9f..71aac2b16a3 100644 --- a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnConverterTest.java +++ b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnConverterTest.java @@ -26,10 +26,10 @@ public class CfnConverterTest { @BeforeAll private static void setup() { testService = Model.assembler() - .addImport(CfnConverterTest.class.getResource("test-service.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(CfnConverterTest.class.getResource("test-service.smithy")) + .discoverModels() + .assemble() + .unwrap(); } @Test @@ -38,28 +38,28 @@ public void convertsResourcesToCloudFormation() { config.setOrganizationName("Smithy"); config.setService(ShapeId.from("smithy.example#TestService")); Map result = CfnConverter.create() - .config(config) - .convertToNodes(testService); + .config(config) + .convertToNodes(testService); assertEquals(result.keySet().size(), 3); assertThat( - result.keySet(), - containsInAnyOrder( - ListUtils.of( - "Smithy::TestService::Bar", - "Smithy::TestService::Basil", - "Smithy::TestService::FooResource" - ).toArray() - ) + result.keySet(), + containsInAnyOrder( + ListUtils.of( + "Smithy::TestService::Bar", + "Smithy::TestService::Basil", + "Smithy::TestService::FooResource" + ).toArray() + ) ); for (String resourceTypeName : result.keySet()) { String filename = Smithy2Cfn.getFileNameFromResourceType(resourceTypeName); // Handle our convention of using ".cfn.json" for schema validation. filename = filename.replace(".json", ".cfn.json"); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream(filename) - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream(filename) + ) ); ObjectNode generatedResource = result.get(resourceTypeName); @@ -74,23 +74,23 @@ public void convertsResourcesToCloudFormation() { @Test public void handlesAwsServiceTraitDefaulting() { Model model = Model.assembler() - .addImport(CfnConverterTest.class.getResource("simple-service-aws.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(CfnConverterTest.class.getResource("simple-service-aws.smithy")) + .discoverModels() + .assemble() + .unwrap(); CfnConfig config = new CfnConfig(); config.setService(ShapeId.from("smithy.example#TestService")); Map result = CfnConverter.create() - .config(config) - .convertToNodes(model); + .config(config) + .convertToNodes(model); assertEquals(result.keySet().size(), 1); assertThat(result.keySet(), containsInAnyOrder(ListUtils.of("AWS::SomeThing::FooResource").toArray())); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("simple-service-aws.cfn.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("simple-service-aws.cfn.json") + ) ); Node.assertEquals(result.get("AWS::SomeThing::FooResource"), expectedNode); @@ -103,19 +103,19 @@ public void usesConfiguredServiceName() { config.setService(ShapeId.from("smithy.example#TestService")); config.setServiceName("ExampleService"); Map result = CfnConverter.create() - .config(config) - .convertToNodes(testService); + .config(config) + .convertToNodes(testService); assertEquals(result.keySet().size(), 3); assertThat( - result.keySet(), - containsInAnyOrder( - ListUtils.of( - "Smithy::ExampleService::Bar", - "Smithy::ExampleService::Basil", - "Smithy::ExampleService::FooResource" - ).toArray() - ) + result.keySet(), + containsInAnyOrder( + ListUtils.of( + "Smithy::ExampleService::Bar", + "Smithy::ExampleService::Basil", + "Smithy::ExampleService::FooResource" + ).toArray() + ) ); } @@ -126,24 +126,24 @@ public void handlesDisabledPropertyCaps() { config.setService(ShapeId.from("smithy.example#TestService")); config.setDisableCapitalizedProperties(true); Map result = CfnConverter.create() - .config(config) - .convertToNodes(testService); + .config(config) + .convertToNodes(testService); assertEquals(result.keySet().size(), 3); assertThat( - result.keySet(), - containsInAnyOrder( - ListUtils.of( - "Smithy::TestService::Bar", - "Smithy::TestService::Basil", - "Smithy::TestService::FooResource" - ).toArray() - ) + result.keySet(), + containsInAnyOrder( + ListUtils.of( + "Smithy::TestService::Bar", + "Smithy::TestService::Basil", + "Smithy::TestService::FooResource" + ).toArray() + ) ); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("disable-caps-fooresource.cfn.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("disable-caps-fooresource.cfn.json") + ) ); Node.assertEquals(result.get("Smithy::TestService::FooResource"), expectedNode); @@ -152,25 +152,25 @@ public void handlesDisabledPropertyCaps() { @Test public void resourcePropertiesWithTagsTest() { Model model = Model.assembler() - .addImport(CfnConverterTest.class.getResource("weather.smithy")) - .addImport(CfnConverterTest.class.getResource("tagging.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(CfnConverterTest.class.getResource("weather.smithy")) + .addImport(CfnConverterTest.class.getResource("tagging.smithy")) + .discoverModels() + .assemble() + .unwrap(); CfnConfig config = new CfnConfig(); config.setOrganizationName("Smithy"); config.setService(ShapeId.from("example.weather#Weather")); config.setServiceName("Weather"); Map result = CfnConverter.create() - .config(config) - .convertToNodes(model); + .config(config) + .convertToNodes(model); assertEquals(1, result.keySet().size()); result.keySet().contains("Smithy::Weather::City"); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("weather.cfn.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("weather.cfn.json") + ) ); Node.assertEquals(result.get("Smithy::Weather::City"), expectedNode); @@ -179,25 +179,25 @@ public void resourcePropertiesWithTagsTest() { @Test public void resourcePropertiesWithTagsServiceWideTest() { Model model = Model.assembler() - .addImport(CfnConverterTest.class.getResource("weather-service-wide.smithy")) - .addImport(CfnConverterTest.class.getResource("tagging.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(CfnConverterTest.class.getResource("weather-service-wide.smithy")) + .addImport(CfnConverterTest.class.getResource("tagging.smithy")) + .discoverModels() + .assemble() + .unwrap(); CfnConfig config = new CfnConfig(); config.setOrganizationName("Smithy"); config.setService(ShapeId.from("example.weather#Weather")); config.setServiceName("Weather"); Map result = CfnConverter.create() - .config(config) - .convertToNodes(model); + .config(config) + .convertToNodes(model); assertEquals(1, result.keySet().size()); result.keySet().contains("Smithy::Weather::City"); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("weather-service-wide.cfn.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("weather-service-wide.cfn.json") + ) ); Node.assertEquals(result.get("Smithy::Weather::City"), expectedNode); diff --git a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnSchemasTest.java b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnSchemasTest.java index 8acb0ed16d0..c837ab95e0a 100644 --- a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnSchemasTest.java +++ b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/CfnSchemasTest.java @@ -40,13 +40,13 @@ public class CfnSchemasTest { @BeforeAll public static void loadSchema() { try ( - InputStream schemaStream = CfnSchemasTest.class.getResourceAsStream( - DEFINITION - ); InputStream draftSchemaStream = CfnSchemasTest.class.getResourceAsStream( - JSON_SCHEMA - ); InputStream configSchemaStream = CfnSchemasTest.class.getResourceAsStream( - CONFIGURATION - ); InputStream baseSchemaStream = CfnSchemasTest.class.getResourceAsStream(BASE_DEFINITION) + InputStream schemaStream = CfnSchemasTest.class.getResourceAsStream( + DEFINITION + ); InputStream draftSchemaStream = CfnSchemasTest.class.getResourceAsStream( + JSON_SCHEMA + ); InputStream configSchemaStream = CfnSchemasTest.class.getResourceAsStream( + CONFIGURATION + ); InputStream baseSchemaStream = CfnSchemasTest.class.getResourceAsStream(BASE_DEFINITION) ) { JSONObject schemaJson = new JSONObject(new JSONTokener(schemaStream)); @@ -55,8 +55,8 @@ public static void loadSchema() { JSONObject draftSchemaJson = new JSONObject(new JSONTokener(draftSchemaStream)); SchemaLoaderBuilder schemaLoaderBuilder = SchemaLoader.builder() - .draftV7Support() - .schemaJson(schemaJson); + .draftV7Support() + .schemaJson(schemaJson); schemaLoaderBuilder.registerSchemaByURI(new URI(BASE_DEFINITION_URI), baseSchemaJson); schemaLoaderBuilder.registerSchemaByURI(new URI(CONFIGURATION_URI), configSchemaJson); schemaLoaderBuilder.registerSchemaByURI(new URI(JSON_SCHEMA_URI_HTTP), draftSchemaJson); @@ -88,10 +88,10 @@ public static List resourceSchemaFiles() { // Check for any ".cfn.json" files at or deeper than the // validation schema definition. return Files.walk(Paths.get(definitionPath.getParent().toUri())) - .filter(Files::isRegularFile) - .filter(file -> file.toString().endsWith(".cfn.json")) - .map(Object::toString) - .collect(Collectors.toList()); + .filter(Files::isRegularFile) + .filter(file -> file.toString().endsWith(".cfn.json")) + .map(Object::toString) + .collect(Collectors.toList()); } catch (IOException | URISyntaxException e) { throw new RuntimeException(e); } diff --git a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/ResourceSchemaTest.java b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/ResourceSchemaTest.java index 1a7124bd121..7dc8d4fa183 100644 --- a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/ResourceSchemaTest.java +++ b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/ResourceSchemaTest.java @@ -34,14 +34,14 @@ public void validateResourceSchemaFromNodeToNode(String resourceSchemaFile) { public static List resourceSchemaFiles() { try { Path definitionPath = Paths.get( - ResourceSchemaTest.class.getResource("aws-sagemaker-domain.cfn.json").toURI() + ResourceSchemaTest.class.getResource("aws-sagemaker-domain.cfn.json").toURI() ); return Files.walk(Paths.get(definitionPath.getParent().toUri())) - .filter(Files::isRegularFile) - .filter(file -> file.toString().endsWith(".cfn.json")) - .map(Object::toString) - .collect(Collectors.toList()); + .filter(Files::isRegularFile) + .filter(file -> file.toString().endsWith(".cfn.json")) + .map(Object::toString) + .collect(Collectors.toList()); } catch (IOException | URISyntaxException e) { throw new RuntimeException(e); } diff --git a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/Smithy2CfnTest.java b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/Smithy2CfnTest.java index f9d0fadddb8..d233302b786 100644 --- a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/Smithy2CfnTest.java +++ b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/Smithy2CfnTest.java @@ -19,21 +19,21 @@ public class Smithy2CfnTest { @Test public void pluginConvertsModel() { Model model = Model.assembler() - .addImport(Smithy2CfnTest.class.getResource("test-service.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(Smithy2CfnTest.class.getResource("test-service.smithy")) + .discoverModels() + .assemble() + .unwrap(); MockManifest manifest = new MockManifest(); PluginContext context = PluginContext.builder() - .settings( - Node.objectNode() - .withMember("organizationName", "Smithy") - .withMember("service", "smithy.example#TestService") - ) - .fileManifest(manifest) - .model(model) - .originalModel(model) - .build(); + .settings( + Node.objectNode() + .withMember("organizationName", "Smithy") + .withMember("service", "smithy.example#TestService") + ) + .fileManifest(manifest) + .model(model) + .originalModel(model) + .build(); new Smithy2Cfn().execute(context); assertEquals(manifest.getFiles().size(), 3); @@ -45,20 +45,20 @@ public void pluginConvertsModel() { @Test public void throwsWhenServiceNotConfigured() { Model model = Model.assembler() - .addImport(Smithy2CfnTest.class.getResource("test-service.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(Smithy2CfnTest.class.getResource("test-service.smithy")) + .discoverModels() + .assemble() + .unwrap(); MockManifest manifest = new MockManifest(); PluginContext context = PluginContext.builder() - .settings( - Node.objectNode() - .withMember("organizationName", "Smithy") - ) - .fileManifest(manifest) - .model(model) - .originalModel(model) - .build(); + .settings( + Node.objectNode() + .withMember("organizationName", "Smithy") + ) + .fileManifest(manifest) + .model(model) + .originalModel(model) + .build(); assertThrows(CfnException.class, () -> { new Smithy2Cfn().execute(context); @@ -68,20 +68,20 @@ public void throwsWhenServiceNotConfigured() { @Test public void throwsWhenOrganizationNameNotConfigured() { Model model = Model.assembler() - .addImport(Smithy2CfnTest.class.getResource("test-service.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(Smithy2CfnTest.class.getResource("test-service.smithy")) + .discoverModels() + .assemble() + .unwrap(); MockManifest manifest = new MockManifest(); PluginContext context = PluginContext.builder() - .settings( - Node.objectNode() - .withMember("service", "smithy.example#TestService") - ) - .fileManifest(manifest) - .model(model) - .originalModel(model) - .build(); + .settings( + Node.objectNode() + .withMember("service", "smithy.example#TestService") + ) + .fileManifest(manifest) + .model(model) + .originalModel(model) + .build(); assertThrows(CfnException.class, () -> { new Smithy2Cfn().execute(context); diff --git a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/TestRunnerTest.java b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/TestRunnerTest.java index 1de0818d961..78b8c5b49e4 100644 --- a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/TestRunnerTest.java +++ b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/TestRunnerTest.java @@ -28,10 +28,10 @@ public class TestRunnerTest { @MethodSource("integFiles") public void generatesResources(String modelFile) { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(modelFile) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(modelFile) + .assemble() + .unwrap(); CfnConfig config = new CfnConfig(); config.setService(ShapeId.from("smithy.example#TestService")); @@ -42,8 +42,8 @@ public void generatesResources(String modelFile) { } Map result = CfnConverter.create() - .config(config) - .convertToNodes(model); + .config(config) + .convertToNodes(model); Node expectedNode = Node.parse(IoUtils.readUtf8File(modelFile.replace(".smithy", ".cfn.json"))); // Assert that we got one resource and that it matches @@ -54,10 +54,10 @@ public void generatesResources(String modelFile) { public static List integFiles() { try { return Files.walk(Paths.get(TestRunnerTest.class.getResource("integ").toURI())) - .filter(Files::isRegularFile) - .filter(file -> file.toString().endsWith(".smithy")) - .map(Object::toString) - .collect(Collectors.toList()); + .filter(Files::isRegularFile) + .filter(file -> file.toString().endsWith(".smithy")) + .map(Object::toString) + .collect(Collectors.toList()); } catch (IOException | URISyntaxException e) { throw new RuntimeException(e); } diff --git a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/AdditionalPropertiesMapperTest.java b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/AdditionalPropertiesMapperTest.java index b1e712401b5..366b4e784b7 100644 --- a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/AdditionalPropertiesMapperTest.java +++ b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/AdditionalPropertiesMapperTest.java @@ -17,25 +17,25 @@ public class AdditionalPropertiesMapperTest { @Test public void setsAdditionalPropertiesFalse() { Model model = Model.assembler() - .addImport(AdditionalPropertiesMapperTest.class.getResource("simple.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(AdditionalPropertiesMapperTest.class.getResource("simple.smithy")) + .discoverModels() + .assemble() + .unwrap(); CfnConfig config = new CfnConfig(); config.setOrganizationName("Smithy"); config.setService(ShapeId.from("smithy.example#TestService")); ObjectNode resourceNode = CfnConverter.create() - .config(config) - .convertToNodes(model) - .get("Smithy::TestService::FooResource"); + .config(config) + .convertToNodes(model) + .get("Smithy::TestService::FooResource"); assertFalse( - resourceNode.expectObjectMember("definitions") - .expectObjectMember("ComplexProperty") - .expectBooleanMember("additionalProperties") - .getValue() + resourceNode.expectObjectMember("definitions") + .expectObjectMember("ComplexProperty") + .expectBooleanMember("additionalProperties") + .getValue() ); } diff --git a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/DeprecatedMapperTest.java b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/DeprecatedMapperTest.java index 661d6c951b7..15861cf36f0 100644 --- a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/DeprecatedMapperTest.java +++ b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/DeprecatedMapperTest.java @@ -20,34 +20,34 @@ public class DeprecatedMapperTest { @Test public void addsDeprecatedPropertiesByDefault() { Model model = Model.assembler() - .addImport(DeprecatedMapperTest.class.getResource("simple.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(DeprecatedMapperTest.class.getResource("simple.smithy")) + .discoverModels() + .assemble() + .unwrap(); CfnConfig config = new CfnConfig(); config.setOrganizationName("Smithy"); config.setService(ShapeId.from("smithy.example#TestService")); ObjectNode resourceNode = CfnConverter.create() - .config(config) - .convertToNodes(model) - .get("Smithy::TestService::FooResource"); + .config(config) + .convertToNodes(model) + .get("Smithy::TestService::FooResource"); Assertions.assertEquals( - ListUtils.of("/properties/FooDeprecatedMutableProperty"), - resourceNode.expectArrayMember("deprecatedProperties") - .getElementsAs(StringNode::getValue) + ListUtils.of("/properties/FooDeprecatedMutableProperty"), + resourceNode.expectArrayMember("deprecatedProperties") + .getElementsAs(StringNode::getValue) ); } @Test public void canDisableDeprecatedPropertyGeneration() { Model model = Model.assembler() - .addImport(DeprecatedMapperTest.class.getResource("simple.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(DeprecatedMapperTest.class.getResource("simple.smithy")) + .discoverModels() + .assemble() + .unwrap(); CfnConfig config = new CfnConfig(); config.setOrganizationName("Smithy"); @@ -55,9 +55,9 @@ public void canDisableDeprecatedPropertyGeneration() { config.setDisableDeprecatedPropertyGeneration(true); ObjectNode resourceNode = CfnConverter.create() - .config(config) - .convertToNodes(model) - .get("Smithy::TestService::FooResource"); + .config(config) + .convertToNodes(model) + .get("Smithy::TestService::FooResource"); assertFalse(resourceNode.getMember("deprecatedProperties").isPresent()); } diff --git a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/DocumentationMapperTest.java b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/DocumentationMapperTest.java index e9cad3c9963..5574cd4c5a7 100644 --- a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/DocumentationMapperTest.java +++ b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/DocumentationMapperTest.java @@ -24,10 +24,10 @@ public class DocumentationMapperTest { @BeforeAll public static void loadModel() { model = Model.assembler() - .addImport(DocumentationMapperTest.class.getResource("simple.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(DocumentationMapperTest.class.getResource("simple.smithy")) + .discoverModels() + .assemble() + .unwrap(); } @Test diff --git a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/HandlerPermissionMapperTest.java b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/HandlerPermissionMapperTest.java index a97ef326e63..80b992d9a7b 100644 --- a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/HandlerPermissionMapperTest.java +++ b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/HandlerPermissionMapperTest.java @@ -28,10 +28,10 @@ public final class HandlerPermissionMapperTest { @BeforeAll public static void loadModel() { model = Model.assembler() - .addImport(DocumentationMapperTest.class.getResource("simple.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(DocumentationMapperTest.class.getResource("simple.smithy")) + .discoverModels() + .assemble() + .unwrap(); } private ObjectNode getResourceByName(String resourceName) { @@ -50,25 +50,25 @@ public void addsCRUHandlerPermissionsByDefault() { assertThat(handlersDefined.keySet(), containsInAnyOrder("create", "read", "update")); assertThat( - handlersDefined.get("create") - .expectObjectNode() - .expectArrayMember("permissions") - .getElementsAs(StringNode::getValue), - containsInAnyOrder("testservice:CreateFooOperation", "otherservice:DescribeDependencyComponent") + handlersDefined.get("create") + .expectObjectNode() + .expectArrayMember("permissions") + .getElementsAs(StringNode::getValue), + containsInAnyOrder("testservice:CreateFooOperation", "otherservice:DescribeDependencyComponent") ); assertThat( - handlersDefined.get("read") - .expectObjectNode() - .expectArrayMember("permissions") - .getElementsAs(StringNode::getValue), - containsInAnyOrder("testservice:GetFooOperation", "otherservice:DescribeThing") + handlersDefined.get("read") + .expectObjectNode() + .expectArrayMember("permissions") + .getElementsAs(StringNode::getValue), + containsInAnyOrder("testservice:GetFooOperation", "otherservice:DescribeThing") ); assertThat( - handlersDefined.get("update") - .expectObjectNode() - .expectArrayMember("permissions") - .getElementsAs(StringNode::getValue), - contains("testservice:UpdateFooOperation") + handlersDefined.get("update") + .expectObjectNode() + .expectArrayMember("permissions") + .getElementsAs(StringNode::getValue), + contains("testservice:UpdateFooOperation") ); } @@ -80,18 +80,18 @@ public void addsPutHandlerPermissionsByDefault() { assertThat(handlersDefined.keySet(), containsInAnyOrder("create", "update")); assertThat( - handlersDefined.get("create") - .expectObjectNode() - .expectArrayMember("permissions") - .getElementsAs(StringNode::getValue), - contains("testservice:CreateBar") + handlersDefined.get("create") + .expectObjectNode() + .expectArrayMember("permissions") + .getElementsAs(StringNode::getValue), + contains("testservice:CreateBar") ); assertThat( - handlersDefined.get("update") - .expectObjectNode() - .expectArrayMember("permissions") - .getElementsAs(StringNode::getValue), - contains("testservice:CreateBar") + handlersDefined.get("update") + .expectObjectNode() + .expectArrayMember("permissions") + .getElementsAs(StringNode::getValue), + contains("testservice:CreateBar") ); } @@ -103,11 +103,11 @@ public void addsPutWithNoReplaceHandlerPermissionsByDefault() { assertThat(handlersDefined.keySet(), contains("create")); assertThat( - handlersDefined.get("create") - .expectObjectNode() - .expectArrayMember("permissions") - .getElementsAs(StringNode::getValue), - contains("testservice:CreateBaz") + handlersDefined.get("create") + .expectObjectNode() + .expectArrayMember("permissions") + .getElementsAs(StringNode::getValue), + contains("testservice:CreateBaz") ); } @@ -119,9 +119,9 @@ public void canDisableHandlerPermissionsGeneration() { config.setDisableHandlerPermissionGeneration(true); ObjectNode resourceNode = CfnConverter.create() - .config(config) - .convertToNodes(model) - .get("Smithy::TestService::FooResource"); + .config(config) + .convertToNodes(model) + .get("Smithy::TestService::FooResource"); assertFalse(resourceNode.getMember("handlers").isPresent()); } diff --git a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/JsonAddTest.java b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/JsonAddTest.java index 8112d05df90..a5cbd58c54a 100644 --- a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/JsonAddTest.java +++ b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/JsonAddTest.java @@ -19,16 +19,16 @@ public class JsonAddTest { @Test public void addsWithPointers() { Model model = Model.assembler() - .addImport(JsonAddTest.class.getResource("simple.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(JsonAddTest.class.getResource("simple.smithy")) + .discoverModels() + .assemble() + .unwrap(); ObjectNode addNode = Node.objectNodeBuilder() - .withMember("/arbitrary/foo", "whoa") - .withMember("/arbitrary/bar/baz", "nested") - .withMember("/documentationUrl", "https://example.com") - .build(); + .withMember("/arbitrary/foo", "whoa") + .withMember("/arbitrary/bar/baz", "nested") + .withMember("/documentationUrl", "https://example.com") + .build(); CfnConfig config = new CfnConfig(); config.setOrganizationName("Smithy"); @@ -36,19 +36,19 @@ public void addsWithPointers() { config.setJsonAdd(MapUtils.of(ShapeId.from("smithy.example#FooResource"), addNode.getStringMap())); ObjectNode resourceNode = CfnConverter.create() - .config(config) - .convertToNodes(model) - .get("Smithy::TestService::FooResource"); + .config(config) + .convertToNodes(model) + .get("Smithy::TestService::FooResource"); String arbitraryFoo = NodePointer.parse("/arbitrary/foo").getValue(resourceNode).expectStringNode().getValue(); String arbitraryBarBaz = NodePointer.parse("/arbitrary/bar/baz") - .getValue(resourceNode) - .expectStringNode() - .getValue(); + .getValue(resourceNode) + .expectStringNode() + .getValue(); String documentationUrl = NodePointer.parse("/documentationUrl") - .getValue(resourceNode) - .expectStringNode() - .getValue(); + .getValue(resourceNode) + .expectStringNode() + .getValue(); Assertions.assertEquals("whoa", arbitraryFoo); Assertions.assertEquals("nested", arbitraryBarBaz); diff --git a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/RequiredMapperTest.java b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/RequiredMapperTest.java index bb5e8277248..9896a79585f 100644 --- a/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/RequiredMapperTest.java +++ b/smithy-aws-cloudformation/src/test/java/software/amazon/smithy/aws/cloudformation/schema/fromsmithy/mappers/RequiredMapperTest.java @@ -21,34 +21,34 @@ public class RequiredMapperTest { @Test public void addsRequiredPropertiesByDefault() { Model model = Model.assembler() - .addImport(RequiredMapperTest.class.getResource("simple.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(RequiredMapperTest.class.getResource("simple.smithy")) + .discoverModels() + .assemble() + .unwrap(); CfnConfig config = new CfnConfig(); config.setOrganizationName("Smithy"); config.setService(ShapeId.from("smithy.example#TestService")); ObjectNode resourceNode = CfnConverter.create() - .config(config) - .convertToNodes(model) - .get("Smithy::TestService::FooResource"); + .config(config) + .convertToNodes(model) + .get("Smithy::TestService::FooResource"); Assertions.assertEquals( - ListUtils.of("FooRequiredProperty"), - resourceNode.expectArrayMember("required") - .getElementsAs(StringNode::getValue) + ListUtils.of("FooRequiredProperty"), + resourceNode.expectArrayMember("required") + .getElementsAs(StringNode::getValue) ); } @Test public void canDisableRequiredPropertyGeneration() { Model model = Model.assembler() - .addImport(RequiredMapperTest.class.getResource("simple.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(RequiredMapperTest.class.getResource("simple.smithy")) + .discoverModels() + .assemble() + .unwrap(); CfnConfig config = new CfnConfig(); config.setOrganizationName("Smithy"); @@ -56,9 +56,9 @@ public void canDisableRequiredPropertyGeneration() { config.setDisableRequiredPropertyGeneration(true); ObjectNode resourceNode = CfnConverter.create() - .config(config) - .convertToNodes(model) - .get("Smithy::TestService::FooResource"); + .config(config) + .convertToNodes(model) + .get("Smithy::TestService::FooResource"); assertFalse(resourceNode.getMember("required").isPresent()); } diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/diff/EndpointSigV4Migration.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/diff/EndpointSigV4Migration.java index 53679bab210..786dffbee69 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/diff/EndpointSigV4Migration.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/diff/EndpointSigV4Migration.java @@ -54,28 +54,28 @@ public List evaluate(Differences differences) { // Validate Service effective auth schemes List> serviceChanges = differences - .changedShapes(ServiceShape.class) - .collect(Collectors.toList()); + .changedShapes(ServiceShape.class) + .collect(Collectors.toList()); for (ChangedShape change : serviceChanges) { ServiceShape oldServiceShape = change.getOldShape(); ServiceShape newServiceShape = change.getNewShape(); if (!oldServiceShape.hasTrait(EndpointRuleSetTrait.ID) - || !newServiceShape.hasTrait(EndpointRuleSetTrait.ID)) { + || !newServiceShape.hasTrait(EndpointRuleSetTrait.ID)) { continue; } Optional> endpointRuleSetOpt = change.getChangedTrait( - EndpointRuleSetTrait.class + EndpointRuleSetTrait.class ); Optional> authOpt = change.getChangedTrait(AuthTrait.class); List oldModeledAuthSchemes = getModeledAuthSchemes(oldServiceIndex, oldServiceShape); List newModeledAuthSchemes = getModeledAuthSchemes(newServiceIndex, newServiceShape); // Validate diffs for changes to `@smithy.rules#endpointRuleSet` and `@auth` and effective auth schemes if (!endpointRuleSetOpt.isPresent() - && !authOpt.isPresent() - // Check modeled auth schemes since they could change without the `@auth` trait present - && oldModeledAuthSchemes.equals(newModeledAuthSchemes)) { + && !authOpt.isPresent() + // Check modeled auth schemes since they could change without the `@auth` trait present + && oldModeledAuthSchemes.equals(newModeledAuthSchemes)) { continue; } @@ -87,16 +87,16 @@ public List evaluate(Differences differences) { // JSON path -> Endpoint entries that exist in both the old and new model and are changed Map> changedEndpoints = newEndpoints.entrySet() - .stream() - .filter(e -> oldEndpoints.containsKey(e.getKey())) - .map( - e -> new SimpleEntry>( - e.getKey(), - Pair.of(oldEndpoints.get(e.getKey()), e.getValue()) + .stream() + .filter(e -> oldEndpoints.containsKey(e.getKey())) + .map( + e -> new SimpleEntry>( + e.getKey(), + Pair.of(oldEndpoints.get(e.getKey()), e.getValue()) + ) ) - ) - .filter(e -> !e.getValue().getLeft().equals(e.getValue().getRight())) - .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); + .filter(e -> !e.getValue().getLeft().equals(e.getValue().getRight())) + .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); for (Entry> entry : changedEndpoints.entrySet()) { String jsonPath = entry.getKey(); Endpoint oldEndpoint = entry.getValue().getLeft(); @@ -110,43 +110,45 @@ public List evaluate(Differences differences) { boolean isNewSigV4APresent = containsSigV4AEquivalentAuthScheme(newAuthSchemes); boolean isSigV4Replaced = isOldSigV4Present && !isNewSigV4Present - && !isOldSigV4APresent && isNewSigV4APresent; + && !isOldSigV4APresent && isNewSigV4APresent; boolean isSigV4AReplaced = !isOldSigV4Present && isNewSigV4Present - && isOldSigV4APresent && !isNewSigV4APresent; + && isOldSigV4APresent && !isNewSigV4APresent; boolean noSigV4XRemoved = isOldSigV4Present && isNewSigV4Present - && isOldSigV4APresent && isNewSigV4APresent; + && isOldSigV4APresent && isNewSigV4APresent; boolean isSigV4Added = !isOldSigV4Present && isNewSigV4Present - && isOldSigV4APresent && isNewSigV4APresent; + && isOldSigV4APresent && isNewSigV4APresent; boolean isSigV4AAdded = isOldSigV4Present && isNewSigV4Present - && !isOldSigV4APresent && isNewSigV4APresent; + && !isOldSigV4APresent && isNewSigV4APresent; if (isSigV4Replaced) { events.add( - danger( - newServiceShape, - "The `aws.auth#sigv4` authentication scheme was replaced by the `aws.auth#sigv4a` " - + "authentication scheme in the effective auth schemes for an endpoint in the " - + "`@smithy.rules#endpointRuleSet` trait applied to `" + newServiceShape.getId() - + "` at: `" - + jsonPath + "`. " - + "Replacing the `aws.auth#sigv4` authentication scheme with the `aws.auth#sigv4a` " - + "authentication scheme directly is not backward compatible since not all credentials usable " - + "by `aws.auth#sigv4` are compatible with `aws.auth#sigv4a`, and can break existing clients' " - + "authentication." - ) + danger( + newServiceShape, + "The `aws.auth#sigv4` authentication scheme was replaced by the `aws.auth#sigv4a` " + + "authentication scheme in the effective auth schemes for an endpoint in the " + + "`@smithy.rules#endpointRuleSet` trait applied to `" + newServiceShape + .getId() + + "` at: `" + + jsonPath + "`. " + + "Replacing the `aws.auth#sigv4` authentication scheme with the `aws.auth#sigv4a` " + + "authentication scheme directly is not backward compatible since not all credentials usable " + + "by `aws.auth#sigv4` are compatible with `aws.auth#sigv4a`, and can break existing clients' " + + "authentication." + ) ); } else if (isSigV4AReplaced) { events.add( - danger( - newServiceShape, - "The `aws.auth#sigv4a` authentication scheme was replaced by the `aws.auth#sigv4` " - + "authentication scheme in the effective auth schemes for an endpoint in the " - + "`@smithy.rules#endpointRuleSet` trait applied to `" + newServiceShape.getId() - + "` at: `" - + jsonPath + "`. " - + "Replacing the `aws.auth#sigv4` authentication scheme with the `aws.auth#sigv4a` " - + "authentication scheme directly may not be backward compatible if the signing scope was " - + "narrowed (typically from `*`)." - ) + danger( + newServiceShape, + "The `aws.auth#sigv4a` authentication scheme was replaced by the `aws.auth#sigv4` " + + "authentication scheme in the effective auth schemes for an endpoint in the " + + "`@smithy.rules#endpointRuleSet` trait applied to `" + newServiceShape + .getId() + + "` at: `" + + jsonPath + "`. " + + "Replacing the `aws.auth#sigv4` authentication scheme with the `aws.auth#sigv4a` " + + "authentication scheme directly may not be backward compatible if the signing scope was " + + "narrowed (typically from `*`)." + ) ); } else if (noSigV4XRemoved) { int oldSigV4Index = getIndexOfSigV4AuthScheme(oldAuthSchemes); @@ -157,31 +159,33 @@ public List evaluate(Differences differences) { boolean isSigV4BeforeSigV4A = sigV4Index < sigV4aIndex; if (isOldSigV4BeforeSigV4A && !isSigV4BeforeSigV4A) { events.add( - danger( - newServiceShape, - "The `aws.auth#sigv4a` authentication scheme was moved before the `aws.auth#sigv4` " - + "authentication scheme in the effective auth schemes for an endpoint in the " - + "`@smithy.rules#endpointRuleSet` trait applied to `" + newServiceShape.getId() - + "` at: `" + jsonPath + "`. " - + "Moving the `aws.auth#sigv4a` authentication scheme before the `aws.auth#sigv4` " - + "authentication scheme is not backward compatible since not all credentials usable by " - + "`aws.auth#sigv4` are compatible with `aws.auth#sigv4a`, and can break existing " - + "clients' authentication." - ) + danger( + newServiceShape, + "The `aws.auth#sigv4a` authentication scheme was moved before the `aws.auth#sigv4` " + + "authentication scheme in the effective auth schemes for an endpoint in the " + + "`@smithy.rules#endpointRuleSet` trait applied to `" + newServiceShape + .getId() + + "` at: `" + jsonPath + "`. " + + "Moving the `aws.auth#sigv4a` authentication scheme before the `aws.auth#sigv4` " + + "authentication scheme is not backward compatible since not all credentials usable by " + + "`aws.auth#sigv4` are compatible with `aws.auth#sigv4a`, and can break existing " + + "clients' authentication." + ) ); } if (!isOldSigV4BeforeSigV4A && isSigV4BeforeSigV4A) { events.add( - danger( - newServiceShape, - "The `aws.auth#sigv4` authentication scheme was moved before the `aws.auth#sigv4a` " - + "authentication scheme in the effective auth schemes for an endpoint in the " - + "`@smithy.rules#endpointRuleSet` trait applied to `" + newServiceShape.getId() - + "` at: `" + jsonPath + "`. " - + "Moving the `aws.auth#sigv4` authentication scheme before the `aws.auth#sigv4a` " - + "authentication scheme may not be backward compatible if the signing scope was narrowed " - + "(typically from `*`)." - ) + danger( + newServiceShape, + "The `aws.auth#sigv4` authentication scheme was moved before the `aws.auth#sigv4a` " + + "authentication scheme in the effective auth schemes for an endpoint in the " + + "`@smithy.rules#endpointRuleSet` trait applied to `" + newServiceShape + .getId() + + "` at: `" + jsonPath + "`. " + + "Moving the `aws.auth#sigv4` authentication scheme before the `aws.auth#sigv4a` " + + "authentication scheme may not be backward compatible if the signing scope was narrowed " + + "(typically from `*`)." + ) ); } } else if (isSigV4Added) { @@ -190,16 +194,17 @@ public List evaluate(Differences differences) { boolean isSigV4AddedBeforeSigV4A = sigV4Index < sigV4aIndex; if (isSigV4AddedBeforeSigV4A) { events.add( - danger( - newServiceShape, - "The `aws.auth#sigv4` authentication scheme was added before the `aws.auth#sigv4a` " - + "authentication scheme in the effective auth schemes for an endpoint in the " - + "`@smithy.rules#endpointRuleSet` trait applied to `" + newServiceShape.getId() - + "` at: `" + jsonPath + "`. " - + "Adding the `aws.auth#sigv4` authentication scheme before an existing `aws.auth#sigv4a` " - + "authentication scheme may not be backward compatible if the signing scope was narrowed " - + "(typically from `*`)." - ) + danger( + newServiceShape, + "The `aws.auth#sigv4` authentication scheme was added before the `aws.auth#sigv4a` " + + "authentication scheme in the effective auth schemes for an endpoint in the " + + "`@smithy.rules#endpointRuleSet` trait applied to `" + newServiceShape + .getId() + + "` at: `" + jsonPath + "`. " + + "Adding the `aws.auth#sigv4` authentication scheme before an existing `aws.auth#sigv4a` " + + "authentication scheme may not be backward compatible if the signing scope was narrowed " + + "(typically from `*`)." + ) ); } } else if (isSigV4AAdded) { @@ -208,17 +213,18 @@ public List evaluate(Differences differences) { boolean isSigV4AAddedBeforeSigV4 = sigV4aIndex < sigV4Index; if (isSigV4AAddedBeforeSigV4) { events.add( - danger( - newServiceShape, - "The `aws.auth#sigv4a` authentication scheme was added before the `aws.auth#sigv4` " - + "authentication scheme in the effective auth schemes for an endpoint in the " - + "`@smithy.rules#endpointRuleSet` trait applied to `" + newServiceShape.getId() - + "` at: `" + jsonPath + "`. " - + "Adding the `aws.auth#sigv4a` authentication scheme before an existing `aws.auth#sigv4` " - + "authentication scheme is not backward compatible since not all credentials usable by " - + "`aws.auth#sigv4` are compatible with `aws.auth#sigv4a`, and can break existing clients' " - + "authentication." - ) + danger( + newServiceShape, + "The `aws.auth#sigv4a` authentication scheme was added before the `aws.auth#sigv4` " + + "authentication scheme in the effective auth schemes for an endpoint in the " + + "`@smithy.rules#endpointRuleSet` trait applied to `" + newServiceShape + .getId() + + "` at: `" + jsonPath + "`. " + + "Adding the `aws.auth#sigv4a` authentication scheme before an existing `aws.auth#sigv4` " + + "authentication scheme is not backward compatible since not all credentials usable by " + + "`aws.auth#sigv4` are compatible with `aws.auth#sigv4a`, and can break existing clients' " + + "authentication." + ) ); } } @@ -230,20 +236,20 @@ public List evaluate(Differences differences) { private static List getAuthSchemes(Endpoint endpoint, List modeledAuthSchemes) { List endpointAuthSchemes = endpoint.getEndpointAuthSchemes() - .stream() - .map(a -> a.get(ID_NAME).asStringLiteral().get().expectLiteral()) - .collect(Collectors.toList()); + .stream() + .map(a -> a.get(ID_NAME).asStringLiteral().get().expectLiteral()) + .collect(Collectors.toList()); return endpointAuthSchemes.size() == 0 - ? modeledAuthSchemes - : endpointAuthSchemes; + ? modeledAuthSchemes + : endpointAuthSchemes; } private static List getModeledAuthSchemes(ServiceIndex serviceIndex, ServiceShape serviceShape) { return serviceIndex.getEffectiveAuthSchemes(serviceShape) - .keySet() - .stream() - .map(ShapeId::toString) - .collect(Collectors.toList()); + .keySet() + .stream() + .map(ShapeId::toString) + .collect(Collectors.toList()); } private static boolean containsSigV4EquivalentAuthScheme(List authSchemes) { diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsArn.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsArn.java index 1d3e5bfff95..a999d146438 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsArn.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsArn.java @@ -53,13 +53,13 @@ public static Optional parse(String arn) { } return Optional.of( - builder() - .partition(base[1]) - .service(base[2]) - .region(base[3]) - .accountId(base[4]) - .resource(Arrays.asList(base[5].split("[:/]", -1))) - .build() + builder() + .partition(base[1]) + .service(base[2]) + .region(base[3]) + .accountId(base[4]) + .resource(Arrays.asList(base[5].split("[:/]", -1))) + .build() ); } @@ -136,7 +136,7 @@ public boolean equals(Object o) { } AwsArn awsArn = (AwsArn) o; return partition.equals(awsArn.partition) && service.equals(awsArn.service) && region.equals(awsArn.region) - && accountId.equals(awsArn.accountId) && resource.equals(awsArn.resource); + && accountId.equals(awsArn.accountId) && resource.equals(awsArn.resource); } @Override @@ -145,20 +145,20 @@ public String toString() { resource.forEach(builder::append); return "Arn[partition=" + partition + ", " - + "service=" + service + ", " - + "region=" + region + ", " - + "accountId=" + accountId + ", " - + "resource=" + builder + "]"; + + "service=" + service + ", " + + "region=" + region + ", " + + "accountId=" + accountId + ", " + + "resource=" + builder + "]"; } @Override public Builder toBuilder() { return builder() - .partition(partition) - .service(service) - .region(region) - .accountId(accountId) - .resource(resource); + .partition(partition) + .service(service) + .region(region) + .accountId(accountId) + .resource(resource); } /** diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsBuiltIns.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsBuiltIns.java index 9e7c12e7734..da0f7ce1429 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsBuiltIns.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsBuiltIns.java @@ -16,167 +16,167 @@ public final class AwsBuiltIns { * Built-in parameter representing the DualStack parameter for SDKs. */ public static final Parameter DUALSTACK = Parameter.builder() - .name("UseDualStack") - .type(ParameterType.BOOLEAN) - .builtIn("AWS::UseDualStack") - .documentation( - "When true, use the dual-stack endpoint. If the configured endpoint does not " - + "support dual-stack, dispatching the request MAY return an error." - ) - .required(true) - .defaultValue(Value.booleanValue(false)) - .build(); + .name("UseDualStack") + .type(ParameterType.BOOLEAN) + .builtIn("AWS::UseDualStack") + .documentation( + "When true, use the dual-stack endpoint. If the configured endpoint does not " + + "support dual-stack, dispatching the request MAY return an error." + ) + .required(true) + .defaultValue(Value.booleanValue(false)) + .build(); /** * Built-in parameter representing whether the endpoint must be FIPS-compliant. */ public static final Parameter FIPS = Parameter.builder() - .name("UseFIPS") - .type(ParameterType.BOOLEAN) - .builtIn("AWS::UseFIPS") - .documentation( - "When true, send this request to the FIPS-compliant regional endpoint. If the " - + "configured endpoint does not have a FIPS compliant endpoint, dispatching " - + "the request will return an error." - ) - .required(true) - .defaultValue(Value.booleanValue(false)) - .build(); + .name("UseFIPS") + .type(ParameterType.BOOLEAN) + .builtIn("AWS::UseFIPS") + .documentation( + "When true, send this request to the FIPS-compliant regional endpoint. If the " + + "configured endpoint does not have a FIPS compliant endpoint, dispatching " + + "the request will return an error." + ) + .required(true) + .defaultValue(Value.booleanValue(false)) + .build(); /** * Built-in parameter representing Region eg. `us-east-1`. */ public static final Parameter REGION = Parameter.builder() - .name("Region") - .type(ParameterType.STRING) - .builtIn("AWS::Region") - .documentation("The AWS region used to dispatch the request.") - .build(); + .name("Region") + .type(ParameterType.STRING) + .builtIn("AWS::Region") + .documentation("The AWS region used to dispatch the request.") + .build(); /** * Built-in parameter representing the AccountId. */ public static final Parameter ACCOUNT_ID = Parameter.builder() - .name("AccountId") - .type(ParameterType.STRING) - .builtIn("AWS::Auth::AccountId") - .documentation("The AWS AccountId used for the request.") - .build(); + .name("AccountId") + .type(ParameterType.STRING) + .builtIn("AWS::Auth::AccountId") + .documentation("The AWS AccountId used for the request.") + .build(); /** * Built-in parameter representing the AccountId Endpoint Mode. */ public static final Parameter ACCOUNT_ID_ENDPOINT_MODE = Parameter.builder() - .name("AccountIdEndpointMode") - .type(ParameterType.STRING) - .builtIn("AWS::Auth::AccountIdEndpointMode") - .documentation("The AccountId Endpoint Mode.") - .build(); + .name("AccountIdEndpointMode") + .type(ParameterType.STRING) + .builtIn("AWS::Auth::AccountIdEndpointMode") + .documentation("The AccountId Endpoint Mode.") + .build(); /** * Built-in parameter representing the Credential Scope. */ public static final Parameter CREDENTIAL_SCOPE = Parameter.builder() - .name("CredentialScope") - .type(ParameterType.STRING) - .builtIn("AWS::Auth::CredentialScope") - .documentation("The AWS Credential Scope used for the request.") - .build(); + .name("CredentialScope") + .type(ParameterType.STRING) + .builtIn("AWS::Auth::CredentialScope") + .documentation("The AWS Credential Scope used for the request.") + .build(); /** * This MUST only be used by the S3 rules. */ public static final Parameter S3_ACCELERATE = Parameter.builder() - .type(ParameterType.BOOLEAN) - .name("Accelerate") - .builtIn("AWS::S3::Accelerate") - .required(true) - .defaultValue(Value.booleanValue(false)) - .documentation("When true, use S3 Accelerate. NOTE: Not all regions support S3 accelerate.") - .build(); + .type(ParameterType.BOOLEAN) + .name("Accelerate") + .builtIn("AWS::S3::Accelerate") + .required(true) + .defaultValue(Value.booleanValue(false)) + .documentation("When true, use S3 Accelerate. NOTE: Not all regions support S3 accelerate.") + .build(); /** * This MUST only be used by the S3 rules. */ public static final Parameter S3_DISABLE_MRAP = Parameter.builder() - .type(ParameterType.BOOLEAN) - .name("DisableMultiRegionAccessPoints") - .builtIn("AWS::S3::DisableMultiRegionAccessPoints") - .required(true) - .defaultValue(Value.booleanValue(false)) - .documentation("Whether multi-region access points (MRAP) should be disabled.") - .build(); + .type(ParameterType.BOOLEAN) + .name("DisableMultiRegionAccessPoints") + .builtIn("AWS::S3::DisableMultiRegionAccessPoints") + .required(true) + .defaultValue(Value.booleanValue(false)) + .documentation("Whether multi-region access points (MRAP) should be disabled.") + .build(); /** * This MUST only be used by the S3 rules. */ public static final Parameter S3_FORCE_PATH_STYLE = Parameter.builder() - .type(ParameterType.BOOLEAN) - .name("ForcePathStyle") - .builtIn("AWS::S3::ForcePathStyle") - .documentation( - "When true, force a path-style endpoint to be used where the bucket name is part " - + "of the path." - ) - .build(); + .type(ParameterType.BOOLEAN) + .name("ForcePathStyle") + .builtIn("AWS::S3::ForcePathStyle") + .documentation( + "When true, force a path-style endpoint to be used where the bucket name is part " + + "of the path." + ) + .build(); /** * This MUST only be used by the S3 rules. */ public static final Parameter S3_USE_ARN_REGION = Parameter.builder() - .type(ParameterType.BOOLEAN) - .name("UseArnRegion") - .builtIn("AWS::S3::UseArnRegion") - .documentation( - "When an Access Point ARN is provided and this flag is enabled, the SDK MUST use " - + "the ARN's region when constructing the endpoint instead of the client's " - + "configured region." - ) - .build(); + .type(ParameterType.BOOLEAN) + .name("UseArnRegion") + .builtIn("AWS::S3::UseArnRegion") + .documentation( + "When an Access Point ARN is provided and this flag is enabled, the SDK MUST use " + + "the ARN's region when constructing the endpoint instead of the client's " + + "configured region." + ) + .build(); /** * This MUST only be used by the S3 rules. */ public static final Parameter S3_USE_GLOBAL_ENDPOINT = Parameter.builder() - .type(ParameterType.BOOLEAN) - .name("UseGlobalEndpoint") - .builtIn("AWS::S3::UseGlobalEndpoint") - .required(true) - .defaultValue(Value.booleanValue(false)) - .documentation( - "Whether the global endpoint should be used, rather then " - + "the regional endpoint for us-east-1." - ) - .build(); + .type(ParameterType.BOOLEAN) + .name("UseGlobalEndpoint") + .builtIn("AWS::S3::UseGlobalEndpoint") + .required(true) + .defaultValue(Value.booleanValue(false)) + .documentation( + "Whether the global endpoint should be used, rather then " + + "the regional endpoint for us-east-1." + ) + .build(); /** * This MUST only be used by the S3Control rules. */ public static final Parameter S3_CONTROL_USE_ARN_REGION = Parameter.builder() - .type(ParameterType.BOOLEAN) - .name("UseArnRegion") - .builtIn("AWS::S3Control::UseArnRegion") - .documentation( - "When an Access Point ARN is provided and this flag is enabled, the SDK MUST use " - + "the ARN's region when constructing the endpoint instead of the client's " - + "configured region." - ) - .build(); + .type(ParameterType.BOOLEAN) + .name("UseArnRegion") + .builtIn("AWS::S3Control::UseArnRegion") + .documentation( + "When an Access Point ARN is provided and this flag is enabled, the SDK MUST use " + + "the ARN's region when constructing the endpoint instead of the client's " + + "configured region." + ) + .build(); /** * This MUST only be used by the STS rules. */ public static final Parameter STS_USE_GLOBAL_ENDPOINT = Parameter.builder() - .type(ParameterType.BOOLEAN) - .name("UseGlobalEndpoint") - .builtIn("AWS::STS::UseGlobalEndpoint") - .required(true) - .defaultValue(Value.booleanValue(false)) - .documentation( - "Whether the global endpoint should be used, rather then " - + "the regional endpoint for us-east-1." - ) - .build(); + .type(ParameterType.BOOLEAN) + .name("UseGlobalEndpoint") + .builtIn("AWS::STS::UseGlobalEndpoint") + .required(true) + .defaultValue(Value.booleanValue(false)) + .documentation( + "Whether the global endpoint should be used, rather then " + + "the regional endpoint for us-east-1." + ) + .build(); private AwsBuiltIns() {} } diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsPartition.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsPartition.java index ea91bb10c4b..eb6f1fcef71 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsPartition.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsPartition.java @@ -52,10 +52,10 @@ public final class AwsPartition extends LibraryFunction { static { PARTITIONS.addAll( - Partitions.fromNode( - Node.parse(Partitions.class.getResourceAsStream("partitions.json")) - ) - .getPartitions() + Partitions.fromNode( + Node.parse(Partitions.class.getResourceAsStream("partitions.json")) + ) + .getPartitions() ); initializeRegionMap(); } @@ -177,22 +177,22 @@ public Value evaluate(List arguments) { PartitionOutputs matchedPartitionOutputs = matchedPartition.getOutputs(); return Value.recordValue( - MapUtils.of( - NAME, - Value.stringValue(matchedPartition.getId()), - DNS_SUFFIX, - Value.stringValue(matchedPartitionOutputs.getDnsSuffix()), - DUAL_STACK_DNS_SUFFIX, - Value.stringValue(matchedPartitionOutputs.getDualStackDnsSuffix()), - SUPPORTS_FIPS, - Value.booleanValue(matchedPartitionOutputs.supportsFips()), - SUPPORTS_DUAL_STACK, - Value.booleanValue(matchedPartitionOutputs.supportsDualStack()), - INFERRED, - Value.booleanValue(inferred), - IMPLICIT_GLOBAL_REGION, - Value.stringValue(matchedPartitionOutputs.getImplicitGlobalRegion()) - ) + MapUtils.of( + NAME, + Value.stringValue(matchedPartition.getId()), + DNS_SUFFIX, + Value.stringValue(matchedPartitionOutputs.getDnsSuffix()), + DUAL_STACK_DNS_SUFFIX, + Value.stringValue(matchedPartitionOutputs.getDualStackDnsSuffix()), + SUPPORTS_FIPS, + Value.booleanValue(matchedPartitionOutputs.supportsFips()), + SUPPORTS_DUAL_STACK, + Value.booleanValue(matchedPartitionOutputs.supportsDualStack()), + INFERRED, + Value.booleanValue(inferred), + IMPLICIT_GLOBAL_REGION, + Value.stringValue(matchedPartitionOutputs.getImplicitGlobalRegion()) + ) ); } diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsRuleSetExtension.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsRuleSetExtension.java index 2af83d49583..f055ebbfa6c 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsRuleSetExtension.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsRuleSetExtension.java @@ -18,38 +18,38 @@ public final class AwsRuleSetExtension implements EndpointRuleSetExtension { @Override public List getBuiltIns() { return ListUtils.of( - AwsBuiltIns.DUALSTACK, - AwsBuiltIns.FIPS, - AwsBuiltIns.REGION, - AwsBuiltIns.ACCOUNT_ID, - AwsBuiltIns.ACCOUNT_ID_ENDPOINT_MODE, - AwsBuiltIns.CREDENTIAL_SCOPE, - AwsBuiltIns.S3_ACCELERATE, - AwsBuiltIns.S3_DISABLE_MRAP, - AwsBuiltIns.S3_FORCE_PATH_STYLE, - AwsBuiltIns.S3_USE_ARN_REGION, - AwsBuiltIns.S3_USE_GLOBAL_ENDPOINT, - AwsBuiltIns.S3_CONTROL_USE_ARN_REGION, - AwsBuiltIns.STS_USE_GLOBAL_ENDPOINT + AwsBuiltIns.DUALSTACK, + AwsBuiltIns.FIPS, + AwsBuiltIns.REGION, + AwsBuiltIns.ACCOUNT_ID, + AwsBuiltIns.ACCOUNT_ID_ENDPOINT_MODE, + AwsBuiltIns.CREDENTIAL_SCOPE, + AwsBuiltIns.S3_ACCELERATE, + AwsBuiltIns.S3_DISABLE_MRAP, + AwsBuiltIns.S3_FORCE_PATH_STYLE, + AwsBuiltIns.S3_USE_ARN_REGION, + AwsBuiltIns.S3_USE_GLOBAL_ENDPOINT, + AwsBuiltIns.S3_CONTROL_USE_ARN_REGION, + AwsBuiltIns.STS_USE_GLOBAL_ENDPOINT ); } @Override public List getLibraryFunctions() { return ListUtils.of( - AwsPartition.getDefinition(), - IsVirtualHostableS3Bucket.getDefinition(), - ParseArn.getDefinition() + AwsPartition.getDefinition(), + IsVirtualHostableS3Bucket.getDefinition(), + ParseArn.getDefinition() ); } @Override public List getAuthSchemeValidators() { return ListUtils.of( - new EndpointAuthUtils.SigV4SchemeValidator(), - new EndpointAuthUtils.SigV4aSchemeValidator(), - new EndpointAuthUtils.SigV4SubSchemeValidator(), - new EndpointAuthUtils.BetaSchemeValidator() + new EndpointAuthUtils.SigV4SchemeValidator(), + new EndpointAuthUtils.SigV4aSchemeValidator(), + new EndpointAuthUtils.SigV4SubSchemeValidator(), + new EndpointAuthUtils.BetaSchemeValidator() ); } } diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/EndpointAuthUtils.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/EndpointAuthUtils.java index 7b7cddf6bd3..36c6429a6d0 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/EndpointAuthUtils.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/EndpointAuthUtils.java @@ -55,13 +55,13 @@ private EndpointAuthUtils() {} */ public static Endpoint.Builder sigv4(Endpoint.Builder builder, Literal signingRegion, Literal signingService) { return builder.addAuthScheme( - SIGV4, - MapUtils.of( - SIGNING_NAME, - signingService, - SIGNING_REGION, - signingRegion - ) + SIGV4, + MapUtils.of( + SIGNING_NAME, + signingService, + SIGNING_REGION, + signingRegion + ) ); } @@ -74,18 +74,18 @@ public static Endpoint.Builder sigv4(Endpoint.Builder builder, Literal signingRe * @return the updated endpoint builder. */ public static Endpoint.Builder sigv4a( - Endpoint.Builder builder, - List signingRegionSet, - Literal signingService + Endpoint.Builder builder, + List signingRegionSet, + Literal signingService ) { return builder.addAuthScheme( - SIGV4A, - MapUtils.of( - SIGNING_NAME, - signingService, - SIGNING_REGION_SET, - Literal.tupleLiteral(signingRegionSet) - ) + SIGV4A, + MapUtils.of( + SIGNING_NAME, + signingService, + SIGNING_REGION_SET, + Literal.tupleLiteral(signingRegionSet) + ) ); } @@ -131,21 +131,21 @@ public boolean test(String name) { @Override public List validateScheme( - Map authScheme, - FromSourceLocation sourceLocation, - BiFunction emitter + Map authScheme, + FromSourceLocation sourceLocation, + BiFunction emitter ) { List events = noExtraProperties( - emitter, - sourceLocation, - authScheme, - ListUtils.of( - RuleSetAuthSchemesValidator.NAME, - ID_SIGNING_NAME, - ID_SIGNING_REGION, - ID_DISABLE_DOUBLE_ENCODING, - ID_DISABLE_NORMALIZE_PATH - ) + emitter, + sourceLocation, + authScheme, + ListUtils.of( + RuleSetAuthSchemesValidator.NAME, + ID_SIGNING_NAME, + ID_SIGNING_REGION, + ID_DISABLE_DOUBLE_ENCODING, + ID_DISABLE_NORMALIZE_PATH + ) ); // Validate shared Sigv4 properties. @@ -158,8 +158,8 @@ public List validateScheme( } private static List validateOptionalSharedProperties( - Map authScheme, - BiFunction emitter + Map authScheme, + BiFunction emitter ) { List events = new ArrayList<>(); // The following properties are only type checked if present. @@ -186,30 +186,30 @@ public boolean test(String name) { @Override public List validateScheme( - Map authScheme, - FromSourceLocation sourceLocation, - BiFunction emitter + Map authScheme, + FromSourceLocation sourceLocation, + BiFunction emitter ) { List events = noExtraProperties( - emitter, - sourceLocation, - authScheme, - ListUtils.of( - RuleSetAuthSchemesValidator.NAME, - ID_SIGNING_NAME, - ID_SIGNING_REGION_SET, - ID_DISABLE_DOUBLE_ENCODING, - ID_DISABLE_NORMALIZE_PATH - ) + emitter, + sourceLocation, + authScheme, + ListUtils.of( + RuleSetAuthSchemesValidator.NAME, + ID_SIGNING_NAME, + ID_SIGNING_REGION_SET, + ID_DISABLE_DOUBLE_ENCODING, + ID_DISABLE_NORMALIZE_PATH + ) ); // The `signingRegionSet` property will always be present. Optional event = validatePropertyType( - emitter, - authScheme.get(ID_SIGNING_REGION_SET), - ID_SIGNING_REGION_SET, - Literal::asTupleLiteral, - "an array" + emitter, + authScheme.get(ID_SIGNING_REGION_SET), + ID_SIGNING_REGION_SET, + Literal::asTupleLiteral, + "an array" ); // If we don't have a tuple, that's our main error. // Otherwise, validate each entry is a string. @@ -219,19 +219,19 @@ public List validateScheme( List signingRegionSet = authScheme.get(ID_SIGNING_REGION_SET).asTupleLiteral().get(); if (signingRegionSet.isEmpty()) { events.add( - emitter.apply( - authScheme.get(ID_SIGNING_REGION_SET), - "The `signingRegionSet` property must not be an empty list." - ) + emitter.apply( + authScheme.get(ID_SIGNING_REGION_SET), + "The `signingRegionSet` property must not be an empty list." + ) ); } else { for (Literal signingRegion : signingRegionSet) { validatePropertyType( - emitter, - signingRegion, - Identifier.of("signingRegionSet.Value"), - Literal::asStringLiteral, - "a string" + emitter, + signingRegion, + Identifier.of("signingRegionSet.Value"), + Literal::asStringLiteral, + "a string" ).ifPresent(events::add); } } @@ -253,22 +253,22 @@ public boolean test(String name) { @Override public List validateScheme( - Map authScheme, - FromSourceLocation sourceLocation, - BiFunction emitter + Map authScheme, + FromSourceLocation sourceLocation, + BiFunction emitter ) { List events = hasAllKeys( - emitter, - authScheme, - ListUtils.of(RuleSetAuthSchemesValidator.NAME, ID_SIGNING_NAME), - sourceLocation + emitter, + authScheme, + ListUtils.of(RuleSetAuthSchemesValidator.NAME, ID_SIGNING_NAME), + sourceLocation ); validateStringProperty(emitter, authScheme, ID_SIGNING_NAME).ifPresent(events::add); // Events are emitted by default as ERROR, but we want to make this viable with acknowledgement. ValidationEvent event = emitter.apply( - sourceLocation, - "Requirements for `sigv4-` auth sub-scheme validation may change." + sourceLocation, + "Requirements for `sigv4-` auth sub-scheme validation may change." ); events.add(event.toBuilder().severity(Severity.DANGER).build()); @@ -276,10 +276,10 @@ public List validateScheme( } private List hasAllKeys( - BiFunction emitter, - Map authScheme, - List requiredKeys, - FromSourceLocation sourceLocation + BiFunction emitter, + Map authScheme, + List requiredKeys, + FromSourceLocation sourceLocation ) { List events = new ArrayList<>(); for (Identifier key : requiredKeys) { @@ -301,25 +301,25 @@ public boolean test(String name) { @Override public List validateScheme( - Map authScheme, - FromSourceLocation sourceLocation, - BiFunction emitter + Map authScheme, + FromSourceLocation sourceLocation, + BiFunction emitter ) { List events = hasAllKeys( - emitter, - authScheme, - ListUtils.of(RuleSetAuthSchemesValidator.NAME, ID_SIGNING_NAME), - sourceLocation + emitter, + authScheme, + ListUtils.of(RuleSetAuthSchemesValidator.NAME, ID_SIGNING_NAME), + sourceLocation ); validateStringProperty(emitter, authScheme, ID_SIGNING_NAME).ifPresent(events::add); return events; } private List hasAllKeys( - BiFunction emitter, - Map authScheme, - List requiredKeys, - FromSourceLocation sourceLocation + BiFunction emitter, + Map authScheme, + List requiredKeys, + FromSourceLocation sourceLocation ) { List events = new ArrayList<>(); for (Identifier key : requiredKeys) { @@ -332,23 +332,23 @@ private List hasAllKeys( } private static List noExtraProperties( - BiFunction emitter, - FromSourceLocation sourceLocation, - Map properties, - List allowedProperties + BiFunction emitter, + FromSourceLocation sourceLocation, + Map properties, + List allowedProperties ) { List events = new ArrayList<>(); for (Identifier propertyName : properties.keySet()) { if (!allowedProperties.contains(propertyName)) { events.add( - emitter.apply( - sourceLocation, - String.format( - "Unexpected key: `%s` (valid keys: %s)", - propertyName, - allowedProperties + emitter.apply( + sourceLocation, + String.format( + "Unexpected key: `%s` (valid keys: %s)", + propertyName, + allowedProperties + ) ) - ) ); } } @@ -356,64 +356,64 @@ private static List noExtraProperties( } private static Optional validateBooleanProperty( - BiFunction emitter, - Map properties, - Identifier propertyName + BiFunction emitter, + Map properties, + Identifier propertyName ) { return validatePropertyType( - emitter, - properties.get(propertyName), - propertyName, - Literal::asBooleanLiteral, - "a boolean" + emitter, + properties.get(propertyName), + propertyName, + Literal::asBooleanLiteral, + "a boolean" ); } private static Optional validateStringProperty( - BiFunction emitter, - Map properties, - Identifier propertyName + BiFunction emitter, + Map properties, + Identifier propertyName ) { return validatePropertyType( - emitter, - properties.get(propertyName), - propertyName, - Literal::asStringLiteral, - "a string" + emitter, + properties.get(propertyName), + propertyName, + Literal::asStringLiteral, + "a string" ); } private static Optional validatePropertyType( - BiFunction emitter, - Literal value, - Identifier propertyName, - Function> validator, - String expectedType + BiFunction emitter, + Literal value, + Identifier propertyName, + Function> validator, + String expectedType ) { if (value == null) { return Optional.of( - emitter.apply( - propertyName, - String.format( - "Expected auth property `%s` of %s type but didn't find one", - propertyName, - expectedType + emitter.apply( + propertyName, + String.format( + "Expected auth property `%s` of %s type but didn't find one", + propertyName, + expectedType + ) ) - ) ); } if (!validator.apply(value).isPresent()) { return Optional.of( - emitter.apply( - value, - String.format( - "Unexpected type for auth property `%s`, found `%s` but expected %s value", - propertyName, - value, - expectedType + emitter.apply( + value, + String.format( + "Unexpected type for auth property `%s`, found `%s` but expected %s value", + propertyName, + value, + expectedType + ) ) - ) ); } return Optional.empty(); diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/IsVirtualHostableS3Bucket.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/IsVirtualHostableS3Bucket.java index 33737cfdc83..0ef6bf37932 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/IsVirtualHostableS3Bucket.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/IsVirtualHostableS3Bucket.java @@ -97,11 +97,11 @@ public Value evaluate(List arguments) { boolean allowDots = arguments.get(1).expectBooleanValue().getValue(); if (allowDots) { return Value.booleanValue( - DOTS_ALLOWED.matcher(hostLabel).matches() - // Don't allow ip address - && !IP_ADDRESS.matcher(hostLabel).matches() - // Don't allow names like bucket-.name or bucket.-name - && !DASH_DOT_SEPARATOR.matcher(hostLabel).matches() + DOTS_ALLOWED.matcher(hostLabel).matches() + // Don't allow ip address + && !IP_ADDRESS.matcher(hostLabel).matches() + // Don't allow names like bucket-.name or bucket.-name + && !DASH_DOT_SEPARATOR.matcher(hostLabel).matches() ); } else { return Value.booleanValue(DOTS_DISALLOWED.matcher(hostLabel).matches()); diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/ParseArn.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/ParseArn.java index 1f6935da499..bbe691ec7ab 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/ParseArn.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/ParseArn.java @@ -109,18 +109,18 @@ public Value evaluate(List arguments) { resourceId.add(Value.stringValue(resourceIdPart)); } return Value.recordValue( - MapUtils.of( - PARTITION, - Value.stringValue(awsArn.getPartition()), - SERVICE, - Value.stringValue(awsArn.getService()), - REGION, - Value.stringValue(awsArn.getRegion()), - ACCOUNT_ID, - Value.stringValue(awsArn.getAccountId()), - RESOURCE_ID, - Value.arrayValue(resourceId) - ) + MapUtils.of( + PARTITION, + Value.stringValue(awsArn.getPartition()), + SERVICE, + Value.stringValue(awsArn.getService()), + REGION, + Value.stringValue(awsArn.getRegion()), + ACCOUNT_ID, + Value.stringValue(awsArn.getAccountId()), + RESOURCE_ID, + Value.arrayValue(resourceId) + ) ); } diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/Partition.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/Partition.java index d192ce40b6b..30ba08b139b 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/Partition.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/Partition.java @@ -66,9 +66,9 @@ public static Partition fromNode(Node node) { objectNode.expectStringMember(ID, builder::id); objectNode.getStringMember(REGION_REGEX, builder::regionRegex); objectNode.getObjectMember( - REGIONS, - regionsNode -> regionsNode.getMembers() - .forEach((k, v) -> builder.putRegion(k.toString(), RegionOverride.fromNode(v))) + REGIONS, + regionsNode -> regionsNode.getMembers() + .forEach((k, v) -> builder.putRegion(k.toString(), RegionOverride.fromNode(v))) ); objectNode.getObjectMember(OUTPUTS, outputsNode -> builder.outputs(PartitionOutputs.fromNode(outputsNode))); @@ -119,10 +119,10 @@ public SourceLocation getSourceLocation() { @Override public Builder toBuilder() { return new Builder(getSourceLocation()) - .id(id) - .regionRegex(regionRegex) - .regions(regions) - .outputs(outputs); + .id(id) + .regionRegex(regionRegex) + .regions(regions) + .outputs(outputs); } @Override @@ -133,11 +133,11 @@ public Node toNode() { } return Node.objectNodeBuilder() - .withMember(ID, Node.from(id)) - .withMember(REGION_REGEX, Node.from(regionRegex)) - .withMember(REGIONS, regionNodeBuilder.build()) - .withMember(OUTPUTS, outputs.toNode()) - .build(); + .withMember(ID, Node.from(id)) + .withMember(REGION_REGEX, Node.from(regionRegex)) + .withMember(REGIONS, regionNodeBuilder.build()) + .withMember(OUTPUTS, outputs.toNode()) + .build(); } @Override @@ -150,8 +150,8 @@ public boolean equals(Object o) { } Partition partition = (Partition) o; return Objects.equals(id, partition.id) && Objects.equals(regionRegex, partition.regionRegex) - && Objects.equals(regions, partition.regions) - && Objects.equals(outputs, partition.outputs); + && Objects.equals(regions, partition.regions) + && Objects.equals(outputs, partition.outputs); } @Override diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/PartitionOutputs.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/PartitionOutputs.java index 39d22631c16..52606984af3 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/PartitionOutputs.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/PartitionOutputs.java @@ -29,12 +29,12 @@ public final class PartitionOutputs implements ToSmithyBuilder private static final String SUPPORTS_DUAL_STACK = "supportsDualStack"; private static final String IMPLICIT_GLOBAL_REGION = "implicitGlobalRegion"; private static final List PROPERTIES = ListUtils.of( - NAME, - DNS_SUFFIX, - DUAL_STACK_DNS_SUFFIX, - SUPPORTS_FIPS, - SUPPORTS_DUAL_STACK, - IMPLICIT_GLOBAL_REGION + NAME, + DNS_SUFFIX, + DUAL_STACK_DNS_SUFFIX, + SUPPORTS_FIPS, + SUPPORTS_DUAL_STACK, + IMPLICIT_GLOBAL_REGION ); private final String name; @@ -148,22 +148,22 @@ public SourceLocation getSourceLocation() { @Override public Builder toBuilder() { return new Builder(getSourceLocation()) - .name(name) - .dnsSuffix(dnsSuffix) - .dualStackDnsSuffix(dualStackDnsSuffix) - .supportsFips(supportsFips) - .supportsDualStack(supportsDualStack) - .implicitGlobalRegion(implicitGlobalRegion); + .name(name) + .dnsSuffix(dnsSuffix) + .dualStackDnsSuffix(dualStackDnsSuffix) + .supportsFips(supportsFips) + .supportsDualStack(supportsDualStack) + .implicitGlobalRegion(implicitGlobalRegion); } @Override public Node toNode() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withMember(DNS_SUFFIX, dnsSuffix) - .withMember(DUAL_STACK_DNS_SUFFIX, dualStackDnsSuffix) - .withMember(SUPPORTS_FIPS, supportsFips) - .withMember(SUPPORTS_DUAL_STACK, supportsDualStack) - .withMember(IMPLICIT_GLOBAL_REGION, implicitGlobalRegion); + .withMember(DNS_SUFFIX, dnsSuffix) + .withMember(DUAL_STACK_DNS_SUFFIX, dualStackDnsSuffix) + .withMember(SUPPORTS_FIPS, supportsFips) + .withMember(SUPPORTS_DUAL_STACK, supportsDualStack) + .withMember(IMPLICIT_GLOBAL_REGION, implicitGlobalRegion); if (name != null) { builder.withMember(NAME, name); @@ -181,22 +181,22 @@ public boolean equals(Object o) { } PartitionOutputs partitionOutputs = (PartitionOutputs) o; return supportsFips == partitionOutputs.supportsFips && supportsDualStack == partitionOutputs.supportsDualStack - && Objects.equals(name, partitionOutputs.name) - && Objects.equals(dnsSuffix, partitionOutputs.dnsSuffix) - && Objects.equals(dualStackDnsSuffix, partitionOutputs.dualStackDnsSuffix) - && Objects.equals(implicitGlobalRegion, partitionOutputs.implicitGlobalRegion); + && Objects.equals(name, partitionOutputs.name) + && Objects.equals(dnsSuffix, partitionOutputs.dnsSuffix) + && Objects.equals(dualStackDnsSuffix, partitionOutputs.dualStackDnsSuffix) + && Objects.equals(implicitGlobalRegion, partitionOutputs.implicitGlobalRegion); } @Override public int hashCode() { return Objects.hash( - name, - dnsSuffix, - dualStackDnsSuffix, - supportsFips, - supportsDualStack, - implicitGlobalRegion + name, + dnsSuffix, + dualStackDnsSuffix, + supportsFips, + supportsDualStack, + implicitGlobalRegion ); } diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/Partitions.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/Partitions.java index e31c23616a1..1076ab84830 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/Partitions.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/Partitions.java @@ -59,8 +59,8 @@ public static Partitions fromNode(Node node) { objNode.getStringMember(VERSION, builder::version); objNode.getArrayMember( - PARTITIONS, - partitionsNode -> partitionsNode.forEach(partNode -> builder.addPartition(Partition.fromNode(partNode))) + PARTITIONS, + partitionsNode -> partitionsNode.forEach(partNode -> builder.addPartition(Partition.fromNode(partNode))) ); return builder.build(); @@ -92,8 +92,8 @@ public SourceLocation getSourceLocation() { @Override public Builder toBuilder() { return new Builder(getSourceLocation()) - .version(version) - .partitions(partitions); + .version(version) + .partitions(partitions); } @Override @@ -102,9 +102,9 @@ public Node toNode() { partitions.forEach(partitionsNodeBuilder::withValue); return Node.objectNodeBuilder() - .withMember(VERSION, Node.from(version)) - .withMember(PARTITIONS, partitionsNodeBuilder.build()) - .build(); + .withMember(VERSION, Node.from(version)) + .withMember(PARTITIONS, partitionsNodeBuilder.build()) + .build(); } @Override @@ -127,9 +127,9 @@ public int hashCode() { @Override public String toString() { return "Partitions{version='" + version - + "', partitions=" + partitions - + ", sourceLocation=" + sourceLocation - + '}'; + + "', partitions=" + partitions + + ", sourceLocation=" + sourceLocation + + '}'; } /** diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/EndpointModifierIndex.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/EndpointModifierIndex.java index 95155e5e383..d90b7bc967a 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/EndpointModifierIndex.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/EndpointModifierIndex.java @@ -34,11 +34,11 @@ public EndpointModifierIndex(Model model) { Optional traitShape = model.getShape(trait.toShapeId()); if (!traitShape.isPresent()) { LOGGER.warning( - String.format( - "`%s` trait found in service `%s`, but the trait definition is missing", - trait.toShapeId(), - serviceShape.toShapeId() - ) + String.format( + "`%s` trait found in service `%s`, but the trait definition is missing", + trait.toShapeId(), + serviceShape.toShapeId() + ) ); continue; } diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/EndpointPatternType.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/EndpointPatternType.java index d033c5a943f..77ab55913b8 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/EndpointPatternType.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/EndpointPatternType.java @@ -40,10 +40,10 @@ public static EndpointPatternType fromNode(Node node) { } } throw new RuntimeException( - String.format( - "Unable to find EndpointPatternType enum with value [%s]", - value.getValue() - ) + String.format( + "Unable to find EndpointPatternType enum with value [%s]", + value.getValue() + ) ); } } diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/PartitionEndpointSpecialCase.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/PartitionEndpointSpecialCase.java index 97076e539a5..0bc71101dbe 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/PartitionEndpointSpecialCase.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/PartitionEndpointSpecialCase.java @@ -18,7 +18,7 @@ * or are located in a region other than the partition's default global region. */ public final class PartitionEndpointSpecialCase - implements FromSourceLocation, ToNode, ToSmithyBuilder { + implements FromSourceLocation, ToNode, ToSmithyBuilder { private static final String ENDPOINT = "endpoint"; private static final String REGION = "region"; @@ -77,21 +77,21 @@ public String getRegion() { @Override public Node toNode() { return Node.objectNodeBuilder() - .withMember(ENDPOINT, endpoint) - .withMember(REGION, region) - .withMember(DUAL_STACK, dualStack.toString()) - .withMember(FIPS, fips.toString()) - .build(); + .withMember(ENDPOINT, endpoint) + .withMember(REGION, region) + .withMember(DUAL_STACK, dualStack.toString()) + .withMember(FIPS, fips.toString()) + .build(); } @Override public Builder toBuilder() { return new Builder() - .endpoint(endpoint) - .region(region) - .dualStack(dualStack) - .fips(fips) - .sourceLocation(sourceLocation); + .endpoint(endpoint) + .region(region) + .dualStack(dualStack) + .fips(fips) + .sourceLocation(sourceLocation); } @Override @@ -108,12 +108,12 @@ public SourceLocation getSourceLocation() { public static PartitionEndpointSpecialCase fromNode(Node node) { ObjectNode objectNode = node.expectObjectNode(); return builder() - .sourceLocation(objectNode.getSourceLocation()) - .endpoint(objectNode.expectStringMember(ENDPOINT).getValue()) - .region(objectNode.expectStringMember(REGION).getValue()) - .dualStack(objectNode.getBooleanMemberOrDefault(DUAL_STACK, null)) - .fips(objectNode.getBooleanMemberOrDefault(FIPS, null)) - .build(); + .sourceLocation(objectNode.getSourceLocation()) + .endpoint(objectNode.expectStringMember(ENDPOINT).getValue()) + .region(objectNode.expectStringMember(REGION).getValue()) + .dualStack(objectNode.getBooleanMemberOrDefault(DUAL_STACK, null)) + .fips(objectNode.getBooleanMemberOrDefault(FIPS, null)) + .build(); } public static Builder builder() { diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/PartitionSpecialCase.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/PartitionSpecialCase.java index 2c47c7b6e36..d0fe877d044 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/PartitionSpecialCase.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/PartitionSpecialCase.java @@ -64,19 +64,19 @@ public Boolean getFips() { @Override public Node toNode() { return Node.objectNodeBuilder() - .withMember(ENDPOINT, endpoint) - .withOptionalMember(DUAL_STACK, Optional.ofNullable(dualStack).map(Node::from)) - .withOptionalMember(FIPS, Optional.ofNullable(fips).map(Node::from)) - .build(); + .withMember(ENDPOINT, endpoint) + .withOptionalMember(DUAL_STACK, Optional.ofNullable(dualStack).map(Node::from)) + .withOptionalMember(FIPS, Optional.ofNullable(fips).map(Node::from)) + .build(); } @Override public Builder toBuilder() { return new Builder() - .dualStack(dualStack) - .endpoint(endpoint) - .fips(fips) - .sourceLocation(sourceLocation); + .dualStack(dualStack) + .endpoint(endpoint) + .fips(fips) + .sourceLocation(sourceLocation); } @Override @@ -93,11 +93,11 @@ public SourceLocation getSourceLocation() { public static PartitionSpecialCase fromNode(Node node) { ObjectNode objectNode = node.expectObjectNode(); return builder() - .sourceLocation(objectNode.getSourceLocation()) - .endpoint(objectNode.expectStringMember(ENDPOINT).getValue()) - .dualStack(objectNode.getBooleanMemberOrDefault(DUAL_STACK, null)) - .fips(objectNode.getBooleanMemberOrDefault(FIPS, null)) - .build(); + .sourceLocation(objectNode.getSourceLocation()) + .endpoint(objectNode.expectStringMember(ENDPOINT).getValue()) + .dualStack(objectNode.getBooleanMemberOrDefault(DUAL_STACK, null)) + .fips(objectNode.getBooleanMemberOrDefault(FIPS, null)) + .build(); } public static Builder builder() { diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/RegionSpecialCase.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/RegionSpecialCase.java index b69908fa7c8..03fe7ffad24 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/RegionSpecialCase.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/RegionSpecialCase.java @@ -74,21 +74,21 @@ public String getSigningRegion() { @Override public Node toNode() { return Node.objectNodeBuilder() - .withMember(ENDPOINT, endpoint) - .withMember(DUAL_STACK, dualStack.toString()) - .withMember(FIPS, fips.toString()) - .withMember(SIGNING_REGION, signingRegion) - .build(); + .withMember(ENDPOINT, endpoint) + .withMember(DUAL_STACK, dualStack.toString()) + .withMember(FIPS, fips.toString()) + .withMember(SIGNING_REGION, signingRegion) + .build(); } @Override public Builder toBuilder() { return new Builder() - .dualStack(dualStack) - .endpoint(endpoint) - .fips(fips) - .signingRegion(signingRegion) - .sourceLocation(sourceLocation); + .dualStack(dualStack) + .endpoint(endpoint) + .fips(fips) + .signingRegion(signingRegion) + .sourceLocation(sourceLocation); } @Override @@ -105,12 +105,12 @@ public SourceLocation getSourceLocation() { public static RegionSpecialCase fromNode(Node node) { ObjectNode objectNode = node.expectObjectNode(); return builder() - .sourceLocation(objectNode.getSourceLocation()) - .endpoint(objectNode.expectStringMember(ENDPOINT).getValue()) - .dualStack(objectNode.getBooleanMemberOrDefault(DUAL_STACK, null)) - .fips(objectNode.getBooleanMemberOrDefault(FIPS, null)) - .signingRegion(objectNode.getStringMemberOrDefault(SIGNING_REGION, null)) - .build(); + .sourceLocation(objectNode.getSourceLocation()) + .endpoint(objectNode.expectStringMember(ENDPOINT).getValue()) + .dualStack(objectNode.getBooleanMemberOrDefault(DUAL_STACK, null)) + .fips(objectNode.getBooleanMemberOrDefault(FIPS, null)) + .signingRegion(objectNode.getStringMemberOrDefault(SIGNING_REGION, null)) + .build(); } public static Builder builder() { diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/StandardPartitionalEndpointsTrait.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/StandardPartitionalEndpointsTrait.java index 8447aa6babf..ffde15f15df 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/StandardPartitionalEndpointsTrait.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/StandardPartitionalEndpointsTrait.java @@ -23,7 +23,7 @@ * and a single endpoint should resolve per partition. */ public final class StandardPartitionalEndpointsTrait extends AbstractTrait - implements ToSmithyBuilder { + implements ToSmithyBuilder { public static final ShapeId ID = ShapeId.from("aws.endpoints#standardPartitionalEndpoints"); public static final String PARTITION_ENDPOINT_SPECIAL_CASES = "partitionEndpointSpecialCases"; public static final String ENDPOINT_PATTERN_TYPE = "endpointPatternType"; @@ -68,17 +68,17 @@ protected Node createNode() { } return ObjectNode.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withMember(PARTITION_ENDPOINT_SPECIAL_CASES, partitionEndpointSpecialCasesNodeBuilder.build()) - .withMember(ENDPOINT_PATTERN_TYPE, endpointPatternType.getName()) - .build(); + .sourceLocation(getSourceLocation()) + .withMember(PARTITION_ENDPOINT_SPECIAL_CASES, partitionEndpointSpecialCasesNodeBuilder.build()) + .withMember(ENDPOINT_PATTERN_TYPE, endpointPatternType.getName()) + .build(); } @Override public Builder toBuilder() { return new Builder() - .partitionEndpointSpecialCases(partitionEndpointSpecialCases) - .endpointPatternType(endpointPatternType); + .partitionEndpointSpecialCases(partitionEndpointSpecialCases) + .endpointPatternType(endpointPatternType); } public static Builder builder() { @@ -95,23 +95,23 @@ public Trait createTrait(ShapeId target, Node value) { ObjectNode objectNode = value.expectObjectNode(); EndpointPatternType endpointPatternType = EndpointPatternType - .fromNode(objectNode.expectStringMember(ENDPOINT_PATTERN_TYPE)); + .fromNode(objectNode.expectStringMember(ENDPOINT_PATTERN_TYPE)); StandardPartitionalEndpointsTrait.Builder builder = builder() - .sourceLocation(value) - .endpointPatternType(endpointPatternType); + .sourceLocation(value) + .endpointPatternType(endpointPatternType); if (objectNode.containsMember(PARTITION_ENDPOINT_SPECIAL_CASES)) { for (Map.Entry entry : objectNode.expectObjectMember(PARTITION_ENDPOINT_SPECIAL_CASES) - .getStringMap() - .entrySet()) { + .getStringMap() + .entrySet()) { List partitionEndpointSpecialCases = new ArrayList<>(); for (Node node : entry.getValue().expectArrayNode().getElements()) { partitionEndpointSpecialCases.add(PartitionEndpointSpecialCase.fromNode(node)); } builder.putPartitionEndpointSpecialCase( - entry.getKey(), - Collections.unmodifiableList(partitionEndpointSpecialCases) + entry.getKey(), + Collections.unmodifiableList(partitionEndpointSpecialCases) ); } } @@ -124,7 +124,7 @@ public Trait createTrait(ShapeId target, Node value) { public static final class Builder extends AbstractTraitBuilder { private final BuilderRef>> partitionEndpointSpecialCases = BuilderRef - .forOrderedMap(); + .forOrderedMap(); private EndpointPatternType endpointPatternType; /** @@ -134,7 +134,7 @@ public static final class Builder extends AbstractTraitBuilder> partitionEndpointSpecialCases + Map> partitionEndpointSpecialCases ) { this.partitionEndpointSpecialCases.clear(); this.partitionEndpointSpecialCases.get().putAll(partitionEndpointSpecialCases); @@ -149,8 +149,8 @@ public Builder partitionEndpointSpecialCases( * @return Returns the builder. */ public Builder putPartitionEndpointSpecialCase( - String partition, - List partitionEndpointSpecialCases + String partition, + List partitionEndpointSpecialCases ) { this.partitionEndpointSpecialCases.get().put(partition, partitionEndpointSpecialCases); return this; diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/StandardRegionalEndpointsTrait.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/StandardRegionalEndpointsTrait.java index 5f34e944fbb..f43d23602de 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/StandardRegionalEndpointsTrait.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/traits/StandardRegionalEndpointsTrait.java @@ -22,7 +22,7 @@ * using the standard AWS regional patterns. */ public final class StandardRegionalEndpointsTrait extends AbstractTrait - implements ToSmithyBuilder { + implements ToSmithyBuilder { public static final ShapeId ID = ShapeId.from("aws.endpoints#standardRegionalEndpoints"); public static final String PARTITION_SPECIAL_CASES = "partitionSpecialCases"; public static final String REGION_SPECIAL_CASES = "regionSpecialCases"; @@ -75,17 +75,17 @@ protected Node createNode() { } return ObjectNode.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withMember(PARTITION_SPECIAL_CASES, partitionSpecialCasesNodeBuilder.build()) - .withMember(REGION_SPECIAL_CASES, regionSpecialCasesNodeBuilder.build()) - .build(); + .sourceLocation(getSourceLocation()) + .withMember(PARTITION_SPECIAL_CASES, partitionSpecialCasesNodeBuilder.build()) + .withMember(REGION_SPECIAL_CASES, regionSpecialCasesNodeBuilder.build()) + .build(); } @Override public Builder toBuilder() { return new Builder() - .partitionSpecialCases(partitionSpecialCases) - .regionSpecialCases(regionSpecialCases); + .partitionSpecialCases(partitionSpecialCases) + .regionSpecialCases(regionSpecialCases); } public static Builder builder() { @@ -102,27 +102,27 @@ public Trait createTrait(ShapeId target, Node value) { ObjectNode objectNode = value.expectObjectNode(); StandardRegionalEndpointsTrait.Builder builder = builder() - .sourceLocation(value); + .sourceLocation(value); if (objectNode.containsMember(PARTITION_SPECIAL_CASES)) { for (Map.Entry entry : objectNode.expectObjectMember(PARTITION_SPECIAL_CASES) - .getStringMap() - .entrySet()) { + .getStringMap() + .entrySet()) { List partitionSpecialCases = new ArrayList<>(); for (Node node : entry.getValue().expectArrayNode().getElements()) { partitionSpecialCases.add(PartitionSpecialCase.fromNode(node)); } builder.putPartitionSpecialCases( - entry.getKey(), - Collections.unmodifiableList(partitionSpecialCases) + entry.getKey(), + Collections.unmodifiableList(partitionSpecialCases) ); } } if (objectNode.containsMember(REGION_SPECIAL_CASES)) { for (Map.Entry entry : objectNode.expectObjectMember(REGION_SPECIAL_CASES) - .getStringMap() - .entrySet()) { + .getStringMap() + .entrySet()) { List regionSpecialCases = new ArrayList<>(); for (Node node : entry.getValue().expectArrayNode().getElements()) { regionSpecialCases.add(RegionSpecialCase.fromNode(node)); @@ -139,7 +139,7 @@ public Trait createTrait(ShapeId target, Node value) { public static final class Builder extends AbstractTraitBuilder { private final BuilderRef>> partitionSpecialCases = BuilderRef - .forOrderedMap(); + .forOrderedMap(); private final BuilderRef>> regionSpecialCases = BuilderRef.forOrderedMap(); /** diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/validators/AwsSpecialCaseEndpointValidator.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/validators/AwsSpecialCaseEndpointValidator.java index 2711efc1861..4e5243ef4e0 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/validators/AwsSpecialCaseEndpointValidator.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/validators/AwsSpecialCaseEndpointValidator.java @@ -30,10 +30,10 @@ public final class AwsSpecialCaseEndpointValidator extends AbstractValidator { private static final Set SUPPORTED_PATTERNS = SetUtils.of( - "{region}", - "{service}", - "{dnsSuffix}", - "{dualStackDnsSuffix}" + "{region}", + "{service}", + "{dnsSuffix}", + "{dualStackDnsSuffix}" ); private static final Pattern PATTERN = Pattern.compile("\\{[^\\}]*\\}"); @@ -43,37 +43,37 @@ public List validate(Model model) { List events = new ArrayList<>(); for (ServiceShape serviceShape : model.getServiceShapesWithTrait(StandardRegionalEndpointsTrait.class)) { events.addAll( - validateRegionalEndpointPatterns( - serviceShape, - serviceShape.expectTrait(StandardRegionalEndpointsTrait.class) - ) + validateRegionalEndpointPatterns( + serviceShape, + serviceShape.expectTrait(StandardRegionalEndpointsTrait.class) + ) ); } for (ServiceShape serviceShape : model.getServiceShapesWithTrait(StandardPartitionalEndpointsTrait.class)) { events.addAll( - validatePartitionalEndpointPatterns( - serviceShape, - serviceShape.expectTrait(StandardPartitionalEndpointsTrait.class) - ) + validatePartitionalEndpointPatterns( + serviceShape, + serviceShape.expectTrait(StandardPartitionalEndpointsTrait.class) + ) ); } return events; } private List validateRegionalEndpointPatterns( - ServiceShape serviceShape, - StandardRegionalEndpointsTrait regionalEndpoints + ServiceShape serviceShape, + StandardRegionalEndpointsTrait regionalEndpoints ) { List events = new ArrayList<>(); for (List specialCases : regionalEndpoints.getRegionSpecialCases().values()) { for (RegionSpecialCase specialCase : specialCases) { events.addAll( - validateEndpointPatterns( - serviceShape, - regionalEndpoints, - specialCase.getEndpoint() - ) + validateEndpointPatterns( + serviceShape, + regionalEndpoints, + specialCase.getEndpoint() + ) ); } } @@ -81,11 +81,11 @@ private List validateRegionalEndpointPatterns( for (List specialCases : regionalEndpoints.getPartitionSpecialCases().values()) { for (PartitionSpecialCase specialCase : specialCases) { events.addAll( - validateEndpointPatterns( - serviceShape, - regionalEndpoints, - specialCase.getEndpoint() - ) + validateEndpointPatterns( + serviceShape, + regionalEndpoints, + specialCase.getEndpoint() + ) ); } } @@ -94,21 +94,21 @@ private List validateRegionalEndpointPatterns( } private List validatePartitionalEndpointPatterns( - ServiceShape serviceShape, - StandardPartitionalEndpointsTrait partitionalEndpoints + ServiceShape serviceShape, + StandardPartitionalEndpointsTrait partitionalEndpoints ) { List events = new ArrayList<>(); for (List specialCases : partitionalEndpoints.getPartitionEndpointSpecialCases() - .values()) { + .values()) { for (PartitionEndpointSpecialCase specialCase : specialCases) { events.addAll( - validateEndpointPatterns( - serviceShape, - partitionalEndpoints, - specialCase.getEndpoint() - ) + validateEndpointPatterns( + serviceShape, + partitionalEndpoints, + specialCase.getEndpoint() + ) ); } } @@ -117,9 +117,9 @@ private List validatePartitionalEndpointPatterns( } private List validateEndpointPatterns( - ServiceShape serviceShape, - FromSourceLocation location, - String endpoint + ServiceShape serviceShape, + FromSourceLocation location, + String endpoint ) { List events = new ArrayList<>(); @@ -133,44 +133,44 @@ private List validateEndpointPatterns( if (!unsupportedPatterns.isEmpty()) { events.add( - danger( - serviceShape, - location, - String.format( - "Endpoint `%s` contains unsupported patterns: %s", - endpoint, - String.join(", ", unsupportedPatterns) - ), - "UnsupportedEndpointPattern" - ) + danger( + serviceShape, + location, + String.format( + "Endpoint `%s` contains unsupported patterns: %s", + endpoint, + String.join(", ", unsupportedPatterns) + ), + "UnsupportedEndpointPattern" + ) ); } if (!(endpoint.startsWith("http://") || endpoint.startsWith("https://"))) { events.add( - danger( - serviceShape, - location, - String.format( - "Endpoint `%s` should start with scheme `http://` or `https://`", - endpoint - ), - "InvalidEndpointPatternScheme" - ) + danger( + serviceShape, + location, + String.format( + "Endpoint `%s` should start with scheme `http://` or `https://`", + endpoint + ), + "InvalidEndpointPatternScheme" + ) ); } if (!isValidUrl(endpoint)) { events.add( - error( - serviceShape, - location, - String.format( - "Endpoint `%s` should be a valid URL.", - endpoint - ), - "InvalidEndpointPatternUrl" - ) + error( + serviceShape, + location, + String.format( + "Endpoint `%s` should be a valid URL.", + endpoint + ), + "InvalidEndpointPatternUrl" + ) ); } @@ -179,8 +179,8 @@ private List validateEndpointPatterns( private boolean isValidUrl(String endpointPattern) { String url = endpointPattern - .replace("{", "") - .replace("}", ""); + .replace("{", "") + .replace("}", ""); try { new URL(url).toURI(); return true; diff --git a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/validators/RuleSetAwsBuiltInValidator.java b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/validators/RuleSetAwsBuiltInValidator.java index 8f3a3c321e2..e932655b9fe 100644 --- a/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/validators/RuleSetAwsBuiltInValidator.java +++ b/smithy-aws-endpoints/src/main/java/software/amazon/smithy/rulesengine/aws/validators/RuleSetAwsBuiltInValidator.java @@ -24,23 +24,23 @@ */ public class RuleSetAwsBuiltInValidator extends AbstractValidator { private static final Set ADDITIONAL_CONSIDERATION_BUILT_INS = SetUtils.of( - AwsBuiltIns.ACCOUNT_ID.getBuiltIn().get(), - AwsBuiltIns.ACCOUNT_ID_ENDPOINT_MODE.getBuiltIn().get(), - AwsBuiltIns.CREDENTIAL_SCOPE.getBuiltIn().get() + AwsBuiltIns.ACCOUNT_ID.getBuiltIn().get(), + AwsBuiltIns.ACCOUNT_ID_ENDPOINT_MODE.getBuiltIn().get(), + AwsBuiltIns.CREDENTIAL_SCOPE.getBuiltIn().get() ); private static final String ADDITIONAL_CONSIDERATION_MESSAGE = "The `%s` built-in used requires additional " - + "consideration of the rules that use it."; + + "consideration of the rules that use it."; @Override public List validate(Model model) { List events = new ArrayList<>(); for (ServiceShape serviceShape : model.getServiceShapesWithTrait(EndpointRuleSetTrait.class)) { events.addAll( - validateRuleSetAwsBuiltIns( - serviceShape, - serviceShape.expectTrait(EndpointRuleSetTrait.class) - .getEndpointRuleSet() - ) + validateRuleSetAwsBuiltIns( + serviceShape, + serviceShape.expectTrait(EndpointRuleSetTrait.class) + .getEndpointRuleSet() + ) ); } return events; @@ -57,18 +57,18 @@ private List validateRuleSetAwsBuiltIns(ServiceShape serviceSha } private Optional validateBuiltIn( - ServiceShape serviceShape, - String builtInName, - FromSourceLocation source + ServiceShape serviceShape, + String builtInName, + FromSourceLocation source ) { if (ADDITIONAL_CONSIDERATION_BUILT_INS.contains(builtInName)) { return Optional.of( - danger( - serviceShape, - source, - String.format(ADDITIONAL_CONSIDERATION_MESSAGE, builtInName), - builtInName - ) + danger( + serviceShape, + source, + String.format(ADDITIONAL_CONSIDERATION_MESSAGE, builtInName), + builtInName + ) ); } return Optional.empty(); diff --git a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsPartitionTest.java b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsPartitionTest.java index 50b249272f8..691814cf83c 100644 --- a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsPartitionTest.java +++ b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/AwsPartitionTest.java @@ -50,24 +50,24 @@ public void overridesPartitions() { // Remove the enumerated regions, so the same region is now inferred. AwsPartition.overridePartitions( - Partitions.builder() - .addPartition( - Partition.builder() - .id("aws") - .regionRegex("^(us|eu|ap|sa|ca|me|af)-\\w+-\\d+$") - .outputs( - PartitionOutputs.builder() - .name("aws") - .dnsSuffix("amazonaws.com") - .dualStackDnsSuffix("api.aws") - .supportsFips(true) - .supportsDualStack(true) - .implicitGlobalRegion("us-east-1") - .build() + Partitions.builder() + .addPartition( + Partition.builder() + .id("aws") + .regionRegex("^(us|eu|ap|sa|ca|me|af)-\\w+-\\d+$") + .outputs( + PartitionOutputs.builder() + .name("aws") + .dnsSuffix("amazonaws.com") + .dualStackDnsSuffix("api.aws") + .supportsFips(true) + .supportsDualStack(true) + .implicitGlobalRegion("us-east-1") + .build() + ) + .build() ) .build() - ) - .build() ); result = evalWithRegion("us-west-1"); @@ -75,9 +75,9 @@ public void overridesPartitions() { // Set the partitions back to what they were. AwsPartition.overridePartitions( - Partitions.fromNode( - Node.parse(Partitions.class.getResourceAsStream("partitions.json")) - ) + Partitions.fromNode( + Node.parse(Partitions.class.getResourceAsStream("partitions.json")) + ) ); } diff --git a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/FunctionsTest.java b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/FunctionsTest.java index 6de240bd1a9..cba7b7cf956 100644 --- a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/FunctionsTest.java +++ b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/FunctionsTest.java @@ -20,14 +20,14 @@ public void awsPartitionOfExpression() { @Test public void isVirtualHostableS3BucketOfExpression() { IsVirtualHostableS3Bucket function = IsVirtualHostableS3Bucket.ofExpressions( - Expression.of("foobar"), - true + Expression.of("foobar"), + true ); assertThat(function, instanceOf(IsVirtualHostableS3Bucket.class)); IsVirtualHostableS3Bucket function2 = IsVirtualHostableS3Bucket.ofExpressions( - Expression.of("foobar"), - Expression.of(true) + Expression.of("foobar"), + Expression.of(true) ); assertThat(function2, instanceOf(IsVirtualHostableS3Bucket.class)); } diff --git a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/IntegrationTest.java b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/IntegrationTest.java index a28b6dd63b5..f7e18cce216 100644 --- a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/IntegrationTest.java +++ b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/IntegrationTest.java @@ -27,18 +27,18 @@ public class IntegrationTest { public static List> invalidRules() throws Exception { try ( - Stream paths = Files.list( - Paths.get(IntegrationTest.class.getResource("invalid-rules/").toURI()) - ) + Stream paths = Files.list( + Paths.get(IntegrationTest.class.getResource("invalid-rules/").toURI()) + ) ) { return paths.map(path -> { try { String pathContents = IoUtils.toUtf8String(new FileInputStream(path.toFile())); Node content = Node.parseJsonWithComments( - pathContents, - path.subpath(path.getNameCount() - 2, path.getNameCount()) - .toString() - .replace("\\", "/") + pathContents, + path.subpath(path.getNameCount() - 2, path.getNameCount()) + .toString() + .replace("\\", "/") ); List commentLines = new ArrayList<>(); diff --git a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/PartitionsTest.java b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/PartitionsTest.java index cc84ab23a05..4a6183f4d0f 100644 --- a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/PartitionsTest.java +++ b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/language/functions/partition/PartitionsTest.java @@ -17,42 +17,42 @@ public void roundtripsPartitions() { Partitions parsed = Partitions.fromNode(parsedNode); Partitions expected = Partitions.builder() - .version("1.0") - .addPartition( - Partition.builder() - .id("aws") - .regionRegex("^(us|eu|ap|sa|ca|me|af)-\\w+-\\d+$") - .putRegion("ca-central-1", RegionOverride.builder().build()) - .putRegion("us-west-2", RegionOverride.builder().build()) - .outputs( - PartitionOutputs.builder() - .dnsSuffix("amazonaws.com") - .dualStackDnsSuffix("api.aws") - .supportsFips(true) - .supportsDualStack(true) - .implicitGlobalRegion("us-east-1") - .build() - ) - .build() - ) - .addPartition( - Partition.builder() - .id("aws-cn") - .regionRegex("^cn\\-\\w+\\-\\d+$") - .putRegion("cn-north-1", RegionOverride.builder().build()) - .putRegion("cn-northwest-1", RegionOverride.builder().build()) - .outputs( - PartitionOutputs.builder() - .dnsSuffix("amazonaws.com.cn") - .dualStackDnsSuffix("api.amazonwebservices.com.cn") - .supportsFips(true) - .supportsDualStack(true) - .implicitGlobalRegion("cn-northwest-1") - .build() - ) - .build() - ) - .build(); + .version("1.0") + .addPartition( + Partition.builder() + .id("aws") + .regionRegex("^(us|eu|ap|sa|ca|me|af)-\\w+-\\d+$") + .putRegion("ca-central-1", RegionOverride.builder().build()) + .putRegion("us-west-2", RegionOverride.builder().build()) + .outputs( + PartitionOutputs.builder() + .dnsSuffix("amazonaws.com") + .dualStackDnsSuffix("api.aws") + .supportsFips(true) + .supportsDualStack(true) + .implicitGlobalRegion("us-east-1") + .build() + ) + .build() + ) + .addPartition( + Partition.builder() + .id("aws-cn") + .regionRegex("^cn\\-\\w+\\-\\d+$") + .putRegion("cn-north-1", RegionOverride.builder().build()) + .putRegion("cn-northwest-1", RegionOverride.builder().build()) + .outputs( + PartitionOutputs.builder() + .dnsSuffix("amazonaws.com.cn") + .dualStackDnsSuffix("api.amazonwebservices.com.cn") + .supportsFips(true) + .supportsDualStack(true) + .implicitGlobalRegion("cn-northwest-1") + .build() + ) + .build() + ) + .build(); Node expectedNode = expected.toNode(); assertThat(parsed, equalTo(expected)); diff --git a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/DualStackOnlyEndpointsTraitTest.java b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/DualStackOnlyEndpointsTraitTest.java index 42cc662edc7..9944cf6e6f1 100644 --- a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/DualStackOnlyEndpointsTraitTest.java +++ b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/DualStackOnlyEndpointsTraitTest.java @@ -15,16 +15,16 @@ class DualStackOnlyEndpointsTraitTest { @Test public void loadsFromModel() { final Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("dualStackOnlyEndpoints.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("dualStackOnlyEndpoints.smithy")) + .assemble() + .unwrap(); Optional trait = model - .expectShape(ShapeId.from("ns.foo#Service1")) - .asServiceShape() - .get() - .getTrait(DualStackOnlyEndpointsTrait.class); + .expectShape(ShapeId.from("ns.foo#Service1")) + .asServiceShape() + .get() + .getTrait(DualStackOnlyEndpointsTrait.class); assertTrue(trait.isPresent()); } diff --git a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/EndpointModifierIndexTest.java b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/EndpointModifierIndexTest.java index 2f3d73a6ce4..53b22d892a6 100644 --- a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/EndpointModifierIndexTest.java +++ b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/EndpointModifierIndexTest.java @@ -15,10 +15,10 @@ class EndpointModifierIndexTest { @Test public void loadsFromModel() { final Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("endpointModifierIndex.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("endpointModifierIndex.smithy")) + .assemble() + .unwrap(); ShapeId service1 = getServiceShapeId(model, "ns.foo#Service1"); ShapeId service2 = getServiceShapeId(model, "ns.foo#Service2"); @@ -31,44 +31,44 @@ public void loadsFromModel() { // Assert this works if you pass in the shape as well. assertEquals(index.getEndpointModifierTraits(model.expectShape(service1)).size(), 1); assertInstanceOf( - StandardRegionalEndpointsTrait.class, - index.getEndpointModifierTraits(service1).get(StandardRegionalEndpointsTrait.ID) + StandardRegionalEndpointsTrait.class, + index.getEndpointModifierTraits(service1).get(StandardRegionalEndpointsTrait.ID) ); assertEquals(index.getEndpointModifierTraits(service2).size(), 1); assertInstanceOf( - StandardPartitionalEndpointsTrait.class, - index.getEndpointModifierTraits(service2).get(StandardPartitionalEndpointsTrait.ID) + StandardPartitionalEndpointsTrait.class, + index.getEndpointModifierTraits(service2).get(StandardPartitionalEndpointsTrait.ID) ); assertEquals(index.getEndpointModifierTraits(service3).size(), 2); assertInstanceOf( - StandardRegionalEndpointsTrait.class, - index.getEndpointModifierTraits(service3).get(StandardRegionalEndpointsTrait.ID) + StandardRegionalEndpointsTrait.class, + index.getEndpointModifierTraits(service3).get(StandardRegionalEndpointsTrait.ID) ); assertInstanceOf( - DualStackOnlyEndpointsTrait.class, - index.getEndpointModifierTraits(service3).get(DualStackOnlyEndpointsTrait.ID) + DualStackOnlyEndpointsTrait.class, + index.getEndpointModifierTraits(service3).get(DualStackOnlyEndpointsTrait.ID) ); assertEquals(index.getEndpointModifierTraits(service4).size(), 2); assertInstanceOf( - StandardPartitionalEndpointsTrait.class, - index.getEndpointModifierTraits(service4).get(StandardPartitionalEndpointsTrait.ID) + StandardPartitionalEndpointsTrait.class, + index.getEndpointModifierTraits(service4).get(StandardPartitionalEndpointsTrait.ID) ); assertInstanceOf( - RuleBasedEndpointsTrait.class, - index.getEndpointModifierTraits(service4).get(RuleBasedEndpointsTrait.ID) + RuleBasedEndpointsTrait.class, + index.getEndpointModifierTraits(service4).get(RuleBasedEndpointsTrait.ID) ); } @Test public void indexSkipsLoadingTraitsWhenDefinitionIsMissing() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("endpointModifierIndex.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("endpointModifierIndex.smithy")) + .assemble() + .unwrap(); // Remove trait shape definition from model to verify index can skip it model = model.toBuilder().removeShape(StandardRegionalEndpointsTrait.ID).build(); @@ -84,7 +84,7 @@ public void indexSkipsLoadingTraitsWhenDefinitionIsMissing() { private ShapeId getServiceShapeId(Model model, String service) { return model - .expectShape(ShapeId.from(service), ServiceShape.class) - .toShapeId(); + .expectShape(ShapeId.from(service), ServiceShape.class) + .toShapeId(); } } diff --git a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/RuleBasedEndpointsTraitTest.java b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/RuleBasedEndpointsTraitTest.java index 7aa7aa3da77..9d39448459c 100644 --- a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/RuleBasedEndpointsTraitTest.java +++ b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/RuleBasedEndpointsTraitTest.java @@ -15,16 +15,16 @@ class RuleBasedEndpointsTraitTest { @Test public void loadsFromModel() { final Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("ruleBasedEndpoints.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("ruleBasedEndpoints.smithy")) + .assemble() + .unwrap(); Optional trait = model - .expectShape(ShapeId.from("ns.foo#Service1")) - .asServiceShape() - .get() - .getTrait(RuleBasedEndpointsTrait.class); + .expectShape(ShapeId.from("ns.foo#Service1")) + .asServiceShape() + .get() + .getTrait(RuleBasedEndpointsTrait.class); assertTrue(trait.isPresent()); } diff --git a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/StandardPartitionalEndpointsTraitTest.java b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/StandardPartitionalEndpointsTraitTest.java index c06533a4981..f408285efef 100644 --- a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/StandardPartitionalEndpointsTraitTest.java +++ b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/StandardPartitionalEndpointsTraitTest.java @@ -16,10 +16,10 @@ class StandardPartitionalEndpointsTraitTest { @Test public void loadsFromModel() { final Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("standardPartitionalEndpoints.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("standardPartitionalEndpoints.smithy")) + .assemble() + .unwrap(); StandardPartitionalEndpointsTrait trait; @@ -50,10 +50,10 @@ public void loadsFromModel() { private StandardPartitionalEndpointsTrait getTraitFromService(Model model, String service) { return model - .expectShape(ShapeId.from(service)) - .asServiceShape() - .get() - .getTrait(StandardPartitionalEndpointsTrait.class) - .get(); + .expectShape(ShapeId.from(service)) + .asServiceShape() + .get() + .getTrait(StandardPartitionalEndpointsTrait.class) + .get(); } } diff --git a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/StandardRegionalEndpointsTraitTest.java b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/StandardRegionalEndpointsTraitTest.java index 2a0ed4bdf1e..cf6136cfd2a 100644 --- a/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/StandardRegionalEndpointsTraitTest.java +++ b/smithy-aws-endpoints/src/test/java/software/amazon/smithy/rulesengine/aws/traits/StandardRegionalEndpointsTraitTest.java @@ -17,10 +17,10 @@ class StandardRegionalEndpointsTraitTest { @Test public void loadsFromModel() { final Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("standardRegionalEndpoints.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("standardRegionalEndpoints.smithy")) + .assemble() + .unwrap(); StandardRegionalEndpointsTrait trait; trait = getTraitFromService(model, "ns.foo#Service1"); @@ -57,10 +57,10 @@ public void loadsFromModel() { private StandardRegionalEndpointsTrait getTraitFromService(Model model, String service) { return model - .expectShape(ShapeId.from(service)) - .asServiceShape() - .get() - .getTrait(StandardRegionalEndpointsTrait.class) - .get(); + .expectShape(ShapeId.from(service)) + .asServiceShape() + .get() + .getTrait(StandardRegionalEndpointsTrait.class) + .get(); } } diff --git a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ActionResource.java b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ActionResource.java index 1db2c88ab22..193bb9f7610 100644 --- a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ActionResource.java +++ b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ActionResource.java @@ -44,8 +44,8 @@ public static Builder builder() { public static ActionResource fromNode(Node value) { Builder builder = builder(); value.expectObjectNode() - .warnIfAdditionalProperties(Collections.singletonList(CONDITION_KEYS)) - .getArrayMember(CONDITION_KEYS, StringNode::getValue, builder::conditionKeys); + .warnIfAdditionalProperties(Collections.singletonList(CONDITION_KEYS)) + .getArrayMember(CONDITION_KEYS, StringNode::getValue, builder::conditionKeys); return builder.build(); } diff --git a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ActionResources.java b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ActionResources.java index 3406c4e65fd..741a19c8bee 100644 --- a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ActionResources.java +++ b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ActionResources.java @@ -56,7 +56,7 @@ private static Builder builder() { public static ActionResources fromNode(Node value) { Builder builder = builder(); ObjectNode node = value.expectObjectNode() - .warnIfAdditionalProperties(ListUtils.of(REQUIRED, OPTIONAL)); + .warnIfAdditionalProperties(ListUtils.of(REQUIRED, OPTIONAL)); if (node.containsMember(REQUIRED)) { for (Map.Entry entry : node.expectObjectMember(REQUIRED).getStringMap().entrySet()) { builder.putRequired(entry.getKey(), ActionResource.fromNode(entry.getValue())); @@ -104,7 +104,7 @@ public boolean equals(Object o) { } ActionResources that = (ActionResources) o; return Objects.equals(required, that.required) - && Objects.equals(optional, that.optional); + && Objects.equals(optional, that.optional); } @Override diff --git a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ConditionKeyDefinition.java b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ConditionKeyDefinition.java index d2072b408c6..a981f542568 100644 --- a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ConditionKeyDefinition.java +++ b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ConditionKeyDefinition.java @@ -42,19 +42,19 @@ public static Builder builder() { public static ConditionKeyDefinition fromNode(Node value) { ObjectNode objectNode = value.expectObjectNode(); Builder builder = builder() - .type(objectNode.expectStringMember(TYPE).getValue()); + .type(objectNode.expectStringMember(TYPE).getValue()); objectNode.getStringMember(DOCUMENTATION) - .map(StringNode::getValue) - .ifPresent(builder::documentation); + .map(StringNode::getValue) + .ifPresent(builder::documentation); objectNode.getStringMember(EXTERNAL_DOCUMENTATION) - .map(StringNode::getValue) - .ifPresent(builder::externalDocumentation); + .map(StringNode::getValue) + .ifPresent(builder::externalDocumentation); objectNode.getStringMember(RELATIVE_DOCUMENTATION) - .map(StringNode::getValue) - .ifPresent(builder::relativeDocumentation); + .map(StringNode::getValue) + .ifPresent(builder::relativeDocumentation); objectNode.getBooleanMember(REQUIRED) - .map(BooleanNode::getValue) - .ifPresent(builder::required); + .map(BooleanNode::getValue) + .ifPresent(builder::required); return builder.build(); } @@ -103,22 +103,22 @@ public boolean isRequired() { @Override public Builder toBuilder() { return builder() - .documentation(documentation) - .externalDocumentation(externalDocumentation) - .relativeDocumentation(relativeDocumentation) - .type(type) - .required(required); + .documentation(documentation) + .externalDocumentation(externalDocumentation) + .relativeDocumentation(relativeDocumentation) + .type(type) + .required(required); } @Override public Node toNode() { return Node.objectNodeBuilder() - .withMember(TYPE, Node.from(type)) - .withOptionalMember(DOCUMENTATION, getDocumentation().map(Node::from)) - .withOptionalMember(EXTERNAL_DOCUMENTATION, getExternalDocumentation().map(Node::from)) - .withOptionalMember(RELATIVE_DOCUMENTATION, getRelativeDocumentation().map(Node::from)) - .withMember(REQUIRED, isRequired()) - .build(); + .withMember(TYPE, Node.from(type)) + .withOptionalMember(DOCUMENTATION, getDocumentation().map(Node::from)) + .withOptionalMember(EXTERNAL_DOCUMENTATION, getExternalDocumentation().map(Node::from)) + .withOptionalMember(RELATIVE_DOCUMENTATION, getRelativeDocumentation().map(Node::from)) + .withMember(REQUIRED, isRequired()) + .build(); } @Override @@ -131,10 +131,10 @@ public boolean equals(Object o) { ConditionKeyDefinition that = (ConditionKeyDefinition) o; return Objects.equals(type, that.type) - && Objects.equals(documentation, that.documentation) - && Objects.equals(externalDocumentation, that.externalDocumentation) - && Objects.equals(relativeDocumentation, that.relativeDocumentation) - && Objects.equals(required, that.required); + && Objects.equals(documentation, that.documentation) + && Objects.equals(externalDocumentation, that.externalDocumentation) + && Objects.equals(relativeDocumentation, that.relativeDocumentation) + && Objects.equals(required, that.required); } @Override diff --git a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ConditionKeysIndex.java b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ConditionKeysIndex.java index e3deb9550f4..9a55d4be5a8 100644 --- a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ConditionKeysIndex.java +++ b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ConditionKeysIndex.java @@ -97,10 +97,10 @@ public Map getDefinedConditionKeys(ToShapeId ser */ public Set getConditionKeyNames(ToShapeId service) { return resourceConditionKeys.getOrDefault(service.toShapeId(), MapUtils.of()) - .values() - .stream() - .flatMap(Set::stream) - .collect(SetUtils.toUnmodifiableSet()); + .values() + .stream() + .flatMap(Set::stream) + .collect(SetUtils.toUnmodifiableSet()); } /** @@ -115,7 +115,7 @@ public Set getConditionKeyNames(ToShapeId service, ToShapeId resourceOrO ShapeId serviceId = service.toShapeId(); ShapeId subjectId = resourceOrOperation.toShapeId(); return Collections.unmodifiableSet( - resourceConditionKeys.getOrDefault(serviceId, MapUtils.of()).getOrDefault(subjectId, SetUtils.of()) + resourceConditionKeys.getOrDefault(serviceId, MapUtils.of()).getOrDefault(subjectId, SetUtils.of()) ); } @@ -132,8 +132,8 @@ public Set getConditionKeyNames(ToShapeId service, ToShapeId resourceOrO * @return Returns the conditions keys of the service or an empty map when not found. */ public Map getDefinedConditionKeys( - ToShapeId service, - ToShapeId resourceOrOperation + ToShapeId service, + ToShapeId resourceOrOperation ) { Map serviceDefinitions = getDefinedConditionKeys(service); Map definitions = new HashMap<>(); @@ -148,26 +148,26 @@ public Map getDefinedConditionKeys( } private void compute( - Model model, - ServiceShape service, - String arnRoot, - Shape subject, - ResourceShape parent + Model model, + ServiceShape service, + String arnRoot, + Shape subject, + ResourceShape parent ) { compute(model, service, arnRoot, subject, parent, SetUtils.of()); } private void compute( - Model model, - ServiceShape service, - String arnRoot, - Shape subject, - ResourceShape parent, - Set parentDefinitions + Model model, + ServiceShape service, + String arnRoot, + Shape subject, + ResourceShape parent, + Set parentDefinitions ) { Set definitions = new HashSet<>(); if (!subject.hasTrait(IamResourceTrait.ID) - || !subject.expectTrait(IamResourceTrait.class).isDisableConditionKeyInheritance() + || !subject.expectTrait(IamResourceTrait.class).isDisableConditionKeyInheritance() ) { definitions.addAll(parentDefinitions); } @@ -177,18 +177,18 @@ private void compute( // Continue recursing into resources and computing keys. subject.asResourceShape().ifPresent(resource -> { boolean disableConditionKeyInference = resource.hasTrait(DisableConditionKeyInferenceTrait.class) - || service.hasTrait(DisableConditionKeyInferenceTrait.class); + || service.hasTrait(DisableConditionKeyInferenceTrait.class); // Add any inferred resource identifiers to the resource and to the service-wide definitions. Map childIdentifiers = !disableConditionKeyInference - ? inferChildResourceIdentifiers(model, service.getId(), arnRoot, resource, parent) - : MapUtils.of(); + ? inferChildResourceIdentifiers(model, service.getId(), arnRoot, resource, parent) + : MapUtils.of(); // Compute the keys of each child operation, passing no keys. resource.getAllOperations() - .stream() - .flatMap(id -> OptionalUtils.stream(model.getShape(id))) - .forEach(child -> compute(model, service, arnRoot, child, resource)); + .stream() + .flatMap(id -> OptionalUtils.stream(model.getShape(id))) + .forEach(child -> compute(model, service, arnRoot, child, resource)); // Child resources always inherit the identifiers of the parent. definitions.addAll(childIdentifiers.values()); @@ -201,11 +201,11 @@ private void compute( } private Map inferChildResourceIdentifiers( - Model model, - ShapeId service, - String arnRoot, - ResourceShape resource, - ResourceShape parent + Model model, + ShapeId service, + String arnRoot, + ResourceShape resource, + ResourceShape parent ) { Map result = new HashMap<>(); @@ -230,9 +230,9 @@ private Map inferChildResourceIdentifiers( // Inline provided documentation or compute a simple string. builder.documentation( - shape.getTrait(DocumentationTrait.class) - .map(DocumentationTrait::getValue) - .orElse(computeIdentifierDocs(resource, childId)) + shape.getTrait(DocumentationTrait.class) + .map(DocumentationTrait::getValue) + .orElse(computeIdentifierDocs(resource, childId)) ); // The identifier name is comprised of "[arn service]:[Resource name][uppercase identifier name] String computeIdentifierName = computeIdentifierName(arnRoot, resource, childId); @@ -256,7 +256,7 @@ private static String computeIdentifierName(String arnRoot, ResourceShape resour private static String getContextKeyResourceName(ResourceShape resource) { return resource.getTrait(IamResourceTrait.class) - .flatMap(IamResourceTrait::getName) - .orElse(resource.getId().getName()); + .flatMap(IamResourceTrait::getName) + .orElse(resource.getId().getName()); } } diff --git a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ConditionKeysValidator.java b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ConditionKeysValidator.java index 1c985b43727..baa91d7b980 100644 --- a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ConditionKeysValidator.java +++ b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/ConditionKeysValidator.java @@ -40,105 +40,105 @@ public List validate(Model model) { OperationIndex operationIndex = OperationIndex.of(model); return model.shapes(ServiceShape.class) - .filter(service -> service.hasTrait(ServiceTrait.class)) - .flatMap(service -> { - List results = new ArrayList<>(); - Set knownKeys = conditionIndex.getDefinedConditionKeys(service).keySet(); - Set serviceResolvedKeys = Collections.emptySet(); + .filter(service -> service.hasTrait(ServiceTrait.class)) + .flatMap(service -> { + List results = new ArrayList<>(); + Set knownKeys = conditionIndex.getDefinedConditionKeys(service).keySet(); + Set serviceResolvedKeys = Collections.emptySet(); - if (service.hasTrait(ServiceResolvedConditionKeysTrait.class)) { - ServiceResolvedConditionKeysTrait trait = service.expectTrait( - ServiceResolvedConditionKeysTrait.class - ); - //assign so we can compare against condition key values for any intersection - serviceResolvedKeys = new HashSet<>(trait.getValues()); - //copy as this is a destructive action and will affect all future access - List invalidNames = new ArrayList<>(trait.getValues()); - invalidNames.removeAll(knownKeys); - if (!invalidNames.isEmpty()) { - results.add( - error( - service, - trait, - String.format( - "This condition keys resolved by the `%s` service " - + "refer to undefined " - + "condition key(s) [%s]. Expected one of the following " - + "defined condition keys: [%s]", - service.getId(), - ValidationUtils.tickedList(invalidNames), - ValidationUtils.tickedList(knownKeys) - ) - ) + if (service.hasTrait(ServiceResolvedConditionKeysTrait.class)) { + ServiceResolvedConditionKeysTrait trait = service.expectTrait( + ServiceResolvedConditionKeysTrait.class ); - } - } - - for (OperationShape operation : topDownIndex.getContainedOperations(service)) { - for (String name : conditionIndex.getConditionKeyNames(service, operation)) { - if (!knownKeys.contains(name) && !name.startsWith("aws:")) { + //assign so we can compare against condition key values for any intersection + serviceResolvedKeys = new HashSet<>(trait.getValues()); + //copy as this is a destructive action and will affect all future access + List invalidNames = new ArrayList<>(trait.getValues()); + invalidNames.removeAll(knownKeys); + if (!invalidNames.isEmpty()) { results.add( - error( - operation, - String.format( - "This operation scoped within the `%s` service refers to an undefined " - + "condition key `%s`. Expected one of the following defined condition " - + "keys: [%s]", - service.getId(), - name, - ValidationUtils.tickedList(knownKeys) + error( + service, + trait, + String.format( + "This condition keys resolved by the `%s` service " + + "refer to undefined " + + "condition key(s) [%s]. Expected one of the following " + + "defined condition keys: [%s]", + service.getId(), + ValidationUtils.tickedList(invalidNames), + ValidationUtils.tickedList(knownKeys) + ) ) - ) ); } } - for (MemberShape memberShape : operationIndex.getInputMembers(operation).values()) { - if (memberShape.hasTrait(ConditionKeyValueTrait.class)) { - ConditionKeyValueTrait trait = memberShape.expectTrait(ConditionKeyValueTrait.class); - String conditionKey = trait.getValue(); - if (!knownKeys.contains(conditionKey)) { + for (OperationShape operation : topDownIndex.getContainedOperations(service)) { + for (String name : conditionIndex.getConditionKeyNames(service, operation)) { + if (!knownKeys.contains(name) && !name.startsWith("aws:")) { results.add( - error( - memberShape, - trait, - String.format( - "This operation `%s` scoped within the `%s` service with member `%s` " - + "refers to an undefined " - + "condition key `%s`. Expected one of the following defined " - + "condition keys: [%s]", - operation.getId(), - service.getId(), - memberShape.getId(), - conditionKey, - ValidationUtils.tickedList(knownKeys) + error( + operation, + String.format( + "This operation scoped within the `%s` service refers to an undefined " + + "condition key `%s`. Expected one of the following defined condition " + + "keys: [%s]", + service.getId(), + name, + ValidationUtils.tickedList(knownKeys) + ) ) - ) ); } - if (serviceResolvedKeys.contains(conditionKey)) { - results.add( - error( - memberShape, - trait, - String.format( - "This operation `%s` scoped within the `%s` service with member `%s` refers" - + " to a condition key `%s` that is also resolved by service.", - operation.getId(), - service.getId(), - memberShape.getId(), - conditionKey, - ValidationUtils.tickedList(knownKeys) - ) - ) - ); + } + + for (MemberShape memberShape : operationIndex.getInputMembers(operation).values()) { + if (memberShape.hasTrait(ConditionKeyValueTrait.class)) { + ConditionKeyValueTrait trait = memberShape.expectTrait(ConditionKeyValueTrait.class); + String conditionKey = trait.getValue(); + if (!knownKeys.contains(conditionKey)) { + results.add( + error( + memberShape, + trait, + String.format( + "This operation `%s` scoped within the `%s` service with member `%s` " + + "refers to an undefined " + + "condition key `%s`. Expected one of the following defined " + + "condition keys: [%s]", + operation.getId(), + service.getId(), + memberShape.getId(), + conditionKey, + ValidationUtils.tickedList(knownKeys) + ) + ) + ); + } + if (serviceResolvedKeys.contains(conditionKey)) { + results.add( + error( + memberShape, + trait, + String.format( + "This operation `%s` scoped within the `%s` service with member `%s` refers" + + " to a condition key `%s` that is also resolved by service.", + operation.getId(), + service.getId(), + memberShape.getId(), + conditionKey, + ValidationUtils.tickedList(knownKeys) + ) + ) + ); + } } } } - } - return results.stream(); - }) - .collect(Collectors.toList()); + return results.stream(); + }) + .collect(Collectors.toList()); } } diff --git a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/DefineConditionKeysTrait.java b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/DefineConditionKeysTrait.java index 6c67bbed965..8878a60b19b 100644 --- a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/DefineConditionKeysTrait.java +++ b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/DefineConditionKeysTrait.java @@ -44,7 +44,7 @@ public Trait createTrait(ShapeId target, Node value) { Builder builder = builder().sourceLocation(value); for (Map.Entry entry : value.expectObjectNode().getMembers().entrySet()) { ConditionKeyDefinition definition = ConditionKeyDefinition.fromNode( - entry.getValue().expectObjectNode() + entry.getValue().expectObjectNode() ); builder.putConditionKey(entry.getKey().getValue(), definition); } diff --git a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/DefineConditionKeysTraitValidator.java b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/DefineConditionKeysTraitValidator.java index 9e330f30b57..f147cdebb18 100644 --- a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/DefineConditionKeysTraitValidator.java +++ b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/DefineConditionKeysTraitValidator.java @@ -29,32 +29,32 @@ public List validate(Model model) { ConditionKeysIndex conditionKeysIndex = ConditionKeysIndex.of(model); for (ServiceShape serviceShape : model.getServiceShapes()) { for (Map.Entry conditionKeyEntry : conditionKeysIndex - .getDefinedConditionKeys(serviceShape) - .entrySet()) { + .getDefinedConditionKeys(serviceShape) + .entrySet()) { // Get all the service resolved condition keys. List serviceResolvedKeys = serviceShape.getTrait(ServiceResolvedConditionKeysTrait.class) - .map(StringListTrait::getValues) - .orElse(ListUtils.of()); + .map(StringListTrait::getValues) + .orElse(ListUtils.of()); // We want to emit an event for definitions that state being required... if (conditionKeyEntry.getValue().isRequired() - // and are not configured to be service resolved. - && !serviceResolvedKeys.contains(conditionKeyEntry.getKey()) + // and are not configured to be service resolved. + && !serviceResolvedKeys.contains(conditionKeyEntry.getKey()) ) { FromSourceLocation sourceLocation = serviceShape.getTrait(DefineConditionKeysTrait.class) - .map(Trait::getSourceLocation) - .orElse(serviceShape.getSourceLocation()); + .map(Trait::getSourceLocation) + .orElse(serviceShape.getSourceLocation()); events.add( - error( - serviceShape, - sourceLocation, - format( - "The `%s` condition key is defined as " - + "required but is resolved from the request. This property is only valid for condition " - + "keys resolved by the service, it MUST also be specified in the " - + "`@serviceResolvedConditionKeys` trait or use the `@required` trait instead.", - conditionKeyEntry.getKey() + error( + serviceShape, + sourceLocation, + format( + "The `%s` condition key is defined as " + + "required but is resolved from the request. This property is only valid for condition " + + "keys resolved by the service, it MUST also be specified in the " + + "`@serviceResolvedConditionKeys` trait or use the `@required` trait instead.", + conditionKeyEntry.getKey() + ) ) - ) ); } } diff --git a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamActionTrait.java b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamActionTrait.java index c760efef826..fe1c5280529 100644 --- a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamActionTrait.java +++ b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamActionTrait.java @@ -23,7 +23,7 @@ * Indicates properties of a Smithy operation as an IAM action. */ public final class IamActionTrait extends AbstractTrait - implements ToSmithyBuilder { + implements ToSmithyBuilder { public static final ShapeId ID = ShapeId.from("aws.iam#iamAction"); private final String name; @@ -68,12 +68,12 @@ public Optional getName() { @SuppressWarnings("deprecation") public static String resolveActionName(OperationShape operation) { return operation.getTrait(IamActionTrait.class) - .flatMap(IamActionTrait::getName) - .orElseGet( - () -> operation.getTrait(ActionNameTrait.class) - .map(ActionNameTrait::getValue) - .orElseGet(() -> operation.getId().getName()) - ); + .flatMap(IamActionTrait::getName) + .orElseGet( + () -> operation.getTrait(ActionNameTrait.class) + .map(ActionNameTrait::getValue) + .orElseGet(() -> operation.getId().getName()) + ); } /** @@ -102,16 +102,16 @@ public Optional getDocumentation() { @SuppressWarnings("deprecation") public static String resolveActionDocumentation(OperationShape operation) { return operation.getTrait(IamActionTrait.class) - .flatMap(IamActionTrait::getDocumentation) - .orElseGet( - () -> operation.getTrait(ActionPermissionDescriptionTrait.class) - .map(ActionPermissionDescriptionTrait::getValue) - .orElseGet( - () -> operation.getTrait(DocumentationTrait.class) - .map(DocumentationTrait::getValue) - .orElse(null) - ) - ); + .flatMap(IamActionTrait::getDocumentation) + .orElseGet( + () -> operation.getTrait(ActionPermissionDescriptionTrait.class) + .map(ActionPermissionDescriptionTrait::getValue) + .orElseGet( + () -> operation.getTrait(DocumentationTrait.class) + .map(DocumentationTrait::getValue) + .orElse(null) + ) + ); } /** @@ -150,13 +150,13 @@ public List getRequiredActions() { @SuppressWarnings("deprecation") public static List resolveRequiredActions(OperationShape operation) { return operation.getTrait(IamActionTrait.class) - .map(IamActionTrait::getRequiredActions) - .filter(FunctionalUtils.not(List::isEmpty)) - .orElseGet( - () -> operation.getTrait(RequiredActionsTrait.class) - .map(RequiredActionsTrait::getValues) - .orElse(ListUtils.of()) - ); + .map(IamActionTrait::getRequiredActions) + .filter(FunctionalUtils.not(List::isEmpty)) + .orElseGet( + () -> operation.getTrait(RequiredActionsTrait.class) + .map(RequiredActionsTrait::getValues) + .orElse(ListUtils.of()) + ); } /** diff --git a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamActionValidator.java b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamActionValidator.java index e8f876e9d66..5240d4aa17b 100644 --- a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamActionValidator.java +++ b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamActionValidator.java @@ -36,31 +36,31 @@ private List validateDuplicateTraits(OperationShape operation, List events = new ArrayList<>(); if (operation.hasTrait(ActionNameTrait.ID) && trait.getName().isPresent()) { events.add( - emitDeprecatedOverride( - operation, - operation.expectTrait(ActionNameTrait.class), - "name" - ) + emitDeprecatedOverride( + operation, + operation.expectTrait(ActionNameTrait.class), + "name" + ) ); } if (operation.hasTrait(ActionPermissionDescriptionTrait.ID) && trait.getDocumentation().isPresent()) { events.add( - emitDeprecatedOverride( - operation, - operation.expectTrait(ActionPermissionDescriptionTrait.class), - "documentation" - ) + emitDeprecatedOverride( + operation, + operation.expectTrait(ActionPermissionDescriptionTrait.class), + "documentation" + ) ); } if (operation.hasTrait(RequiredActionsTrait.ID) && !trait.getRequiredActions().isEmpty()) { events.add( - emitDeprecatedOverride( - operation, - operation.expectTrait(RequiredActionsTrait.class), - "requiredActions" - ) + emitDeprecatedOverride( + operation, + operation.expectTrait(RequiredActionsTrait.class), + "requiredActions" + ) ); } return events; @@ -68,23 +68,23 @@ private List validateDuplicateTraits(OperationShape operation, private ValidationEvent emitDeprecatedOverride(OperationShape operation, Trait trait, String name) { return error( - operation, - trait, - format( - "Operation has the `%s` property of the " - + "`@aws.iam#iamAction` trait set and the deprecated `@%s` trait applied.", - name, - trait.toShapeId() - ), - "ConflictingProperty", - name + operation, + trait, + format( + "Operation has the `%s` property of the " + + "`@aws.iam#iamAction` trait set and the deprecated `@%s` trait applied.", + name, + trait.toShapeId() + ), + "ConflictingProperty", + name ); } private Optional validateUniqueResourceNames(OperationShape operation, IamActionTrait trait) { if (!trait.getResources().isPresent() - || trait.getResources().get().getRequired().isEmpty() - || trait.getResources().get().getOptional().isEmpty() + || trait.getResources().get().getRequired().isEmpty() + || trait.getResources().get().getOptional().isEmpty() ) { return Optional.empty(); } @@ -96,14 +96,14 @@ private Optional validateUniqueResourceNames(OperationShape ope } return Optional.of( - danger( - operation, - trait, - "Operation has the following resource names defined as both " - + "required and optional: " + duplicateNames, - "Resources", - "DuplicateEntries" - ) + danger( + operation, + trait, + "Operation has the following resource names defined as both " + + "required and optional: " + duplicateNames, + "Resources", + "DuplicateEntries" + ) ); } } diff --git a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamResourceTrait.java b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamResourceTrait.java index 9cf58ec5287..ad149a58a0d 100644 --- a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamResourceTrait.java +++ b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamResourceTrait.java @@ -18,7 +18,7 @@ * Indicates properties of a Smithy resource in AWS IAM. */ public final class IamResourceTrait extends AbstractTrait - implements ToSmithyBuilder { + implements ToSmithyBuilder { public static final ShapeId ID = ShapeId.from("aws.iam#iamResource"); private final String name; @@ -55,8 +55,8 @@ public Optional getName() { */ public static String resolveResourceName(ResourceShape resource) { return resource.getTrait(IamResourceTrait.class) - .flatMap(IamResourceTrait::getName) - .orElse(resource.getId().getName()); + .flatMap(IamResourceTrait::getName) + .orElse(resource.getId().getName()); } /** diff --git a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamResourceTraitConflictingNameValidator.java b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamResourceTraitConflictingNameValidator.java index c03d1a477b5..53cad23c21d 100644 --- a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamResourceTraitConflictingNameValidator.java +++ b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamResourceTraitConflictingNameValidator.java @@ -30,8 +30,8 @@ public class IamResourceTraitConflictingNameValidator extends AbstractValidator public List validate(Model model) { TopDownIndex topDownIndex = TopDownIndex.of(model); return model.shapes(ServiceShape.class) - .flatMap(shape -> validateService(topDownIndex, shape).stream()) - .collect(Collectors.toList()); + .flatMap(shape -> validateService(topDownIndex, shape).stream()) + .collect(Collectors.toList()); } private List validateService(TopDownIndex topDownIndex, ServiceShape service) { @@ -42,21 +42,21 @@ private List validateService(TopDownIndex topDownIndex, Service resourceMap.computeIfAbsent(resourceName, k -> new ArrayList<>()).add(resource.getId()); } resourceMap.entrySet() - .stream() - .filter(entry -> entry.getValue().size() > 1) - .map( - entry -> error( - service, - String.format( - "Multiple IAM resources defined with the same IAM resource name is not allowed in a service " - + "closure, but found multiple resources named `%s` in the service `%s`: [%s]", - entry.getKey(), - service.getId(), - tickedList(entry.getValue()) - ) + .stream() + .filter(entry -> entry.getValue().size() > 1) + .map( + entry -> error( + service, + String.format( + "Multiple IAM resources defined with the same IAM resource name is not allowed in a service " + + "closure, but found multiple resources named `%s` in the service `%s`: [%s]", + entry.getKey(), + service.getId(), + tickedList(entry.getValue()) + ) + ) ) - ) - .forEach(events::add); + .forEach(events::add); return events; } } diff --git a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamResourceTraitValidator.java b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamResourceTraitValidator.java index 6333e940d4e..d72e32108a9 100644 --- a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamResourceTraitValidator.java +++ b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/IamResourceTraitValidator.java @@ -30,24 +30,24 @@ public List validate(Model model) { // check that the resource name is consistent between the two traits if (resource.hasTrait(ArnTrait.class)) { String resourceName = resource.expectTrait(IamResourceTrait.class) - .getName() - .orElseGet(() -> StringUtils.lowerCase(resource.getId().getName())); + .getName() + .orElseGet(() -> StringUtils.lowerCase(resource.getId().getName())); ArnTrait arnTrait = resource.expectTrait(ArnTrait.class); List arnComponents = parseArnComponents(arnTrait.getTemplate()); // Do not check for a matching resource name when the arn is marked as absolute if (!arnComponents.contains(resourceName) && !arnTrait.isAbsolute()) { results.add( - danger( - resource, - String.format( - "The `@aws.iam#iamResource` trait applied to the resource " - + "defines an IAM resource name, `%s`, that does not match the `@arn` template, " - + "`%s`, of the resource.", - resourceName, - arnTrait.getTemplate() + danger( + resource, + String.format( + "The `@aws.iam#iamResource` trait applied to the resource " + + "defines an IAM resource name, `%s`, that does not match the `@arn` template, " + + "`%s`, of the resource.", + resourceName, + arnTrait.getTemplate() + ) ) - ) ); } } diff --git a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/SupportedPrincipalTypesTrait.java b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/SupportedPrincipalTypesTrait.java index 22fe727423c..e78107da960 100644 --- a/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/SupportedPrincipalTypesTrait.java +++ b/smithy-aws-iam-traits/src/main/java/software/amazon/smithy/aws/iam/traits/SupportedPrincipalTypesTrait.java @@ -12,7 +12,7 @@ import software.amazon.smithy.utils.ToSmithyBuilder; public final class SupportedPrincipalTypesTrait extends StringListTrait - implements ToSmithyBuilder { + implements ToSmithyBuilder { public static final ShapeId ID = ShapeId.from("aws.iam#supportedPrincipalTypes"); public SupportedPrincipalTypesTrait(List principals, FromSourceLocation sourceLocation) { diff --git a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ActionNameTraitTest.java b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ActionNameTraitTest.java index 16501789067..b9ad837b08a 100644 --- a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ActionNameTraitTest.java +++ b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ActionNameTraitTest.java @@ -17,10 +17,10 @@ public class ActionNameTraitTest { @SuppressWarnings("deprecation") public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("actionname-override.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("actionname-override.smithy")) + .assemble() + .unwrap(); Shape shape = result.expectShape(ShapeId.from("smithy.example#Echo")); ActionNameTrait trait = shape.expectTrait(ActionNameTrait.class); diff --git a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ActionPermissionDescriptionTraitTest.java b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ActionPermissionDescriptionTraitTest.java index 6ec2e00f6e5..666b42376bb 100644 --- a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ActionPermissionDescriptionTraitTest.java +++ b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ActionPermissionDescriptionTraitTest.java @@ -22,9 +22,9 @@ public void createsTrait() { Node node = Node.from("Foo baz bar"); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ActionPermissionDescriptionTrait.ID, - ShapeId.from("ns.foo#foo"), - node + ActionPermissionDescriptionTrait.ID, + ShapeId.from("ns.foo#foo"), + node ); assertTrue(trait.isPresent()); diff --git a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ConditionKeyValueTraitTest.java b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ConditionKeyValueTraitTest.java index 541efe23036..85d56170269 100644 --- a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ConditionKeyValueTraitTest.java +++ b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ConditionKeyValueTraitTest.java @@ -16,10 +16,10 @@ public class ConditionKeyValueTraitTest { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("condition-key-value.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("condition-key-value.smithy")) + .assemble() + .unwrap(); Shape shape = result.expectShape(ShapeId.from("smithy.example#EchoInput$id1")); ConditionKeyValueTrait trait = shape.expectTrait(ConditionKeyValueTrait.class); diff --git a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ConditionKeysIndexTest.java b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ConditionKeysIndexTest.java index 4e2fd01046e..968d7a53be3 100644 --- a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ConditionKeysIndexTest.java +++ b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ConditionKeysIndexTest.java @@ -21,47 +21,47 @@ public class ConditionKeysIndexTest { @Test public void successfullyLoadsConditionKeys() { Model model = Model.assembler() - .addImport(getClass().getResource("successful-condition-keys.smithy")) - .discoverModels(getClass().getClassLoader()) - .assemble() - .unwrap(); + .addImport(getClass().getResource("successful-condition-keys.smithy")) + .discoverModels(getClass().getClassLoader()) + .assemble() + .unwrap(); ShapeId service = ShapeId.from("smithy.example#MyService"); ConditionKeysIndex index = ConditionKeysIndex.of(model); assertThat( - index.getConditionKeyNames(service), - containsInAnyOrder( - "aws:accountId", - "foo:baz", - "myservice:Resource1Id1", - "myservice:ResourceTwoId2", - "myservice:bar" - ) + index.getConditionKeyNames(service), + containsInAnyOrder( + "aws:accountId", + "foo:baz", + "myservice:Resource1Id1", + "myservice:ResourceTwoId2", + "myservice:bar" + ) ); assertThat( - index.getConditionKeyNames(service, ShapeId.from("smithy.example#Operation1")), - containsInAnyOrder("aws:accountId", "myservice:bar") + index.getConditionKeyNames(service, ShapeId.from("smithy.example#Operation1")), + containsInAnyOrder("aws:accountId", "myservice:bar") ); assertThat( - index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource1")), - containsInAnyOrder("aws:accountId", "foo:baz", "myservice:Resource1Id1") + index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource1")), + containsInAnyOrder("aws:accountId", "foo:baz", "myservice:Resource1Id1") ); // Note that ID1 is not duplicated but rather reused on the child operation. assertThat( - index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource2")), - containsInAnyOrder( - "aws:accountId", - "foo:baz", - "myservice:Resource1Id1", - "myservice:ResourceTwoId2" - ) + index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource2")), + containsInAnyOrder( + "aws:accountId", + "foo:baz", + "myservice:Resource1Id1", + "myservice:ResourceTwoId2" + ) ); // This resource has inheritance disabled. assertThat(index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource3")), empty()); // This resource has inheritance disabled and an explicit list provided. assertThat( - index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource4")), - contains("foo:baz") + index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource4")), + contains("foo:baz") ); // Note that while this operation binds identifiers, it contains no unique ConditionKeys to bind. assertThat(index.getConditionKeyNames(service, ShapeId.from("smithy.example#GetResource2")), is(empty())); @@ -69,105 +69,105 @@ public void successfullyLoadsConditionKeys() { // Defined context keys are assembled from the names and mapped with the definitions. assertEquals(index.getDefinedConditionKeys(service).get("foo:baz").getDocumentation().get(), "Foo baz"); assertEquals( - index.getDefinedConditionKeys(service).get("foo:baz").getRelativeDocumentation().get(), - "condition-keys.html" + index.getDefinedConditionKeys(service).get("foo:baz").getRelativeDocumentation().get(), + "condition-keys.html" ); assertThat( - index.getDefinedConditionKeys(service).get("myservice:Resource1Id1").getDocumentation(), - not(Optional.empty()) + index.getDefinedConditionKeys(service).get("myservice:Resource1Id1").getDocumentation(), + not(Optional.empty()) ); assertEquals( - index.getDefinedConditionKeys(service).get("myservice:ResourceTwoId2").getDocumentation().get(), - "This is Foo" + index.getDefinedConditionKeys(service).get("myservice:ResourceTwoId2").getDocumentation().get(), + "This is Foo" ); assertThat( - index.getDefinedConditionKeys(service, ShapeId.from("smithy.example#GetResource2")).keySet(), - is(empty()) + index.getDefinedConditionKeys(service, ShapeId.from("smithy.example#GetResource2")).keySet(), + is(empty()) ); } @Test public void disableConditionKeyInferenceForResources() { Model model = Model.assembler() - .addImport(getClass().getResource("disable-condition-key-inference-for-resources.smithy")) - .discoverModels(getClass().getClassLoader()) - .assemble() - .unwrap(); + .addImport(getClass().getResource("disable-condition-key-inference-for-resources.smithy")) + .discoverModels(getClass().getClassLoader()) + .assemble() + .unwrap(); ShapeId service = ShapeId.from("smithy.example#MyService"); ConditionKeysIndex index = ConditionKeysIndex.of(model); assertThat( - index.getConditionKeyNames(service), - containsInAnyOrder("my:service", "aws:operation1", "resource:1", "myservice:Resource1Id1") + index.getConditionKeyNames(service), + containsInAnyOrder("my:service", "aws:operation1", "resource:1", "myservice:Resource1Id1") ); // Verify inference key myservice:Resource2Id2 does not exist assertThat(index.getConditionKeyNames(service), not(contains("myservice:Resource2Id2"))); assertThat( - index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource1")), - containsInAnyOrder("resource:1", "myservice:Resource1Id1") + index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource1")), + containsInAnyOrder("resource:1", "myservice:Resource1Id1") ); assertThat( - index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource1")), - not(contains("myservice:Resource2Id2")) + index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource1")), + not(contains("myservice:Resource2Id2")) ); assertThat( - index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource2")), - containsInAnyOrder("resource:1", "myservice:Resource1Id1") + index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource2")), + containsInAnyOrder("resource:1", "myservice:Resource1Id1") ); assertThat( - index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource2")), - not(contains("myservice:Resource2Id2")) + index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource2")), + not(contains("myservice:Resource2Id2")) ); } @Test public void disableConditionKeyInferenceForService() { Model model = Model.assembler() - .addImport(getClass().getResource("disable-condition-key-inference-for-service.smithy")) - .discoverModels(getClass().getClassLoader()) - .assemble() - .unwrap(); + .addImport(getClass().getResource("disable-condition-key-inference-for-service.smithy")) + .discoverModels(getClass().getClassLoader()) + .assemble() + .unwrap(); ShapeId service = ShapeId.from("smithy.example#MyService"); ConditionKeysIndex index = ConditionKeysIndex.of(model); assertThat( - index.getConditionKeyNames(service), - containsInAnyOrder("my:service", "aws:operation1", "resource:1") + index.getConditionKeyNames(service), + containsInAnyOrder("my:service", "aws:operation1", "resource:1") ); // Verify inference key myservice:Resource1Id1 AND myservice:Resource2Id2 do not exist assertThat( - index.getConditionKeyNames(service), - not(contains("myservice:Resource1Id1", "myservice:Resource2Id2")) + index.getConditionKeyNames(service), + not(contains("myservice:Resource1Id1", "myservice:Resource2Id2")) ); assertThat( - index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource1")), - not(contains("myservice:Resource1Id1", "myservice:Resource2Id2")) + index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource1")), + not(contains("myservice:Resource1Id1", "myservice:Resource2Id2")) ); assertThat( - index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource1")), - contains("resource:1") + index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource1")), + contains("resource:1") ); assertThat( - index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource2")), - contains("resource:1") + index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource2")), + contains("resource:1") ); assertThat( - index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource2")), - not(contains("myservice:Resource1Id1", "myservice:Resource2Id2")) + index.getConditionKeyNames(service, ShapeId.from("smithy.example#Resource2")), + not(contains("myservice:Resource1Id1", "myservice:Resource2Id2")) ); } } diff --git a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/DefineConditionKeysTraitTest.java b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/DefineConditionKeysTraitTest.java index 585aa91a2b3..6deeba596de 100644 --- a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/DefineConditionKeysTraitTest.java +++ b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/DefineConditionKeysTraitTest.java @@ -17,10 +17,10 @@ public class DefineConditionKeysTraitTest { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("define-condition-keys.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("define-condition-keys.smithy")) + .assemble() + .unwrap(); Shape shape = result.expectShape(ShapeId.from("smithy.example#MyService")); DefineConditionKeysTrait trait = shape.expectTrait(DefineConditionKeysTrait.class); diff --git a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/IamActionTraitTest.java b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/IamActionTraitTest.java index 4ea27c874ba..650ba2e544d 100644 --- a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/IamActionTraitTest.java +++ b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/IamActionTraitTest.java @@ -24,10 +24,10 @@ public class IamActionTraitTest { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("iam-action.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("iam-action.smithy")) + .assemble() + .unwrap(); Shape fooOperation = result.expectShape(ID); @@ -53,10 +53,10 @@ public void loadsFromModel() { @SuppressWarnings("deprecation") public void prefersIamActionTraitName() { OperationShape op = OperationShape.builder() - .id(ID) - .addTrait(IamActionTrait.builder().name("ThisOne").build()) - .addTrait(new ActionNameTrait("Unused")) - .build(); + .id(ID) + .addTrait(IamActionTrait.builder().name("ThisOne").build()) + .addTrait(new ActionNameTrait("Unused")) + .build(); assertEquals("ThisOne", IamActionTrait.resolveActionName(op)); } @@ -65,9 +65,9 @@ public void prefersIamActionTraitName() { @SuppressWarnings("deprecation") public void usesDeprecatedActionNameTrait() { OperationShape op = OperationShape.builder() - .id(ID) - .addTrait(new ActionNameTrait("ThisOne")) - .build(); + .id(ID) + .addTrait(new ActionNameTrait("ThisOne")) + .build(); assertEquals("ThisOne", IamActionTrait.resolveActionName(op)); } @@ -83,11 +83,11 @@ public void defaultsToOperationName() { @SuppressWarnings("deprecation") public void prefersIamActionTraitDocumentation() { OperationShape op = OperationShape.builder() - .id(ID) - .addTrait(IamActionTrait.builder().documentation("ThisOne").build()) - .addTrait(new ActionPermissionDescriptionTrait("Unused")) - .addTrait(new DocumentationTrait("Unused")) - .build(); + .id(ID) + .addTrait(IamActionTrait.builder().documentation("ThisOne").build()) + .addTrait(new ActionPermissionDescriptionTrait("Unused")) + .addTrait(new DocumentationTrait("Unused")) + .build(); assertEquals("ThisOne", IamActionTrait.resolveActionDocumentation(op)); } @@ -96,10 +96,10 @@ public void prefersIamActionTraitDocumentation() { @SuppressWarnings("deprecation") public void usesDeprecatedActionPermissionDescriptionTrait() { OperationShape op = OperationShape.builder() - .id(ID) - .addTrait(new ActionPermissionDescriptionTrait("ThisOne")) - .addTrait(new DocumentationTrait("Unused")) - .build(); + .id(ID) + .addTrait(new ActionPermissionDescriptionTrait("ThisOne")) + .addTrait(new DocumentationTrait("Unused")) + .build(); assertEquals("ThisOne", IamActionTrait.resolveActionDocumentation(op)); } @@ -107,9 +107,9 @@ public void usesDeprecatedActionPermissionDescriptionTrait() { @Test public void usesDocumentationTrait() { OperationShape op = OperationShape.builder() - .id(ID) - .addTrait(new DocumentationTrait("ThisOne")) - .build(); + .id(ID) + .addTrait(new DocumentationTrait("ThisOne")) + .build(); assertEquals("ThisOne", IamActionTrait.resolveActionDocumentation(op)); } @@ -125,10 +125,10 @@ public void defaultsToNoDocumentation() { @SuppressWarnings("deprecation") public void prefersIamActionTraitRequiredActions() { OperationShape op = OperationShape.builder() - .id(ID) - .addTrait(IamActionTrait.builder().addRequiredAction("ThisOne").build()) - .addTrait(new ActionNameTrait("Unused")) - .build(); + .id(ID) + .addTrait(IamActionTrait.builder().addRequiredAction("ThisOne").build()) + .addTrait(new ActionNameTrait("Unused")) + .build(); assertThat(IamActionTrait.resolveRequiredActions(op), contains("ThisOne")); } @@ -137,9 +137,9 @@ public void prefersIamActionTraitRequiredActions() { @SuppressWarnings("deprecation") public void usesDeprecatedRequiredActionsTrait() { OperationShape op = OperationShape.builder() - .id(ID) - .addTrait(RequiredActionsTrait.builder().addValue("ThisOne").build()) - .build(); + .id(ID) + .addTrait(RequiredActionsTrait.builder().addValue("ThisOne").build()) + .build(); assertThat(IamActionTrait.resolveRequiredActions(op), contains("ThisOne")); } diff --git a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/IamResourceTraitTest.java b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/IamResourceTraitTest.java index efda27731be..42fe18ff356 100644 --- a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/IamResourceTraitTest.java +++ b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/IamResourceTraitTest.java @@ -20,18 +20,18 @@ public class IamResourceTraitTest { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("iam-resource.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("iam-resource.smithy")) + .assemble() + .unwrap(); Shape superResource = result.expectShape(ID); assertTrue(superResource.hasTrait(IamResourceTrait.class)); assertEquals(superResource.expectTrait(IamResourceTrait.class).getName().get(), "super"); assertEquals( - superResource.expectTrait(IamResourceTrait.class).getRelativeDocumentation().get(), - "API-Super.html" + superResource.expectTrait(IamResourceTrait.class).getRelativeDocumentation().get(), + "API-Super.html" ); assertFalse(superResource.expectTrait(IamResourceTrait.class).isDisableConditionKeyInheritance()); } @@ -39,9 +39,9 @@ public void loadsFromModel() { @Test public void prefersIamResourceTraitName() { ResourceShape resource = ResourceShape.builder() - .id(ID) - .addTrait(IamResourceTrait.builder().name("ThisOne").build()) - .build(); + .id(ID) + .addTrait(IamResourceTrait.builder().name("ThisOne").build()) + .build(); assertEquals("ThisOne", IamResourceTrait.resolveResourceName(resource)); } diff --git a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/RequiredActionsTraitTest.java b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/RequiredActionsTraitTest.java index 658c54b3269..c06fa577fdc 100644 --- a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/RequiredActionsTraitTest.java +++ b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/RequiredActionsTraitTest.java @@ -18,20 +18,20 @@ public class RequiredActionsTraitTest { @SuppressWarnings("deprecation") public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("required-actions.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("required-actions.smithy")) + .assemble() + .unwrap(); Shape myOperation = result.expectShape(ShapeId.from("smithy.example#MyOperation")); assertTrue(myOperation.hasTrait(RequiredActionsTrait.class)); assertThat( - myOperation.expectTrait(RequiredActionsTrait.class).getValues(), - containsInAnyOrder( - "iam:PassRole", - "ec2:RunInstances" - ) + myOperation.expectTrait(RequiredActionsTrait.class).getValues(), + containsInAnyOrder( + "iam:PassRole", + "ec2:RunInstances" + ) ); } } diff --git a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ServiceResolvedConditionKeysTraitTest.java b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ServiceResolvedConditionKeysTraitTest.java index 7f24da90348..9c1e5918d60 100644 --- a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ServiceResolvedConditionKeysTraitTest.java +++ b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/ServiceResolvedConditionKeysTraitTest.java @@ -17,10 +17,10 @@ public class ServiceResolvedConditionKeysTraitTest { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("service-resolved-condition-keys.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("service-resolved-condition-keys.smithy")) + .assemble() + .unwrap(); Shape shape = result.expectShape(ShapeId.from("smithy.example#MyService")); ServiceResolvedConditionKeysTrait trait = shape.expectTrait(ServiceResolvedConditionKeysTrait.class); diff --git a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/SupportedPrincipalTypesTraitTest.java b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/SupportedPrincipalTypesTraitTest.java index 71bea55c6d2..10cac8ed41e 100644 --- a/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/SupportedPrincipalTypesTraitTest.java +++ b/smithy-aws-iam-traits/src/test/java/software/amazon/smithy/aws/iam/traits/SupportedPrincipalTypesTraitTest.java @@ -17,30 +17,30 @@ public class SupportedPrincipalTypesTraitTest { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("supported-principal-types.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("supported-principal-types.smithy")) + .assemble() + .unwrap(); Shape myService = result.expectShape(ShapeId.from("smithy.example#MyService")); Shape myOperation = result.expectShape(ShapeId.from("smithy.example#MyOperation")); assertTrue(myService.hasTrait(SupportedPrincipalTypesTrait.class)); assertThat( - myService.expectTrait(SupportedPrincipalTypesTrait.class).getValues(), - containsInAnyOrder( - "IAMUser", - "IAMRole" - ) + myService.expectTrait(SupportedPrincipalTypesTrait.class).getValues(), + containsInAnyOrder( + "IAMUser", + "IAMRole" + ) ); assertTrue(myOperation.hasTrait(SupportedPrincipalTypesTrait.class)); assertThat( - myOperation.expectTrait(SupportedPrincipalTypesTrait.class).getValues(), - containsInAnyOrder( - "Root", - "FederatedUser" - ) + myOperation.expectTrait(SupportedPrincipalTypesTrait.class).getValues(), + containsInAnyOrder( + "Root", + "FederatedUser" + ) ); } } diff --git a/smithy-aws-smoke-test-model/src/main/java/software/amazon/smithy/aws/smoketests/model/AwsSmokeTestModel.java b/smithy-aws-smoke-test-model/src/main/java/software/amazon/smithy/aws/smoketests/model/AwsSmokeTestModel.java index b4524100731..08c6c4201cf 100644 --- a/smithy-aws-smoke-test-model/src/main/java/software/amazon/smithy/aws/smoketests/model/AwsSmokeTestModel.java +++ b/smithy-aws-smoke-test-model/src/main/java/software/amazon/smithy/aws/smoketests/model/AwsSmokeTestModel.java @@ -24,8 +24,8 @@ private AwsSmokeTestModel() { */ public static boolean hasAwsVendorParams(SmokeTestCase testCase) { return testCase.getVendorParamsShape() - .filter(AwsVendorParams.ID::equals) - .isPresent(); + .filter(AwsVendorParams.ID::equals) + .isPresent(); } /** @@ -35,8 +35,8 @@ public static boolean hasAwsVendorParams(SmokeTestCase testCase) { */ public static boolean hasS3VendorParams(SmokeTestCase testCase) { return testCase.getVendorParamsShape() - .filter(S3VendorParams.ID::equals) - .isPresent(); + .filter(S3VendorParams.ID::equals) + .isPresent(); } /** diff --git a/smithy-aws-smoke-test-model/src/main/java/software/amazon/smithy/aws/smoketests/model/BaseAwsVendorParams.java b/smithy-aws-smoke-test-model/src/main/java/software/amazon/smithy/aws/smoketests/model/BaseAwsVendorParams.java index eb94ed89152..b9d2abff98f 100644 --- a/smithy-aws-smoke-test-model/src/main/java/software/amazon/smithy/aws/smoketests/model/BaseAwsVendorParams.java +++ b/smithy-aws-smoke-test-model/src/main/java/software/amazon/smithy/aws/smoketests/model/BaseAwsVendorParams.java @@ -27,14 +27,14 @@ public abstract class BaseAwsVendorParams { BaseAwsVendorParams(ObjectNode node) { this.region = node.getStringMemberOrDefault("region", DEFAULT_REGION); this.sigv4aRegionSet = node.getArrayMember("sigv4aRegionSet") - .map(a -> a.getElementsAs(el -> el.expectStringNode().getValue())) - .orElse(null); + .map(a -> a.getElementsAs(el -> el.expectStringNode().getValue())) + .orElse(null); this.uri = node.getStringMemberOrDefault("uri", null); this.useFips = node.getBooleanMemberOrDefault("useFips", DEFAULT_USE_FIPS); this.useDualstack = node.getBooleanMemberOrDefault("useDualstack", DEFAULT_USE_DUALSTACK); this.useAccountIdRouting = node.getBooleanMemberOrDefault( - "useAccountIdRouting", - DEFAULT_USE_ACCOUNT_ID_ROUTING + "useAccountIdRouting", + DEFAULT_USE_ACCOUNT_ID_ROUTING ); } diff --git a/smithy-aws-smoke-test-model/src/main/java/software/amazon/smithy/aws/smoketests/model/S3VendorParams.java b/smithy-aws-smoke-test-model/src/main/java/software/amazon/smithy/aws/smoketests/model/S3VendorParams.java index 33fb27c520e..de28e20f107 100644 --- a/smithy-aws-smoke-test-model/src/main/java/software/amazon/smithy/aws/smoketests/model/S3VendorParams.java +++ b/smithy-aws-smoke-test-model/src/main/java/software/amazon/smithy/aws/smoketests/model/S3VendorParams.java @@ -32,8 +32,8 @@ public final class S3VendorParams extends BaseAwsVendorParams { this.forcePathStyle = node.getBooleanMemberOrDefault("forcePathStyle", DEFAULT_FORCE_PATH_STYLE); this.useArnRegion = node.getBooleanMemberOrDefault("useArnRegion", DEFAULT_USE_ARN_REGION); this.useMultiRegionAccessPoints = node.getBooleanMemberOrDefault( - "useMultiRegionAccessPoints", - DEFAULT_USE_MULTI_REGION_ACCESS_POINTS + "useMultiRegionAccessPoints", + DEFAULT_USE_MULTI_REGION_ACCESS_POINTS ); } diff --git a/smithy-aws-smoke-test-model/src/test/java/software/amazon/smithy/aws/smoketests/model/AwsSmokeTestModelTest.java b/smithy-aws-smoke-test-model/src/test/java/software/amazon/smithy/aws/smoketests/model/AwsSmokeTestModelTest.java index 788859227fc..9ba2d14df46 100644 --- a/smithy-aws-smoke-test-model/src/test/java/software/amazon/smithy/aws/smoketests/model/AwsSmokeTestModelTest.java +++ b/smithy-aws-smoke-test-model/src/test/java/software/amazon/smithy/aws/smoketests/model/AwsSmokeTestModelTest.java @@ -22,16 +22,16 @@ public class AwsSmokeTestModelTest { @Test public void determinesIfTestCaseHasAwsVendorParams() { SmokeTestCase withAwsVendorParamsShape = SmokeTestCase.builder() - .id("foo") - .expectation(Expectation.success()) - .vendorParamsShape(AwsVendorParams.ID) - .build(); + .id("foo") + .expectation(Expectation.success()) + .vendorParamsShape(AwsVendorParams.ID) + .build(); SmokeTestCase withNoVendorParamsShape = withAwsVendorParamsShape.toBuilder() - .vendorParamsShape(null) - .build(); + .vendorParamsShape(null) + .build(); SmokeTestCase withOtherVendorParamsShape = withNoVendorParamsShape.toBuilder() - .vendorParamsShape(S3VendorParams.ID) - .build(); + .vendorParamsShape(S3VendorParams.ID) + .build(); assertThat(AwsSmokeTestModel.hasAwsVendorParams(withAwsVendorParamsShape), is(true)); assertThat(AwsSmokeTestModel.hasAwsVendorParams(withNoVendorParamsShape), is(false)); @@ -41,16 +41,16 @@ public void determinesIfTestCaseHasAwsVendorParams() { @Test public void determinesIfTestCaseHasS3VendorParams() { SmokeTestCase withS3VendorParamsShape = SmokeTestCase.builder() - .id("foo") - .expectation(Expectation.success()) - .vendorParamsShape(S3VendorParams.ID) - .build(); + .id("foo") + .expectation(Expectation.success()) + .vendorParamsShape(S3VendorParams.ID) + .build(); SmokeTestCase withNoVendorParamsShape = withS3VendorParamsShape.toBuilder() - .vendorParamsShape(null) - .build(); + .vendorParamsShape(null) + .build(); SmokeTestCase withOtherVendorParamsShape = withNoVendorParamsShape.toBuilder() - .vendorParamsShape(AwsVendorParams.ID) - .build(); + .vendorParamsShape(AwsVendorParams.ID) + .build(); assertThat(AwsSmokeTestModel.hasS3VendorParams(withS3VendorParamsShape), is(true)); assertThat(AwsSmokeTestModel.hasS3VendorParams(withNoVendorParamsShape), is(false)); @@ -60,16 +60,16 @@ public void determinesIfTestCaseHasS3VendorParams() { @Test public void canGetAwsVendorParamsFromTestCase() { SmokeTestCase withoutVendorParams = SmokeTestCase.builder() - .id("foo") - .expectation(Expectation.success()) - .vendorParamsShape(AwsVendorParams.ID) - .build(); + .id("foo") + .expectation(Expectation.success()) + .vendorParamsShape(AwsVendorParams.ID) + .build(); SmokeTestCase withNoVendorParamsShape = withoutVendorParams.toBuilder() - .vendorParamsShape(null) - .build(); + .vendorParamsShape(null) + .build(); SmokeTestCase withOtherVendorParamsShape = withNoVendorParamsShape.toBuilder() - .vendorParamsShape(S3VendorParams.ID) - .build(); + .vendorParamsShape(S3VendorParams.ID) + .build(); assertThat(AwsSmokeTestModel.getAwsVendorParams(withoutVendorParams), not(equalTo(Optional.empty()))); assertThat(AwsSmokeTestModel.getAwsVendorParams(withNoVendorParamsShape), equalTo(Optional.empty())); @@ -79,11 +79,11 @@ public void canGetAwsVendorParamsFromTestCase() { @Test public void fillsInDefaultsForAwsVendorParams() { AwsVendorParams vendorParams = AwsSmokeTestModel.getAwsVendorParams( - SmokeTestCase.builder() - .id("foo") - .expectation(Expectation.success()) - .vendorParamsShape(AwsVendorParams.ID) - .build() + SmokeTestCase.builder() + .id("foo") + .expectation(Expectation.success()) + .vendorParamsShape(AwsVendorParams.ID) + .build() ).get(); assertThat(vendorParams.getRegion(), equalTo("us-west-2")); @@ -97,11 +97,11 @@ public void fillsInDefaultsForAwsVendorParams() { @Test public void fillsInDefaultsForS3VendorParams() { S3VendorParams vendorParams = AwsSmokeTestModel.getS3VendorParams( - SmokeTestCase.builder() - .id("foo") - .expectation(Expectation.success()) - .vendorParamsShape(S3VendorParams.ID) - .build() + SmokeTestCase.builder() + .id("foo") + .expectation(Expectation.success()) + .vendorParamsShape(S3VendorParams.ID) + .build() ).get(); assertThat(vendorParams.getRegion(), equalTo("us-west-2")); @@ -121,16 +121,16 @@ public void fillsInDefaultsForS3VendorParams() { @Test public void loadsAwsVendorParamsFromModel() { Model model = Model.assembler() - .discoverModels() - .addImport(getClass().getResource("vendor-params.smithy")) - .assemble() - .unwrap(); + .discoverModels() + .addImport(getClass().getResource("vendor-params.smithy")) + .assemble() + .unwrap(); SmokeTestsTrait trait = model.expectShape(ShapeId.from("com.foo#GetFoo")).expectTrait(SmokeTestsTrait.class); SmokeTestCase awsCase = trait.getTestCases() - .stream() - .filter(testCase -> testCase.getId().equals("AwsVendorParamsCase")) - .findAny() - .get(); + .stream() + .filter(testCase -> testCase.getId().equals("AwsVendorParamsCase")) + .findAny() + .get(); assertThat(AwsSmokeTestModel.hasAwsVendorParams(awsCase), is(true)); assertThat(AwsSmokeTestModel.getAwsVendorParams(awsCase), not(equalTo(Optional.empty()))); @@ -147,17 +147,17 @@ public void loadsAwsVendorParamsFromModel() { @Test public void loadsS3VendorParamsFromModel() { Model model = Model.assembler() - .discoverModels() - .addImport(getClass().getResource("vendor-params.smithy")) - .assemble() - .unwrap(); + .discoverModels() + .addImport(getClass().getResource("vendor-params.smithy")) + .assemble() + .unwrap(); SmokeTestCase s3Case = model.expectShape(ShapeId.from("com.foo#GetFoo")) - .expectTrait(SmokeTestsTrait.class) - .getTestCases() - .stream() - .filter(testCase -> testCase.getId().equals("S3VendorParamsCase")) - .findAny() - .get(); + .expectTrait(SmokeTestsTrait.class) + .getTestCases() + .stream() + .filter(testCase -> testCase.getId().equals("S3VendorParamsCase")) + .findAny() + .get(); assertThat(AwsSmokeTestModel.hasS3VendorParams(s3Case), is(true)); assertThat(AwsSmokeTestModel.getS3VendorParams(s3Case), not(equalTo(Optional.empty()))); diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnIndex.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnIndex.java index 2a4e397f3f1..6d341ffbfec 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnIndex.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnIndex.java @@ -43,13 +43,13 @@ public ArnIndex(Model model) { // Pre-compute all of the ARN templates in a service shape. TopDownIndex topDownIndex = TopDownIndex.of(model); List services = model.shapes(ServiceShape.class) - .filter(shape -> shape.hasTrait(ServiceTrait.class)) - .collect(Collectors.toList()); + .filter(shape -> shape.hasTrait(ServiceTrait.class)) + .collect(Collectors.toList()); templates = unmodifiableMap( - services.stream() - .map(service -> compileServiceArns(topDownIndex, service)) - .collect(Collectors.toMap(Pair::getLeft, Pair::getRight)) + services.stream() + .map(service -> compileServiceArns(topDownIndex, service)) + .collect(Collectors.toMap(Pair::getLeft, Pair::getRight)) ); // Pre-compute all effective ARNs in each service. @@ -75,9 +75,9 @@ private Pair> compileServiceArns(TopDownIndex in } private void compileEffectiveArns( - TopDownIndex index, - IdentifierBindingIndex bindings, - ServiceShape service + TopDownIndex index, + IdentifierBindingIndex bindings, + ServiceShape service ) { Map operationMappings = new HashMap<>(); effectiveArns.put(service.getId(), operationMappings); @@ -97,7 +97,7 @@ private void compileEffectiveArns( for (ResourceShape resource : index.getContainedResources(service)) { if (resource.getResources().contains(entry.getKey())) { resource.getTrait(ArnTrait.class) - .ifPresent(trait -> operationMappings.put(operation.getId(), trait)); + .ifPresent(trait -> operationMappings.put(operation.getId(), trait)); } } } @@ -114,8 +114,8 @@ private void compileEffectiveArns( */ public String getServiceArnNamespace(ToShapeId serviceId) { return arnServices.containsKey(serviceId.toShapeId()) - ? arnServices.get(serviceId.toShapeId()) - : serviceId.toShapeId().getName().toLowerCase(Locale.US); + ? arnServices.get(serviceId.toShapeId()) + : serviceId.toShapeId().getName().toLowerCase(Locale.US); } /** @@ -144,7 +144,7 @@ public Map getServiceResourceArns(ToShapeId service) { */ public Optional getEffectiveOperationArn(ToShapeId service, ToShapeId operation) { return Optional.ofNullable(effectiveArns.get(service.toShapeId())) - .flatMap(operationArns -> Optional.ofNullable(operationArns.get(operation.toShapeId()))); + .flatMap(operationArns -> Optional.ofNullable(operationArns.get(operation.toShapeId()))); } /** @@ -170,24 +170,24 @@ public Optional getEffectiveOperationArn(ToShapeId service, ToShapeId */ public Optional getFullResourceArnTemplate(ToShapeId service, ToShapeId resource) { return Optional.ofNullable(getServiceResourceArns(service).get(resource.toShapeId())) - .map(trait -> { - StringBuilder result = new StringBuilder(); - if (!trait.isAbsolute()) { - result.append("arn:") - .append("{AWS::Partition}:") - .append(getServiceArnNamespace(service)) - .append(":"); - if (!trait.isNoRegion()) { - result.append("{AWS::Region}"); - } - result.append(":"); - if (!trait.isNoAccount()) { - result.append("{AWS::AccountId}"); + .map(trait -> { + StringBuilder result = new StringBuilder(); + if (!trait.isAbsolute()) { + result.append("arn:") + .append("{AWS::Partition}:") + .append(getServiceArnNamespace(service)) + .append(":"); + if (!trait.isNoRegion()) { + result.append("{AWS::Region}"); + } + result.append(":"); + if (!trait.isNoAccount()) { + result.append("{AWS::AccountId}"); + } + result.append(":"); } - result.append(":"); - } - return result.append(trait.getTemplate()).toString(); - }); + return result.append(trait.getTemplate()).toString(); + }); } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnReferenceTrait.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnReferenceTrait.java index 550ab23c164..6f1b46f0d07 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnReferenceTrait.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnReferenceTrait.java @@ -46,14 +46,14 @@ public Trait createTrait(ShapeId target, Node value) { ObjectNode objectNode = value.expectObjectNode(); Builder builder = builder().sourceLocation(value); objectNode.getStringMember(TYPE) - .map(StringNode::getValue) - .ifPresent(builder::type); + .map(StringNode::getValue) + .ifPresent(builder::type); objectNode.getStringMember(SERVICE) - .map(stringNode -> stringNode.expectShapeId(target.getNamespace())) - .ifPresent(builder::service); + .map(stringNode -> stringNode.expectShapeId(target.getNamespace())) + .ifPresent(builder::service); objectNode.getStringMember(RESOURCE) - .map(stringNode -> stringNode.expectShapeId(target.getNamespace())) - .ifPresent(builder::resource); + .map(stringNode -> stringNode.expectShapeId(target.getNamespace())) + .ifPresent(builder::resource); ArnReferenceTrait result = builder.build(); result.setNodeCache(value); return result; @@ -94,20 +94,20 @@ public Optional getService() { @Override public Builder toBuilder() { return new Builder() - .sourceLocation(getSourceLocation()) - .type(type) - .service(service) - .resource(resource); + .sourceLocation(getSourceLocation()) + .type(type) + .service(service) + .resource(resource); } @Override protected Node createNode() { return Node.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withOptionalMember(TYPE, getType().map(Node::from)) - .withOptionalMember(SERVICE, getService().map(ShapeId::toString).map(Node::from)) - .withOptionalMember(RESOURCE, getResource().map(ShapeId::toString).map(Node::from)) - .build(); + .sourceLocation(getSourceLocation()) + .withOptionalMember(TYPE, getType().map(Node::from)) + .withOptionalMember(SERVICE, getService().map(ShapeId::toString).map(Node::from)) + .withOptionalMember(RESOURCE, getResource().map(ShapeId::toString).map(Node::from)) + .build(); } // Due to the defaulting of this trait, equals has to be overridden @@ -121,8 +121,8 @@ public boolean equals(Object other) { } else { ArnReferenceTrait ot = (ArnReferenceTrait) other; return Objects.equals(type, ot.type) - && Objects.equals(service, ot.service) - && Objects.equals(resource, ot.resource); + && Objects.equals(service, ot.service) + && Objects.equals(resource, ot.resource); } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnTemplateValidator.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnTemplateValidator.java index 06bd43cd7ce..d9763e5c643 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnTemplateValidator.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnTemplateValidator.java @@ -68,25 +68,25 @@ private List validateResourceArn(ResourceShape resource, ArnTra // Validates the syntax of each template. private Optional syntax(Shape shape, ArnTrait trait) { List invalid = trait.getLabels() - .stream() - .filter(expr -> !EXPRESSION_PATTERN.matcher(expr).find()) - .collect(toList()); + .stream() + .filter(expr -> !EXPRESSION_PATTERN.matcher(expr).find()) + .collect(toList()); if (invalid.isEmpty()) { return Optional.empty(); } return Optional.of( - error( - shape, - trait, - String.format( - "aws.api#arn trait contains invalid template labels: %s. Template labels must match the " - + "following regular expression: %s", - tickedList(invalid), - EXPRESSION_PATTERN.pattern() + error( + shape, + trait, + String.format( + "aws.api#arn trait contains invalid template labels: %s. Template labels must match the " + + "following regular expression: %s", + tickedList(invalid), + EXPRESSION_PATTERN.pattern() + ) ) - ) ); } @@ -96,17 +96,17 @@ private Optional tooMuch(Collection names, Shape shape, templateCheck.removeAll(names); if (!templateCheck.isEmpty()) { return Optional.of( - error( - shape, - trait, - String.format( - "Invalid aws.api#arn trait resource, `%s`. Found template labels in the trait " - + "that are not the names of the identifiers of the resource: %s. Extraneous identifiers: [%s]", - trait.getTemplate(), - names, - tickedList(templateCheck) + error( + shape, + trait, + String.format( + "Invalid aws.api#arn trait resource, `%s`. Found template labels in the trait " + + "that are not the names of the identifiers of the resource: %s. Extraneous identifiers: [%s]", + trait.getTemplate(), + names, + tickedList(templateCheck) + ) ) - ) ); } return Optional.empty(); @@ -118,16 +118,16 @@ private Optional enough(Collection names, Shape shape, identifierVars.removeAll(trait.getLabels()); if (!identifierVars.isEmpty()) { return Optional.of( - error( - shape, - trait, - String.format( - "Invalid aws.api#arn trait resource, `%s`. The following resource identifier names " - + "were missing from the `arn` template: %s", - trait.getTemplate(), - tickedList(identifierVars) + error( + shape, + trait, + String.format( + "Invalid aws.api#arn trait resource, `%s`. The following resource identifier names " + + "were missing from the `arn` template: %s", + trait.getTemplate(), + tickedList(identifierVars) + ) ) - ) ); } return Optional.empty(); diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnTrait.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnTrait.java index 1ee0621107c..7c9fcb9669d 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnTrait.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnTrait.java @@ -57,9 +57,9 @@ private ArnTrait(Builder builder) { if (template.startsWith("/")) { throw new SourceException( - "Invalid aws.api#arn trait. The template must not start with '/'. " - + "Found `" + template + "`", - getSourceLocation() + "Invalid aws.api#arn trait. The template must not start with '/'. " + + "Found `" + template + "`", + getSourceLocation() ); } } @@ -153,26 +153,26 @@ public boolean isReusable() { @Override protected Node createNode() { return Node.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withMember(TEMPLATE, Node.from(getTemplate())) - .withMember(ABSOLUTE, Node.from(isAbsolute())) - .withMember(NO_ACCOUNT, Node.from(isNoAccount())) - .withMember(NO_REGION, Node.from(isNoRegion())) - .withOptionalMember(RESOURCE_DELIMITER, getResourceDelimiter()) - .withMember(REUSABLE, Node.from(isReusable())) - .build(); + .sourceLocation(getSourceLocation()) + .withMember(TEMPLATE, Node.from(getTemplate())) + .withMember(ABSOLUTE, Node.from(isAbsolute())) + .withMember(NO_ACCOUNT, Node.from(isNoAccount())) + .withMember(NO_REGION, Node.from(isNoRegion())) + .withOptionalMember(RESOURCE_DELIMITER, getResourceDelimiter()) + .withMember(REUSABLE, Node.from(isReusable())) + .build(); } @Override public Builder toBuilder() { return builder() - .sourceLocation(getSourceLocation()) - .noRegion(isNoRegion()) - .noAccount(isNoAccount()) - .absolute(isAbsolute()) - .template(getTemplate()) - .resourceDelimiter(resourceDelimiter) - .reusable(reusable); + .sourceLocation(getSourceLocation()) + .noRegion(isNoRegion()) + .noAccount(isNoAccount()) + .absolute(isAbsolute()) + .template(getTemplate()) + .resourceDelimiter(resourceDelimiter) + .reusable(reusable); } // Due to the defaulting of this trait, equals has to be overridden @@ -186,11 +186,11 @@ public boolean equals(Object other) { } else { ArnTrait oa = (ArnTrait) other; return template.equals(oa.template) - && absolute == oa.absolute - && noAccount == oa.noAccount - && noRegion == oa.noRegion - && resourceDelimiter == oa.resourceDelimiter - && reusable == oa.reusable; + && absolute == oa.absolute + && noAccount == oa.noAccount + && noRegion == oa.noRegion + && resourceDelimiter == oa.resourceDelimiter + && reusable == oa.reusable; } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ErrorRenameValidator.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ErrorRenameValidator.java index 7bc4a488a12..63d3bb775d5 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ErrorRenameValidator.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ErrorRenameValidator.java @@ -42,12 +42,12 @@ public final class ErrorRenameValidator extends AbstractValidator { * Hence, error shape renaming are not supported for these protocols. */ private static final Set UNSUPPORTED_PROTOCOLS = SetUtils.of( - AwsJson1_0Trait.ID, - AwsJson1_1Trait.ID, - AwsQueryTrait.ID, - Ec2QueryTrait.ID, - RestJson1Trait.ID, - RestXmlTrait.ID + AwsJson1_0Trait.ID, + AwsJson1_1Trait.ID, + AwsQueryTrait.ID, + Ec2QueryTrait.ID, + RestJson1Trait.ID, + RestXmlTrait.ID ); @Override @@ -87,16 +87,16 @@ private void validate(Model model, ServiceShape service, List e ShapeId from = shape.get().getId(); String to = renames.get(from); events.add( - error( - service, - String.format( - "Service attempts to rename an error shape from `%s` to \"%s\"; " - + "Service protocols %s do not support error renaming.", - from, - to, - unsupportedProtocols + error( + service, + String.format( + "Service attempts to rename an error shape from `%s` to \"%s\"; " + + "Service protocols %s do not support error renaming.", + from, + to, + unsupportedProtocols + ) ) - ) ); }); } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/EventSourceValidator.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/EventSourceValidator.java index 9d7df472401..bdd97e526f2 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/EventSourceValidator.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/EventSourceValidator.java @@ -26,8 +26,8 @@ public final class EventSourceValidator extends AbstractValidator { private static final Map KNOWN_EXCEPTIONS = MapUtils.of( - "cloudwatch.amazonaws.com", - "monitoring.amazonaws.com" + "cloudwatch.amazonaws.com", + "monitoring.amazonaws.com" ); @Override @@ -50,10 +50,10 @@ private Optional validateService(ServiceShape service, ServiceT message = "aws.api#service|cloudTrailEventSource must not use placeholders, but found: " + source; } else if (!source.equals(expectedEventSource)) { message = String.format( - "aws.api#service|cloudTrailEventSource does not match the expected value. " - + "Expected '%s', but found '%s'.", - expectedEventSource, - source + "aws.api#service|cloudTrailEventSource does not match the expected value. " + + "Expected '%s', but found '%s'.", + expectedEventSource, + source ); } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/HttpChecksumTrait.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/HttpChecksumTrait.java index 3c2be25cd97..20a8040c550 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/HttpChecksumTrait.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/HttpChecksumTrait.java @@ -28,11 +28,11 @@ public final class HttpChecksumTrait extends AbstractTrait implements ToSmithyBu public static final String CHECKSUM_PREFIX = "x-amz-checksum-"; // This list should be in sync with the trait definition in `aws.protocols.smithy`. public static final List CHECKSUM_ALGORITHMS = ListUtils.of( - "CRC64NVME", - "CRC32C", - "CRC32", - "SHA1", - "SHA256" + "CRC64NVME", + "CRC32C", + "CRC32", + "SHA1", + "SHA256" ); public static final List VALIDATION_MODES = ListUtils.of("ENABLED"); @@ -61,11 +61,11 @@ public static Builder builder() { @Override public Builder toBuilder() { return new Builder() - .sourceLocation(getSourceLocation()) - .requestChecksumRequired(requestChecksumRequired) - .requestAlgorithmMember(requestAlgorithmMember) - .requestValidationModeMember(requestValidationModeMember) - .responseAlgorithms(responseAlgorithms); + .sourceLocation(getSourceLocation()) + .requestChecksumRequired(requestChecksumRequired) + .requestAlgorithmMember(requestAlgorithmMember) + .requestValidationModeMember(requestValidationModeMember) + .responseAlgorithms(responseAlgorithms); } /** @@ -118,9 +118,9 @@ public static String getChecksumLocationName(String checksumAlgorithm) { @Override protected Node createNode() { ObjectNode.Builder builder = ObjectNode.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withOptionalMember(REQUEST_ALGORITHM_MEMBER, getRequestAlgorithmMember().map(Node::from)) - .withOptionalMember(REQUEST_VALIDATION_MODE_MEMBER, getRequestValidationModeMember().map(Node::from)); + .sourceLocation(getSourceLocation()) + .withOptionalMember(REQUEST_ALGORITHM_MEMBER, getRequestAlgorithmMember().map(Node::from)) + .withOptionalMember(REQUEST_VALIDATION_MODE_MEMBER, getRequestValidationModeMember().map(Node::from)); if (isRequestChecksumRequired()) { builder.withMember(REQUEST_CHECKSUM_REQUIRED, Node.from(true)); @@ -145,8 +145,8 @@ public Trait createTrait(ShapeId target, Node value) { builder.requestChecksumRequired(objectNode.getBooleanMemberOrDefault(REQUEST_CHECKSUM_REQUIRED)); objectNode.getStringMember(REQUEST_ALGORITHM_MEMBER) - .map(StringNode::getValue) - .ifPresent(builder::requestAlgorithmMember); + .map(StringNode::getValue) + .ifPresent(builder::requestAlgorithmMember); objectNode.getArrayMember(RESPONSE_ALGORITHMS).ifPresent(responseAlgorithmNodes -> { for (String algorithm : responseAlgorithmNodes.getElementsAs(StringNode::getValue)) { @@ -155,8 +155,8 @@ public Trait createTrait(ShapeId target, Node value) { }); objectNode.getStringMember(REQUEST_VALIDATION_MODE_MEMBER) - .map(StringNode::getValue) - .ifPresent(builder::requestValidationModeMember); + .map(StringNode::getValue) + .ifPresent(builder::requestValidationModeMember); HttpChecksumTrait result = builder.build(); result.setNodeCache(value); diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/HttpChecksumTraitValidator.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/HttpChecksumTraitValidator.java index 381fcab415b..7ab3a8299e0 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/HttpChecksumTraitValidator.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/HttpChecksumTraitValidator.java @@ -60,23 +60,23 @@ private List validateOperation(Model model, OperationShape oper // Request checksum behavior is defined when either the `requestChecksumRequired` // property or `requestAlgorithmMember` property are modeled. boolean isRequestChecksumConfiguration = trait.isRequestChecksumRequired() || trait.getRequestAlgorithmMember() - .isPresent(); + .isPresent(); // Response checksum behavior is defined when either the `requestValidationModeMember` // property or `responseAlgorithms` property are modeled. Actually both are needed, but this check helps do // deeper validation later. boolean isResponseChecksumConfiguration = !trait.getResponseAlgorithms().isEmpty() || trait - .getRequestValidationModeMember() - .isPresent(); + .getRequestValidationModeMember() + .isPresent(); if (!isRequestChecksumConfiguration && !isResponseChecksumConfiguration) { return ListUtils.of( - error( - operation, - trait, - "The `httpChecksum` trait must define at least one of the" - + " `request` or `response` checksum behaviors." - ) + error( + operation, + trait, + "The `httpChecksum` trait must define at least one of the" + + " `request` or `response` checksum behaviors." + ) ); } @@ -97,10 +97,10 @@ private List validateOperation(Model model, OperationShape oper } private List validateRequestChecksumConfiguration( - Model model, - HttpChecksumTrait trait, - OperationShape operation, - StructureShape input + Model model, + HttpChecksumTrait trait, + OperationShape operation, + StructureShape input ) { List events = new ArrayList<>(); @@ -114,21 +114,21 @@ private List validateRequestChecksumConfiguration( } private Optional validateAlgorithmMember( - Model model, - HttpChecksumTrait trait, - OperationShape operation, - StructureShape input + Model model, + HttpChecksumTrait trait, + OperationShape operation, + StructureShape input ) { // Validate that requestAlgorithmMember, if present, targets a properly configured member. if (trait.getRequestAlgorithmMember().isPresent()) { return validateEnumMember( - model, - trait, - HttpChecksumTrait.REQUEST_ALGORITHM_MEMBER, - operation, - input, - trait.getRequestAlgorithmMember().get(), - HttpChecksumTrait.CHECKSUM_ALGORITHMS + model, + trait, + HttpChecksumTrait.REQUEST_ALGORITHM_MEMBER, + operation, + input, + trait.getRequestAlgorithmMember().get(), + HttpChecksumTrait.CHECKSUM_ALGORITHMS ); } return Optional.empty(); @@ -136,27 +136,27 @@ private Optional validateAlgorithmMember( @SuppressWarnings("deprecation") private Optional validateEnumMember( - Model model, - HttpChecksumTrait trait, - String traitProperty, - OperationShape operation, - StructureShape input, - String memberName, - List supportedValues + Model model, + HttpChecksumTrait trait, + String traitProperty, + OperationShape operation, + StructureShape input, + String memberName, + List supportedValues ) { Optional member = input.getMember(memberName); // There's no member that matches the configured name. if (!member.isPresent()) { return Optional.of( - error( - operation, - trait, - format( - "The `%s` property of the `httpChecksum` trait targets" - + " a member that does not exist.", - traitProperty + error( + operation, + trait, + format( + "The `%s` property of the `httpChecksum` trait targets" + + " a member that does not exist.", + traitProperty + ) ) - ) ); } @@ -172,15 +172,15 @@ private Optional validateEnumMember( } else { // This member does not have an enum trait. return Optional.of( - error( - operation, - trait, - format( - "The `%s` property of the `httpChecksum` trait targets" - + " a member that does not resolve an `enum` trait.", - traitProperty + error( + operation, + trait, + format( + "The `%s` property of the `httpChecksum` trait targets" + + " a member that does not resolve an `enum` trait.", + traitProperty + ) ) - ) ); } @@ -191,16 +191,16 @@ private Optional validateEnumMember( // The member has an enum that contains unsupported values. return Optional.of( - error( - operation, - trait, - format( - "The `%s` property of the `httpChecksum` trait targets" - + " a member with an `enum` trait that contains unsupported values: %s", - traitProperty, - ValidationUtils.tickedList(unsupportedValues) + error( + operation, + trait, + format( + "The `%s` property of the `httpChecksum` trait targets" + + " a member with an `enum` trait that contains unsupported values: %s", + traitProperty, + ValidationUtils.tickedList(unsupportedValues) + ) ) - ) ); } @@ -213,77 +213,77 @@ private List validateHeaderConflicts(OperationShape operation, // with HttpPrefixHeaders may unintentionally conflict with the checksum header resolved using the // HttpChecksum trait. member.getTrait(HttpPrefixHeadersTrait.class) - .map(HttpPrefixHeadersTrait::getValue) - .ifPresent(headerPrefix -> { - if (HttpChecksumTrait.CHECKSUM_PREFIX.startsWith(headerPrefix)) { - String memberName = member.getId().getName(); - String prefixString = headerPrefix.toLowerCase(Locale.US); - events.add( - danger( - operation, - format( - "The `httpPrefixHeaders` binding of `%s` uses" - + " the prefix `%s` that conflicts with the prefix `%s` used by the" - + " `httpChecksum` trait.", - memberName, - prefixString, - HttpChecksumTrait.CHECKSUM_PREFIX - ), - "HttpPrefixHeaders", - memberName, - prefixString - ) - ); - } - }); + .map(HttpPrefixHeadersTrait::getValue) + .ifPresent(headerPrefix -> { + if (HttpChecksumTrait.CHECKSUM_PREFIX.startsWith(headerPrefix)) { + String memberName = member.getId().getName(); + String prefixString = headerPrefix.toLowerCase(Locale.US); + events.add( + danger( + operation, + format( + "The `httpPrefixHeaders` binding of `%s` uses" + + " the prefix `%s` that conflicts with the prefix `%s` used by the" + + " `httpChecksum` trait.", + memberName, + prefixString, + HttpChecksumTrait.CHECKSUM_PREFIX + ), + "HttpPrefixHeaders", + memberName, + prefixString + ) + ); + } + }); // Service may model members that are bound to the http header for checksum on input or output shape. // This enables customers to provide checksum as input, or access returned checksum value in output. // We trigger a WARNING event to prevent any unintentional behavior. member.getTrait(HttpHeaderTrait.class) - .map(HttpHeaderTrait::getValue) - .ifPresent(headerName -> { - if (headerName.startsWith(HttpChecksumTrait.CHECKSUM_PREFIX)) { - String memberName = member.getId().getName(); - String headerString = headerName.toLowerCase(Locale.US); - events.add( - warning( - operation, - format( - "The `httpHeader` binding of `%s` on `%s`" - + " starts with the prefix `%s` used by the `httpChecksum` trait.", - headerString, - memberName, - HttpChecksumTrait.CHECKSUM_PREFIX - ), - "HttpHeader", - memberName, - headerString - ) - ); - } - }); + .map(HttpHeaderTrait::getValue) + .ifPresent(headerName -> { + if (headerName.startsWith(HttpChecksumTrait.CHECKSUM_PREFIX)) { + String memberName = member.getId().getName(); + String headerString = headerName.toLowerCase(Locale.US); + events.add( + warning( + operation, + format( + "The `httpHeader` binding of `%s` on `%s`" + + " starts with the prefix `%s` used by the `httpChecksum` trait.", + headerString, + memberName, + HttpChecksumTrait.CHECKSUM_PREFIX + ), + "HttpHeader", + memberName, + headerString + ) + ); + } + }); } return events; } private List validateResponseChecksumConfiguration( - Model model, - HttpChecksumTrait trait, - OperationShape operation, - StructureShape input + Model model, + HttpChecksumTrait trait, + OperationShape operation, + StructureShape input ) { List events = new ArrayList<>(); // Validate requestValidationModeMember is set properly for response behavior. if (!trait.getRequestValidationModeMember().isPresent()) { events.add( - error( - operation, - trait, - "The `httpChecksum` trait must model the" - + " `requestValidationModeMember` property to support response checksum behavior." - ) + error( + operation, + trait, + "The `httpChecksum` trait must model the" + + " `requestValidationModeMember` property to support response checksum behavior." + ) ); } else { validateValidationModeMember(model, trait, operation, input).map(events::add); @@ -292,12 +292,12 @@ private List validateResponseChecksumConfiguration( // Validate responseAlgorithms is not empty. if (trait.getResponseAlgorithms().isEmpty()) { events.add( - error( - operation, - trait, - "The `httpChecksum` trait must model the" - + " `responseAlgorithms` property to support response checksum behavior." - ) + error( + operation, + trait, + "The `httpChecksum` trait must model the" + + " `responseAlgorithms` property to support response checksum behavior." + ) ); } @@ -318,20 +318,20 @@ private List validateResponseChecksumConfiguration( } private Optional validateValidationModeMember( - Model model, - HttpChecksumTrait trait, - OperationShape operation, - StructureShape input + Model model, + HttpChecksumTrait trait, + OperationShape operation, + StructureShape input ) { // Validate that requestValidationModeMember, which we've found already, targets a properly configured member. return validateEnumMember( - model, - trait, - HttpChecksumTrait.REQUEST_VALIDATION_MODE_MEMBER, - operation, - input, - trait.getRequestValidationModeMember().get(), - HttpChecksumTrait.VALIDATION_MODES + model, + trait, + HttpChecksumTrait.REQUEST_VALIDATION_MODE_MEMBER, + operation, + input, + trait.getRequestValidationModeMember().get(), + HttpChecksumTrait.VALIDATION_MODES ); } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/SdkServiceIdValidator.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/SdkServiceIdValidator.java index 3b2a937cdba..47548f75e05 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/SdkServiceIdValidator.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/SdkServiceIdValidator.java @@ -40,21 +40,21 @@ public final class SdkServiceIdValidator extends AbstractValidator { * No new serviceId's should be added to this list in the future. */ private static final Set PREEXISTING_SERVICE_IDS = SetUtils.of( - "ACM PCA", - "ApiGatewayManagementApi", - "Config Service", - "Cost and Usage Report Service", - "Application Discovery Service", - "Database Migration Service", - "Directory Service", - "Elasticsearch Service", - "IoT 1Click Devices Service", - "IoTAnalytics", - "Lex Model Building Service", - "Lex Runtime Service", - "Marketplace Entitlement Service", - "mq", - "Resource Groups Tagging API" + "ACM PCA", + "ApiGatewayManagementApi", + "Config Service", + "Cost and Usage Report Service", + "Application Discovery Service", + "Database Migration Service", + "Directory Service", + "Elasticsearch Service", + "IoT 1Click Devices Service", + "IoTAnalytics", + "Lex Model Building Service", + "Lex Runtime Service", + "Marketplace Entitlement Service", + "mq", + "Resource Groups Tagging API" ); @Override @@ -96,10 +96,10 @@ public static void validateServiceId(String serviceId) { if (containsCompanyName(serviceId)) { messages.add( - String.format( - "Must not contain any of the following company names: [%s]", - ValidationUtils.tickedList(COMPANY_NAMES) - ) + String.format( + "Must not contain any of the following company names: [%s]", + ValidationUtils.tickedList(COMPANY_NAMES) + ) ); } @@ -113,11 +113,11 @@ public static void validateServiceId(String serviceId) { if (!messages.isEmpty()) { throw new IllegalArgumentException( - String.format( - "Invalid SDK service ID value, `%s`: %s", - serviceId, - String.join(";", messages) - ) + String.format( + "Invalid SDK service ID value, `%s`: %s", + serviceId, + String.join(";", messages) + ) ); } } @@ -141,8 +141,8 @@ private static Optional endsWithForbiddenWord(String value) { String lowercase = value.toLowerCase(Locale.US); return DISALLOWED_ENDINGS.stream() - .filter(lowercase::endsWith) - .findFirst(); + .filter(lowercase::endsWith) + .findFirst(); } private static boolean validForPattern(String value) { diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ServiceTrait.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ServiceTrait.java index ecb612cef1a..f68490b7197 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ServiceTrait.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ServiceTrait.java @@ -42,8 +42,8 @@ private ServiceTrait(Builder builder) { this.arnNamespace = SmithyBuilder.requiredState("arnNamespace", builder.arnNamespace); this.cloudFormationName = SmithyBuilder.requiredState("cloudFormationName", builder.cloudFormationName); this.cloudTrailEventSource = SmithyBuilder.requiredState( - "cloudTrailEventSource", - builder.cloudTrailEventSource + "cloudTrailEventSource", + builder.cloudTrailEventSource ); this.docId = builder.docId; this.endpointPrefix = SmithyBuilder.requiredState("endpointPrefix", builder.endpointPrefix); @@ -59,32 +59,32 @@ public Trait createTrait(ShapeId target, Node value) { ObjectNode objectNode = value.expectObjectNode(); Builder builder = builder().sourceLocation(value); String sdkId = objectNode.getStringMember("sdkId") - .map(StringNode::getValue) - .orElseThrow( - () -> new SourceException( - String.format( - "No sdkId was provided. Perhaps you could set this to %s?", - target.getName() - ), - value - ) - ); + .map(StringNode::getValue) + .orElseThrow( + () -> new SourceException( + String.format( + "No sdkId was provided. Perhaps you could set this to %s?", + target.getName() + ), + value + ) + ); builder.sdkId(sdkId); objectNode.getStringMember("arnNamespace") - .map(StringNode::getValue) - .ifPresent(builder::arnNamespace); + .map(StringNode::getValue) + .ifPresent(builder::arnNamespace); objectNode.getStringMember("cloudFormationName") - .map(StringNode::getValue) - .ifPresent(builder::cloudFormationName); + .map(StringNode::getValue) + .ifPresent(builder::cloudFormationName); objectNode.getStringMember("cloudTrailEventSource") - .map(StringNode::getValue) - .ifPresent(builder::cloudTrailEventSource); + .map(StringNode::getValue) + .ifPresent(builder::cloudTrailEventSource); objectNode.getStringMember("docId") - .map(StringNode::getValue) - .ifPresent(builder::docId); + .map(StringNode::getValue) + .ifPresent(builder::docId); objectNode.getStringMember("endpointPrefix") - .map(StringNode::getValue) - .ifPresent(builder::endpointPrefix); + .map(StringNode::getValue) + .ifPresent(builder::endpointPrefix); ServiceTrait result = builder.build(target); result.setNodeCache(value); return result; @@ -167,11 +167,11 @@ protected Optional getDocId() { private String buildDefaultDocId(ServiceShape serviceShape) { if (!serviceShape.expectTrait(ServiceTrait.class).equals(this)) { throw new ExpectationNotMetException( - String.format( - "Provided service shape `%s` is not the target of this trait.", - serviceShape.getId() - ), - this + String.format( + "Provided service shape `%s` is not the target of this trait.", + serviceShape.getId() + ), + this ); } @@ -200,26 +200,26 @@ public Optional getAbbreviation() { @Override public Builder toBuilder() { return new Builder() - .sdkId(sdkId) - .sourceLocation(getSourceLocation()) - .cloudFormationName(cloudFormationName) - .arnNamespace(arnNamespace) - .cloudTrailEventSource(cloudTrailEventSource) - .docId(docId) - .endpointPrefix(endpointPrefix); + .sdkId(sdkId) + .sourceLocation(getSourceLocation()) + .cloudFormationName(cloudFormationName) + .arnNamespace(arnNamespace) + .cloudTrailEventSource(cloudTrailEventSource) + .docId(docId) + .endpointPrefix(endpointPrefix); } @Override protected Node createNode() { return Node.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withMember("sdkId", Node.from(sdkId)) - .withMember("arnNamespace", Node.from(getArnNamespace())) - .withMember("cloudFormationName", Node.from(getCloudFormationName())) - .withMember("cloudTrailEventSource", Node.from(getCloudTrailEventSource())) - .withOptionalMember("docId", getDocId().map(Node::from)) - .withMember("endpointPrefix", Node.from(getEndpointPrefix())) - .build(); + .sourceLocation(getSourceLocation()) + .withMember("sdkId", Node.from(sdkId)) + .withMember("arnNamespace", Node.from(getArnNamespace())) + .withMember("cloudFormationName", Node.from(getCloudFormationName())) + .withMember("cloudTrailEventSource", Node.from(getCloudTrailEventSource())) + .withOptionalMember("docId", getDocId().map(Node::from)) + .withMember("endpointPrefix", Node.from(getEndpointPrefix())) + .build(); } // Due to the defaulting of this trait, equals has to be overridden @@ -233,24 +233,24 @@ public boolean equals(Object other) { } else { ServiceTrait os = (ServiceTrait) other; return sdkId.equals(os.sdkId) - && arnNamespace.equals(os.arnNamespace) - && cloudFormationName.equals(os.cloudFormationName) - && cloudTrailEventSource.equals(os.cloudTrailEventSource) - && Objects.equals(docId, os.docId) - && endpointPrefix.equals(os.endpointPrefix); + && arnNamespace.equals(os.arnNamespace) + && cloudFormationName.equals(os.cloudFormationName) + && cloudTrailEventSource.equals(os.cloudTrailEventSource) + && Objects.equals(docId, os.docId) + && endpointPrefix.equals(os.endpointPrefix); } } @Override public int hashCode() { return Objects.hash( - toShapeId(), - sdkId, - arnNamespace, - cloudFormationName, - cloudTrailEventSource, - docId, - endpointPrefix + toShapeId(), + sdkId, + arnNamespace, + cloudFormationName, + cloudTrailEventSource, + docId, + endpointPrefix ); } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/CognitoUserPoolsTrait.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/CognitoUserPoolsTrait.java index b2b41762237..81cf8be363f 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/CognitoUserPoolsTrait.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/CognitoUserPoolsTrait.java @@ -40,9 +40,9 @@ public Provider() { public Trait createTrait(ShapeId target, Node value) { ObjectNode objectNode = value.expectObjectNode(); CognitoUserPoolsTrait result = builder() - .sourceLocation(value) - .providerArns(objectNode.expectArrayMember(PROVIDER_ARNS).getElementsAs(StringNode::getValue)) - .build(); + .sourceLocation(value) + .providerArns(objectNode.expectArrayMember(PROVIDER_ARNS).getElementsAs(StringNode::getValue)) + .build(); result.setNodeCache(objectNode); return result; } @@ -72,9 +72,9 @@ public Builder toBuilder() { @Override protected Node createNode() { return Node.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withMember(PROVIDER_ARNS, providerArns.stream().map(Node::from).collect(ArrayNode.collect())) - .build(); + .sourceLocation(getSourceLocation()) + .withMember(PROVIDER_ARNS, providerArns.stream().map(Node::from).collect(ArrayNode.collect())) + .build(); } /** Builder for {@link CognitoUserPoolsTrait}. */ diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/SigV4ATrait.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/SigV4ATrait.java index e415da2eb1b..b7a39d77a9b 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/SigV4ATrait.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/SigV4ATrait.java @@ -43,16 +43,16 @@ public static Builder builder() { @Override public Builder toBuilder() { return builder() - .sourceLocation(getSourceLocation()) - .name(getName()); + .sourceLocation(getSourceLocation()) + .name(getName()); } @Override protected Node createNode() { return Node.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withMember(NAME, getName()) - .build(); + .sourceLocation(getSourceLocation()) + .withMember(NAME, getName()) + .build(); } public static final class Builder extends AbstractTraitBuilder { diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/SigV4Trait.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/SigV4Trait.java index f3493cce7ba..93a1ea4efce 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/SigV4Trait.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/SigV4Trait.java @@ -42,8 +42,8 @@ public static Builder builder() { @Override public Builder toBuilder() { return builder() - .name(getName()) - .sourceLocation(getSourceLocation()); + .name(getName()) + .sourceLocation(getSourceLocation()); } @Override diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/SigV4TraitsValidator.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/SigV4TraitsValidator.java index 2cd4594efba..b7bfd751224 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/SigV4TraitsValidator.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/SigV4TraitsValidator.java @@ -50,13 +50,13 @@ private List validateService(Model model, ServiceShape service) String sigv4Name = sigv4TraitOptional.get().getName(); if (!serviceArnNamespace.equals(sigv4Name)) { events.add( - createValuesShouldMatchWarning( - service, - SERVICE_ARN_NAMESPACE, - serviceArnNamespace, - SIGV4_NAME, - sigv4Name - ) + createValuesShouldMatchWarning( + service, + SERVICE_ARN_NAMESPACE, + serviceArnNamespace, + SIGV4_NAME, + sigv4Name + ) ); } } @@ -65,13 +65,13 @@ private List validateService(Model model, ServiceShape service) String sigv4aName = sigv4aTraitOptional.get().getName(); if (!serviceArnNamespace.equals(sigv4aName)) { events.add( - createValuesShouldMatchWarning( - service, - SERVICE_ARN_NAMESPACE, - serviceArnNamespace, - SIGV4A_NAME, - sigv4aName - ) + createValuesShouldMatchWarning( + service, + SERVICE_ARN_NAMESPACE, + serviceArnNamespace, + SIGV4A_NAME, + sigv4aName + ) ); } } @@ -82,13 +82,13 @@ private List validateService(Model model, ServiceShape service) String sigv4aName = sigv4aTraitOptional.get().getName(); if (!sigv4Name.equals(sigv4aName)) { events.add( - createValuesShouldMatchWarning( - service, - SIGV4_NAME, - sigv4Name, - SIGV4A_NAME, - sigv4aName - ) + createValuesShouldMatchWarning( + service, + SIGV4_NAME, + sigv4Name, + SIGV4A_NAME, + sigv4aName + ) ); } } @@ -96,21 +96,21 @@ private List validateService(Model model, ServiceShape service) } private ValidationEvent createValuesShouldMatchWarning( - ServiceShape service, - ShapeId member1, - String value1, - ShapeId member2, - String value2 + ServiceShape service, + ShapeId member1, + String value1, + ShapeId member2, + String value2 ) { return warning( - service, - String.format( - "Value for `%s` \"%s\" and value for `%s` \"%s\" SHOULD match.", - member1.toString(), - value1, - member2.toString(), - value2 - ) + service, + String.format( + "Value for `%s` \"%s\" and value for `%s` \"%s\" SHOULD match.", + member1.toString(), + value1, + member2.toString(), + value2 + ) ); } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/diff/SigV4Migration.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/diff/SigV4Migration.java index 77ac055dece..d0371f5f97f 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/diff/SigV4Migration.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/auth/diff/SigV4Migration.java @@ -47,35 +47,35 @@ public List evaluate(Differences differences) { // Validate Service effective auth schemes List> serviceChanges = differences - .changedShapes(ServiceShape.class) - .collect(Collectors.toList()); + .changedShapes(ServiceShape.class) + .collect(Collectors.toList()); for (ChangedShape change : serviceChanges) { ServiceShape oldServiceShape = change.getOldShape(); List oldAuthSchemes = oldServiceIndex - .getEffectiveAuthSchemes(oldServiceShape) - .keySet() - .stream() - .collect(Collectors.toList()); + .getEffectiveAuthSchemes(oldServiceShape) + .keySet() + .stream() + .collect(Collectors.toList()); ServiceShape newServiceShape = change.getNewShape(); List newAuthSchemes = newServiceIndex - .getEffectiveAuthSchemes(newServiceShape) - .keySet() - .stream() - .collect(Collectors.toList()); + .getEffectiveAuthSchemes(newServiceShape) + .keySet() + .stream() + .collect(Collectors.toList()); validateMigration( - newServiceShape, - oldAuthSchemes, - newAuthSchemes, - events + newServiceShape, + oldAuthSchemes, + newAuthSchemes, + events ); } Map> operationToContainedServiceBindings = computeOperationToContainedServiceBindings( - newModel + newModel ); List> operationChanges = differences - .changedShapes(OperationShape.class) - .collect(Collectors.toList()); + .changedShapes(OperationShape.class) + .collect(Collectors.toList()); for (ChangedShape change : operationChanges) { OperationShape newOperationShape = change.getNewShape(); Set newOperationServiceBindings = operationToContainedServiceBindings.get(newOperationShape); @@ -85,27 +85,27 @@ public List evaluate(Differences differences) { // Validate Operation effective auth schemes for (ServiceShape newServiceShape : newOperationServiceBindings) { oldModel.getShape(newServiceShape.getId()) - .filter(Shape::isServiceShape) - .map(s -> (ServiceShape) s) - .ifPresent(oldServiceShape -> { - OperationShape oldOperationShape = change.getOldShape(); - List oldAuthSchemes = oldServiceIndex - .getEffectiveAuthSchemes(oldServiceShape, oldOperationShape) - .keySet() - .stream() - .collect(Collectors.toList()); - List newAuthSchemes = newServiceIndex - .getEffectiveAuthSchemes(newServiceShape, newOperationShape) - .keySet() - .stream() - .collect(Collectors.toList()); - validateMigration( - newOperationShape, - oldAuthSchemes, - newAuthSchemes, - events - ); - }); + .filter(Shape::isServiceShape) + .map(s -> (ServiceShape) s) + .ifPresent(oldServiceShape -> { + OperationShape oldOperationShape = change.getOldShape(); + List oldAuthSchemes = oldServiceIndex + .getEffectiveAuthSchemes(oldServiceShape, oldOperationShape) + .keySet() + .stream() + .collect(Collectors.toList()); + List newAuthSchemes = newServiceIndex + .getEffectiveAuthSchemes(newServiceShape, newOperationShape) + .keySet() + .stream() + .collect(Collectors.toList()); + validateMigration( + newOperationShape, + oldAuthSchemes, + newAuthSchemes, + events + ); + }); } } @@ -113,10 +113,10 @@ public List evaluate(Differences differences) { } private void validateMigration( - Shape shape, - List oldAuthSchemes, - List newAuthSchemes, - List events + Shape shape, + List oldAuthSchemes, + List newAuthSchemes, + List events ) { boolean isOldSigV4Present = oldAuthSchemes.contains(SigV4Trait.ID); boolean isOldSigV4APresent = oldAuthSchemes.contains(SigV4ATrait.ID); @@ -130,25 +130,25 @@ private void validateMigration( boolean isSigV4AAdded = isOldSigV4Present && isNewSigV4Present && !isOldSigV4APresent && isNewSigV4APresent; if (isSigV4Replaced) { events.add( - danger( - shape, - "The `aws.auth#sigv4` authentication scheme was replaced by the `aws.auth#sigv4a` authentication " - + "scheme in the effective auth schemes for `" + shape.getId() + "`. " - + "Replacing the `aws.auth#sigv4` authentication scheme with the `aws.auth#sigv4a` authentication " - + "scheme directly is not backward compatible since not all credentials usable by `aws.auth#sigv4` are " - + "compatible with `aws.auth#sigv4a`, and can break existing clients' authentication." - ) + danger( + shape, + "The `aws.auth#sigv4` authentication scheme was replaced by the `aws.auth#sigv4a` authentication " + + "scheme in the effective auth schemes for `" + shape.getId() + "`. " + + "Replacing the `aws.auth#sigv4` authentication scheme with the `aws.auth#sigv4a` authentication " + + "scheme directly is not backward compatible since not all credentials usable by `aws.auth#sigv4` are " + + "compatible with `aws.auth#sigv4a`, and can break existing clients' authentication." + ) ); } else if (isSigV4AReplaced) { events.add( - danger( - shape, - "The `aws.auth#sigv4a` authentication scheme was replaced by the `aws.auth#sigv4` authentication " - + "scheme in the effective auth schemes for `" + shape.getId() + "`. " - + "Replacing the `aws.auth#sigv4` authentication scheme with the `aws.auth#sigv4a` authentication " - + "scheme directly may not be backward compatible if the signing scope was narrowed (typically from " - + "`*`)." - ) + danger( + shape, + "The `aws.auth#sigv4a` authentication scheme was replaced by the `aws.auth#sigv4` authentication " + + "scheme in the effective auth schemes for `" + shape.getId() + "`. " + + "Replacing the `aws.auth#sigv4` authentication scheme with the `aws.auth#sigv4a` authentication " + + "scheme directly may not be backward compatible if the signing scope was narrowed (typically from " + + "`*`)." + ) ); } else if (noSigV4XRemoved) { int oldSigV4Index = oldAuthSchemes.indexOf(SigV4Trait.ID); @@ -159,25 +159,25 @@ private void validateMigration( boolean isSigV4BeforeSigV4A = sigV4Index < sigV4aIndex; if (isOldSigV4BeforeSigV4A && !isSigV4BeforeSigV4A) { events.add( - danger( - shape, - "The `aws.auth#sigv4a` authentication scheme was moved before the `aws.auth#sigv4` authentication " - + "scheme in the effective auth schemes for `" + shape.getId() + "`. " - + "Moving the `aws.auth#sigv4a` authentication scheme before the `aws.auth#sigv4` authentication " - + "scheme is not backward compatible since not all credentials usable by `aws.auth#sigv4` are " - + "compatible with `aws.auth#sigv4a`, and can break existing clients' authentication." - ) + danger( + shape, + "The `aws.auth#sigv4a` authentication scheme was moved before the `aws.auth#sigv4` authentication " + + "scheme in the effective auth schemes for `" + shape.getId() + "`. " + + "Moving the `aws.auth#sigv4a` authentication scheme before the `aws.auth#sigv4` authentication " + + "scheme is not backward compatible since not all credentials usable by `aws.auth#sigv4` are " + + "compatible with `aws.auth#sigv4a`, and can break existing clients' authentication." + ) ); } if (!isOldSigV4BeforeSigV4A && isSigV4BeforeSigV4A) { events.add( - danger( - shape, - "The `aws.auth#sigv4` authentication scheme was moved before the `aws.auth#sigv4a` authentication " - + "scheme in the effective auth schemes for `" + shape.getId() + "`. " - + "Moving the `aws.auth#sigv4` authentication scheme before the `aws.auth#sigv4a` authentication " - + "scheme may not be backward compatible if the signing scope was narrowed (typically from `*`)." - ) + danger( + shape, + "The `aws.auth#sigv4` authentication scheme was moved before the `aws.auth#sigv4a` authentication " + + "scheme in the effective auth schemes for `" + shape.getId() + "`. " + + "Moving the `aws.auth#sigv4` authentication scheme before the `aws.auth#sigv4a` authentication " + + "scheme may not be backward compatible if the signing scope was narrowed (typically from `*`)." + ) ); } } else if (isSigV4Added) { @@ -186,14 +186,14 @@ private void validateMigration( boolean isSigV4AddedBeforeSigV4A = sigV4Index < sigV4aIndex; if (isSigV4AddedBeforeSigV4A) { events.add( - danger( - shape, - "The `aws.auth#sigv4` authentication scheme was added before the `aws.auth#sigv4a` authentication " - + "scheme in the effective auth schemes for `" + shape.getId() + "`. " - + "Adding the `aws.auth#sigv4` authentication scheme before an existing `aws.auth#sigv4a` " - + "authentication scheme may not be backward compatible if the signing scope was narrowed " - + "(typically from `*`)." - ) + danger( + shape, + "The `aws.auth#sigv4` authentication scheme was added before the `aws.auth#sigv4a` authentication " + + "scheme in the effective auth schemes for `" + shape.getId() + "`. " + + "Adding the `aws.auth#sigv4` authentication scheme before an existing `aws.auth#sigv4a` " + + "authentication scheme may not be backward compatible if the signing scope was narrowed " + + "(typically from `*`)." + ) ); } } else if (isSigV4AAdded) { @@ -202,15 +202,15 @@ private void validateMigration( boolean isSigV4AAddedBeforeSigV4 = sigV4aIndex < sigV4Index; if (isSigV4AAddedBeforeSigV4) { events.add( - danger( - shape, - "The `aws.auth#sigv4a` authentication scheme was added before the `aws.auth#sigv4` authentication " - + "scheme in the effective auth schemes for `" + shape.getId() + "`. " - + "Adding the `aws.auth#sigv4a` authentication scheme before an existing `aws.auth#sigv4` " - + "authentication scheme is not backward compatible since not all credentials usable by " - + "`aws.auth#sigv4` are compatible with `aws.auth#sigv4a`, and can break existing clients' " - + "authentication." - ) + danger( + shape, + "The `aws.auth#sigv4a` authentication scheme was added before the `aws.auth#sigv4` authentication " + + "scheme in the effective auth schemes for `" + shape.getId() + "`. " + + "Adding the `aws.auth#sigv4a` authentication scheme before an existing `aws.auth#sigv4` " + + "authentication scheme is not backward compatible since not all credentials usable by " + + "`aws.auth#sigv4` are compatible with `aws.auth#sigv4a`, and can break existing clients' " + + "authentication." + ) ); } } @@ -221,7 +221,7 @@ private static Map> computeOperationToContaine TopDownIndex topDownIndex = TopDownIndex.of(model); for (OperationShape operationShape : model.getOperationShapes()) { Set operationEntry = operationToContainedServiceBindings - .getOrDefault(operationShape, new HashSet()); + .getOrDefault(operationShape, new HashSet()); for (ServiceShape serviceShape : model.getServiceShapes()) { if (topDownIndex.getContainedOperations(serviceShape).contains(operationShape)) { operationEntry.add(serviceShape); diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformer.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformer.java index 9b525ba12eb..bc07067c396 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformer.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformer.java @@ -28,26 +28,26 @@ public final class CleanClientDiscoveryTraitTransformer implements ModelTransfor @Override public Model onRemove(ModelTransformer transformer, Collection shapes, Model model) { Set removedOperations = shapes.stream() - .filter(Shape::isOperationShape) - .map(Shape::getId) - .collect(Collectors.toSet()); + .filter(Shape::isOperationShape) + .map(Shape::getId) + .collect(Collectors.toSet()); Set removedErrors = shapes.stream() - .filter(shape -> shape.hasTrait(ErrorTrait.class)) - .map(Shape::getId) - .collect(Collectors.toSet()); + .filter(shape -> shape.hasTrait(ErrorTrait.class)) + .map(Shape::getId) + .collect(Collectors.toSet()); Set servicesToUpdate = getServicesToUpdate(model, removedOperations, removedErrors); Set shapesToUpdate = new HashSet<>(servicesToUpdate); Set operationsToUpdate = getOperationsToUpdate( - model, - servicesToUpdate.stream().map(Shape::getId).collect(Collectors.toSet()) + model, + servicesToUpdate.stream().map(Shape::getId).collect(Collectors.toSet()) ); shapesToUpdate.addAll(operationsToUpdate); Set membersToUpdate = getMembersToUpdate( - model, - operationsToUpdate.stream().map(Shape::getId).collect(Collectors.toSet()) + model, + operationsToUpdate.stream().map(Shape::getId).collect(Collectors.toSet()) ); shapesToUpdate.addAll(membersToUpdate); return transformer.replaceShapes(model, shapesToUpdate); @@ -67,19 +67,19 @@ private Set getServicesToUpdate(Model model, Set removedOperatio } private Set getOperationsToUpdate( - Model model, - Set updatedServices + Model model, + Set updatedServices ) { ClientEndpointDiscoveryIndex discoveryIndex = ClientEndpointDiscoveryIndex.of(model); Set stillBoundOperations = model.shapes(ServiceShape.class) - // Get all endpoint discovery services - .filter(service -> service.hasTrait(ClientEndpointDiscoveryTrait.class)) - .map(Shape::getId) - // Get those services who aren't having their discovery traits removed - .filter(service -> !updatedServices.contains(service)) - // Get all the discovery operations bound to those services - .flatMap(service -> discoveryIndex.getEndpointDiscoveryOperations(service).stream()) - .collect(Collectors.toSet()); + // Get all endpoint discovery services + .filter(service -> service.hasTrait(ClientEndpointDiscoveryTrait.class)) + .map(Shape::getId) + // Get those services who aren't having their discovery traits removed + .filter(service -> !updatedServices.contains(service)) + // Get all the discovery operations bound to those services + .flatMap(service -> discoveryIndex.getEndpointDiscoveryOperations(service).stream()) + .collect(Collectors.toSet()); // Get all endpoint discovery operations Set result = new HashSet<>(); @@ -96,25 +96,25 @@ private Set getOperationsToUpdate( private Set getMembersToUpdate(Model model, Set updatedOperations) { Set stillBoundMembers = model.shapes(OperationShape.class) - // Get all endpoint discovery operations - .filter(operation -> operation.hasTrait(ClientDiscoveredEndpointTrait.class)) - // Filter out the ones which are having their endpoint discovery traits removed - .filter(operation -> !updatedOperations.contains(operation.getId())) - // Get the input shapes of those operations - .map(operation -> model.getShape(operation.getInputShape()).flatMap(Shape::asStructureShape)) - .filter(Optional::isPresent) - // Get the input members - .flatMap(input -> input.get().getAllMembers().values().stream()) - .map(Shape::getId) - .collect(Collectors.toSet()); + // Get all endpoint discovery operations + .filter(operation -> operation.hasTrait(ClientDiscoveredEndpointTrait.class)) + // Filter out the ones which are having their endpoint discovery traits removed + .filter(operation -> !updatedOperations.contains(operation.getId())) + // Get the input shapes of those operations + .map(operation -> model.getShape(operation.getInputShape()).flatMap(Shape::asStructureShape)) + .filter(Optional::isPresent) + // Get the input members + .flatMap(input -> input.get().getAllMembers().values().stream()) + .map(Shape::getId) + .collect(Collectors.toSet()); return model.shapes(MemberShape.class) - // Get all members which have the endpoint discovery id trait - .filter(member -> member.hasTrait(ClientEndpointDiscoveryIdTrait.class)) - // Get those which are on structures that aren't still bound to endpoint discovery operations - .filter(member -> !stillBoundMembers.contains(member.getId())) - // Remove the trait - .map(member -> member.toBuilder().removeTrait(ClientEndpointDiscoveryIdTrait.ID).build()) - .collect(Collectors.toSet()); + // Get all members which have the endpoint discovery id trait + .filter(member -> member.hasTrait(ClientEndpointDiscoveryIdTrait.class)) + // Get those which are on structures that aren't still bound to endpoint discovery operations + .filter(member -> !stillBoundMembers.contains(member.getId())) + // Remove the trait + .map(member -> member.toBuilder().removeTrait(ClientEndpointDiscoveryIdTrait.ID).build()) + .collect(Collectors.toSet()); } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientDiscoveredEndpointTrait.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientDiscoveredEndpointTrait.java index 81abda38af4..0f6c67c365f 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientDiscoveredEndpointTrait.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientDiscoveredEndpointTrait.java @@ -16,7 +16,7 @@ * logic. */ public final class ClientDiscoveredEndpointTrait extends AbstractTrait - implements ToSmithyBuilder { + implements ToSmithyBuilder { public static final ShapeId ID = ShapeId.from("aws.api#clientDiscoveredEndpoint"); private static final String REQUIRED = "required"; @@ -45,9 +45,9 @@ public boolean isRequired() { @Override protected Node createNode() { return Node.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withMember(REQUIRED, Node.from(isRequired())) - .build(); + .sourceLocation(getSourceLocation()) + .withMember(REQUIRED, Node.from(isRequired())) + .build(); } @Override @@ -81,9 +81,9 @@ public Provider() { public ClientDiscoveredEndpointTrait createTrait(ShapeId target, Node value) { ObjectNode objectNode = value.expectObjectNode(); ClientDiscoveredEndpointTrait result = builder() - .sourceLocation(value) - .required(objectNode.getBooleanMemberOrDefault(REQUIRED, true)) - .build(); + .sourceLocation(value) + .required(objectNode.getBooleanMemberOrDefault(REQUIRED, true)) + .build(); result.setNodeCache(objectNode); return result; } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIndex.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIndex.java index 3a383582f77..d88326338f3 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIndex.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIndex.java @@ -36,18 +36,18 @@ public ClientEndpointDiscoveryIndex(Model model) { Optional endpointErrorId = trait.getOptionalError(); Optional endpointOperation = model.getShape(endpointOperationId) - .flatMap(Shape::asOperationShape); + .flatMap(Shape::asOperationShape); Optional endpointError = endpointErrorId - .flatMap(model::getShape) - .flatMap(Shape::asStructureShape); + .flatMap(model::getShape) + .flatMap(Shape::asStructureShape); if (endpointOperation.isPresent()) { Map serviceInfo = getOperations( - service, - endpointOperation.get(), - endpointError.orElse(null), - topDownIndex, - opIndex + service, + endpointOperation.get(), + endpointError.orElse(null), + topDownIndex, + opIndex ); if (!serviceInfo.isEmpty()) { endpointDiscoveryInfo.put(service.getId(), serviceInfo); @@ -61,23 +61,23 @@ public static ClientEndpointDiscoveryIndex of(Model model) { } private Map getOperations( - ServiceShape service, - OperationShape endpointOperation, - StructureShape endpointError, - TopDownIndex topDownIndex, - OperationIndex opIndex + ServiceShape service, + OperationShape endpointOperation, + StructureShape endpointError, + TopDownIndex topDownIndex, + OperationIndex opIndex ) { Map result = new HashMap<>(); for (OperationShape operation : topDownIndex.getContainedOperations(service)) { operation.getTrait(ClientDiscoveredEndpointTrait.class).ifPresent(trait -> { List discoveryIds = getDiscoveryIds(opIndex, operation); ClientEndpointDiscoveryInfo info = new ClientEndpointDiscoveryInfo( - service, - operation, - endpointOperation, - endpointError, - discoveryIds, - trait.isRequired() + service, + operation, + endpointOperation, + endpointError, + discoveryIds, + trait.isRequired() ); result.put(operation.getId(), info); }); @@ -97,12 +97,12 @@ private List getDiscoveryIds(OperationIndex opIndex, OperationShape public Optional getEndpointDiscoveryInfo(ToShapeId service, ToShapeId operation) { return Optional.ofNullable(endpointDiscoveryInfo.get(service.toShapeId())) - .flatMap(mappings -> Optional.ofNullable(mappings.get(operation.toShapeId()))); + .flatMap(mappings -> Optional.ofNullable(mappings.get(operation.toShapeId()))); } public Set getEndpointDiscoveryOperations(ToShapeId service) { return Optional.ofNullable(endpointDiscoveryInfo.get(service.toShapeId())) - .flatMap(mappings -> Optional.of(mappings.keySet())) - .orElse(new HashSet<>()); + .flatMap(mappings -> Optional.of(mappings.keySet())) + .orElse(new HashSet<>()); } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryInfo.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryInfo.java index 93f2cab3067..8265782c7d1 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryInfo.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryInfo.java @@ -21,12 +21,12 @@ public final class ClientEndpointDiscoveryInfo { private final boolean required; ClientEndpointDiscoveryInfo( - ServiceShape service, - OperationShape operation, - OperationShape discoveryOperation, - StructureShape error, - List discoveryIds, - boolean required + ServiceShape service, + OperationShape operation, + OperationShape discoveryOperation, + StructureShape error, + List discoveryIds, + boolean required ) { this.service = service; this.operation = operation; diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryTrait.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryTrait.java index 568c8fc17b3..15f5c9b6423 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryTrait.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryTrait.java @@ -16,7 +16,7 @@ * Configures endpoint discovery for the targeted service. */ public final class ClientEndpointDiscoveryTrait extends AbstractTrait - implements ToSmithyBuilder { + implements ToSmithyBuilder { public static final ShapeId ID = ShapeId.from("aws.api#clientEndpointDiscovery"); private static final String OPERATION = "operation"; @@ -73,18 +73,18 @@ public ShapeId getError() { @Override protected Node createNode() { return Node.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withMember(OPERATION, Node.from(getOperation().toString())) - .withOptionalMember(ERROR, getOptionalError().map(error -> Node.from(error.toString()))) - .build(); + .sourceLocation(getSourceLocation()) + .withMember(OPERATION, Node.from(getOperation().toString())) + .withOptionalMember(ERROR, getOptionalError().map(error -> Node.from(error.toString()))) + .build(); } @Override public Builder toBuilder() { return new Builder() - .sourceLocation(getSourceLocation()) - .operation(operation) - .error(error); + .sourceLocation(getSourceLocation()) + .operation(operation) + .error(error); } /** Builder for {@link ClientEndpointDiscoveryTrait}. */ @@ -137,8 +137,8 @@ public Provider() { public ClientEndpointDiscoveryTrait createTrait(ShapeId target, Node value) { ObjectNode objectNode = value.expectObjectNode(); Builder builder = builder() - .sourceLocation(value) - .operation(objectNode.expectStringMember(OPERATION).expectShapeId()); + .sourceLocation(value) + .operation(objectNode.expectStringMember(OPERATION).expectShapeId()); objectNode.getStringMember(ERROR).ifPresent(error -> builder.error(error.expectShapeId())); ClientEndpointDiscoveryTrait result = builder.build(); result.setNodeCache(objectNode); diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryValidator.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryValidator.java index d65304273ce..5709cc17cc9 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryValidator.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryValidator.java @@ -49,20 +49,20 @@ public List validate(Model model) { } validationEvents.addAll( - endpointDiscoveryServices.values() - .stream() - .map(ClientEndpointDiscoveryTrait::getOperation) - .map(operation -> model.getShape(operation).flatMap(Shape::asOperationShape)) - .filter(Optional::isPresent) - .map(Optional::get) - .flatMap( - endpointOperation -> validateEndpointOperation( - model, - opIndex, - endpointOperation - ).stream() - ) - .collect(Collectors.toList()) + endpointDiscoveryServices.values() + .stream() + .map(ClientEndpointDiscoveryTrait::getOperation) + .map(operation -> model.getShape(operation).flatMap(Shape::asOperationShape)) + .filter(Optional::isPresent) + .map(Optional::get) + .flatMap( + endpointOperation -> validateEndpointOperation( + model, + opIndex, + endpointOperation + ).stream() + ) + .collect(Collectors.toList()) ); validationEvents.addAll(validateServices(discoveryIndex, endpointDiscoveryServices)); @@ -73,123 +73,123 @@ public List validate(Model model) { private List validateTrait(ServiceShape service, ClientEndpointDiscoveryTrait trait) { if (!trait.getOptionalError().isPresent()) { return ListUtils.of( - danger( - service, - trait, - "Services SHOULD define an error which indicates an endpoint is invalid.", - MISSING_ERROR_DEFINITION - ) + danger( + service, + trait, + "Services SHOULD define an error which indicates an endpoint is invalid.", + MISSING_ERROR_DEFINITION + ) ); } return Collections.emptyList(); } private List validateServices( - ClientEndpointDiscoveryIndex discoveryIndex, - Map endpointDiscoveryServices + ClientEndpointDiscoveryIndex discoveryIndex, + Map endpointDiscoveryServices ) { List validationEvents = endpointDiscoveryServices.entrySet() - .stream() - .filter(pair -> !pair.getKey().getAllOperations().contains(pair.getValue().getOperation())) - .map( - pair -> error( - pair.getKey(), - String.format( - "The operation `%s` must be bound to the service `%s` to use it as the endpoint operation.", - pair.getValue().getOperation(), - pair.getKey() - ), - UNBOUND_OPERATION, - pair.getValue().getOperation().getName() - ) - ) - .collect(Collectors.toList()); - - validationEvents.addAll( - endpointDiscoveryServices.keySet() .stream() - .filter(service -> discoveryIndex.getEndpointDiscoveryOperations(service).isEmpty()) + .filter(pair -> !pair.getKey().getAllOperations().contains(pair.getValue().getOperation())) .map( - service -> warning( - service, - String.format( - "The service `%s` is configured to use endpoint discovery, but has no operations bound with " - + "the `%s` trait.", - service.getId().toString(), - ClientDiscoveredEndpointTrait.ID.toString() - ), - NO_OPERATIONS - ) + pair -> error( + pair.getKey(), + String.format( + "The operation `%s` must be bound to the service `%s` to use it as the endpoint operation.", + pair.getValue().getOperation(), + pair.getKey() + ), + UNBOUND_OPERATION, + pair.getValue().getOperation().getName() + ) ) - .collect(Collectors.toList()) + .collect(Collectors.toList()); + + validationEvents.addAll( + endpointDiscoveryServices.keySet() + .stream() + .filter(service -> discoveryIndex.getEndpointDiscoveryOperations(service).isEmpty()) + .map( + service -> warning( + service, + String.format( + "The service `%s` is configured to use endpoint discovery, but has no operations bound with " + + "the `%s` trait.", + service.getId().toString(), + ClientDiscoveredEndpointTrait.ID.toString() + ), + NO_OPERATIONS + ) + ) + .collect(Collectors.toList()) ); return validationEvents; } private List validateOperations( - Model model, - ClientEndpointDiscoveryIndex discoveryIndex, - Map endpointDiscoveryServices + Model model, + ClientEndpointDiscoveryIndex discoveryIndex, + Map endpointDiscoveryServices ) { return model.shapes(OperationShape.class) - .filter(operation -> operation.hasTrait(ClientDiscoveredEndpointTrait.class)) - .map(operation -> { - List infos = endpointDiscoveryServices.keySet() - .stream() - .map(service -> discoveryIndex.getEndpointDiscoveryInfo(service, operation)) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(Collectors.toList()); - return Pair.of(operation, infos); - }) - .flatMap(pair -> validateOperation(pair.getLeft(), pair.getRight()).stream()) - .collect(Collectors.toList()); + .filter(operation -> operation.hasTrait(ClientDiscoveredEndpointTrait.class)) + .map(operation -> { + List infos = endpointDiscoveryServices.keySet() + .stream() + .map(service -> discoveryIndex.getEndpointDiscoveryInfo(service, operation)) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toList()); + return Pair.of(operation, infos); + }) + .flatMap(pair -> validateOperation(pair.getLeft(), pair.getRight()).stream()) + .collect(Collectors.toList()); } private List validateOperation(OperationShape operation, List infos) { if (infos.isEmpty()) { return Collections.singletonList( - error( - operation, - String.format( - "The operation `%s` is marked with `%s` but is not attached to a " - + "service with the `%s` trait.", - operation.getId().toString(), - ClientDiscoveredEndpointTrait.ID.toString(), - ClientEndpointDiscoveryTrait.ID.toString() + error( + operation, + String.format( + "The operation `%s` is marked with `%s` but is not attached to a " + + "service with the `%s` trait.", + operation.getId().toString(), + ClientDiscoveredEndpointTrait.ID.toString(), + ClientEndpointDiscoveryTrait.ID.toString() + ) ) - ) ); } return infos.stream() - .filter(discoveryInfo -> discoveryInfo.getOptionalError().isPresent()) - .filter( - discoveryInfo -> !operation.getErrors() - .contains( - discoveryInfo.getOptionalError().get().getId() - ) - ) - .map( - discoveryInfo -> error( - operation, - String.format( - "The operation `%s` is marked with `%s` and is bound to the service " - + "`%s` but does not have the required error `%s`.", - operation.getId(), - ClientDiscoveredEndpointTrait.ID.toString(), - discoveryInfo.getService().getId(), - discoveryInfo.getOptionalError().get().getId() - ) + .filter(discoveryInfo -> discoveryInfo.getOptionalError().isPresent()) + .filter( + discoveryInfo -> !operation.getErrors() + .contains( + discoveryInfo.getOptionalError().get().getId() + ) + ) + .map( + discoveryInfo -> error( + operation, + String.format( + "The operation `%s` is marked with `%s` and is bound to the service " + + "`%s` but does not have the required error `%s`.", + operation.getId(), + ClientDiscoveredEndpointTrait.ID.toString(), + discoveryInfo.getService().getId(), + discoveryInfo.getOptionalError().get().getId() + ) + ) ) - ) - .collect(Collectors.toList()); + .collect(Collectors.toList()); } private List validateEndpointOperation( - Model model, - OperationIndex opIndex, - OperationShape operation + Model model, + OperationIndex opIndex, + OperationShape operation ) { List events = new ArrayList<>(); events.addAll(validateEndpointOperationInput(model, opIndex.expectInputShape(operation), operation)); @@ -198,138 +198,138 @@ private List validateEndpointOperation( Map outputMembers = output.getAllMembers(); if (outputMembers.size() != 1 || !outputMembers.containsKey("Endpoints")) { events.add( - error( - operation, - String.format( - "Endpoint discovery operation output must only contain an `Endpoints` member, but found: [%s]", - String.join(",", outputMembers.keySet()) + error( + operation, + String.format( + "Endpoint discovery operation output must only contain an `Endpoints` member, but found: [%s]", + String.join(",", outputMembers.keySet()) + ) ) - ) ); } Optional.ofNullable(outputMembers.get("Endpoints")) - .map(member -> Pair.of(member, model.getShape(member.getTarget()))) - .ifPresent(pair -> { - Optional listShape = pair.getRight().flatMap(Shape::asListShape); - if (!listShape.isPresent()) { - events.add( - error( - pair.getLeft(), - "The output member `Endpoints` on an endpoint discovery " - + "operation must be a list." - ) - ); - return; - } + .map(member -> Pair.of(member, model.getShape(member.getTarget()))) + .ifPresent(pair -> { + Optional listShape = pair.getRight().flatMap(Shape::asListShape); + if (!listShape.isPresent()) { + events.add( + error( + pair.getLeft(), + "The output member `Endpoints` on an endpoint discovery " + + "operation must be a list." + ) + ); + return; + } - Optional listMember = model.getShape(listShape.get().getMember().getTarget()) - .flatMap(Shape::asStructureShape); - if (!listMember.isPresent()) { - events.add( - error( - listShape.get(), - "The member of the Endpoints list in an " - + "endpoint discovery operation must be a structure shape." - ) - ); - return; - } + Optional listMember = model.getShape(listShape.get().getMember().getTarget()) + .flatMap(Shape::asStructureShape); + if (!listMember.isPresent()) { + events.add( + error( + listShape.get(), + "The member of the Endpoints list in an " + + "endpoint discovery operation must be a structure shape." + ) + ); + return; + } - Optional addressMember = listMember.get().getMember("Address"); - Optional address = addressMember.flatMap(member -> model.getShape(member.getTarget())); - if (address.isPresent() && !address.get().isStringShape()) { - events.add( - error( - addressMember.get(), - "The `Address` member of the `Endpoint` shape must " - + "be a string type." - ) - ); - } + Optional addressMember = listMember.get().getMember("Address"); + Optional address = addressMember.flatMap(member -> model.getShape(member.getTarget())); + if (address.isPresent() && !address.get().isStringShape()) { + events.add( + error( + addressMember.get(), + "The `Address` member of the `Endpoint` shape must " + + "be a string type." + ) + ); + } - Optional cachePeriodMember = listMember.get().getMember("CachePeriodInMinutes"); - Optional cachePeriod = cachePeriodMember - .flatMap(member -> model.getShape(member.getTarget())); - if (cachePeriod.isPresent() && !cachePeriod.get().isLongShape()) { - events.add( - error( - cachePeriodMember.get(), - "The `CachePeriodInMinutes` member of the " - + "`Endpoint` shape must be a long type." - ) - ); - } + Optional cachePeriodMember = listMember.get().getMember("CachePeriodInMinutes"); + Optional cachePeriod = cachePeriodMember + .flatMap(member -> model.getShape(member.getTarget())); + if (cachePeriod.isPresent() && !cachePeriod.get().isLongShape()) { + events.add( + error( + cachePeriodMember.get(), + "The `CachePeriodInMinutes` member of the " + + "`Endpoint` shape must be a long type." + ) + ); + } - Set memberNames = SetUtils.copyOf(listMember.get().getMemberNames()); - if (!memberNames.equals(SetUtils.of("Address", "CachePeriodInMinutes"))) { - events.add( - error( - listMember.get(), - String.format( - "The `Endpoint` shape must only have the members `Address` and `CachePeriodInMinutes`, " - + "but found: %s", - String.join(", ", memberNames) - ) - ) - ); - } - }); + Set memberNames = SetUtils.copyOf(listMember.get().getMemberNames()); + if (!memberNames.equals(SetUtils.of("Address", "CachePeriodInMinutes"))) { + events.add( + error( + listMember.get(), + String.format( + "The `Endpoint` shape must only have the members `Address` and `CachePeriodInMinutes`, " + + "but found: %s", + String.join(", ", memberNames) + ) + ) + ); + } + }); return events; } private List validateEndpointOperationInput( - Model model, - StructureShape input, - OperationShape operation + Model model, + StructureShape input, + OperationShape operation ) { List events = new ArrayList<>(); Set memberNames = SetUtils.copyOf(input.getMemberNames()); if (!VALID_INPUT_MEMBERS.containsAll(memberNames)) { events.add( - error( - input, - String.format( - "Input for endpoint discovery operation `%s` may only have the members Operation and " - + "Identifiers but found: %s", - operation.getId().toString(), - String.join(", ", memberNames) + error( + input, + String.format( + "Input for endpoint discovery operation `%s` may only have the members Operation and " + + "Identifiers but found: %s", + operation.getId().toString(), + String.join(", ", memberNames) + ) ) - ) ); } input.getMember("Operation") - .flatMap(member -> model.getShape(member.getTarget())) - .filter(shape -> !shape.isStringShape()) - .ifPresent( - shape -> events.add( - error( - shape, - "The Operation member of an endpoint discovery operation must be a string" - ) - ) - ); + .flatMap(member -> model.getShape(member.getTarget())) + .filter(shape -> !shape.isStringShape()) + .ifPresent( + shape -> events.add( + error( + shape, + "The Operation member of an endpoint discovery operation must be a string" + ) + ) + ); input.getMember("Identifiers") - .map(member -> Pair.of(member, model.getShape(member.getTarget()))) - .ifPresent(pair -> { - Optional map = pair.getRight().flatMap(Shape::asMapShape); - if (map.isPresent()) { - Optional value = model.getShape(map.get().getValue().getTarget()); - if (value.isPresent() && value.get().isStringShape()) { - return; + .map(member -> Pair.of(member, model.getShape(member.getTarget()))) + .ifPresent(pair -> { + Optional map = pair.getRight().flatMap(Shape::asMapShape); + if (map.isPresent()) { + Optional value = model.getShape(map.get().getValue().getTarget()); + if (value.isPresent() && value.get().isStringShape()) { + return; + } } - } - events.add( - error( - pair.getLeft(), - "The Identifiers member of an endpoint discovery " - + "operation must be a map whose keys and values are strings." - ) - ); - }); + events.add( + error( + pair.getLeft(), + "The Identifiers member of an endpoint discovery " + + "operation must be a map whose keys and values are strings." + ) + ); + }); return events; } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/AwsProtocolTrait.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/AwsProtocolTrait.java index 288b1715994..10de57e977e 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/AwsProtocolTrait.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/AwsProtocolTrait.java @@ -117,11 +117,11 @@ public B fromNode(Node node) { sourceLocation(node.getSourceLocation()); ObjectNode objectNode = node.expectObjectNode(); objectNode.getArrayMember(HTTP) - .map(values -> Node.loadArrayOfString(HTTP, values)) - .ifPresent(this::http); + .map(values -> Node.loadArrayOfString(HTTP, values)) + .ifPresent(this::http); objectNode.getArrayMember(EVENT_STREAM_HTTP) - .map(values -> Node.loadArrayOfString(EVENT_STREAM_HTTP, values)) - .ifPresent(this::eventStreamHttp); + .map(values -> Node.loadArrayOfString(EVENT_STREAM_HTTP, values)) + .ifPresent(this::eventStreamHttp); return (B) this; } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/AwsQueryErrorTrait.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/AwsQueryErrorTrait.java index 029b19e9a4b..98d5347c260 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/AwsQueryErrorTrait.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/AwsQueryErrorTrait.java @@ -58,8 +58,8 @@ public int getHttpResponseCode() { @Override protected Node createNode() { return new ObjectNode(MapUtils.of(), getSourceLocation()) - .withMember("code", getCode()) - .withMember("httpResponseCode", getHttpResponseCode()); + .withMember("code", getCode()) + .withMember("httpResponseCode", getHttpResponseCode()); } @Override diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/ProtocolHttpPayloadValidator.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/ProtocolHttpPayloadValidator.java index ef6a72c5645..574952512c1 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/ProtocolHttpPayloadValidator.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/ProtocolHttpPayloadValidator.java @@ -34,12 +34,12 @@ @SmithyInternalApi public final class ProtocolHttpPayloadValidator extends AbstractValidator { private static final Set VALID_HTTP_PAYLOAD_TYPES = SetUtils.of( - ShapeType.STRUCTURE, - ShapeType.UNION, - ShapeType.DOCUMENT, - ShapeType.BLOB, - ShapeType.STRING, - ShapeType.ENUM + ShapeType.STRUCTURE, + ShapeType.UNION, + ShapeType.DOCUMENT, + ShapeType.BLOB, + ShapeType.STRING, + ShapeType.ENUM ); @Override @@ -48,9 +48,9 @@ public List validate(Model model) { HttpBindingIndex bindingIndex = HttpBindingIndex.of(model); TopDownIndex topDownIndex = TopDownIndex.of(model); return model.shapes(ServiceShape.class) - .filter(service -> usesAwsProtocol(service, serviceIndex)) - .flatMap(service -> validateService(model, service, bindingIndex, topDownIndex).stream()) - .collect(Collectors.toList()); + .filter(service -> usesAwsProtocol(service, serviceIndex)) + .flatMap(service -> validateService(model, service, bindingIndex, topDownIndex).stream()) + .collect(Collectors.toList()); } private boolean usesAwsProtocol(ServiceShape service, ServiceIndex index) { @@ -63,10 +63,10 @@ private boolean usesAwsProtocol(ServiceShape service, ServiceIndex index) { } private List validateService( - Model model, - ServiceShape service, - HttpBindingIndex bindingIndex, - TopDownIndex topDownIndex + Model model, + ServiceShape service, + HttpBindingIndex bindingIndex, + TopDownIndex topDownIndex ) { List events = new ArrayList<>(); @@ -90,11 +90,11 @@ private Optional validateBindings(Model model, Collection validateBindings(Model model, Collection VALID_HTTP_PAYLOAD_TYPES.contains(shape.getType())) - .orElse(false); + .map(shape -> VALID_HTTP_PAYLOAD_TYPES.contains(shape.getType())) + .orElse(false); } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/ProtocolHttpValidator.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/ProtocolHttpValidator.java index 912756cc89e..90b390e373f 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/ProtocolHttpValidator.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/protocols/ProtocolHttpValidator.java @@ -25,8 +25,8 @@ public final class ProtocolHttpValidator extends AbstractValidator { public List validate(Model model) { ServiceIndex serviceIndex = ServiceIndex.of(model); return model.shapes(ServiceShape.class) - .flatMap(service -> validateService(service, serviceIndex).stream()) - .collect(Collectors.toList()); + .flatMap(service -> validateService(service, serviceIndex).stream()) + .collect(Collectors.toList()); } private List validateService(ServiceShape service, ServiceIndex index) { @@ -39,17 +39,17 @@ private List validateService(ServiceShape service, ServiceIndex invalid.removeAll(awsProtocolTrait.getHttp()); if (!invalid.isEmpty()) { events.add( - error( - service, - protocol, - String.format( - "The following values of the `eventStreamHttp` property do " - + "not also appear in the `http` property of the %s protocol " - + "trait: %s", - protocol.toShapeId(), - invalid + error( + service, + protocol, + String.format( + "The following values of the `eventStreamHttp` property do " + + "not also appear in the `http` property of the %s protocol " + + "trait: %s", + protocol.toShapeId(), + invalid + ) ) - ) ); } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/AwsTagIndex.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/AwsTagIndex.java index 06e957053b4..2a7df421d95 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/AwsTagIndex.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/AwsTagIndex.java @@ -44,8 +44,8 @@ private AwsTagIndex(Model model) { for (ServiceShape service : model.getServiceShapesWithTrait(TagEnabledTrait.class)) { computeTaggingApis(model, service); if (serviceTagOperationIsValid.contains(service.getId()) - && serviceUntagOperationIsValid.contains(service.getId()) - && serviceListTagsOperationIsValid.contains(service.getId()) + && serviceUntagOperationIsValid.contains(service.getId()) + && serviceListTagsOperationIsValid.contains(service.getId()) ) { servicesWithAllTagOperations.add(service.getId()); } @@ -213,9 +213,9 @@ private void computeTaggingApis(Model model, ServiceShape service) { } private void calculateTagApi( - Model model, - ServiceShape service, - Map operationMap + Model model, + ServiceShape service, + Map operationMap ) { TopDownIndex topDownIndex = TopDownIndex.of(model); OperationIndex operationIndex = OperationIndex.of(model); @@ -230,19 +230,19 @@ private void calculateTagApi( } for (ResourceShape resourceShape : topDownIndex.getContainedResources(service)) { shapeToTagOperation.put( - resourceShape.getId(), - resourceShape.getTrait(TaggableTrait.class) - .flatMap(TaggableTrait::getApiConfig) - .map(TaggableApiConfig::getTagApi) - .orElse(shapeToTagOperation.get(service.getId())) + resourceShape.getId(), + resourceShape.getTrait(TaggableTrait.class) + .flatMap(TaggableTrait::getApiConfig) + .map(TaggableApiConfig::getTagApi) + .orElse(shapeToTagOperation.get(service.getId())) ); } } private void calculateUntagApi( - Model model, - ServiceShape service, - Map operationMap + Model model, + ServiceShape service, + Map operationMap ) { TopDownIndex topDownIndex = TopDownIndex.of(model); OperationIndex operationIndex = OperationIndex.of(model); @@ -257,19 +257,19 @@ private void calculateUntagApi( } for (ResourceShape resourceShape : topDownIndex.getContainedResources(service)) { shapeToUntagOperation.put( - resourceShape.getId(), - resourceShape.getTrait(TaggableTrait.class) - .flatMap(TaggableTrait::getApiConfig) - .map(TaggableApiConfig::getUntagApi) - .orElse(shapeToUntagOperation.get(service.getId())) + resourceShape.getId(), + resourceShape.getTrait(TaggableTrait.class) + .flatMap(TaggableTrait::getApiConfig) + .map(TaggableApiConfig::getUntagApi) + .orElse(shapeToUntagOperation.get(service.getId())) ); } } private void calculateListTagsApi( - Model model, - ServiceShape service, - Map operationMap + Model model, + ServiceShape service, + Map operationMap ) { TopDownIndex topDownIndex = TopDownIndex.of(model); OperationIndex operationIndex = OperationIndex.of(model); @@ -284,11 +284,11 @@ private void calculateListTagsApi( } for (ResourceShape resourceShape : topDownIndex.getContainedResources(service)) { shapeToListTagsOperation.put( - resourceShape.getId(), - resourceShape.getTrait(TaggableTrait.class) - .flatMap(TaggableTrait::getApiConfig) - .map(TaggableApiConfig::getListTagsApi) - .orElse(shapeToListTagsOperation.get(service.getId())) + resourceShape.getId(), + resourceShape.getTrait(TaggableTrait.class) + .flatMap(TaggableTrait::getApiConfig) + .map(TaggableApiConfig::getListTagsApi) + .orElse(shapeToListTagsOperation.get(service.getId())) ); } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/ServiceTaggingValidator.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/ServiceTaggingValidator.java index a6c26dc3831..a2635001e91 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/ServiceTaggingValidator.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/ServiceTaggingValidator.java @@ -68,27 +68,27 @@ private List validateService(ServiceShape service, AwsTagIndex private ValidationEvent getMissingOperationEvent(ServiceShape service, FromSourceLocation location, String opName) { return warning( - service, - location, - "Service marked `aws.api#TagEnabled` is missing an operation named " - + "'" + opName + ".'" + service, + location, + "Service marked `aws.api#TagEnabled` is missing an operation named " + + "'" + opName + ".'" ); } private ValidationEvent getInvalidOperationEvent( - ServiceShape service, - FromSourceLocation location, - ShapeId opId, - String opName + ServiceShape service, + FromSourceLocation location, + ShapeId opId, + String opName ) { return danger( - service, - location, - String.format( - "Shape `%s` does not satisfy '%s' operation requirements.", - opId.toString(), - opName - ) + service, + location, + String.format( + "Shape `%s` does not satisfy '%s' operation requirements.", + opId.toString(), + opName + ) ); } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagEnabledServiceValidator.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagEnabledServiceValidator.java index a11899153be..dc2939846ef 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagEnabledServiceValidator.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagEnabledServiceValidator.java @@ -29,9 +29,9 @@ public List validate(Model model) { } private List validateService( - ServiceShape service, - AwsTagIndex tagIndex, - TopDownIndex topDownIndex + ServiceShape service, + AwsTagIndex tagIndex, + TopDownIndex topDownIndex ) { List events = new ArrayList<>(); TagEnabledTrait trait = service.expectTrait(TagEnabledTrait.class); @@ -44,22 +44,22 @@ private List validateService( } if (taggableResourceCount == 0) { events.add( - error( - service, - "Service marked `aws.api#tagEnabled` trait must have at least one " - + "`aws.api#taggable` resource." - ) + error( + service, + "Service marked `aws.api#tagEnabled` trait must have at least one " + + "`aws.api#taggable` resource." + ) ); } if (!trait.getDisableDefaultOperations() && !tagIndex.serviceHasTagApis(service.getId())) { events.add( - warning( - service, - "Service marked `aws.api#tagEnabled` trait does not have" - + " consistent tagging operations implemented: {TagResource, UntagResource, and" - + " ListTagsForResource}." - ) + warning( + service, + "Service marked `aws.api#tagEnabled` trait does not have" + + " consistent tagging operations implemented: {TagResource, UntagResource, and" + + " ListTagsForResource}." + ) ); } return events; diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagEnabledTrait.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagEnabledTrait.java index 076f15b56e2..8d735acdde7 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagEnabledTrait.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagEnabledTrait.java @@ -29,7 +29,7 @@ public TagEnabledTrait(Builder builder) { @Override protected Node createNode() { return new ObjectNode(MapUtils.of(), getSourceLocation()) - .withMember("disableDefaultOperations", getDisableDefaultOperations()); + .withMember("disableDefaultOperations", getDisableDefaultOperations()); } public boolean getDisableDefaultOperations() { diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagResourcePropertyNameValidator.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagResourcePropertyNameValidator.java index 2f13eaf7d77..875b5cba10b 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagResourcePropertyNameValidator.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagResourcePropertyNameValidator.java @@ -23,13 +23,13 @@ public List validate(Model model) { TaggableTrait trait = resource.expectTrait(TaggableTrait.class); if (trait.getProperty().isPresent() && !TaggingShapeUtils.isTagDesiredName(trait.getProperty().get())) { events.add( - warning( - resource, - String.format( - "Suggested tag property name is '%s'.", - TaggingShapeUtils.getDesiredTagsPropertyName() + warning( + resource, + String.format( + "Suggested tag property name is '%s'.", + TaggingShapeUtils.getDesiredTagsPropertyName() + ) ) - ) ); } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagResourcePropertyTypeValidator.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagResourcePropertyTypeValidator.java index a6eda45edaa..3676f02738a 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagResourcePropertyTypeValidator.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TagResourcePropertyTypeValidator.java @@ -29,11 +29,11 @@ public List validate(Model model) { Shape propertyShape = model.expectShape(properties.get(trait.getProperty().get())); if (!TaggingShapeUtils.verifyTagsShape(model, propertyShape)) { events.add( - error( - resource, - "Tag property must be a list shape targeting a member" - + " containing a pair of strings, or a Map shape targeting a string member." - ) + error( + resource, + "Tag property must be a list shape targeting a member" + + " containing a pair of strings, or a Map shape targeting a string member." + ) ); } } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggableApiConfig.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggableApiConfig.java index 615cfa0b7b4..39eb4bca335 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggableApiConfig.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggableApiConfig.java @@ -75,20 +75,20 @@ public SourceLocation getSourceLocation() { public Builder toBuilder() { Builder builder = builder(); return builder - .tagApi(tagApi) - .untagApi(untagApi) - .listTagsApi(listTagsApi) - .sourceLocation(sourceLocation); + .tagApi(tagApi) + .untagApi(untagApi) + .listTagsApi(listTagsApi) + .sourceLocation(sourceLocation); } @Override public Node toNode() { return Node.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withMember("tagApi", tagApi.toString()) - .withMember("untagApi", untagApi.toString()) - .withMember("listTagsApi", listTagsApi.toString()) - .build(); + .sourceLocation(getSourceLocation()) + .withMember("tagApi", tagApi.toString()) + .withMember("untagApi", untagApi.toString()) + .withMember("listTagsApi", listTagsApi.toString()) + .build(); } @Override diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggableResourceValidator.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggableResourceValidator.java index 6c3db00b61f..50f475e2202 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggableResourceValidator.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggableResourceValidator.java @@ -48,11 +48,11 @@ public List validate(Model model) { // It's possible the resource was marked as taggable but the service isn't tagEnabled. if (resourceLikelyTaggable && !service.hasTrait(TagEnabledTrait.class)) { events.add( - warning( - service, - "Service has resources with `aws.api#taggable` applied but does not " - + "have the `aws.api#tagEnabled` trait." - ) + warning( + service, + "Service has resources with `aws.api#taggable` applied but does not " + + "have the `aws.api#tagEnabled` trait." + ) ); } } @@ -61,23 +61,23 @@ public List validate(Model model) { } private List validateResource( - Model model, - ResourceShape resource, - ServiceShape service, - AwsTagIndex awsTagIndex + Model model, + ResourceShape resource, + ServiceShape service, + AwsTagIndex awsTagIndex ) { List events = new ArrayList<>(); // Generate danger if resource has tag property in update API. if (awsTagIndex.isResourceTagOnUpdate(resource.getId())) { Shape operation = resource.getUpdate().isPresent() - ? model.expectShape(resource.getUpdate().get()) - : model.expectShape(resource.getPut().get()); + ? model.expectShape(resource.getUpdate().get()) + : model.expectShape(resource.getPut().get()); events.add( - danger( - operation, - "Update and put resource lifecycle operations should not support updating tags" - + " because it is a privileged operation that modifies access." - ) + danger( + operation, + "Update and put resource lifecycle operations should not support updating tags" + + " because it is a privileged operation that modifies access." + ) ); } // A valid taggable resource must support one of the following: @@ -91,25 +91,25 @@ private List validateResource( if (isServiceWideTaggable && !isInstanceOpTaggable && !resource.hasTrait(ArnTrait.class)) { events.add( - error( - resource, - "Resource is taggable only via service-wide tag operations." - + " It must use the `aws.api@arn` trait." - ) + error( + resource, + "Resource is taggable only via service-wide tag operations." + + " It must use the `aws.api@arn` trait." + ) ); } if (!isServiceWideTaggable && !isInstanceOpTaggable) { events.add( - error( - resource, - String.format( - "Resource does not have tagging CRUD operations and is not" - + " compatible with service-wide tagging operations" - + " for service `%s`.", - service.getId() + error( + resource, + String.format( + "Resource does not have tagging CRUD operations and is not" + + " compatible with service-wide tagging operations" + + " for service `%s`.", + service.getId() + ) ) - ) ); } @@ -131,11 +131,11 @@ private boolean isTaggableViaInstanceOperations(Model model, ResourceShape resou Optional tagApi = resolveTagOperation(apiConfig.getTagApi(), model); if (tagApi.isPresent()) { tagApiVerified = TaggingShapeUtils.isTagPropertyInInput( - Optional.of(tagApi.get().getId()), - model, - resource + Optional.of(tagApi.get().getId()), + model, + resource ) - && verifyTagApi(tagApi.get(), model); + && verifyTagApi(tagApi.get(), model); } Optional untagApi = resolveTagOperation(apiConfig.getUntagApi(), model); @@ -156,9 +156,9 @@ private boolean isTaggableViaInstanceOperations(Model model, ResourceShape resou private boolean verifyListTagsApi(OperationShape listTagsApi, Model model) { // Verify Tags map or list member but on the output. return exactlyOne( - collectMemberTargetShapes(listTagsApi.getOutputShape(), model), - memberEntry -> TaggingShapeUtils.isTagDesiredName(memberEntry.getKey().getMemberName()) - && TaggingShapeUtils.verifyTagsShape(model, memberEntry.getValue()) + collectMemberTargetShapes(listTagsApi.getOutputShape(), model), + memberEntry -> TaggingShapeUtils.isTagDesiredName(memberEntry.getKey().getMemberName()) + && TaggingShapeUtils.verifyTagsShape(model, memberEntry.getValue()) ); } @@ -166,24 +166,24 @@ private boolean verifyUntagApi(OperationShape untagApi, Model model) { // Tag API has a tags property on its input AND has exactly one member targeting a tag shape with an // appropriate name. return exactlyOne( - collectMemberTargetShapes(untagApi.getInputShape(), model), - memberEntry -> TaggingShapeUtils.isTagKeysDesiredName(memberEntry.getKey().getMemberName()) - && TaggingShapeUtils.verifyTagKeysShape(model, memberEntry.getValue()) + collectMemberTargetShapes(untagApi.getInputShape(), model), + memberEntry -> TaggingShapeUtils.isTagKeysDesiredName(memberEntry.getKey().getMemberName()) + && TaggingShapeUtils.verifyTagKeysShape(model, memberEntry.getValue()) ); } private boolean verifyTagApi(OperationShape tagApi, Model model) { // Tag API has exactly one member targeting a tag list or map shape with an appropriate name. return exactlyOne( - collectMemberTargetShapes(tagApi.getInputShape(), model), - memberEntry -> TaggingShapeUtils.isTagDesiredName(memberEntry.getKey().getMemberName()) - && TaggingShapeUtils.verifyTagsShape(model, memberEntry.getValue()) + collectMemberTargetShapes(tagApi.getInputShape(), model), + memberEntry -> TaggingShapeUtils.isTagDesiredName(memberEntry.getKey().getMemberName()) + && TaggingShapeUtils.verifyTagsShape(model, memberEntry.getValue()) ); } private boolean exactlyOne( - Collection> collection, - Predicate> test + Collection> collection, + Predicate> test ) { int count = 0; for (Map.Entry entry : collection) { @@ -198,10 +198,10 @@ private Collection> collectMemberTargetShapes(Shap Collection> collection = new ArrayList<>(); for (MemberShape memberShape : model.expectShape(ioShapeId).members()) { collection.add( - new AbstractMap.SimpleImmutableEntry<>( - memberShape, - model.expectShape(memberShape.getTarget()) - ) + new AbstractMap.SimpleImmutableEntry<>( + memberShape, + model.expectShape(memberShape.getTarget()) + ) ); } return collection; diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggableTrait.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggableTrait.java index f7f732e64a9..d02d3d3d6b6 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggableTrait.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggableTrait.java @@ -60,9 +60,9 @@ public Optional getProperty() { @Override protected Node createNode() { return new ObjectNode(MapUtils.of(), getSourceLocation()) - .withOptionalMember("property", getProperty().map(Node::from)) - .withOptionalMember("apiConfig", getApiConfig().map(TaggableApiConfig::toNode)) - .withMember("disableSystemTags", getDisableSystemTags()); + .withOptionalMember("property", getProperty().map(Node::from)) + .withOptionalMember("apiConfig", getApiConfig().map(TaggableApiConfig::toNode)) + .withMember("disableSystemTags", getDisableSystemTags()); } public static Builder builder() { @@ -72,10 +72,10 @@ public static Builder builder() { @Override public Builder toBuilder() { return builder() - .property(property) - .apiConfig(apiConfig) - .disableSystemTags(disableSystemTags) - .sourceLocation(getSourceLocation()); + .property(property) + .apiConfig(apiConfig) + .disableSystemTags(disableSystemTags) + .sourceLocation(getSourceLocation()); } public static final class Builder extends AbstractTraitBuilder { @@ -123,25 +123,25 @@ public TaggableTrait createTrait(ShapeId target, Node value) { if (valueObjectNode.containsMember("apiConfig")) { TaggableApiConfig.Builder apiConfigBuilder = TaggableApiConfig.builder(); apiConfigBuilder.tagApi( - ShapeId.from( - valueObjectNode.expectObjectMember("apiConfig") - .expectStringMember("tagApi") - .getValue() - ) + ShapeId.from( + valueObjectNode.expectObjectMember("apiConfig") + .expectStringMember("tagApi") + .getValue() + ) ); apiConfigBuilder.untagApi( - ShapeId.from( - valueObjectNode.expectObjectMember("apiConfig") - .expectStringMember("untagApi") - .getValue() - ) + ShapeId.from( + valueObjectNode.expectObjectMember("apiConfig") + .expectStringMember("untagApi") + .getValue() + ) ); apiConfigBuilder.listTagsApi( - ShapeId.from( - valueObjectNode.expectObjectMember("apiConfig") - .expectStringMember("listTagsApi") - .getValue() - ) + ShapeId.from( + valueObjectNode.expectObjectMember("apiConfig") + .expectStringMember("listTagsApi") + .getValue() + ) ); builder.apiConfig(apiConfigBuilder.build()); } diff --git a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggingShapeUtils.java b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggingShapeUtils.java index 4b846883989..a27cf8ae9d0 100644 --- a/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggingShapeUtils.java +++ b/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/tagging/TaggingShapeUtils.java @@ -28,11 +28,11 @@ final class TaggingShapeUtils { static final String LIST_TAGS_OPNAME = "ListTagsForResource"; private static final Pattern TAG_PROPERTY_REGEX = Pattern - .compile("^[T|t]ag(s|[L|l]ist)$"); + .compile("^[T|t]ag(s|[L|l]ist)$"); private static final Pattern RESOURCE_ARN_REGEX = Pattern - .compile("^([R|r]esource)?([A|a]rn|ARN)$"); + .compile("^([R|r]esource)?([A|a]rn|ARN)$"); private static final Pattern TAG_KEYS_REGEX = Pattern - .compile("^[T|t]ag[K|k]eys$"); + .compile("^[T|t]ag[K|k]eys$"); private TaggingShapeUtils() {} @@ -69,7 +69,7 @@ static boolean isTagKeysDesiredName(String memberName) { static boolean hasResourceArnInput(Map inputMembers, Model model) { for (Map.Entry memberEntry : inputMembers.entrySet()) { if (isArnMemberDesiredName(memberEntry.getKey()) - && model.expectShape(memberEntry.getValue().getTarget()).isStringShape()) { + && model.expectShape(memberEntry.getValue().getTarget()).isStringShape()) { return true; } } @@ -120,19 +120,19 @@ static boolean verifyTagMapShape(Model model, Shape tagShape) { static boolean verifyTagKeysShape(Model model, Shape tagShape) { // A list or set that targets a string shape qualifies as listing tag keys return (tagShape.isListShape() - && model.expectShape(tagShape.asListShape().get().getMember().getTarget()).isStringShape()); + && model.expectShape(tagShape.asListShape().get().getMember().getTarget()).isStringShape()); } static boolean verifyTagResourceOperation( - Model model, - OperationShape tagResourceOperation, - OperationIndex operationIndex + Model model, + OperationShape tagResourceOperation, + OperationIndex operationIndex ) { Map inputMembers = operationIndex.getInputMembers(tagResourceOperation); int taglistMemberCount = 0; for (Map.Entry memberEntry : inputMembers.entrySet()) { if (isTagDesiredName(memberEntry.getKey()) - && verifyTagsShape(model, model.expectShape(memberEntry.getValue().getTarget())) + && verifyTagsShape(model, model.expectShape(memberEntry.getValue().getTarget())) ) { ++taglistMemberCount; } @@ -141,15 +141,15 @@ && verifyTagsShape(model, model.expectShape(memberEntry.getValue().getTarget())) } static boolean verifyUntagResourceOperation( - Model model, - OperationShape untagResourceOperation, - OperationIndex operationIndex + Model model, + OperationShape untagResourceOperation, + OperationIndex operationIndex ) { Map inputMembers = operationIndex.getInputMembers(untagResourceOperation); int untagKeyMemberCount = 0; for (Map.Entry memberEntry : inputMembers.entrySet()) { if (isTagKeysDesiredName(memberEntry.getKey()) - && verifyTagKeysShape(model, model.expectShape(memberEntry.getValue().getTarget())) + && verifyTagKeysShape(model, model.expectShape(memberEntry.getValue().getTarget())) ) { ++untagKeyMemberCount; } @@ -158,16 +158,16 @@ && verifyTagKeysShape(model, model.expectShape(memberEntry.getValue().getTarget( } static boolean verifyListTagsOperation( - Model model, - OperationShape listTagsResourceOperation, - OperationIndex operationIndex + Model model, + OperationShape listTagsResourceOperation, + OperationIndex operationIndex ) { Map inputMembers = operationIndex.getInputMembers(listTagsResourceOperation); Map outputMembers = operationIndex.getOutputMembers(listTagsResourceOperation); int taglistMemberCount = 0; for (Map.Entry memberEntry : outputMembers.entrySet()) { if (isTagDesiredName(memberEntry.getKey()) - && verifyTagsShape(model, model.expectShape(memberEntry.getValue().getTarget())) + && verifyTagsShape(model, model.expectShape(memberEntry.getValue().getTarget())) ) { ++taglistMemberCount; } @@ -176,9 +176,9 @@ && verifyTagsShape(model, model.expectShape(memberEntry.getValue().getTarget())) } static boolean isTagPropertyInInput( - Optional operationId, - Model model, - ResourceShape resource + Optional operationId, + Model model, + ResourceShape resource ) { if (operationId.isPresent()) { PropertyBindingIndex propertyBindingIndex = PropertyBindingIndex.of(model); @@ -193,9 +193,9 @@ static boolean isTagPropertyInInput( } static boolean isTagPropertyInShape( - String tagPropertyName, - Shape shape, - PropertyBindingIndex propertyBindingIndex + String tagPropertyName, + Shape shape, + PropertyBindingIndex propertyBindingIndex ) { for (MemberShape member : shape.members()) { Optional propertyName = propertyBindingIndex.getPropertyName(member.getId()); diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnIndexTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnIndexTest.java index 4008f7287db..3e696c9c222 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnIndexTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnIndexTest.java @@ -22,10 +22,10 @@ public class ArnIndexTest { @BeforeAll public static void beforeClass() { model = Model.assembler() - .discoverModels(ArnIndexTest.class.getClassLoader()) - .addImport(ArnIndexTest.class.getResource("test-model.smithy")) - .assemble() - .unwrap(); + .discoverModels(ArnIndexTest.class.getClassLoader()) + .addImport(ArnIndexTest.class.getResource("test-model.smithy")) + .assemble() + .unwrap(); } @Test @@ -34,18 +34,18 @@ public void loadsFromModel() { ShapeId id = ShapeId.from("ns.foo#SomeService"); Shape someResource = model.getShape(ShapeId.from("ns.foo#SomeResource")).get(); ArnTrait template1 = ArnTrait.builder() - .template("someresource/{someId}") - .build(); + .template("someresource/{someId}") + .build(); Shape childResource = model.getShape(ShapeId.from("ns.foo#ChildResource")).get(); ArnTrait template2 = ArnTrait.builder() - .template("someresource/{someId}/{childId}") - .build(); + .template("someresource/{someId}/{childId}") + .build(); Shape rootArnResource = model.getShape(ShapeId.from("ns.foo#RootArnResource")).get(); ArnTrait template3 = ArnTrait.builder() - .template("rootArnResource") - .noAccount(true) - .noRegion(true) - .build(); + .template("rootArnResource") + .noAccount(true) + .noRegion(true) + .build(); assertThat(arnIndex.getServiceArnNamespace(id), equalTo("service")); Map templates = arnIndex.getServiceResourceArns(id); @@ -63,28 +63,30 @@ public void computesFullArnTemplate() { ShapeId service = ShapeId.from("ns.foo#SomeService"); assertThat( - arnIndex.getFullResourceArnTemplate(service, ShapeId.from("ns.foo#SomeResource")), - equalTo(Optional.of("arn:{AWS::Partition}:service:{AWS::Region}:{AWS::AccountId}:someresource/{someId}")) + arnIndex.getFullResourceArnTemplate(service, ShapeId.from("ns.foo#SomeResource")), + equalTo( + Optional.of("arn:{AWS::Partition}:service:{AWS::Region}:{AWS::AccountId}:someresource/{someId}") + ) ); assertThat( - arnIndex.getFullResourceArnTemplate(service, ShapeId.from("ns.foo#ChildResource")), - equalTo( - Optional.of( - "arn:{AWS::Partition}:service:{AWS::Region}:{AWS::AccountId}:someresource/{someId}/{childId}" + arnIndex.getFullResourceArnTemplate(service, ShapeId.from("ns.foo#ChildResource")), + equalTo( + Optional.of( + "arn:{AWS::Partition}:service:{AWS::Region}:{AWS::AccountId}:someresource/{someId}/{childId}" + ) ) - ) ); assertThat( - arnIndex.getFullResourceArnTemplate(service, ShapeId.from("ns.foo#RootArnResource")), - equalTo(Optional.of("arn:{AWS::Partition}:service:::rootArnResource")) + arnIndex.getFullResourceArnTemplate(service, ShapeId.from("ns.foo#RootArnResource")), + equalTo(Optional.of("arn:{AWS::Partition}:service:::rootArnResource")) ); assertThat( - arnIndex.getFullResourceArnTemplate(service, ShapeId.from("ns.foo#Invalid")), - equalTo(Optional.empty()) + arnIndex.getFullResourceArnTemplate(service, ShapeId.from("ns.foo#Invalid")), + equalTo(Optional.empty()) ); assertThat( - arnIndex.getFullResourceArnTemplate(service, ShapeId.from("ns.foo#AbsoluteResource")), - equalTo(Optional.of("{arn}")) + arnIndex.getFullResourceArnTemplate(service, ShapeId.from("ns.foo#AbsoluteResource")), + equalTo(Optional.of("{arn}")) ); } @@ -100,30 +102,30 @@ public void returnsDefaultServiceArnNamespaceForAwsService() { ArnIndex arnIndex = new ArnIndex(model); assertThat( - arnIndex.getServiceArnNamespace(ShapeId.from("ns.foo#EmptyAwsService")), - equalTo("emptyawsservice") + arnIndex.getServiceArnNamespace(ShapeId.from("ns.foo#EmptyAwsService")), + equalTo("emptyawsservice") ); } @Test public void findsEffectiveArns() { Model m = Model.assembler() - .discoverModels(ArnIndexTest.class.getClassLoader()) - .addImport(ArnIndexTest.class.getResource("effective-arns.smithy")) - .assemble() - .unwrap(); + .discoverModels(ArnIndexTest.class.getClassLoader()) + .addImport(ArnIndexTest.class.getResource("effective-arns.smithy")) + .assemble() + .unwrap(); ArnIndex index = ArnIndex.of(m); ShapeId service = ShapeId.from("ns.foo#SomeService"); assertThat( - index.getEffectiveOperationArn(service, ShapeId.from("ns.foo#InstanceOperation")) - .map(ArnTrait::getTemplate), - equalTo(Optional.of("foo/{id}")) + index.getEffectiveOperationArn(service, ShapeId.from("ns.foo#InstanceOperation")) + .map(ArnTrait::getTemplate), + equalTo(Optional.of("foo/{id}")) ); assertThat( - index.getEffectiveOperationArn(service, ShapeId.from("ns.foo#CollectionOperation")) - .map(ArnTrait::getTemplate), - equalTo(Optional.of("foo")) + index.getEffectiveOperationArn(service, ShapeId.from("ns.foo#CollectionOperation")) + .map(ArnTrait::getTemplate), + equalTo(Optional.of("foo")) ); } } diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnReferenceTraitTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnReferenceTraitTest.java index 49a65783516..7d04519bf68 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnReferenceTraitTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnReferenceTraitTest.java @@ -38,7 +38,7 @@ public void loadsEmptyTrait() { @Test public void loadsTraitWithOptionalValues() { Node node = Node.parse( - "{\"resource\": \"com.foo#Baz\", \"service\": \"com.foo#Bar\", \"type\": \"AWS::Foo::Baz\"}" + "{\"resource\": \"com.foo#Baz\", \"service\": \"com.foo#Bar\", \"type\": \"AWS::Foo::Baz\"}" ); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait(ArnReferenceTrait.ID, ShapeId.from("ns.foo#foo"), node); @@ -66,10 +66,10 @@ public void loadsTraitWithOptionalValuesAndRelativeShapeIds() { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("test-model.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("test-model.smithy")) + .assemble() + .unwrap(); Shape service = result.expectShape(ShapeId.from("ns.foo#AbsoluteResourceArn")); ArnReferenceTrait trait = service.getTrait(ArnReferenceTrait.class).get(); diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnTemplateValidatorTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnTemplateValidatorTest.java index a250abff041..a71837497b9 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnTemplateValidatorTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnTemplateValidatorTest.java @@ -57,19 +57,19 @@ public void findsExtraneousIdentifiers() { events.sort(Comparator.comparing(event -> event.getShapeId().get().toString())); assertThat( - events.get(0).getMessage(), - equalTo( - "Invalid aws.api#arn trait resource, `a/{aid}/{InvalidId}/{InvalidId2}`. Found template " - + "labels in the trait that are not the names of the identifiers of the resource: [aid]. " - + "Extraneous identifiers: [`InvalidId`, `InvalidId2`]" - ) + events.get(0).getMessage(), + equalTo( + "Invalid aws.api#arn trait resource, `a/{aid}/{InvalidId}/{InvalidId2}`. Found template " + + "labels in the trait that are not the names of the identifiers of the resource: [aid]. " + + "Extraneous identifiers: [`InvalidId`, `InvalidId2`]" + ) ); assertThat( - events.get(1).getMessage(), - containsString( - "Invalid aws.api#arn trait resource, `a/{aid}/{InvalidId}/{InvalidId2}/b/{bid}/{AnotherInvalid}`. " - + "Found template labels in the trait that are not the names of the identifiers of the resource" - ) + events.get(1).getMessage(), + containsString( + "Invalid aws.api#arn trait resource, `a/{aid}/{InvalidId}/{InvalidId2}/b/{bid}/{AnotherInvalid}`. " + + "Found template labels in the trait that are not the names of the identifiers of the resource" + ) ); } @@ -80,8 +80,8 @@ public void validatesTemplatePlaceHolders() { assertThat(result.getValidationEvents(Severity.ERROR), hasSize(1)); List events = result.getValidationEvents(Severity.ERROR); assertThat( - events.get(0).getMessage(), - containsString("aws.api#arn trait contains invalid template labels") + events.get(0).getMessage(), + containsString("aws.api#arn trait contains invalid template labels") ); } } diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnTraitTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnTraitTest.java index 82a954cee2f..a4be88d8a73 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnTraitTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnTraitTest.java @@ -44,7 +44,7 @@ public void loadsTraitWithFromNode() { @Test public void canSetOtherFields() { Node node = Node.parse( - "{\"noAccount\": true, \"noRegion\": true, \"absolute\": false, \"template\": \"foo\", \"reusable\": true}" + "{\"noAccount\": true, \"noRegion\": true, \"absolute\": false, \"template\": \"foo\", \"reusable\": true}" ); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait(ArnTrait.ID, ShapeId.from("ns.foo#foo"), node); @@ -77,7 +77,7 @@ public void canSetAbsoluteAndDelimiter() { @Test public void canSetIncludeTemplateExpressions() { Node node = Node.parse( - "{\"noAccount\": false, \"noRegion\": false, \"template\": \"foo/{Baz}/bar/{Bam}/boo/{Boo}\"}" + "{\"noAccount\": false, \"noRegion\": false, \"template\": \"foo/{Baz}/bar/{Bam}/boo/{Boo}\"}" ); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait(ArnTrait.ID, ShapeId.from("ns.foo#foo"), node); @@ -93,11 +93,11 @@ public void resourcePartCannotStartWithSlash() { assertThrows(SourceException.class, () -> { Node node = Node.parse("{\"template\": \"/resource\"}"); TraitFactory.createServiceFactory() - .createTrait( - ArnTrait.ID, - ShapeId.from("ns.foo#foo"), - node - ); + .createTrait( + ArnTrait.ID, + ShapeId.from("ns.foo#foo"), + node + ); }); } @@ -106,11 +106,11 @@ public void validatesAccountValue() { assertThrows(SourceException.class, () -> { Node node = Node.parse("{\"template\": \"foo\", \"noAccount\": \"invalid\"}"); TraitFactory.createServiceFactory() - .createTrait( - ArnTrait.ID, - ShapeId.from("ns.foo#foo"), - node - ); + .createTrait( + ArnTrait.ID, + ShapeId.from("ns.foo#foo"), + node + ); }); } @@ -119,11 +119,11 @@ public void validatesRegionValue() { assertThrows(SourceException.class, () -> { Node node = Node.parse("{\"template\": \"foo\", \"noRegion\": \"invalid\"}"); TraitFactory.createServiceFactory() - .createTrait( - ArnTrait.ID, - ShapeId.from("ns.foo#foo"), - node - ); + .createTrait( + ArnTrait.ID, + ShapeId.from("ns.foo#foo"), + node + ); }); } } diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/DataTraitTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/DataTraitTest.java index d1a98946b63..8659d95bc79 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/DataTraitTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/DataTraitTest.java @@ -14,27 +14,27 @@ public class DataTraitTest { private Model getModel() { return Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("data-classification-model.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("data-classification-model.json")) + .assemble() + .unwrap(); } @Test public void loadsWithString() { Model model = getModel(); assertTrue( - model.getShape(ShapeId.from("ns.foo#A")) - .flatMap(shape -> shape.getTrait(DataTrait.class)) - .filter(trait -> trait.getValue().equals("account")) - .isPresent() + model.getShape(ShapeId.from("ns.foo#A")) + .flatMap(shape -> shape.getTrait(DataTrait.class)) + .filter(trait -> trait.getValue().equals("account")) + .isPresent() ); assertTrue( - model.getShape(ShapeId.from("ns.foo#B")) - .flatMap(shape -> shape.getTrait(DataTrait.class)) - .filter(trait -> trait.getValue().equals("tagging")) - .isPresent() + model.getShape(ShapeId.from("ns.foo#B")) + .flatMap(shape -> shape.getTrait(DataTrait.class)) + .filter(trait -> trait.getValue().equals("tagging")) + .isPresent() ); } } diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/EventSourceValidatorTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/EventSourceValidatorTest.java index e15cfb31013..5ed922792b8 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/EventSourceValidatorTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/EventSourceValidatorTest.java @@ -21,16 +21,16 @@ public class EventSourceValidatorTest { @Test public void detectsWhenEventSourceIsUnexpected() { ServiceTrait trait = ServiceTrait.builder() - .sdkId("Foo") - .arnNamespace("foo") - .cloudTrailEventSource("REPLACE_ME_LATER") - .cloudFormationName("AWS::Foo") - .build(); + .sdkId("Foo") + .arnNamespace("foo") + .cloudTrailEventSource("REPLACE_ME_LATER") + .cloudFormationName("AWS::Foo") + .build(); ServiceShape service = ServiceShape.builder() - .id("smithy.example#Foo") - .version("123") - .addTrait(trait) - .build(); + .id("smithy.example#Foo") + .version("123") + .addTrait(trait) + .build(); Model model = Model.builder().addShape(service).build(); EventSourceValidator validator = new EventSourceValidator(); List events = validator.validate(model); @@ -44,16 +44,16 @@ public void detectsWhenEventSourceIsUnexpected() { @Test public void detectsWhenEventSourceIsPlaceholder() { ServiceTrait trait = ServiceTrait.builder() - .sdkId("Foo") - .arnNamespace("foo") - .cloudTrailEventSource("notfoo.amazonaws.com") - .cloudFormationName("AWS::Foo") - .build(); + .sdkId("Foo") + .arnNamespace("foo") + .cloudTrailEventSource("notfoo.amazonaws.com") + .cloudFormationName("AWS::Foo") + .build(); ServiceShape service = ServiceShape.builder() - .id("smithy.example#Foo") - .version("123") - .addTrait(trait) - .build(); + .id("smithy.example#Foo") + .version("123") + .addTrait(trait) + .build(); Model model = Model.builder().addShape(service).build(); EventSourceValidator validator = new EventSourceValidator(); List events = validator.validate(model); @@ -62,24 +62,24 @@ public void detectsWhenEventSourceIsPlaceholder() { assertThat(event.getSeverity(), is(Severity.WARNING)); assertThat(event.getShapeId().get(), equalTo(service.getId())); assertThat( - event.getMessage(), - containsString("Expected 'foo.amazonaws.com', but found 'notfoo.amazonaws.com'") + event.getMessage(), + containsString("Expected 'foo.amazonaws.com', but found 'notfoo.amazonaws.com'") ); } @Test public void ignoresKnownExceptions() { ServiceTrait trait = ServiceTrait.builder() - .sdkId("Foo") - .arnNamespace("cloudwatch") - .cloudTrailEventSource("monitoring.amazonaws.com") - .cloudFormationName("AWS::Foo") - .build(); + .sdkId("Foo") + .arnNamespace("cloudwatch") + .cloudTrailEventSource("monitoring.amazonaws.com") + .cloudFormationName("AWS::Foo") + .build(); ServiceShape service = ServiceShape.builder() - .id("smithy.example#Foo") - .version("123") - .addTrait(trait) - .build(); + .id("smithy.example#Foo") + .version("123") + .addTrait(trait) + .build(); Model model = Model.builder().addShape(service).build(); EventSourceValidator validator = new EventSourceValidator(); List events = validator.validate(model); diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/HttpChecksumTraitTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/HttpChecksumTraitTest.java index df3d94e0e5c..0ac2afc35e7 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/HttpChecksumTraitTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/HttpChecksumTraitTest.java @@ -37,15 +37,15 @@ public void loadsTrait() { } ObjectNode node = Node.objectNode() - .withMember("requestChecksumRequired", Node.from(true)) - .withMember("requestAlgorithmMember", Node.from("ChecksumAlgorithm")) - .withMember("requestValidationModeMember", Node.from("ChecksumMode")) - .withMember("responseAlgorithms", ArrayNode.fromNodes(responseAlgorithmNodes)); + .withMember("requestChecksumRequired", Node.from(true)) + .withMember("requestAlgorithmMember", Node.from("ChecksumAlgorithm")) + .withMember("requestValidationModeMember", Node.from("ChecksumMode")) + .withMember("responseAlgorithms", ArrayNode.fromNodes(responseAlgorithmNodes)); Optional trait = provider.createTrait( - ShapeId.from("aws.protocols#httpChecksum"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("aws.protocols#httpChecksum"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(HttpChecksumTrait.class)); @@ -55,14 +55,14 @@ public void loadsTrait() { assertThat(checksumTrait.getRequestAlgorithmMember().get(), equalTo("ChecksumAlgorithm")); assertThat(checksumTrait.getRequestValidationModeMember().get(), equalTo("ChecksumMode")); assertThat( - checksumTrait.getResponseAlgorithms(), - containsInRelativeOrder( - "CRC64NVME", - "CRC32C", - "CRC32", - "SHA1", - "SHA256" - ) + checksumTrait.getResponseAlgorithms(), + containsInRelativeOrder( + "CRC64NVME", + "CRC32C", + "CRC32", + "SHA1", + "SHA256" + ) ); assertThat(node.expectBooleanMember("requestChecksumRequired"), equalTo(BooleanNode.from(true))); diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/PlaneIndexTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/PlaneIndexTest.java index b7a8048eb3f..3bac310e0fb 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/PlaneIndexTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/PlaneIndexTest.java @@ -15,10 +15,10 @@ public class PlaneIndexTest { @Test public void computesControlPlaneVsDataPlane() { Model model = Model.assembler() - .discoverModels(PlaneIndexTest.class.getClassLoader()) - .addImport(PlaneIndexTest.class.getResource("planes.json")) - .assemble() - .unwrap(); + .discoverModels(PlaneIndexTest.class.getClassLoader()) + .addImport(PlaneIndexTest.class.getResource("planes.json")) + .assemble() + .unwrap(); ShapeId service = ShapeId.from("smithy.example#Service"); PlaneIndex index = PlaneIndex.of(model); diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/SdkServiceIdValidatorTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/SdkServiceIdValidatorTest.java index ee24960d67c..3f352191bb8 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/SdkServiceIdValidatorTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/SdkServiceIdValidatorTest.java @@ -22,14 +22,14 @@ public class SdkServiceIdValidatorTest { public void validatesServiceShapesDuringBuild() { ShapeId id = ShapeId.from("com.foo#Baz"); ServiceShape serviceShape = ServiceShape.builder() - .id(id) - .version("2016-04-01") - .addTrait(ServiceTrait.builder().sdkId("AWS Foo").build(id)) - .build(); + .id(id) + .version("2016-04-01") + .addTrait(ServiceTrait.builder().sdkId("AWS Foo").build(id)) + .build(); ValidatedResult result = Model.assembler() - .addShape(serviceShape) - .discoverModels(getClass().getClassLoader()) - .assemble(); + .addShape(serviceShape) + .discoverModels(getClass().getClassLoader()) + .assemble(); assertThat(result.getValidationEvents(Severity.DANGER), not(empty())); } @@ -37,8 +37,8 @@ public void validatesServiceShapesDuringBuild() { @Test public void doesNotAllowCompanyNames() { IllegalArgumentException thrown = Assertions.assertThrows( - IllegalArgumentException.class, - () -> SdkServiceIdValidator.validateServiceId("AWS Foo") + IllegalArgumentException.class, + () -> SdkServiceIdValidator.validateServiceId("AWS Foo") ); assertThat(thrown.getMessage(), containsString("company names")); @@ -47,8 +47,8 @@ public void doesNotAllowCompanyNames() { @Test public void doesNotAllowBadSuffix() { IllegalArgumentException thrown = Assertions.assertThrows( - IllegalArgumentException.class, - () -> SdkServiceIdValidator.validateServiceId("Foo Service") + IllegalArgumentException.class, + () -> SdkServiceIdValidator.validateServiceId("Foo Service") ); assertThat(thrown.getMessage(), containsString("case-insensitively end with")); @@ -57,8 +57,8 @@ public void doesNotAllowBadSuffix() { @Test public void mustMatchRegex() { Assertions.assertThrows( - IllegalArgumentException.class, - () -> SdkServiceIdValidator.validateServiceId("!Nope!") + IllegalArgumentException.class, + () -> SdkServiceIdValidator.validateServiceId("!Nope!") ); } @@ -70,8 +70,8 @@ public void noTrailingWhitespace() { @Test public void doesNotAllowShortIds() { IllegalArgumentException thrown = Assertions.assertThrows( - IllegalArgumentException.class, - () -> SdkServiceIdValidator.validateServiceId("") + IllegalArgumentException.class, + () -> SdkServiceIdValidator.validateServiceId("") ); assertThat(thrown.getMessage(), containsString("1 and 50")); @@ -80,8 +80,8 @@ public void doesNotAllowShortIds() { @Test public void doesNotAllowLongIds() { IllegalArgumentException thrown = Assertions.assertThrows( - IllegalArgumentException.class, - () -> SdkServiceIdValidator.validateServiceId("Foobarbazqux Foobarbazqux Foobarbazqux Foobarbazqux") + IllegalArgumentException.class, + () -> SdkServiceIdValidator.validateServiceId("Foobarbazqux Foobarbazqux Foobarbazqux Foobarbazqux") ); assertThat(thrown.getMessage(), containsString("1 and 50")); diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ServiceTraitTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ServiceTraitTest.java index 7c9606b12f3..2b5b63d7d6a 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ServiceTraitTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ServiceTraitTest.java @@ -45,8 +45,8 @@ public void loadsTraitWithString() { @Test public void loadsTraitWithOptionalValues() { Node node = Node.parse( - "{\"sdkId\": \"Foo\", \"arnNamespace\": \"service\", \"cloudFormationName\": \"Baz\", " - + "\"endpointPrefix\": \"endpoint-prefix\", \"docId\": \"doc-id\"}" + "{\"sdkId\": \"Foo\", \"arnNamespace\": \"service\", \"cloudFormationName\": \"Baz\", " + + "\"endpointPrefix\": \"endpoint-prefix\", \"docId\": \"doc-id\"}" ); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait(ServiceTrait.ID, ShapeId.from("ns.foo#foo"), node); @@ -82,19 +82,19 @@ public void requiresSdkServiceId() { @Test public void requiresProperServiceShapeToResolveDocId() { ServiceTrait trait = ServiceTrait.builder() - .sdkId("Foo SDK") - .arnNamespace("foo") - .cloudTrailEventSource("cloudTrailEventSource") - .cloudFormationName("AWS::Foo") - .build(); + .sdkId("Foo SDK") + .arnNamespace("foo") + .cloudTrailEventSource("cloudTrailEventSource") + .cloudFormationName("AWS::Foo") + .build(); ServiceShape service = ServiceShape.builder() - .id("smithy.example#Foo") - .version("123") - .addTrait(trait) - .build(); + .id("smithy.example#Foo") + .version("123") + .addTrait(trait) + .build(); ServiceShape anotherService = ServiceShape.builder() - .id("smithy.example#Bar") - .build(); + .id("smithy.example#Bar") + .build(); assertThat(trait.resolveDocId(service), equalTo("foo-sdk-123")); assertThrows(ExpectationNotMetException.class, () -> trait.resolveDocId(anotherService)); @@ -103,12 +103,12 @@ public void requiresProperServiceShapeToResolveDocId() { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("test-model.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("test-model.smithy")) + .assemble() + .unwrap(); ServiceShape service = result - .expectShape(ShapeId.from("ns.foo#SomeService"), ServiceShape.class); + .expectShape(ShapeId.from("ns.foo#SomeService"), ServiceShape.class); ServiceTrait trait = service.expectTrait(ServiceTrait.class); assertThat(trait.getSdkId(), equalTo("Some Value")); @@ -122,13 +122,13 @@ public void loadsFromModel() { @Test public void equality() { Node node1 = Node.parse( - "{\"sdkId\": \"Foo1\", \"arnNamespace\": \"service\", \"cloudFormationName\": \"Baz\", " - + "\"endpointPrefix\": \"endpoint-prefix\"}" + "{\"sdkId\": \"Foo1\", \"arnNamespace\": \"service\", \"cloudFormationName\": \"Baz\", " + + "\"endpointPrefix\": \"endpoint-prefix\"}" ); Node node2 = Node.parse( - "{\"sdkId\": \"Foo2\", \"arnNamespace\": \"service\", \"cloudFormationName\": \"Baz\", " - + "\"endpointPrefix\": \"endpoint-prefix\"}" + "{\"sdkId\": \"Foo2\", \"arnNamespace\": \"service\", \"cloudFormationName\": \"Baz\", " + + "\"endpointPrefix\": \"endpoint-prefix\"}" ); TraitFactory provider = TraitFactory.createServiceFactory(); diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/auth/SigV4ATraitTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/auth/SigV4ATraitTest.java index 281fbc495c4..bced08999e0 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/auth/SigV4ATraitTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/auth/SigV4ATraitTest.java @@ -26,8 +26,8 @@ public class SigV4ATraitTest { @Test public void loadsTrait() { Node node = ObjectNode.builder() - .withMember("name", StringNode.from(MOCK_SIGNING_NAME)) - .build(); + .withMember("name", StringNode.from(MOCK_SIGNING_NAME)) + .build(); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait(SigV4ATrait.ID, MOCK_TARGET, node); diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/auth/UnsignedPayloadTraitTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/auth/UnsignedPayloadTraitTest.java index e3b36a817fe..c29b87ba746 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/auth/UnsignedPayloadTraitTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/auth/UnsignedPayloadTraitTest.java @@ -14,16 +14,16 @@ public class UnsignedPayloadTraitTest { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("unsigned-request-payload.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("unsigned-request-payload.json")) + .assemble() + .unwrap(); assertTrue( - result - .getShape(ShapeId.from("ns.foo#Unsigned1")) - .flatMap(shape -> shape.getTrait(UnsignedPayloadTrait.class)) - .isPresent() + result + .getShape(ShapeId.from("ns.foo#Unsigned1")) + .flatMap(shape -> shape.getTrait(UnsignedPayloadTrait.class)) + .isPresent() ); } } diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformerTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformerTest.java index f198a9a9a9d..eee413eee8c 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformerTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformerTest.java @@ -21,34 +21,34 @@ public class CleanClientDiscoveryTraitTransformerTest { @Test public void removesTraitsWhenOperationRemoved() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("test-model.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("test-model.json")) + .assemble() + .unwrap(); Model result = ModelTransformer.create().filterShapes(model, shape -> { return !shape.getId().toString().equals("ns.foo#DescribeEndpoints"); }); ServiceShape service = result - .getShape(ShapeId.from("ns.foo#FooService")) - .flatMap(Shape::asServiceShape) - .get(); + .getShape(ShapeId.from("ns.foo#FooService")) + .flatMap(Shape::asServiceShape) + .get(); OperationShape getOperation = result - .getShape(ShapeId.from("ns.foo#GetObject")) - .flatMap(Shape::asOperationShape) - .get(); + .getShape(ShapeId.from("ns.foo#GetObject")) + .flatMap(Shape::asOperationShape) + .get(); OperationShape putOperation = result - .getShape(ShapeId.from("ns.foo#PutObject")) - .flatMap(Shape::asOperationShape) - .get(); + .getShape(ShapeId.from("ns.foo#PutObject")) + .flatMap(Shape::asOperationShape) + .get(); MemberShape putId = result - .getShape(ShapeId.from("ns.foo#PutObjectInput$Id")) - .flatMap(Shape::asMemberShape) - .get(); + .getShape(ShapeId.from("ns.foo#PutObjectInput$Id")) + .flatMap(Shape::asMemberShape) + .get(); assertFalse(service.hasTrait(ClientEndpointDiscoveryTrait.class)); // discovery is required for this operation, so it keeps the trait @@ -60,34 +60,34 @@ public void removesTraitsWhenOperationRemoved() { @Test public void doesntRemoveTraitsWhenErrorRemoved() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("test-model.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("test-model.json")) + .assemble() + .unwrap(); Model result = ModelTransformer.create().filterShapes(model, shape -> { return !shape.getId().toString().equals("ns.foo#InvalidEndpointError"); }); ServiceShape service = result - .getShape(ShapeId.from("ns.foo#FooService")) - .flatMap(Shape::asServiceShape) - .get(); + .getShape(ShapeId.from("ns.foo#FooService")) + .flatMap(Shape::asServiceShape) + .get(); OperationShape getOperation = result - .getShape(ShapeId.from("ns.foo#GetObject")) - .flatMap(Shape::asOperationShape) - .get(); + .getShape(ShapeId.from("ns.foo#GetObject")) + .flatMap(Shape::asOperationShape) + .get(); OperationShape putOperation = result - .getShape(ShapeId.from("ns.foo#PutObject")) - .flatMap(Shape::asOperationShape) - .get(); + .getShape(ShapeId.from("ns.foo#PutObject")) + .flatMap(Shape::asOperationShape) + .get(); MemberShape putId = result - .getShape(ShapeId.from("ns.foo#PutObjectInput$Id")) - .flatMap(Shape::asMemberShape) - .get(); + .getShape(ShapeId.from("ns.foo#PutObjectInput$Id")) + .flatMap(Shape::asMemberShape) + .get(); assertTrue(service.hasTrait(ClientEndpointDiscoveryTrait.class)); assertTrue(getOperation.hasTrait(ClientDiscoveredEndpointTrait.class)); @@ -98,24 +98,24 @@ public void doesntRemoveTraitsWhenErrorRemoved() { @Test public void doesntRemoveOptionalOperationTraitIfStillBoundToDiscoveryService() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("multiple-configured-services.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("multiple-configured-services.json")) + .assemble() + .unwrap(); Model result = ModelTransformer.create().filterShapes(model, shape -> { return !shape.getId().toString().equals("ns.foo#DescribeEndpointsFoo"); }); OperationShape getOperation = result - .getShape(ShapeId.from("ns.foo#GetObjectFoo")) - .flatMap(Shape::asOperationShape) - .get(); + .getShape(ShapeId.from("ns.foo#GetObjectFoo")) + .flatMap(Shape::asOperationShape) + .get(); OperationShape putOperation = result - .getShape(ShapeId.from("ns.foo#PutObject")) - .flatMap(Shape::asOperationShape) - .get(); + .getShape(ShapeId.from("ns.foo#PutObject")) + .flatMap(Shape::asOperationShape) + .get(); assertTrue(getOperation.hasTrait(ClientDiscoveredEndpointTrait.class)); assertTrue(putOperation.hasTrait(ClientDiscoveredEndpointTrait.class)); @@ -124,19 +124,19 @@ public void doesntRemoveOptionalOperationTraitIfStillBoundToDiscoveryService() { @Test public void keepsDiscoveryIdTraitIfStillBound() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("multiple-configured-services.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("multiple-configured-services.json")) + .assemble() + .unwrap(); Model result = ModelTransformer.create().filterShapes(model, shape -> { return !shape.getId().toString().equals("ns.foo#DescribeEndpointsFoo"); }); MemberShape id = result - .getShape(ShapeId.from("ns.foo#GetObjectInput$Id")) - .flatMap(Shape::asMemberShape) - .get(); + .getShape(ShapeId.from("ns.foo#GetObjectInput$Id")) + .flatMap(Shape::asMemberShape) + .get(); assertTrue(id.hasTrait(ClientEndpointDiscoveryIdTrait.class)); diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientDiscoveredEndpointTraitTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientDiscoveredEndpointTraitTest.java index 45d4a05fc2a..06228e3a5f1 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientDiscoveredEndpointTraitTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientDiscoveredEndpointTraitTest.java @@ -16,14 +16,14 @@ public class ClientDiscoveredEndpointTraitTest { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("test-model.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("test-model.json")) + .assemble() + .unwrap(); OperationShape operation = result - .expectShape(ShapeId.from("ns.foo#GetObject")) - .asOperationShape() - .get(); + .expectShape(ShapeId.from("ns.foo#GetObject")) + .asOperationShape() + .get(); ClientDiscoveredEndpointTrait trait = operation.getTrait(ClientDiscoveredEndpointTrait.class).get(); assertTrue(trait.isRequired()); diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIdTraitTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIdTraitTest.java index b64806834f9..1ff86e9e4f4 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIdTraitTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIdTraitTest.java @@ -25,21 +25,21 @@ public class ClientEndpointDiscoveryIdTraitTest { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("test-model.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("test-model.json")) + .assemble() + .unwrap(); OperationShape operation = result - .expectShape(ShapeId.from("ns.foo#GetObject")) - .asOperationShape() - .get(); + .expectShape(ShapeId.from("ns.foo#GetObject")) + .asOperationShape() + .get(); MemberShape member = result - .getShape(operation.getInputShape()) - .get() - .asStructureShape() - .get() - .getMember("Id") - .get(); + .getShape(operation.getInputShape()) + .get() + .asStructureShape() + .get() + .getMember("Id") + .get(); assertTrue(member.getTrait(ClientEndpointDiscoveryIdTrait.class).isPresent()); } @@ -47,9 +47,9 @@ public void loadsFromModel() { @Test public void operationMustHaveDiscoveredEndpointTrait() { ValidatedResult result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("no-operation-discovery.json")) - .assemble(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("no-operation-discovery.json")) + .assemble(); List events = result.getValidationEvents(Severity.ERROR); assertThat(events, not(empty())); diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIndexTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIndexTest.java index 6f587ebc472..9047e679b3b 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIndexTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIndexTest.java @@ -20,10 +20,10 @@ public class ClientEndpointDiscoveryIndexTest { @Test public void getsDiscoveryInformation() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("test-model.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("test-model.json")) + .assemble() + .unwrap(); ClientEndpointDiscoveryIndex discoveryIndex = ClientEndpointDiscoveryIndex.of(result); ShapeId service = ShapeId.from("ns.foo#FooService"); @@ -42,10 +42,10 @@ public void getsDiscoveryInformation() { @Test public void handlesOperationsWithoutConfiguration() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("test-model.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("test-model.json")) + .assemble() + .unwrap(); ClientEndpointDiscoveryIndex discoveryIndex = ClientEndpointDiscoveryIndex.of(result); ShapeId service = ShapeId.from("ns.foo#FooService"); @@ -58,10 +58,10 @@ public void handlesOperationsWithoutConfiguration() { @Test public void handlesServicesWithoutConfiguration() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("test-model.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("test-model.json")) + .assemble() + .unwrap(); ClientEndpointDiscoveryIndex discoveryIndex = ClientEndpointDiscoveryIndex.of(result); ShapeId service = ShapeId.from("ns.foo#BarService"); @@ -74,10 +74,10 @@ public void handlesServicesWithoutConfiguration() { @Test public void getsDiscoveryOperations() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("test-model.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("test-model.json")) + .assemble() + .unwrap(); ClientEndpointDiscoveryIndex discoveryIndex = ClientEndpointDiscoveryIndex.of(result); ShapeId service = ShapeId.from("ns.foo#FooService"); Set discoveryOperations = discoveryIndex.getEndpointDiscoveryOperations(service); diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryTraitTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryTraitTest.java index a89e8409727..21bb0297c4d 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryTraitTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryTraitTest.java @@ -16,14 +16,14 @@ public class ClientEndpointDiscoveryTraitTest { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("test-model.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("test-model.json")) + .assemble() + .unwrap(); ServiceShape service = result - .expectShape(ShapeId.from("ns.foo#FooService")) - .asServiceShape() - .get(); + .expectShape(ShapeId.from("ns.foo#FooService")) + .asServiceShape() + .get(); ClientEndpointDiscoveryTrait trait = service.getTrait(ClientEndpointDiscoveryTrait.class).get(); assertEquals(trait.getOperation(), ShapeId.from("ns.foo#DescribeEndpoints")); diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryValidatorTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryValidatorTest.java index 9ba73ec37d9..8b0f88d8e84 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryValidatorTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryValidatorTest.java @@ -20,9 +20,9 @@ public class ClientEndpointDiscoveryValidatorTest { @Test public void validatesEndpointOperationBound() { ValidatedResult result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("endpoint-operation-unbound.json")) - .assemble(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("endpoint-operation-unbound.json")) + .assemble(); List events = result.getValidationEvents(Severity.ERROR); assertThat(events, not(empty())); @@ -32,9 +32,9 @@ public void validatesEndpointOperationBound() { @Test public void warnsOnConfiguredServicesWithoutBoundConfiguredOperations() { ValidatedResult result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("no-configured-operations.json")) - .assemble(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("no-configured-operations.json")) + .assemble(); List events = result.getValidationEvents(Severity.WARNING); assertThat(events, not(empty())); @@ -44,9 +44,9 @@ public void warnsOnConfiguredServicesWithoutBoundConfiguredOperations() { @Test public void validatesOperationBoundToConfiguredService() { ValidatedResult result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("service-not-configured.json")) - .assemble(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("service-not-configured.json")) + .assemble(); List events = result.getValidationEvents(Severity.ERROR); assertThat(events, not(empty())); diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/tagging/AwsTagIndexTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/tagging/AwsTagIndexTest.java index 69b8f43368d..cce71a7e270 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/tagging/AwsTagIndexTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/tagging/AwsTagIndexTest.java @@ -31,10 +31,10 @@ public final class AwsTagIndexTest { @BeforeAll public static void loadModel() { model = Model.assembler() - .addImport(AwsTagIndex.class.getResource("aws-tag-index-test-model.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(AwsTagIndex.class.getResource("aws-tag-index-test-model.smithy")) + .discoverModels() + .assemble() + .unwrap(); tagIndex = AwsTagIndex.of(model); } @@ -93,11 +93,11 @@ public void detectsResourceTagMutation(ShapeId shapeId, boolean isTagOnCreate, b public static Stream resourceTagMutabilities() { return Stream.of( - Arguments.of(CITY_RESOURCE_ID, false, false), - Arguments.of(ShapeId.fromParts(NAMESPACE, "Town"), true, true), - Arguments.of(ShapeId.fromParts(NAMESPACE, "Farm"), true, true), - Arguments.of(ShapeId.fromParts(NAMESPACE, "Barn"), true, false), - Arguments.of(ShapeId.fromParts(NAMESPACE, "Silo"), true, true) + Arguments.of(CITY_RESOURCE_ID, false, false), + Arguments.of(ShapeId.fromParts(NAMESPACE, "Town"), true, true), + Arguments.of(ShapeId.fromParts(NAMESPACE, "Farm"), true, true), + Arguments.of(ShapeId.fromParts(NAMESPACE, "Barn"), true, false), + Arguments.of(ShapeId.fromParts(NAMESPACE, "Silo"), true, true) ); } diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/tagging/TagEnabledTraitTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/tagging/TagEnabledTraitTest.java index 58d97b8b2c6..352fca1de46 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/tagging/TagEnabledTraitTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/tagging/TagEnabledTraitTest.java @@ -26,9 +26,9 @@ public void loadsTrait() { Map properties = new HashMap<>(); properties.put(StringNode.from("disableDefaultOperations"), Node.from(true)); Optional trait = provider.createTrait( - ShapeId.from("aws.api#tagEnabled"), - ShapeId.from("ns.qux#foo"), - Node.objectNode(properties) + ShapeId.from("aws.api#tagEnabled"), + ShapeId.from("ns.qux#foo"), + Node.objectNode(properties) ); assertTrue(trait.isPresent()); @@ -41,9 +41,9 @@ public void loadsTrait() { public void loadsTraitDefaultCheck() { TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("aws.api#tagEnabled"), - ShapeId.from("ns.qux#foo"), - Node.objectNode() + ShapeId.from("aws.api#tagEnabled"), + ShapeId.from("ns.qux#foo"), + Node.objectNode() ); assertTrue(trait.isPresent()); diff --git a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/tagging/TaggableTraitTest.java b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/tagging/TaggableTraitTest.java index 57ddf4f2a0b..ee2fa86efee 100644 --- a/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/tagging/TaggableTraitTest.java +++ b/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/tagging/TaggableTraitTest.java @@ -34,9 +34,9 @@ public void loadsTrait() { objectNodeBuilder.withMember("disableSystemTags", true); ObjectNode objectNode = objectNodeBuilder.build(); Optional trait = provider.createTrait( - ShapeId.from("aws.api#taggable"), - ShapeId.from("ns.qux#foo"), - objectNode + ShapeId.from("aws.api#taggable"), + ShapeId.from("ns.qux#foo"), + objectNode ); assertTrue(trait.isPresent()); @@ -60,9 +60,9 @@ public void loadsEmptySpecificationDefaults() { TraitFactory provider = TraitFactory.createServiceFactory(); ObjectNode objectNode = Node.objectNode(); Optional trait = provider.createTrait( - ShapeId.from("aws.api#taggable"), - ShapeId.from("ns.qux#foo"), - objectNode + ShapeId.from("aws.api#taggable"), + ShapeId.from("ns.qux#foo"), + objectNode ); assertTrue(trait.isPresent()); diff --git a/smithy-cli/src/it/java/software/amazon/smithy/cli/CleanCommandTest.java b/smithy-cli/src/it/java/software/amazon/smithy/cli/CleanCommandTest.java index 25bfa7f33db..bbebf6fbfdc 100644 --- a/smithy-cli/src/it/java/software/amazon/smithy/cli/CleanCommandTest.java +++ b/smithy-cli/src/it/java/software/amazon/smithy/cli/CleanCommandTest.java @@ -53,8 +53,8 @@ public void cleanRemovesAllCacheDirectories() throws IOException { try { Files.createDirectories(IntegUtils.SMITHY_TEMPLATE_CACHE_PATH); assertTrue( - Files.exists(IntegUtils.SMITHY_TEMPLATE_CACHE_PATH) - && Files.isDirectory(IntegUtils.SMITHY_ROOT_CACHE_PATH) + Files.exists(IntegUtils.SMITHY_TEMPLATE_CACHE_PATH) + && Files.isDirectory(IntegUtils.SMITHY_ROOT_CACHE_PATH) ); IntegUtils.run(PROJECT_NAME, ListUtils.of("clean"), result -> { assertThat(result.getExitCode(), equalTo(0)); @@ -72,8 +72,8 @@ public void cleanWithTemplateOptionRemovesOnlyTemplateDir() throws IOException { try { Files.createDirectories(IntegUtils.SMITHY_TEMPLATE_CACHE_PATH); assertTrue( - Files.exists(IntegUtils.SMITHY_TEMPLATE_CACHE_PATH) - && Files.isDirectory(IntegUtils.SMITHY_ROOT_CACHE_PATH) + Files.exists(IntegUtils.SMITHY_TEMPLATE_CACHE_PATH) + && Files.isDirectory(IntegUtils.SMITHY_ROOT_CACHE_PATH) ); IntegUtils.withProject(PROJECT_NAME, root -> { diff --git a/smithy-cli/src/it/java/software/amazon/smithy/cli/DiffCommandTest.java b/smithy-cli/src/it/java/software/amazon/smithy/cli/DiffCommandTest.java index 16aac57ba0b..fca0c8270c2 100644 --- a/smithy-cli/src/it/java/software/amazon/smithy/cli/DiffCommandTest.java +++ b/smithy-cli/src/it/java/software/amazon/smithy/cli/DiffCommandTest.java @@ -70,16 +70,16 @@ public void canWriteCsvOutput() { writeFile(b, "$version: \"2.0\"\nnamespace example\n@aaaaaa\nstring A\n"); RunResult result = IntegUtils.run( - dir, - ListUtils.of( - "diff", - "--old", - a.toString(), - "--new", - b.toString(), - "--format", - "csv" - ) + dir, + ListUtils.of( + "diff", + "--old", + a.toString(), + "--new", + b.toString(), + "--format", + "csv" + ) ); assertThat("Not 1: output [" + result.getOutput() + ']', result.getExitCode(), is(1)); assertThat(result.getOutput(), containsString("severity,id,")); @@ -97,16 +97,16 @@ public void showsLabelForDiffEvents() { writeFile(b, "$version: \"2.0\"\nnamespace example\nstring A\nstring B\n"); // Added B. RunResult result = IntegUtils.run( - dir, - ListUtils.of( - "diff", - "--old", - a.toString(), - "--new", - b.toString(), - "--severity", - "NOTE" - ) + dir, + ListUtils.of( + "diff", + "--old", + a.toString(), + "--new", + b.toString(), + "--severity", + "NOTE" + ) ); // Note that this is required since the default severity is WARNING. assertThat("Not 0: output [" + result.getOutput() + ']', result.getExitCode(), is(0)); assertThat(result.getOutput(), containsString("── DIFF NOTE ──")); @@ -132,16 +132,16 @@ public void doesNotUseImportsOrSourcesWithArbitraryMode() { writeFile(file, "$version: \"2.0\"\nnamespace smithy.example\ninteger MyString\n"); RunResult result = IntegUtils.run( - dir, - ListUtils.of( - "diff", - "-c", - dir.resolve("smithy-build.json").toString(), - "--old", - file.toString(), - "--new", - file.toString() - ) + dir, + ListUtils.of( + "diff", + "-c", + dir.resolve("smithy-build.json").toString(), + "--old", + file.toString(), + "--new", + file.toString() + ) ); assertThat("Not 0: output [" + result.getOutput() + ']', result.getExitCode(), is(0)); }); @@ -158,16 +158,16 @@ public void requiresOldAndNewForArbitraryMode() { @Test public void doesNotAllowNewWithProjectMode() { RunResult result = IntegUtils.run( - Paths.get("."), - ListUtils.of( - "diff", - "--mode", - "project", - "--new", - "x", - "--old", - "y" - ) + Paths.get("."), + ListUtils.of( + "diff", + "--mode", + "project", + "--new", + "x", + "--old", + "y" + ) ); assertThat("Not 1: output [" + result.getOutput() + ']', result.getExitCode(), is(1)); @@ -179,14 +179,14 @@ public void projectModeUsesConfigOfOldModel() { IntegUtils.withProject("diff-example-conflict-with-simple", outer -> { IntegUtils.withProject("simple-config-sources", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of( - "diff", - "--mode", - "project", - "--old", - outer.toString() - ) + dir, + ListUtils.of( + "diff", + "--mode", + "project", + "--old", + outer.toString() + ) ); assertThat("Not 1: output [" + result.getOutput() + ']', result.getExitCode(), is(1)); @@ -200,14 +200,14 @@ public void projectModeCanDiffAgainstSingleFile() { // Diff against itself (the only model file of the project), so there should be no differences. IntegUtils.withProject("simple-config-sources", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of( - "diff", - "--mode", - "project", - "--old", - dir.resolve("model").resolve("main.smithy").toString() - ) + dir, + ListUtils.of( + "diff", + "--mode", + "project", + "--old", + dir.resolve("model").resolve("main.smithy").toString() + ) ); assertThat("Not 0: output [" + result.getOutput() + ']', result.getExitCode(), is(0)); diff --git a/smithy-cli/src/it/java/software/amazon/smithy/cli/FormatCommandTest.java b/smithy-cli/src/it/java/software/amazon/smithy/cli/FormatCommandTest.java index 1390f8fa01b..3fc52cd856a 100644 --- a/smithy-cli/src/it/java/software/amazon/smithy/cli/FormatCommandTest.java +++ b/smithy-cli/src/it/java/software/amazon/smithy/cli/FormatCommandTest.java @@ -17,8 +17,8 @@ public void failsWhenNoModelsGiven() { IntegUtils.run("bad-formatting", ListUtils.of("format"), result -> { assertThat(result.getExitCode(), equalTo(1)); assertThat( - result.getOutput(), - containsString("No .smithy model or directory was provided as a positional argument") + result.getOutput(), + containsString("No .smithy model or directory was provided as a positional argument") ); }); } @@ -29,8 +29,8 @@ public void failsWhenBadFileGiven() { assertThat(result.getExitCode(), equalTo(1)); assertThat( - result.getOutput(), - containsString("`THIS_FILE_DOES_NOT_EXIST_1234` is not a valid file or directory") + result.getOutput(), + containsString("`THIS_FILE_DOES_NOT_EXIST_1234` is not a valid file or directory") ); }); } @@ -42,18 +42,18 @@ public void formatsSingleFile() { String model = result.getFile("model/other.smithy"); assertThat( - model, - equalTo( - String.format( - "$version: \"2.0\"%n" - + "%n" - + "namespace smithy.example%n" - + "%n" - + "string MyString%n" - + "%n" - + "string MyString2%n" + model, + equalTo( + String.format( + "$version: \"2.0\"%n" + + "%n" + + "namespace smithy.example%n" + + "%n" + + "string MyString%n" + + "%n" + + "string MyString2%n" + ) ) - ) ); }); } @@ -65,35 +65,35 @@ public void formatsDirectory() { String main = result.getFile("model/main.smithy"); assertThat( - main, - equalTo( - String.format( - "$version: \"2.0\"%n" - + "%n" - + "metadata this_is_a_long_string = {%n" - + " this_is_a_long_string1: \"a\"%n" - + " this_is_a_long_string2: \"b\"%n" - + " this_is_a_long_string3: \"c\"%n" - + " this_is_a_long_string4: \"d\"%n" - + "}%n" + main, + equalTo( + String.format( + "$version: \"2.0\"%n" + + "%n" + + "metadata this_is_a_long_string = {%n" + + " this_is_a_long_string1: \"a\"%n" + + " this_is_a_long_string2: \"b\"%n" + + " this_is_a_long_string3: \"c\"%n" + + " this_is_a_long_string4: \"d\"%n" + + "}%n" + ) ) - ) ); String other = result.getFile("model/other.smithy"); assertThat( - other, - equalTo( - String.format( - "$version: \"2.0\"%n" - + "%n" - + "namespace smithy.example%n" - + "%n" - + "string MyString%n" - + "%n" - + "string MyString2%n" + other, + equalTo( + String.format( + "$version: \"2.0\"%n" + + "%n" + + "namespace smithy.example%n" + + "%n" + + "string MyString%n" + + "%n" + + "string MyString2%n" + ) ) - ) ); }); } diff --git a/smithy-cli/src/it/java/software/amazon/smithy/cli/InitCommandTest.java b/smithy-cli/src/it/java/software/amazon/smithy/cli/InitCommandTest.java index e13ceb70859..f9d8bf9b93e 100644 --- a/smithy-cli/src/it/java/software/amazon/smithy/cli/InitCommandTest.java +++ b/smithy-cli/src/it/java/software/amazon/smithy/cli/InitCommandTest.java @@ -35,12 +35,12 @@ public void init() { IntegUtils.withTempDir("exitZero", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of("init", "-t", "quickstart-cli", "-u", templatesDir.toString()) + dir, + ListUtils.of("init", "-t", "quickstart-cli", "-u", templatesDir.toString()) ); assertThat( - result.getOutput(), - containsString("Smithy project created in directory: quickstart-cli") + result.getOutput(), + containsString("Smithy project created in directory: quickstart-cli") ); assertThat(result.getExitCode(), is(0)); assertThat(Files.exists(Paths.get(dir.toString(), "quickstart-cli")), is(true)); @@ -55,12 +55,12 @@ public void usesDefaultTemplate() { IntegUtils.withTempDir("defaultTemplate", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of("init", "-u", templatesDir.toString()) + dir, + ListUtils.of("init", "-u", templatesDir.toString()) ); assertThat( - result.getOutput(), - containsString("Smithy project created in directory: quickstart-cli") + result.getOutput(), + containsString("Smithy project created in directory: quickstart-cli") ); assertThat(result.getExitCode(), is(0)); }); @@ -74,12 +74,12 @@ public void missingTemplate() { IntegUtils.withTempDir("emptyTemplateName", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of("init", "-t", "", "-u", templatesDir.toString()) + dir, + ListUtils.of("init", "-t", "", "-u", templatesDir.toString()) ); assertThat( - result.getOutput(), - containsString("Please specify a template name using `--template` or `-t`") + result.getOutput(), + containsString("Please specify a template name using `--template` or `-t`") ); assertThat(result.getExitCode(), is(1)); }); @@ -93,12 +93,12 @@ public void includedFileJson() { IntegUtils.withTempDir("includedFiles", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of("init", "-t", "included-file-json", "-u", templatesDir.toString()) + dir, + ListUtils.of("init", "-t", "included-file-json", "-u", templatesDir.toString()) ); assertThat( - result.getOutput(), - containsString("Smithy project created in directory: ") + result.getOutput(), + containsString("Smithy project created in directory: ") ); assertThat(result.getExitCode(), is(0)); assertThat(Files.exists(Paths.get(dir.toString(), "included-file-json")), is(true)); @@ -114,12 +114,12 @@ public void includedFileGradle() { IntegUtils.withTempDir("includedFilesGradle", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of("init", "-t", "included-files-gradle", "-u", templatesDir.toString()) + dir, + ListUtils.of("init", "-t", "included-files-gradle", "-u", templatesDir.toString()) ); assertThat( - result.getOutput(), - containsString("Smithy project created in directory: ") + result.getOutput(), + containsString("Smithy project created in directory: ") ); assertThat(result.getExitCode(), is(0)); assertThat(Files.exists(Paths.get(dir.toString(), "included-files-gradle")), is(true)); @@ -129,21 +129,26 @@ public void includedFileGradle() { throw new RuntimeException(e); } assertThat( - Files.exists(Paths.get(dir.toString(), "included-files-gradle/gradle.properties")), - is(true) + Files.exists(Paths.get(dir.toString(), "included-files-gradle/gradle.properties")), + is(true) ); assertThat(Files.exists(Paths.get(dir.toString(), "included-files-gradle/gradlew")), is(true)); assertThat(Files.exists(Paths.get(dir.toString(), "included-files-gradle/gradle")), is(true)); assertThat(Files.exists(Paths.get(dir.toString(), "included-files-gradle/gradle/wrapper")), is(true)); assertThat( - Files.exists(Paths.get(dir.toString(), "included-files-gradle/gradle/wrapper/gradle-wrapper.jar")), - is(true) + Files.exists( + Paths.get(dir.toString(), "included-files-gradle/gradle/wrapper/gradle-wrapper.jar") + ), + is(true) ); assertThat( - Files.exists( - Paths.get(dir.toString(), "included-files-gradle/gradle/wrapper/gradle-wrapper.properties") - ), - is(true) + Files.exists( + Paths.get( + dir.toString(), + "included-files-gradle/gradle/wrapper/gradle-wrapper.properties" + ) + ), + is(true) ); }); }); @@ -156,35 +161,35 @@ public void unexpectedTemplate() { IntegUtils.withTempDir("unexpectedTemplate", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of("init", "-t", "blabla", "-u", templatesDir.toString()) + dir, + ListUtils.of("init", "-t", "blabla", "-u", templatesDir.toString()) ); String expectedOutput = new StringBuilder() - .append("Invalid template `blabla`. `Smithy-Examples` provides the following templates:") - .append(System.lineSeparator()) - .append(System.lineSeparator()) - .append( - "───────────────────── ─────────────────────────────────────────────────────────────────────────────" - ) - .append(System.lineSeparator()) - .append("NAME DOCUMENTATION") - .append(System.lineSeparator()) - .append( - "───────────────────── ─────────────────────────────────────────────────────────────────────────────" - ) - .append(System.lineSeparator()) - .append("bad-include-path Template with incorrect include path. Should throw error.") - .append(System.lineSeparator()) - .append("bad-template-path Template with incorrect path. Should throw error.") - .append(System.lineSeparator()) - .append("included-file-json Smithy Quickstart example with json file included.") - .append(System.lineSeparator()) - .append("included-files-gradle Smithy Quickstart example with gradle files included.") - .append(System.lineSeparator()) - .append("quickstart-cli Smithy Quickstart example weather service.") - .append(System.lineSeparator()) - .toString(); + .append("Invalid template `blabla`. `Smithy-Examples` provides the following templates:") + .append(System.lineSeparator()) + .append(System.lineSeparator()) + .append( + "───────────────────── ─────────────────────────────────────────────────────────────────────────────" + ) + .append(System.lineSeparator()) + .append("NAME DOCUMENTATION") + .append(System.lineSeparator()) + .append( + "───────────────────── ─────────────────────────────────────────────────────────────────────────────" + ) + .append(System.lineSeparator()) + .append("bad-include-path Template with incorrect include path. Should throw error.") + .append(System.lineSeparator()) + .append("bad-template-path Template with incorrect path. Should throw error.") + .append(System.lineSeparator()) + .append("included-file-json Smithy Quickstart example with json file included.") + .append(System.lineSeparator()) + .append("included-files-gradle Smithy Quickstart example with gradle files included.") + .append(System.lineSeparator()) + .append("quickstart-cli Smithy Quickstart example weather service.") + .append(System.lineSeparator()) + .toString(); assertThat(result.getOutput(), containsString(expectedOutput)); assertThat(result.getExitCode(), is(1)); @@ -199,20 +204,20 @@ public void withDirectoryArg() { IntegUtils.withTempDir("withDirectoryArg", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of( - "init", - "-t", - "quickstart-cli", - "-o", - "hello-world", - "-u", - templatesDir.toString() - ) + dir, + ListUtils.of( + "init", + "-t", + "quickstart-cli", + "-o", + "hello-world", + "-u", + templatesDir.toString() + ) ); assertThat( - result.getOutput(), - containsString("Smithy project created in directory: hello-world") + result.getOutput(), + containsString("Smithy project created in directory: hello-world") ); assertThat(result.getExitCode(), is(0)); assertThat(Files.exists(Paths.get(dir.toString(), "hello-world")), is(true)); @@ -220,20 +225,20 @@ public void withDirectoryArg() { IntegUtils.withTempDir("withNestedDirectoryArg", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of( - "init", - "-t", - "quickstart-cli", - "-o", - "./hello/world", - "-u", - templatesDir.toString() - ) + dir, + ListUtils.of( + "init", + "-t", + "quickstart-cli", + "-o", + "./hello/world", + "-u", + templatesDir.toString() + ) ); assertThat( - result.getOutput(), - containsString("Smithy project created in directory: ./hello/world") + result.getOutput(), + containsString("Smithy project created in directory: ./hello/world") ); assertThat(result.getExitCode(), is(0)); assertThat(Files.exists(Paths.get(dir.toString(), "./hello/world")), is(true)); @@ -248,20 +253,20 @@ public void withLongHandArgs() { IntegUtils.withTempDir("withLongHandArgs", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of( - "init", - "--template", - "quickstart-cli", - "--output", - "hello-world", - "--url", - templatesDir.toString() - ) + dir, + ListUtils.of( + "init", + "--template", + "quickstart-cli", + "--output", + "hello-world", + "--url", + templatesDir.toString() + ) ); assertThat( - result.getOutput(), - containsString("Smithy project created in directory: hello-world") + result.getOutput(), + containsString("Smithy project created in directory: hello-world") ); assertThat(result.getExitCode(), is(0)); assertThat(Files.exists(Paths.get(dir.toString(), "hello-world")), is(true)); @@ -276,37 +281,37 @@ public void withListArg() { IntegUtils.withTempDir("withListArg", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of( - "init", - "--list", - "--url", - templatesDir.toString() - ) + dir, + ListUtils.of( + "init", + "--list", + "--url", + templatesDir.toString() + ) ); String expectedOutput = new StringBuilder() - .append( - "───────────────────── ─────────────────────────────────────────────────────────────────────────────" - ) - .append(System.lineSeparator()) - .append("NAME DOCUMENTATION") - .append(System.lineSeparator()) - .append( - "───────────────────── ─────────────────────────────────────────────────────────────────────────────" - ) - .append(System.lineSeparator()) - .append("bad-include-path Template with incorrect include path. Should throw error.") - .append(System.lineSeparator()) - .append("bad-template-path Template with incorrect path. Should throw error.") - .append(System.lineSeparator()) - .append("included-file-json Smithy Quickstart example with json file included.") - .append(System.lineSeparator()) - .append("included-files-gradle Smithy Quickstart example with gradle files included.") - .append(System.lineSeparator()) - .append("quickstart-cli Smithy Quickstart example weather service.") - .append(System.lineSeparator()) - .toString(); + .append( + "───────────────────── ─────────────────────────────────────────────────────────────────────────────" + ) + .append(System.lineSeparator()) + .append("NAME DOCUMENTATION") + .append(System.lineSeparator()) + .append( + "───────────────────── ─────────────────────────────────────────────────────────────────────────────" + ) + .append(System.lineSeparator()) + .append("bad-include-path Template with incorrect include path. Should throw error.") + .append(System.lineSeparator()) + .append("bad-template-path Template with incorrect path. Should throw error.") + .append(System.lineSeparator()) + .append("included-file-json Smithy Quickstart example with json file included.") + .append(System.lineSeparator()) + .append("included-files-gradle Smithy Quickstart example with gradle files included.") + .append(System.lineSeparator()) + .append("quickstart-cli Smithy Quickstart example weather service.") + .append(System.lineSeparator()) + .toString(); assertThat(result.getOutput(), containsString(expectedOutput)); assertThat(result.getExitCode(), is(0)); @@ -325,8 +330,8 @@ public void outputDirectoryAlreadyExists() { try { existingPath = Files.createDirectory(dir.resolve("quickstart-cli")); result = IntegUtils.run( - dir, - ListUtils.of("init", "-t", "quickstart-cli", "-u", templatesDir.toString()) + dir, + ListUtils.of("init", "-t", "quickstart-cli", "-u", templatesDir.toString()) ); } catch (IOException e) { throw new RuntimeException(e); @@ -347,8 +352,8 @@ public void executesInitSuccessQuiet() { IntegUtils.withTempDir("exitZeroQuiet", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of("init", "--quiet", "-t", "quickstart-cli", "-u", templatesDir.toString()) + dir, + ListUtils.of("init", "--quiet", "-t", "quickstart-cli", "-u", templatesDir.toString()) ); assertThat(result.getOutput().trim(), emptyString()); @@ -365,17 +370,17 @@ public void badTemplatePathFailureExpected() { IntegUtils.withTempDir("badTemplatePath", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of("init", "-t", "bad-template-path", "-u", templatesDir.toString()) + dir, + ListUtils.of("init", "-t", "bad-template-path", "-u", templatesDir.toString()) ); assertThat(Files.exists(Paths.get(dir.toString(), "bad-template-path")), is(false)); assertThat(result.getExitCode(), is(1)); assertThat( - result.getOutput(), - containsString( - "Template path `getting-started-example/does-not-exist` for template" - + " \"bad-template-path\" is invalid." - ) + result.getOutput(), + containsString( + "Template path `getting-started-example/does-not-exist` for template" + + " \"bad-template-path\" is invalid." + ) ); }); }); @@ -388,17 +393,17 @@ public void badIncludePathFailureExpected() { IntegUtils.withTempDir("badIncludePath", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of("init", "-t", "bad-include-path", "-u", templatesDir.toString()) + dir, + ListUtils.of("init", "-t", "bad-include-path", "-u", templatesDir.toString()) ); assertThat(Files.exists(Paths.get(dir.toString(), " bad-include-path")), is(false)); assertThat(result.getExitCode(), is(1)); assertThat( - result.getOutput(), - containsString( - "File or directory `getting-started-example/does-not-exist` is marked" - + " for inclusion in template \"bad-include-path\", but was not found" - ) + result.getOutput(), + containsString( + "File or directory `getting-started-example/does-not-exist` is marked" + + " for inclusion in template \"bad-include-path\", but was not found" + ) ); }); }); @@ -411,30 +416,30 @@ public void cacheCreatedOnFirstCreationOfTemplate() { try { RunResult resultFirst = IntegUtils.run(root, ListUtils.of("init", "-o", "hello-world")); assertTrue( - Files.exists(IntegUtils.SMITHY_TEMPLATE_CACHE_PATH) - && Files.isDirectory(IntegUtils.SMITHY_TEMPLATE_CACHE_PATH) + Files.exists(IntegUtils.SMITHY_TEMPLATE_CACHE_PATH) + && Files.isDirectory(IntegUtils.SMITHY_TEMPLATE_CACHE_PATH) ); assertThat(resultFirst.getExitCode(), equalTo(0)); assertThat( - resultFirst.getOutput(), - containsString("template repo cloned") + resultFirst.getOutput(), + containsString("template repo cloned") ); assertThat( - resultFirst.getOutput(), - containsString("Smithy project created in directory: hello-world") + resultFirst.getOutput(), + containsString("Smithy project created in directory: hello-world") ); IoUtils.rmdir(root.resolve("hello-world")); RunResult resultSecond = IntegUtils.run(root, ListUtils.of("init", "-o", "hello-world")); assertTrue( - Files.exists(IntegUtils.SMITHY_TEMPLATE_CACHE_PATH) - && Files.isDirectory(IntegUtils.SMITHY_TEMPLATE_CACHE_PATH) + Files.exists(IntegUtils.SMITHY_TEMPLATE_CACHE_PATH) + && Files.isDirectory(IntegUtils.SMITHY_TEMPLATE_CACHE_PATH) ); assertThat(resultSecond.getExitCode(), equalTo(0)); assertThat(resultSecond.getOutput(), not(containsString("template repo cloned"))); assertThat( - resultSecond.getOutput(), - containsString("Smithy project created in directory: hello-world") + resultSecond.getOutput(), + containsString("Smithy project created in directory: hello-world") ); } finally { IntegUtils.clearCacheDirIfExists(); @@ -450,12 +455,12 @@ public void noCacheCreatedWhenLocalRepo() { IntegUtils.withTempDir("exitZero", dir -> { RunResult result = IntegUtils.run( - dir, - ListUtils.of("init", "-t", "quickstart-cli", "-u", templatesDir.toString()) + dir, + ListUtils.of("init", "-t", "quickstart-cli", "-u", templatesDir.toString()) ); assertThat( - result.getOutput(), - containsString("Smithy project created in directory: quickstart-cli") + result.getOutput(), + containsString("Smithy project created in directory: quickstart-cli") ); assertThat(result.getExitCode(), is(0)); assertThat(Files.exists(Paths.get(dir.toString(), "quickstart-cli")), is(true)); diff --git a/smithy-cli/src/it/java/software/amazon/smithy/cli/IntegUtils.java b/smithy-cli/src/it/java/software/amazon/smithy/cli/IntegUtils.java index 6c574bc10d4..67a87c592b1 100644 --- a/smithy-cli/src/it/java/software/amazon/smithy/cli/IntegUtils.java +++ b/smithy-cli/src/it/java/software/amazon/smithy/cli/IntegUtils.java @@ -29,7 +29,7 @@ public final class IntegUtils { public static final Path SMITHY_ROOT_CACHE_PATH = Paths.get(System.getProperty("java.io.tmpdir")) - .resolve("smithy-cache"); + .resolve("smithy-cache"); public static final Path SMITHY_TEMPLATE_CACHE_PATH = SMITHY_ROOT_CACHE_PATH.resolve("templates"); private static final Logger LOGGER = Logger.getLogger(IntegUtils.class.getName()); @@ -47,19 +47,19 @@ public static void run(String projectName, List args, Consumer args, - Map env, - Consumer consumer + String projectName, + List args, + Map env, + Consumer consumer ) { withProject(projectName, path -> consumer.accept(run(path, args, env))); } public static void runWithEmptyCache( - String projectName, - List args, - Map env, - Consumer consumer + String projectName, + List args, + Map env, + Consumer consumer ) { try { String cacheDir = Files.createTempDirectory("foo").toString(); diff --git a/smithy-cli/src/it/java/software/amazon/smithy/cli/LockCommandTest.java b/smithy-cli/src/it/java/software/amazon/smithy/cli/LockCommandTest.java index 094a0ab8bec..f583d32cf3c 100644 --- a/smithy-cli/src/it/java/software/amazon/smithy/cli/LockCommandTest.java +++ b/smithy-cli/src/it/java/software/amazon/smithy/cli/LockCommandTest.java @@ -33,28 +33,28 @@ public void writesLockfile() throws IOException { // artifact mockArtifactAndSha( - mockServer, - "/artifactory-2/com/example/artifact/1.0.0/artifact-1.0.0.jar", - "FAKE JAR CONTENT" + mockServer, + "/artifactory-2/com/example/artifact/1.0.0/artifact-1.0.0.jar", + "FAKE JAR CONTENT" ); mockArtifactAndSha( - mockServer, - "/artifactory-2/com/example/artifact/maven-metadata.xml", - getMetadataForVersions(ListUtils.of("1.0.0")) + mockServer, + "/artifactory-2/com/example/artifact/maven-metadata.xml", + getMetadataForVersions(ListUtils.of("1.0.0")) ); mockArtifactAndSha( - mockServer, - "/artifactory-2/com/example/artifact/1.0.0/artifact-1.0.0.pom", - pomFileContents() + mockServer, + "/artifactory-2/com/example/artifact/1.0.0/artifact-1.0.0.pom", + pomFileContents() ); // Dependency mockArtifactAndSha( - mockServer, - "/artifactory-1/com/example/dependency/1.0.0/dependency-1.0.0.jar", - "ANOTHER FAKE JAR" + mockServer, + "/artifactory-1/com/example/dependency/1.0.0/dependency-1.0.0.jar", + "ANOTHER FAKE JAR" ); // Use an empty cache @@ -67,10 +67,10 @@ public void writesLockfile() throws IOException { RunResult lockResult = IntegUtils.run(root, ListUtils.of("lock", "--debug"), env); assertThat(lockResult.getExitCode(), equalTo(0)); assertThat( - lockResult.getOutput(), - containsString( - "software.amazon.smithy.cli.dependencies.DependencyResolver - Resolved Maven dependencies: [com.example:artifact:jar:1.0.0" - ) + lockResult.getOutput(), + containsString( + "software.amazon.smithy.cli.dependencies.DependencyResolver - Resolved Maven dependencies: [com.example:artifact:jar:1.0.0" + ) ); assertThat(lockResult.getOutput(), containsString("Saving resolved artifacts to lockfile.")); @@ -78,8 +78,8 @@ public void writesLockfile() throws IOException { RunResult validateResult = IntegUtils.run(root, ListUtils.of("validate", "--debug"), env); assertThat(validateResult.getExitCode(), equalTo(0)); assertThat( - validateResult.getOutput(), - containsString("`smithy-lock.json` found. Using locked dependencies: ") + validateResult.getOutput(), + containsString("`smithy-lock.json` found. Using locked dependencies: ") ); }); } finally { @@ -97,42 +97,42 @@ public void lockedDependenciesUsed() { // artifacts mockArtifactAndSha( - mockServer, - "/artifactory-2/com/example/artifact/1.0.0/artifact-1.0.0.jar", - "FAKE JAR CONTENT" + mockServer, + "/artifactory-2/com/example/artifact/1.0.0/artifact-1.0.0.jar", + "FAKE JAR CONTENT" ); mockArtifactAndSha( - mockServer, - "/artifactory-2/com/example/artifact/1.1.0/artifact-1.1.0.jar", - "FAKE JAR CONTENT" + mockServer, + "/artifactory-2/com/example/artifact/1.1.0/artifact-1.1.0.jar", + "FAKE JAR CONTENT" ); mockArtifactAndSha( - mockServer, - "/artifactory-2/com/example/artifact/1.2.0/artifact-1.2.0.jar", - "FAKE JAR CONTENT" + mockServer, + "/artifactory-2/com/example/artifact/1.2.0/artifact-1.2.0.jar", + "FAKE JAR CONTENT" ); mockArtifactAndSha( - mockServer, - "/artifactory-2/com/example/artifact/maven-metadata.xml", - getMetadataForVersions(ListUtils.of("1.2.0", "1.1.0", "1.0.0")) + mockServer, + "/artifactory-2/com/example/artifact/maven-metadata.xml", + getMetadataForVersions(ListUtils.of("1.2.0", "1.1.0", "1.0.0")) ); IntegUtils.runWithEmptyCache( - "lockfile-used", - ListUtils.of("validate", "--debug"), - Collections.emptyMap(), - result -> { - assertThat(result.getExitCode(), equalTo(0)); - assertThat( - result.getOutput(), - containsString( - "software.amazon.smithy.cli.dependencies.DependencyResolver - Resolved Maven dependencies: [com.example:artifact:jar:1.1.0" - ) - ); - } + "lockfile-used", + ListUtils.of("validate", "--debug"), + Collections.emptyMap(), + result -> { + assertThat(result.getExitCode(), equalTo(0)); + assertThat( + result.getOutput(), + containsString( + "software.amazon.smithy.cli.dependencies.DependencyResolver - Resolved Maven dependencies: [com.example:artifact:jar:1.1.0" + ) + ); + } ); } finally { if (mockServer != null) { @@ -144,62 +144,62 @@ public void lockedDependenciesUsed() { @Test public void clashingLockAndConfigThrowsException() { IntegUtils.runWithEmptyCache( - "clashing-lockfile", - ListUtils.of("validate", "--debug"), - Collections.emptyMap(), - result -> { - assertThat(result.getExitCode(), equalTo(1)); - assertThat( - result.getOutput(), - containsString("`smithy-lock.json` does not match configured dependencies.") - ); - } + "clashing-lockfile", + ListUtils.of("validate", "--debug"), + Collections.emptyMap(), + result -> { + assertThat(result.getExitCode(), equalTo(1)); + assertThat( + result.getOutput(), + containsString("`smithy-lock.json` does not match configured dependencies.") + ); + } ); } private String getMetadataForVersions(List versions) { String versionSection = versions.stream() - .map(v -> "" + v + "\n") - .collect(Collectors.joining()); + .map(v -> "" + v + "\n") + .collect(Collectors.joining()); return "\n" + - "\n" + - " com.example\n" + - " artifact\n" + - " " + versions.get(0) + "\n" + - " \n" + - " " + versions.get(0) + "\n" + - " " + versions.get(0) + "\n" + - " \n" + versionSection + - " \n" + - " 20230724184336\n" + - " \n" + - "\n"; + "\n" + + " com.example\n" + + " artifact\n" + + " " + versions.get(0) + "\n" + + " \n" + + " " + versions.get(0) + "\n" + + " " + versions.get(0) + "\n" + + " \n" + versionSection + + " \n" + + " 20230724184336\n" + + " \n" + + "\n"; } private String pomFileContents() { return "\n" + - "\n" - + - " 4.0.0\n" + - " com.example\n" + - " artifact\n" + - " jar\n" + - " artifact\n" + - " 1.0.0\n" + - " artifact\n" + - " \n" + - " com.example\n" + - " \n" + - " \n" + - " early-semver\n" + - " \n" + - " \n" + - " \n" + - " com.example\n" + - " dependency\n" + - " 1.0.0\n" + - " \n" + - " \n" + - ""; + "\n" + + + " 4.0.0\n" + + " com.example\n" + + " artifact\n" + + " jar\n" + + " artifact\n" + + " 1.0.0\n" + + " artifact\n" + + " \n" + + " com.example\n" + + " \n" + + " \n" + + " early-semver\n" + + " \n" + + " \n" + + " \n" + + " com.example\n" + + " dependency\n" + + " 1.0.0\n" + + " \n" + + " \n" + + ""; } } diff --git a/smithy-cli/src/it/java/software/amazon/smithy/cli/MavenResolverMultipleReposTest.java b/smithy-cli/src/it/java/software/amazon/smithy/cli/MavenResolverMultipleReposTest.java index 1432a1fc46b..913339b64d4 100644 --- a/smithy-cli/src/it/java/software/amazon/smithy/cli/MavenResolverMultipleReposTest.java +++ b/smithy-cli/src/it/java/software/amazon/smithy/cli/MavenResolverMultipleReposTest.java @@ -29,46 +29,46 @@ public void multipleRepositoriesOnSameHostName() { // artifact mockArtifactAndSha( - mockServer, - "/artifactory-2/com/example/artifact/1.0.0-SNAPSHOT/artifact-1.0.0-20230724.184336-2.jar", - "FAKE JAR CONTENT" + mockServer, + "/artifactory-2/com/example/artifact/1.0.0-SNAPSHOT/artifact-1.0.0-20230724.184336-2.jar", + "FAKE JAR CONTENT" ); mockArtifactAndSha( - mockServer, - "/artifactory-2/com/example/artifact/1.0.0-SNAPSHOT/artifact-1.0.0-20230724.184336-1.pom", - pomFileContents() + mockServer, + "/artifactory-2/com/example/artifact/1.0.0-SNAPSHOT/artifact-1.0.0-20230724.184336-1.pom", + pomFileContents() ); mockArtifactAndSha( - mockServer, - "/artifactory-2/com/example/artifact/1.0.0-SNAPSHOT/maven-metadata.xml", - metadataFileContents() + mockServer, + "/artifactory-2/com/example/artifact/1.0.0-SNAPSHOT/maven-metadata.xml", + metadataFileContents() ); // dependency mockArtifactAndSha( - mockServer, - "/artifactory-1/com/example/dependency/1.0.0/dependency-1.0.0.jar", - "ANOTHER FAKE JAR" + mockServer, + "/artifactory-1/com/example/dependency/1.0.0/dependency-1.0.0.jar", + "ANOTHER FAKE JAR" ); mockNotFound(mockServer, "/artifactory-1/.*"); mockNotFound(mockServer, "/artifactory-2/.*"); IntegUtils.runWithEmptyCache( - "maven-multiple-repos", - ListUtils.of("validate", "--debug"), - Collections.emptyMap(), - result -> { - assertThat(result.getExitCode(), equalTo(0)); - assertThat( - result.getOutput(), - containsString( - "software.amazon.smithy.cli.dependencies.DependencyResolver - Resolved Maven dependencies: [com.example:artifact:jar:1.0.0-20230724.184336-2" - ) - ); - } + "maven-multiple-repos", + ListUtils.of("validate", "--debug"), + Collections.emptyMap(), + result -> { + assertThat(result.getExitCode(), equalTo(0)); + assertThat( + result.getOutput(), + containsString( + "software.amazon.smithy.cli.dependencies.DependencyResolver - Resolved Maven dependencies: [com.example:artifact:jar:1.0.0-20230724.184336-2" + ) + ); + } ); } finally { if (mockServer != null) { @@ -79,94 +79,94 @@ public void multipleRepositoriesOnSameHostName() { public static void mockArtifactAndSha(ClientAndServer mockServer, String path, String contents) { mockSuccess( - mockServer, - path, - contents + mockServer, + path, + contents ); mockSuccess( - mockServer, - path + ".sha1", - DigestUtils.sha1Hex(contents) + mockServer, + path + ".sha1", + DigestUtils.sha1Hex(contents) ); } private String metadataFileContents() { return "\n" + - "\n" + - " com.example\n" + - " artifact\n" + - " 1.0.0-SNAPSHOT\n" + - " \n" + - " \n" + - " 20230724.184336\n" + - " 1\n" + - " \n" + - " 20230724184336\n" + - " \n" + - " \n" + - " jar\n" + - " 1.0.0-20230724.184336-2\n" + - " 20230724184336\n" + - " \n" + - " \n" + - " pom\n" + - " 1.0.0-20230724.184336-1\n" + - " 20230724184336\n" + - " \n" + - " \n" + - " \n" + - "\n"; + "\n" + + " com.example\n" + + " artifact\n" + + " 1.0.0-SNAPSHOT\n" + + " \n" + + " \n" + + " 20230724.184336\n" + + " 1\n" + + " \n" + + " 20230724184336\n" + + " \n" + + " \n" + + " jar\n" + + " 1.0.0-20230724.184336-2\n" + + " 20230724184336\n" + + " \n" + + " \n" + + " pom\n" + + " 1.0.0-20230724.184336-1\n" + + " 20230724184336\n" + + " \n" + + " \n" + + " \n" + + "\n"; } private String pomFileContents() { return "\n" + - "\n" - + - " 4.0.0\n" + - " com.example\n" + - " artifact\n" + - " jar\n" + - " artifact\n" + - " 1.0.0-SNAPSHOT\n" + - " artifact\n" + - " \n" + - " com.example\n" + - " \n" + - " \n" + - " early-semver\n" + - " \n" + - " \n" + - " \n" + - " com.example\n" + - " dependency\n" + - " 1.0.0\n" + - " \n" + - " \n" + - ""; + "\n" + + + " 4.0.0\n" + + " com.example\n" + + " artifact\n" + + " jar\n" + + " artifact\n" + + " 1.0.0-SNAPSHOT\n" + + " artifact\n" + + " \n" + + " com.example\n" + + " \n" + + " \n" + + " early-semver\n" + + " \n" + + " \n" + + " \n" + + " com.example\n" + + " dependency\n" + + " 1.0.0\n" + + " \n" + + " \n" + + ""; } private static void mockNotFound(ClientAndServer mockServer, String path) { mockServer.when( - HttpRequest - .request() - .withMethod("GET") - .withPath(path) + HttpRequest + .request() + .withMethod("GET") + .withPath(path) ).respond(HttpResponse.notFoundResponse()); } private static void mockSuccess(ClientAndServer mockServer, String path, String responseBody) { mockServer.when( - HttpRequest - .request() - .withMethod("GET") - .withPath(path) + HttpRequest + .request() + .withMethod("GET") + .withPath(path) ) - .respond( - HttpResponse - .response() - .withStatusCode(200) - .withBody(responseBody) - ); + .respond( + HttpResponse + .response() + .withStatusCode(200) + .withBody(responseBody) + ); } } diff --git a/smithy-cli/src/it/java/software/amazon/smithy/cli/MavenResolverTest.java b/smithy-cli/src/it/java/software/amazon/smithy/cli/MavenResolverTest.java index 296350badd8..c5116eb926f 100644 --- a/smithy-cli/src/it/java/software/amazon/smithy/cli/MavenResolverTest.java +++ b/smithy-cli/src/it/java/software/amazon/smithy/cli/MavenResolverTest.java @@ -61,8 +61,8 @@ public void lowerSmithyVersionsAreUpgradedToNewerVersionsQuiet() { IntegUtils.run("lower-smithy-version", ListUtils.of("validate", "--quiet"), result -> { assertThat(result.getExitCode(), equalTo(0)); assertThat( - result.getOutput(), - not(containsString("Replacing software.amazon.smithy:smithy-model:jar:1.0.0")) + result.getOutput(), + not(containsString("Replacing software.amazon.smithy:smithy-model:jar:1.0.0")) ); }); } @@ -81,43 +81,45 @@ public void usesCustomRepoWithAuth() { try { mockServer = startClientAndServer(1234); mockServer.when( - HttpRequest - .request() - .withMethod("GET") - .withHeader("Authorization", "Basic eHh4Onl5eQ==") - .withPath("/maven/not/there/software/amazon/smithy/smithy-aws-iam-traits/.*\\.jar") + HttpRequest + .request() + .withMethod("GET") + .withHeader("Authorization", "Basic eHh4Onl5eQ==") + .withPath("/maven/not/there/software/amazon/smithy/smithy-aws-iam-traits/.*\\.jar") ) - .respond( - HttpResponse - .response() - .withStatusCode(200) - .withBody("FAKE JAR CONTENT") - ); + .respond( + HttpResponse + .response() + .withStatusCode(200) + .withBody("FAKE JAR CONTENT") + ); mockServer.when( - HttpRequest - .request() - .withMethod("GET") - .withPath("/maven/not/there/software/amazon/smithy/smithy-aws-iam-traits/.*") + HttpRequest + .request() + .withMethod("GET") + .withPath("/maven/not/there/software/amazon/smithy/smithy-aws-iam-traits/.*") ) - .respond( - HttpResponse - .response() - .withStatusCode(401) - .withHeader("WWW-Authenticate", "Basic realm=\"Artifactory Realm\"") - ); + .respond( + HttpResponse + .response() + .withStatusCode(401) + .withHeader("WWW-Authenticate", "Basic realm=\"Artifactory Realm\"") + ); IntegUtils.runWithEmptyCache( - "maven-auth", - ListUtils.of("validate", "--debug"), - Collections.emptyMap(), - result -> { - assertThat(result.getExitCode(), equalTo(1)); - assertThat( - result.getOutput(), - containsString("HttpAuthenticator - Selected authentication options: [BASIC [complete=true]]") - ); - assertThat(result.getOutput(), containsString("HttpAuthenticator - Authentication succeeded")); - } + "maven-auth", + ListUtils.of("validate", "--debug"), + Collections.emptyMap(), + result -> { + assertThat(result.getExitCode(), equalTo(1)); + assertThat( + result.getOutput(), + containsString( + "HttpAuthenticator - Selected authentication options: [BASIC [complete=true]]" + ) + ); + assertThat(result.getOutput(), containsString("HttpAuthenticator - Authentication succeeded")); + } ); } finally { if (mockServer != null) { @@ -135,30 +137,30 @@ public void usesProxyConfiguration() { proxyServer = startClientAndProxy(2323); HttpRequest request = HttpRequest.request() - .withMethod("GET") - .withPath("/maven/not/there/software/amazon/smithy/smithy-aws-iam-traits/.*\\.jar"); + .withMethod("GET") + .withPath("/maven/not/there/software/amazon/smithy/smithy-aws-iam-traits/.*\\.jar"); mockServer.when(request) - .respond( - HttpResponse - .response() - .withStatusCode(200) - .withBody("FAKE JAR CONTENT") - ); + .respond( + HttpResponse + .response() + .withStatusCode(200) + .withBody("FAKE JAR CONTENT") + ); IntegUtils.runWithEmptyCache( - "maven-proxy", - ListUtils.of("validate", "--debug"), - Collections.emptyMap(), - result -> { - assertThat(result.getExitCode(), equalTo(0)); - assertThat(result.getOutput(), containsString("Resolving Maven dependencies for Smithy CLI")); - assertThat( - result.getOutput(), - containsString("Opening connection {}->http://localhost:2323->http://localhost:1234") - ); - assertThat(result.getOutput(), containsString("Connecting to localhost/127.0.0.1:2323")); - } + "maven-proxy", + ListUtils.of("validate", "--debug"), + Collections.emptyMap(), + result -> { + assertThat(result.getExitCode(), equalTo(0)); + assertThat(result.getOutput(), containsString("Resolving Maven dependencies for Smithy CLI")); + assertThat( + result.getOutput(), + containsString("Opening connection {}->http://localhost:2323->http://localhost:1234") + ); + assertThat(result.getOutput(), containsString("Connecting to localhost/127.0.0.1:2323")); + } ); // Check that expected request was forwarded by the proxy proxyServer.verify(request); @@ -182,34 +184,34 @@ public void usesProxyConfigurationFromEnv() { proxyServer = startClientAndProxy(2323); HttpRequest request = HttpRequest.request() - .withMethod("GET") - .withPath("/maven/not/there/software/amazon/smithy/smithy-aws-iam-traits/.*\\.jar"); + .withMethod("GET") + .withPath("/maven/not/there/software/amazon/smithy/smithy-aws-iam-traits/.*\\.jar"); mockServer.when(request) - .respond( - HttpResponse - .response() - .withStatusCode(200) - .withBody("FAKE JAR CONTENT") - ); + .respond( + HttpResponse + .response() + .withStatusCode(200) + .withBody("FAKE JAR CONTENT") + ); Map envMap = MapUtils.of( - EnvironmentVariable.SMITHY_PROXY_HOST.toString(), - "http://localhost:2323" + EnvironmentVariable.SMITHY_PROXY_HOST.toString(), + "http://localhost:2323" ); IntegUtils.runWithEmptyCache( - "maven-proxy-env", - ListUtils.of("validate", "--debug"), - envMap, - result -> { - assertThat(result.getExitCode(), equalTo(0)); - assertThat(result.getOutput(), containsString("Resolving Maven dependencies for Smithy CLI")); - assertThat( - result.getOutput(), - containsString("Opening connection {}->http://localhost:2323->http://localhost:1234") - ); - assertThat(result.getOutput(), containsString("Connecting to localhost/127.0.0.1:2323")); - } + "maven-proxy-env", + ListUtils.of("validate", "--debug"), + envMap, + result -> { + assertThat(result.getExitCode(), equalTo(0)); + assertThat(result.getOutput(), containsString("Resolving Maven dependencies for Smithy CLI")); + assertThat( + result.getOutput(), + containsString("Opening connection {}->http://localhost:2323->http://localhost:1234") + ); + assertThat(result.getOutput(), containsString("Connecting to localhost/127.0.0.1:2323")); + } ); // Check that expected request was forwarded by the proxy proxyServer.verify(request); @@ -230,8 +232,8 @@ public void ignoresEmptyCacheFiles() { try { Files.createDirectories(path.resolve("build").resolve("smithy")); Files.write( - path.resolve("build").resolve("smithy").resolve("classpath.json"), - "".getBytes(StandardCharsets.UTF_8) + path.resolve("build").resolve("smithy").resolve("classpath.json"), + "".getBytes(StandardCharsets.UTF_8) ); RunResult result = IntegUtils.run(path, ListUtils.of("validate", "--debug", "model")); @@ -253,10 +255,10 @@ public void deletesStaleCacheFiles() { // Update the config file lastModified time to force the cache to be invalidated. assertThat( - result.resolve(result.getRoot(), "smithy-build.json") - .toFile() - .setLastModified(System.currentTimeMillis()), - is(true) + result.resolve(result.getRoot(), "smithy-build.json") + .toFile() + .setLastModified(System.currentTimeMillis()), + is(true) ); // Do the next run and expect it to resolve, invalidate the cache, and work. @@ -279,8 +281,8 @@ public void invalidatesCacheWhenDependencyChanges() { ObjectNode node = Node.parse(cacheContents).expectObjectNode(); ObjectNode artifacts = node.expectObjectMember("artifacts"); String location = artifacts.expectObjectMember( - "software.amazon.smithy:smithy-aws-traits:" - + TEST_VERSION + "software.amazon.smithy:smithy-aws-traits:" + + TEST_VERSION ).expectStringMember("path").getValue(); // Set the lastModified of the JAR to the current time, which is > than the time of the config file, @@ -298,38 +300,38 @@ public void invalidatesCacheWhenDependencyChanges() { @Test public void canIgnoreDependencyResolution() { IntegUtils.run( - "aws-model", - ListUtils.of("validate", "model"), - MapUtils.of(EnvironmentVariable.SMITHY_DEPENDENCY_MODE.toString(), "ignore"), - result -> { - assertThat(result.getExitCode(), equalTo(1)); - } + "aws-model", + ListUtils.of("validate", "model"), + MapUtils.of(EnvironmentVariable.SMITHY_DEPENDENCY_MODE.toString(), "ignore"), + result -> { + assertThat(result.getExitCode(), equalTo(1)); + } ); } @Test public void canForbidDependencyResolution() { IntegUtils.run( - "aws-model", - ListUtils.of("validate", "model"), - MapUtils.of(EnvironmentVariable.SMITHY_DEPENDENCY_MODE.toString(), "forbid"), - result -> { - assertThat(result.getExitCode(), equalTo(1)); - assertThat(result.getOutput(), containsString("set to 'forbid'")); - } + "aws-model", + ListUtils.of("validate", "model"), + MapUtils.of(EnvironmentVariable.SMITHY_DEPENDENCY_MODE.toString(), "forbid"), + result -> { + assertThat(result.getExitCode(), equalTo(1)); + assertThat(result.getOutput(), containsString("set to 'forbid'")); + } ); } @Test public void validatesDependencyResolution() { IntegUtils.run( - "aws-model", - ListUtils.of("validate", "model"), - MapUtils.of(EnvironmentVariable.SMITHY_DEPENDENCY_MODE.toString(), "Beeblebrox"), - result -> { - assertThat(result.getExitCode(), equalTo(1)); - assertThat(result.getOutput(), containsString("Beeblebrox")); - } + "aws-model", + ListUtils.of("validate", "model"), + MapUtils.of(EnvironmentVariable.SMITHY_DEPENDENCY_MODE.toString(), "Beeblebrox"), + result -> { + assertThat(result.getExitCode(), equalTo(1)); + assertThat(result.getOutput(), containsString("Beeblebrox")); + } ); } @@ -338,27 +340,27 @@ public void canDisableMavenLocalDefaultWithEnvSetting() { // Note that running with an empty cache means it can't find the packages at all. Running with a cache // means it could potentially find the packages. IntegUtils.runWithEmptyCache( - "aws-model", - ListUtils.of("validate", "--debug", "model"), - MapUtils.of(EnvironmentVariable.SMITHY_MAVEN_REPOS.toString(), ""), - result -> { - assertThat(result.getExitCode(), equalTo(1)); - } + "aws-model", + ListUtils.of("validate", "--debug", "model"), + MapUtils.of(EnvironmentVariable.SMITHY_MAVEN_REPOS.toString(), ""), + result -> { + assertThat(result.getExitCode(), equalTo(1)); + } ); } @Test public void canSetMavenReposUsingEnvironmentVariable() { IntegUtils.runWithEmptyCache( - "aws-model", - ListUtils.of("validate", "--debug", "model"), - MapUtils.of( - EnvironmentVariable.SMITHY_MAVEN_REPOS.toString(), - "https://repo.maven.apache.org/maven2" - ), - result -> { - assertThat(result.getExitCode(), equalTo(0)); - } + "aws-model", + ListUtils.of("validate", "--debug", "model"), + MapUtils.of( + EnvironmentVariable.SMITHY_MAVEN_REPOS.toString(), + "https://repo.maven.apache.org/maven2" + ), + result -> { + assertThat(result.getExitCode(), equalTo(0)); + } ); } @@ -366,13 +368,13 @@ public void canSetMavenReposUsingEnvironmentVariable() { public void setSetMavenRepoWithEnvUsingAuth() { String repo = "https://xxx:yyy@localhost:1234/maven/not/there"; IntegUtils.runWithEmptyCache( - "aws-model", - ListUtils.of("validate", "--debug", "model"), - MapUtils.of(EnvironmentVariable.SMITHY_MAVEN_REPOS.toString(), repo), - result -> { - assertThat(result.getOutput(), containsString("username=xxx, password=***")); - assertThat(result.getExitCode(), equalTo(1)); - } + "aws-model", + ListUtils.of("validate", "--debug", "model"), + MapUtils.of(EnvironmentVariable.SMITHY_MAVEN_REPOS.toString(), repo), + result -> { + assertThat(result.getOutput(), containsString("username=xxx, password=***")); + assertThat(result.getExitCode(), equalTo(1)); + } ); } } diff --git a/smithy-cli/src/it/java/software/amazon/smithy/cli/RootCommandTest.java b/smithy-cli/src/it/java/software/amazon/smithy/cli/RootCommandTest.java index e75e221f661..a233cfe613c 100644 --- a/smithy-cli/src/it/java/software/amazon/smithy/cli/RootCommandTest.java +++ b/smithy-cli/src/it/java/software/amazon/smithy/cli/RootCommandTest.java @@ -68,21 +68,21 @@ public void errorsOnInvalidArgument() { @Test public void runsWithColors() { IntegUtils.run( - "simple-config-sources", - ListUtils.of("--help"), - MapUtils.of(EnvironmentVariable.FORCE_COLOR.toString(), "true"), - result -> { - assertThat(result.getExitCode(), equalTo(0)); - assertThat(result.getOutput(), containsString("[0m")); - } + "simple-config-sources", + ListUtils.of("--help"), + MapUtils.of(EnvironmentVariable.FORCE_COLOR.toString(), "true"), + result -> { + assertThat(result.getExitCode(), equalTo(0)); + assertThat(result.getOutput(), containsString("[0m")); + } ); } private void ensureHelpOutput(RunResult result) { // Make sure it's the help output. assertThat( - result.getOutput(), - containsString("Usage: smithy [-h | --help] [--version] []") + result.getOutput(), + containsString("Usage: smithy [-h | --help] [--version] []") ); // Make sure commands are listed. assertThat(result.getOutput(), containsString("Available commands:")); diff --git a/smithy-cli/src/it/java/software/amazon/smithy/cli/RunResult.java b/smithy-cli/src/it/java/software/amazon/smithy/cli/RunResult.java index 43fcb88d434..18755e91d15 100644 --- a/smithy-cli/src/it/java/software/amazon/smithy/cli/RunResult.java +++ b/smithy-cli/src/it/java/software/amazon/smithy/cli/RunResult.java @@ -123,9 +123,9 @@ Set getDirectories() { @Override public String toString() { return "RunResult{" - + "args='" + args + '\'' - + ", exitCode=" + exitCode - + ", output='" + output + '\'' - + ", root=" + root + '}'; + + "args='" + args + '\'' + + ", exitCode=" + exitCode + + ", output='" + output + '\'' + + ", root=" + root + '}'; } } diff --git a/smithy-cli/src/it/java/software/amazon/smithy/cli/SelectTest.java b/smithy-cli/src/it/java/software/amazon/smithy/cli/SelectTest.java index ffb9949de75..2be7c7b26b7 100644 --- a/smithy-cli/src/it/java/software/amazon/smithy/cli/SelectTest.java +++ b/smithy-cli/src/it/java/software/amazon/smithy/cli/SelectTest.java @@ -48,14 +48,14 @@ public void selectsVariables() { @Test public void selectsTraits() { List args = Arrays.asList( - "select", - // Can use just shape names, or an absolute shape ID. Including a trait - // here doesn't mean a shape in the result is required to have the trait. - "--show-traits", - "length, range, smithy.api#documentation", - // Every match has to have length or range, but documentation is optional. - "--selector", - ":is([trait|length], [trait|range])" + "select", + // Can use just shape names, or an absolute shape ID. Including a trait + // here doesn't mean a shape in the result is required to have the trait. + "--show-traits", + "length, range, smithy.api#documentation", + // Every match has to have length or range, but documentation is optional. + "--selector", + ":is([trait|length], [trait|range])" ); IntegUtils.run("simple-config-sources", args, result -> { assertThat(result.getExitCode(), equalTo(0)); diff --git a/smithy-cli/src/it/java/software/amazon/smithy/cli/SmithyBuildTest.java b/smithy-cli/src/it/java/software/amazon/smithy/cli/SmithyBuildTest.java index 279431548e8..24c4a00e44e 100644 --- a/smithy-cli/src/it/java/software/amazon/smithy/cli/SmithyBuildTest.java +++ b/smithy-cli/src/it/java/software/amazon/smithy/cli/SmithyBuildTest.java @@ -24,9 +24,9 @@ public void buildsModelsWithSourcesAndDefaultPlugins() { @Test public void canSetSpecificConfigFile() { IntegUtils.run( - "simple-config-sources", - ListUtils.of("build", "-c", "smithy-build.json"), - this::doSimpleBuildAssertions + "simple-config-sources", + ListUtils.of("build", "-c", "smithy-build.json"), + this::doSimpleBuildAssertions ); } @@ -102,12 +102,12 @@ public void failsWhenConfigIsProvidedAndDisabled() { // Disable the config file detection and don't pass model via positional arguments. // This causes main.smithy to not be loaded. IntegUtils.run( - "simple-config-sources", - ListUtils.of("build", "--no-config", "-c", "smithy-build.json"), - result -> { - assertThat(result.getExitCode(), equalTo(1)); - assertThat(result.getOutput(), containsString("Invalid combination of --no-config and --config")); - } + "simple-config-sources", + ListUtils.of("build", "--no-config", "-c", "smithy-build.json"), + result -> { + assertThat(result.getExitCode(), equalTo(1)); + assertThat(result.getOutput(), containsString("Invalid combination of --no-config and --config")); + } ); } } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/BuildParameterBuilder.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/BuildParameterBuilder.java index 3ba41b9fa16..13d04bcb14a 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/BuildParameterBuilder.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/BuildParameterBuilder.java @@ -135,9 +135,9 @@ private static Set splitAndFilterString(String delimiter, String value) } return Stream.of(value.split(Pattern.quote(delimiter))) - .map(String::trim) - .filter(FunctionalUtils.not(String::isEmpty)) - .collect(Collectors.toCollection(LinkedHashSet::new)); + .map(String::trim) + .filter(FunctionalUtils.not(String::isEmpty)) + .collect(Collectors.toCollection(LinkedHashSet::new)); } /** @@ -363,9 +363,9 @@ private Result configureSourceProjection() { private Result configureProjection() { if (projectionSourceTags.isEmpty()) { LOGGER.warning( - "No projection source tags were set for the projection `" + projection + "`, so the " - + "projection will not have any sources in it other than files found in the sources of " - + "the package being built." + "No projection source tags were set for the projection `" + projection + "`, so the " + + "projection will not have any sources in it other than files found in the sources of " + + "the package being built." ); String buildCp = String.join(System.getProperty(PATH_SEPARATOR), buildClasspath); return new Result(this, buildCp, buildCp, sources); @@ -424,10 +424,10 @@ public static final class Result { public final String discoveryClasspath; private Result( - BuildParameterBuilder builder, - String discoveryClasspath, - String classpath, - Set sources + BuildParameterBuilder builder, + String discoveryClasspath, + String classpath, + Set sources ) { this.classpath = classpath; this.sources = new LinkedHashSet<>(sources); @@ -525,8 +525,8 @@ public Set findJarsWithMatchingTags(Set classpath, Set t } catch (IOException e) { throw new SmithyBuildException( - "Error reading manifest from JAR in build dependencies: " + e.getMessage(), - e + "Error reading manifest from JAR in build dependencies: " + e.getMessage(), + e ); } } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/Cli.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/Cli.java index f38719d2c65..1aff2c30a84 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/Cli.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/Cli.java @@ -60,9 +60,9 @@ public int run(String[] args) { } LoggingArgumentsHandler arguments = new LoggingArgumentsHandler( - colorFormatter, - stderrPrinter, - Arguments.of(args) + colorFormatter, + stderrPrinter, + Arguments.of(args) ); arguments.addReceiver(standardOptions); diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/EnvironmentVariable.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/EnvironmentVariable.java index a8c80ba7500..33e64d8cea3 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/EnvironmentVariable.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/EnvironmentVariable.java @@ -48,9 +48,9 @@ public String get() { // versions of the Gradle plugin can use newer versions of Smithy. This means that even if Gradle is // updated to disable dependency resolution, previous versions could inadvertently use it. LOGGER.info( - "Detected that the Smithy CLI is running in Gradle, so dependency resolution is disabled. " - + "This can be overridden by setting SMITHY_DEPENDENCY_MODE environment variable to " - + "'standard'." + "Detected that the Smithy CLI is running in Gradle, so dependency resolution is disabled. " + + "This can be overridden by setting SMITHY_DEPENDENCY_MODE environment variable to " + + "'standard'." ); return "ignore"; } else { diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/HelpPrinter.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/HelpPrinter.java index c4375ac3820..89aaefa9e55 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/HelpPrinter.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/HelpPrinter.java @@ -118,8 +118,8 @@ public void print(ColorFormatter colors, CliPrinter printer) { LineWrapper builder = new LineWrapper(maxWidth); builder.appendWithinLine("Usage: ") - .appendWithinLine(colors.style(name, ColorTheme.EM_UNDERLINE)) - .space(); + .appendWithinLine(colors.style(name, ColorTheme.EM_UNDERLINE)) + .space(); // Calculate the column manually to account for possible styles interfering with the current column number. builder.indent("Usage: ".length() + name.length() + 1); diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/StandardOptions.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/StandardOptions.java index 3099bcdca5b..0ad1240cb89 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/StandardOptions.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/StandardOptions.java @@ -37,11 +37,11 @@ public void registerHelp(HelpPrinter printer) { printer.option(FORCE_COLOR, null, "Force the use of ANSI colors."); printer.option(STACKTRACE, null, "Display a stacktrace on error."); printer.param( - LOGGING, - null, - "LOG_LEVEL", - "Set the log level (defaults to WARNING). Set to one of OFF, SEVERE, WARNING, INFO, " - + "FINE, ALL." + LOGGING, + null, + "LOG_LEVEL", + "Set the log level (defaults to WARNING). Set to one of OFF, SEVERE, WARNING, INFO, " + + "FINE, ALL." ); } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/AstCommand.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/AstCommand.java index e53955a3ec1..2ef25863455 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/AstCommand.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/AstCommand.java @@ -43,9 +43,9 @@ public int execute(Arguments arguments, Env env) { arguments.addReceiver(new Options()); CommandAction action = HelpActionWrapper.fromCommand( - this, - parentCommandName, - new ClasspathAction(dependencyResolverFactory, this::runWithClassLoader) + this, + parentCommandName, + new ClasspathAction(dependencyResolverFactory, this::runWithClassLoader) ); return action.apply(arguments, env); @@ -72,14 +72,14 @@ public void registerHelp(HelpPrinter printer) { private int runWithClassLoader(SmithyBuildConfig config, Arguments arguments, Env env) { Model model = new ModelBuilder() - .config(config) - .arguments(arguments) - .env(env) - .models(arguments.getPositional()) - .validationPrinter(env.stderr()) - .validationMode(Validator.Mode.QUIET) - .defaultSeverity(Severity.DANGER) - .build(); + .config(config) + .arguments(arguments) + .env(env) + .models(arguments.getPositional()) + .validationPrinter(env.stderr()) + .validationMode(Validator.Mode.QUIET) + .defaultSeverity(Severity.DANGER) + .build(); ModelSerializer serializer = ModelSerializer.builder().build(); Options options = arguments.getReceiver(Options.class); diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/BuildCommand.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/BuildCommand.java index 821fbfdf6a4..5c99aebe54e 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/BuildCommand.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/BuildCommand.java @@ -66,9 +66,9 @@ public int execute(Arguments arguments, Env env) { arguments.addReceiver(new Options()); CommandAction action = HelpActionWrapper.fromCommand( - this, - parentCommandName, - new ClasspathAction(dependencyResolverFactory, this::runWithClassLoader) + this, + parentCommandName, + new ClasspathAction(dependencyResolverFactory, this::runWithClassLoader) ); return action.apply(arguments, env); @@ -104,12 +104,12 @@ private int runWithClassLoader(SmithyBuildConfig config, Arguments arguments, En StandardOptions standardOptions = arguments.getReceiver(StandardOptions.class); ClassLoader classLoader = env.classLoader(); Model model = new ModelBuilder() - .config(config) - .arguments(arguments) - .env(env) - .models(models) - .validationPrinter(env.stderr()) - .build(); + .config(config) + .arguments(arguments) + .env(env) + .models(models) + .validationPrinter(env.stderr()) + .build(); if (!standardOptions.quiet()) { env.colors().println(env.stderr(), "Validated model, now starting projections...", ColorTheme.MUTED); @@ -124,8 +124,8 @@ private int runWithClassLoader(SmithyBuildConfig config, Arguments arguments, En return assembler; }; SmithyBuild smithyBuild = SmithyBuild.create(classLoader, modelAssemblerSupplier) - .config(config) - .model(model); + .config(config) + .model(model); if (buildOptions.output() != null) { smithyBuild.outputDirectory(buildOptions.output()); @@ -151,12 +151,12 @@ private int runWithClassLoader(SmithyBuildConfig config, Arguments arguments, En try (ColorBuffer buffer = ColorBuffer.of(env.colors(), env.stderr())) { buffer.print("Summary", ColorTheme.EM_UNDERLINE); buffer.println( - String.format( - ": Smithy built %s projection(s), %s plugin(s), and %s artifacts", - resultConsumer.projectionCount, - resultConsumer.pluginCount, - resultConsumer.artifactCount - ) + String.format( + ": Smithy built %s projection(s), %s plugin(s), and %s artifacts", + resultConsumer.projectionCount, + resultConsumer.pluginCount, + resultConsumer.artifactCount + ) ); } } @@ -168,11 +168,11 @@ private int runWithClassLoader(SmithyBuildConfig config, Arguments arguments, En try (ColorBuffer buffer = ColorBuffer.of(env.colors(), error)) { buffer.println(); buffer.println( - String.format( - "The following %d Smithy build projection(s) failed: %s", - resultConsumer.failedProjections.size(), - resultConsumer.failedProjections - ) + String.format( + "The following %d Smithy build projection(s) failed: %s", + resultConsumer.failedProjections.size(), + resultConsumer.failedProjections + ) ); } throw new CliError(error.toString()); @@ -245,23 +245,23 @@ public void accept(ProjectionResult result) { w.println(); }, statusStyle); buffer - .print(status) - .append(" projection ") - .append(result.getProjectionName()) - .append(" (") - .append(String.valueOf(result.getModel().toSet().size())) - .append("): ") - .append(String.valueOf(root)) - .println(); + .print(status) + .append(" projection ") + .append(result.getProjectionName()) + .append(" (") + .append(String.valueOf(result.getModel().toSet().size())) + .append("): ") + .append(String.valueOf(root)) + .println(); } if (result.isBroken()) { SourceContextLoader loader = SourceContextLoader.createModelAwareLoader(result.getModel(), 4); PrettyAnsiValidationFormatter formatter = PrettyAnsiValidationFormatter.builder() - .sourceContextLoader(loader) - .colors(colors) - .titleLabel(result.getProjectionName(), statusStyle) - .build(); + .sourceContextLoader(loader) + .colors(colors) + .titleLabel(result.getProjectionName(), statusStyle) + .build(); result.getEvents().forEach(event -> { if (event.getSeverity() == Severity.DANGER || event.getSeverity() == Severity.ERROR) { buffer.println(formatter.format(event)); diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/BuildOptions.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/BuildOptions.java index 1ee80818b68..9d4dd8dac92 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/BuildOptions.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/BuildOptions.java @@ -28,15 +28,15 @@ final class BuildOptions implements ArgumentReceiver { @Override public void registerHelp(HelpPrinter printer) { printer.option( - ALLOW_UNKNOWN_TRAITS, - ALLOW_UNKNOWN_TRAITS_SHORT, - "Ignore unknown traits when validating models." + ALLOW_UNKNOWN_TRAITS, + ALLOW_UNKNOWN_TRAITS_SHORT, + "Ignore unknown traits when validating models." ); printer.param( - "--output", - null, - "OUTPUT_PATH", - "Where to write Smithy artifacts, caches, and other files (defaults to './build/smithy')." + "--output", + null, + "OUTPUT_PATH", + "Where to write Smithy artifacts, caches, and other files (defaults to './build/smithy')." ); if (!noPositionalArguments) { @@ -85,8 +85,8 @@ Path resolveOutput(SmithyBuildConfig config) { return Paths.get(output); } else { return config.getOutputDirectory() - .map(Paths::get) - .orElseGet(SmithyBuild::getDefaultOutputDirectory); + .map(Paths::get) + .orElseGet(SmithyBuild::getDefaultOutputDirectory); } } } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ClasspathAction.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ClasspathAction.java index cd583c63f66..738897e7e94 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ClasspathAction.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ClasspathAction.java @@ -60,14 +60,14 @@ static final class ThreadResult { } private void runTaskWithClasspath( - BuildOptions buildOptions, - SmithyBuildConfig smithyBuildConfig, - Command.Env env, - Consumer consumer + BuildOptions buildOptions, + SmithyBuildConfig smithyBuildConfig, + Command.Env env, + Consumer consumer ) { Set dependencies = smithyBuildConfig.getMaven() - .map(MavenConfig::getDependencies) - .orElse(Collections.emptySet()); + .map(MavenConfig::getDependencies) + .orElse(Collections.emptySet()); String dependencyMode = EnvironmentVariable.SMITHY_DEPENDENCY_MODE.get(); boolean useIsolation = false; @@ -75,25 +75,25 @@ private void runTaskWithClasspath( case "forbid": if (!dependencies.isEmpty()) { throw new DependencyResolverException( - String.format( - "%s is set to 'forbid', but the following Maven dependencies are defined in " - + "smithy-build.json: %s. Dependencies are forbidden in this configuration.", - EnvironmentVariable.SMITHY_DEPENDENCY_MODE, - dependencies - ) + String.format( + "%s is set to 'forbid', but the following Maven dependencies are defined in " + + "smithy-build.json: %s. Dependencies are forbidden in this configuration.", + EnvironmentVariable.SMITHY_DEPENDENCY_MODE, + dependencies + ) ); } break; case "ignore": if (!dependencies.isEmpty()) { LOGGER.warning( - () -> String.format( - "%s is set to 'ignore', and the following Maven dependencies are defined in " - + "smithy-build.json: %s. If the build fails, then you may need to manually configure " - + "the classpath.", - EnvironmentVariable.SMITHY_DEPENDENCY_MODE, - dependencies - ) + () -> String.format( + "%s is set to 'ignore', and the following Maven dependencies are defined in " + + "smithy-build.json: %s. If the build fails, then you may need to manually configure " + + "the classpath.", + EnvironmentVariable.SMITHY_DEPENDENCY_MODE, + dependencies + ) ); } break; @@ -102,21 +102,21 @@ private void runTaskWithClasspath( break; default: throw new CliError( - String.format( - "Unknown %s setting: '%s'", - EnvironmentVariable.SMITHY_DEPENDENCY_MODE, - dependencyMode - ) + String.format( + "Unknown %s setting: '%s'", + EnvironmentVariable.SMITHY_DEPENDENCY_MODE, + dependencyMode + ) ); } if (useIsolation) { long start = System.nanoTime(); List files = resolveDependencies( - buildOptions, - smithyBuildConfig, - env, - smithyBuildConfig.getMaven().get() + buildOptions, + smithyBuildConfig, + env, + smithyBuildConfig.getMaven().get() ); long end = System.nanoTime(); LOGGER.fine(() -> "Dependency resolution time in ms: " + ((end - start) / 1000000)); @@ -128,18 +128,18 @@ private void runTaskWithClasspath( } private List resolveDependencies( - BuildOptions buildOptions, - SmithyBuildConfig smithyBuildConfig, - Command.Env env, - MavenConfig maven + BuildOptions buildOptions, + SmithyBuildConfig smithyBuildConfig, + Command.Env env, + MavenConfig maven ) { DependencyResolver baseResolver = dependencyResolverFactory.create(smithyBuildConfig, env); long lastModified = smithyBuildConfig.getLastModifiedInMillis(); DependencyResolver delegate = new FilterCliVersionResolver(SmithyCli.getVersion(), baseResolver); DependencyResolver resolver = new FileCacheResolver( - getCacheFile(buildOptions, smithyBuildConfig), - lastModified, - delegate + getCacheFile(buildOptions, smithyBuildConfig), + lastModified, + delegate ); Set repositories = ConfigurationUtils.getConfiguredMavenRepos(smithyBuildConfig); @@ -151,13 +151,13 @@ private List resolveDependencies( LockFile lockFile = lockFileOptional.get(); if (lockFile.getConfigHash() != ConfigurationUtils.configHash(maven.getDependencies(), repositories)) { throw new CliError( - "`smithy-lock.json` does not match configured dependencies. " - + "Re-lock dependencies using the `lock` command or revert changes." + "`smithy-lock.json` does not match configured dependencies. " + + "Re-lock dependencies using the `lock` command or revert changes." ); } LOGGER.fine( - () -> "`smithy-lock.json` found. Using locked dependencies: " - + lockFile.getDependencyCoordinateSet() + () -> "`smithy-lock.json` found. Using locked dependencies: " + + lockFile.getDependencyCoordinateSet() ); lockFile.getDependencyCoordinateSet().forEach(resolver::addDependency); } else { diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/CleanCommand.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/CleanCommand.java index 499614a5df5..2820eee706b 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/CleanCommand.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/CleanCommand.java @@ -57,8 +57,8 @@ private int run(Arguments arguments, Env env) { SmithyBuildConfig config = configOptions.createSmithyBuildConfig(); Path dir = config.getOutputDirectory() - .map(Paths::get) - .orElseGet(SmithyBuild::getDefaultOutputDirectory); + .map(Paths::get) + .orElseGet(SmithyBuild::getDefaultOutputDirectory); LOGGER.fine(() -> "Deleting directory: " + dir); if (!IoUtils.rmdir(dir)) { LOGGER.fine(() -> "Directory does not exist: " + dir); @@ -91,10 +91,10 @@ public boolean testOption(String name) { @Override public void registerHelp(HelpPrinter printer) { printer.param( - "--templates", - "-t", - null, - "Clean only the templates cache." + "--templates", + "-t", + null, + "Clean only the templates cache." ); } } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ConfigOptions.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ConfigOptions.java index 7d111197954..77334926451 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ConfigOptions.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ConfigOptions.java @@ -29,11 +29,11 @@ final class ConfigOptions implements ArgumentReceiver { @Override public void registerHelp(HelpPrinter printer) { printer.param( - "--config", - "-c", - "CONFIG_PATH...", - "Path to smithy-build.json config (defaults to ./smithy-build.json if not specified). " - + "This option can be repeated, merging each config file." + "--config", + "-c", + "CONFIG_PATH...", + "Path to smithy-build.json config (defaults to ./smithy-build.json if not specified). " + + "This option can be repeated, merging each config file." ); printer.option("--no-config", null, "Disable config file detection and use."); } @@ -69,8 +69,8 @@ List config() { // Don't find the default config if --no-config is passed. if (config.isEmpty() && !noConfig) { Path defaultConfig = root != null - ? root.resolve("smithy-build.json").toAbsolutePath() - : Paths.get("smithy-build.json").toAbsolutePath(); + ? root.resolve("smithy-build.json").toAbsolutePath() + : Paths.get("smithy-build.json").toAbsolutePath(); if (Files.exists(defaultConfig)) { LOGGER.fine("Detected smithy-build.json at " + defaultConfig); config = Collections.singletonList(defaultConfig.toString()); @@ -86,8 +86,8 @@ SmithyBuildConfig createSmithyBuildConfig() { if (noConfig && !config.isEmpty()) { throw new CliError( - "Invalid combination of --no-config and --config. --no-config can be omitted because " - + "providing --config/-c disables automatically loading ./smithy-build.json." + "Invalid combination of --no-config and --config. --no-config can be omitted because " + + "providing --config/-c disables automatically loading ./smithy-build.json." ); } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ConfigurationUtils.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ConfigurationUtils.java index 91a951ad3ff..b5fb1f9193c 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ConfigurationUtils.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ConfigurationUtils.java @@ -18,8 +18,8 @@ final class ConfigurationUtils { private static final int FNV_PRIME = 0x1000193; private static final Logger LOGGER = Logger.getLogger(ConfigurationUtils.class.getName()); private static final MavenRepository CENTRAL = MavenRepository.builder() - .url("https://repo.maven.apache.org/maven2") - .build(); + .url("https://repo.maven.apache.org/maven2") + .build(); private ConfigurationUtils() { // Utility Class should not be instantiated @@ -45,18 +45,18 @@ public static Set getConfiguredMavenRepos(SmithyBuildConfig con } Set configuredRepos = config.getMaven() - .map(MavenConfig::getRepositories) - .orElse(Collections.emptySet()); + .map(MavenConfig::getRepositories) + .orElse(Collections.emptySet()); if (!configuredRepos.isEmpty()) { repositories.addAll(configuredRepos); } else if (envRepos == null) { LOGGER.finest( - () -> String.format( - "maven.repositories is not defined in `smithy-build.json` and the %s " - + "environment variable is not set. Defaulting to Maven Central.", - EnvironmentVariable.SMITHY_MAVEN_REPOS - ) + () -> String.format( + "maven.repositories is not defined in `smithy-build.json` and the %s " + + "environment variable is not set. Defaulting to Maven Central.", + EnvironmentVariable.SMITHY_MAVEN_REPOS + ) ); repositories.add(CENTRAL); } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/DiffCommand.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/DiffCommand.java index 70e4fc34033..8ee78ef19ab 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/DiffCommand.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/DiffCommand.java @@ -61,10 +61,10 @@ public int execute(Arguments arguments, Env env) { arguments.getReceiver(BuildOptions.class).noPositionalArguments(true); CommandAction action = HelpActionWrapper.fromCommand( - this, - parentCommandName, - this::getDocumentation, - new ClasspathAction(dependencyResolverFactory, this::runWithClassLoader) + this, + parentCommandName, + this::getDocumentation, + new ClasspathAction(dependencyResolverFactory, this::runWithClassLoader) ); return action.apply(arguments, env); @@ -73,54 +73,54 @@ public int execute(Arguments arguments, Env env) { private String getDocumentation(ColorFormatter colors) { String ls = System.lineSeparator(); String content = "The `diff` command supports different modes through the `--mode` option:" - + ls - + ls - + "`--mode arbitrary`:" - + ls - + "Compares two arbitrary models. This mode requires that `--old` and `--new` are specified. " - + "When run within a project directory that contains a `smithy-build.json` config, any dependencies " - + "defined in the config file are used when loading both the old and new models; however, `imports` " - + "and `sources` defined in the config file are not used. This is the default mode when no `--mode` " - + "is specified and `--old` or `--new` are provided." - + ls - + ls - + " smithy diff --old /path/old --new /path/new" - + ls - + " smithy diff --mode arbitrary --old /path/old --new /path/new" - + ls - + ls - + "`--mode project`:" - + ls - + "Compares the current state of a project against another project. `--old` is required and points " - + "to the location of another Smithy model or the root directory of another project. `--new` is not " - + "allowed in this mode because the new model is the project in the current working directory. The " - + "old model does not use any `sources` or `imports` defined by the current project, though it is " - + "loaded using any dependencies defined by the current project. If the `--old` argument points to " - + "a directory that contains a `smithy-build.json` file, any `imports` or `sources` defined in that " - + "config file will be used when loading the old model, though the dependencies of the old model " - + "are ignored." - + ls - + ls - + " smithy diff --mode project --old /path/old" - + ls - + ls - + "`--mode git`:" - + ls - + "Compares the current state of a Smithy project to another commit in the current git repo. This " - + "command must be run from within a git repo. The `--old` argument can be provided to specify a " - + "specific revision to compare against. If `--old` is not provided, the commit defaults to `HEAD` " - + "(the last commit on the current branch). This mode is a wrapper around `--mode project`, so its " - + "restrictions apply. This is the default mode when no arguments are provided." - + ls - + ls - + " # Equivalent to `smithy diff --mode git`" - + " smithy diff" - + ls - + " smithy diff --mode git" - + ls - + " smithy diff --mode git --old main" - + ls - + " smithy diff --mode git --old HEAD~2"; + + ls + + ls + + "`--mode arbitrary`:" + + ls + + "Compares two arbitrary models. This mode requires that `--old` and `--new` are specified. " + + "When run within a project directory that contains a `smithy-build.json` config, any dependencies " + + "defined in the config file are used when loading both the old and new models; however, `imports` " + + "and `sources` defined in the config file are not used. This is the default mode when no `--mode` " + + "is specified and `--old` or `--new` are provided." + + ls + + ls + + " smithy diff --old /path/old --new /path/new" + + ls + + " smithy diff --mode arbitrary --old /path/old --new /path/new" + + ls + + ls + + "`--mode project`:" + + ls + + "Compares the current state of a project against another project. `--old` is required and points " + + "to the location of another Smithy model or the root directory of another project. `--new` is not " + + "allowed in this mode because the new model is the project in the current working directory. The " + + "old model does not use any `sources` or `imports` defined by the current project, though it is " + + "loaded using any dependencies defined by the current project. If the `--old` argument points to " + + "a directory that contains a `smithy-build.json` file, any `imports` or `sources` defined in that " + + "config file will be used when loading the old model, though the dependencies of the old model " + + "are ignored." + + ls + + ls + + " smithy diff --mode project --old /path/old" + + ls + + ls + + "`--mode git`:" + + ls + + "Compares the current state of a Smithy project to another commit in the current git repo. This " + + "command must be run from within a git repo. The `--old` argument can be provided to specify a " + + "specific revision to compare against. If `--old` is not provided, the commit defaults to `HEAD` " + + "(the last commit on the current branch). This mode is a wrapper around `--mode project`, so its " + + "restrictions apply. This is the default mode when no arguments are provided." + + ls + + ls + + " # Equivalent to `smithy diff --mode git`" + + " smithy diff" + + ls + + " smithy diff --mode git" + + ls + + " smithy diff --mode git --old main" + + ls + + " smithy diff --mode git --old HEAD~2"; return StyleHelper.markdownLiterals(content, colors); } @@ -157,24 +157,24 @@ public Consumer testParameter(String name) { @Override public void registerHelp(HelpPrinter printer) { printer.param( - "--mode", - null, - "DIFF_MODE", - "The diff mode to use: 'arbitrary' (the default mode), 'project', 'git'." + "--mode", + null, + "DIFF_MODE", + "The diff mode to use: 'arbitrary' (the default mode), 'project', 'git'." ); printer.param( - "--old", - null, - "OLD_MODEL", - "Path to an old Smithy model file or directory that contains model files. When using " - + "git mode, this argument refers to a Git commit or branch." + "--old", + null, + "OLD_MODEL", + "Path to an old Smithy model file or directory that contains model files. When using " + + "git mode, this argument refers to a Git commit or branch." ); printer.param( - "--new", - null, - "NEW_MODEL", - "Path to the new Smithy model file or directory that contains model files. This argument " - + "is not allowed in project or git mode." + "--new", + null, + "NEW_MODEL", + "Path to the new Smithy model file or directory that contains model files. This argument " + + "is not allowed in project or git mode." ); } } @@ -218,9 +218,9 @@ int diff(SmithyBuildConfig config, Arguments arguments, Options options, Env env // Use the ModelBuilder template to build the old model. Model oldModel = modelBuilder - .models(Collections.singletonList(options.oldModel)) - .titleLabel("OLD", ColorTheme.DIFF_EVENT_TITLE) - .build(); + .models(Collections.singletonList(options.oldModel)) + .titleLabel("OLD", ColorTheme.DIFF_EVENT_TITLE) + .build(); // Use the same ModelBuilder template to build the new model, being careful to use the original config. Model newModel = createNewModel(modelBuilder, Collections.singletonList(options.newModel), config); @@ -249,10 +249,10 @@ int diff(SmithyBuildConfig config, Arguments arguments, Options options, Env env oldConfig.root(Paths.get(options.oldModel)); Model oldModel = modelBuilder - .models(Collections.emptyList()) - .config(oldConfig.createSmithyBuildConfig()) - .titleLabel("OLD", ColorTheme.DIFF_EVENT_TITLE) - .build(); + .models(Collections.emptyList()) + .config(oldConfig.createSmithyBuildConfig()) + .titleLabel("OLD", ColorTheme.DIFF_EVENT_TITLE) + .build(); // Use the same ModelBuilder template to build the new model, being careful to use the original config. Model newModel = createNewModel(modelBuilder, Collections.emptyList(), config); @@ -271,11 +271,11 @@ int diff(SmithyBuildConfig config, Arguments arguments, Options options, Env env if (!arguments.getReceiver(StandardOptions.class).quiet()) { env.colors() - .println( - env.stderr(), - "Comparing current project to git " + options.oldModel, - ColorTheme.MUTED - ); + .println( + env.stderr(), + "Comparing current project to git " + options.oldModel, + ColorTheme.MUTED + ); } // Setup a worktree if one isn't present. @@ -292,26 +292,26 @@ int diff(SmithyBuildConfig config, Arguments arguments, Options options, Env env // Now create the worktree using a dedicated branch. The branch allows other worktrees to checkout // the same branch or SHA without conflicting. exec( - ListUtils.of( - "git", - "worktree", - "add", - "--quiet", - "--force", - "-B", - DIFF_WORKTREE_BRANCH, - worktreePath.toString(), - sha - ), - root, - "Unable to create git worktree" + ListUtils.of( + "git", + "worktree", + "add", + "--quiet", + "--force", + "-B", + DIFF_WORKTREE_BRANCH, + worktreePath.toString(), + sha + ), + root, + "Unable to create git worktree" ); } else { // Checkout the right commit in the worktree. exec( - ListUtils.of("git", "reset", "--quiet", "--hard", sha), - worktreePath, - "Unable to checkout " + options.oldModel + " in git worktree" + ListUtils.of("git", "reset", "--quiet", "--hard", sha), + worktreePath, + "Unable to checkout " + options.oldModel + " in git worktree" ); } @@ -331,23 +331,23 @@ private String getSha(Path root, String commitish) { // Create a ModelBuilder template to load the old, then new, then diff both. protected final ModelBuilder createModelBuilder(SmithyBuildConfig config, Arguments arguments, Env env) { return new ModelBuilder() - .config(config) - .arguments(arguments) - .env(env) - .validationPrinter(env.stdout()) - // Only report issues that fail the build. - .validationMode(Validator.Mode.QUIET_CORE_ONLY) - .defaultSeverity(Severity.DANGER); + .config(config) + .arguments(arguments) + .env(env) + .validationPrinter(env.stdout()) + // Only report issues that fail the build. + .validationMode(Validator.Mode.QUIET_CORE_ONLY) + .defaultSeverity(Severity.DANGER); } // Creating a new model is the same for each diff mode. protected final Model createNewModel(ModelBuilder builder, List models, SmithyBuildConfig config) { return builder - .models(models) - .titleLabel("NEW", ColorTheme.DIFF_EVENT_TITLE) - .config(config) - .disableOutputFormatFraming(true) // don't repeat things like CSV headers. - .build(); + .models(models) + .titleLabel("NEW", ColorTheme.DIFF_EVENT_TITLE) + .config(config) + .disableOutputFormatFraming(true) // don't repeat things like CSV headers. + .build(); } // Running the diff is the same for each diff mode. @@ -355,11 +355,11 @@ protected final void runDiff(ModelBuilder builder, Env env, Model oldModel, Mode ClassLoader classLoader = env.classLoader(); List events = ModelDiff.compare(classLoader, oldModel, newModel); builder - .titleLabel("DIFF", ColorTheme.DIFF_TITLE) - .validatedResult(new ValidatedResult<>(newModel, events)) - .defaultSeverity(null) // reset so it takes on standard option settings. - .disableOutputFormatFraming(true) // don't repeat things like CSV headers. - .build(); + .titleLabel("DIFF", ColorTheme.DIFF_TITLE) + .validatedResult(new ValidatedResult<>(newModel, events)) + .defaultSeverity(null) // reset so it takes on standard option settings. + .disableOutputFormatFraming(true) // don't repeat things like CSV headers. + .build(); } abstract int diff(SmithyBuildConfig config, Arguments arguments, Options options, Env env); diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/FormatCommand.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/FormatCommand.java index d3a845b943e..26e4ed43a76 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/FormatCommand.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/FormatCommand.java @@ -45,8 +45,8 @@ private static final class Options implements ArgumentReceiver { @Override public void registerHelp(HelpPrinter printer) { printer.positional( - "", - "A single `.smithy` model file or a directory of model files to recursively format." + "", + "A single `.smithy` model file or a directory of model files to recursively format." ); } } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/HelpActionWrapper.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/HelpActionWrapper.java index 9a9866bd643..fa83714c56e 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/HelpActionWrapper.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/HelpActionWrapper.java @@ -28,11 +28,11 @@ final class HelpActionWrapper implements CommandAction { private final String summary; HelpActionWrapper( - String name, - String parentCommandName, - String summary, - Function documentationProvider, - CommandAction delegate + String name, + String parentCommandName, + String summary, + Function documentationProvider, + CommandAction delegate ) { this.name = name; this.parentCommandName = parentCommandName; @@ -46,17 +46,17 @@ static HelpActionWrapper fromCommand(Command command, String parentCommandName, } static HelpActionWrapper fromCommand( - Command command, - String parentCommandName, - Function documentationProvider, - CommandAction delegate + Command command, + String parentCommandName, + Function documentationProvider, + CommandAction delegate ) { return new HelpActionWrapper( - command.getName(), - parentCommandName, - command.getSummary(), - documentationProvider, - delegate + command.getName(), + parentCommandName, + command.getSummary(), + documentationProvider, + delegate ); } @@ -77,8 +77,8 @@ public int apply(Arguments arguments, Command.Env env) { private void printHelp(Arguments arguments, ColorFormatter colors, CliPrinter printer) { String title = StringUtils.isEmpty(parentCommandName) ? name : parentCommandName + " " + name; HelpPrinter.fromArguments(title, arguments) - .summary(summary) - .documentation(documentationProvider.apply(colors)) - .print(colors, printer); + .summary(summary) + .documentation(documentationProvider.apply(colors)) + .print(colors, printer); } } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/InitCommand.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/InitCommand.java index 7f72e5eb9af..34731fd50d8 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/InitCommand.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/InitCommand.java @@ -84,26 +84,26 @@ private int run(Arguments arguments, Env env) { // If the cache directory does not exist, create it if (!Files.exists(templateRepoDirPath)) { try ( - ProgressTracker t = new ProgressTracker( - env, - ProgressStyle.dots("cloning template repo", "template repo cloned"), - standardOptions.quiet() - ) + ProgressTracker t = new ProgressTracker( + env, + ProgressStyle.dots("cloning template repo", "template repo cloned"), + standardOptions.quiet() + ) ) { Path templateCachePath = CliCache.getTemplateCache().get(); String relativeTemplateDir = templateCachePath.relativize(templateRepoDirPath).toString(); // Only clone the latest commit from HEAD. Do not include history exec( - ListUtils.of( - "git", - "clone", - "--depth", - "1", - "--single-branch", - options.repositoryUrl, - relativeTemplateDir - ), - templateCachePath + ListUtils.of( + "git", + "clone", + "--depth", + "1", + "--single-branch", + options.repositoryUrl, + relativeTemplateDir + ), + templateCachePath ); } } @@ -118,11 +118,11 @@ private int run(Arguments arguments, Env env) { // If a change was detected, force the template repo to update if (!StringUtils.isEmpty(response)) { try ( - ProgressTracker t = new ProgressTracker( - env, - ProgressStyle.dots("updating template cache", "template repo updated"), - standardOptions.quiet() - ) + ProgressTracker t = new ProgressTracker( + env, + ProgressStyle.dots("updating template cache", "template repo updated"), + standardOptions.quiet() + ) ) { exec(ListUtils.of("git", "reset", "--hard", "origin/main"), templateRepoDirPath); exec(ListUtils.of("git", "clean", "-dfx"), templateRepoDirPath); @@ -131,7 +131,7 @@ private int run(Arguments arguments, Env env) { } ObjectNode smithyTemplatesNode = readJsonFileAsNode(templateRepoDirPath.resolve(SMITHY_TEMPLATE_JSON)) - .expectObjectNode(); + .expectObjectNode(); if (options.listTemplates) { this.listTemplates(smithyTemplatesNode, env); } else { @@ -148,8 +148,8 @@ private void validateTemplateDir(Path templateRepoDirPath, String templateUrl) { Path templateJsonPath = templateRepoDirPath.resolve(SMITHY_TEMPLATE_JSON); if (!Files.exists(templateJsonPath) && Files.isRegularFile(templateJsonPath)) { throw new CliError( - "Template repository " + templateUrl - + " does not contain a valid `smithy-templates.json`." + "Template repository " + templateUrl + + " does not contain a valid `smithy-templates.json`." ); } } @@ -167,9 +167,9 @@ private Path getTemplateRepoDirPath(String repoPath, boolean isLocalRepo) { // Remove "/" and ".." and ":" characters so a directory can be created with no nesting private String getCacheDirFromUrl(final String repositoryUrl) { return repositoryUrl.replace(".git", "") - .replace(":", "_") - .replace("/", "_") - .replace(".", "_"); + .replace(":", "_") + .replace("/", "_") + .replace(".", "_"); } private void listTemplates(ObjectNode smithyTemplatesNode, Env env) { @@ -194,17 +194,17 @@ private String getTemplateList(ObjectNode smithyTemplatesNode, Env env) { for (Map.Entry entry : getTemplatesNode(smithyTemplatesNode).getMembers().entrySet()) { String template = entry.getKey().getValue(); String documentation = entry.getValue() - .expectObjectNode() - .expectMember( - DOCUMENTATION, - String.format( - "Missing expected member `%s` from `%s` object", - DOCUMENTATION, - template + .expectObjectNode() + .expectMember( + DOCUMENTATION, + String.format( + "Missing expected member `%s` from `%s` object", + DOCUMENTATION, + template + ) ) - ) - .expectStringNode() - .getValue(); + .expectStringNode() + .getValue(); templates.put(template, documentation); @@ -216,9 +216,9 @@ private String getTemplateList(ObjectNode smithyTemplatesNode, Env env) { writeTemplateBorder(builder, maxTemplateLength, maxDocLength); builder.print(pad(NAME.toUpperCase(Locale.US), maxTemplateLength), ColorTheme.NOTE) - .print(COLUMN_SEPARATOR) - .print(DOCUMENTATION.toUpperCase(Locale.US), ColorTheme.NOTE) - .println(); + .print(COLUMN_SEPARATOR) + .print(DOCUMENTATION.toUpperCase(Locale.US), ColorTheme.NOTE) + .println(); writeTemplateBorder(builder, maxTemplateLength, maxDocLength); int offset = maxTemplateLength + COLUMN_SEPARATOR.length(); @@ -228,12 +228,12 @@ private String getTemplateList(ObjectNode smithyTemplatesNode, Env env) { String doc = entry.getValue(); builder.print(pad(template, maxTemplateLength), ColorTheme.TEMPLATE_TITLE) - .print(COLUMN_SEPARATOR) - .print( - wrapDocumentation(doc, maxDocLength, offset), - ColorTheme.MUTED - ) - .println(); + .print(COLUMN_SEPARATOR) + .print( + wrapDocumentation(doc, maxDocLength, offset), + ColorTheme.MUTED + ) + .println(); } return builder.toString(); @@ -241,9 +241,9 @@ private String getTemplateList(ObjectNode smithyTemplatesNode, Env env) { private static void writeTemplateBorder(ColorBuffer writer, int maxNameLength, int maxDocLength) { writer.print(pad("", maxNameLength).replace(" ", "─"), ColorTheme.TEMPLATE_LIST_BORDER) - .print(COLUMN_SEPARATOR) - .print(pad("", maxDocLength).replace(" ", "─"), ColorTheme.TEMPLATE_LIST_BORDER) - .println(); + .print(COLUMN_SEPARATOR) + .print(pad("", maxDocLength).replace(" ", "─"), ColorTheme.TEMPLATE_LIST_BORDER) + .println(); } private static String wrapDocumentation(String doc, int maxLength, int offset) { @@ -251,11 +251,11 @@ private static String wrapDocumentation(String doc, int maxLength, int offset) { } private void cloneTemplate( - Path templateRepoDirPath, - ObjectNode smithyTemplatesNode, - Options options, - StandardOptions standardOptions, - Env env + Path templateRepoDirPath, + ObjectNode smithyTemplatesNode, + Options options, + StandardOptions standardOptions, + Env env ) { String template = options.template; @@ -277,12 +277,12 @@ private void cloneTemplate( ObjectNode templatesNode = getTemplatesNode(smithyTemplatesNode); if (!templatesNode.containsMember(template)) { throw new IllegalArgumentException( - String.format( - "Invalid template `%s`. `%s` provides the following templates:%n%n%s", - template, - getTemplatesName(smithyTemplatesNode), - getTemplateList(smithyTemplatesNode, env) - ) + String.format( + "Invalid template `%s`. `%s` provides the following templates:%n%n%s", + template, + getTemplatesName(smithyTemplatesNode), + getTemplateList(smithyTemplatesNode, env) + ) ); } ObjectNode templateNode = templatesNode.expectObjectMember(template).expectObjectNode(); @@ -302,11 +302,11 @@ private void cloneTemplate( if (!Files.exists(stagingPath.resolve(templatePath))) { throw new CliError( - String.format( - "Template path `%s` for template \"%s\" is invalid.", - templatePath, - template - ) + String.format( + "Template path `%s` for template \"%s\" is invalid.", + templatePath, + template + ) ); } IoUtils.copyDir(Paths.get(stagingPath.toString(), templatePath), dest); @@ -327,17 +327,17 @@ private static Path createStagingRepo(Path repoPath) { throw new CliError("Unable to create staging directory for template."); } exec( - ListUtils.of( - "git", - "clone", - "--no-checkout", - "--depth", - "1", - "--sparse", - "file://" + repoPath.toString(), - temp.toString() - ), - Paths.get(".") + ListUtils.of( + "git", + "clone", + "--no-checkout", + "--depth", + "1", + "--sparse", + "file://" + repoPath.toString(), + temp.toString() + ), + Paths.get(".") ); return temp; @@ -349,36 +349,36 @@ private static ObjectNode getSmithyTemplatesNode(Path jsonFilePath) { private static ObjectNode getTemplatesNode(ObjectNode smithyTemplatesNode) { return smithyTemplatesNode - .expectMember( - TEMPLATES, - String.format( - "Missing expected member `%s` from %s", - TEMPLATES, - SMITHY_TEMPLATE_JSON + .expectMember( + TEMPLATES, + String.format( + "Missing expected member `%s` from %s", + TEMPLATES, + SMITHY_TEMPLATE_JSON + ) ) - ) - .expectObjectNode(); + .expectObjectNode(); } private static String getTemplatesName(ObjectNode smithyTemplatesNode) { return smithyTemplatesNode - .expectMember( - NAME, - String.format( - "Missing expected member `%s` from %s", - NAME, - SMITHY_TEMPLATE_JSON + .expectMember( + NAME, + String.format( + "Missing expected member `%s` from %s", + NAME, + SMITHY_TEMPLATE_JSON + ) ) - ) - .expectStringNode() - .getValue(); + .expectStringNode() + .getValue(); } private static String getTemplatePath(ObjectNode templateNode, String templateName) { return templateNode - .expectMember(PATH, String.format("Missing expected member `%s` from `%s` object", PATH, templateName)) - .expectStringNode() - .getValue(); + .expectMember(PATH, String.format("Missing expected member `%s` from `%s` object", PATH, templateName)) + .expectStringNode() + .getValue(); } private static List getIncludedFiles(ObjectNode templateNode) { @@ -388,21 +388,21 @@ private static List getIncludedFiles(ObjectNode templateNode) { } private static void copyIncludedFiles( - String temp, - String dest, - List includedFiles, - String templateName, - Env env + String temp, + String dest, + List includedFiles, + String templateName, + Env env ) { for (String included : includedFiles) { Path includedPath = Paths.get(temp, included); if (!Files.exists(includedPath)) { throw new CliError( - String.format( - "File or directory `%s` is marked for inclusion in template \"%s\", but was not found", - included, - templateName - ) + String.format( + "File or directory `%s` is marked for inclusion in template \"%s\", but was not found", + included, + templateName + ) ); } @@ -414,8 +414,8 @@ private static void copyIncludedFiles( Files.copy(includedPath, target); } catch (IOException e) { throw new CliError( - "Unable to copy included file: " + includedPath - + "to destination directory: " + target + "Unable to copy included file: " + includedPath + + "to destination directory: " + target ); } } @@ -478,28 +478,28 @@ public Consumer testParameter(String name) { @Override public void registerHelp(HelpPrinter printer) { printer.param( - "--template", - "-t", - "quickstart-cli", - "Specify the template to be used in the Smithy project" + "--template", + "-t", + "quickstart-cli", + "Specify the template to be used in the Smithy project" ); printer.param( - "--url", - null, - "https://github.com/smithy-lang/smithy-examples.git", - "Smithy templates repository url" + "--url", + null, + "https://github.com/smithy-lang/smithy-examples.git", + "Smithy templates repository url" ); printer.param( - "--output", - "-o", - "new-smithy-project", - "Smithy project directory" + "--output", + "-o", + "new-smithy-project", + "Smithy project directory" ); printer.param( - "--list", - "-l", - null, - "List available templates" + "--list", + "-l", + null, + "List available templates" ); } } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/LockCommand.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/LockCommand.java index 0d9fb070099..6745dc1d685 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/LockCommand.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/LockCommand.java @@ -57,18 +57,18 @@ private int run(Arguments arguments, Env env) { Set repositories = ConfigurationUtils.getConfiguredMavenRepos(smithyBuildConfig); Set dependencies = smithyBuildConfig.getMaven() - .map(MavenConfig::getDependencies) - .orElse(Collections.emptySet()); + .map(MavenConfig::getDependencies) + .orElse(Collections.emptySet()); dependencies.forEach(resolver::addDependency); repositories.forEach(resolver::addRepository); List resolvedArtifacts = resolver.resolve(); LOGGER.fine(() -> "Resolved artifacts with Maven: " + resolvedArtifacts); LockFile lock = LockFile.builder() - .configHash(ConfigurationUtils.configHash(dependencies, repositories)) - .artifacts(resolvedArtifacts) - .repositories(repositories) - .build(); + .configHash(ConfigurationUtils.configHash(dependencies, repositories)) + .artifacts(resolvedArtifacts) + .repositories(repositories) + .build(); LOGGER.fine(() -> "Saving resolved artifacts to lockfile."); lock.save(); diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/LockFile.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/LockFile.java index fc195d7cc9b..54e09609827 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/LockFile.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/LockFile.java @@ -39,11 +39,11 @@ final class LockFile implements ToSmithyBuilder, ToNode { private static final String ARTIFACT_LIST_NAME = "artifacts"; private static final String REPOSITORIES_LIST_NAME = "repositories"; private static final List EXPECTED_PROPERTIES = ListUtils.of( - WARNING_STR, - VERSION_NAME, - CONFIG_HASH_NAME, - ARTIFACT_LIST_NAME, - REPOSITORIES_LIST_NAME + WARNING_STR, + VERSION_NAME, + CONFIG_HASH_NAME, + ARTIFACT_LIST_NAME, + REPOSITORIES_LIST_NAME ); private final Map artifacts; @@ -61,15 +61,15 @@ private LockFile(Builder builder) { public static LockFile fromNode(Node node) { LockFile.Builder builder = builder(); node.expectObjectNode() - .warnIfAdditionalProperties(EXPECTED_PROPERTIES) - .getStringMember(VERSION_NAME, builder::version) - .getNumberMember(CONFIG_HASH_NAME, n -> builder.configHash(n.intValue())) - .getObjectMember(ARTIFACT_LIST_NAME, artifactList -> { - for (Map.Entry entry : artifactList.getStringMap().entrySet()) { - builder.artifact(LockedArtifact.fromCoordinateNode(entry.getKey(), entry.getValue())); - } - }) - .getArrayMember(REPOSITORIES_LIST_NAME, StringNode::getValue, builder::repositories); + .warnIfAdditionalProperties(EXPECTED_PROPERTIES) + .getStringMember(VERSION_NAME, builder::version) + .getNumberMember(CONFIG_HASH_NAME, n -> builder.configHash(n.intValue())) + .getObjectMember(ARTIFACT_LIST_NAME, artifactList -> { + for (Map.Entry entry : artifactList.getStringMap().entrySet()) { + builder.artifact(LockedArtifact.fromCoordinateNode(entry.getKey(), entry.getValue())); + } + }) + .getArrayMember(REPOSITORIES_LIST_NAME, StringNode::getValue, builder::repositories); return builder.build(); } @@ -95,10 +95,10 @@ public static Optional load(Path path) { @Override public Node toNode() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withMember(WARNING_STR, "") - .withMember(VERSION_NAME, version) - .withMember(CONFIG_HASH_NAME, configHash) - .withMember(REPOSITORIES_LIST_NAME, ArrayNode.fromStrings(repositories)); + .withMember(WARNING_STR, "") + .withMember(VERSION_NAME, version) + .withMember(CONFIG_HASH_NAME, configHash) + .withMember(REPOSITORIES_LIST_NAME, ArrayNode.fromStrings(repositories)); ObjectNode.Builder artifactNodeBuilder = Node.objectNodeBuilder(); for (LockedArtifact artifact : artifacts.values()) { @@ -167,9 +167,9 @@ public void save() { @Override public LockFile.Builder toBuilder() { return builder().repositories(repositories) - .artifacts(artifacts) - .version(version) - .configHash(configHash); + .artifacts(artifacts) + .version(version) + .configHash(configHash); } public static final class Builder implements SmithyBuilder { @@ -260,8 +260,8 @@ private static LockedArtifact fromCoordinateNode(String coordinates, Node node) @Override public Node toNode() { return Node.objectNodeBuilder() - .withMember(SHA_SUM_MEMBER_NAME, shaSum) - .build(); + .withMember(SHA_SUM_MEMBER_NAME, shaSum) + .build(); } boolean matchesResolved(ResolvedArtifact resolved) { diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/MigrateCommand.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/MigrateCommand.java index 875b1488e3b..254807720dd 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/MigrateCommand.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/MigrateCommand.java @@ -83,12 +83,12 @@ public String getSummary() { public int execute(Arguments arguments, Env env) { if (!arguments.getReceiver(StandardOptions.class).quiet()) { env.colors() - .style( - env.stderr(), - "upgrade-1-to-2 is deprecated. Use the migrate command instead." - + System.lineSeparator(), - ColorTheme.DEPRECATED - ); + .style( + env.stderr(), + "upgrade-1-to-2 is deprecated. Use the migrate command instead." + + System.lineSeparator(), + ColorTheme.DEPRECATED + ); env.stderr().flush(); } return command.execute(arguments, env); @@ -117,9 +117,9 @@ public int execute(Arguments arguments, Env env) { arguments.addReceiver(new BuildOptions()); CommandAction action = HelpActionWrapper.fromCommand( - this, - parentCommandName, - this::run + this, + parentCommandName, + this::run ); return action.apply(arguments, env); @@ -144,26 +144,26 @@ private int run(Arguments arguments, Env env) { SmithyBuildConfig temporaryConfig = configBuilder.build(); Model initialModel = new ModelBuilder() - .config(smithyBuildConfig) - .arguments(arguments) - .env(env) - .models(models) - .validationPrinter(env.stderr()) - .defaultSeverity(Severity.DANGER) - .build(); + .config(smithyBuildConfig) + .arguments(arguments) + .env(env) + .models(models) + .validationPrinter(env.stderr()) + .defaultSeverity(Severity.DANGER) + .build(); SmithyBuild smithyBuild = SmithyBuild.create(classLoader) - .config(temporaryConfig) - // Only build the source projection - .projectionFilter(name -> name.equals("source")) - // The only traits we care about looking at are in the prelude, - // so we can safely ignore any that are unknown. - .modelAssemblerSupplier(() -> { - ModelAssembler assembler = Model.assembler(); - assembler.putProperty(ModelAssembler.ALLOW_UNKNOWN_TRAITS, true); - return assembler; - }) - .model(initialModel); + .config(temporaryConfig) + // Only build the source projection + .projectionFilter(name -> name.equals("source")) + // The only traits we care about looking at are in the prelude, + // so we can safely ignore any that are unknown. + .modelAssemblerSupplier(() -> { + ModelAssembler assembler = Model.assembler(); + assembler.putProperty(ModelAssembler.ALLOW_UNKNOWN_TRAITS, true); + return assembler; + }) + .model(initialModel); // Run SmithyBuild to get the finalized model ResultConsumer resultConsumer = new ResultConsumer(); @@ -188,9 +188,9 @@ private int run(Arguments arguments, Env env) { assembler.assemble().validate(); } catch (ValidatedResultException e) { throw new RuntimeException( - "Upgraded Smithy models are invalid. " - + "Please report the following errors to Smithy team.\n" - + e.getMessage() + "Upgraded Smithy models are invalid. " + + "Please report the following errors to Smithy team.\n" + + e.getMessage() ); } @@ -203,28 +203,28 @@ private int run(Arguments arguments, Env env) { private List resolveModelFiles(Model model, List modelFilesOrDirectories) { Set absoluteModelFilesOrDirectories = modelFilesOrDirectories.stream() - .map(path -> Paths.get(path).toAbsolutePath()) - .collect(Collectors.toSet()); + .map(path -> Paths.get(path).toAbsolutePath()) + .collect(Collectors.toSet()); return model.shapes() - .filter(shape -> !Prelude.isPreludeShape(shape)) - .filter(shape -> !shape.getSourceLocation().getFilename().startsWith("jar:")) - .map(shape -> Paths.get(shape.getSourceLocation().getFilename()).toAbsolutePath()) - .distinct() - .filter(locationPath -> { - for (Path inputPath : absoluteModelFilesOrDirectories) { - if (!locationPath.startsWith(inputPath)) { - LOGGER.finest("Skipping non-target model file: " + locationPath); + .filter(shape -> !Prelude.isPreludeShape(shape)) + .filter(shape -> !shape.getSourceLocation().getFilename().startsWith("jar:")) + .map(shape -> Paths.get(shape.getSourceLocation().getFilename()).toAbsolutePath()) + .distinct() + .filter(locationPath -> { + for (Path inputPath : absoluteModelFilesOrDirectories) { + if (!locationPath.startsWith(inputPath)) { + LOGGER.finest("Skipping non-target model file: " + locationPath); + return false; + } + } + if (!locationPath.toString().endsWith(".smithy")) { + LOGGER.info("Skipping non-IDL model file: " + locationPath); return false; } - } - if (!locationPath.toString().endsWith(".smithy")) { - LOGGER.info("Skipping non-IDL model file: " + locationPath); - return false; - } - return true; - }) - .sorted() - .collect(Collectors.toList()); + return true; + }) + .sorted() + .collect(Collectors.toList()); } private void writeMigratedFile(String upgradeFileString, Path filePath) { @@ -244,12 +244,12 @@ String upgradeFile(Model completeModel, Path filePath) { ShapeMigrateVisitor visitor = new ShapeMigrateVisitor(completeModel, contents); completeModel.shapes() - .filter(shape -> shape.getSourceLocation().getFilename().equals(filePath.toString())) - // Apply updates to the shapes at the bottom of the file first. - // This lets us modify the file without invalidating the existing - // source locations. - .sorted(Comparator.comparing(Shape::getSourceLocation).reversed()) - .forEach(shape -> shape.accept(visitor)); + .filter(shape -> shape.getSourceLocation().getFilename().equals(filePath.toString())) + // Apply updates to the shapes at the bottom of the file first. + // This lets us modify the file without invalidating the existing + // source locations. + .sorted(Comparator.comparing(Shape::getSourceLocation).reversed()) + .forEach(shape -> shape.accept(visitor)); return updateVersion(visitor.getModelString()); } @@ -308,9 +308,9 @@ protected Void getDefault(Shape shape) { } // Handle members in reverse definition order. shape.members() - .stream() - .sorted(Comparator.comparing(Shape::getSourceLocation).reversed()) - .forEach(this::handleMemberShape); + .stream() + .sorted(Comparator.comparing(Shape::getSourceLocation).reversed()) + .forEach(this::handleMemberShape); return null; } @@ -326,7 +326,7 @@ private void handleMemberShape(MemberShape shape) { private boolean hasSyntheticDefault(Shape shape) { Optional defaultLocation = shape.getTrait(DefaultTrait.class) - .map(Trait::getSourceLocation); + .map(Trait::getSourceLocation); // When Smithy injects the default trait, it sets the source // location equal to the shape's source location. This is // impossible in any other scenario, so we can use this info @@ -406,15 +406,15 @@ private String serializeEnum(StringShape shape) { // We're leaving the other traits where they are in the model // string to preserve things like comments as much as is possible. StringShape stripped = shape.toBuilder() - .clearTraits() - .addTrait(shape.expectTrait(EnumTrait.class)) - .build(); + .clearTraits() + .addTrait(shape.expectTrait(EnumTrait.class)) + .build(); // Build a faux model that only contains the enum we want to write. Model model = Model.assembler() - .addShapes(stripped) - .assemble() - .unwrap(); + .addShapes(stripped) + .assemble() + .unwrap(); // Use existing conversion tools to convert it to an enum shape, // then serialize it using the idl serializer. diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ModelBuilder.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ModelBuilder.java index c353b2cfe44..bc8e8ce86f7 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ModelBuilder.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ModelBuilder.java @@ -61,9 +61,9 @@ public ModelBuilder arguments(Arguments arguments) { // Only some commands (like validate) actually let you customize the output format, so assume a default. if (validationOutputFormat == null) { validationOutputFormat( - arguments.hasReceiver(ValidationEventFormatOptions.class) - ? arguments.getReceiver(ValidationEventFormatOptions.class).format() - : ValidationEventFormatOptions.Format.TEXT + arguments.hasReceiver(ValidationEventFormatOptions.class) + ? arguments.getReceiver(ValidationEventFormatOptions.class).format() + : ValidationEventFormatOptions.Format.TEXT ); } @@ -138,8 +138,8 @@ public Model build() { // Resolve validator options and severity. ValidatorOptions validatorOptions = arguments.hasReceiver(ValidatorOptions.class) - ? arguments.getReceiver(ValidatorOptions.class) - : new ValidatorOptions(); + ? arguments.getReceiver(ValidatorOptions.class) + : new ValidatorOptions(); resolveMinSeverity(standardOptions, validatorOptions); ClassLoader classLoader = env.classLoader(); @@ -184,13 +184,13 @@ public Model build() { sortedEvents.sort(Comparator.comparing(ValidationEvent::getSourceLocation)); SourceContextLoader sourceContextLoader = validatedResult.getResult() - .map(model -> SourceContextLoader.createModelAwareLoader(model, DEFAULT_CODE_LINES)) - .orElseGet(() -> SourceContextLoader.createLineBasedLoader(DEFAULT_CODE_LINES)); + .map(model -> SourceContextLoader.createModelAwareLoader(model, DEFAULT_CODE_LINES)) + .orElseGet(() -> SourceContextLoader.createLineBasedLoader(DEFAULT_CODE_LINES)); PrettyAnsiValidationFormatter formatter = PrettyAnsiValidationFormatter.builder() - .sourceContextLoader(sourceContextLoader) - .colors(colors) - .titleLabel(titleLabel, titleLabelStyles) - .build(); + .sourceContextLoader(sourceContextLoader) + .colors(colors) + .titleLabel(titleLabel, titleLabelStyles) + .build(); if (!disableOutputFormatFraming) { validationOutputFormat.beginPrinting(validationPrinter); @@ -217,10 +217,10 @@ public Model build() { } static Consumer createStatusUpdater( - StandardOptions standardOptions, - ColorFormatter colors, - CliPrinter stderr, - AtomicInteger issueCount + StandardOptions standardOptions, + ColorFormatter colors, + CliPrinter stderr, + AtomicInteger issueCount ) { // Only show the status if not quiet and the terminal supports ANSI. if (standardOptions.quiet() || !colors.isColorEnabled()) { @@ -276,7 +276,7 @@ private boolean shouldDiscoverDependencies(SmithyBuildConfig config, boolean dis return true; } else { return config.getMaven().isPresent() - && EnvironmentVariable.SMITHY_DEPENDENCY_MODE.get().equals("standard"); + && EnvironmentVariable.SMITHY_DEPENDENCY_MODE.get().equals("standard"); } } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/PrettyAnsiValidationFormatter.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/PrettyAnsiValidationFormatter.java index eb811297a12..d3d4d01524a 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/PrettyAnsiValidationFormatter.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/PrettyAnsiValidationFormatter.java @@ -116,7 +116,7 @@ private void printTitle(ColorBuffer writer, ValidationEvent event, Style border, // dash+padding, [padding + titleLabel + padding + padding], severity, padding+dash, padding, padding. int prefixLength = 3 + (titleLabel.isEmpty() ? 0 : (titleLabel.length() + 2)) - + 1 + event.getSeverity().toString().length() + 1 + 3 + 1; + + 1 + event.getSeverity().toString().length() + 1 + 3 + 1; writer.style(w -> { w.append(" ──"); diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ProgressStyle.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ProgressStyle.java index 80fe25840d5..0fc928e4ad4 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ProgressStyle.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ProgressStyle.java @@ -31,11 +31,11 @@ public void updateAction(Command.Env env, AtomicInteger tracker) { int tickCount = tracker.getAndIncrement(); int tickNumber = tickCount % (TICKER_LENGTH + 1); String loadStr = StringUtils.repeat(PROGRESS_CHAR, tickNumber) - + StringUtils.repeat(" ", TICKER_LENGTH - tickNumber); + + StringUtils.repeat(" ", TICKER_LENGTH - tickNumber); try (ColorBuffer buffer = getBuffer(env)) { buffer.print("\r") - .print(progressMessage, ColorTheme.NOTE) - .print(loadStr, ColorTheme.NOTE); + .print(progressMessage, ColorTheme.NOTE) + .print(loadStr, ColorTheme.NOTE); } } @@ -43,14 +43,14 @@ public void updateAction(Command.Env env, AtomicInteger tracker) { public void closeAction(Command.Env env) { try (ColorBuffer buffer = getBuffer(env)) { buffer.print("\r") - .print(closeMessage, ColorTheme.SUCCESS) - .print(" [", ColorTheme.MUTED) - .print( - (System.currentTimeMillis() - startTimeMillis) / 1000.0 + "s", - ColorTheme.NOTE - ) - .print("]", ColorTheme.MUTED) - .println(); + .print(closeMessage, ColorTheme.SUCCESS) + .print(" [", ColorTheme.MUTED) + .print( + (System.currentTimeMillis() - startTimeMillis) / 1000.0 + "s", + ColorTheme.NOTE + ) + .print("]", ColorTheme.MUTED) + .println(); } } }; diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/SelectCommand.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/SelectCommand.java index b55991b43c9..ed233160553 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/SelectCommand.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/SelectCommand.java @@ -67,10 +67,10 @@ public int execute(Arguments arguments, Env env) { arguments.addReceiver(new Options()); CommandAction action = HelpActionWrapper.fromCommand( - this, - parentCommandName, - this::getDocumentation, - new ClasspathAction(dependencyResolverFactory, this::runWithClassLoader) + this, + parentCommandName, + this::getDocumentation, + new ClasspathAction(dependencyResolverFactory, this::runWithClassLoader) ); return action.apply(arguments, env); @@ -78,7 +78,7 @@ public int execute(Arguments arguments, Env env) { private String getDocumentation(ColorFormatter colors) { return "By default, each matching shape ID is printed to stdout on a new line. Pass --show or --show-traits " - + "to get JSON array output."; + + "to get JSON array output."; } private static final class Options implements ArgumentReceiver { @@ -101,10 +101,10 @@ protected void inject(Selector.ShapeMatch match, ObjectNode.Builder builder) { // Only shapes with a real source location add a file. if (!source.getFilename().equals(SourceLocation.NONE.getFilename())) { builder.withMember( - "file", - source.getFilename() - + ':' + source.getLine() - + ':' + source.getColumn() + "file", + source.getFilename() + + ':' + source.getLine() + + ':' + source.getColumn() ); } } @@ -117,8 +117,8 @@ protected void inject(Selector.ShapeMatch match, ObjectNode.Builder builder) { ObjectNode.Builder varBuilder = Node.objectNodeBuilder(); for (Map.Entry> varEntry : match.entrySet()) { varBuilder.withMember( - varEntry.getKey(), - sortShapeIds(varEntry.getValue()).map(Node::from).collect(ArrayNode.collect()) + varEntry.getKey(), + sortShapeIds(varEntry.getValue()).map(Node::from).collect(ArrayNode.collect()) ); } ObjectNode collectedVars = varBuilder.build(); @@ -195,29 +195,29 @@ public Consumer testParameter(String name) { @Override public void registerHelp(HelpPrinter printer) { printer.param( - "--selector", - null, - "SELECTOR", - "The Smithy selector to execute. Reads from STDIN when not provided." + "--selector", + null, + "SELECTOR", + "The Smithy selector to execute. Reads from STDIN when not provided." ); printer.param( - "--show", - null, - "DATA", - "Displays additional top-level members in each match and forces JSON output. This parameter " - + "accepts a comma-separated list of values, including 'type', 'file', and 'vars'. 'type' " - + "adds a string member containing the shape type of each match. 'file' adds a string " - + "member containing the absolute path to where the shape is defined followed by the line " - + "number then column (e.g., '/path/example.smithy:10:1'). 'vars' adds an object containing " - + "the variables that were captured when a shape was matched." + "--show", + null, + "DATA", + "Displays additional top-level members in each match and forces JSON output. This parameter " + + "accepts a comma-separated list of values, including 'type', 'file', and 'vars'. 'type' " + + "adds a string member containing the shape type of each match. 'file' adds a string " + + "member containing the absolute path to where the shape is defined followed by the line " + + "number then column (e.g., '/path/example.smithy:10:1'). 'vars' adds an object containing " + + "the variables that were captured when a shape was matched." ); printer.param( - "--show-traits", - null, - "TRAITS", - "Returns JSON output that includes the values of specific traits applied to matched shapes, " - + "stored in a 'traits' property. Provide a comma-separated list of trait shape IDs. " - + "Prelude traits may omit a namespace (e.g., 'required' or 'smithy.api#required')." + "--show-traits", + null, + "TRAITS", + "Returns JSON output that includes the values of specific traits applied to matched shapes, " + + "stored in a 'traits' property. Provide a comma-separated list of trait shape IDs. " + + "Prelude traits may omit a namespace (e.g., 'required' or 'smithy.api#required')." ); } @@ -231,14 +231,14 @@ public Selector selector() { private int runWithClassLoader(SmithyBuildConfig config, Arguments arguments, Env env) { Model model = new ModelBuilder() - .config(config) - .arguments(arguments) - .env(env) - .models(arguments.getPositional()) - .validationPrinter(env.stderr()) - .validationMode(Validator.Mode.QUIET_CORE_ONLY) - .defaultSeverity(Severity.DANGER) - .build(); + .config(config) + .arguments(arguments) + .env(env) + .models(arguments.getPositional()) + .validationPrinter(env.stderr()) + .validationMode(Validator.Mode.QUIET_CORE_ONLY) + .defaultSeverity(Severity.DANGER) + .build(); Options options = arguments.getReceiver(Options.class); Selector selector = options.selector(); @@ -269,7 +269,7 @@ void dumpResults(Selector selector, Model model, Options options, CliPrinter std void dumpResults(Selector selector, Model model, Options options, CliPrinter stdout) { List result = selector.matches(model).map(match -> { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withMember("shape", Node.from(match.getShape().getId().toString())); + .withMember("shape", Node.from(match.getShape().getId().toString())); for (Options.Show showData : options.show) { showData.inject(match, builder); @@ -279,8 +279,8 @@ void dumpResults(Selector selector, Model model, Options options, CliPrinter std Map values = new TreeMap<>(); for (ShapeId trait : options.showTraits) { match.getShape() - .findTrait(trait) - .ifPresent(found -> values.put(Node.from(trait.toString()), found.toNode())); + .findTrait(trait) + .ifPresent(found -> values.put(Node.from(trait.toString()), found.toNode())); } builder.withMember("traits", Node.objectNode(values)); } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/SmithyCommand.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/SmithyCommand.java index f19611f3e32..74fa40cfd9d 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/SmithyCommand.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/SmithyCommand.java @@ -29,19 +29,19 @@ public SmithyCommand(DependencyResolver.Factory dependencyResolverFactory) { Command deprecated1To2Command = MigrateCommand.createDeprecatedAlias(migrateCommand); commands = Arrays.asList( - new VersionCommand(), - new ValidateCommand(getName(), dependencyResolverFactory), - new BuildCommand(getName(), dependencyResolverFactory), - new DiffCommand(getName(), dependencyResolverFactory), - new AstCommand(getName(), dependencyResolverFactory), - new SelectCommand(getName(), dependencyResolverFactory), - new FormatCommand(getName()), - new CleanCommand(getName()), - migrateCommand, - deprecated1To2Command, - new WarmupCommand(getName()), - new InitCommand(getName()), - new LockCommand(getName(), dependencyResolverFactory) + new VersionCommand(), + new ValidateCommand(getName(), dependencyResolverFactory), + new BuildCommand(getName(), dependencyResolverFactory), + new DiffCommand(getName(), dependencyResolverFactory), + new AstCommand(getName(), dependencyResolverFactory), + new SelectCommand(getName(), dependencyResolverFactory), + new FormatCommand(getName()), + new CleanCommand(getName()), + migrateCommand, + deprecated1To2Command, + new WarmupCommand(getName()), + new InitCommand(getName()), + new LockCommand(getName(), dependencyResolverFactory) ); } @@ -57,10 +57,10 @@ public String getSummary() { private void printHelp(ColorFormatter colors, CliPrinter printer) { printer.println( - String.format( - "Usage: %s [-h | --help] [--version] []", - colors.style("smithy", ColorTheme.EM_UNDERLINE) - ) + String.format( + "Usage: %s [-h | --help] [--version] []", + colors.style("smithy", ColorTheme.EM_UNDERLINE) + ) ); printer.println(""); printer.println("Available commands:"); @@ -77,11 +77,11 @@ private void printHelp(ColorFormatter colors, CliPrinter printer) { for (Command command : commands) { if (!command.isHidden()) { printer.println( - String.format( - " %-" + longestName + "s %s", - colors.style(command.getName(), ColorTheme.LITERAL), - command.getSummary() - ) + String.format( + " %-" + longestName + "s %s", + colors.style(command.getName(), ColorTheme.LITERAL), + command.getSummary() + ) ); } } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ValidateCommand.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ValidateCommand.java index e295ff6bbd9..9467b674354 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ValidateCommand.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ValidateCommand.java @@ -40,9 +40,9 @@ public int execute(Arguments arguments, Env env) { arguments.addReceiver(new ValidationEventFormatOptions()); CommandAction action = HelpActionWrapper.fromCommand( - this, - parentCommandName, - new ClasspathAction(dependencyResolverFactory, this::runWithClassLoader) + this, + parentCommandName, + new ClasspathAction(dependencyResolverFactory, this::runWithClassLoader) ); return action.apply(arguments, env); @@ -50,12 +50,12 @@ public int execute(Arguments arguments, Env env) { private int runWithClassLoader(SmithyBuildConfig config, Arguments arguments, Env env) { new ModelBuilder() - .config(config) - .arguments(arguments) - .env(env) - .models(arguments.getPositional()) - .validationPrinter(env.stdout()) - .build(); + .config(config) + .arguments(arguments) + .env(env) + .models(arguments.getPositional()) + .validationPrinter(env.stdout()) + .build(); LOGGER.info("Smithy validation complete"); return 0; } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ValidationEventFormatOptions.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ValidationEventFormatOptions.java index 221e5d5eef4..f7c5581f9ec 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ValidationEventFormatOptions.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ValidationEventFormatOptions.java @@ -34,18 +34,18 @@ void beginPrinting(CliPrinter printer) { @Override void print(CliPrinter printer, ValidationEventFormatter formatter, ValidationEvent event) { printer.println( - String.format( - "\"%s\",\"%s\",\"%s\",\"%s\",%d,%d,\"%s\",\"%s\",\"%s\"", - event.getSeverity().toString(), - formatCsv(event.getId()), - event.getShapeId().map(ShapeId::toString).orElse(""), - formatCsv(event.getSourceLocation().getFilename()), - event.getSourceLocation().getLine(), - event.getSourceLocation().getColumn(), - formatCsv(event.getMessage()), - formatCsv(event.getHint().orElse("")), - formatCsv(event.getSuppressionReason().orElse("")) - ) + String.format( + "\"%s\",\"%s\",\"%s\",\"%s\",%d,%d,\"%s\",\"%s\",\"%s\"", + event.getSeverity().toString(), + formatCsv(event.getId()), + event.getShapeId().map(ShapeId::toString).orElse(""), + formatCsv(event.getSourceLocation().getFilename()), + event.getSourceLocation().getLine(), + event.getSourceLocation().getColumn(), + formatCsv(event.getMessage()), + formatCsv(event.getHint().orElse("")), + formatCsv(event.getSuppressionReason().orElse("")) + ) ); } }; @@ -67,10 +67,10 @@ private static String formatCsv(String value) { @Override public void registerHelp(HelpPrinter printer) { printer.param( - VALIDATION_FORMAT, - null, - "text|csv", - "Specifies the format to write validation events (text or csv). Defaults to text." + VALIDATION_FORMAT, + null, + "text|csv", + "Specifies the format to write validation events (text or csv). Defaults to text." ); } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ValidatorOptions.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ValidatorOptions.java index 9e9ba528bbc..f9e562e2a93 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ValidatorOptions.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/ValidatorOptions.java @@ -31,27 +31,27 @@ final class ValidatorOptions implements ArgumentReceiver { @Override public void registerHelp(HelpPrinter printer) { printer.param( - SEVERITY, - null, - "SEVERITY", - "Set the minimum reported validation severity (one of NOTE, " - + "WARNING [default setting], DANGER, ERROR)." + SEVERITY, + null, + "SEVERITY", + "Set the minimum reported validation severity (one of NOTE, " + + "WARNING [default setting], DANGER, ERROR)." ); printer.param( - SHOW_VALIDATORS, - null, - "VALIDATORS", - "Comma-separated list of hierarchical validation event " - + "IDs to show in the output of the command, " - + "hiding the rest." + SHOW_VALIDATORS, + null, + "VALIDATORS", + "Comma-separated list of hierarchical validation event " + + "IDs to show in the output of the command, " + + "hiding the rest." ); printer.param( - HIDE_VALIDATORS, - null, - "VALIDATORS", - "Comma-separated list of hierarchical validation event " - + "IDs to hide in the output of the command, " - + "showing the rest." + HIDE_VALIDATORS, + null, + "VALIDATORS", + "Comma-separated list of hierarchical validation event " + + "IDs to hide in the output of the command, " + + "showing the rest." ); } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/WarmupCommand.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/WarmupCommand.java index 064ee99c950..9986de8a134 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/WarmupCommand.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/WarmupCommand.java @@ -131,42 +131,42 @@ private int orchestrate(boolean isDebug, CliPrinter printer) { LOGGER.info("Building class list"); callJava( - Phase.CLASSES, - isDebug, - printer, - baseDir, - baseArgs, - "-Xshare:off", - "-XX:DumpLoadedClassList=" + classListFile, - SmithyCli.class.getName(), - "warmup" + Phase.CLASSES, + isDebug, + printer, + baseDir, + baseArgs, + "-Xshare:off", + "-XX:DumpLoadedClassList=" + classListFile, + SmithyCli.class.getName(), + "warmup" ); LOGGER.info("Building archive from classlist"); callJava( - Phase.WRAPPER, - isDebug, - printer, - baseDir, - baseArgs, - "-XX:SharedClassListFile=" + classListFile, - "-Xshare:dump", - "-XX:SharedArchiveFile=" + jsaFile, - SmithyCli.class.getName(), - "warmup" + Phase.WRAPPER, + isDebug, + printer, + baseDir, + baseArgs, + "-XX:SharedClassListFile=" + classListFile, + "-Xshare:dump", + "-XX:SharedArchiveFile=" + jsaFile, + SmithyCli.class.getName(), + "warmup" ); LOGGER.info("Validating that the archive was created correctly"); callJava( - null, - isDebug, - printer, - baseDir, - baseArgs, - "-Xshare:on", - "-XX:SharedArchiveFile=" + jsaFile, - SmithyCli.class.getName(), - "--help" + null, + isDebug, + printer, + baseDir, + baseArgs, + "-Xshare:on", + "-XX:SharedArchiveFile=" + jsaFile, + SmithyCli.class.getName(), + "--help" ); classListFile.toFile().delete(); @@ -185,12 +185,12 @@ private String getOrThrowIfUndefinedProperty(String property) { } private void callJava( - Phase phase, - boolean isDebug, - CliPrinter printer, - Path baseDir, - List baseArgs, - String... args + Phase phase, + boolean isDebug, + CliPrinter printer, + Path baseDir, + List baseArgs, + String... args ) { List resolved = new ArrayList<>(baseArgs); Collections.addAll(resolved, args); @@ -232,11 +232,11 @@ private int runCodeToOptimize(Arguments arguments, Env env) { File buildFile = tempDirWithPrefix.resolve("smithy-build.json").toFile(); try (FileWriter writer = new FileWriter(buildFile)) { writer.write( - "{\n" - + " \"version\": \"1.0\",\n" - + " \"maven\": {\"dependencies\": [\"software.amazon.smithy:smithy-model:" - + SmithyCli.getVersion() + "\"]}\n" - + "}" + "{\n" + + " \"version\": \"1.0\",\n" + + " \"maven\": {\"dependencies\": [\"software.amazon.smithy:smithy-model:" + + SmithyCli.getVersion() + "\"]}\n" + + "}" ); } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/FileCacheResolver.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/FileCacheResolver.java index 04e71f59486..6a39b0b8ee9 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/FileCacheResolver.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/FileCacheResolver.java @@ -105,7 +105,7 @@ private List load() { // If the version of the cache file does not match the current version or does not exist // invalidate it so we can replace it with a more recent version. if (!node.containsMember("version") - || !CURRENT_CACHE_FILE_VERSION.equals(node.expectStringMember("version").getValue()) + || !CURRENT_CACHE_FILE_VERSION.equals(node.expectStringMember("version").getValue()) ) { LOGGER.fine(() -> "Invalidating dependency cache: cache file uses old version"); invalidate(); diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/FilterCliVersionResolver.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/FilterCliVersionResolver.java index 37341047eae..48552dbe84e 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/FilterCliVersionResolver.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/FilterCliVersionResolver.java @@ -26,12 +26,12 @@ public final class FilterCliVersionResolver implements DependencyResolver { private static final Logger LOGGER = Logger.getLogger(FilterCliVersionResolver.class.getName()); private static final String SMITHY_GROUP = "software.amazon.smithy"; private static final Set CLI_ARTIFACTS = SetUtils.of( - "smithy-utils", - "smithy-model", - "smithy-build", - "smithy-cli", - "smithy-diff", - "smithy-syntax" + "smithy-utils", + "smithy-model", + "smithy-build", + "smithy-cli", + "smithy-diff", + "smithy-syntax" ); private final String version; @@ -78,9 +78,9 @@ public List resolve() { int compare = artifactVersion.compareTo(parsedSmithyVersion); if (compare > 0) { throw new DependencyResolverException( - "The Smithy CLI is at version " + parsedSmithyVersion + ", but dependencies resolved to " - + "use a newer, incompatible version of " + artifact.getCoordinates() + ". Please " - + "update the Smithy CLI." + "The Smithy CLI is at version " + parsedSmithyVersion + ", but dependencies resolved to " + + "use a newer, incompatible version of " + artifact.getCoordinates() + ". Please " + + "update the Smithy CLI." ); } else if (compare < 0) { replacements.add("- Replaced " + artifact.getCoordinates()); @@ -93,11 +93,11 @@ public List resolve() { if (!replacements.isEmpty()) { String contents = String.join(System.lineSeparator(), replacements); LOGGER.info( - "Resolved dependencies were replaced with dependencies used by the Smithy CLI (" - + version + "). If the CLI fails due to issues like unknown classes, methods, missing " - + "traits, etc, then consider upgrading your dependencies to match the version of the CLI " - + "or modifying your declared dependencies." - + System.lineSeparator() + contents + "Resolved dependencies were replaced with dependencies used by the Smithy CLI (" + + version + "). If the CLI fails due to issues like unknown classes, methods, missing " + + "traits, etc, then consider upgrading your dependencies to match the version of the CLI " + + "or modifying your declared dependencies." + + System.lineSeparator() + contents ); } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/MavenDependencyResolver.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/MavenDependencyResolver.java index e5a8d65fa52..5cc7bcd3db3 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/MavenDependencyResolver.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/MavenDependencyResolver.java @@ -73,8 +73,8 @@ public void serviceCreationFailed(Class type, Class impl, Throwable except } }); commonProxy = getProxy( - EnvironmentVariable.SMITHY_PROXY_HOST.get(), - EnvironmentVariable.SMITHY_PROXY_CREDENTIALS.get() + EnvironmentVariable.SMITHY_PROXY_HOST.get(), + EnvironmentVariable.SMITHY_PROXY_CREDENTIALS.get() ); repositorySystem = locator.getService(RepositorySystem.class); @@ -106,8 +106,8 @@ public void addRepository(MavenRepository repository) { remoteRepositories.add(builder.build()); } catch (URISyntaxException e) { throw new DependencyResolverException( - "Invalid Maven repository URL: " + repository.getUrl() - + ": " + e.getMessage() + "Invalid Maven repository URL: " + repository.getUrl() + + ": " + e.getMessage() ); } } @@ -115,7 +115,7 @@ public void addRepository(MavenRepository repository) { private void addProxyInfo(MavenRepository repository, RemoteRepository.Builder builder) { if (repository.getProxyHost().isPresent()) { builder.setProxy( - getProxy(repository.getProxyHost().get(), repository.getProxyCredentials().orElse(null)) + getProxy(repository.getProxyHost().get(), repository.getProxyCredentials().orElse(null)) ); } else if (commonProxy != null) { builder.setProxy(commonProxy); @@ -131,8 +131,8 @@ private static Proxy getProxy(final String host, final String userPass) { if (userPass != null) { String[] userSettings = parseProxyCredentials(userPass); AuthenticationBuilder authBuilder = new AuthenticationBuilder() - .addUsername(userSettings[0]) - .addPassword(userSettings[1]); + .addUsername(userSettings[0]) + .addPassword(userSettings[1]); return new Proxy(hostUrl.getProtocol(), hostUrl.getHost(), hostUrl.getPort(), authBuilder.build()); } else { return new Proxy(hostUrl.getProtocol(), hostUrl.getHost(), hostUrl.getPort()); @@ -144,8 +144,8 @@ private static String[] parseProxyCredentials(String value) { String[] settings = value.split(":"); if (settings.length != 2) { throw new DependencyResolverException( - "Expected two values separated by ':' for " - + EnvironmentVariable.SMITHY_PROXY_CREDENTIALS + ", but found " + settings.length + "Expected two values separated by ':' for " + + EnvironmentVariable.SMITHY_PROXY_CREDENTIALS + ", but found " + settings.length ); } return settings; @@ -156,8 +156,8 @@ private static URL parseHostString(String value) { return new URL(value); } catch (MalformedURLException exc) { throw new DependencyResolverException( - "Expected a valid URL for " - + EnvironmentVariable.SMITHY_PROXY_HOST + ". Found " + value + "Expected a valid URL for " + + EnvironmentVariable.SMITHY_PROXY_HOST + ". Found " + value ); } } @@ -168,10 +168,10 @@ private void addUserInfoAuth(URI uri, String userInfo, RemoteRepository.Builder throw new DependencyResolverException("Invalid credentials provided for " + uri); } builder.setAuthentication( - new AuthenticationBuilder() - .addUsername(parts[0]) - .addPassword(parts[1]) - .build() + new AuthenticationBuilder() + .addUsername(parts[0]) + .addPassword(parts[1]) + .build() ); } @@ -191,12 +191,12 @@ public List resolve() { for (ArtifactResult result : results) { Artifact artifact = result.getArtifact(); artifacts.add( - new ResolvedArtifact( - artifact.getFile().toPath(), - artifact.getGroupId(), - artifact.getArtifactId(), - artifact.getVersion() - ) + new ResolvedArtifact( + artifact.getFile().toPath(), + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getVersion() + ) ); } return artifacts; @@ -228,8 +228,8 @@ private static void validateDependencyVersion(Artifact artifact) { private List resolveMavenArtifacts() { LOGGER.fine( - () -> "Resolving Maven dependencies for Smithy CLI; repos: " - + remoteRepositories + "; dependencies: " + dependencies + () -> "Resolving Maven dependencies for Smithy CLI; repos: " + + remoteRepositories + "; dependencies: " + dependencies ); CollectRequest collectRequest = new CollectRequest(); collectRequest.setRepositories(remoteRepositories); @@ -238,8 +238,8 @@ private List resolveMavenArtifacts() { try { List results = repositorySystem - .resolveDependencies(session, dependencyRequest) - .getArtifactResults(); + .resolveDependencies(session, dependencyRequest) + .getArtifactResults(); LOGGER.fine(() -> "Resolved Maven dependencies: " + results); return results; } catch (DependencyResolutionException e) { diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/ResolvedArtifact.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/ResolvedArtifact.java index fd282ee273c..9725d5399bc 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/ResolvedArtifact.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/dependencies/ResolvedArtifact.java @@ -35,12 +35,12 @@ public ResolvedArtifact(Path path, String groupId, String artifactId, String ver } private ResolvedArtifact( - Path path, - String coordinates, - String groupId, - String artifactId, - String version, - String shaSum + Path path, + String coordinates, + String groupId, + String artifactId, + String version, + String shaSum ) { this.coordinates = Objects.requireNonNull(coordinates); this.path = Objects.requireNonNull(path); @@ -164,16 +164,16 @@ public boolean equals(Object o) { } ResolvedArtifact artifact = (ResolvedArtifact) o; return path.equals(artifact.path) - && shaSum.equals(artifact.shaSum) - && coordinates.equals(artifact.coordinates); + && shaSum.equals(artifact.shaSum) + && coordinates.equals(artifact.coordinates); } @Override public Node toNode() { return Node.objectNodeBuilder() - .withMember(PATH_MEMBER_NAME, path.toString()) - .withMember(SHA_SUM_MEMBER_NAME, shaSum) - .build(); + .withMember(PATH_MEMBER_NAME, path.toString()) + .withMember(SHA_SUM_MEMBER_NAME, shaSum) + .build(); } private static String[] parseCoordinates(String coordinates) { diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/BuildParameterBuilderTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/BuildParameterBuilderTest.java index 239dcb554f3..41ea98bc035 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/BuildParameterBuilderTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/BuildParameterBuilderTest.java @@ -30,16 +30,16 @@ public class BuildParameterBuilderTest { public void cannotSetTagsUnlessProjecting() { Assertions.assertThrows(SmithyBuildException.class, () -> { new BuildParameterBuilder() - .projectionSourceTags(ListUtils.of("foo", "baz")) - .build(); + .projectionSourceTags(ListUtils.of("foo", "baz")) + .build(); }); } @Test public void skipsMissingConfigFiles() { BuildParameterBuilder.Result result = new BuildParameterBuilder() - .addConfigIfExists("/does/not/exist.json") - .build(); + .addConfigIfExists("/does/not/exist.json") + .build(); assertThat(result.args, not(hasItem("--config"))); } @@ -48,8 +48,8 @@ public void skipsMissingConfigFiles() { public void addsConfigFilesWhenFound() throws URISyntaxException { String configFile = Paths.get(getClass().getResource("smithy-build-a.json").toURI()).toString(); BuildParameterBuilder.Result result = new BuildParameterBuilder() - .addConfigIfExists(configFile) - .build(); + .addConfigIfExists(configFile) + .build(); assertThat(result.args, hasItem("--config")); assertThat(result.args, hasItem(configFile)); @@ -58,8 +58,8 @@ public void addsConfigFilesWhenFound() throws URISyntaxException { @Test public void allowsUnknownTraits() { BuildParameterBuilder.Result result = new BuildParameterBuilder() - .allowUnknownTraits(true) - .build(); + .allowUnknownTraits(true) + .build(); assertThat(result.args, hasItem("--allow-unknown-traits")); } @@ -67,8 +67,8 @@ public void allowsUnknownTraits() { @Test public void canSetOutput() { BuildParameterBuilder.Result result = new BuildParameterBuilder() - .output("/path/to/foo") - .build(); + .output("/path/to/foo") + .build(); assertThat(result.args, hasItem("--output")); assertThat(result.args, hasItem("/path/to/foo")); @@ -77,8 +77,8 @@ public void canSetOutput() { @Test public void canSetProjection() { BuildParameterBuilder.Result result = new BuildParameterBuilder() - .projection("testing") - .build(); + .projection("testing") + .build(); assertThat(result.args, hasItem("--projection")); assertThat(result.args, hasItem("testing")); @@ -87,8 +87,8 @@ public void canSetProjection() { @Test public void canSetPlugin() { BuildParameterBuilder.Result result = new BuildParameterBuilder() - .plugin("testing") - .build(); + .plugin("testing") + .build(); assertThat(result.args, hasItem("--plugin")); assertThat(result.args, hasItem("testing")); @@ -97,8 +97,8 @@ public void canSetPlugin() { @Test public void canEnableDiscoveryWithNoClasspaths() { BuildParameterBuilder.Result result = new BuildParameterBuilder() - .discover(true) - .build(); + .discover(true) + .build(); assertThat(result.args, hasItem("--discover")); assertThat(result.args, not(hasItem("--discover-classpath"))); @@ -107,8 +107,8 @@ public void canEnableDiscoveryWithNoClasspaths() { @Test public void canAddExtraArguments() { BuildParameterBuilder.Result result = new BuildParameterBuilder() - .addExtraArgs("--foo", "baz", "--bar") - .build(); + .addExtraArgs("--foo", "baz", "--bar") + .build(); assertThat(result.args, hasItem("--foo")); assertThat(result.args, hasItem("baz")); @@ -118,20 +118,20 @@ public void canAddExtraArguments() { @Test public void ignoresNullAndEmptyValues() { BuildParameterBuilder.Result result = new BuildParameterBuilder() - .sources(null) - .projectionSource(null) - .projectionSource("") - .projectionSourceTags((String) null) - .projectionSourceTags((Collection) null) - .addConfig(null) - .addConfig("") - .addConfigIfExists(null) - .addConfigIfExists("") - .buildClasspath(null) - .buildClasspath("") - .libClasspath(null) - .libClasspath("") - .build(); + .sources(null) + .projectionSource(null) + .projectionSource("") + .projectionSourceTags((String) null) + .projectionSourceTags((Collection) null) + .addConfig(null) + .addConfig("") + .addConfigIfExists(null) + .addConfigIfExists("") + .buildClasspath(null) + .buildClasspath("") + .libClasspath(null) + .libClasspath("") + .build(); assertThat(result.args, contains("build")); assertThat(result.classpath.length(), is(0)); @@ -150,22 +150,22 @@ private static String cp(String... paths) { @Test public void sourceBuildUsesCorrectClasspaths() { BuildParameterBuilder.Result result = new BuildParameterBuilder() - .sources(ListUtils.of("foo.smithy", "bar.smithy")) - // Note that duplicates are removed when necessary. - .libClasspath(cp("foo.jar", "baz.jar", "bar.jar")) - .buildClasspath(cp("foo.jar", "/abc/123.jar")) - .discover(true) - .build(); + .sources(ListUtils.of("foo.smithy", "bar.smithy")) + // Note that duplicates are removed when necessary. + .libClasspath(cp("foo.jar", "baz.jar", "bar.jar")) + .buildClasspath(cp("foo.jar", "/abc/123.jar")) + .discover(true) + .build(); assertThat( - result.args, - contains( - "build", - "--discover-classpath", - cp("foo.jar", "baz.jar", "bar.jar"), - "foo.smithy", - "bar.smithy" - ) + result.args, + contains( + "build", + "--discover-classpath", + cp("foo.jar", "baz.jar", "bar.jar"), + "foo.smithy", + "bar.smithy" + ) ); assertThat(result.classpath, equalTo(cp("foo.jar", "baz.jar", "bar.jar", "/abc/123.jar"))); assertThat(result.discoveryClasspath, equalTo(cp("foo.jar", "baz.jar", "bar.jar"))); @@ -175,8 +175,8 @@ public void sourceBuildUsesCorrectClasspaths() { @Test public void skipsSourcesThatDoNotExsit() { BuildParameterBuilder.Result result = new BuildParameterBuilder() - .addSourcesIfExists(ListUtils.of("foo.smithy", "bar.smithy")) - .build(); + .addSourcesIfExists(ListUtils.of("foo.smithy", "bar.smithy")) + .build(); assertThat(result.args, contains("build")); } @@ -184,22 +184,22 @@ public void skipsSourcesThatDoNotExsit() { @Test public void projectionBuildUsesCorrectClasspaths() { BuildParameterBuilder.Result result = new BuildParameterBuilder() - .projectionSource("foo") - .sources(ListUtils.of("foo.smithy", "bar.smithy")) - .libClasspath(cp("foo.jar", "baz.jar", "bar.jar")) - .buildClasspath(cp("foo.jar", "/abc/123.jar")) - .discover(true) - .build(); + .projectionSource("foo") + .sources(ListUtils.of("foo.smithy", "bar.smithy")) + .libClasspath(cp("foo.jar", "baz.jar", "bar.jar")) + .buildClasspath(cp("foo.jar", "/abc/123.jar")) + .discover(true) + .build(); assertThat( - result.args, - contains( - "build", - "--discover-classpath", - cp("foo.jar", "/abc/123.jar"), - "foo.smithy", - "bar.smithy" - ) + result.args, + contains( + "build", + "--discover-classpath", + cp("foo.jar", "/abc/123.jar"), + "foo.smithy", + "bar.smithy" + ) ); assertThat(result.classpath, equalTo(cp("foo.jar", "/abc/123.jar"))); assertThat(result.discoveryClasspath, equalTo(cp("foo.jar", "/abc/123.jar"))); @@ -209,12 +209,12 @@ public void projectionBuildUsesCorrectClasspaths() { @Test public void projectionBuildSkipsMissingJars() { BuildParameterBuilder.Result result = new BuildParameterBuilder() - .projectionSource("foo") - .projectionSourceTags("abc, def") - .libClasspath(cp("foo.jar", "baz.jar", "bar.jar")) - .buildClasspath(cp("foo.jar", "/abc/123.jar")) - .discover(true) - .build(); + .projectionSource("foo") + .projectionSourceTags("abc, def") + .libClasspath(cp("foo.jar", "baz.jar", "bar.jar")) + .buildClasspath(cp("foo.jar", "/abc/123.jar")) + .discover(true) + .build(); assertThat(result.classpath, equalTo(cp("foo.jar", "/abc/123.jar"))); assertThat(result.discoveryClasspath, equalTo(cp("foo.jar", "/abc/123.jar"))); @@ -226,16 +226,16 @@ public void projectionBuildTaggedSourcesRemovedFromModelDiscovery() { Set parsedTags = new HashSet<>(); BuildParameterBuilder.Result result = new BuildParameterBuilder() - .projectionSource("foo") - .projectionSourceTags("abc, def") - .libClasspath(cp("abc.jar")) - .buildClasspath(cp("foo.jar", "baz.jar", "bar.jar")) - .discover(true) - .tagMatcher((cp, tags) -> { - parsedTags.addAll(tags); - return SetUtils.of("baz.jar"); - }) - .build(); + .projectionSource("foo") + .projectionSourceTags("abc, def") + .libClasspath(cp("abc.jar")) + .buildClasspath(cp("foo.jar", "baz.jar", "bar.jar")) + .discover(true) + .tagMatcher((cp, tags) -> { + parsedTags.addAll(tags); + return SetUtils.of("baz.jar"); + }) + .build(); assertThat(parsedTags, containsInAnyOrder("abc", "def")); assertThat(result.classpath, equalTo(cp("foo.jar", "baz.jar", "bar.jar"))); @@ -252,12 +252,12 @@ public void findsProjectionJarsWithSourceTags() throws URISyntaxException { String buildCp = a + separator + b + separator + c; BuildParameterBuilder.Result result = new BuildParameterBuilder() - .projectionSource("foo") - .projectionSourceTags("X, Blah") - .libClasspath("abc.jar") - .buildClasspath(buildCp) - .discover(true) - .build(); + .projectionSource("foo") + .projectionSourceTags("X, Blah") + .libClasspath("abc.jar") + .buildClasspath(buildCp) + .discover(true) + .build(); // The classpath keeps all of the JARs. assertThat(result.classpath, equalTo(buildCp)); @@ -279,12 +279,12 @@ public void usesCustomSeparator() throws URISyntaxException { String buildCp = a + "|" + b + "|" + c; BuildParameterBuilder.Result result = new BuildParameterBuilder() - .projectionSource("foo") - .projectionSourceTags("X, Blah") - .libClasspath("abc.jar") - .buildClasspath(buildCp) - .discover(true) - .build(); + .projectionSource("foo") + .projectionSourceTags("X, Blah") + .libClasspath("abc.jar") + .buildClasspath(buildCp) + .discover(true) + .build(); assertThat(result.classpath, equalTo(buildCp)); assertThat(result.discoveryClasspath, equalTo(b + "|" + c)); diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/HelpPrinterTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/HelpPrinterTest.java index 1967791e0cd..c49eaf90b2f 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/HelpPrinterTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/HelpPrinterTest.java @@ -29,13 +29,13 @@ public void worksWithJustOneOption() { help.print(AnsiColorFormatter.NO_COLOR, printer); assertThat( - printer.toString(), - startsWith( - "Usage: foo [--foo | -f] \n" - + "\n" - + " --foo, -f\n" - + " The foo value" - ) + printer.toString(), + startsWith( + "Usage: foo [--foo | -f] \n" + + "\n" + + " --foo, -f\n" + + " The foo value" + ) ); } @@ -49,17 +49,17 @@ public void worksWithMultipleOptions() { help.print(AnsiColorFormatter.NO_COLOR, printer); assertThat( - printer.toString(), - startsWith( - "Usage: foo [--foo | -f] [--bar] [-b] \n" - + "\n" - + " --foo, -f\n" - + " The foo value\n" - + " --bar\n" - + " The bar value\n" - + " -b\n" - + " What is this" - ) + printer.toString(), + startsWith( + "Usage: foo [--foo | -f] [--bar] [-b] \n" + + "\n" + + " --foo, -f\n" + + " The foo value\n" + + " --bar\n" + + " The bar value\n" + + " -b\n" + + " What is this" + ) ); } @@ -74,19 +74,19 @@ public void worksWithMultipleOptionsAndParams() { help.print(AnsiColorFormatter.NO_COLOR, printer); assertThat( - printer.toString(), - startsWith( - "Usage: foo [--foo | -f] [--bar] [-b] [--baz | -a BAZ] \n" - + "\n" - + " --foo, -f\n" - + " The foo value\n" - + " --bar\n" - + " The bar value\n" - + " -b\n" - + " What is this\n" - + " --baz, -a BAZ\n" - + " The baz param" - ) + printer.toString(), + startsWith( + "Usage: foo [--foo | -f] [--bar] [-b] [--baz | -a BAZ] \n" + + "\n" + + " --foo, -f\n" + + " The foo value\n" + + " --bar\n" + + " The bar value\n" + + " -b\n" + + " What is this\n" + + " --baz, -a BAZ\n" + + " The baz param" + ) ); } @@ -102,21 +102,21 @@ public void includesPositionalArguments() { help.print(AnsiColorFormatter.NO_COLOR, printer); assertThat( - printer.toString(), - startsWith( - "Usage: foo [--foo | -f] [--bar] [-b] [--baz | -a BAZ] [FILE...]\n" - + "\n" - + " --foo, -f\n" - + " The foo value\n" - + " --bar\n" - + " The bar value\n" - + " -b\n" - + " What is this\n" - + " --baz, -a BAZ\n" - + " The baz param\n" - + " FILE...\n" - + " Files to add" - ) + printer.toString(), + startsWith( + "Usage: foo [--foo | -f] [--bar] [-b] [--baz | -a BAZ] [FILE...]\n" + + "\n" + + " --foo, -f\n" + + " The foo value\n" + + " --bar\n" + + " The bar value\n" + + " -b\n" + + " What is this\n" + + " --baz, -a BAZ\n" + + " The baz param\n" + + " FILE...\n" + + " Files to add" + ) ); } @@ -125,26 +125,26 @@ public void wrapsArgumentDocs() { BufferPrinter printer = new BufferPrinter(); HelpPrinter help = new HelpPrinter("foo").maxWidth(100); help.option( - "--foo", - "-f", - "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " - + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " - + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " - + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo." + "--foo", + "-f", + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " + + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " + + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " + + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo." ); help.print(AnsiColorFormatter.NO_COLOR, printer); assertThat( - printer.toString(), - startsWith( - "Usage: foo [--foo | -f] \n" - + "\n" - + " --foo, -f\n" - + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" - + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" - + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" - + " foo foo foo foo foo.\n" - ) + printer.toString(), + startsWith( + "Usage: foo [--foo | -f] \n" + + "\n" + + " --foo, -f\n" + + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" + + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" + + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" + + " foo foo foo foo foo.\n" + ) ); } @@ -153,27 +153,27 @@ public void wrapsArgumentDocsWithDefaultWrapping() { BufferPrinter printer = new BufferPrinter(); HelpPrinter help = new HelpPrinter("foo"); help.option( - "--foo", - "-f", - "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " - + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " - + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " - + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo." + "--foo", + "-f", + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " + + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " + + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " + + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo." ); help.print(AnsiColorFormatter.NO_COLOR, printer); assertThat( - printer.toString(), - startsWith( - "Usage: foo [--foo | -f] \n" - + "\n" - + " --foo, -f\n" - + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" - + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" - + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" - + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" - + " foo foo." - ) + printer.toString(), + startsWith( + "Usage: foo [--foo | -f] \n" + + "\n" + + " --foo, -f\n" + + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" + + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" + + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" + + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" + + " foo foo." + ) ); } @@ -182,26 +182,26 @@ public void wrappingHandlesIndentingOnNewlinesToo() { BufferPrinter printer = new BufferPrinter(); HelpPrinter help = new HelpPrinter("foo").maxWidth(100); help.option( - "--foo", - "-f", - "foo foo foo foo foo foo foo foo foo foo\nfoo foo foo foo foo foo foo foo foo foo " - + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " - + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " - + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo." + "--foo", + "-f", + "foo foo foo foo foo foo foo foo foo foo\nfoo foo foo foo foo foo foo foo foo foo " + + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " + + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo " + + "foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo." ); help.print(AnsiColorFormatter.NO_COLOR, printer); assertThat( - printer.toString(), - startsWith( - "Usage: foo [--foo | -f] \n" - + "\n" - + " --foo, -f\n" - + " foo foo foo foo foo foo foo foo foo foo\n" - + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" - + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" - + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo." - ) + printer.toString(), + startsWith( + "Usage: foo [--foo | -f] \n" + + "\n" + + " --foo, -f\n" + + " foo foo foo foo foo foo foo foo foo foo\n" + + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" + + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo \n" + + " foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo." + ) ); } @@ -212,32 +212,32 @@ public void includesWrappedSummaryAndDocumentation() { ; help.option("--foo", "-f", "The foo value"); help.summary( - "Hello1 Hello2 Hello3 Hello4 Hello5 Hello6 Hello7 Hello8 Hello9 Hello10 Hello11 Hello12 Hello13 " - + "Hello14 Hello15 Hello16 Hello17 Hello18 Hello19 Hello20 Hello21 Hello22 Hello23 Hello24 " - + "Hello25 Hello26 Hello27 Hello28." + "Hello1 Hello2 Hello3 Hello4 Hello5 Hello6 Hello7 Hello8 Hello9 Hello10 Hello11 Hello12 Hello13 " + + "Hello14 Hello15 Hello16 Hello17 Hello18 Hello19 Hello20 Hello21 Hello22 Hello23 Hello24 " + + "Hello25 Hello26 Hello27 Hello28." ); help.documentation( - "Goodbye1 Goodbye2 Goodbye3 Goodbye4 Goodbye5 Goodbye6 Goodbye7 Goodbye8 Goodbye9 " - + "Goodbye10 Goodbye11 Goodbye12 Goodbye13 Goodbye14 Goodbye15 Goodbye16 Goodbye17 " - + "Goodbye18 Goodbye19 Goodbye20 Goodbye21." + "Goodbye1 Goodbye2 Goodbye3 Goodbye4 Goodbye5 Goodbye6 Goodbye7 Goodbye8 Goodbye9 " + + "Goodbye10 Goodbye11 Goodbye12 Goodbye13 Goodbye14 Goodbye15 Goodbye16 Goodbye17 " + + "Goodbye18 Goodbye19 Goodbye20 Goodbye21." ); help.print(AnsiColorFormatter.NO_COLOR, printer); assertThat( - printer.toString().trim(), - equalTo( - "Usage: foo [--foo | -f] \n" - + "\n" - + "Hello1 Hello2 Hello3 Hello4 Hello5 Hello6 Hello7 Hello8 Hello9 Hello10 Hello11 Hello12 Hello13 \n" - + "Hello14 Hello15 Hello16 Hello17 Hello18 Hello19 Hello20 Hello21 Hello22 Hello23 Hello24 Hello25 \n" - + "Hello26 Hello27 Hello28.\n" - + "\n" - + " --foo, -f\n" - + " The foo value\n" - + " \n" - + "Goodbye1 Goodbye2 Goodbye3 Goodbye4 Goodbye5 Goodbye6 Goodbye7 Goodbye8 Goodbye9 Goodbye10 Goodbye11\n" - + "Goodbye12 Goodbye13 Goodbye14 Goodbye15 Goodbye16 Goodbye17 Goodbye18 Goodbye19 Goodbye20 Goodbye21." - ) + printer.toString().trim(), + equalTo( + "Usage: foo [--foo | -f] \n" + + "\n" + + "Hello1 Hello2 Hello3 Hello4 Hello5 Hello6 Hello7 Hello8 Hello9 Hello10 Hello11 Hello12 Hello13 \n" + + "Hello14 Hello15 Hello16 Hello17 Hello18 Hello19 Hello20 Hello21 Hello22 Hello23 Hello24 Hello25 \n" + + "Hello26 Hello27 Hello28.\n" + + "\n" + + " --foo, -f\n" + + " The foo value\n" + + " \n" + + "Goodbye1 Goodbye2 Goodbye3 Goodbye4 Goodbye5 Goodbye6 Goodbye7 Goodbye8 Goodbye9 Goodbye10 Goodbye11\n" + + "Goodbye12 Goodbye13 Goodbye14 Goodbye15 Goodbye16 Goodbye17 Goodbye18 Goodbye19 Goodbye20 Goodbye21." + ) ); } @@ -250,15 +250,15 @@ public void handlesCarriageReturns() { help.print(AnsiColorFormatter.NO_COLOR, printer); assertThat( - printer.toString(), - startsWith( - "Usage: foo [--foo | -f] \n" - + "\n" - + "Hello1\nHello2\n\nHello3\nHello4.\n\n" - + "\n" - + " --foo, -f\n" - + " The foo value\n" - ) + printer.toString(), + startsWith( + "Usage: foo [--foo | -f] \n" + + "\n" + + "Hello1\nHello2\n\nHello3\nHello4.\n\n" + + "\n" + + " --foo, -f\n" + + " The foo value\n" + ) ); } } diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/BuildCommandTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/BuildCommandTest.java index 2ff2dccc492..e73293bdb52 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/BuildCommandTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/BuildCommandTest.java @@ -70,8 +70,8 @@ public void validationFailuresCausedByProjectionsAreDetected() throws Exception assertThat(result.code(), not(0)); assertThat(result.stderr(), containsString("ResourceLifecycle")); assertThat( - result.stderr(), - containsString("The following 1 Smithy build projection(s) failed: [exampleProjection]") + result.stderr(), + containsString("The following 1 Smithy build projection(s) failed: [exampleProjection]") ); } diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/CodeFormatterTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/CodeFormatterTest.java index 9387d59197c..e94574e7d92 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/CodeFormatterTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/CodeFormatterTest.java @@ -27,22 +27,22 @@ public void outputsSequentialLinesWithNoCursor() { ColorFormatter colors = AnsiColorFormatter.NO_COLOR; CodeFormatter formatter = new CodeFormatter(ColorBuffer.of(colors, builder), 80); List lines = Arrays.asList( - new SourceContextLoader.Line(2, "A"), - new SourceContextLoader.Line(3, "B"), - new SourceContextLoader.Line(4, "C"), - new SourceContextLoader.Line(5, "D") + new SourceContextLoader.Line(2, "A"), + new SourceContextLoader.Line(3, "B"), + new SourceContextLoader.Line(4, "C"), + new SourceContextLoader.Line(5, "D") ); formatter.writeCode(0, 0, lines); assertThat( - builder.toString(), - equalTo( - "2| A" + ls - + "3| B" + ls - + "4| C" + ls - + "5| D" + ls2 - ) + builder.toString(), + equalTo( + "2| A" + ls + + "3| B" + ls + + "4| C" + ls + + "5| D" + ls2 + ) ); } @@ -52,23 +52,23 @@ public void outputsSequentialLinesWithCursor() { ColorFormatter colors = AnsiColorFormatter.NO_COLOR; CodeFormatter formatter = new CodeFormatter(ColorBuffer.of(colors, builder), 80); List lines = Arrays.asList( - new SourceContextLoader.Line(2, "Aa"), - new SourceContextLoader.Line(3, "Bb"), - new SourceContextLoader.Line(4, "Cc"), - new SourceContextLoader.Line(5, "Dd") + new SourceContextLoader.Line(2, "Aa"), + new SourceContextLoader.Line(3, "Bb"), + new SourceContextLoader.Line(4, "Cc"), + new SourceContextLoader.Line(5, "Dd") ); formatter.writeCode(3, 2, lines); assertThat( - builder.toString(), - equalTo( - "2| Aa" + ls - + "3| Bb" + ls - + " | ^" + ls - + "4| Cc" + ls - + "5| Dd" + ls2 - ) + builder.toString(), + equalTo( + "2| Aa" + ls + + "3| Bb" + ls + + " | ^" + ls + + "4| Cc" + ls + + "5| Dd" + ls2 + ) ); } @@ -78,25 +78,25 @@ public void detectsLineSkips() { ColorFormatter colors = AnsiColorFormatter.NO_COLOR; CodeFormatter formatter = new CodeFormatter(ColorBuffer.of(colors, builder), 80); List lines = Arrays.asList( - new SourceContextLoader.Line(2, "Aa"), - new SourceContextLoader.Line(8, "Bb"), - new SourceContextLoader.Line(9, "Cc"), - new SourceContextLoader.Line(12, "Dd") + new SourceContextLoader.Line(2, "Aa"), + new SourceContextLoader.Line(8, "Bb"), + new SourceContextLoader.Line(9, "Cc"), + new SourceContextLoader.Line(12, "Dd") ); formatter.writeCode(8, 2, lines); assertThat( - builder.toString(), - equalTo( - "2 | Aa" + ls - + "··|" + ls - + "8 | Bb" + ls - + " | ^" + ls - + "9 | Cc" + ls - + "··|" + ls - + "12| Dd" + ls2 - ) + builder.toString(), + equalTo( + "2 | Aa" + ls + + "··|" + ls + + "8 | Bb" + ls + + " | ^" + ls + + "9 | Cc" + ls + + "··|" + ls + + "12| Dd" + ls2 + ) ); } @@ -106,7 +106,7 @@ public void truncatesLongLines() { ColorFormatter colors = AnsiColorFormatter.NO_COLOR; CodeFormatter formatter = new CodeFormatter(ColorBuffer.of(colors, builder), 10); List lines = Collections.singletonList( - new SourceContextLoader.Line(1, "abcdefghijklmnopqrstuvwxyz") + new SourceContextLoader.Line(1, "abcdefghijklmnopqrstuvwxyz") ); formatter.writeCode(0, 0, lines); diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/ConfigurationUtilsTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/ConfigurationUtilsTest.java index 3578e0944e6..159f5f9d6db 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/ConfigurationUtilsTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/ConfigurationUtilsTest.java @@ -17,15 +17,15 @@ public class ConfigurationUtilsTest { private static final MavenRepository CENTRAL = MavenRepository.builder() - .url("https://repo.maven.apache.org/maven2") - .build(); + .url("https://repo.maven.apache.org/maven2") + .build(); private static final MavenRepository TEST_REPO_1 = MavenRepository.builder() - .url("fake_fake_fake") - .build(); + .url("fake_fake_fake") + .build(); private static final MavenRepository TEST_REPO_2 = MavenRepository.builder() - .url("not_real") - .build(); + .url("not_real") + .build(); @Test public void returnsDefaultRepository() { @@ -39,13 +39,13 @@ public void returnsDefaultRepository() { @Test public void returnsCorrectRepositoriesInConfig() { SmithyBuildConfig config = SmithyBuildConfig.builder() - .version("1.0") - .maven( - MavenConfig.builder() - .repositories(ListUtils.of(TEST_REPO_1, TEST_REPO_2)) - .build() - ) - .build(); + .version("1.0") + .maven( + MavenConfig.builder() + .repositories(ListUtils.of(TEST_REPO_1, TEST_REPO_2)) + .build() + ) + .build(); Set repositorySet = ConfigurationUtils.getConfiguredMavenRepos(config); assertEquals(repositorySet.size(), 2); diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/DiffCommandTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/DiffCommandTest.java index cd45cb2e6cc..8a8bab1d198 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/DiffCommandTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/DiffCommandTest.java @@ -20,13 +20,13 @@ public void canOutputCsv() throws Exception { Path oldModel = Paths.get(getClass().getResource("diff/old.smithy").toURI()); Path newModel = Paths.get(getClass().getResource("diff/new.smithy").toURI()); CliUtils.Result result = CliUtils.runSmithy( - "diff", - "--old", - oldModel.toString(), - "--new", - newModel.toString(), - "--format", - "csv" + "diff", + "--old", + oldModel.toString(), + "--new", + newModel.toString(), + "--format", + "csv" ); assertThat(result.code(), not(0)); diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/LockFileTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/LockFileTest.java index 4f113adc90f..8ce3b9009ea 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/LockFileTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/LockFileTest.java @@ -59,13 +59,13 @@ public void loadsFromNode() { public void validatesResolved() { LockFile lock = LockFile.fromNode(getNode()); List artifactList = ListUtils.of( - ResolvedArtifact.fromCoordinateNode( - "software.amazon.smithy:smithy-aws-traits:1.37.0", - Node.objectNodeBuilder() - .withMember("path", "/a") - .withMember("sha1", "sum") - .build() - ) + ResolvedArtifact.fromCoordinateNode( + "software.amazon.smithy:smithy-aws-traits:1.37.0", + Node.objectNodeBuilder() + .withMember("path", "/a") + .withMember("sha1", "sum") + .build() + ) ); lock.validateArtifacts(artifactList); } @@ -74,13 +74,13 @@ public void validatesResolved() { public void throwsErrorOnIncompatibleDependencies() { LockFile lock = LockFile.fromNode(getNode()); List artifactList = ListUtils.of( - ResolvedArtifact.fromCoordinateNode( - "software.amazon.smithy:smithy-aws-traits:1.37.0", - Node.objectNodeBuilder() - .withMember("path", "/a") - .withMember("sha1", "badSum") - .build() - ) + ResolvedArtifact.fromCoordinateNode( + "software.amazon.smithy:smithy-aws-traits:1.37.0", + Node.objectNodeBuilder() + .withMember("path", "/a") + .withMember("sha1", "badSum") + .build() + ) ); Assertions.assertThrows(CliError.class, () -> lock.validateArtifacts(artifactList)); } @@ -88,7 +88,7 @@ public void throwsErrorOnIncompatibleDependencies() { @Test public void loadsSmithyLockfile() throws URISyntaxException { File lockfileResource = new File( - Objects.requireNonNull(getClass().getResource("smithy-lock-test.json")).toURI() + Objects.requireNonNull(getClass().getResource("smithy-lock-test.json")).toURI() ); Optional lockFileOptional = LockFile.load(lockfileResource.toPath()); @@ -108,17 +108,17 @@ public void returnsEmptyWhenNoLockfile() { private Node getNode() { return Node.objectNodeBuilder() - .withMember("version", "1.0") - .withMember("configHash", -1856284556) - .withMember("repositories", ArrayNode.fromNodes(Node.from("repo"))) - .withMember( - "artifacts", - Node.objectNode() - .withMember( - "software.amazon.smithy:smithy-aws-traits:1.37.0", - Node.objectNode().withMember("sha1", "sum") - ) - ) - .build(); + .withMember("version", "1.0") + .withMember("configHash", -1856284556) + .withMember("repositories", ArrayNode.fromNodes(Node.from("repo"))) + .withMember( + "artifacts", + Node.objectNode() + .withMember( + "software.amazon.smithy:smithy-aws-traits:1.37.0", + Node.objectNode().withMember("sha1", "sum") + ) + ) + .build(); } } diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/MigrateCommandTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/MigrateCommandTest.java index d62c77c50ce..883c9fe61d3 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/MigrateCommandTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/MigrateCommandTest.java @@ -52,16 +52,16 @@ public void testUpgrade(Path initialPath, String name) { public static Stream source() throws Exception { Path start = Paths.get(MigrateCommandTest.class.getResource("upgrade/cases").toURI()); return Files.walk(start) - .filter(path -> path.getFileName().toString().endsWith(".v1.smithy")) - .map(path -> Arguments.of(path, path.getFileName().toString().replace(".v1.smithy", ""))); + .filter(path -> path.getFileName().toString().endsWith(".v1.smithy")) + .map(path -> Arguments.of(path, path.getFileName().toString().replace(".v1.smithy", ""))); } @Test public void testUpgradeDirectory() throws Exception { Path baseDir = Paths.get( - MigrateCommandTest.class.getResource( - "upgrade/directory-cases/all-local/v1" - ).toURI() + MigrateCommandTest.class.getResource( + "upgrade/directory-cases/all-local/v1" + ).toURI() ).toAbsolutePath(); Path tempDir = Files.createTempDirectory("testUpgradeDirectory"); @@ -77,9 +77,9 @@ public void testUpgradeDirectory() throws Exception { @Test public void testUpgradeDirectoryWithProjection() throws Exception { Path baseDir = Paths.get( - MigrateCommandTest.class.getResource( - "upgrade/directory-cases/ignores-projections/v1" - ).toURI() + MigrateCommandTest.class.getResource( + "upgrade/directory-cases/ignores-projections/v1" + ).toURI() ); Path tempDir = Files.createTempDirectory("testUpgradeDirectory"); @@ -94,9 +94,9 @@ public void testUpgradeDirectoryWithProjection() throws Exception { @Test public void testUpgradeDirectoryWithJar() throws Exception { Path baseDir = Paths.get( - MigrateCommandTest.class.getResource( - "upgrade/directory-cases/with-jar/v1" - ).toURI() + MigrateCommandTest.class.getResource( + "upgrade/directory-cases/with-jar/v1" + ).toURI() ); Path tempDir = Files.createTempDirectory("testUpgradeDirectory"); @@ -105,12 +105,12 @@ public void testUpgradeDirectoryWithJar() throws Exception { Path modelsDir = tempDir.resolve("model"); Path config = tempDir.resolve("smithy-build.json"); SmithyCli.create() - .run( - "upgrade-1-to-2", - "--config", - config.toString(), - modelsDir.toString() - ); + .run( + "upgrade-1-to-2", + "--config", + config.toString(), + modelsDir.toString() + ); assertDirEqual(baseDir.getParent().resolve("v2"), tempDir); } @@ -129,15 +129,15 @@ public void testUpgradeV2Noop(Path noopTestFilePath, String name) { public static Stream noopSource() throws Exception { Path start = Paths.get(MigrateCommandTest.class.getResource("upgrade/no-op").toURI()); return Files.walk(start) - .filter(path -> Files.isRegularFile(path)) - .map(path -> Arguments.of(path, path.getFileName().toString().replace(".v2.smithy", ""))); + .filter(path -> Files.isRegularFile(path)) + .map(path -> Arguments.of(path, path.getFileName().toString().replace(".v2.smithy", ""))); } private void assertDirEqual(Path actualDir, Path expectedDir) throws Exception { Set files = Files.walk(actualDir) - .filter(Files::isRegularFile) - .filter(path -> path.toString().endsWith(".smithy")) - .collect(Collectors.toSet()); + .filter(Files::isRegularFile) + .filter(path -> path.toString().endsWith(".smithy")) + .collect(Collectors.toSet()); for (Path actual : files) { Path expected = expectedDir.resolve(actualDir.relativize(actual)); assertThat(IoUtils.readUtf8File(actual), equalTo(IoUtils.readUtf8File(expected))); diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/PrettyAnsiValidationFormatterTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/PrettyAnsiValidationFormatterTest.java index 38e31388555..34148a12df5 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/PrettyAnsiValidationFormatterTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/PrettyAnsiValidationFormatterTest.java @@ -27,19 +27,19 @@ public void formatsEventsWithNoColors() { String formatted = formatTestEventWithSeverity(pretty, Severity.ERROR); assertThat( - formatted, - equalTo( - "\n" - + "── ERROR ───────────────────────────────────────────────────────────────── Foo\n" - + "Shape: smithy.example#Foo\n" - + "File: build/resources/test/software/amazon/smithy/cli/commands/valid-model.smithy:5:1\n" - + "\n" - + "4| \n" - + "5| resource Foo {\n" - + " | ^\n" - + "\n" - + "Hello, `there`\n" - ) + formatted, + equalTo( + "\n" + + "── ERROR ───────────────────────────────────────────────────────────────── Foo\n" + + "Shape: smithy.example#Foo\n" + + "File: build/resources/test/software/amazon/smithy/cli/commands/valid-model.smithy:5:1\n" + + "\n" + + "4| \n" + + "5| resource Foo {\n" + + " | ^\n" + + "\n" + + "Hello, `there`\n" + ) ); // keeps ticks because formatting is disabled. } @@ -49,20 +49,20 @@ public void formatsEventsWithHintWithNoColors() { String formatted = formatTestEventWithSeverity(pretty, Severity.ERROR, "Some hint"); assertThat( - formatted, - equalTo( - "\n" - + "── ERROR ───────────────────────────────────────────────────────────────── Foo\n" - + "Shape: smithy.example#Foo\n" - + "File: build/resources/test/software/amazon/smithy/cli/commands/valid-model.smithy:5:1\n" - + "\n" - + "4| \n" - + "5| resource Foo {\n" - + " | ^\n" - + "\n" - + "Hello, `there`\n\n" - + "HINT: Some hint\n" - ) + formatted, + equalTo( + "\n" + + "── ERROR ───────────────────────────────────────────────────────────────── Foo\n" + + "Shape: smithy.example#Foo\n" + + "File: build/resources/test/software/amazon/smithy/cli/commands/valid-model.smithy:5:1\n" + + "\n" + + "4| \n" + + "5| resource Foo {\n" + + " | ^\n" + + "\n" + + "Hello, `there`\n\n" + + "HINT: Some hint\n" + ) ); // keeps ticks because formatting is disabled. } @@ -72,19 +72,19 @@ public void formatsEventsWithColors() { String formatted = formatTestEventWithSeverity(pretty, Severity.ERROR); assertThat( - formatted, - equalTo( - "\n" - + "\u001B[31m── \u001B[0m\u001B[41;30m ERROR \u001B[0m\u001B[31m ───────────────────────────────────────────────────────────────── \u001B[0mFoo\n" - + "\u001B[90mShape: \u001B[0m\u001B[95msmithy.example#Foo\u001B[0m\n" - + "\u001B[90mFile: \u001B[0m\u001B[90mbuild/resources/test/software/amazon/smithy/cli/commands/valid-model.smithy:5:1\u001B[0m\n" - + "\n" - + "\u001B[90m4| \u001B[0m\n" - + "\u001B[90m5| \u001B[0mresource Foo {\n" - + "\u001B[90m |\u001B[0m \u001B[31m^\u001B[0m\n" - + "\n" - + "Hello, \u001B[36mthere\u001B[0m\n" - ) + formatted, + equalTo( + "\n" + + "\u001B[31m── \u001B[0m\u001B[41;30m ERROR \u001B[0m\u001B[31m ───────────────────────────────────────────────────────────────── \u001B[0mFoo\n" + + "\u001B[90mShape: \u001B[0m\u001B[95msmithy.example#Foo\u001B[0m\n" + + "\u001B[90mFile: \u001B[0m\u001B[90mbuild/resources/test/software/amazon/smithy/cli/commands/valid-model.smithy:5:1\u001B[0m\n" + + "\n" + + "\u001B[90m4| \u001B[0m\n" + + "\u001B[90m5| \u001B[0mresource Foo {\n" + + "\u001B[90m |\u001B[0m \u001B[31m^\u001B[0m\n" + + "\n" + + "Hello, \u001B[36mthere\u001B[0m\n" + ) ); } @@ -94,20 +94,20 @@ public void formatsEventsWithHintWithColors() { String formatted = formatTestEventWithSeverity(pretty, Severity.ERROR, "Some hint"); assertThat( - formatted, - equalTo( - "\n" - + "\u001B[31m── \u001B[0m\u001B[41;30m ERROR \u001B[0m\u001B[31m ───────────────────────────────────────────────────────────────── \u001B[0mFoo\n" - + "\u001B[90mShape: \u001B[0m\u001B[95msmithy.example#Foo\u001B[0m\n" - + "\u001B[90mFile: \u001B[0m\u001B[90mbuild/resources/test/software/amazon/smithy/cli/commands/valid-model.smithy:5:1\u001B[0m\n" - + "\n" - + "\u001B[90m4| \u001B[0m\n" - + "\u001B[90m5| \u001B[0mresource Foo {\n" - + "\u001B[90m |\u001B[0m \u001B[31m^\u001B[0m\n" - + "\n" - + "Hello, \u001B[36mthere\u001B[0m\n\n" - + "\u001B[92mHINT: \u001B[0mSome hint\n" - ) + formatted, + equalTo( + "\n" + + "\u001B[31m── \u001B[0m\u001B[41;30m ERROR \u001B[0m\u001B[31m ───────────────────────────────────────────────────────────────── \u001B[0mFoo\n" + + "\u001B[90mShape: \u001B[0m\u001B[95msmithy.example#Foo\u001B[0m\n" + + "\u001B[90mFile: \u001B[0m\u001B[90mbuild/resources/test/software/amazon/smithy/cli/commands/valid-model.smithy:5:1\u001B[0m\n" + + "\n" + + "\u001B[90m4| \u001B[0m\n" + + "\u001B[90m5| \u001B[0mresource Foo {\n" + + "\u001B[90m |\u001B[0m \u001B[31m^\u001B[0m\n" + + "\n" + + "Hello, \u001B[36mthere\u001B[0m\n\n" + + "\u001B[92mHINT: \u001B[0mSome hint\n" + ) ); } @@ -115,23 +115,23 @@ public void formatsEventsWithHintWithColors() { public void doesNotIncludeSourceLocationNoneInOutput() { PrettyAnsiValidationFormatter pretty = createFormatter(AnsiColorFormatter.NO_COLOR); ValidationEvent event = ValidationEvent.builder() - .id("Hello") - .severity(Severity.WARNING) - .shapeId(ShapeId.from("smithy.example#Foo")) - .message("Hi") - .build(); + .id("Hello") + .severity(Severity.WARNING) + .shapeId(ShapeId.from("smithy.example#Foo")) + .message("Hi") + .build(); String formatted = normalizeLinesAndFiles(pretty.format(event)); assertThat( - formatted, - equalTo( - "\n" - + "── WARNING ───────────────────────────────────────────────────────────── Hello\n" - + "Shape: smithy.example#Foo\n" - + "\n" - + "Hi\n" - ) + formatted, + equalTo( + "\n" + + "── WARNING ───────────────────────────────────────────────────────────── Hello\n" + + "Shape: smithy.example#Foo\n" + + "\n" + + "Hi\n" + ) ); } @@ -139,27 +139,27 @@ public void doesNotIncludeSourceLocationNoneInOutput() { public void wrapsLongLines() { PrettyAnsiValidationFormatter pretty = createFormatter(AnsiColorFormatter.NO_COLOR); ValidationEvent event = ValidationEvent.builder() - .id("Hello") - .severity(Severity.WARNING) - .shapeId(ShapeId.from("smithy.example#Foo")) - .message( - "abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 " - + "abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890" - ) - .build(); + .id("Hello") + .severity(Severity.WARNING) + .shapeId(ShapeId.from("smithy.example#Foo")) + .message( + "abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890 " + + "abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890" + ) + .build(); String formatted = normalizeLinesAndFiles(pretty.format(event)); assertThat( - formatted, - equalTo( - "\n" - + "── WARNING ───────────────────────────────────────────────────────────── Hello\n" - + "Shape: smithy.example#Foo\n" - + "\n" - + "abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890\n" - + "abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890\n" - ) + formatted, + equalTo( + "\n" + + "── WARNING ───────────────────────────────────────────────────────────── Hello\n" + + "Shape: smithy.example#Foo\n" + + "\n" + + "abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890\n" + + "abcdefghijklmnopqrstuvwxyz 1234567890 abcdefghijklmnopqrstuvwxyz 1234567890\n" + ) ); } @@ -175,12 +175,12 @@ private String formatTestEventWithSeverity(PrettyAnsiValidationFormatter pretty, private String formatTestEventWithSeverity(PrettyAnsiValidationFormatter pretty, Severity severity, String hint) { Model model = Model.assembler().addImport(getClass().getResource("valid-model.smithy")).assemble().unwrap(); ValidationEvent event = ValidationEvent.builder() - .id("Foo") - .severity(severity) - .shape(model.expectShape(ShapeId.from("smithy.example#Foo"))) - .message("Hello, `there`") - .hint(hint) - .build(); + .id("Foo") + .severity(severity) + .shape(model.expectShape(ShapeId.from("smithy.example#Foo"))) + .message("Hello, `there`") + .hint(hint) + .build(); return normalizeLinesAndFiles(pretty.format(event)); } @@ -195,58 +195,58 @@ public void toleratesInvalidSourceFiles() { throw new UncheckedIOException(new IOException("Error!!!")); }; PrettyAnsiValidationFormatter pretty = PrettyAnsiValidationFormatter.builder() - .sourceContextLoader(loader) - .colors(colors) - .build(); + .sourceContextLoader(loader) + .colors(colors) + .build(); ValidationEvent event = ValidationEvent.builder() - .id("Foo") - .severity(Severity.NOTE) - .sourceLocation(new SourceLocation("/foo", 1, 1)) - .message("Hello") - .build(); + .id("Foo") + .severity(Severity.NOTE) + .sourceLocation(new SourceLocation("/foo", 1, 1)) + .message("Hello") + .build(); String result = normalizeLinesAndFiles(pretty.format(event)); assertThat( - result, - equalTo( - "\n" - + "── NOTE ────────────────────────────────────────────────────────────────── Foo\n" - + "File: /foo:1:1\n" - + "\n" - + "Invalid source file: Error!!!\n" - + "\n" - + "Hello\n" - ) + result, + equalTo( + "\n" + + "── NOTE ────────────────────────────────────────────────────────────────── Foo\n" + + "File: /foo:1:1\n" + + "\n" + + "Invalid source file: Error!!!\n" + + "\n" + + "Hello\n" + ) ); } @Test public void showsTitleLabelsWhenPresent() { PrettyAnsiValidationFormatter pretty = PrettyAnsiValidationFormatter.builder() - .sourceContextLoader(SourceContextLoader.createLineBasedLoader(4)) - .colors(AnsiColorFormatter.FORCE_COLOR) - .titleLabel("FOO", Style.BG_BLUE, Style.BLACK) - .build(); + .sourceContextLoader(SourceContextLoader.createLineBasedLoader(4)) + .colors(AnsiColorFormatter.FORCE_COLOR) + .titleLabel("FOO", Style.BG_BLUE, Style.BLACK) + .build(); ValidationEvent event = ValidationEvent.builder() - .id("Hello") - .severity(Severity.WARNING) - .shapeId(ShapeId.from("smithy.example#Foo")) - .message("hello") - .build(); + .id("Hello") + .severity(Severity.WARNING) + .shapeId(ShapeId.from("smithy.example#Foo")) + .message("hello") + .build(); String formatted = normalizeLinesAndFiles(pretty.format(event)); assertThat( - formatted, - equalTo( - "\n" - + "\u001B[33m── \u001B[0m\u001B[44;30m FOO \u001B[0m\u001B[43;30m " - + "WARNING \u001B[0m\u001B[33m ──────────────────────────────────────────────────────── \u001B[0mHello\n" - + "\u001B[90mShape: \u001B[0m\u001B[95msmithy.example#Foo\u001B[0m\n" - + "\n" - + "hello\n" - ) + formatted, + equalTo( + "\n" + + "\u001B[33m── \u001B[0m\u001B[44;30m FOO \u001B[0m\u001B[43;30m " + + "WARNING \u001B[0m\u001B[33m ──────────────────────────────────────────────────────── \u001B[0mHello\n" + + "\u001B[90mShape: \u001B[0m\u001B[95msmithy.example#Foo\u001B[0m\n" + + "\n" + + "hello\n" + ) ); } } diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/SelectCommandTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/SelectCommandTest.java index de9f5cae2a1..1b0f575beda 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/SelectCommandTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/SelectCommandTest.java @@ -61,12 +61,12 @@ public void printsSuccessfulMatchesToStdout() throws Exception { public void printsJsonVarsToStdout() throws Exception { String model = Paths.get(getClass().getResource("valid-model.smithy").toURI()).toString(); CliUtils.Result result = CliUtils.runSmithy( - "select", - "--selector", - "string $referenceMe(<)", - "--show", - "vars", - model + "select", + "--selector", + "string $referenceMe(<)", + "--show", + "vars", + model ); assertThat(result.code(), equalTo(0)); diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/ValidateCommandTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/ValidateCommandTest.java index e02a6b106ef..54598663817 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/ValidateCommandTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/commands/ValidateCommandTest.java @@ -130,11 +130,11 @@ public void canSetSeverityToError() throws Exception { private CliUtils.Result runValidationEventsTest(Severity severity) throws Exception { Path validationEventsModel = Paths.get(getClass().getResource("validation-events.smithy").toURI()); return CliUtils.runSmithy( - "validate", - "--debug", - "--severity", - severity.toString(), - validationEventsModel.toString() + "validate", + "--debug", + "--severity", + severity.toString(), + validationEventsModel.toString() ); } @@ -190,11 +190,11 @@ public void validatesEventIdsAreNotLeadingEmpty() { public void canShowEventsById() throws Exception { Path validationEventsModel = Paths.get(getClass().getResource("validation-events.smithy").toURI()); CliUtils.Result result = CliUtils.runSmithy( - "validate", - "--debug", - "--show-validators", - "EmitWarnings", - validationEventsModel.toString() + "validate", + "--debug", + "--show-validators", + "EmitWarnings", + validationEventsModel.toString() ); assertThat(result.code(), not(0)); @@ -207,11 +207,11 @@ public void canShowEventsById() throws Exception { public void canHideEventsById() throws Exception { Path validationEventsModel = Paths.get(getClass().getResource("validation-events.smithy").toURI()); CliUtils.Result result = CliUtils.runSmithy( - "validate", - "--debug", - "--hide-validators", - "EmitDangers", - validationEventsModel.toString() + "validate", + "--debug", + "--hide-validators", + "EmitDangers", + validationEventsModel.toString() ); assertThat(result.code(), not(0)); @@ -224,10 +224,10 @@ public void canHideEventsById() throws Exception { public void canOutputCsv() throws Exception { Path validationEventsModel = Paths.get(getClass().getResource("validation-events.smithy").toURI()); CliUtils.Result result = CliUtils.runSmithy( - "validate", - "--format", - "csv", - validationEventsModel.toString() + "validate", + "--format", + "csv", + validationEventsModel.toString() ); assertThat(result.code(), not(0)); @@ -245,10 +245,10 @@ public void canOutputCsv() throws Exception { public void canOutputText() throws Exception { Path validationEventsModel = Paths.get(getClass().getResource("validation-events.smithy").toURI()); CliUtils.Result result = CliUtils.runSmithy( - "validate", - "--format", - "text", - validationEventsModel.toString() + "validate", + "--format", + "text", + validationEventsModel.toString() ); assertThat(result.code(), not(0)); diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/DependencyUtilsTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/DependencyUtilsTest.java index 64e00f22ee4..1aa9b8f0ae1 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/DependencyUtilsTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/DependencyUtilsTest.java @@ -17,11 +17,11 @@ public void computesCorrectShaHash() throws URISyntaxException { // Expected sha was computed using the `sha1sum` command line utility String expectedSha = "543d822a441db77f32309650a1b3c1510c9be392"; String shaHash = DependencyUtils.computeSha1( - Paths.get( - Objects.requireNonNull( - getClass().getResource("sha-test.txt") - ).toURI() - ) + Paths.get( + Objects.requireNonNull( + getClass().getResource("sha-test.txt") + ).toURI() + ) ); assertEquals(shaHash, expectedSha); } diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/FileCacheResolverTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/FileCacheResolverTest.java index 07ae332af38..d0f8cdb755a 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/FileCacheResolverTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/FileCacheResolverTest.java @@ -45,7 +45,7 @@ public void ignoresAndDeletesEmptyCacheFiles() throws IOException { File jar = File.createTempFile("foo", ".json"); List result = ListUtils.of( - ResolvedArtifact.fromCoordinates(jar.toPath(), "com.foo:bar:1.0.0") + ResolvedArtifact.fromCoordinates(jar.toPath(), "com.foo:bar:1.0.0") ); Mock mock = new Mock(result); DependencyResolver resolver = new FileCacheResolver(cache, System.currentTimeMillis(), mock); @@ -116,9 +116,9 @@ public void invalidatesCacheWhenConfigIsNewerThanCache() throws IOException { Mock mock = new Mock(result); // Set the "config" last modified to a future date to ensure it's newer than the "JAR" file. DependencyResolver cachingResolver = new FileCacheResolver( - cache, - jar.lastModified() + Duration.parse("P1D").toMillis(), - mock + cache, + jar.lastModified() + Duration.parse("P1D").toMillis(), + mock ); List resolved = cachingResolver.resolve(); diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/FilterCliVersionResolverTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/FilterCliVersionResolverTest.java index d4decada6e6..0879821027b 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/FilterCliVersionResolverTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/FilterCliVersionResolverTest.java @@ -56,29 +56,32 @@ public void addDependency(String coordinates) { @Override public List resolve() { return Arrays.asList( - ResolvedArtifact.fromCoordinateNode( - "software.amazon.smithy:smithy-model:1.25.0", - getNodeForPath("/a") - ), - ResolvedArtifact.fromCoordinateNode( - "software.amazon.smithy:smithy-utils:1.25.0", - getNodeForPath("/b") - ), - ResolvedArtifact.fromCoordinateNode( - "software.amazon.smithy:smithy-other:1.25.0", - getNodeForPath("/c") - ), - ResolvedArtifact.fromCoordinateNode("software.amazon.foo:foo-other:1.0.0", getNodeForPath("/d")) + ResolvedArtifact.fromCoordinateNode( + "software.amazon.smithy:smithy-model:1.25.0", + getNodeForPath("/a") + ), + ResolvedArtifact.fromCoordinateNode( + "software.amazon.smithy:smithy-utils:1.25.0", + getNodeForPath("/b") + ), + ResolvedArtifact.fromCoordinateNode( + "software.amazon.smithy:smithy-other:1.25.0", + getNodeForPath("/c") + ), + ResolvedArtifact.fromCoordinateNode("software.amazon.foo:foo-other:1.0.0", getNodeForPath("/d")) ); } }); assertThat( - filter.resolve(), - contains( - ResolvedArtifact.fromCoordinateNode("software.amazon.smithy:smithy-other:1.25.0", getNodeForPath("/c")), - ResolvedArtifact.fromCoordinateNode("software.amazon.foo:foo-other:1.0.0", getNodeForPath("/d")) - ) + filter.resolve(), + contains( + ResolvedArtifact.fromCoordinateNode( + "software.amazon.smithy:smithy-other:1.25.0", + getNodeForPath("/c") + ), + ResolvedArtifact.fromCoordinateNode("software.amazon.foo:foo-other:1.0.0", getNodeForPath("/d")) + ) ); } @@ -98,10 +101,10 @@ public void addDependency(String coordinates) { @Override public List resolve() { return ListUtils.of( - ResolvedArtifact.fromCoordinateNode( - "software.amazon.smithy:smithy-model:1.27.0", - getNodeForPath("/a") - ) + ResolvedArtifact.fromCoordinateNode( + "software.amazon.smithy:smithy-model:1.27.0", + getNodeForPath("/a") + ) ); } }); @@ -111,8 +114,8 @@ public List resolve() { private static Node getNodeForPath(String pathStr) { return Node.objectNodeBuilder() - .withMember("path", pathStr) - .withMember("sha1", "sum") - .build(); + .withMember("path", pathStr) + .withMember("sha1", "sum") + .build(); } } diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/MavenDependencyResolverTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/MavenDependencyResolverTest.java index d12333e2454..f2518cfe7fb 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/MavenDependencyResolverTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/MavenDependencyResolverTest.java @@ -19,10 +19,10 @@ public void allowsValidDependenciesAndRepos() { DependencyResolver resolver = new MavenDependencyResolver(); resolver.addRepository(MavenRepository.builder().url("https://example.com").build()); resolver.addRepository( - MavenRepository.builder() - .url("https://mvn.example.com") - .httpCredentials("user:pass") - .build() + MavenRepository.builder() + .url("https://mvn.example.com") + .httpCredentials("user:pass") + .build() ); resolver.addDependency("com.foo:baz1:1.0.0"); resolver.addDependency("com.foo:baz2:[1.0.0]"); @@ -42,15 +42,15 @@ public void validatesDependencies(String value) { public static Stream invalidDependencies() { return Stream.of( - Arguments.of("X"), - Arguments.of("smithy.foo:bar:RELEASE"), - Arguments.of("smithy.foo:bar:latest-status"), - Arguments.of("smithy.foo:bar:LATEST"), - Arguments.of("smithy.foo:bar:1.25.0+"), - Arguments.of("a::1.2.0"), - Arguments.of(":b:1.2.0"), - Arguments.of("a:b:"), - Arguments.of("a:b: ") + Arguments.of("X"), + Arguments.of("smithy.foo:bar:RELEASE"), + Arguments.of("smithy.foo:bar:latest-status"), + Arguments.of("smithy.foo:bar:LATEST"), + Arguments.of("smithy.foo:bar:1.25.0+"), + Arguments.of("a::1.2.0"), + Arguments.of(":b:1.2.0"), + Arguments.of("a:b:"), + Arguments.of("a:b: ") ); } @@ -60,9 +60,9 @@ public void repositoryNeedsValidUrl() { Assertions.assertThrows(DependencyResolverException.class, () -> { resolver.addRepository( - MavenRepository.builder() - .url("!nope://") - .build() + MavenRepository.builder() + .url("!nope://") + .build() ); }); } diff --git a/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/ResolvedArtifactTest.java b/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/ResolvedArtifactTest.java index b5999785185..73de631e94b 100644 --- a/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/ResolvedArtifactTest.java +++ b/smithy-cli/src/test/java/software/amazon/smithy/cli/dependencies/ResolvedArtifactTest.java @@ -48,8 +48,8 @@ public void validatesCoordinatesNotTooManyParts() { String coordinates = "com.foo:baz-bam:1.2.0:boo"; Assertions.assertThrows( - DependencyResolverException.class, - () -> ResolvedArtifact.fromCoordinateNode(coordinates, getNode()) + DependencyResolverException.class, + () -> ResolvedArtifact.fromCoordinateNode(coordinates, getNode()) ); } @@ -58,8 +58,8 @@ public void validatesCoordinatesEnoughParts() { String coordinates = "com.foo:baz-bam"; Assertions.assertThrows( - DependencyResolverException.class, - () -> ResolvedArtifact.fromCoordinateNode(coordinates, getNode()) + DependencyResolverException.class, + () -> ResolvedArtifact.fromCoordinateNode(coordinates, getNode()) ); } @@ -67,8 +67,8 @@ public void validatesCoordinatesEnoughParts() { public void createsArtifactFromNode() { Path path = Paths.get("/a"); ResolvedArtifact artifact = ResolvedArtifact.fromCoordinateNode( - "com.foo:baz-bam:1.2.0", - getNode() + "com.foo:baz-bam:1.2.0", + getNode() ); assertThat(artifact.getPath(), equalTo(path)); @@ -81,8 +81,8 @@ public void createsArtifactFromNode() { public Node getNode() { return Node.objectNodeBuilder() - .withMember("path", "/a") - .withMember("sha1", "sum") - .build(); + .withMember("path", "/a") + .withMember("sha1", "sum") + .build(); } } diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/DependencyTracker.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/DependencyTracker.java index c0dc2808aa0..e5be189769b 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/DependencyTracker.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/DependencyTracker.java @@ -89,10 +89,10 @@ public final class DependencyTracker implements SymbolDependencyContainer { private static final String PROPERTIES = "properties"; private static final Set TOP_LEVEL_PROPERTIES = SetUtils.of(VERSION, DEPENDENCIES); private static final Set ALLOWED_SYMBOL_PROPERTIES = SetUtils.of( - PACKAGE_NAME, - DEPENDENCY_TYPE, - VERSION, - PROPERTIES + PACKAGE_NAME, + DEPENDENCY_TYPE, + VERSION, + PROPERTIES ); private final List dependencies = new ArrayList<>(); @@ -133,8 +133,8 @@ public SymbolDependency getByName(String name, String dependencyType) { } } throw new IllegalArgumentException( - "Unknown dependency '" + name + "' of type '" + dependencyType + "'. " - + "Known dependencies: " + dependencies + "Unknown dependency '" + name + "' of type '" + dependencyType + "'. " + + "Known dependencies: " + dependencies ); } @@ -210,10 +210,10 @@ public void addDependency(SymbolDependency dependency) { */ public void addDependency(String packageName, String version, String dependencyType) { SymbolDependency dependency = SymbolDependency.builder() - .packageName(packageName) - .version(version) - .dependencyType(dependencyType) - .build(); + .packageName(packageName) + .version(version) + .dependencyType(dependencyType) + .build(); addDependency(dependency); } @@ -247,9 +247,9 @@ public void addDependenciesFromJson(URL jsonFile) { parseDependenciesFromJson(Node.parse(stream)); } catch (IOException e) { throw new UncheckedIOException( - "Error loading dependencies from " - + jsonFile + ": " + e.getMessage(), - e + "Error loading dependencies from " + + jsonFile + ": " + e.getMessage(), + e ); } } diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/IntegrationTopologicalSort.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/IntegrationTopologicalSort.java index 2b6a9b6836e..bd78d944159 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/IntegrationTopologicalSort.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/IntegrationTopologicalSort.java @@ -33,8 +33,8 @@ final class IntegrationTopologicalSort> { // If priority is a tie, then sort based on insertion order of integrations. // This makes the order deterministic. return byteResult == 0 - ? Integer.compare(insertionOrder.get(left), insertionOrder.get(right)) - : byteResult; + ? Integer.compare(insertionOrder.get(left), insertionOrder.get(right)) + : byteResult; }); IntegrationTopologicalSort(Iterable integrations) { @@ -66,12 +66,12 @@ private void addIntegration(I integration) { insertionOrder.put(integration.name(), insertionOrder.size()); if (previous != null) { throw new IllegalArgumentException( - String.format( - "Conflicting SmithyIntegration names detected for '%s': %s and %s", - integration.name(), - integration.getClass().getCanonicalName(), - previous.getClass().getCanonicalName() - ) + String.format( + "Conflicting SmithyIntegration names detected for '%s': %s and %s", + integration.name(), + integration.getClass().getCanonicalName(), + previous.getClass().getCanonicalName() + ) ); } } @@ -86,8 +86,8 @@ private List getValidatedDependencies(String descriptor, String what, Li return false; } else { LOGGER.warning( - what + " is supposed to run " + descriptor + " an integration that could " - + "not be found, '" + value + "'" + what + " is supposed to run " + descriptor + " an integration that could " + + "not be found, '" + value + "'" ); return true; } @@ -120,8 +120,8 @@ List sort() { if (!forwardDependencies.isEmpty()) { throw new IllegalArgumentException( - "SmithyIntegration cycles detected among " - + forwardDependencies.keySet() + "SmithyIntegration cycles detected among " + + forwardDependencies.keySet() ); } diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/ReservedWordSymbolProvider.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/ReservedWordSymbolProvider.java index 523bfd73c44..47b13cc639b 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/ReservedWordSymbolProvider.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/ReservedWordSymbolProvider.java @@ -96,8 +96,8 @@ public static final class Builder { */ public SymbolProvider build() { return new ReservedWordSymbolProvider( - SmithyBuilder.requiredState("delegate", delegate), - buildEscaper() + SmithyBuilder.requiredState("delegate", delegate), + buildEscaper() ); } @@ -245,18 +245,18 @@ public Symbol escapeSymbol(Shape shape, Symbol symbol) { // Only create a new symbol when needed. if (newName.equals(symbol.getName()) - && newNamespace.equals(symbol.getNamespace()) - && newDeclarationFile.equals(symbol.getDeclarationFile()) - && newDefinitionFile.equals(symbol.getDeclarationFile())) { + && newNamespace.equals(symbol.getNamespace()) + && newDeclarationFile.equals(symbol.getDeclarationFile()) + && newDefinitionFile.equals(symbol.getDeclarationFile())) { return symbol; } return symbol.toBuilder() - .name(newName) - .namespace(newNamespace, symbol.getNamespaceDelimiter()) - .declarationFile(newDeclarationFile) - .definitionFile(newDefinitionFile) - .build(); + .name(newName) + .namespace(newNamespace, symbol.getNamespaceDelimiter()) + .declarationFile(newDeclarationFile) + .definitionFile(newDefinitionFile) + .build(); } /** @@ -276,12 +276,12 @@ private static String convertWord(String name, String result, ReservedWords rese String newResult = reservedWords.escape(result); LOGGER.warning( - () -> String.format( - "Reserved word: %s is a reserved word for a %s. Converting to %s", - result, - name, - newResult - ) + () -> String.format( + "Reserved word: %s is a reserved word for a %s. Converting to %s", + result, + name, + newResult + ) ); return newResult; } diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/ReservedWordsBuilder.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/ReservedWordsBuilder.java index d8c210be4c3..57f837c3f1e 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/ReservedWordsBuilder.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/ReservedWordsBuilder.java @@ -124,15 +124,15 @@ private static String escapeWithUnderscore(String word) { private static Set readNonBlankNonCommentLines(URL url) { try ( - InputStream is = url.openConnection().getInputStream(); BufferedReader reader = new BufferedReader( - new InputStreamReader(is, StandardCharsets.UTF_8) - ) + InputStream is = url.openConnection().getInputStream(); BufferedReader reader = new BufferedReader( + new InputStreamReader(is, StandardCharsets.UTF_8) + ) ) { return reader.lines() - .filter(StringUtils::isNotBlank) - .filter(line -> !line.startsWith("#")) - .map(word -> StringUtils.stripEnd(word, null)) - .collect(Collectors.toSet()); + .filter(StringUtils::isNotBlank) + .filter(line -> !line.startsWith("#")) + .map(word -> StringUtils.stripEnd(word, null)) + .collect(Collectors.toSet()); } catch (IOException e) { throw new UncheckedIOException("Error loading reserved words from " + url + ": " + e.getMessage(), e); } diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/Symbol.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/Symbol.java index 48097d2bcbf..b5204b0b6ac 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/Symbol.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/Symbol.java @@ -48,7 +48,7 @@ * */ public final class Symbol extends TypedPropertiesBag - implements SymbolContainer, SymbolDependencyContainer, ToSmithyBuilder { + implements SymbolContainer, SymbolDependencyContainer, ToSmithyBuilder { private final String namespace; private final String namespaceDelimiter; private final String name; @@ -177,10 +177,10 @@ public String relativize(String namespace) { */ public SymbolReference toReference(String alias, SymbolReference.Option... options) { return SymbolReference.builder() - .alias(alias) - .symbol(this) - .options(options) - .build(); + .alias(alias) + .symbol(this) + .options(options) + .build(); } /** @@ -231,8 +231,8 @@ public Symbol toReferencedSymbol(String alias) { */ public Symbol.Builder toReferencedSymbolBuilder(String alias) { return builder() - .name(alias) - .addReference(toReference(alias, SymbolReference.ContextOption.USE)); + .name(alias) + .addReference(toReference(alias, SymbolReference.ContextOption.USE)); } /** @@ -258,13 +258,13 @@ public List getSymbols() { public Builder toBuilder() { Builder builder = new Builder(); return builder.namespace(namespace, namespaceDelimiter) - .name(name) - .properties(getProperties()) - .typedProperties(getTypedProperties()) - .definitionFile(definitionFile) - .declarationFile(declarationFile) - .references(references) - .dependencies(dependencies); + .name(name) + .properties(getProperties()) + .typedProperties(getTypedProperties()) + .definitionFile(definitionFile) + .declarationFile(declarationFile) + .references(references) + .dependencies(dependencies); } @Override @@ -281,14 +281,14 @@ public boolean equals(Object o) { } Symbol symbol = (Symbol) o; return super.equals(o) - && Objects.equals(namespace, symbol.namespace) - && Objects.equals(namespaceDelimiter, symbol.namespaceDelimiter) - && Objects.equals(name, symbol.name) - && getProperties().equals(symbol.getProperties()) - && Objects.equals(declarationFile, symbol.declarationFile) - && Objects.equals(definitionFile, symbol.definitionFile) - && references.equals(symbol.references) - && dependencies.equals(symbol.dependencies); + && Objects.equals(namespace, symbol.namespace) + && Objects.equals(namespaceDelimiter, symbol.namespaceDelimiter) + && Objects.equals(name, symbol.name) + && getProperties().equals(symbol.getProperties()) + && Objects.equals(declarationFile, symbol.declarationFile) + && Objects.equals(definitionFile, symbol.definitionFile) + && references.equals(symbol.references) + && dependencies.equals(symbol.dependencies); } @Override @@ -300,8 +300,8 @@ public int hashCode() { * Builds a Symbol. */ public static final class Builder - extends TypedPropertiesBag.Builder - implements SmithyBuilder { + extends TypedPropertiesBag.Builder + implements SmithyBuilder { private String name; private String namespace = ""; @@ -460,11 +460,11 @@ public Builder addDependency(String packageName, String version) { */ public Builder addDependency(String dependencyType, String packageName, String version) { return addDependency( - SymbolDependency.builder() - .dependencyType(dependencyType) - .packageName(packageName) - .version(version) - .build() + SymbolDependency.builder() + .dependencyType(dependencyType) + .packageName(packageName) + .version(version) + .build() ); } } diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/SymbolDependency.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/SymbolDependency.java index 41279c3660b..fabc79d299d 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/SymbolDependency.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/SymbolDependency.java @@ -57,7 +57,7 @@ * suggestion. */ public final class SymbolDependency extends TypedPropertiesBag - implements SymbolDependencyContainer, ToSmithyBuilder, Comparable { + implements SymbolDependencyContainer, ToSmithyBuilder, Comparable { private final String dependencyType; private final String packageName; @@ -93,17 +93,17 @@ public static Builder builder() { * @throws CodegenException when two package versions conflict. */ public static Map> gatherDependencies( - Stream symbolStream + Stream symbolStream ) { return gatherDependencies(symbolStream, (a, b) -> { throw new CodegenException( - String.format( - "Found a conflicting `%s` dependency for `%s`: `%s` conflicts with `%s`", - a.getDependencyType(), - a.getPackageName(), - a.getVersion(), - b.getVersion() - ) + String.format( + "Found a conflicting `%s` dependency for `%s`: `%s` conflicts with `%s`", + a.getDependencyType(), + a.getPackageName(), + a.getVersion(), + b.getVersion() + ) ); }); } @@ -132,22 +132,22 @@ public static Map> gatherDependencies( * @return Returns a map of dependency types to a map of package to version. */ public static Map> gatherDependencies( - Stream symbolStream, - BinaryOperator versionMergeFunction + Stream symbolStream, + BinaryOperator versionMergeFunction ) { return symbolStream - .sorted() - .collect( - Collectors.groupingBy( - SymbolDependency::getDependencyType, - Collectors.toMap( - SymbolDependency::getPackageName, - Function.identity(), - guardedMerge(versionMergeFunction), - TreeMap::new - ) - ) - ); + .sorted() + .collect( + Collectors.groupingBy( + SymbolDependency::getDependencyType, + Collectors.toMap( + SymbolDependency::getPackageName, + Function.identity(), + guardedMerge(versionMergeFunction), + TreeMap::new + ) + ) + ); } private static BinaryOperator guardedMerge(BinaryOperator original) { @@ -197,20 +197,20 @@ public List getDependencies() { @Override public Builder toBuilder() { return builder() - .dependencyType(dependencyType) - .packageName(packageName) - .version(version) - .properties(getProperties()) - .typedProperties(getTypedProperties()); + .dependencyType(dependencyType) + .packageName(packageName) + .version(version) + .properties(getProperties()) + .typedProperties(getTypedProperties()); } @Override public String toString() { return "SymbolDependency{" - + "dependencyType='" + dependencyType + '\'' - + ", packageName='" + packageName + '\'' - + ", version='" + version + '\'' - + '}'; + + "dependencyType='" + dependencyType + '\'' + + ", packageName='" + packageName + '\'' + + ", version='" + version + '\'' + + '}'; } @Override @@ -223,9 +223,9 @@ public boolean equals(Object o) { SymbolDependency that = (SymbolDependency) o; return super.equals(o) - && dependencyType.equals(that.dependencyType) - && packageName.equals(that.packageName) - && version.equals(that.version); + && dependencyType.equals(that.dependencyType) + && packageName.equals(that.packageName) + && version.equals(that.version); } @Override @@ -258,8 +258,8 @@ public int compareTo(SymbolDependency other) { * Builds a SymbolDependency. */ public static final class Builder - extends TypedPropertiesBag.Builder - implements SmithyBuilder { + extends TypedPropertiesBag.Builder + implements SmithyBuilder { private String dependencyType = ""; private String packageName; diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/SymbolReference.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/SymbolReference.java index b029153a7b0..25acb71f625 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/SymbolReference.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/SymbolReference.java @@ -34,8 +34,8 @@ * necessary both when defining and when using a symbol. */ public final class SymbolReference - extends TypedPropertiesBag - implements SymbolContainer, SymbolDependencyContainer, ToSmithyBuilder { + extends TypedPropertiesBag + implements SymbolContainer, SymbolDependencyContainer, ToSmithyBuilder { /** * Top-level interface for all {@code SymbolReference} options. @@ -155,11 +155,11 @@ public List getDependencies() { @Override public Builder toBuilder() { return new Builder() - .symbol(symbol) - .options(options) - .properties(getProperties()) - .typedProperties(getTypedProperties()) - .alias(alias); + .symbol(symbol) + .options(options) + .properties(getProperties()) + .typedProperties(getTypedProperties()) + .alias(alias); } @Override @@ -172,10 +172,10 @@ public boolean equals(Object o) { SymbolReference that = (SymbolReference) o; return super.equals(o) - && symbol.equals(that.symbol) - && getProperties().equals(that.getProperties()) - && options.equals(that.options) - && alias.equals(that.alias); + && symbol.equals(that.symbol) + && getProperties().equals(that.getProperties()) + && options.equals(that.options) + && alias.equals(that.alias); } @Override @@ -192,8 +192,8 @@ public String toString() { * Builds a SymbolReference. */ public static final class Builder - extends TypedPropertiesBag.Builder - implements SmithyBuilder { + extends TypedPropertiesBag.Builder + implements SmithyBuilder { private Symbol symbol; private final BuilderRef> options = BuilderRef.forUnorderedSet(); diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/SymbolWriter.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/SymbolWriter.java index ac0ba1b6008..a3d9e9bd58d 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/SymbolWriter.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/SymbolWriter.java @@ -65,7 +65,7 @@ */ @SmithyUnstableApi public abstract class SymbolWriter, I extends ImportContainer> - extends AbstractCodeWriter implements SymbolDependencyContainer { + extends AbstractCodeWriter implements SymbolDependencyContainer { private static final Logger LOGGER = Logger.getLogger(SymbolWriter.class.getName()); private static final String RELATIVIZE_SYMBOLS = "__RelativizeSymbols"; @@ -98,7 +98,7 @@ public abstract class SymbolWriter, I extends Impor */ @FunctionalInterface public interface Factory> - extends BiFunction { + extends BiFunction { /** * Creates a {@code SymbolWriter} of type {@code W} for the given * filename and namespace. @@ -141,8 +141,8 @@ public String apply(Object type, String indent) { return typeSymbol.getAlias(); } else { throw new CodegenException( - "Invalid type provided to $T. Expected a Symbol or SymbolReference, " - + "but found `" + type + "`" + "Invalid type provided to $T. Expected a Symbol or SymbolReference, " + + "but found `" + type + "`" ); } } @@ -269,12 +269,12 @@ public W addUseImports(SymbolReference symbolReference) { @SuppressWarnings("unchecked") public final W addImport(Symbol symbol, String alias, SymbolReference.ContextOption... options) { LOGGER.finest( - () -> String.format( - "Adding import %s as `%s` (%s)", - symbol.getNamespace(), - alias, - Arrays.toString(options) - ) + () -> String.format( + "Adding import %s as `%s` (%s)", + symbol.getNamespace(), + alias, + Arrays.toString(options) + ) ); // Always add the dependencies of the symbol. diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/TopologicalIndex.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/TopologicalIndex.java index aa6a9c8e87d..072c8af2f03 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/TopologicalIndex.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/TopologicalIndex.java @@ -79,10 +79,10 @@ public TopologicalIndex(Model model) { } private Set explore( - Shape shape, - List path, - Set visited, - NeighborProvider provider + Shape shape, + List path, + Set visited, + NeighborProvider provider ) { if (visited.contains(shape)) { return Collections.singleton(new PathFinder.Path(path)); diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/TypedPropertiesBag.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/TypedPropertiesBag.java index 83c14bf0376..50a5138c8bc 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/TypedPropertiesBag.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/TypedPropertiesBag.java @@ -71,21 +71,21 @@ public Optional getProperty(Property property) { @SuppressWarnings("unchecked") public Optional getProperty(String name, Class type) { return getProperty(name) - .map(value -> { - if (!type.isInstance(value)) { - throw new IllegalArgumentException( - String.format( - "%s property `%s` of `%s` is not an instance of `%s`. Found `%s`", - getClass().getSimpleName(), - name, - this, - type.getName(), - value.getClass().getName() - ) - ); - } - return (T) value; - }); + .map(value -> { + if (!type.isInstance(value)) { + throw new IllegalArgumentException( + String.format( + "%s property `%s` of `%s` is not an instance of `%s`. Found `%s`", + getClass().getSimpleName(), + name, + this, + type.getName(), + value.getClass().getName() + ) + ); + } + return (T) value; + }); } /** @@ -97,14 +97,14 @@ public Optional getProperty(String name, Class type) { */ public Object expectProperty(String name) { return getProperty(name).orElseThrow( - () -> new IllegalArgumentException( - String.format( - "Property `%s` is not part of %s, `%s`", - name, - getClass().getSimpleName(), - this + () -> new IllegalArgumentException( + String.format( + "Property `%s` is not part of %s, `%s`", + name, + getClass().getSimpleName(), + this + ) ) - ) ); } @@ -121,14 +121,14 @@ public Object expectProperty(String name) { */ public T expectProperty(String name, Class type) { return getProperty(name, type).orElseThrow( - () -> new IllegalArgumentException( - String.format( - "Property `%s` is not part of %s, `%s`", - name, - getClass().getSimpleName(), - this + () -> new IllegalArgumentException( + String.format( + "Property `%s` is not part of %s, `%s`", + name, + getClass().getSimpleName(), + this + ) ) - ) ); } @@ -141,13 +141,13 @@ public T expectProperty(String name, Class type) { */ public T expectProperty(Property property) { return getProperty(property).orElseThrow( - () -> new IllegalArgumentException( - String.format( - "Property `%s` expected but not found on %s", - property, - this + () -> new IllegalArgumentException( + String.format( + "Property `%s` expected but not found on %s", + property, + this + ) ) - ) ); } diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/WriterDelegator.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/WriterDelegator.java index 9420194bc16..3bba51f0086 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/WriterDelegator.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/WriterDelegator.java @@ -51,7 +51,7 @@ * @param The type of {@link SymbolWriter} to create and manage. */ public class WriterDelegator> - implements SymbolDependencyContainer { + implements SymbolDependencyContainer { private final FileManifest fileManifest; private final SymbolProvider symbolProvider; diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/CodegenDirector.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/CodegenDirector.java index 8cc5338f02c..9afcc7545e2 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/CodegenDirector.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/CodegenDirector.java @@ -162,8 +162,8 @@ public S settings(Class settingsType, Node settingsNode) { S deserialized = new NodeMapper().deserialize(settingsNode, settingsType); settings(deserialized); settingsNode.asObjectNode() - .flatMap(node -> node.getObjectMember("integrations")) - .ifPresent(this::integrationSettings); + .flatMap(node -> node.getObjectMember("integrations")) + .ifPresent(this::integrationSettings); return deserialized; } @@ -230,8 +230,8 @@ public void integrationFinder(Supplier> integrationFinder) { */ public void integrationClassLoader(ClassLoader classLoader) { Objects.requireNonNull( - integrationClass, - "integrationClass() must be called before calling integrationClassLoader" + integrationClass, + "integrationClass() must be called before calling integrationClassLoader" ); integrationFinder(() -> ServiceLoader.load(integrationClass, classLoader)); } @@ -336,8 +336,8 @@ public void flattenPaginationInfoIntoOperations() { transforms.add((model, transformer) -> { LOGGER.finest("Flattening pagination info into operation traits for directed codegen"); return transformer.flattenPaginationInfoIntoOperations( - model, - model.expectShape(service, ServiceShape.class) + model, + model.expectShape(service, ServiceShape.class) ); }); } @@ -397,8 +397,8 @@ public void run() { LOGGER.fine("All setup done. Beginning code generation"); LOGGER.finest( - () -> "Performing custom codegen for " - + directedCodegen.getClass().getName() + " before shape codegen" + () -> "Performing custom codegen for " + + directedCodegen.getClass().getName() + " before shape codegen" ); CustomizeDirective customizeDirective = new CustomizeDirective<>(context, serviceShape); directedCodegen.customizeBeforeShapeGeneration(customizeDirective); @@ -410,16 +410,16 @@ public void run() { directedCodegen.generateService(new GenerateServiceDirective<>(context, serviceShape)); LOGGER.finest( - () -> "Performing custom codegen for " - + directedCodegen.getClass().getName() + " before integrations" + () -> "Performing custom codegen for " + + directedCodegen.getClass().getName() + " before integrations" ); directedCodegen.customizeBeforeIntegrations(customizeDirective); applyIntegrationCustomizations(context, integrations); LOGGER.finest( - () -> "Performing custom codegen for " - + directedCodegen.getClass().getName() + " after integrations" + () -> "Performing custom codegen for " + + directedCodegen.getClass().getName() + " after integrations" ); directedCodegen.customizeAfterIntegrations(customizeDirective); @@ -443,11 +443,11 @@ private void validateState() { // Use a default integration finder implementation. if (integrationFinder == null) { LOGGER.fine( - () -> String.format( - "Finding %s integrations using the %s class loader", - integrationClass.getName(), - CodegenDirector.class.getCanonicalName() - ) + () -> String.format( + "Finding %s integrations using the %s class loader", + integrationClass.getName(), + CodegenDirector.class.getCanonicalName() + ) ); integrationClassLoader(getClass().getClassLoader()); } @@ -482,7 +482,7 @@ private void preprocessModelWithIntegrations(List integrations) { private SymbolProvider createSymbolProvider(List integrations, ServiceShape serviceShape) { LOGGER.fine(() -> "Creating a symbol provider from " + settings.getClass().getName()); SymbolProvider provider = directedCodegen.createSymbolProvider( - new CreateSymbolProviderDirective<>(model, settings, serviceShape) + new CreateSymbolProviderDirective<>(model, settings, serviceShape) ); LOGGER.finer(() -> "Decorating symbol provider using " + integrationClass.getName()); @@ -496,14 +496,14 @@ private SymbolProvider createSymbolProvider(List integrations, ServiceShape s private C createContext(ServiceShape serviceShape, SymbolProvider provider, List integrations) { LOGGER.fine(() -> "Creating a codegen context for " + directedCodegen.getClass().getName()); return directedCodegen.createContext( - new CreateContextDirective<>( - model, - settings, - serviceShape, - provider, - fileManifest, - integrations - ) + new CreateContextDirective<>( + model, + settings, + serviceShape, + provider, + fileManifest, + integrations + ) ); } @@ -518,11 +518,11 @@ private void registerInterceptors(C context, List integrations) { private void generateShapesInService(C context, ServiceShape serviceShape) { LOGGER.fine( - () -> String.format( - "Generating shapes for %s in %s order", - directedCodegen.getClass().getName(), - this.shapeGenerationOrder.name() - ) + () -> String.format( + "Generating shapes for %s in %s order", + directedCodegen.getClass().getName(), + this.shapeGenerationOrder.name() + ) ); Set shapes = new Walker(context.model()).walkShapes(serviceShape); ShapeGenerator generator = new ShapeGenerator<>(context, serviceShape, directedCodegen); @@ -562,15 +562,15 @@ private void generateShapesInService(C context, ServiceShape serviceShape) { private void applyIntegrationCustomizations(C context, List integrations) { for (I integration : integrations) { LOGGER.finest( - () -> "Customizing codegen for " + directedCodegen.getClass().getName() - + " using integration " + integration.getClass().getName() + () -> "Customizing codegen for " + directedCodegen.getClass().getName() + + " using integration " + integration.getClass().getName() ); integration.customize(context); } } private static class ShapeGenerator, C extends CodegenContext, S> - extends ShapeVisitor.Default { + extends ShapeVisitor.Default { private final C context; private final ServiceShape serviceShape; @@ -591,7 +591,7 @@ protected Void getDefault(Shape shape) { public Void resourceShape(ResourceShape shape) { LOGGER.finest(() -> "Generating resource " + shape.getId()); directedCodegen.generateResource( - new GenerateResourceDirective<>(context, serviceShape, shape) + new GenerateResourceDirective<>(context, serviceShape, shape) ); return null; } @@ -600,7 +600,7 @@ public Void resourceShape(ResourceShape shape) { public Void operationShape(OperationShape shape) { LOGGER.finest(() -> "Generating operation " + shape.getId()); directedCodegen.generateOperation( - new GenerateOperationDirective<>(context, serviceShape, shape) + new GenerateOperationDirective<>(context, serviceShape, shape) ); return null; } diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/CreateContextDirective.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/CreateContextDirective.java index 3bdf07be5b1..564ad0a30ed 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/CreateContextDirective.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/CreateContextDirective.java @@ -32,12 +32,12 @@ public final class CreateContextDirective integrations; CreateContextDirective( - Model model, - S settings, - ServiceShape service, - SymbolProvider symbolProvider, - FileManifest fileManifest, - List integrations + Model model, + S settings, + ServiceShape service, + SymbolProvider symbolProvider, + FileManifest fileManifest, + List integrations ) { super(model, settings, service); this.symbolProvider = symbolProvider; diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateEnumDirective.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateEnumDirective.java index bc8f3b7648c..4b002eb7361 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateEnumDirective.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateEnumDirective.java @@ -67,11 +67,11 @@ public EnumTrait getEnumTrait() { public EnumShape expectEnumShape() { return shape().asEnumShape() - .orElseThrow( - () -> new ExpectationNotMetException( - "Expected an enum shape, but found " + shape(), - shape() - ) - ); + .orElseThrow( + () -> new ExpectationNotMetException( + "Expected an enum shape, but found " + shape(), + shape() + ) + ); } } diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateErrorDirective.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateErrorDirective.java index 246dff4ace1..fa57ebfe2c9 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateErrorDirective.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateErrorDirective.java @@ -17,7 +17,7 @@ * @see DirectedCodegen#generateError */ public final class GenerateErrorDirective, S> - extends ShapeDirective { + extends ShapeDirective { GenerateErrorDirective(C context, ServiceShape service, StructureShape shape) { super(context, service, shape); diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateIntEnumDirective.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateIntEnumDirective.java index d079795f163..4767e2d748d 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateIntEnumDirective.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateIntEnumDirective.java @@ -32,11 +32,11 @@ private static Shape validateShape(Shape shape) { public IntEnumShape expectIntEnumShape() { return shape().asIntEnumShape() - .orElseThrow( - () -> new ExpectationNotMetException( - "Expected an IntEnum shape, but found " + shape(), - shape() - ) - ); + .orElseThrow( + () -> new ExpectationNotMetException( + "Expected an IntEnum shape, but found " + shape(), + shape() + ) + ); } } diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateListDirective.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateListDirective.java index 2ca3f620b8c..be60510284a 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateListDirective.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateListDirective.java @@ -16,7 +16,7 @@ * @see DirectedCodegen#generateList */ public class GenerateListDirective, S> - extends ShapeDirective { + extends ShapeDirective { GenerateListDirective(C context, ServiceShape service, ListShape shape) { super(context, service, shape); } diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateMapDirective.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateMapDirective.java index 75f17f0513a..385ad027e91 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateMapDirective.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateMapDirective.java @@ -16,7 +16,7 @@ * @see DirectedCodegen#generateMap */ public class GenerateMapDirective, S> - extends ShapeDirective { + extends ShapeDirective { GenerateMapDirective(C context, ServiceShape service, MapShape shape) { super(context, service, shape); } diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateOperationDirective.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateOperationDirective.java index 26f13e4d991..54a2d4b4ba6 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateOperationDirective.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateOperationDirective.java @@ -16,7 +16,7 @@ * @see DirectedCodegen#generateOperation */ public class GenerateOperationDirective, S> - extends ShapeDirective { + extends ShapeDirective { GenerateOperationDirective(C context, ServiceShape service, OperationShape shape) { super(context, service, shape); } diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateResourceDirective.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateResourceDirective.java index 09fb02ea9d1..b910b315c79 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateResourceDirective.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateResourceDirective.java @@ -16,7 +16,7 @@ * @see DirectedCodegen#generateResource */ public final class GenerateResourceDirective, S> - extends ShapeDirective { + extends ShapeDirective { GenerateResourceDirective(C context, ServiceShape service, ResourceShape shape) { super(context, service, shape); } diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateServiceDirective.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateServiceDirective.java index 72f7b4141d2..c9c02c30f7f 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateServiceDirective.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateServiceDirective.java @@ -25,7 +25,7 @@ * @see DirectedCodegen#generateService */ public final class GenerateServiceDirective, S> - extends ShapeDirective { + extends ShapeDirective { GenerateServiceDirective(C context, ServiceShape service) { super(context, service, service); diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateStructureDirective.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateStructureDirective.java index 0015c2a3158..0921bb0658f 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateStructureDirective.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateStructureDirective.java @@ -19,7 +19,7 @@ * @see DirectedCodegen#generateStructure */ public final class GenerateStructureDirective, S> - extends ShapeDirective { + extends ShapeDirective { GenerateStructureDirective(C context, ServiceShape service, StructureShape shape) { super(context, service, shape); diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateUnionDirective.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateUnionDirective.java index 7527389c865..e28b8c0f235 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateUnionDirective.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/GenerateUnionDirective.java @@ -17,7 +17,7 @@ * @see DirectedCodegen#generateUnion */ public final class GenerateUnionDirective, S> - extends ShapeDirective { + extends ShapeDirective { GenerateUnionDirective(C context, ServiceShape service, UnionShape shape) { super(context, service, shape); diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/ShapeDirective.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/ShapeDirective.java index 43f5e686689..7e2001c09cb 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/ShapeDirective.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/directed/ShapeDirective.java @@ -17,7 +17,7 @@ * @param Codegen settings type. */ public abstract class ShapeDirective, S> - extends ContextualDirective { + extends ContextualDirective { private final T shape; private final Symbol symbol; diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/ArtifactDefinitions.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/ArtifactDefinitions.java index 45c9b3af8c1..ef3a7db3fc8 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/ArtifactDefinitions.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/ArtifactDefinitions.java @@ -62,9 +62,9 @@ public static Builder builder() { @Override public ObjectNode toNode() { return ObjectNode.objectNodeBuilder() - .withMember(TAGS_TEXT, ObjectNode.fromStringMap(tags)) - .withMember(TYPE_TEXT, ObjectNode.fromStringMap(types)) - .build(); + .withMember(TAGS_TEXT, ObjectNode.fromStringMap(tags)) + .withMember(TYPE_TEXT, ObjectNode.fromStringMap(types)) + .build(); } /** @@ -103,8 +103,8 @@ public Map getTypes() { @Override public Builder toBuilder() { return builder() - .tags(tags) - .types(types); + .tags(tags) + .types(types); } public static final class Builder implements SmithyBuilder { diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/ShapeLink.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/ShapeLink.java index 391b5220cba..cbf1eb8d18e 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/ShapeLink.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/ShapeLink.java @@ -68,11 +68,11 @@ public static Builder builder() { @Override public ObjectNode toNode() { ObjectNode.Builder builder = ObjectNode.objectNodeBuilder() - .withMember(ID_TEXT, id) - .withMember(TYPE_TEXT, type) - .withOptionalMember(FILE_TEXT, getFile().map(Node::from)) - .withOptionalMember(LINE_TEXT, getLine().map(Node::from)) - .withOptionalMember(COLUMN_TEXT, getColumn().map(Node::from)); + .withMember(ID_TEXT, id) + .withMember(TYPE_TEXT, type) + .withOptionalMember(FILE_TEXT, getFile().map(Node::from)) + .withOptionalMember(LINE_TEXT, getLine().map(Node::from)) + .withOptionalMember(COLUMN_TEXT, getColumn().map(Node::from)); if (!tags.isEmpty()) { builder.withMember(TAGS_TEXT, Node.fromStrings(tags)); @@ -156,12 +156,12 @@ public Optional getColumn() { @Override public Builder toBuilder() { return builder() - .id(id) - .column(column) - .type(type) - .tags(tags) - .line(line) - .file(file); + .id(id) + .column(column) + .type(type) + .tags(tags) + .line(line) + .file(file); } public static final class Builder implements SmithyBuilder { diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/TraceFile.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/TraceFile.java index f8519eabf95..d12ad3cbc7f 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/TraceFile.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/TraceFile.java @@ -68,8 +68,8 @@ private TraceFile(Builder builder) { public static TraceFile fromNode(Node value) { ObjectNode node = value.expectObjectNode(); Builder builder = builder() - .smithyTrace(node.expectStringMember(SMITHY_TRACE_TEXT).getValue()) - .metadata(TraceMetadata.fromNode(node.expectObjectMember(METADATA_TEXT))); + .smithyTrace(node.expectStringMember(SMITHY_TRACE_TEXT).getValue()) + .metadata(TraceMetadata.fromNode(node.expectObjectMember(METADATA_TEXT))); //parse shapes Map shapeMap = node.expectObjectMember(SHAPES_TEXT).getMembers(); @@ -104,19 +104,19 @@ public ObjectNode toNode() { for (Map.Entry> entry : shapes.entrySet()) { String shapeId = entry.getKey().toString(); ArrayNode shapeListNode = entry.getValue() //get list of ShapeLinks - .stream() - .map(ShapeLink::toNode) //convert each ShapeLink to an ObjectNode - .collect(ArrayNode.collect()); //collect each ObjectNode in an ArrayNode + .stream() + .map(ShapeLink::toNode) //convert each ShapeLink to an ObjectNode + .collect(ArrayNode.collect()); //collect each ObjectNode in an ArrayNode shapesBuilder.withMember(shapeId, shapeListNode); } //returning ObjectNode for TraceFile return ObjectNode.objectNodeBuilder() - .withMember(SMITHY_TRACE_TEXT, smithyTrace) - .withMember(METADATA_TEXT, metadata) - .withOptionalMember(DEFINITIONS_TEXT, getArtifactDefinitions()) - .withMember(SHAPES_TEXT, shapesBuilder.build()) - .build(); + .withMember(SMITHY_TRACE_TEXT, smithyTrace) + .withMember(METADATA_TEXT, metadata) + .withOptionalMember(DEFINITIONS_TEXT, getArtifactDefinitions()) + .withMember(SHAPES_TEXT, shapesBuilder.build()) + .build(); } /** @@ -137,9 +137,9 @@ private void validateTypesAndTags() { //checking if link's type is in artifactDefinitions if (!artifactDefinitions.getTypes().containsKey(link.getType())) { throw new ExpectationNotMetException( - entry.getKey().toString() - + " contains types that aren't in definitions.", - SourceLocation.none() + entry.getKey().toString() + + " contains types that aren't in definitions.", + SourceLocation.none() ); } @@ -148,9 +148,9 @@ private void validateTypesAndTags() { for (String tag : tags) { if (!artifactDefinitions.getTags().containsKey(tag)) { throw new ExpectationNotMetException( - entry.getKey().toString() + " " + tag - + " is a tag that isn't in definitions.", - SourceLocation.none() + entry.getKey().toString() + " " + tag + + " is a tag that isn't in definitions.", + SourceLocation.none() ); } } @@ -172,10 +172,10 @@ public void validateModel(Model model) { Set fileShapesCopy = new HashSet<>(fileShapes); Set modelShapes = model.toSet() - .stream() - .filter(shape -> !Prelude.isPreludeShape(shape)) //ignore shapes in smithy.api namespace - .map(Shape::getId) //get ShapeId for each shape - .collect(Collectors.toSet()); //collect into a set of ShapeIds + .stream() + .filter(shape -> !Prelude.isPreludeShape(shape)) //ignore shapes in smithy.api namespace + .map(Shape::getId) //get ShapeId for each shape + .collect(Collectors.toSet()); //collect into a set of ShapeIds //get shapes in TraceFile that aren't in model; fileShapes.removeAll(modelShapes); @@ -258,10 +258,10 @@ public Map> getShapes() { @Override public Builder toBuilder() { return builder() - .metadata(metadata) - .smithyTrace(smithyTrace) - .definitions(artifactDefinitions) - .shapes(shapes); + .metadata(metadata) + .smithyTrace(smithyTrace) + .definitions(artifactDefinitions) + .shapes(shapes); } /** diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/TraceMetadata.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/TraceMetadata.java index 174b7bb319c..4789371bf3f 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/TraceMetadata.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/TraceMetadata.java @@ -69,13 +69,13 @@ public static Builder builder() { @Override public ObjectNode toNode() { return ObjectNode.objectNodeBuilder() - .withMember(ID_TEXT, id) - .withMember(VERSION_TEXT, version) - .withMember(TYPE_TEXT, type) - .withMember(TIMESTAMP_TEXT, timestamp) - .withOptionalMember(TYPE_VERSION_TEXT, getTypeVersion().map(Node::from)) - .withOptionalMember(HOMEPAGE_TEXT, getHomepage().map(Node::from)) - .build(); + .withMember(ID_TEXT, id) + .withMember(VERSION_TEXT, version) + .withMember(TYPE_TEXT, type) + .withMember(TIMESTAMP_TEXT, timestamp) + .withOptionalMember(TYPE_VERSION_TEXT, getTypeVersion().map(Node::from)) + .withOptionalMember(HOMEPAGE_TEXT, getHomepage().map(Node::from)) + .build(); } /** @@ -149,12 +149,12 @@ public Optional getHomepage() { @Override public Builder toBuilder() { return builder() - .id(id) - .version(version) - .timestamp(timestamp) - .type(type) - .typeVersion(typeVersion) - .homepage(homepage); + .id(id) + .version(version) + .timestamp(timestamp) + .type(type) + .typeVersion(typeVersion) + .homepage(homepage); } public static final class Builder implements SmithyBuilder { diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/TracingSymbolProvider.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/TracingSymbolProvider.java index b1069aa180c..5b8ff319589 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/TracingSymbolProvider.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/trace/TracingSymbolProvider.java @@ -30,7 +30,7 @@ private TracingSymbolProvider(Builder builder) { symbolProvider = SmithyBuilder.requiredState("symbolProvider", builder.symbolProvider); shapeLinkCreator = SmithyBuilder.requiredState("shapeLinkCreator", builder.shapeLinkCreator); traceFileBuilder.metadata(SmithyBuilder.requiredState("metadata", builder.metadata)) - .definitions(builder.artifactDefinitions); + .definitions(builder.artifactDefinitions); } /** @@ -132,11 +132,11 @@ public Builder metadata(TraceMetadata metadata) { public Builder setTraceMetadataAsDefault(String artifactType) { String tempIdVersion = UUID.randomUUID().toString(); this.metadata = TraceMetadata.builder() - .version(tempIdVersion) - .id(tempIdVersion) - .type(artifactType) - .setTimestampAsNow() - .build(); + .version(tempIdVersion) + .id(tempIdVersion) + .type(artifactType) + .setTimestampAsNow() + .build(); return this; } diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/writer/CodegenWriter.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/writer/CodegenWriter.java index d35859250eb..3b2e5e729db 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/writer/CodegenWriter.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/writer/CodegenWriter.java @@ -75,7 +75,7 @@ @SmithyUnstableApi @Deprecated public class CodegenWriter, U extends ImportContainer> - extends CodeWriter implements SymbolDependencyContainer { + extends CodeWriter implements SymbolDependencyContainer { private static final Logger LOGGER = Logger.getLogger(CodegenWriter.class.getName()); private static final String RELATIVIZE_SYMBOLS = "__CodegenWriterRelativizeSymbols"; @@ -117,8 +117,8 @@ public String apply(Object type, String indent) { return typeSymbol.getAlias(); } else { throw new CodegenException( - "Invalid type provided to $T. Expected a Symbol or SymbolReference, " - + "but found `" + type + "`" + "Invalid type provided to $T. Expected a Symbol or SymbolReference, " + + "but found `" + type + "`" ); } } @@ -254,12 +254,12 @@ public T addUseImports(SymbolReference symbolReference) { @SuppressWarnings("unchecked") public final T addImport(Symbol symbol, String alias, SymbolReference.ContextOption... options) { LOGGER.finest( - () -> String.format( - "Adding import %s as `%s` (%s)", - symbol.getNamespace(), - alias, - Arrays.toString(options) - ) + () -> String.format( + "Adding import %s as `%s` (%s)", + symbol.getNamespace(), + alias, + Arrays.toString(options) + ) ); // Always add the dependencies of the symbol. diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/writer/CodegenWriterDelegator.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/writer/CodegenWriterDelegator.java index 00f64242038..9ab540dffce 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/writer/CodegenWriterDelegator.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/writer/CodegenWriterDelegator.java @@ -71,9 +71,9 @@ public class CodegenWriterDelegator> { * @param codegenWriterFactory Factory used to create new {@link CodegenWriter}s. */ public CodegenWriterDelegator( - FileManifest fileManifest, - SymbolProvider symbolProvider, - CodegenWriterFactory codegenWriterFactory + FileManifest fileManifest, + SymbolProvider symbolProvider, + CodegenWriterFactory codegenWriterFactory ) { this.fileManifest = fileManifest; this.symbolProvider = symbolProvider; diff --git a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/writer/SymbolWriter.java b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/writer/SymbolWriter.java index a4ee12f8e2e..0b1ff3c69c5 100644 --- a/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/writer/SymbolWriter.java +++ b/smithy-codegen-core/src/main/java/software/amazon/smithy/codegen/core/writer/SymbolWriter.java @@ -30,7 +30,7 @@ @SmithyUnstableApi @Deprecated public class SymbolWriter, U extends ImportContainer> - extends AbstractCodeWriter implements SymbolDependencyContainer { + extends AbstractCodeWriter implements SymbolDependencyContainer { private static final Logger LOGGER = Logger.getLogger(SymbolWriter.class.getName()); private static final String RELATIVIZE_SYMBOLS = "__CodegenWriterRelativizeSymbols"; @@ -72,8 +72,8 @@ public String apply(Object type, String indent) { return typeSymbol.getAlias(); } else { throw new CodegenException( - "Invalid type provided to $T. Expected a Symbol or SymbolReference, " - + "but found `" + type + "`" + "Invalid type provided to $T. Expected a Symbol or SymbolReference, " + + "but found `" + type + "`" ); } } @@ -209,12 +209,12 @@ public T addUseImports(SymbolReference symbolReference) { @SuppressWarnings("unchecked") public final T addImport(Symbol symbol, String alias, SymbolReference.ContextOption... options) { LOGGER.finest( - () -> String.format( - "Adding import %s as `%s` (%s)", - symbol.getNamespace(), - alias, - Arrays.toString(options) - ) + () -> String.format( + "Adding import %s as `%s` (%s)", + symbol.getNamespace(), + alias, + Arrays.toString(options) + ) ); // Always add the dependencies of the symbol. diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/IntegrationTopologicalSortTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/IntegrationTopologicalSortTest.java index 803ed4a5aa9..932708d48f9 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/IntegrationTopologicalSortTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/IntegrationTopologicalSortTest.java @@ -21,7 +21,7 @@ public class IntegrationTopologicalSortTest { private static final class MySettings {} private static final class MyIntegration implements - SmithyIntegration> { + SmithyIntegration> { private final String name; private final byte priority; private final List runBefore; @@ -74,9 +74,9 @@ public String toString() { static List toStrings(List> integrations) { return SmithyIntegration.sort(integrations) - .stream() - .map(SmithyIntegration::name) - .collect(Collectors.toList()); + .stream() + .map(SmithyIntegration::name) + .collect(Collectors.toList()); } @Test @@ -168,8 +168,8 @@ public void detectsCycles() { integrations.add(new MyIntegration("d", (byte) 0, ListUtils.of("b"), ListUtils.of("a"))); RuntimeException e = Assertions.assertThrows( - IllegalArgumentException.class, - () -> SmithyIntegration.sort(integrations) + IllegalArgumentException.class, + () -> SmithyIntegration.sort(integrations) ); assertThat(e.getMessage(), equalTo("SmithyIntegration cycles detected among [b, d]")); } @@ -181,15 +181,15 @@ public void detectsConflictingNames() { integrations.add(new MyIntegration("a")); RuntimeException e = Assertions.assertThrows( - IllegalArgumentException.class, - () -> SmithyIntegration.sort(integrations) + IllegalArgumentException.class, + () -> SmithyIntegration.sort(integrations) ); assertThat( - e.getMessage(), - equalTo( - "Conflicting SmithyIntegration names detected for 'a': software.amazon.smithy.codegen.core.IntegrationTopologicalSortTest.MyIntegration " - + "and software.amazon.smithy.codegen.core.IntegrationTopologicalSortTest.MyIntegration" - ) + e.getMessage(), + equalTo( + "Conflicting SmithyIntegration names detected for 'a': software.amazon.smithy.codegen.core.IntegrationTopologicalSortTest.MyIntegration " + + "and software.amazon.smithy.codegen.core.IntegrationTopologicalSortTest.MyIntegration" + ) ); } diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/MappedReservedWordsTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/MappedReservedWordsTest.java index 6c36e2858d6..e869d656e05 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/MappedReservedWordsTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/MappedReservedWordsTest.java @@ -14,9 +14,9 @@ public class MappedReservedWordsTest { @Test public void mapsOverReservedWords() { ReservedWords reservedWords = MappedReservedWords.builder() - .put("foo", "Foo") - .put("baz", "Baz") - .build(); + .put("foo", "Foo") + .put("baz", "Baz") + .build(); assertThat(reservedWords.isReserved("foo"), is(true)); assertThat(reservedWords.isReserved("Foo"), is(false)); @@ -34,9 +34,9 @@ public void mapsOverReservedWords() { @Test public void mapsOverReservedWordsCaseInsensitively() { ReservedWords reservedWords = MappedReservedWords.builder() - .putCaseInsensitive("foo", "Foo") - .putCaseInsensitive("baz", "Baz") - .build(); + .putCaseInsensitive("foo", "Foo") + .putCaseInsensitive("baz", "Baz") + .build(); assertThat(reservedWords.isReserved("foo"), is(true)); assertThat(reservedWords.isReserved("Foo"), is(true)); diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/ReservedWordSymbolProviderTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/ReservedWordSymbolProviderTest.java index 973758287ca..8cb63d14cb3 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/ReservedWordSymbolProviderTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/ReservedWordSymbolProviderTest.java @@ -21,14 +21,14 @@ public void escapesReservedFilenames() { ReservedWords reservedWords = new ReservedWordsBuilder().put("/foo/bar/bam", "/rewritten").build(); MockProvider delegate = new MockProvider(); SymbolProvider provider = ReservedWordSymbolProvider.builder() - .symbolProvider(delegate) - .filenameReservedWords(reservedWords) - .build(); + .symbolProvider(delegate) + .filenameReservedWords(reservedWords) + .build(); delegate.mock = Symbol.builder() - .name("foo") - .definitionFile("/foo/bar/bam") - .declarationFile("/foo/bar/bam") - .build(); + .name("foo") + .definitionFile("/foo/bar/bam") + .declarationFile("/foo/bar/bam") + .build(); assertThat(provider.toSymbol(s1).getDeclarationFile(), equalTo("/rewritten")); assertThat(provider.toSymbol(s2).getDefinitionFile(), equalTo("/rewritten")); @@ -42,9 +42,9 @@ public void escapesReservedNamespaces() { ReservedWords reservedWords = new ReservedWordsBuilder().put("foo.baz", "foo._baz").build(); MockProvider delegate = new MockProvider(); SymbolProvider provider = ReservedWordSymbolProvider.builder() - .symbolProvider(delegate) - .namespaceReservedWords(reservedWords) - .build(); + .symbolProvider(delegate) + .namespaceReservedWords(reservedWords) + .build(); delegate.mock = Symbol.builder().namespace("foo.bar", ".").name("Baz").build(); assertThat(provider.toSymbol(s1).getNamespace(), equalTo("foo.bar")); @@ -61,9 +61,9 @@ public void escapesReservedNames() { ReservedWords reservedWords = new ReservedWordsBuilder().put("Bam", "_Bam").build(); MockProvider delegate = new MockProvider(); SymbolProvider provider = ReservedWordSymbolProvider.builder() - .symbolProvider(delegate) - .nameReservedWords(reservedWords) - .build(); + .symbolProvider(delegate) + .nameReservedWords(reservedWords) + .build(); delegate.mock = Symbol.builder().namespace("foo.bar", ".").name("Baz").build(); assertThat(provider.toSymbol(s1).getName(), equalTo("Baz")); @@ -80,9 +80,9 @@ public void escapesReservedMemberNames() { ReservedWords reservedWords = new ReservedWordsBuilder().put("baz", "_baz").build(); SymbolProvider delegate = new MockProvider(); SymbolProvider provider = ReservedWordSymbolProvider.builder() - .symbolProvider(delegate) - .memberReservedWords(reservedWords) - .build(); + .symbolProvider(delegate) + .memberReservedWords(reservedWords) + .build(); assertThat(provider.toMemberName(s1), equalTo("foo")); assertThat(provider.toMemberName(s2), equalTo("_baz")); @@ -95,10 +95,10 @@ public void escapesOnlyWhenPredicateReturnsTrue() { ReservedWords reservedWords = new ReservedWordsBuilder().put("Bam", "_Bam").build(); MockProvider delegate = new MockProvider(); SymbolProvider provider = ReservedWordSymbolProvider.builder() - .symbolProvider(delegate) - .nameReservedWords(reservedWords) - .escapePredicate((shape, symbol) -> false) - .build(); + .symbolProvider(delegate) + .nameReservedWords(reservedWords) + .escapePredicate((shape, symbol) -> false) + .build(); delegate.mock = Symbol.builder().namespace("foo.baz", ".").name("Bam").build(); assertThat(provider.toSymbol(stringShape).getName(), equalTo("Bam")); @@ -111,8 +111,8 @@ public void canCreateEscaper() { ReservedWords reservedWords = new ReservedWordsBuilder().put("baz", "_baz").build(); SymbolProvider delegate = new MockProvider(); ReservedWordSymbolProvider.Escaper escaper = ReservedWordSymbolProvider.builder() - .memberReservedWords(reservedWords) - .buildEscaper(); + .memberReservedWords(reservedWords) + .buildEscaper(); assertThat(escaper.escapeMemberName(delegate.toMemberName(s1)), equalTo("_baz")); } diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/ReservedWordsBuilderTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/ReservedWordsBuilderTest.java index e15116668b6..28a11dc436e 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/ReservedWordsBuilderTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/ReservedWordsBuilderTest.java @@ -13,8 +13,8 @@ public class ReservedWordsBuilderTest { @Test public void loadsWords() { ReservedWords words = new ReservedWordsBuilder() - .loadWords(getClass().getResource("words.txt")) - .build(); + .loadWords(getClass().getResource("words.txt")) + .build(); basicWordTestTest(words, "_"); assertThat(words.escape("Boolean"), equalTo("Boolean")); @@ -31,8 +31,8 @@ private void basicWordTestTest(ReservedWords words, String prefix) { @Test public void loadsCaseInsensitiveWords() { ReservedWords words = new ReservedWordsBuilder() - .loadCaseInsensitiveWords(getClass().getResource("words.txt")) - .build(); + .loadCaseInsensitiveWords(getClass().getResource("words.txt")) + .build(); basicWordTestTest(words, "_"); assertThat(words.escape("Boolean"), equalTo("_Boolean")); @@ -41,8 +41,8 @@ public void loadsCaseInsensitiveWords() { @Test public void loadsWordsWithCustomEscaper() { ReservedWords words = new ReservedWordsBuilder() - .loadWords(getClass().getResource("words.txt"), word -> "$" + word) - .build(); + .loadWords(getClass().getResource("words.txt"), word -> "$" + word) + .build(); basicWordTestTest(words, "$"); assertThat(words.escape("Boolean"), equalTo("Boolean")); @@ -51,8 +51,8 @@ public void loadsWordsWithCustomEscaper() { @Test public void loadsCaseInsensitiveWordsWithCustomEscaper() { ReservedWords words = new ReservedWordsBuilder() - .loadCaseInsensitiveWords(getClass().getResource("words.txt"), word -> "$" + word) - .build(); + .loadCaseInsensitiveWords(getClass().getResource("words.txt"), word -> "$" + word) + .build(); basicWordTestTest(words, "$"); assertThat(words.escape("Boolean"), equalTo("$Boolean")); diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolDependencyTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolDependencyTest.java index e4e67725a0b..33e2e514778 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolDependencyTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolDependencyTest.java @@ -23,9 +23,9 @@ public class SymbolDependencyTest { @Test public void setsDefaultTypeToEmptyString() { SymbolDependency dependency = SymbolDependency.builder() - .packageName("foo") - .version("10") - .build(); + .packageName("foo") + .version("10") + .build(); assertThat(dependency.getPackageName(), equalTo("foo")); assertThat(dependency.getVersion(), equalTo("10")); @@ -35,10 +35,10 @@ public void setsDefaultTypeToEmptyString() { @Test public void convertsToBuilder() { SymbolDependency dependency = SymbolDependency.builder() - .dependencyType("dev") - .packageName("foo") - .version("10.0.1") - .build(); + .dependencyType("dev") + .packageName("foo") + .version("10.0.1") + .build(); assertThat(dependency.toBuilder().build(), equalTo(dependency)); } @@ -46,11 +46,11 @@ public void convertsToBuilder() { @Test public void hasProperties() { SymbolDependency dependency = SymbolDependency.builder() - .dependencyType("dev") - .packageName("foo") - .version("10.0.1") - .putProperty("foo", "baz!") - .build(); + .dependencyType("dev") + .packageName("foo") + .version("10.0.1") + .putProperty("foo", "baz!") + .build(); assertThat(dependency.expectProperty("foo", String.class), equalTo("baz!")); } @@ -85,11 +85,11 @@ public void gathersDependencies() { List> conflicts = new ArrayList<>(); Map> result = SymbolDependency.gatherDependencies( - Stream.of(a, aDuplicate, a2, a3, b, b2, c), - (sa, sb) -> { - conflicts.add(Pair.of(sa, sb)); - return sb; - } + Stream.of(a, aDuplicate, a2, a3, b, b2, c), + (sa, sb) -> { + conflicts.add(Pair.of(sa, sb)); + return sb; + } ); assertThat(conflicts, contains(Pair.of(b, b2))); diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolReferenceTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolReferenceTest.java index be69f758fd0..528b64f8e0a 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolReferenceTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolReferenceTest.java @@ -28,9 +28,9 @@ public void propertiesAndOptionsAreUsedInEquals() { Symbol symbol = Symbol.builder().name("foo").build(); SymbolReference ref1 = new SymbolReference(symbol); SymbolReference ref2 = new SymbolReference( - symbol, - MapUtils.of("foo", true), - SymbolReference.ContextOption.USE + symbol, + MapUtils.of("foo", true), + SymbolReference.ContextOption.USE ); SymbolReference ref3 = new SymbolReference(symbol, SymbolReference.ContextOption.USE); diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolTest.java index 3f1e7ad1507..e624f77cee9 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolTest.java @@ -18,9 +18,9 @@ public class SymbolTest { public void relativizesSymbol() { String ns = "com.foo"; Symbol symbol = Symbol.builder() - .name("Baz") - .namespace(ns, "::") - .build(); + .name("Baz") + .namespace(ns, "::") + .build(); assertThat(symbol.relativize(ns), equalTo("Baz")); assertThat(symbol.relativize("com.bam"), equalTo("com.foo::Baz")); @@ -29,10 +29,10 @@ public void relativizesSymbol() { @Test public void getsPropertiesFromClass() { Symbol symbol = Symbol.builder() - .name("foo") - .putProperty("baz", "bar") - .putProperty("bam", 100) - .build(); + .name("foo") + .putProperty("baz", "bar") + .putProperty("bam", 100) + .build(); assertThat(symbol.expectProperty("baz", String.class), equalTo("bar")); assertThat(symbol.expectProperty("bam", Integer.class), equalTo(100)); @@ -44,10 +44,10 @@ public void getsTypedProperties() { Property integerProperty = Property.named("int"); Symbol symbol = Symbol.builder() - .name("foo") - .putProperty(stringProperty, "foo") - .putProperty(integerProperty, 100) - .build(); + .name("foo") + .putProperty(stringProperty, "foo") + .putProperty(integerProperty, 100) + .build(); assertThat(symbol.expectProperty(stringProperty), equalTo("foo")); assertThat(symbol.expectProperty(integerProperty), equalTo(100)); @@ -76,9 +76,9 @@ public void throwsIfExpectedTypedPropertyIsNotPresent() { public void throwsIfExpectedPropertyIsNotOfSameType() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Symbol symbol = Symbol.builder() - .name("foo") - .putProperty("bam", 100) - .build(); + .name("foo") + .putProperty("bam", 100) + .build(); symbol.expectProperty("bam", String.class); }); @@ -87,9 +87,9 @@ public void throwsIfExpectedPropertyIsNotOfSameType() { @Test public void returnsDefinitionIfDeclarationPresent() { Symbol symbol = Symbol.builder() - .name("foo") - .declarationFile("/foo/bar.baz") - .build(); + .name("foo") + .declarationFile("/foo/bar.baz") + .build(); assertThat(symbol.getDefinitionFile(), equalTo("/foo/bar.baz")); } @@ -97,9 +97,9 @@ public void returnsDefinitionIfDeclarationPresent() { @Test public void returnsDeclarationIfDefinitionPresent() { Symbol symbol = Symbol.builder() - .name("foo") - .declarationFile("/foo/bar.baz") - .build(); + .name("foo") + .declarationFile("/foo/bar.baz") + .build(); assertThat(symbol.getDeclarationFile(), equalTo("/foo/bar.baz")); } @@ -107,10 +107,10 @@ public void returnsDeclarationIfDefinitionPresent() { @Test public void returnsAppropriateDefinitionAndDeclarationFiles() { Symbol symbol = Symbol.builder() - .name("foo") - .definitionFile("/foo/bar.baz") - .declarationFile("/foo/bar.h") - .build(); + .name("foo") + .definitionFile("/foo/bar.baz") + .declarationFile("/foo/bar.h") + .build(); assertThat(symbol.getDefinitionFile(), equalTo("/foo/bar.baz")); assertThat(symbol.getDeclarationFile(), equalTo("/foo/bar.h")); @@ -122,10 +122,10 @@ public void canAddDependencies() { SymbolDependency b = SymbolDependency.builder().packageName("b1").version("b2").build(); Symbol symbol = Symbol.builder() - .name("foo") - .addDependency("a1", "a2") - .addDependency(SymbolDependency.builder().packageName("b1").version("b2").build()) - .build(); + .name("foo") + .addDependency("a1", "a2") + .addDependency(SymbolDependency.builder().packageName("b1").version("b2").build()) + .build(); assertThat(symbol.getDependencies(), containsInAnyOrder(a, b)); assertThat(symbol.toBuilder().build(), equalTo(symbol)); @@ -134,9 +134,9 @@ public void canAddDependencies() { @Test public void convertsToAliasedSymbolReference() { Symbol symbol = Symbol.builder() - .name("foo") - .namespace("bar", ".") - .build(); + .name("foo") + .namespace("bar", ".") + .build(); SymbolReference reference = symbol.toReference("__foo", SymbolReference.ContextOption.DECLARE); assertThat(reference.getSymbol(), is(symbol)); @@ -147,17 +147,17 @@ public void convertsToAliasedSymbolReference() { @Test public void convertsToAliasedSymbol() { Symbol symbol = Symbol.builder() - .name("foo") - .namespace("bar", ".") - .build(); + .name("foo") + .namespace("bar", ".") + .build(); Symbol symbolRef = symbol.toReferencedSymbol("__foo"); SymbolReference ref = SymbolReference.builder() - .alias("__foo") - .symbol(symbol) - .options(SymbolReference.ContextOption.USE) - .build(); + .alias("__foo") + .symbol(symbol) + .options(SymbolReference.ContextOption.USE) + .build(); assertThat(symbolRef.getName(), equalTo("__foo")); assertThat(symbolRef.getNamespace(), equalTo("")); diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolWriterTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolWriterTest.java index c449443caf1..496f6f8181c 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolWriterTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/SymbolWriterTest.java @@ -18,10 +18,10 @@ public class SymbolWriterTest { public void managesDependencies() { MySimpleWriter writer = new MySimpleWriter("foo"); SymbolDependency dep = SymbolDependency.builder() - .packageName("foo") - .version("123") - .dependencyType("Dev") - .build(); + .packageName("foo") + .version("123") + .dependencyType("Dev") + .build(); writer.addDependency(dep); assertThat(writer.getDependencies(), contains(dep)); @@ -31,16 +31,16 @@ public void managesDependencies() { public void addsUseImportsWithReferences() { MySimpleWriter writer = new MySimpleWriter("foo"); Symbol s = Symbol.builder() - .declarationFile("foo.ts") - .definitionFile("foo.ts") - .name("Hello") - .namespace("com/foo", "/") - .build(); + .declarationFile("foo.ts") + .definitionFile("foo.ts") + .name("Hello") + .namespace("com/foo", "/") + .build(); SymbolReference reference = SymbolReference.builder() - .symbol(s) - .alias("X") - .options(SymbolReference.ContextOption.USE) - .build(); + .symbol(s) + .alias("X") + .options(SymbolReference.ContextOption.USE) + .build(); writer.addUseImports(reference); assertThat(writer.getImportContainer().imports, hasKey("X")); @@ -51,16 +51,16 @@ public void addsUseImportsWithReferences() { public void omitsUseImportsWithReferencesIfSameNamespace() { MySimpleWriter writer = new MySimpleWriter("foo"); Symbol s = Symbol.builder() - .declarationFile("foo.ts") - .definitionFile("foo.ts") - .name("Hello") - .namespace("foo", "/") - .build(); + .declarationFile("foo.ts") + .definitionFile("foo.ts") + .name("Hello") + .namespace("foo", "/") + .build(); SymbolReference reference = SymbolReference.builder() - .symbol(s) - .alias("X") - .options(SymbolReference.ContextOption.USE) - .build(); + .symbol(s) + .alias("X") + .options(SymbolReference.ContextOption.USE) + .build(); writer.addUseImports(reference); assertThat(writer.getImportContainer().imports, not(hasKey("X"))); @@ -70,20 +70,20 @@ public void omitsUseImportsWithReferencesIfSameNamespace() { public void importsUseReferencesFromSymbols() { MySimpleWriter writer = new MySimpleWriter("foo"); Symbol string = Symbol.builder() - .definitionFile("java/lang/String.java") - .name("String") - .namespace("java.lang", ".") - .build(); + .definitionFile("java/lang/String.java") + .name("String") + .namespace("java.lang", ".") + .build(); SymbolReference reference = SymbolReference.builder() - .symbol(string) - .alias("MyString") - .build(); + .symbol(string) + .alias("MyString") + .build(); Symbol someList = Symbol.builder() - .definitionFile("java/util/List.java") - .name("List") - .namespace("java.util", ".") - .addReference(reference) - .build(); + .definitionFile("java/util/List.java") + .name("List") + .namespace("java.util", ".") + .addReference(reference) + .build(); writer.addUseImports(someList); assertThat(writer.getImportContainer().imports, hasKey("List")); @@ -118,9 +118,9 @@ public void formatsSymbolReferences() { MySimpleWriter writer = new MySimpleWriter("com.foo"); Symbol string = Symbol.builder().name("String").namespace("example.foo", ".").build(); SymbolReference reference = SymbolReference.builder() - .alias("Str") - .symbol(string) - .build(); + .alias("Str") + .symbol(string) + .build(); writer.write("$T", reference); assertThat(writer.toString(), equalTo("Str\n")); diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/TopologicalIndexTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/TopologicalIndexTest.java index 2f4a53d03f6..6c9d529c629 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/TopologicalIndexTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/TopologicalIndexTest.java @@ -32,9 +32,9 @@ public class TopologicalIndexTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(TopologicalIndexTest.class.getResource("topological-sort.smithy")) - .assemble() - .unwrap(); + .addImport(TopologicalIndexTest.class.getResource("topological-sort.smithy")) + .assemble() + .unwrap(); } @AfterAll @@ -57,30 +57,30 @@ public void sortsTopologically() { } assertThat( - ordered, - contains( - "smithy.example#MyString", - "smithy.example#BamList$member", - "smithy.example#BamList", - "smithy.example#Bar$bam", - "smithy.api#Integer", - "smithy.example#Bar$baz", - "smithy.example#Bar", - "smithy.example#Foo$bar", - "smithy.example#Foo$foo", - "smithy.example#Foo" - ) + ordered, + contains( + "smithy.example#MyString", + "smithy.example#BamList$member", + "smithy.example#BamList", + "smithy.example#Bar$bam", + "smithy.api#Integer", + "smithy.example#Bar$baz", + "smithy.example#Bar", + "smithy.example#Foo$bar", + "smithy.example#Foo$foo", + "smithy.example#Foo" + ) ); assertThat( - recursive, - contains( - "smithy.example#Recursive", - "smithy.example#Recursive$b", - "smithy.example#RecursiveList$member", - "smithy.example#RecursiveList", - "smithy.example#Recursive$a" - ) + recursive, + contains( + "smithy.example#Recursive", + "smithy.example#Recursive$b", + "smithy.example#RecursiveList$member", + "smithy.example#RecursiveList", + "smithy.example#Recursive$a" + ) ); } @@ -113,71 +113,71 @@ public void getsRecursiveClosureByShape() { TopologicalIndex index = TopologicalIndex.of(model); assertThat( - index.getRecursiveClosure(model.expectShape(ShapeId.from("smithy.example#MyString"))), - empty() + index.getRecursiveClosure(model.expectShape(ShapeId.from("smithy.example#MyString"))), + empty() ); assertThat( - index.getRecursiveClosure(model.expectShape(ShapeId.from("smithy.example#Recursive$b"))), - not(empty()) + index.getRecursiveClosure(model.expectShape(ShapeId.from("smithy.example#Recursive$b"))), + not(empty()) ); } @Test public void handlesMoreRecursion() { Model recursive = Model.assembler() - .addImport(getClass().getResource("topological-recursion.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("topological-recursion.smithy")) + .assemble() + .unwrap(); TopologicalIndex index = TopologicalIndex.of(recursive); // The topological index must capture all shapes in the index not in the prelude. Set nonPrelude = recursive.shapes() - .filter(FunctionalUtils.not(Prelude::isPreludeShape)) - .collect(Collectors.toSet()); + .filter(FunctionalUtils.not(Prelude::isPreludeShape)) + .collect(Collectors.toSet()); Set topologicalShapes = new HashSet<>(index.getOrderedShapes()); topologicalShapes.addAll(index.getRecursiveShapes()); assertThat(topologicalShapes, equalTo(nonPrelude)); // The ordered shape IDs must be in the this order. List orderedIds = index.getOrderedShapes() - .stream() - .map(Shape::getId) - .map(ShapeId::toString) - .collect(Collectors.toList()); + .stream() + .map(Shape::getId) + .map(ShapeId::toString) + .collect(Collectors.toList()); assertThat( - orderedIds, - contains( - "smithy.example#MyString", - "smithy.example#NonRecursive$foo", - "smithy.example#NonRecursive", - "smithy.example#NonRecursiveList$member", - "smithy.example#NonRecursiveList", - "smithy.example#User$notRecursive", - "smithy.example#UsersMap$key" - ) + orderedIds, + contains( + "smithy.example#MyString", + "smithy.example#NonRecursive$foo", + "smithy.example#NonRecursive", + "smithy.example#NonRecursiveList$member", + "smithy.example#NonRecursiveList", + "smithy.example#User$notRecursive", + "smithy.example#UsersMap$key" + ) ); List recursiveIds = index.getRecursiveShapes() - .stream() - .map(Shape::getId) - .map(ShapeId::toString) - .collect(Collectors.toList()); + .stream() + .map(Shape::getId) + .map(ShapeId::toString) + .collect(Collectors.toList()); assertThat( - recursiveIds, - contains( - "smithy.example#User", - "smithy.example#User$recursiveUser", - "smithy.example#UsersList$member", - "smithy.example#UsersMap$value", - "smithy.example#GetFooInput$foo", - "smithy.example#UsersList", - "smithy.example#UsersMap", - "smithy.example#GetFooInput", - "smithy.example#User$recursiveList", - "smithy.example#User$recursiveMap", - "smithy.example#GetFoo", - "smithy.example#Example" - ) + recursiveIds, + contains( + "smithy.example#User", + "smithy.example#User$recursiveUser", + "smithy.example#UsersList$member", + "smithy.example#UsersMap$value", + "smithy.example#GetFooInput$foo", + "smithy.example#UsersList", + "smithy.example#UsersMap", + "smithy.example#GetFooInput", + "smithy.example#User$recursiveList", + "smithy.example#User$recursiveMap", + "smithy.example#GetFoo", + "smithy.example#Example" + ) ); for (String recursiveId : recursiveIds) { diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/WriterDelegatorTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/WriterDelegatorTest.java index 0e0131e0832..80760f8f74f 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/WriterDelegatorTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/WriterDelegatorTest.java @@ -24,14 +24,14 @@ public class WriterDelegatorTest { public void createsSymbolsAndFilesForShapeWriters() { MockManifest mockManifest = new MockManifest(); SymbolProvider provider = (shape) -> Symbol.builder() - .namespace("com.foo", ".") - .name("Baz") - .definitionFile("com/foo/Baz.bam") - .build(); + .namespace("com.foo", ".") + .name("Baz") + .definitionFile("com/foo/Baz.bam") + .build(); WriterDelegator delegator = new WriterDelegator<>( - mockManifest, - provider, - (f, n) -> new MySimpleWriter(n) + mockManifest, + provider, + (f, n) -> new MySimpleWriter(n) ); Shape shape = StringShape.builder().id("com.foo#Baz").build(); delegator.useShapeWriter(shape, writer -> {}); @@ -44,15 +44,15 @@ public void createsFilesForSymbolWriters() { MockManifest mockManifest = new MockManifest(); SymbolProvider provider = (shape) -> null; WriterDelegator delegator = new WriterDelegator<>( - mockManifest, - provider, - (f, n) -> new MySimpleWriter(n) + mockManifest, + provider, + (f, n) -> new MySimpleWriter(n) ); Symbol symbol = Symbol.builder() - .namespace("com.foo", ".") - .name("Baz") - .definitionFile("com/foo/Baz.bam") - .build(); + .namespace("com.foo", ".") + .name("Baz") + .definitionFile("com/foo/Baz.bam") + .build(); delegator.useSymbolWriter(symbol, writer -> {}); assertThat(delegator.getWriters(), hasKey(Paths.get("com/foo/Baz.bam").toString())); @@ -63,14 +63,14 @@ public void aggregatesDependencies() { MockManifest mockManifest = new MockManifest(); SymbolProvider provider = (shape) -> null; WriterDelegator delegator = new WriterDelegator<>( - mockManifest, - provider, - (f, n) -> new MySimpleWriter(n) + mockManifest, + provider, + (f, n) -> new MySimpleWriter(n) ); SymbolDependency dependency = SymbolDependency.builder() - .packageName("x") - .version("123") - .build(); + .packageName("x") + .version("123") + .build(); delegator.useFileWriter("foo/baz", writer -> { writer.addDependency(dependency); @@ -84,9 +84,9 @@ public void writesNewlineBetweenFiles() { MockManifest mockManifest = new MockManifest(); SymbolProvider provider = (shape) -> null; WriterDelegator delegator = new WriterDelegator<>( - mockManifest, - provider, - (f, n) -> new MySimpleWriter(n) + mockManifest, + provider, + (f, n) -> new MySimpleWriter(n) ); delegator.useFileWriter("foo/baz", writer -> { @@ -98,8 +98,8 @@ public void writesNewlineBetweenFiles() { }); assertThat( - delegator.getWriters().get(Paths.get("foo/baz").toString()).toString(), - equalTo(".\n\n.\n") + delegator.getWriters().get(Paths.get("foo/baz").toString()).toString(), + equalTo(".\n\n.\n") ); } @@ -108,9 +108,9 @@ public void canDisableNewlineBetweenFiles() { MockManifest mockManifest = new MockManifest(); SymbolProvider provider = (shape) -> null; WriterDelegator delegator = new WriterDelegator<>( - mockManifest, - provider, - (f, n) -> new MySimpleWriter(n) + mockManifest, + provider, + (f, n) -> new MySimpleWriter(n) ); delegator.setAutomaticSeparator(""); @@ -123,8 +123,8 @@ public void canDisableNewlineBetweenFiles() { }); assertThat( - delegator.getWriters().get(Paths.get("foo/baz").toString()).toString(), - equalTo("..\n") + delegator.getWriters().get(Paths.get("foo/baz").toString()).toString(), + equalTo("..\n") ); } @@ -132,14 +132,14 @@ public void canDisableNewlineBetweenFiles() { public void flushesAllWriters() { MockManifest mockManifest = new MockManifest(); SymbolProvider provider = (shape) -> Symbol.builder() - .namespace("com.foo", ".") - .name("Baz") - .definitionFile("com/foo/Baz.bam") - .build(); + .namespace("com.foo", ".") + .name("Baz") + .definitionFile("com/foo/Baz.bam") + .build(); WriterDelegator delegator = new WriterDelegator<>( - mockManifest, - provider, - (f, n) -> new MySimpleWriter(n) + mockManifest, + provider, + (f, n) -> new MySimpleWriter(n) ); Shape shape = StringShape.builder().id("com.foo#Baz").build(); delegator.useShapeWriter(shape, writer -> { @@ -155,14 +155,14 @@ public void flushesAllWriters() { public void registersInterceptors() { MockManifest mockManifest = new MockManifest(); SymbolProvider provider = (shape) -> Symbol.builder() - .namespace("com.foo", ".") - .name("Baz") - .definitionFile("com/foo/Baz.bam") - .build(); + .namespace("com.foo", ".") + .name("Baz") + .definitionFile("com/foo/Baz.bam") + .build(); WriterDelegator delegator = new WriterDelegator<>( - mockManifest, - provider, - (f, n) -> new MySimpleWriter(n) + mockManifest, + provider, + (f, n) -> new MySimpleWriter(n) ); CodeInterceptor a = CodeInterceptor.forName("test", (w, s) -> { diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/CodegenDirectorTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/CodegenDirectorTest.java index ba0cfbc3b92..2a836aa737f 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/CodegenDirectorTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/CodegenDirectorTest.java @@ -40,9 +40,9 @@ private static final class TestDirected implements DirectedCodegen directive) { return shape -> Symbol.builder() - .name(shape.getId().getName()) - .namespace(shape.getId().getNamespace(), ".") - .build(); + .name(shape.getId().getName()) + .namespace(shape.getId().getNamespace(), ".") + .build(); } @Override @@ -50,18 +50,18 @@ public TestContext createContext(CreateContextDirective delegator = new WriterDelegator<>( - directive.fileManifest(), - directive.symbolProvider(), - (f, s) -> new TestWriter() + directive.fileManifest(), + directive.symbolProvider(), + (f, s) -> new TestWriter() ); return new TestContext( - directive.model(), - directive.settings(), - directive.symbolProvider(), - directive.fileManifest(), - delegator, - directive.service() + directive.model(), + directive.settings(), + directive.symbolProvider(), + directive.fileManifest(), + delegator, + directive.service() ); } @@ -169,9 +169,9 @@ public void performsCodegen() { CodegenDirector runner = new CodegenDirector<>(); FileManifest manifest = new MockManifest(); Model model = Model.assembler() - .addImport(getClass().getResource("directed-model.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("directed-model.smithy")) + .assemble() + .unwrap(); runner.settings(new TestSettings()); runner.directedCodegen(testDirected); @@ -186,28 +186,28 @@ public void performsCodegen() { // asserts that mixin smithy.example#Paginated is not generated assertThat( - testDirected.generatedShapes, - containsInAnyOrder( - ShapeId.from("smithy.example#Foo"), - ShapeId.from("smithy.example#TheFoo"), - ShapeId.from("smithy.example#ListFooInput"), - ShapeId.from("smithy.example#ListFooOutput"), - ShapeId.from("smithy.example#FooStructure"), - ShapeId.from("smithy.example#FooList"), - ShapeId.from("smithy.example#StringMap"), - ShapeId.from("smithy.example#Status"), - ShapeId.from("smithy.example#FaceCard"), - ShapeId.from("smithy.example#Instruction"), - ShapeId.from("smithy.api#Unit"), - ShapeId.from("smithy.example#ListFoo") - ) + testDirected.generatedShapes, + containsInAnyOrder( + ShapeId.from("smithy.example#Foo"), + ShapeId.from("smithy.example#TheFoo"), + ShapeId.from("smithy.example#ListFooInput"), + ShapeId.from("smithy.example#ListFooOutput"), + ShapeId.from("smithy.example#FooStructure"), + ShapeId.from("smithy.example#FooList"), + ShapeId.from("smithy.example#StringMap"), + ShapeId.from("smithy.example#Status"), + ShapeId.from("smithy.example#FaceCard"), + ShapeId.from("smithy.example#Instruction"), + ShapeId.from("smithy.api#Unit"), + ShapeId.from("smithy.example#ListFoo") + ) ); assertThat( - testDirected.generatedStringTypeEnums, - containsInAnyOrder( - ShapeId.from("smithy.example#Status") - ) + testDirected.generatedStringTypeEnums, + containsInAnyOrder( + ShapeId.from("smithy.example#Status") + ) ); assertThat(testDirected.generatedEnumTypeEnums, empty()); } @@ -218,9 +218,9 @@ public void performsCodegenWithStringEnumsChangedToEnumShapes() { CodegenDirector runner = new CodegenDirector<>(); FileManifest manifest = new MockManifest(); Model model = Model.assembler() - .addImport(getClass().getResource("directed-model.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("directed-model.smithy")) + .assemble() + .unwrap(); runner.settings(new TestSettings()); runner.directedCodegen(testDirected); @@ -236,28 +236,28 @@ public void performsCodegenWithStringEnumsChangedToEnumShapes() { // asserts that mixin smithy.example#Paginated is not generated assertThat( - testDirected.generatedShapes, - containsInAnyOrder( - ShapeId.from("smithy.example#Foo"), - ShapeId.from("smithy.example#TheFoo"), - ShapeId.from("smithy.example#ListFooInput"), - ShapeId.from("smithy.example#ListFooOutput"), - ShapeId.from("smithy.example#FooStructure"), - ShapeId.from("smithy.example#FooList"), - ShapeId.from("smithy.example#StringMap"), - ShapeId.from("smithy.example#Status"), - ShapeId.from("smithy.example#FaceCard"), - ShapeId.from("smithy.example#Instruction"), - ShapeId.from("smithy.api#Unit"), - ShapeId.from("smithy.example#ListFoo") - ) + testDirected.generatedShapes, + containsInAnyOrder( + ShapeId.from("smithy.example#Foo"), + ShapeId.from("smithy.example#TheFoo"), + ShapeId.from("smithy.example#ListFooInput"), + ShapeId.from("smithy.example#ListFooOutput"), + ShapeId.from("smithy.example#FooStructure"), + ShapeId.from("smithy.example#FooList"), + ShapeId.from("smithy.example#StringMap"), + ShapeId.from("smithy.example#Status"), + ShapeId.from("smithy.example#FaceCard"), + ShapeId.from("smithy.example#Instruction"), + ShapeId.from("smithy.api#Unit"), + ShapeId.from("smithy.example#ListFoo") + ) ); assertThat( - testDirected.generatedEnumTypeEnums, - containsInAnyOrder( - ShapeId.from("smithy.example#Status") - ) + testDirected.generatedEnumTypeEnums, + containsInAnyOrder( + ShapeId.from("smithy.example#Status") + ) ); assertThat(testDirected.generatedStringTypeEnums, empty()); } @@ -268,9 +268,9 @@ public void sortsShapesWithDefaultTopologicalOrder() { CodegenDirector runner = new CodegenDirector<>(); FileManifest manifest = new MockManifest(); Model model = Model.assembler() - .addImport(getClass().getResource("needs-sorting.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("needs-sorting.smithy")) + .assemble() + .unwrap(); runner.settings(new TestSettings()); runner.directedCodegen(testDirected); @@ -284,19 +284,19 @@ public void sortsShapesWithDefaultTopologicalOrder() { runner.run(); assertThat( - testDirected.generatedShapes, - contains( - ShapeId.from("smithy.example#D"), - ShapeId.from("smithy.example#C"), - ShapeId.from("smithy.example#B"), - ShapeId.from("smithy.example#A"), - ShapeId.from("smithy.example#FooOperationOutput"), - ShapeId.from("smithy.example#RecursiveA"), - ShapeId.from("smithy.example#RecursiveB"), - ShapeId.from("smithy.example#FooOperationInput"), - ShapeId.from("smithy.example#FooOperation"), - ShapeId.from("smithy.example#Foo") - ) + testDirected.generatedShapes, + contains( + ShapeId.from("smithy.example#D"), + ShapeId.from("smithy.example#C"), + ShapeId.from("smithy.example#B"), + ShapeId.from("smithy.example#A"), + ShapeId.from("smithy.example#FooOperationOutput"), + ShapeId.from("smithy.example#RecursiveA"), + ShapeId.from("smithy.example#RecursiveB"), + ShapeId.from("smithy.example#FooOperationInput"), + ShapeId.from("smithy.example#FooOperation"), + ShapeId.from("smithy.example#Foo") + ) ); } @@ -306,9 +306,9 @@ public void testShapesGenerationWithAlphabeticalOrder() { CodegenDirector runner = new CodegenDirector<>(); FileManifest manifest = new MockManifest(); Model model = Model.assembler() - .addImport(getClass().getResource("needs-sorting.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("needs-sorting.smithy")) + .assemble() + .unwrap(); runner.settings(new TestSettings()); runner.directedCodegen(testDirected); @@ -321,19 +321,19 @@ public void testShapesGenerationWithAlphabeticalOrder() { runner.run(); assertThat( - testDirected.generatedShapes, - contains( - ShapeId.from("smithy.example#A"), - ShapeId.from("smithy.example#B"), - ShapeId.from("smithy.example#C"), - ShapeId.from("smithy.example#D"), - ShapeId.from("smithy.example#FooOperation"), - ShapeId.from("smithy.example#FooOperationInput"), - ShapeId.from("smithy.example#FooOperationOutput"), - ShapeId.from("smithy.example#RecursiveA"), - ShapeId.from("smithy.example#RecursiveB"), - ShapeId.from("smithy.example#Foo") - ) + testDirected.generatedShapes, + contains( + ShapeId.from("smithy.example#A"), + ShapeId.from("smithy.example#B"), + ShapeId.from("smithy.example#C"), + ShapeId.from("smithy.example#D"), + ShapeId.from("smithy.example#FooOperation"), + ShapeId.from("smithy.example#FooOperationInput"), + ShapeId.from("smithy.example#FooOperationOutput"), + ShapeId.from("smithy.example#RecursiveA"), + ShapeId.from("smithy.example#RecursiveB"), + ShapeId.from("smithy.example#Foo") + ) ); } @@ -343,9 +343,9 @@ public void testShapesGenerationWithoutOrder() { CodegenDirector runner = new CodegenDirector<>(); FileManifest manifest = new MockManifest(); Model model = Model.assembler() - .addImport(getClass().getResource("needs-sorting.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("needs-sorting.smithy")) + .assemble() + .unwrap(); runner.settings(new TestSettings()); runner.directedCodegen(testDirected); @@ -358,19 +358,19 @@ public void testShapesGenerationWithoutOrder() { runner.run(); assertThat( - testDirected.generatedShapes, - contains( - ShapeId.from("smithy.example#FooOperation"), - ShapeId.from("smithy.example#FooOperationOutput"), - ShapeId.from("smithy.example#A"), - ShapeId.from("smithy.example#B"), - ShapeId.from("smithy.example#C"), - ShapeId.from("smithy.example#D"), - ShapeId.from("smithy.example#FooOperationInput"), - ShapeId.from("smithy.example#RecursiveA"), - ShapeId.from("smithy.example#RecursiveB"), - ShapeId.from("smithy.example#Foo") - ) + testDirected.generatedShapes, + contains( + ShapeId.from("smithy.example#FooOperation"), + ShapeId.from("smithy.example#FooOperationOutput"), + ShapeId.from("smithy.example#A"), + ShapeId.from("smithy.example#B"), + ShapeId.from("smithy.example#C"), + ShapeId.from("smithy.example#D"), + ShapeId.from("smithy.example#FooOperationInput"), + ShapeId.from("smithy.example#RecursiveA"), + ShapeId.from("smithy.example#RecursiveB"), + ShapeId.from("smithy.example#Foo") + ) ); } @@ -380,16 +380,16 @@ public void testConfiguresIntegrations() { CodegenDirector runner = new CodegenDirector<>(); FileManifest manifest = new MockManifest(); Model model = Model.assembler() - .addImport(getClass().getResource("needs-sorting.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("needs-sorting.smithy")) + .assemble() + .unwrap(); ObjectNode integrationSettings = Node.objectNode().withMember("spam", "eggs"); ObjectNode allIntegrationSettings = Node.objectNode() - .withMember("capturing-integration", integrationSettings); + .withMember("capturing-integration", integrationSettings); ObjectNode settings = Node.objectNode() - .withMember("foo", "hi") - .withMember("integrations", allIntegrationSettings); + .withMember("foo", "hi") + .withMember("integrations", allIntegrationSettings); runner.settings(TestSettings.class, settings); runner.directedCodegen(testDirected); runner.fileManifest(manifest); diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/DirectiveTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/DirectiveTest.java index c1a3e2eb7a8..9cdbc434a09 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/DirectiveTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/DirectiveTest.java @@ -22,8 +22,8 @@ public class DirectiveTest { public void providesOperations() { TestContext context = TestContext.create("directive-operations.smithy", ShapeId.from("smithy.example#Foo")); GenerateServiceDirective d = new GenerateServiceDirective<>( - context, - context.service() + context, + context.service() ); Set operationShapes = d.operations(); @@ -32,11 +32,11 @@ public void providesOperations() { Set operations = operationShapes.stream().map(Shape::getId).collect(Collectors.toSet()); assertThat( - operations, - containsInAnyOrder( - ShapeId.from("smithy.example#GetA"), - ShapeId.from("smithy.example#DeleteA") - ) + operations, + containsInAnyOrder( + ShapeId.from("smithy.example#GetA"), + ShapeId.from("smithy.example#DeleteA") + ) ); } @@ -45,8 +45,8 @@ public void providesOperations() { public void providesConnectedShapes() { TestContext context = TestContext.create("directive-operations.smithy", ShapeId.from("smithy.example#Foo")); GenerateServiceDirective d = new GenerateServiceDirective<>( - context, - context.service() + context, + context.service() ); Map connected = d.connectedShapes(); diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/GenerateServiceDirectiveTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/GenerateServiceDirectiveTest.java index 34233b9b447..dddb1ea13d6 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/GenerateServiceDirectiveTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/GenerateServiceDirectiveTest.java @@ -25,8 +25,8 @@ public void getsServiceTitleWithExplicitTrait() { @Test public void getsServiceTitleFromSymbolDefault() { GenerateServiceDirective d = createDirective( - "service-title.smithy", - ShapeId.from("smithy.example#Foo2") + "service-title.smithy", + ShapeId.from("smithy.example#Foo2") ); assertThat(d.serviceTitle(), equalTo("Foo2")); diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/TestContext.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/TestContext.java index b3afae36adc..da47314e26b 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/TestContext.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/directed/TestContext.java @@ -28,27 +28,27 @@ final class TestContext implements CodegenContext Symbol.builder() - .name(shape.getId().getName()) - .namespace("example", ".") - .build(); + .name(shape.getId().getName()) + .namespace("example", ".") + .build(); WriterDelegator delegator = new WriterDelegator<>(manifest, symbolProvider, (file, namespace) -> { throw new UnsupportedOperationException(); }); Model model = Model.assembler() - .addImport(TestContext.class.getResource(modelFile)) - .assemble() - .unwrap(); + .addImport(TestContext.class.getResource(modelFile)) + .assemble() + .unwrap(); ServiceShape service = model.expectShape(serviceId, ServiceShape.class); return new TestContext(model, new TestSettings(), symbolProvider, manifest, delegator, service); } TestContext( - Model model, - TestSettings settings, - SymbolProvider symbolProvider, - FileManifest fileManifest, - WriterDelegator delegator, - ServiceShape service + Model model, + TestSettings settings, + SymbolProvider symbolProvider, + FileManifest fileManifest, + WriterDelegator delegator, + ServiceShape service ) { this.model = model; this.settings = settings; diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/ArtifactDefinitionsTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/ArtifactDefinitionsTest.java index 653ac4304f3..f8ad490ae12 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/ArtifactDefinitionsTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/ArtifactDefinitionsTest.java @@ -22,18 +22,18 @@ class ArtifactDefinitionsTest { @Test void assertsToNodeWorksWithCorrectFields() { ArtifactDefinitions artifactDefinitions = ArtifactDefinitions.builder() - .addType("t1", "t1val") - .addType("t2", "t2val") - .addTag("tag1", "tag1val") - .addTag("tag2", "tag2val") - .build(); + .addType("t1", "t1val") + .addType("t2", "t2val") + .addTag("tag1", "tag1val") + .addTag("tag2", "tag2val") + .build(); ObjectNode node = artifactDefinitions.toNode(); ObjectNode builtNode = ObjectNode.objectNodeBuilder() - .withMember(ArtifactDefinitions.TAGS_TEXT, ObjectNode.fromStringMap(artifactDefinitions.getTags())) - .withMember(ArtifactDefinitions.TYPE_TEXT, ObjectNode.fromStringMap(artifactDefinitions.getTypes())) - .build(); + .withMember(ArtifactDefinitions.TAGS_TEXT, ObjectNode.fromStringMap(artifactDefinitions.getTags())) + .withMember(ArtifactDefinitions.TYPE_TEXT, ObjectNode.fromStringMap(artifactDefinitions.getTypes())) + .build(); Assertions.assertDoesNotThrow(() -> Node.assertEquals(node, builtNode)); } @@ -41,16 +41,16 @@ void assertsToNodeWorksWithCorrectFields() { @Test void assertsFromNodeWorksWithCorrectFields() { ArtifactDefinitions artifactDefinitions = ArtifactDefinitions.builder() - .addType("t1", "t1val") - .addType("t2", "t2val") - .addTag("tag1", "tag1val") - .addTag("tag2", "tag2val") - .build(); + .addType("t1", "t1val") + .addType("t2", "t2val") + .addTag("tag1", "tag1val") + .addTag("tag2", "tag2val") + .build(); ObjectNode node = ObjectNode.objectNodeBuilder() - .withMember(ArtifactDefinitions.TAGS_TEXT, ObjectNode.fromStringMap(artifactDefinitions.getTags())) - .withMember(ArtifactDefinitions.TYPE_TEXT, ObjectNode.fromStringMap(artifactDefinitions.getTypes())) - .build(); + .withMember(ArtifactDefinitions.TAGS_TEXT, ObjectNode.fromStringMap(artifactDefinitions.getTags())) + .withMember(ArtifactDefinitions.TYPE_TEXT, ObjectNode.fromStringMap(artifactDefinitions.getTypes())) + .build(); ArtifactDefinitions artifactDefinitions2 = ArtifactDefinitions.fromNode(node); @@ -61,15 +61,15 @@ void assertsFromNodeWorksWithCorrectFields() { @Test void assertsFromDefinitionsFileWorksWithRequiredFields() throws URISyntaxException, FileNotFoundException { ArtifactDefinitions artifactDefinitions = createFromFileHelper( - getClass().getResource("definitions.json").toURI() + getClass().getResource("definitions.json").toURI() ); ArtifactDefinitions artifactDefinitions2 = ArtifactDefinitions.builder() - .addType("t1", "t1val") - .addType("t2", "t2val") - .addTag("tag1", "tag1val") - .addTag("tag2", "tag2val") - .build(); + .addType("t1", "t1val") + .addType("t2", "t2val") + .addTag("tag1", "tag1val") + .addTag("tag2", "tag2val") + .build(); assertThat(artifactDefinitions.getTags(), equalTo(artifactDefinitions2.getTags())); assertThat(artifactDefinitions.getTypes(), equalTo(artifactDefinitions2.getTypes())); @@ -79,9 +79,9 @@ void assertsFromDefinitionsFileWorksWithRequiredFields() throws URISyntaxExcepti void assertBuildThrowsWithoutRequiredTypesField() { Assertions.assertThrows(IllegalStateException.class, () -> { ArtifactDefinitions.builder() - .addTag("tag1", "tag1val") - .addTag("tag2", "tag2val") - .build(); + .addTag("tag1", "tag1val") + .addTag("tag2", "tag2val") + .build(); }); } @@ -89,9 +89,9 @@ void assertBuildThrowsWithoutRequiredTypesField() { void assertBuildThrowsWithoutRequiredTagsField() { Assertions.assertThrows(IllegalStateException.class, () -> { ArtifactDefinitions.builder() - .addType("t1", "t1val") - .addType("t2", "t2val") - .build(); + .addType("t1", "t1val") + .addType("t2", "t2val") + .build(); }); } diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/ShapeLinkTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/ShapeLinkTest.java index 7050e09972f..baa7a2ea927 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/ShapeLinkTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/ShapeLinkTest.java @@ -19,26 +19,26 @@ class ShapeLinkTest { @Test void assertsToNodeWorksWithAllFields() { ShapeLink shapeLink = ShapeLink.builder() - .addTag("tag") - .file("file") - .id("id") - .type("type") - .line(1) - .column(2) - .build(); + .addTag("tag") + .file("file") + .id("id") + .type("type") + .line(1) + .column(2) + .build(); ObjectNode node = shapeLink.toNode(); assertThat(node.getStringMember(ShapeLink.TYPE_TEXT).get().getValue(), equalTo("type")); assertThat(node.getNumberMember(ShapeLink.LINE_TEXT).get().getValue(), equalTo(1)); assertThat( - node.getArrayMember(ShapeLink.TAGS_TEXT) - .get() - .get(0) - .get() - .expectStringNode() - .getValue(), - equalTo("tag") + node.getArrayMember(ShapeLink.TAGS_TEXT) + .get() + .get(0) + .get() + .expectStringNode() + .getValue(), + equalTo("tag") ); } @@ -48,13 +48,13 @@ void assertsFromNodeWorksWithAllFields() { tags.add("tag"); Node node = ObjectNode.objectNodeBuilder() - .withMember(ShapeLink.ID_TEXT, "id") - .withMember(ShapeLink.TYPE_TEXT, "type") - .withOptionalMember(ShapeLink.TAGS_TEXT, Optional.of(tags).map(Node::fromStrings)) - .withOptionalMember(ShapeLink.FILE_TEXT, Optional.of("file").map(Node::from)) - .withOptionalMember(ShapeLink.LINE_TEXT, Optional.of(1).map(Node::from)) - .withOptionalMember(ShapeLink.COLUMN_TEXT, Optional.of(2).map(Node::from)) - .build(); + .withMember(ShapeLink.ID_TEXT, "id") + .withMember(ShapeLink.TYPE_TEXT, "type") + .withOptionalMember(ShapeLink.TAGS_TEXT, Optional.of(tags).map(Node::fromStrings)) + .withOptionalMember(ShapeLink.FILE_TEXT, Optional.of("file").map(Node::from)) + .withOptionalMember(ShapeLink.LINE_TEXT, Optional.of(1).map(Node::from)) + .withOptionalMember(ShapeLink.COLUMN_TEXT, Optional.of(2).map(Node::from)) + .build(); ShapeLink shapeLink2 = ShapeLink.fromNode(node); @@ -70,12 +70,12 @@ void assertsFromNodeWorksWithAllFields() { void assertBuildThrowsWithoutRequiredTypesField() { Assertions.assertThrows(IllegalStateException.class, () -> { ShapeLink.builder() - .addTag("tag") - .file("file") - .id("id") - .line(1) - .column(2) - .build(); + .addTag("tag") + .file("file") + .id("id") + .line(1) + .column(2) + .build(); }); } @@ -83,12 +83,12 @@ void assertBuildThrowsWithoutRequiredTypesField() { void assertBuildThrowsWithoutRequiredIdField() { Assertions.assertThrows(IllegalStateException.class, () -> { ShapeLink.builder() - .addTag("tag") - .file("file") - .line(1) - .type("type") - .column(2) - .build(); + .addTag("tag") + .file("file") + .line(1) + .type("type") + .column(2) + .build(); }); } diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/TraceFileTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/TraceFileTest.java index be511ccbaf5..4942a3af27c 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/TraceFileTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/TraceFileTest.java @@ -47,13 +47,13 @@ void assertWriteTraceFileFromScratchWorks() throws IOException, URISyntaxExcepti String typeVersion = "1.8"; String homepage = "https://github.com/aws/aws-sdk-java-v2/"; TraceMetadata traceMetadata = TraceMetadata.builder() - .id(id) - .version(version) - .type(type) - .setTimestampAsNow() - .homepage(homepage) - .typeVersion(typeVersion) - .build(); + .id(id) + .version(version) + .type(type) + .setTimestampAsNow() + .homepage(homepage) + .typeVersion(typeVersion) + .build(); /** * Building Definitions - this example uses addTag and addType to add individual key value pairs. @@ -61,11 +61,11 @@ void assertWriteTraceFileFromScratchWorks() throws IOException, URISyntaxExcepti * having to add them individually. */ ArtifactDefinitions artifactDefinitions = ArtifactDefinitions.builder() - .addTag("service", "Service client") - .addTag("request", "AWS SDK request type") - .addTag("requestBuilder", "AWS SDK request builder") - .addType("TYPE", "Class, interface (including annotation type), or enum declaration") - .build(); + .addTag("service", "Service client") + .addTag("request", "AWS SDK request type") + .addTag("requestBuilder", "AWS SDK request builder") + .addType("TYPE", "Class, interface (including annotation type), or enum declaration") + .build(); /** * Building TraceFile - build the trace file by passing the different objects to the builder @@ -75,41 +75,41 @@ void assertWriteTraceFileFromScratchWorks() throws IOException, URISyntaxExcepti * setting it. */ TraceFile.Builder traceFileBuilder = TraceFile.builder() - .metadata(traceMetadata) - .definitions(artifactDefinitions); + .metadata(traceMetadata) + .definitions(artifactDefinitions); //adding one ShapeLink to TraceFile type = "TYPE"; id = "software.amazon.awssdk.services.snowball.SnowballClient"; traceFileBuilder.addShapeLink( - "com.amazonaws.snowball#Snowball", - ShapeLink.builder() - .type(type) - .id(id) - .addTag("service") - .build() + "com.amazonaws.snowball#Snowball", + ShapeLink.builder() + .type(type) + .id(id) + .addTag("service") + .build() ); //adding multiple ShapeLinks for the same ShapeId; can also add a List type = "TYPE"; id = "software.amazon.awssdk.services.snowball.model.ListClusterJobsRequest$Builder"; traceFileBuilder.addShapeLink( - "com.amazonaws.snowball#ListClustersRequest", - ShapeLink.builder() - .type(type) - .id(id) - .addTag("requestBuilder") - .build() + "com.amazonaws.snowball#ListClustersRequest", + ShapeLink.builder() + .type(type) + .id(id) + .addTag("requestBuilder") + .build() ); type = "TYPE"; id = "software.amazon.awssdk.services.snowball.model.ListClusterJobsRequest"; traceFileBuilder.addShapeLink( - "com.amazonaws.snowball#ListClustersRequest", - ShapeLink.builder() - .type(type) - .id(id) - .addTag("request") - .build() + "com.amazonaws.snowball#ListClustersRequest", + ShapeLink.builder() + .type(type) + .id(id) + .addTag("request") + .build() ); //finally, build the TraceFile @@ -138,16 +138,16 @@ void assertWriteTraceFileFromScratchWorks() throws IOException, URISyntaxExcepti //few assorted checks assertThat(traceFile2.getMetadata().getId(), equalTo("software.amazon.awssdk.services:snowball:2.10.79")); assertThat( - traceFile2.getArtifactDefinitions().get().getTags().keySet(), - containsInAnyOrder( - "service", - "request", - "requestBuilder" - ) + traceFile2.getArtifactDefinitions().get().getTags().keySet(), + containsInAnyOrder( + "service", + "request", + "requestBuilder" + ) ); assertThat( - traceFile2.getShapes().get(ShapeId.from("com.amazonaws.snowball#Snowball")).get(0).getType(), - equalTo("TYPE") + traceFile2.getShapes().get(ShapeId.from("com.amazonaws.snowball#Snowball")).get(0).getType(), + equalTo("TYPE") ); assertThat(traceFile2.getSmithyTrace(), equalTo("1.0")); } @@ -158,18 +158,18 @@ void assertsParseTraceFileWorksWithCorrectTraceFile() throws URISyntaxException, assertThat(traceFile.getMetadata().getId(), equalTo("software.amazon.awssdk.services:snowball:2.10.79")); assertThat( - traceFile.getArtifactDefinitions().get().getTags().keySet(), - containsInAnyOrder( - "service", - "request", - "response", - "requestBuilder", - "responseBuilder" - ) + traceFile.getArtifactDefinitions().get().getTags().keySet(), + containsInAnyOrder( + "service", + "request", + "response", + "requestBuilder", + "responseBuilder" + ) ); assertThat( - traceFile.getShapes().get(ShapeId.from("com.amazonaws.snowball#Snowball")).get(0).getType(), - equalTo("TYPE") + traceFile.getShapes().get(ShapeId.from("com.amazonaws.snowball#Snowball")).get(0).getType(), + equalTo("TYPE") ); assertThat(traceFile.getSmithyTrace(), equalTo("1.0")); } @@ -182,18 +182,18 @@ void assertsWriteTraceFileWorksWithCorrectTraceFile() throws URISyntaxException, assertThat(traceFile2.getMetadata().getId(), equalTo("software.amazon.awssdk.services:snowball:2.10.79")); assertThat( - traceFile2.getArtifactDefinitions().get().getTags().keySet(), - containsInAnyOrder( - "service", - "request", - "response", - "requestBuilder", - "responseBuilder" - ) + traceFile2.getArtifactDefinitions().get().getTags().keySet(), + containsInAnyOrder( + "service", + "request", + "response", + "requestBuilder", + "responseBuilder" + ) ); assertThat( - traceFile2.getShapes().get(ShapeId.from("com.amazonaws.snowball#Snowball")).get(0).getType(), - equalTo("TYPE") + traceFile2.getShapes().get(ShapeId.from("com.amazonaws.snowball#Snowball")).get(0).getType(), + equalTo("TYPE") ); assertThat(traceFile2.getSmithyTrace(), equalTo("1.0")); } @@ -210,8 +210,8 @@ void assertParseWriteWorksWithoutDefinitions() throws IOException, URISyntaxExce assertThat(traceFile.getMetadata().getId(), equalTo("software.amazon.awssdk.services:snowball:2.10.79")); assertThat( - traceFile.getShapes().get(ShapeId.from("com.amazonaws.snowball#Snowball")).get(0).getType(), - equalTo("TYPE") + traceFile.getShapes().get(ShapeId.from("com.amazonaws.snowball#Snowball")).get(0).getType(), + equalTo("TYPE") ); assertThat(traceFile.getSmithyTrace(), equalTo("1.0")); } @@ -227,15 +227,15 @@ void buildThrowsOnInvalidType() throws ExpectationNotMetException { Assertions.assertThrows(ExpectationNotMetException.class, () -> { TraceFile traceFile = parseTraceFileFromFile(getClass().getResource("trace-file.json").toURI()); traceFile.toBuilder() - .addShapeLink( - "com.amazonaws.snowball#Snowball", - ShapeLink - .builder() - .id("id") - .type("fake_type") - .build() - ) - .build(); + .addShapeLink( + "com.amazonaws.snowball#Snowball", + ShapeLink + .builder() + .id("id") + .type("fake_type") + .build() + ) + .build(); }); } @@ -244,16 +244,16 @@ void buildThrowsOnInvalidTag() throws ExpectationNotMetException { Assertions.assertThrows(ExpectationNotMetException.class, () -> { TraceFile traceFile = parseTraceFileFromFile(getClass().getResource("trace-file.json").toURI()); traceFile.toBuilder() - .addShapeLink( - "com.amazonaws.snowball#Snowball", - ShapeLink - .builder() - .id("id") - .type("TYPE") - .addTag("fake_tag") - .build() - ) - .build(); + .addShapeLink( + "com.amazonaws.snowball#Snowball", + ShapeLink + .builder() + .id("id") + .type("TYPE") + .addTag("fake_tag") + .build() + ) + .build(); }); } @@ -261,7 +261,7 @@ void buildThrowsOnInvalidTag() throws ExpectationNotMetException { void validateModelDoesNotThrowOnValidTraceFileModelPair() throws ExpectationNotMetException, URISyntaxException, FileNotFoundException { Assertions.assertDoesNotThrow(() -> { TraceFile traceFile = parseTraceFileFromFile( - getClass().getResource("trace-for-simple-service-validation.json").toURI() + getClass().getResource("trace-for-simple-service-validation.json").toURI() ); traceFile.validateModel(assembleModelTestHelper("simple-service.smithy")); }); @@ -271,7 +271,7 @@ void validateModelDoesNotThrowOnValidTraceFileModelPair() throws ExpectationNotM void validateModelThrowsOnTraceFileWithoutAllModelShapeIDs() throws ExpectationNotMetException, URISyntaxException, FileNotFoundException { Assertions.assertThrows(ExpectationNotMetException.class, () -> { TraceFile traceFile = parseTraceFileFromFile( - getClass().getResource("trace-for-model-validation.json").toURI() + getClass().getResource("trace-for-model-validation.json").toURI() ); traceFile.validateModel(assembleModelTestHelper("service-with-shapeids.smithy")); }); @@ -281,7 +281,7 @@ void validateModelThrowsOnTraceFileWithoutAllModelShapeIDs() throws ExpectationN void validateModelThrowsOnModelWithoutAllTraceFileShapeIds() throws ExpectationNotMetException, URISyntaxException, FileNotFoundException { Assertions.assertThrows(ExpectationNotMetException.class, () -> { TraceFile traceFile = parseTraceFileFromFile( - getClass().getResource("trace-for-simple-service-validation.json").toURI() + getClass().getResource("trace-for-simple-service-validation.json").toURI() ); Model model = assembleModelTestHelper("simple-service.smithy"); //add a shape to our model that's not in our trace file @@ -339,9 +339,9 @@ MockManifest writeTraceFileTestHelper(TraceFile traceFile, String fileName) thro Model assembleModelTestHelper(String modelResourceName) { return Model.assembler() - .addImport(getClass().getResource(modelResourceName)) - .assemble() - .unwrap(); + .addImport(getClass().getResource(modelResourceName)) + .assemble() + .unwrap(); } } diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/TraceMetadataTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/TraceMetadataTest.java index 542eb24b81a..4ca70bba852 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/TraceMetadataTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/TraceMetadataTest.java @@ -18,13 +18,13 @@ class TraceMetadataTest { @Test void assertsToNodeWorksWithRequiredFields() { TraceMetadata am = new TraceMetadata.Builder() - .id("a") - .version("b") - .type("c") - .timestamp("d") - .homepage("hp") - .typeVersion("tv") - .build(); + .id("a") + .version("b") + .type("c") + .timestamp("d") + .homepage("hp") + .typeVersion("tv") + .build(); ObjectNode node = am.toNode(); @@ -39,13 +39,13 @@ void assertsToNodeWorksWithRequiredFields() { @Test void assertsFromNodeWorksWithRequiredFields() { Node node = ObjectNode.objectNodeBuilder() - .withMember(TraceMetadata.ID_TEXT, "id") - .withMember(TraceMetadata.VERSION_TEXT, "version") - .withMember(TraceMetadata.TYPE_TEXT, "type") - .withMember(TraceMetadata.TIMESTAMP_TEXT, "timestamp") - .withOptionalMember(TraceMetadata.TYPE_VERSION_TEXT, Optional.of("type").map(Node::from)) - .withOptionalMember(TraceMetadata.HOMEPAGE_TEXT, Optional.of("homepage").map(Node::from)) - .build(); + .withMember(TraceMetadata.ID_TEXT, "id") + .withMember(TraceMetadata.VERSION_TEXT, "version") + .withMember(TraceMetadata.TYPE_TEXT, "type") + .withMember(TraceMetadata.TIMESTAMP_TEXT, "timestamp") + .withOptionalMember(TraceMetadata.TYPE_VERSION_TEXT, Optional.of("type").map(Node::from)) + .withOptionalMember(TraceMetadata.HOMEPAGE_TEXT, Optional.of("homepage").map(Node::from)) + .build(); TraceMetadata am2 = TraceMetadata.fromNode(node); @@ -61,10 +61,10 @@ void assertsFromNodeWorksWithRequiredFields() { void assertBuildThrowsWithoutRequiredId() { Assertions.assertThrows(IllegalStateException.class, () -> { TraceMetadata am = new TraceMetadata.Builder() - .version("b") - .type("c") - .setTimestampAsNow() - .build(); + .version("b") + .type("c") + .setTimestampAsNow() + .build(); }); } @@ -72,10 +72,10 @@ void assertBuildThrowsWithoutRequiredId() { void assertBuildThrowsWithoutRequiredVersion() { Assertions.assertThrows(IllegalStateException.class, () -> { TraceMetadata am = new TraceMetadata.Builder() - .id("a") - .type("c") - .setTimestampAsNow() - .build(); + .id("a") + .type("c") + .setTimestampAsNow() + .build(); }); } @@ -83,10 +83,10 @@ void assertBuildThrowsWithoutRequiredVersion() { void assertBuildThrowsWithoutRequiredType() { Assertions.assertThrows(IllegalStateException.class, () -> { TraceMetadata am = new TraceMetadata.Builder() - .id("a") - .version("b") - .setTimestampAsNow() - .build(); + .id("a") + .version("b") + .setTimestampAsNow() + .build(); }); } @@ -94,10 +94,10 @@ void assertBuildThrowsWithoutRequiredType() { void assertBuildThrowsWithoutRequiredTimestamp() { Assertions.assertThrows(IllegalStateException.class, () -> { TraceMetadata am = new TraceMetadata.Builder() - .id("a") - .version("b") - .type("c") - .build(); + .id("a") + .version("b") + .type("c") + .build(); }); } diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/TracingSymbolProviderTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/TracingSymbolProviderTest.java index 65a87a0ea00..b639369b24b 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/TracingSymbolProviderTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/trace/TracingSymbolProviderTest.java @@ -24,11 +24,11 @@ class TracingSymbolProviderTest { void assertBuildDoesNotThrowWithAllFields() { Assertions.assertDoesNotThrow(() -> { TracingSymbolProvider.builder() - .metadata(constructTraceMetadata()) - .artifactDefinitions(constructArtifactDefinitions()) - .symbolProvider(new TestSymbolProvider()) - .shapeLinkCreator(constructFunction()) - .build(); + .metadata(constructTraceMetadata()) + .artifactDefinitions(constructArtifactDefinitions()) + .symbolProvider(new TestSymbolProvider()) + .shapeLinkCreator(constructFunction()) + .build(); }); } @@ -36,10 +36,10 @@ void assertBuildDoesNotThrowWithAllFields() { void assertBuildDoesNotThrowWithRequiredFields() { Assertions.assertDoesNotThrow(() -> { TracingSymbolProvider.builder() - .metadata(constructTraceMetadata()) - .symbolProvider(new TestSymbolProvider()) - .shapeLinkCreator(constructFunction()) - .build(); + .metadata(constructTraceMetadata()) + .symbolProvider(new TestSymbolProvider()) + .shapeLinkCreator(constructFunction()) + .build(); }); } @@ -47,54 +47,54 @@ void assertBuildDoesNotThrowWithRequiredFields() { void assertBuildDoesNotThrowWithDefaultTraceMetadata() { Assertions.assertDoesNotThrow(() -> { TracingSymbolProvider.builder() - .setTraceMetadataAsDefault("Java") - .symbolProvider(new TestSymbolProvider()) - .shapeLinkCreator(constructFunction()) - .build(); + .setTraceMetadataAsDefault("Java") + .symbolProvider(new TestSymbolProvider()) + .shapeLinkCreator(constructFunction()) + .build(); }); } @Test void assertBuildFailsWithoutSymbolProvider() { Assertions.assertThrows( - IllegalStateException.class, - () -> TracingSymbolProvider.builder() - .metadata(constructTraceMetadata()) - .shapeLinkCreator(constructFunction()) - .build() + IllegalStateException.class, + () -> TracingSymbolProvider.builder() + .metadata(constructTraceMetadata()) + .shapeLinkCreator(constructFunction()) + .build() ); } @Test void assertBuildFailsWithoutTraceMetadata() { Assertions.assertThrows( - IllegalStateException.class, - () -> TracingSymbolProvider.builder() - .symbolProvider(new TestSymbolProvider()) - .shapeLinkCreator(constructFunction()) - .build() + IllegalStateException.class, + () -> TracingSymbolProvider.builder() + .symbolProvider(new TestSymbolProvider()) + .shapeLinkCreator(constructFunction()) + .build() ); } @Test void assertBuildFailsWithoutShapeLinkCreator() { Assertions.assertThrows( - IllegalStateException.class, - () -> TracingSymbolProvider.builder() - .metadata(constructTraceMetadata()) - .symbolProvider(new TestSymbolProvider()) - .build() + IllegalStateException.class, + () -> TracingSymbolProvider.builder() + .metadata(constructTraceMetadata()) + .symbolProvider(new TestSymbolProvider()) + .build() ); } @Test void assertToSymbolShapeLinkCreatorCreatesShapeLink() { TracingSymbolProvider tracingSymbolProvider = TracingSymbolProvider.builder() - .metadata(constructTraceMetadata()) - .artifactDefinitions(constructArtifactDefinitions()) - .symbolProvider(new TestSymbolProvider()) - .shapeLinkCreator(constructFunction()) - .build(); + .metadata(constructTraceMetadata()) + .artifactDefinitions(constructArtifactDefinitions()) + .symbolProvider(new TestSymbolProvider()) + .shapeLinkCreator(constructFunction()) + .build(); Shape shape = StringShape.builder().id("namespace.foo#baz").build(); @@ -111,11 +111,11 @@ void assertToSymbolShapeLinkCreatorCreatesShapeLink() { @Test void assertToSymbolDoesNotDuplicateShapeLinks() { TracingSymbolProvider tracingSymbolProvider = TracingSymbolProvider.builder() - .metadata(constructTraceMetadata()) - .artifactDefinitions(constructArtifactDefinitions()) - .symbolProvider(new TestSymbolProvider()) - .shapeLinkCreator(constructFunction()) - .build(); + .metadata(constructTraceMetadata()) + .artifactDefinitions(constructArtifactDefinitions()) + .symbolProvider(new TestSymbolProvider()) + .shapeLinkCreator(constructFunction()) + .build(); Shape shape = StringShape.builder().id("namespace.foo#baz").build(); @@ -130,28 +130,28 @@ void assertToSymbolDoesNotDuplicateShapeLinks() { ArtifactDefinitions constructArtifactDefinitions() { return ArtifactDefinitions.builder() - .addTag("service", "Service client") - .addType("TYPE", "Class, interface (including annotation type), or enum declaration") - .build(); + .addTag("service", "Service client") + .addType("TYPE", "Class, interface (including annotation type), or enum declaration") + .build(); } TraceMetadata constructTraceMetadata() { return TraceMetadata.builder() - .id("software.amazon.awssdk.services:snowball:2.10.79") - .version("2.10.79") - .type("Java") - .setTimestampAsNow() - .build(); + .id("software.amazon.awssdk.services:snowball:2.10.79") + .version("2.10.79") + .type("Java") + .setTimestampAsNow() + .build(); } BiFunction> constructFunction() { return (shape, symbol) -> { List list = new ArrayList<>(); list.add( - ShapeLink.builder() - .id(symbol.toString()) - .type("TYPE") - .build() + ShapeLink.builder() + .id(symbol.toString()) + .type("TYPE") + .build() ); return list; }; @@ -162,11 +162,11 @@ static class TestSymbolProvider implements SymbolProvider { @Override public Symbol toSymbol(Shape shape) { return Symbol.builder() - .putProperty("shape", shape) - .name(shape.getId().getName()) - .namespace(shape.getId().getNamespace(), "/") - .definitionFile("file.java") - .build(); + .putProperty("shape", shape) + .name(shape.getId().getName()) + .namespace(shape.getId().getNamespace(), "/") + .definitionFile("file.java") + .build(); } } diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/CodegenWriterDelegatorTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/CodegenWriterDelegatorTest.java index 9692becb832..420b6969fbb 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/CodegenWriterDelegatorTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/CodegenWriterDelegatorTest.java @@ -25,14 +25,14 @@ public class CodegenWriterDelegatorTest { public void createsSymbolsAndFilesForShapeWriters() { MockManifest mockManifest = new MockManifest(); SymbolProvider provider = (shape) -> Symbol.builder() - .namespace("com.foo", ".") - .name("Baz") - .definitionFile("com/foo/Baz.bam") - .build(); + .namespace("com.foo", ".") + .name("Baz") + .definitionFile("com/foo/Baz.bam") + .build(); CodegenWriterDelegator delegator = new CodegenWriterDelegator<>( - mockManifest, - provider, - (f, n) -> new MyWriter(n) + mockManifest, + provider, + (f, n) -> new MyWriter(n) ); Shape shape = StringShape.builder().id("com.foo#Baz").build(); delegator.useShapeWriter(shape, writer -> {}); @@ -45,14 +45,14 @@ public void aggregatesDependencies() { MockManifest mockManifest = new MockManifest(); SymbolProvider provider = (shape) -> null; CodegenWriterDelegator delegator = new CodegenWriterDelegator<>( - mockManifest, - provider, - (f, n) -> new MyWriter(n) + mockManifest, + provider, + (f, n) -> new MyWriter(n) ); SymbolDependency dependency = SymbolDependency.builder() - .packageName("x") - .version("123") - .build(); + .packageName("x") + .version("123") + .build(); delegator.useFileWriter("foo/baz", writer -> { writer.addDependency(dependency); @@ -66,9 +66,9 @@ public void writesNewlineBetweenFiles() { MockManifest mockManifest = new MockManifest(); SymbolProvider provider = (shape) -> null; CodegenWriterDelegator delegator = new CodegenWriterDelegator<>( - mockManifest, - provider, - (f, n) -> new MyWriter(n) + mockManifest, + provider, + (f, n) -> new MyWriter(n) ); delegator.useFileWriter("foo/baz", writer -> { @@ -80,8 +80,8 @@ public void writesNewlineBetweenFiles() { }); assertThat( - delegator.getWriters().get(Paths.get("foo/baz").toString()).toString(), - equalTo(".\n\n.\n") + delegator.getWriters().get(Paths.get("foo/baz").toString()).toString(), + equalTo(".\n\n.\n") ); } @@ -90,9 +90,9 @@ public void canDisableNewlineBetweenFiles() { MockManifest mockManifest = new MockManifest(); SymbolProvider provider = (shape) -> null; CodegenWriterDelegator delegator = new CodegenWriterDelegator<>( - mockManifest, - provider, - (f, n) -> new MyWriter(n) + mockManifest, + provider, + (f, n) -> new MyWriter(n) ); delegator.setAutomaticSeparator(""); @@ -105,8 +105,8 @@ public void canDisableNewlineBetweenFiles() { }); assertThat( - delegator.getWriters().get(Paths.get("foo/baz").toString()).toString(), - equalTo("..\n") + delegator.getWriters().get(Paths.get("foo/baz").toString()).toString(), + equalTo("..\n") ); } @@ -114,14 +114,14 @@ public void canDisableNewlineBetweenFiles() { public void flushesAllWriters() { MockManifest mockManifest = new MockManifest(); SymbolProvider provider = (shape) -> Symbol.builder() - .namespace("com.foo", ".") - .name("Baz") - .definitionFile("com/foo/Baz.bam") - .build(); + .namespace("com.foo", ".") + .name("Baz") + .definitionFile("com/foo/Baz.bam") + .build(); CodegenWriterDelegator delegator = new CodegenWriterDelegator<>( - mockManifest, - provider, - (f, n) -> new MyWriter(n) + mockManifest, + provider, + (f, n) -> new MyWriter(n) ); Shape shape = StringShape.builder().id("com.foo#Baz").build(); delegator.useShapeWriter(shape, writer -> { diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/CodegenWriterTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/CodegenWriterTest.java index 6e4e41a7795..54fa84a8068 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/CodegenWriterTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/CodegenWriterTest.java @@ -22,10 +22,10 @@ public class CodegenWriterTest { public void managesDependencies() { MyWriter writer = new MyWriter("foo"); SymbolDependency dep = SymbolDependency.builder() - .packageName("foo") - .version("123") - .dependencyType("Dev") - .build(); + .packageName("foo") + .version("123") + .dependencyType("Dev") + .build(); writer.addDependency(dep); assertThat(writer.getDependencies(), contains(dep)); @@ -44,16 +44,16 @@ public void writesDocumentationWithSanitation() { public void addsUseImportsWithReferences() { MyWriter writer = new MyWriter("foo"); Symbol s = Symbol.builder() - .declarationFile("foo.ts") - .definitionFile("foo.ts") - .name("Hello") - .namespace("com/foo", "/") - .build(); + .declarationFile("foo.ts") + .definitionFile("foo.ts") + .name("Hello") + .namespace("com/foo", "/") + .build(); SymbolReference reference = SymbolReference.builder() - .symbol(s) - .alias("X") - .options(SymbolReference.ContextOption.USE) - .build(); + .symbol(s) + .alias("X") + .options(SymbolReference.ContextOption.USE) + .build(); writer.addUseImports(reference); assertThat(writer.getImportContainer().imports, hasKey("X")); @@ -64,16 +64,16 @@ public void addsUseImportsWithReferences() { public void omitsUseImportsWithReferencesIfSameNamespace() { MyWriter writer = new MyWriter("foo"); Symbol s = Symbol.builder() - .declarationFile("foo.ts") - .definitionFile("foo.ts") - .name("Hello") - .namespace("foo", "/") - .build(); + .declarationFile("foo.ts") + .definitionFile("foo.ts") + .name("Hello") + .namespace("foo", "/") + .build(); SymbolReference reference = SymbolReference.builder() - .symbol(s) - .alias("X") - .options(SymbolReference.ContextOption.USE) - .build(); + .symbol(s) + .alias("X") + .options(SymbolReference.ContextOption.USE) + .build(); writer.addUseImports(reference); assertThat(writer.getImportContainer().imports, not(hasKey("X"))); @@ -83,20 +83,20 @@ public void omitsUseImportsWithReferencesIfSameNamespace() { public void importsUseReferencesFromSymbols() { MyWriter writer = new MyWriter("foo"); Symbol string = Symbol.builder() - .definitionFile("java/lang/String.java") - .name("String") - .namespace("java.lang", ".") - .build(); + .definitionFile("java/lang/String.java") + .name("String") + .namespace("java.lang", ".") + .build(); SymbolReference reference = SymbolReference.builder() - .symbol(string) - .alias("MyString") - .build(); + .symbol(string) + .alias("MyString") + .build(); Symbol someList = Symbol.builder() - .definitionFile("java/util/List.java") - .name("List") - .namespace("java.util", ".") - .addReference(reference) - .build(); + .definitionFile("java/util/List.java") + .name("List") + .namespace("java.util", ".") + .addReference(reference) + .build(); writer.addUseImports(someList); assertThat(writer.getImportContainer().imports, hasKey("List")); @@ -131,9 +131,9 @@ public void formatsSymbolReferences() { MyWriter writer = new MyWriter("com.foo"); Symbol string = Symbol.builder().name("String").namespace("example.foo", ".").build(); SymbolReference reference = SymbolReference.builder() - .alias("Str") - .symbol(string) - .build(); + .alias("Str") + .symbol(string) + .build(); writer.write("$T", reference); assertThat(writer.toString(), equalTo("Str\n")); diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/JavaStyleDocumentationWriterBuilderTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/JavaStyleDocumentationWriterBuilderTest.java index 0221d5c9353..a72e69eadfc 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/JavaStyleDocumentationWriterBuilderTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/JavaStyleDocumentationWriterBuilderTest.java @@ -22,8 +22,8 @@ public void writesAndEscapesBlockQuotes() { }); assertThat( - writer.toString(), - equalTo("/**\n * Hello.\n * *\\/\n * Goodbye.\n */\n") + writer.toString(), + equalTo("/**\n * Hello.\n * *\\/\n * Goodbye.\n */\n") ); } @@ -31,8 +31,8 @@ public void writesAndEscapesBlockQuotes() { public void canSetCustomSectionName() { MyWriter writer = new MyWriter("foo"); DocumentationWriter docWriter = new JavaStyleDocumentationWriterBuilder() - .namedDocumentationSection("docs") - .build(); + .namedDocumentationSection("docs") + .build(); writer.onSection("docs", contents -> { writer.writeInlineWithNoFormatting(contents.toString().toUpperCase(Locale.ENGLISH)); }); @@ -41,8 +41,8 @@ public void canSetCustomSectionName() { }); assertThat( - writer.toString(), - equalTo("/**\n * HELLO\n */\n") + writer.toString(), + equalTo("/**\n * HELLO\n */\n") ); } @@ -50,8 +50,8 @@ public void canSetCustomSectionName() { public void ensuresNewlineIsAddedBeforeClosing() { MyWriter writer = new MyWriter("foo"); DocumentationWriter docWriter = new JavaStyleDocumentationWriterBuilder() - .namedDocumentationSection("docs") - .build(); + .namedDocumentationSection("docs") + .build(); writer.onSection("docs", contents -> { writer.writeInlineWithNoFormatting(contents.toString().toUpperCase(Locale.ENGLISH)); }); @@ -60,8 +60,8 @@ public void ensuresNewlineIsAddedBeforeClosing() { }); assertThat( - writer.toString(), - equalTo("/**\n * HELLO\n */\n") + writer.toString(), + equalTo("/**\n * HELLO\n */\n") ); } @@ -69,15 +69,15 @@ public void ensuresNewlineIsAddedBeforeClosing() { public void canSetCustomMappingFunction() { MyWriter writer = new MyWriter("foo"); DocumentationWriter docWriter = new JavaStyleDocumentationWriterBuilder() - .mappingFunction(s -> s.toUpperCase(Locale.ENGLISH)) - .build(); + .mappingFunction(s -> s.toUpperCase(Locale.ENGLISH)) + .build(); docWriter.writeDocs(writer, () -> { writer.write("Hello"); }); assertThat( - writer.toString(), - equalTo("/**\n * HELLO\n */\n") + writer.toString(), + equalTo("/**\n * HELLO\n */\n") ); } @@ -85,15 +85,15 @@ public void canSetCustomMappingFunction() { public void canEscapeAt() { MyWriter writer = new MyWriter("foo"); DocumentationWriter docWriter = new JavaStyleDocumentationWriterBuilder() - .escapeAtSignWithEntity(true) - .build(); + .escapeAtSignWithEntity(true) + .build(); docWriter.writeDocs(writer, () -> { writer.write("Hello @foo"); }); assertThat( - writer.toString(), - equalTo("/**\n * Hello @foo\n */\n") + writer.toString(), + equalTo("/**\n * Hello @foo\n */\n") ); } @@ -101,16 +101,16 @@ public void canEscapeAt() { public void canEscapeAtWithComposedCustomEscaper() { MyWriter writer = new MyWriter("foo"); DocumentationWriter docWriter = new JavaStyleDocumentationWriterBuilder() - .mappingFunction(s -> s.toUpperCase(Locale.ENGLISH)) - .escapeAtSignWithEntity(true) - .build(); + .mappingFunction(s -> s.toUpperCase(Locale.ENGLISH)) + .escapeAtSignWithEntity(true) + .build(); docWriter.writeDocs(writer, () -> { writer.write("Hello @foo"); }); assertThat( - writer.toString(), - equalTo("/**\n * HELLO @FOO\n */\n") + writer.toString(), + equalTo("/**\n * HELLO @FOO\n */\n") ); } } diff --git a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/SymbolWriterTest.java b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/SymbolWriterTest.java index 57593846ad5..699aa5b3f2d 100644 --- a/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/SymbolWriterTest.java +++ b/smithy-codegen-core/src/test/java/software/amazon/smithy/codegen/core/writer/SymbolWriterTest.java @@ -22,10 +22,10 @@ public class SymbolWriterTest { public void managesDependencies() { MySimpleWriter writer = new MySimpleWriter("foo"); SymbolDependency dep = SymbolDependency.builder() - .packageName("foo") - .version("123") - .dependencyType("Dev") - .build(); + .packageName("foo") + .version("123") + .dependencyType("Dev") + .build(); writer.addDependency(dep); assertThat(writer.getDependencies(), contains(dep)); @@ -44,16 +44,16 @@ public void writesDocumentationWithSanitation() { public void addsUseImportsWithReferences() { MySimpleWriter writer = new MySimpleWriter("foo"); Symbol s = Symbol.builder() - .declarationFile("foo.ts") - .definitionFile("foo.ts") - .name("Hello") - .namespace("com/foo", "/") - .build(); + .declarationFile("foo.ts") + .definitionFile("foo.ts") + .name("Hello") + .namespace("com/foo", "/") + .build(); SymbolReference reference = SymbolReference.builder() - .symbol(s) - .alias("X") - .options(SymbolReference.ContextOption.USE) - .build(); + .symbol(s) + .alias("X") + .options(SymbolReference.ContextOption.USE) + .build(); writer.addUseImports(reference); assertThat(writer.getImportContainer().imports, hasKey("X")); @@ -64,16 +64,16 @@ public void addsUseImportsWithReferences() { public void omitsUseImportsWithReferencesIfSameNamespace() { MySimpleWriter writer = new MySimpleWriter("foo"); Symbol s = Symbol.builder() - .declarationFile("foo.ts") - .definitionFile("foo.ts") - .name("Hello") - .namespace("foo", "/") - .build(); + .declarationFile("foo.ts") + .definitionFile("foo.ts") + .name("Hello") + .namespace("foo", "/") + .build(); SymbolReference reference = SymbolReference.builder() - .symbol(s) - .alias("X") - .options(SymbolReference.ContextOption.USE) - .build(); + .symbol(s) + .alias("X") + .options(SymbolReference.ContextOption.USE) + .build(); writer.addUseImports(reference); assertThat(writer.getImportContainer().imports, not(hasKey("X"))); @@ -83,20 +83,20 @@ public void omitsUseImportsWithReferencesIfSameNamespace() { public void importsUseReferencesFromSymbols() { MySimpleWriter writer = new MySimpleWriter("foo"); Symbol string = Symbol.builder() - .definitionFile("java/lang/String.java") - .name("String") - .namespace("java.lang", ".") - .build(); + .definitionFile("java/lang/String.java") + .name("String") + .namespace("java.lang", ".") + .build(); SymbolReference reference = SymbolReference.builder() - .symbol(string) - .alias("MyString") - .build(); + .symbol(string) + .alias("MyString") + .build(); Symbol someList = Symbol.builder() - .definitionFile("java/util/List.java") - .name("List") - .namespace("java.util", ".") - .addReference(reference) - .build(); + .definitionFile("java/util/List.java") + .name("List") + .namespace("java.util", ".") + .addReference(reference) + .build(); writer.addUseImports(someList); assertThat(writer.getImportContainer().imports, hasKey("List")); @@ -131,9 +131,9 @@ public void formatsSymbolReferences() { MySimpleWriter writer = new MySimpleWriter("com.foo"); Symbol string = Symbol.builder().name("String").namespace("example.foo", ".").build(); SymbolReference reference = SymbolReference.builder() - .alias("Str") - .symbol(string) - .build(); + .alias("Str") + .symbol(string) + .build(); writer.write("$T", reference); assertThat(writer.toString(), equalTo("Str\n")); diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/ChangedMetadata.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/ChangedMetadata.java index a27d8926da9..3ede743c059 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/ChangedMetadata.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/ChangedMetadata.java @@ -64,8 +64,8 @@ public boolean equals(Object o) { } else { ChangedMetadata that = (ChangedMetadata) o; return getKey().equals(that.getKey()) - && Objects.equals(getOldValue(), that.getOldValue()) - && Objects.equals(getNewValue(), that.getNewValue()); + && Objects.equals(getOldValue(), that.getOldValue()) + && Objects.equals(getNewValue(), that.getNewValue()); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/ChangedShape.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/ChangedShape.java index 32b9685666f..1e2db50b856 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/ChangedShape.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/ChangedShape.java @@ -73,9 +73,9 @@ public ShapeId getShapeId() { */ public Stream addedTraits() { return traitDiff.values() - .stream() - .filter(pair -> pair.getLeft() == null) - .map(Pair::getRight); + .stream() + .filter(pair -> pair.getLeft() == null) + .map(Pair::getRight); } /** @@ -85,9 +85,9 @@ public Stream addedTraits() { */ public Stream removedTraits() { return traitDiff.values() - .stream() - .filter(pair -> pair.getRight() == null) - .map(Pair::getLeft); + .stream() + .filter(pair -> pair.getRight() == null) + .map(Pair::getLeft); } /** @@ -139,9 +139,9 @@ public boolean isTraitInBoth(ShapeId trait) { @SuppressWarnings("unchecked") public Optional> getChangedTrait(Class traitType) { return changedTraits() - .filter(p -> traitType.isInstance(p.getLeft()) && traitType.isInstance(p.getRight())) - .map(p -> (Pair) p) - .findFirst(); + .filter(p -> traitType.isInstance(p.getLeft()) && traitType.isInstance(p.getRight())) + .map(p -> (Pair) p) + .findFirst(); } /** @@ -171,7 +171,7 @@ public boolean equals(Object o) { // there's no need to compare the traitDiff property. ChangedShape that = (ChangedShape) o; return Objects.equals(getOldShape(), that.getOldShape()) - && Objects.equals(getNewShape(), that.getNewShape()); + && Objects.equals(getNewShape(), that.getNewShape()); } } @@ -199,10 +199,10 @@ private static Map> findTraitDifferences(Shape oldSh } // Find traits that were added. newShape.getAllTraits() - .values() - .stream() - .filter(newTrait -> !oldShape.findTrait(newTrait.toShapeId()).isPresent()) - .forEach(newTrait -> changes.put(newTrait.toShapeId(), Pair.of(null, newTrait))); + .values() + .stream() + .filter(newTrait -> !oldShape.findTrait(newTrait.toShapeId()).isPresent()) + .forEach(newTrait -> changes.put(newTrait.toShapeId(), Pair.of(null, newTrait))); return changes; } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/Differences.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/Differences.java index cc0fbc2cfc3..2cdfb41ff5b 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/Differences.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/Differences.java @@ -81,10 +81,10 @@ public Stream addedShapes(Class shapeType) { */ public Stream> addedMetadata() { return newModel.getMetadata() - .entrySet() - .stream() - .filter(entry -> !oldModel.getMetadata().containsKey(entry.getKey())) - .map(entry -> Pair.of(entry.getKey(), entry.getValue())); + .entrySet() + .stream() + .filter(entry -> !oldModel.getMetadata().containsKey(entry.getKey())) + .map(entry -> Pair.of(entry.getKey(), entry.getValue())); } /** @@ -117,10 +117,10 @@ public Stream removedShapes(Class shapeType) { */ public Stream> removedMetadata() { return oldModel.getMetadata() - .entrySet() - .stream() - .filter(entry -> !newModel.getMetadata().containsKey(entry.getKey())) - .map(entry -> Pair.of(entry.getKey(), entry.getValue())); + .entrySet() + .stream() + .filter(entry -> !newModel.getMetadata().containsKey(entry.getKey())) + .map(entry -> Pair.of(entry.getKey(), entry.getValue())); } /** @@ -142,8 +142,8 @@ public Stream> changedShapes() { @SuppressWarnings("unchecked") public Stream> changedShapes(Class type) { return changedShapes() - .filter(change -> type.isInstance(change.getOldShape()) && type.isInstance(change.getNewShape())) - .map(change -> (ChangedShape) change); + .filter(change -> type.isInstance(change.getOldShape()) && type.isInstance(change.getNewShape())) + .map(change -> (ChangedShape) change); } /** diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/ModelDiff.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/ModelDiff.java index c6e9bb00c79..bc3c82696a6 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/ModelDiff.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/ModelDiff.java @@ -62,11 +62,11 @@ public static List compare(Model oldModel, Model newModel) { */ public static List compare(ClassLoader classLoader, Model oldModel, Model newModel) { return builder() - .oldModel(oldModel) - .newModel(newModel) - .classLoader(classLoader) - .compare() - .getDiffEvents(); + .oldModel(oldModel) + .newModel(newModel) + .classLoader(classLoader) + .compare() + .getDiffEvents(); } /** @@ -79,10 +79,10 @@ public static final class Result { private final List newModelEvents; public Result( - Differences differences, - List diffEvents, - List oldModelEvents, - List newModelEvents + Differences differences, + List diffEvents, + List oldModelEvents, + List newModelEvents ) { this.differences = Objects.requireNonNull(differences); this.diffEvents = Objects.requireNonNull(diffEvents); @@ -173,9 +173,9 @@ public boolean equals(Object o) { } Result result = (Result) o; return getDifferences().equals(result.getDifferences()) - && getDiffEvents().equals(result.getDiffEvents()) - && getOldModelEvents().equals(result.getOldModelEvents()) - && getNewModelEvents().equals(result.getNewModelEvents()); + && getDiffEvents().equals(result.getDiffEvents()) + && getOldModelEvents().equals(result.getOldModelEvents()) + && getNewModelEvents().equals(result.getNewModelEvents()); } @Override @@ -239,7 +239,7 @@ public Builder newModel(Model newModel) { */ public Builder oldModel(ValidatedResult oldModel) { this.oldModel = oldModel.getResult() - .orElseThrow(() -> new IllegalArgumentException("No old model present in ValidatedResult")); + .orElseThrow(() -> new IllegalArgumentException("No old model present in ValidatedResult")); this.oldModelEvents = oldModel.getValidationEvents(); return this; } @@ -253,7 +253,7 @@ public Builder oldModel(ValidatedResult oldModel) { */ public Builder newModel(ValidatedResult newModel) { this.newModel = newModel.getResult() - .orElseThrow(() -> new IllegalArgumentException("No new model present in ValidatedResult")); + .orElseThrow(() -> new IllegalArgumentException("No new model present in ValidatedResult")); this.newModelEvents = newModel.getValidationEvents(); return this; } @@ -274,15 +274,15 @@ public Result compare() { // Applies suppressions and elevates event severities. ValidationEventDecorator decoratorResult = new ModelBasedEventDecorator() - .createDecorator(newModel) - .getResult() - .orElse(ValidationEventDecorator.IDENTITY); + .createDecorator(newModel) + .getResult() + .orElse(ValidationEventDecorator.IDENTITY); List diffEvents = evaluators.parallelStream() - .flatMap(evaluator -> evaluator.evaluate(differences).stream()) - // No need to call canDecorate first since that method will always return true in any code path. - .map(decoratorResult::decorate) - .collect(Collectors.toList()); + .flatMap(evaluator -> evaluator.evaluate(differences).stream()) + // No need to call canDecorate first since that method will always return true in any code path. + .map(decoratorResult::decorate) + .collect(Collectors.toList()); return new Result(differences, diffEvents, oldModelEvents, newModelEvents); } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AbstractDiffEvaluator.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AbstractDiffEvaluator.java index bbf5cd37c30..722d6257892 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AbstractDiffEvaluator.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AbstractDiffEvaluator.java @@ -60,11 +60,11 @@ protected final ValidationEvent note(Shape shape, FromSourceLocation location, S private ValidationEvent createEvent(Severity severity, Shape shape, FromSourceLocation location, String message) { return createEvent( - ValidationEvent.builder() - .severity(severity) - .message(message) - .shapeId(shape.getId()) - .sourceLocation(location.getSourceLocation()) + ValidationEvent.builder() + .severity(severity) + .message(message) + .shapeId(shape.getId()) + .sourceLocation(location.getSourceLocation()) ); } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AbstractLengthAndRangeValidator.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AbstractLengthAndRangeValidator.java index 1e1fe9187a2..0bbb8bd81e1 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AbstractLengthAndRangeValidator.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AbstractLengthAndRangeValidator.java @@ -26,13 +26,13 @@ abstract class AbstractLengthAndRangeValidator extends Abstract @Override public final List evaluate(Differences differences) { return differences.changedShapes() - .flatMap(change -> { - Pair pair = change.getChangedTrait(getTraitType()).orElse(null); - return pair == null - ? Stream.empty() - : validateTrait(change, pair).stream(); - }) - .collect(Collectors.toList()); + .flatMap(change -> { + Pair pair = change.getChangedTrait(getTraitType()).orElse(null); + return pair == null + ? Stream.empty() + : validateTrait(change, pair).stream(); + }) + .collect(Collectors.toList()); } abstract Class getTraitType(); @@ -52,29 +52,29 @@ private List validateTrait(ChangedShape change, Pair 0) { events.add( - error( - change.getNewShape(), - String.format( - "%s trait value `min` was made more restrictive by raising from %s to %s", - newTrait.toShapeId(), - oldMin, - newMin + error( + change.getNewShape(), + String.format( + "%s trait value `min` was made more restrictive by raising from %s to %s", + newTrait.toShapeId(), + oldMin, + newMin + ) ) - ) ); } if (newMax != null && (oldMax == null || oldMax.compareTo(newMax) > 0)) { events.add( - error( - change.getNewShape(), - String.format( - "%s trait value `max` was made more restrictive by lowering from %s to %s", - newTrait.toShapeId(), - oldMax, - newMax + error( + change.getNewShape(), + String.format( + "%s trait value `max` was made more restrictive by lowering from %s to %s", + newTrait.toShapeId(), + oldMax, + newMax + ) ) - ) ); } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedEntityBinding.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedEntityBinding.java index 3bd5b5169f5..0801457304d 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedEntityBinding.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedEntityBinding.java @@ -39,10 +39,10 @@ public List evaluate(Differences differences) { private void validateOperation(ChangedShape change, List events) { findAdded(change.getOldShape().getOperations(), change.getNewShape().getOperations()) - .forEach(added -> events.add(createAddedEvent(ADDED_OPERATION, change.getNewShape(), added))); + .forEach(added -> events.add(createAddedEvent(ADDED_OPERATION, change.getNewShape(), added))); findAdded(change.getOldShape().getResources(), change.getNewShape().getResources()) - .forEach(added -> events.add(createAddedEvent(ADDED_RESOURCE, change.getNewShape(), added))); + .forEach(added -> events.add(createAddedEvent(ADDED_RESOURCE, change.getNewShape(), added))); } private Set findAdded(Set oldShapes, Set newShapes) { @@ -55,17 +55,17 @@ private ValidationEvent createAddedEvent(String typeOfAddition, EntityShape pare String childType = typeOfAddition.equals(ADDED_RESOURCE) ? "Resource" : "Operation"; String typeOfParentShape = ShapeType.RESOURCE.equals(parentEntity.getType()) ? TO_RESOURCE : TO_SERVICE; String message = String.format( - "%s binding of `%s` was added to the %s shape, `%s`", - childType, - childShape, - parentEntity.getType(), - parentEntity.getId() + "%s binding of `%s` was added to the %s shape, `%s`", + childType, + childShape, + parentEntity.getType(), + parentEntity.getId() ); return ValidationEvent.builder() - .id(typeOfAddition + typeOfParentShape + childShape.getName()) - .severity(Severity.NOTE) - .shape(parentEntity) - .message(message) - .build(); + .id(typeOfAddition + typeOfParentShape + childShape.getName()) + .severity(Severity.NOTE) + .shape(parentEntity) + .message(message) + .build(); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedMetadata.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedMetadata.java index c2799a3f579..ce264c2d484 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedMetadata.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedMetadata.java @@ -18,20 +18,20 @@ public final class AddedMetadata extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.addedMetadata() - .map( - metadata -> ValidationEvent.builder() - .id(getEventId()) - .severity(Severity.NOTE) - .sourceLocation(metadata.getRight().getSourceLocation()) - .message( - String.format( - "Metadata key `%s` was added with the following value: %s", - metadata.getLeft(), - Node.prettyPrintJson(metadata.getRight()) - ) - ) - .build() - ) - .collect(Collectors.toList()); + .map( + metadata -> ValidationEvent.builder() + .id(getEventId()) + .severity(Severity.NOTE) + .sourceLocation(metadata.getRight().getSourceLocation()) + .message( + String.format( + "Metadata key `%s` was added with the following value: %s", + metadata.getLeft(), + Node.prettyPrintJson(metadata.getRight()) + ) + ) + .build() + ) + .collect(Collectors.toList()); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedOperationError.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedOperationError.java index 4c50a1a7e5d..e7ea124a35f 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedOperationError.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedOperationError.java @@ -24,8 +24,8 @@ public final class AddedOperationError extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.changedShapes(OperationShape.class) - .flatMap(change -> createErrorViolations(change, differences.getNewModel()).stream()) - .collect(Collectors.toList()); + .flatMap(change -> createErrorViolations(change, differences.getNewModel()).stream()) + .collect(Collectors.toList()); } private List createErrorViolations(ChangedShape change, Model newModel) { @@ -38,23 +38,23 @@ private List createErrorViolations(ChangedShape SourceLocation errorSource = newModel.expectShape(error).getSourceLocation(); if (!change.getOldShape().getErrors().contains(error)) { events.add( - ValidationEvent.builder() - .id(getEventId() + "." + error.getName()) - .severity(Severity.WARNING) - .message( - String.format( - "The `%s` error was added to the `%s` operation. This " - + "is backward-compatible if the error is only " - + "encountered as a result of a change in behavior of " - + "the client (for example, the client sends a new " - + "parameter to an operation).", - error, - change.getShapeId() - ) - ) - .shape(change.getNewShape()) - .sourceLocation(errorSource) - .build() + ValidationEvent.builder() + .id(getEventId() + "." + error.getName()) + .severity(Severity.WARNING) + .message( + String.format( + "The `%s` error was added to the `%s` operation. This " + + "is backward-compatible if the error is only " + + "encountered as a result of a change in behavior of " + + "the client (for example, the client sends a new " + + "parameter to an operation).", + error, + change.getShapeId() + ) + ) + .shape(change.getNewShape()) + .sourceLocation(errorSource) + .build() ); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedRequiredMember.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedRequiredMember.java index 77fb5e66f63..2a25f50f7ce 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedRequiredMember.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedRequiredMember.java @@ -23,36 +23,38 @@ public class AddedRequiredMember extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { List events = newRequiredMembers(differences) - .map(this::emit) - .collect(Collectors.toList()); + .map(this::emit) + .collect(Collectors.toList()); return events; } private Stream newRequiredMembers(Differences differences) { return differences.changedShapes(StructureShape.class) - .flatMap( - change -> change.getNewShape() - .members() - .stream() - .filter( - newMember -> newMember.hasTrait(RequiredTrait.ID) - && !newMember.hasTrait(DefaultTrait.ID) - // Members that did not exist before - && change.getOldShape().getAllMembers().get(newMember.getMemberName()) == null - ) - ); + .flatMap( + change -> change.getNewShape() + .members() + .stream() + .filter( + newMember -> newMember.hasTrait(RequiredTrait.ID) + && !newMember.hasTrait(DefaultTrait.ID) + // Members that did not exist before + && change.getOldShape() + .getAllMembers() + .get(newMember.getMemberName()) == null + ) + ); } private ValidationEvent emit(MemberShape memberShape) { return ValidationEvent.builder() - .id(getEventId()) - .shape(memberShape) - .message( - "Adding a new member with the `required` trait " - + "but not the `default` trait is backwards-incompatible." - ) - .severity(Severity.ERROR) - .build(); + .id(getEventId()) + .shape(memberShape) + .message( + "Adding a new member with the `required` trait " + + "but not the `default` trait is backwards-incompatible." + ) + .severity(Severity.ERROR) + .build(); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedServiceError.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedServiceError.java index 037410ea479..af1cd675e51 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedServiceError.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedServiceError.java @@ -21,8 +21,8 @@ public final class AddedServiceError extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.changedShapes(ServiceShape.class) - .flatMap(change -> createErrorViolations(change).stream()) - .collect(Collectors.toList()); + .flatMap(change -> createErrorViolations(change).stream()) + .collect(Collectors.toList()); } private List createErrorViolations(ChangedShape change) { @@ -34,18 +34,18 @@ private List createErrorViolations(ChangedShape c for (ShapeId id : change.getNewShape().getErrors()) { if (!change.getOldShape().getErrors().contains(id)) { events.add( - warning( - change.getNewShape(), - String.format( - "The `%s` error was added to the `%s` service, making this error common " - + "to all operations within the service. This is backward-compatible if the " - + "error is only encountered as a result of a change in behavior of " - + "the client (for example, the client sends a new " - + "parameter to an operation).", - id, - change.getShapeId() + warning( + change.getNewShape(), + String.format( + "The `%s` error was added to the `%s` service, making this error common " + + "to all operations within the service. This is backward-compatible if the " + + "error is only encountered as a result of a change in behavior of " + + "the client (for example, the client sends a new " + + "parameter to an operation).", + id, + change.getShapeId() + ) ) - ) ); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedShape.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedShape.java index b7d8cdc4146..4ea9ff7d91e 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedShape.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedShape.java @@ -23,16 +23,16 @@ public final class AddedShape extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.addedShapes() - .filter(shape -> !isMemberOfAddedShape(shape, differences)) - .filter(shape -> !isMemberOfConvertedEnumShape(shape, differences)) - .map(shape -> note(shape, String.format("Added %s `%s`", shape.getType(), shape.getId()))) - .collect(Collectors.toList()); + .filter(shape -> !isMemberOfAddedShape(shape, differences)) + .filter(shape -> !isMemberOfConvertedEnumShape(shape, differences)) + .map(shape -> note(shape, String.format("Added %s `%s`", shape.getType(), shape.getId()))) + .collect(Collectors.toList()); } private boolean isMemberOfAddedShape(Shape shape, Differences differences) { return shape.asMemberShape() - .filter(member -> !differences.getOldModel().getShapeIds().contains(member.getContainer())) - .isPresent(); + .filter(member -> !differences.getOldModel().getShapeIds().contains(member.getContainer())) + .isPresent(); } private boolean isMemberOfConvertedEnumShape(Shape shape, Differences differences) { @@ -43,14 +43,14 @@ private boolean isMemberOfConvertedEnumShape(Shape shape, Differences difference ShapeId conversionShapeId = shape.asMemberShape().get().getContainer(); Optional oldStringShapeWithEnumTrait = differences.getOldModel() - .getShape(conversionShapeId) - .flatMap(Shape::asStringShape) - .filter(s -> s.getType() == ShapeType.STRING) - .filter(s -> s.hasTrait(EnumTrait.ID)); + .getShape(conversionShapeId) + .flatMap(Shape::asStringShape) + .filter(s -> s.getType() == ShapeType.STRING) + .filter(s -> s.hasTrait(EnumTrait.ID)); Optional newEnumShape = differences.getNewModel() - .getShape(conversionShapeId) - .flatMap(Shape::asEnumShape); + .getShape(conversionShapeId) + .flatMap(Shape::asEnumShape); // Changes in enum values are handled in the ChangedEnumTrait evaluator return newEnumShape.isPresent() && oldStringShapeWithEnumTrait.isPresent(); diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedTraitDefinition.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedTraitDefinition.java index aaf3dd62d20..f5553fc0ade 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedTraitDefinition.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedTraitDefinition.java @@ -18,15 +18,15 @@ public final class AddedTraitDefinition extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.addedShapes() - .filter(shape -> shape.hasTrait(TraitDefinition.class)) - .map( - shape -> ValidationEvent.builder() - .id(getEventId()) - .severity(Severity.NOTE) - .shape(shape) - .message(String.format("Trait definition `%s` was added", shape.getId())) - .build() - ) - .collect(Collectors.toList()); + .filter(shape -> shape.hasTrait(TraitDefinition.class)) + .map( + shape -> ValidationEvent.builder() + .id(getEventId()) + .severity(Severity.NOTE) + .shape(shape) + .message(String.format("Trait definition `%s` was added", shape.getId())) + .build() + ) + .collect(Collectors.toList()); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedDefault.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedDefault.java index 3f7345fdf60..4c52e5ad37e 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedDefault.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedDefault.java @@ -30,13 +30,13 @@ public List evaluate(Differences differences) { change.getTraitDifferences().forEach((traitId, pair) -> { if (traitId.equals(DefaultTrait.ID)) { if ((pair.left == null || pair.left instanceof DefaultTrait) - && (pair.right == null || pair.right instanceof DefaultTrait)) { + && (pair.right == null || pair.right instanceof DefaultTrait)) { validateChange( - events, - differences.getNewModel(), - change, - (DefaultTrait) pair.left, - (DefaultTrait) pair.right + events, + differences.getNewModel(), + change, + (DefaultTrait) pair.left, + (DefaultTrait) pair.right ); } } @@ -47,41 +47,41 @@ public List evaluate(Differences differences) { } private void validateChange( - List events, - Model model, - ChangedShape change, - DefaultTrait oldTrait, - DefaultTrait newTrait + List events, + Model model, + ChangedShape change, + DefaultTrait oldTrait, + DefaultTrait newTrait ) { if (newTrait == null) { if (!isInconsequentialRemovalOfDefaultTrait(model, oldTrait, change.getNewShape())) { events.add( - error( - change.getNewShape(), - "@default trait was removed. This will break previously generated code." - ) + error( + change.getNewShape(), + "@default trait was removed. This will break previously generated code." + ) ); } } else if (oldTrait == null) { if (change.getNewShape().getType() != ShapeType.MEMBER) { events.add( - error( - change.getNewShape(), - newTrait, - "Adding the @default trait to a root-level shape will break previously generated " - + "code. Added @default: " + Node.printJson(newTrait.toNode()) - ) + error( + change.getNewShape(), + newTrait, + "Adding the @default trait to a root-level shape will break previously generated " + + "code. Added @default: " + Node.printJson(newTrait.toNode()) + ) ); } else if (!change.getNewShape().hasTrait(AddedDefaultTrait.class)) { if (!newTrait.toNode().isNullNode()) { events.add( - error( - change.getNewShape(), - newTrait, - "Adding the @default trait to a member without also adding the @addedDefault " - + "trait will break previously generated code. Added @default: " - + Node.printJson(newTrait.toNode()) - ) + error( + change.getNewShape(), + newTrait, + "Adding the @default trait to a member without also adding the @addedDefault " + + "trait will break previously generated code. Added @default: " + + Node.printJson(newTrait.toNode()) + ) ); } } @@ -90,13 +90,13 @@ private void validateChange( evaluateChangedTrait(model, change.getNewShape().asMemberShape().get(), oldTrait, newTrait, events); } else { events.add( - error( - change.getNewShape(), - newTrait, - "Changing the @default value of a root-level shape will break previously generated " - + "code. Old value: " + Node.printJson(oldTrait.toNode()) - + ". New value: " + Node.printJson(newTrait.toNode()) - ) + error( + change.getNewShape(), + newTrait, + "Changing the @default value of a root-level shape will break previously generated " + + "code. Old value: " + Node.printJson(oldTrait.toNode()) + + ". New value: " + Node.printJson(newTrait.toNode()) + ) ); } } @@ -105,28 +105,28 @@ private void validateChange( private boolean isInconsequentialRemovalOfDefaultTrait(Model model, DefaultTrait trait, Shape removedFrom) { // Removing a default of null if the target is nullable is not an issue. return removedFrom.asMemberShape() - .map(member -> { - if (trait.toNode().isNullNode()) { - // If the target has no defined default, then removing a default(null) trait is fine. - Node targetDefault = model.expectShape(member.getTarget()) - .getTrait(DefaultTrait.class) - .map(DefaultTrait::toNode) - .orElse(Node.nullNode()); // If no default, then assume target has a default of null. - return targetDefault.isNullNode(); - } else { - // Removing a non-null trait is always an issue. - return false; - } - }) - .orElse(false); + .map(member -> { + if (trait.toNode().isNullNode()) { + // If the target has no defined default, then removing a default(null) trait is fine. + Node targetDefault = model.expectShape(member.getTarget()) + .getTrait(DefaultTrait.class) + .map(DefaultTrait::toNode) + .orElse(Node.nullNode()); // If no default, then assume target has a default of null. + return targetDefault.isNullNode(); + } else { + // Removing a non-null trait is always an issue. + return false; + } + }) + .orElse(false); } private void evaluateChangedTrait( - Model model, - MemberShape member, - DefaultTrait oldTrait, - DefaultTrait newTrait, - List events + Model model, + MemberShape member, + DefaultTrait oldTrait, + DefaultTrait newTrait, + List events ) { Shape target = model.expectShape(member.getTarget()); Node oldValue = oldTrait.toNode(); @@ -136,36 +136,36 @@ private void evaluateChangedTrait( if (oldZeroValue == newZeroValue) { events.add( - danger( - member, - newTrait, - "Changing the @default value of a member is dangerous and could break " - + "previously generated code or lead to subtle errors. Do this only " - + "when strictly necessary. Old value: " + Node.printJson(oldValue) - + ". New value: " + Node.printJson(newValue) - ) + danger( + member, + newTrait, + "Changing the @default value of a member is dangerous and could break " + + "previously generated code or lead to subtle errors. Do this only " + + "when strictly necessary. Old value: " + Node.printJson(oldValue) + + ". New value: " + Node.printJson(newValue) + ) ); } else if (oldZeroValue) { events.add( - error( - member, - newTrait, - "The @default trait of this member changed from the zero value of the " - + "target shape, `" + Node.printJson(oldValue) + "`, to a value that " - + "is not the zero value, `" + Node.printJson(newValue) + "`. This " - + "will break previously generated code." - ) + error( + member, + newTrait, + "The @default trait of this member changed from the zero value of the " + + "target shape, `" + Node.printJson(oldValue) + "`, to a value that " + + "is not the zero value, `" + Node.printJson(newValue) + "`. This " + + "will break previously generated code." + ) ); } else { events.add( - error( - member, - newTrait, - "The @default trait of this member changed from something other than " - + "the zero value of the target shape, `" + Node.printJson(oldValue) - + "`, to the zero value, `" + Node.printJson(newValue) + "`. This " - + "will break previously generated code." - ) + error( + member, + newTrait, + "The @default trait of this member changed from something other than " + + "the zero value of the target shape, `" + Node.printJson(oldValue) + + "`, to the zero value, `" + Node.printJson(newValue) + "`. This " + + "will break previously generated code." + ) ); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedEnumTrait.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedEnumTrait.java index 6ad0ef82ba4..2cf76f11341 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedEnumTrait.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedEnumTrait.java @@ -37,12 +37,12 @@ public final class ChangedEnumTrait extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.changedShapes() - .flatMap( - change -> OptionalUtils.stream(getChangedEnumTraitPair(change)) - .map(p -> Pair.of(change, p)) - ) - .flatMap(pair -> validateEnum(pair.getLeft(), pair.getRight()).stream()) - .collect(Collectors.toList()); + .flatMap( + change -> OptionalUtils.stream(getChangedEnumTraitPair(change)) + .map(p -> Pair.of(change, p)) + ) + .flatMap(pair -> validateEnum(pair.getLeft(), pair.getRight()).stream()) + .collect(Collectors.toList()); } private Optional> getChangedEnumTraitPair(ChangedShape change) { @@ -54,10 +54,10 @@ private Optional> getChangedEnumTraitPair(ChangedShap // Change between enum trait in old model and enum shape synthetic enum trait in new model if (expectedStringToEnumChange(change)) { return Optional.of( - Pair.of( - change.getOldShape().expectTrait(EnumTrait.class), - change.getNewShape().expectTrait(SyntheticEnumTrait.class) - ) + Pair.of( + change.getOldShape().expectTrait(EnumTrait.class), + change.getNewShape().expectTrait(SyntheticEnumTrait.class) + ) ); } return Optional.empty(); @@ -72,39 +72,39 @@ private List validateEnum(ChangedShape change, Pair maybeNewValue = newTrait.getValues() - .stream() - .filter(d -> d.getValue().equals(definition.getValue())) - .findFirst(); + .stream() + .filter(d -> d.getValue().equals(definition.getValue())) + .findFirst(); if (!maybeNewValue.isPresent()) { events.add( - ValidationEvent.builder() - .severity(Severity.ERROR) - .message(String.format("Enum value `%s` was removed", definition.getValue())) - .shape(change.getNewShape()) - .sourceLocation(oldTrait.getSourceLocation()) - .id(getEventId() + REMOVED + enumIndex) - .build() + ValidationEvent.builder() + .severity(Severity.ERROR) + .message(String.format("Enum value `%s` was removed", definition.getValue())) + .shape(change.getNewShape()) + .sourceLocation(oldTrait.getSourceLocation()) + .id(getEventId() + REMOVED + enumIndex) + .build() ); oldEndPosition--; } else { EnumDefinition newValue = maybeNewValue.get(); if (!newValue.getName().equals(definition.getName())) { events.add( - ValidationEvent.builder() - .severity(Severity.ERROR) - .message( - String.format( - "Enum `name` changed from `%s` to `%s` for the `%s` value", - definition.getName().orElse(null), - newValue.getName().orElse(null), - definition.getValue() - ) - ) - .shape(change.getNewShape()) - .sourceLocation(change.getNewShape().getSourceLocation()) - .id(getEventId() + NAME_CHANGED + enumIndex) - .build() + ValidationEvent.builder() + .severity(Severity.ERROR) + .message( + String.format( + "Enum `name` changed from `%s` to `%s` for the `%s` value", + definition.getName().orElse(null), + newValue.getName().orElse(null), + definition.getValue() + ) + ) + .shape(change.getNewShape()) + .sourceLocation(change.getNewShape().getSourceLocation()) + .id(getEventId() + NAME_CHANGED + enumIndex) + .build() ); } } @@ -115,20 +115,20 @@ private List validateEnum(ChangedShape change, Pair validateEnum(ChangedShape change, Pair evaluate(Differences differences) { Stream> changes = Stream.concat( - differences.changedShapes(StructureShape.class), - differences.changedShapes(UnionShape.class) + differences.changedShapes(StructureShape.class), + differences.changedShapes(UnionShape.class) ); return changes - .filter(diff -> isUnordered(diff.getOldShape().members(), diff.getNewShape().members())) - .map( - diff -> danger( - diff.getNewShape(), - String.format( - "%s shape members were reordered. This can cause ABI compatibility issues in languages " - + "like C and C++ where the layout and alignment of a data structure matters.", - diff.getOldShape().getType() - ) + .filter(diff -> isUnordered(diff.getOldShape().members(), diff.getNewShape().members())) + .map( + diff -> danger( + diff.getNewShape(), + String.format( + "%s shape members were reordered. This can cause ABI compatibility issues in languages " + + "like C and C++ where the layout and alignment of a data structure matters.", + diff.getOldShape().getType() + ) + ) ) - ) - .collect(Collectors.toList()); + .collect(Collectors.toList()); } private static boolean isUnordered(Collection a, Collection b) { diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedMemberTarget.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedMemberTarget.java index 27934d78028..a1fa506f723 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedMemberTarget.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedMemberTarget.java @@ -50,9 +50,9 @@ public final class ChangedMemberTarget extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.changedShapes(MemberShape.class) - .filter(change -> !change.getOldShape().getTarget().equals(change.getNewShape().getTarget())) - .map(change -> createChangeEvent(differences, change)) - .collect(Collectors.toList()); + .filter(change -> !change.getOldShape().getTarget().equals(change.getNewShape().getTarget())) + .map(change -> createChangeEvent(differences, change)) + .collect(Collectors.toList()); } private ValidationEvent createChangeEvent(Differences differences, ChangedShape change) { @@ -69,11 +69,11 @@ private ValidationEvent createChangeEvent(Differences differences, ChangedShape< } return ValidationEvent.builder() - .severity(severity) - .id(getEventId()) - .shape(change.getNewShape()) - .message(message) - .build(); + .severity(severity) + .id(getEventId()) + .shape(change.getNewShape()) + .message(message) + .build(); } private Shape getShapeTarget(Model model, ShapeId id) { @@ -87,11 +87,11 @@ private static List areShapesCompatible(Shape oldShape, Shape newShape) if (oldShape.getType() != newShape.getType()) { return ListUtils.of( - String.format( - "The type of the targeted shape changed from %s to %s", - oldShape.getType(), - newShape.getType() - ) + String.format( + "The type of the targeted shape changed from %s to %s", + oldShape.getType(), + newShape.getType() + ) ); } @@ -103,11 +103,11 @@ private static List areShapesCompatible(Shape oldShape, Shape newShape) for (ShapeId significantCodegenTrait : SIGNIFICANT_CODEGEN_TRAITS) { if (oldShape.hasTrait(significantCodegenTrait)) { results.add( - String.format( - "The `%s` trait was found on the target, so the name of the targeted " - + "shape matters for codegen", - significantCodegenTrait - ) + String.format( + "The `%s` trait was found on the target, so the name of the targeted " + + "shape matters for codegen", + significantCodegenTrait + ) ); } } @@ -118,26 +118,26 @@ private static List areShapesCompatible(Shape oldShape, Shape newShape) if (oldShape instanceof CollectionShape) { evaluateMember( - oldShape.getType(), - results, - ((CollectionShape) oldShape).getMember(), - ((CollectionShape) newShape).getMember() + oldShape.getType(), + results, + ((CollectionShape) oldShape).getMember(), + ((CollectionShape) newShape).getMember() ); } else if (oldShape instanceof MapShape) { MapShape oldMapShape = (MapShape) oldShape; MapShape newMapShape = (MapShape) newShape; // Both the key and value need to be evaluated for maps. evaluateMember( - oldShape.getType(), - results, - oldMapShape.getKey(), - newMapShape.getKey() + oldShape.getType(), + results, + oldMapShape.getKey(), + newMapShape.getKey() ); evaluateMember( - oldShape.getType(), - results, - oldMapShape.getValue(), - newMapShape.getValue() + oldShape.getType(), + results, + oldMapShape.getValue(), + newMapShape.getValue() ); } @@ -145,44 +145,44 @@ private static List areShapesCompatible(Shape oldShape, Shape newShape) } private static void evaluateMember( - ShapeType oldShapeType, - List results, - MemberShape oldMember, - MemberShape newMember + ShapeType oldShapeType, + List results, + MemberShape oldMember, + MemberShape newMember ) { String memberSlug = oldShapeType == ShapeType.MAP ? oldMember.getMemberName() + " " : ""; if (!oldMember.getTarget().equals(newMember.getTarget())) { results.add( - String.format( - "Both the old and new shapes are a %s, but the old shape %stargeted " - + "`%s` while the new shape targets `%s`", - oldShapeType, - memberSlug, - oldMember.getTarget(), - newMember.getTarget() - ) + String.format( + "Both the old and new shapes are a %s, but the old shape %stargeted " + + "`%s` while the new shape targets `%s`", + oldShapeType, + memberSlug, + oldMember.getTarget(), + newMember.getTarget() + ) ); } else if (!oldMember.getAllTraits().equals(newMember.getAllTraits())) { results.add( - String.format( - "Both the old and new shapes are a %s, but their %smembers have " - + "differing traits. %s", - oldShapeType, - memberSlug, - createTraitDiffMessage(oldMember, newMember) - ) + String.format( + "Both the old and new shapes are a %s, but their %smembers have " + + "differing traits. %s", + oldShapeType, + memberSlug, + createTraitDiffMessage(oldMember, newMember) + ) ); } } private static String createSimpleMessage(ChangedShape change, Shape oldTarget, Shape newTarget) { return String.format( - "The shape targeted by the member `%s` changed from `%s` (%s) to `%s` (%s). ", - change.getShapeId(), - change.getOldShape().getTarget(), - oldTarget.getType(), - change.getNewShape().getTarget(), - newTarget.getType() + "The shape targeted by the member `%s` changed from `%s` (%s) to `%s` (%s). ", + change.getShapeId(), + change.getOldShape().getTarget(), + oldTarget.getType(), + change.getNewShape().getTarget(), + newTarget.getType() ); } @@ -191,16 +191,16 @@ private static String createTraitDiffMessage(Shape oldShape, Shape newShape) { ChangedShape targetChange = new ChangedShape<>(oldShape, newShape); Set removedTraits = targetChange.removedTraits() - .map(Trait::toShapeId) - .collect(Collectors.toCollection(TreeSet::new)); + .map(Trait::toShapeId) + .collect(Collectors.toCollection(TreeSet::new)); if (!removedTraits.isEmpty()) { joiner.add("The targeted shape no longer has the following traits: " + removedTraits); } Set addedTraits = targetChange.addedTraits() - .map(Trait::toShapeId) - .collect(Collectors.toCollection(TreeSet::new)); + .map(Trait::toShapeId) + .collect(Collectors.toCollection(TreeSet::new)); if (!addedTraits.isEmpty()) { joiner.add("The newly targeted shape now has the following additional traits: " + addedTraits); diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedMetadata.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedMetadata.java index 27c2ccf46b3..bc551c52698 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedMetadata.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedMetadata.java @@ -18,21 +18,21 @@ public final class ChangedMetadata extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.changedMetadata() - .map( - metadata -> ValidationEvent.builder() - .id(getEventId()) - .severity(Severity.WARNING) - .sourceLocation(metadata) - .message( - String.format( - "Metadata key `%s` was changed from %s to %s", - metadata.getKey(), - Node.prettyPrintJson(metadata.getOldValue()), - Node.prettyPrintJson(metadata.getNewValue()) - ) - ) - .build() - ) - .collect(Collectors.toList()); + .map( + metadata -> ValidationEvent.builder() + .id(getEventId()) + .severity(Severity.WARNING) + .sourceLocation(metadata) + .message( + String.format( + "Metadata key `%s` was changed from %s to %s", + metadata.getKey(), + Node.prettyPrintJson(metadata.getOldValue()), + Node.prettyPrintJson(metadata.getNewValue()) + ) + ) + .build() + ) + .collect(Collectors.toList()); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedNullability.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedNullability.java index 080ed07adc8..f48e785a325 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedNullability.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedNullability.java @@ -41,10 +41,10 @@ public List evaluate(Differences differences) { Set events = new HashSet<>(); Stream.concat( - // Get members that changed. - differences.changedShapes(MemberShape.class), - // Get members of structures that added/removed the input trait. - changedInputMembers(differences) + // Get members that changed. + differences.changedShapes(MemberShape.class), + // Get members of structures that added/removed the input trait. + changedInputMembers(differences) ).forEach(change -> { // If NullableIndex says the nullability of a member changed, then that's a breaking change. MemberShape oldShape = change.getOldShape(); @@ -61,33 +61,35 @@ public List evaluate(Differences differences) { private Stream> changedInputMembers(Differences differences) { return differences.changedShapes(StructureShape.class) - .filter(change -> change.isTraitAdded(InputTrait.ID) || change.isTraitRemoved(InputTrait.ID)) - // Find all members that existed before and exist now. - .flatMap( - change -> change.getNewShape() - .members() - .stream() - .map(newMember -> { - MemberShape old = change.getOldShape().getAllMembers().get(newMember.getMemberName()); - return old == null ? null : new ChangedShape<>(old, newMember); - }) - .filter(Objects::nonNull) - ); + .filter(change -> change.isTraitAdded(InputTrait.ID) || change.isTraitRemoved(InputTrait.ID)) + // Find all members that existed before and exist now. + .flatMap( + change -> change.getNewShape() + .members() + .stream() + .map(newMember -> { + MemberShape old = change.getOldShape() + .getAllMembers() + .get(newMember.getMemberName()); + return old == null ? null : new ChangedShape<>(old, newMember); + }) + .filter(Objects::nonNull) + ); } private void createErrors( - Differences differences, - ChangedShape change, - boolean wasNullable, - Collection events + Differences differences, + ChangedShape change, + boolean wasNullable, + Collection events ) { MemberShape oldMember = change.getOldShape(); MemberShape newMember = change.getNewShape(); String message = String.format( - "Member `%s` changed from %s to %s: ", - oldMember.getMemberName(), - wasNullable ? "nullable" : "non-nullable", - wasNullable ? "non-nullable" : "nullable" + "Member `%s` changed from %s to %s: ", + oldMember.getMemberName(), + wasNullable ? "nullable" : "non-nullable", + wasNullable ? "non-nullable" : "nullable" ); boolean oldHasInput = hasInputTrait(differences.getOldModel(), oldMember); boolean newHasInput = hasInputTrait(differences.getNewModel(), newMember); @@ -96,104 +98,105 @@ private void createErrors( Shape newTarget = differences.getNewModel().expectShape(newMember.getTarget()); List eventsToAdd = new ArrayList<>(); SourceLocation newMemberContainerSource = differences.getNewModel() - .expectShape(newMember.getContainer()) - .getSourceLocation(); + .expectShape(newMember.getContainer()) + .getSourceLocation(); if (oldHasInput && !newHasInput) { // If there was an input trait before, but not now, then the nullability must have // changed from nullable to non-nullable. eventsToAdd.add( - emit( - Severity.ERROR, - "RemovedInputTrait", - shape, - newMemberContainerSource, - message, - "The @input trait was removed from " + newMember.getContainer() - ) + emit( + Severity.ERROR, + "RemovedInputTrait", + shape, + newMemberContainerSource, + message, + "The @input trait was removed from " + newMember.getContainer() + ) ); } else if (!oldHasInput && newHasInput) { // If there was no input trait before, but there is now, then the nullability must have // changed from non-nullable to nullable. eventsToAdd.add( - emit( - Severity.DANGER, - "AddedInputTrait", - shape, - newMemberContainerSource, - message, - "The @input trait was added to " + newMember.getContainer() - ) + emit( + Severity.DANGER, + "AddedInputTrait", + shape, + newMemberContainerSource, + message, + "The @input trait was added to " + newMember.getContainer() + ) ); } else if (!newHasInput) { // Can't add clientOptional to a preexisting required member. if (change.isTraitAdded(ClientOptionalTrait.ID) && change.isTraitInBoth(RequiredTrait.ID)) { eventsToAdd.add( - emit( - Severity.ERROR, - "AddedClientOptionalTrait", - shape, - oldMemberSourceLocation, - message, - "The @clientOptional trait was added to a @required member." - ) + emit( + Severity.ERROR, + "AddedClientOptionalTrait", + shape, + oldMemberSourceLocation, + message, + "The @clientOptional trait was added to a @required member." + ) ); } // Can't add required to a member unless the member is marked as @clientOptional or part of @input. if (change.isTraitAdded(RequiredTrait.ID) && !newMember.hasTrait(ClientOptionalTrait.ID)) { eventsToAdd.add( - emit( - Severity.ERROR, - "AddedRequiredTrait", - shape, - oldMemberSourceLocation, - message, - "The @required trait was added to a member." - ) + emit( + Severity.ERROR, + "AddedRequiredTrait", + shape, + oldMemberSourceLocation, + message, + "The @required trait was added to a member." + ) ); } // Can't add the default trait to a member unless the member was previously required. if (change.isTraitAdded(DefaultTrait.ID) && !change.isTraitRemoved(RequiredTrait.ID)) { eventsToAdd.add( - emit( - Severity.ERROR, - "AddedDefaultTrait", - shape, - oldMemberSourceLocation, - message, - "The @default trait was added to a member that was not previously @required." - ) + emit( + Severity.ERROR, + "AddedDefaultTrait", + shape, + oldMemberSourceLocation, + message, + "The @default trait was added to a member that was not previously @required." + ) ); } // Can only remove the required trait if the member was nullable or replaced by the default trait. if (change.isTraitRemoved(RequiredTrait.ID) - && !newMember.hasTrait(DefaultTrait.ID) - && !oldMember.hasTrait(ClientOptionalTrait.ID)) { + && !newMember.hasTrait(DefaultTrait.ID) + && !oldMember.hasTrait(ClientOptionalTrait.ID)) { if (newTarget.isStructureShape() || newTarget.isUnionShape()) { eventsToAdd.add( - emit( - Severity.WARNING, - "RemovedRequiredTrait.StructureOrUnion", - shape, - oldMemberSourceLocation, - message, - "The @required trait was removed from a member " - + "that targets a " + newTarget.getType() + ". This is backward compatible in " - + "generators that always treat structures and unions as optional " - + "(e.g., AWS generators)" - ) + emit( + Severity.WARNING, + "RemovedRequiredTrait.StructureOrUnion", + shape, + oldMemberSourceLocation, + message, + "The @required trait was removed from a member " + + "that targets a " + newTarget.getType() + + ". This is backward compatible in " + + "generators that always treat structures and unions as optional " + + "(e.g., AWS generators)" + ) ); } else { eventsToAdd.add( - emit( - Severity.ERROR, - "RemovedRequiredTrait", - shape, - oldMemberSourceLocation, - message, - "The @required trait was removed and not replaced with the @default " - + "trait and @addedDefault trait." - ) + emit( + Severity.ERROR, + "RemovedRequiredTrait", + shape, + oldMemberSourceLocation, + message, + "The @required trait was removed and not replaced with the @default " + + "trait and @addedDefault trait." + ) ); } } @@ -212,21 +215,21 @@ private boolean hasInputTrait(Model model, MemberShape member) { } private ValidationEvent emit( - Severity severity, - String eventIdSuffix, - ShapeId shape, - SourceLocation sourceLocation, - String prefixMessage, - String message + Severity severity, + String eventIdSuffix, + ShapeId shape, + SourceLocation sourceLocation, + String prefixMessage, + String message ) { String actualId = eventIdSuffix == null ? getEventId() : (getEventId() + '.' + eventIdSuffix); String actualMessage = prefixMessage == null ? message : (prefixMessage + "; " + message); return ValidationEvent.builder() - .id(actualId) - .shapeId(shape) - .sourceLocation(sourceLocation) - .message(actualMessage) - .severity(severity) - .build(); + .id(actualId) + .shapeId(shape) + .sourceLocation(sourceLocation) + .message(actualMessage) + .severity(severity) + .build(); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedOperationInput.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedOperationInput.java index 7791f9effe9..6ef559b89b2 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedOperationInput.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedOperationInput.java @@ -18,18 +18,18 @@ public final class ChangedOperationInput extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.changedShapes(OperationShape.class) - .filter(change -> !change.getOldShape().getInputShape().equals(change.getNewShape().getInputShape())) - .map( - change -> error( - change.getNewShape(), - String.format( - "Changed operation input of `%s` from `%s` to `%s`", - change.getShapeId(), - change.getOldShape().getInputShape(), - change.getNewShape().getInputShape() - ) + .filter(change -> !change.getOldShape().getInputShape().equals(change.getNewShape().getInputShape())) + .map( + change -> error( + change.getNewShape(), + String.format( + "Changed operation input of `%s` from `%s` to `%s`", + change.getShapeId(), + change.getOldShape().getInputShape(), + change.getNewShape().getInputShape() + ) + ) ) - ) - .collect(Collectors.toList()); + .collect(Collectors.toList()); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedOperationOutput.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedOperationOutput.java index 506fa059807..0205c7b7744 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedOperationOutput.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedOperationOutput.java @@ -18,18 +18,18 @@ public final class ChangedOperationOutput extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.changedShapes(OperationShape.class) - .filter(change -> !change.getOldShape().getOutputShape().equals(change.getNewShape().getOutputShape())) - .map( - change -> error( - change.getNewShape(), - String.format( - "Changed operation output of `%s` from `%s` to `%s`", - change.getShapeId(), - change.getOldShape().getOutputShape(), - change.getNewShape().getOutputShape() - ) + .filter(change -> !change.getOldShape().getOutputShape().equals(change.getNewShape().getOutputShape())) + .map( + change -> error( + change.getNewShape(), + String.format( + "Changed operation output of `%s` from `%s` to `%s`", + change.getShapeId(), + change.getOldShape().getOutputShape(), + change.getNewShape().getOutputShape() + ) + ) ) - ) - .collect(Collectors.toList()); + .collect(Collectors.toList()); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedResourceIdentifiers.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedResourceIdentifiers.java index 6870c48cc68..b55ca2f99f4 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedResourceIdentifiers.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedResourceIdentifiers.java @@ -17,18 +17,18 @@ public final class ChangedResourceIdentifiers extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.changedShapes(ResourceShape.class) - .filter(diff -> !diff.getOldShape().getIdentifiers().equals(diff.getNewShape().getIdentifiers())) - .map( - diff -> error( - diff.getNewShape(), - String.format( - "Identifiers of resource `%s` changed from %s to %s.", - diff.getShapeId(), - diff.getOldShape().getIdentifiers(), - diff.getNewShape().getIdentifiers() - ) + .filter(diff -> !diff.getOldShape().getIdentifiers().equals(diff.getNewShape().getIdentifiers())) + .map( + diff -> error( + diff.getNewShape(), + String.format( + "Identifiers of resource `%s` changed from %s to %s.", + diff.getShapeId(), + diff.getOldShape().getIdentifiers(), + diff.getNewShape().getIdentifiers() + ) + ) ) - ) - .collect(Collectors.toList()); + .collect(Collectors.toList()); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedShapeType.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedShapeType.java index adaa6a0df10..46337bfc138 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedShapeType.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedShapeType.java @@ -21,21 +21,21 @@ public final class ChangedShapeType extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.changedShapes() - .filter(diff -> diff.getOldShape().getType() != diff.getNewShape().getType()) - .filter(diff -> !expectedSetToListChange(diff)) - .filter(diff -> !expectedStringToEnumChange(diff)) - .map( - diff -> error( - diff.getNewShape(), - String.format( - "Shape `%s` type was changed from `%s` to `%s`.", - diff.getShapeId(), - diff.getOldShape().getType(), - diff.getNewShape().getType() - ) + .filter(diff -> diff.getOldShape().getType() != diff.getNewShape().getType()) + .filter(diff -> !expectedSetToListChange(diff)) + .filter(diff -> !expectedStringToEnumChange(diff)) + .map( + diff -> error( + diff.getNewShape(), + String.format( + "Shape `%s` type was changed from `%s` to `%s`.", + diff.getShapeId(), + diff.getOldShape().getType(), + diff.getNewShape().getType() + ) + ) ) - ) - .collect(Collectors.toList()); + .collect(Collectors.toList()); } static boolean expectedStringToEnumChange(ChangedShape diff) { diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ModifiedTrait.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ModifiedTrait.java index 2951146bce0..e9b51b4b5c3 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ModifiedTrait.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ModifiedTrait.java @@ -83,17 +83,17 @@ public final class ModifiedTrait extends AbstractDiffEvaluator { * default set of diff strategies so we are notified when traits are modified. */ private static final List DEFAULT_STRATEGIES = ListUtils.of( - new DiffStrategy(DiffType.ADD, Severity.NOTE), - new DiffStrategy(DiffType.UPDATE, Severity.NOTE), - new DiffStrategy(DiffType.REMOVE, Severity.WARNING) + new DiffStrategy(DiffType.ADD, Severity.NOTE), + new DiffStrategy(DiffType.UPDATE, Severity.NOTE), + new DiffStrategy(DiffType.REMOVE, Severity.WARNING) ); /** Traits in this list have special backward compatibility rules and can't be validated here. */ private static final Set IGNORED_TRAITS = SetUtils.of( - BoxTrait.ID, - RequiredTrait.ID, - SyntheticEnumTrait.ID, - OriginalShapeIdTrait.ID + BoxTrait.ID, + RequiredTrait.ID, + SyntheticEnumTrait.ID, + OriginalShapeIdTrait.ID ); @Override @@ -110,19 +110,19 @@ public List evaluate(Differences differences) { if (!IGNORED_TRAITS.contains(traitId)) { // If we don't know about the trait, warn on any change to it. List diffStrategies = strategies.computeIfAbsent( - traitId, - t -> ListUtils.of(new DiffStrategy(DiffType.CONST, Severity.WARNING)) + traitId, + t -> ListUtils.of(new DiffStrategy(DiffType.CONST, Severity.WARNING)) ); for (DiffStrategy strategy : diffStrategies) { List diffEvents = strategy.diffType.validate( - differences.getNewModel(), - "", - changedShape.getNewShape(), - traitId, - oldTrait == null ? null : oldTrait.toNode(), - newTrait == null ? null : newTrait.toNode(), - strategy.severity + differences.getNewModel(), + "", + changedShape.getNewShape(), + traitId, + oldTrait == null ? null : oldTrait.toNode(), + newTrait == null ? null : newTrait.toNode(), + strategy.severity ); events.addAll(diffEvents); } @@ -214,13 +214,13 @@ private enum DiffType { ADD { @Override List validate( - Model model, - String path, - Shape shape, - ShapeId trait, - Node left, - Node right, - Severity severity + Model model, + String path, + Shape shape, + ShapeId trait, + Node left, + Node right, + Severity severity ) { if (left != null) { return Collections.emptyList(); @@ -232,21 +232,21 @@ List validate( message = String.format("Added trait `%s` with value %s", trait, pretty); } else { message = String.format( - "Added trait contents to `%s` at path `%s` with value %s", - trait, - path, - pretty + "Added trait contents to `%s` at path `%s` with value %s", + trait, + path, + pretty ); } return Collections.singletonList( - ValidationEvent.builder() - .id(getValidationEventId(this, trait)) - .severity(severity) - .shape(shape) - .sourceLocation(right) - .message(message) - .build() + ValidationEvent.builder() + .id(getValidationEventId(this, trait)) + .severity(severity) + .shape(shape) + .sourceLocation(right) + .message(message) + .build() ); } }, @@ -254,13 +254,13 @@ List validate( REMOVE { @Override List validate( - Model model, - String path, - Shape shape, - ShapeId trait, - Node left, - Node right, - Severity severity + Model model, + String path, + Shape shape, + ShapeId trait, + Node left, + Node right, + Severity severity ) { if (right != null) { return Collections.emptyList(); @@ -272,21 +272,21 @@ List validate( message = String.format("Removed trait `%s`. Previous trait value: %s", trait, pretty); } else { message = String.format( - "Removed trait contents from `%s` at path `%s`. Removed value: %s", - trait, - path, - pretty + "Removed trait contents from `%s` at path `%s`. Removed value: %s", + trait, + path, + pretty ); } return Collections.singletonList( - ValidationEvent.builder() - .id(getValidationEventId(this, trait)) - .severity(severity) - .shape(shape) - .sourceLocation(left.getSourceLocation()) - .message(message) - .build() + ValidationEvent.builder() + .id(getValidationEventId(this, trait)) + .severity(severity) + .shape(shape) + .sourceLocation(left.getSourceLocation()) + .message(message) + .build() ); } }, @@ -294,13 +294,13 @@ List validate( UPDATE { @Override List validate( - Model model, - String path, - Shape shape, - ShapeId trait, - Node left, - Node right, - Severity severity + Model model, + String path, + Shape shape, + ShapeId trait, + Node left, + Node right, + Severity severity ) { if (left == null || right == null || Objects.equals(left, right)) { return Collections.emptyList(); @@ -313,21 +313,21 @@ List validate( message = String.format("Changed trait `%s` from %s to %s", trait, leftPretty, rightPretty); } else { message = String.format( - "Changed trait contents of `%s` at path `%s` from %s to %s", - trait, - path, - leftPretty, - rightPretty + "Changed trait contents of `%s` at path `%s` from %s to %s", + trait, + path, + leftPretty, + rightPretty ); } return Collections.singletonList( - ValidationEvent.builder() - .id(getValidationEventId(this, trait)) - .severity(severity) - .shape(shape) - .message(message) - .build() + ValidationEvent.builder() + .id(getValidationEventId(this, trait)) + .severity(severity) + .shape(shape) + .message(message) + .build() ); } }, @@ -335,13 +335,13 @@ List validate( CONST { @Override List validate( - Model model, - String path, - Shape shape, - ShapeId trait, - Node left, - Node right, - Severity severity + Model model, + String path, + Shape shape, + ShapeId trait, + Node left, + Node right, + Severity severity ) { List events = new ArrayList<>(); events.addAll(ADD.validate(model, path, shape, trait, left, right, severity)); @@ -354,13 +354,13 @@ List validate( CONTENTS { @Override List validate( - Model model, - String path, - Shape shape, - ShapeId trait, - Node left, - Node right, - Severity severity + Model model, + String path, + Shape shape, + ShapeId trait, + Node left, + Node right, + Severity severity ) { // The trait needs to exist in both models to perform this check. if (left == null || right == null) { @@ -382,34 +382,34 @@ List validate( }; abstract List validate( - Model model, - String path, - Shape shape, - ShapeId trait, - Node left, - Node right, - Severity severity + Model model, + String path, + Shape shape, + ShapeId trait, + Node left, + Node right, + Severity severity ); private static String getValidationEventId(DiffType diffType, ShapeId trait) { return String.format( - "%s.%s.%s", - ModifiedTrait.class.getSimpleName(), - StringUtils.capitalize(StringUtils.lowerCase(diffType.toString())), - trait + "%s.%s.%s", + ModifiedTrait.class.getSimpleName(), + StringUtils.capitalize(StringUtils.lowerCase(diffType.toString())), + trait ); } } private static void crawlContents( - Model model, - Shape startingShape, - ShapeId trait, - Shape currentTraitShape, - Node leftValue, - Node rightValue, - List events, - String path + Model model, + Shape startingShape, + ShapeId trait, + Shape currentTraitShape, + Node leftValue, + Node rightValue, + List events, + String path ) { currentTraitShape.accept(new DiffCrawler(model, startingShape, trait, leftValue, rightValue, events, path)); } @@ -425,13 +425,13 @@ private static final class DiffCrawler extends ShapeVisitor.Default { private final String path; DiffCrawler( - Model model, - Shape startingShape, - ShapeId trait, - Node leftValue, - Node rightValue, - List events, - String path + Model model, + Shape startingShape, + ShapeId trait, + Node leftValue, + Node rightValue, + List events, + String path ) { this.model = model; this.startingShape = startingShape; @@ -453,25 +453,25 @@ public Void listShape(ListShape shape) { Node element = leftValues.get(i); if (rightValues.size() > i) { crawlContents( - model, - startingShape, - trait, - shape.getMember(), - element, - rightValues.get(i), - events, - path + '/' + i + model, + startingShape, + trait, + shape.getMember(), + element, + rightValues.get(i), + events, + path + '/' + i ); } else { crawlContents( - model, - startingShape, - trait, - shape.getMember(), - element, - null, - events, - path + '/' + i + model, + startingShape, + trait, + shape.getMember(), + element, + null, + events, + path + '/' + i ); } } @@ -481,14 +481,14 @@ public Void listShape(ListShape shape) { Node element = rightValues.get(i); if (leftValues.size() <= i) { crawlContents( - model, - startingShape, - trait, - shape.getMember(), - null, - element, - events, - path + '/' + i + model, + startingShape, + trait, + shape.getMember(), + null, + element, + events, + path + '/' + i ); } } @@ -506,29 +506,29 @@ public Void mapShape(MapShape shape) { for (Map.Entry entry : leftValues.entrySet()) { Node rightValue = rightValues.get(entry.getKey()); crawlContents( - model, - startingShape, - trait, - shape.getValue(), - entry.getValue(), - rightValue, - events, - path + '/' + entry.getKey() - ); - } - - // Look for added entries. - for (Map.Entry entry : rightValues.entrySet()) { - if (!leftValues.containsKey(entry.getKey())) { - crawlContents( model, startingShape, trait, shape.getValue(), - null, entry.getValue(), + rightValue, events, path + '/' + entry.getKey() + ); + } + + // Look for added entries. + for (Map.Entry entry : rightValues.entrySet()) { + if (!leftValues.containsKey(entry.getKey())) { + crawlContents( + model, + startingShape, + trait, + shape.getValue(), + null, + entry.getValue(), + events, + path + '/' + entry.getKey() ); } } @@ -558,14 +558,14 @@ private void crawlStructuredShape(Shape shape) { Node rightValue = rightObj.getMember(member.getMemberName()).orElse(null); if (leftValue != null || rightValue != null) { crawlContents( - model, - startingShape, - trait, - member, - leftValue, - rightValue, - events, - path + '/' + member.getMemberName() + model, + startingShape, + trait, + member, + leftValue, + rightValue, + events, + path + '/' + member.getMemberName() ); } } @@ -577,15 +577,15 @@ public Void memberShape(MemberShape shape) { List strategies = createStrategiesForShape(shape, false); for (DiffStrategy strategy : strategies) { events.addAll( - strategy.diffType.validate( - model, - path, - startingShape, - trait, - leftValue, - rightValue, - strategy.severity - ) + strategy.diffType.validate( + model, + path, + startingShape, + trait, + leftValue, + rightValue, + strategy.severity + ) ); } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedEntityBinding.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedEntityBinding.java index 8c65557ffa3..e950729f6cc 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedEntityBinding.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedEntityBinding.java @@ -39,10 +39,10 @@ public List evaluate(Differences differences) { private void validateOperation(ChangedShape change, List events) { findRemoved(change.getOldShape().getOperations(), change.getNewShape().getOperations()) - .forEach(removed -> events.add(createRemovedEvent(REMOVED_OPERATION, change.getNewShape(), removed))); + .forEach(removed -> events.add(createRemovedEvent(REMOVED_OPERATION, change.getNewShape(), removed))); findRemoved(change.getOldShape().getResources(), change.getNewShape().getResources()) - .forEach(removed -> events.add(createRemovedEvent(REMOVED_RESOURCE, change.getNewShape(), removed))); + .forEach(removed -> events.add(createRemovedEvent(REMOVED_RESOURCE, change.getNewShape(), removed))); } private Set findRemoved(Set oldShapes, Set newShapes) { @@ -55,17 +55,17 @@ private ValidationEvent createRemovedEvent(String typeOfRemoval, EntityShape par String childType = typeOfRemoval.equals(REMOVED_RESOURCE) ? "Resource" : "Operation"; String typeOfParentShape = ShapeType.RESOURCE.equals(parentEntity.getType()) ? FROM_RESOURCE : FROM_SERVICE; String message = String.format( - "%s binding of `%s` was removed from %s shape, `%s`", - childType, - childShape, - parentEntity.getType(), - parentEntity.getId() + "%s binding of `%s` was removed from %s shape, `%s`", + childType, + childShape, + parentEntity.getType(), + parentEntity.getId() ); return ValidationEvent.builder() - .id(typeOfRemoval + typeOfParentShape + childShape.getName()) - .severity(Severity.ERROR) - .shape(parentEntity) - .message(message) - .build(); + .id(typeOfRemoval + typeOfParentShape + childShape.getName()) + .severity(Severity.ERROR) + .shape(parentEntity) + .message(message) + .build(); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedMetadata.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedMetadata.java index c8906c11641..7622091e0d8 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedMetadata.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedMetadata.java @@ -18,20 +18,20 @@ public final class RemovedMetadata extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.removedMetadata() - .map( - metadata -> ValidationEvent.builder() - .id(getEventId() + "." + metadata.getLeft()) - .severity(Severity.DANGER) - .sourceLocation(metadata.getRight().getSourceLocation()) - .message( - String.format( - "Metadata key `%s` was removed with the following value: %s", - metadata.getLeft(), - Node.prettyPrintJson(metadata.getRight()) - ) - ) - .build() - ) - .collect(Collectors.toList()); + .map( + metadata -> ValidationEvent.builder() + .id(getEventId() + "." + metadata.getLeft()) + .severity(Severity.DANGER) + .sourceLocation(metadata.getRight().getSourceLocation()) + .message( + String.format( + "Metadata key `%s` was removed with the following value: %s", + metadata.getLeft(), + Node.prettyPrintJson(metadata.getRight()) + ) + ) + .build() + ) + .collect(Collectors.toList()); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedOperationError.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedOperationError.java index f2b941759f7..567459edde4 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedOperationError.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedOperationError.java @@ -22,8 +22,8 @@ public final class RemovedOperationError extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.changedShapes(OperationShape.class) - .flatMap(change -> createErrorViolations(change).stream()) - .collect(Collectors.toList()); + .flatMap(change -> createErrorViolations(change).stream()) + .collect(Collectors.toList()); } private List createErrorViolations(ChangedShape change) { @@ -35,18 +35,18 @@ private List createErrorViolations(ChangedShape for (ShapeId error : change.getOldShape().getErrors()) { if (!change.getNewShape().getErrors().contains(error)) { events.add( - ValidationEvent.builder() - .id(getEventId() + "." + error.getName()) - .severity(Severity.WARNING) - .message( - String.format( - "The `%s` error was removed from the `%s` operation.", - error, - change.getShapeId() - ) - ) - .shape(change.getNewShape()) - .build() + ValidationEvent.builder() + .id(getEventId() + "." + error.getName()) + .severity(Severity.WARNING) + .message( + String.format( + "The `%s` error was removed from the `%s` operation.", + error, + change.getShapeId() + ) + ) + .shape(change.getNewShape()) + .build() ); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedServiceError.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedServiceError.java index 0589ccd1933..3eafb435d88 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedServiceError.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedServiceError.java @@ -21,8 +21,8 @@ public final class RemovedServiceError extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.changedShapes(ServiceShape.class) - .flatMap(change -> createErrorViolations(change).stream()) - .collect(Collectors.toList()); + .flatMap(change -> createErrorViolations(change).stream()) + .collect(Collectors.toList()); } private List createErrorViolations(ChangedShape change) { @@ -34,16 +34,16 @@ private List createErrorViolations(ChangedShape c for (ShapeId id : change.getOldShape().getErrors()) { if (!change.getNewShape().getErrors().contains(id)) { events.add( - warning( - change.getNewShape(), - String.format( - "The `%s` error was removed from the `%s` service. This means that it " - + "is no longer considered an error common to all operations within the " - + "service.", - change.getShapeId(), - id + warning( + change.getNewShape(), + String.format( + "The `%s` error was removed from the `%s` service. This means that it " + + "is no longer considered an error common to all operations within the " + + "service.", + change.getShapeId(), + id + ) ) - ) ); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedShape.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedShape.java index 274d82221dd..b121e5dc903 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedShape.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedShape.java @@ -22,41 +22,41 @@ public final class RemovedShape extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.removedShapes() - .filter(shape -> !shape.hasTrait(PrivateTrait.class)) - .filter(shape -> !isMemberOfRemovedShape(shape, differences)) - .map( - shape -> isInconsequentialType(shape) - ? ValidationEvent.builder() - .severity(Severity.WARNING) - .message(String.format("Removed %s `%s`", shape.getType(), shape.getId())) - .shapeId(shape.getId()) - .id(getEventId() + ".ScalarShape") - .sourceLocation(shape.getSourceLocation()) - .build() - : error(shape, String.format("Removed %s `%s`", shape.getType(), shape.getId())) - ) - .collect(Collectors.toList()); + .filter(shape -> !shape.hasTrait(PrivateTrait.class)) + .filter(shape -> !isMemberOfRemovedShape(shape, differences)) + .map( + shape -> isInconsequentialType(shape) + ? ValidationEvent.builder() + .severity(Severity.WARNING) + .message(String.format("Removed %s `%s`", shape.getType(), shape.getId())) + .shapeId(shape.getId()) + .id(getEventId() + ".ScalarShape") + .sourceLocation(shape.getSourceLocation()) + .build() + : error(shape, String.format("Removed %s `%s`", shape.getType(), shape.getId())) + ) + .collect(Collectors.toList()); } private boolean isMemberOfRemovedShape(Shape shape, Differences differences) { return shape.asMemberShape() - .filter(member -> !differences.getNewModel().getShapeIds().contains(member.getContainer())) - .isPresent(); + .filter(member -> !differences.getNewModel().getShapeIds().contains(member.getContainer())) + .isPresent(); } private boolean isInconsequentialType(Shape shape) { ShapeType shapeType = shape.getType(); return shapeType == ShapeType.BIG_DECIMAL - || shapeType == ShapeType.BIG_INTEGER - || shapeType == ShapeType.BLOB - || shapeType == ShapeType.BOOLEAN - || shapeType == ShapeType.BYTE - || shapeType == ShapeType.DOUBLE - || shapeType == ShapeType.FLOAT - || shapeType == ShapeType.SHORT - || shapeType == ShapeType.TIMESTAMP - || shapeType == ShapeType.LONG - || ((shapeType == ShapeType.STRING) && !shape.hasTrait(EnumTrait.class)) - || (shapeType == ShapeType.INTEGER); + || shapeType == ShapeType.BIG_INTEGER + || shapeType == ShapeType.BLOB + || shapeType == ShapeType.BOOLEAN + || shapeType == ShapeType.BYTE + || shapeType == ShapeType.DOUBLE + || shapeType == ShapeType.FLOAT + || shapeType == ShapeType.SHORT + || shapeType == ShapeType.TIMESTAMP + || shapeType == ShapeType.LONG + || ((shapeType == ShapeType.STRING) && !shape.hasTrait(EnumTrait.class)) + || (shapeType == ShapeType.INTEGER); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedTraitDefinition.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedTraitDefinition.java index d77d1ba3cc6..1f7bead9b3e 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedTraitDefinition.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedTraitDefinition.java @@ -18,16 +18,16 @@ public final class RemovedTraitDefinition extends AbstractDiffEvaluator { @Override public List evaluate(Differences differences) { return differences.removedShapes() - .filter(shape -> shape.hasTrait(TraitDefinition.class)) - .map( - shape -> ValidationEvent.builder() - .id(getEventId()) - .severity(Severity.ERROR) - .shape(shape) - .sourceLocation(shape.expectTrait(TraitDefinition.class).getSourceLocation()) - .message(String.format("Trait definition `%s` was removed", shape.getId())) - .build() - ) - .collect(Collectors.toList()); + .filter(shape -> shape.hasTrait(TraitDefinition.class)) + .map( + shape -> ValidationEvent.builder() + .id(getEventId()) + .severity(Severity.ERROR) + .shape(shape) + .sourceLocation(shape.expectTrait(TraitDefinition.class).getSourceLocation()) + .message(String.format("Trait definition `%s` was removed", shape.getId())) + .build() + ) + .collect(Collectors.toList()); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ServiceRename.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ServiceRename.java index 358db59cbf5..8fa1292a772 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ServiceRename.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ServiceRename.java @@ -27,64 +27,64 @@ public List evaluate(Differences differences) { Walker oldWalker = new Walker(differences.getOldModel()); return differences.changedShapes(ServiceShape.class) - .flatMap(diff -> { - ServiceShape oldShape = diff.getOldShape(); - ServiceShape newShape = diff.getNewShape(); - if (oldShape.getRename().equals(newShape.getRename())) { - return Stream.empty(); - } - - // Look for the removal or changing of old renames. - List events = new ArrayList<>(); - for (Map.Entry old : oldShape.getRename().entrySet()) { - String newValue = newShape.getRename().get(old.getKey()); - if (newValue == null) { - events.add( - error( - newShape, - String.format( - "Service rename of `%s` to `%s` was removed", - old.getKey(), - old.getValue() - ) - ) - ); - } else if (!old.getValue().equals(newValue)) { - events.add( - error( - newShape, - String.format( - "Service rename of `%s` was changed from `%s` to `%s`", - old.getKey(), - old.getValue(), - newValue - ) - ) - ); + .flatMap(diff -> { + ServiceShape oldShape = diff.getOldShape(); + ServiceShape newShape = diff.getNewShape(); + if (oldShape.getRename().equals(newShape.getRename())) { + return Stream.empty(); } - } - // Look for the addition of new renames to shapes already in the closure. - Set oldClosure = oldWalker.walkShapeIds(oldShape); - for (Map.Entry newEntry : newShape.getRename().entrySet()) { - if (!oldShape.getRename().containsKey(newEntry.getKey())) { - if (oldClosure.contains(newEntry.getKey())) { + // Look for the removal or changing of old renames. + List events = new ArrayList<>(); + for (Map.Entry old : oldShape.getRename().entrySet()) { + String newValue = newShape.getRename().get(old.getKey()); + if (newValue == null) { + events.add( + error( + newShape, + String.format( + "Service rename of `%s` to `%s` was removed", + old.getKey(), + old.getValue() + ) + ) + ); + } else if (!old.getValue().equals(newValue)) { events.add( - error( - newShape, - String.format( - "Service rename of `%s` to `%s` was added to an old shape", - newEntry.getKey(), - newEntry.getValue() + error( + newShape, + String.format( + "Service rename of `%s` was changed from `%s` to `%s`", + old.getKey(), + old.getValue(), + newValue + ) ) - ) ); } } - } - return events.stream(); - }) - .collect(Collectors.toList()); + // Look for the addition of new renames to shapes already in the closure. + Set oldClosure = oldWalker.walkShapeIds(oldShape); + for (Map.Entry newEntry : newShape.getRename().entrySet()) { + if (!oldShape.getRename().containsKey(newEntry.getKey())) { + if (oldClosure.contains(newEntry.getKey())) { + events.add( + error( + newShape, + String.format( + "Service rename of `%s` to `%s` was added to an old shape", + newEntry.getKey(), + newEntry.getValue() + ) + ) + ); + } + } + } + + return events.stream(); + }) + .collect(Collectors.toList()); } } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/TraitBreakingChange.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/TraitBreakingChange.java index c7d2ffd4778..dfcc94df1ae 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/TraitBreakingChange.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/TraitBreakingChange.java @@ -29,14 +29,14 @@ public final class TraitBreakingChange extends AbstractDiffEvaluator { private static final List ANY_TYPES = Arrays.asList( - TraitDefinition.ChangeType.ADD, - TraitDefinition.ChangeType.REMOVE, - TraitDefinition.ChangeType.UPDATE + TraitDefinition.ChangeType.ADD, + TraitDefinition.ChangeType.REMOVE, + TraitDefinition.ChangeType.UPDATE ); private static final List PRESENCE_TYPES = Arrays.asList( - TraitDefinition.ChangeType.ADD, - TraitDefinition.ChangeType.REMOVE + TraitDefinition.ChangeType.ADD, + TraitDefinition.ChangeType.REMOVE ); @Override @@ -50,15 +50,15 @@ public List evaluate(Differences differences) { // Use the breaking changes rules of the new trait. differences.getNewModel().getShape(traitId).ifPresent(traitShape -> { List rules = traitShape - .expectTrait(TraitDefinition.class) - .getBreakingChanges(); + .expectTrait(TraitDefinition.class) + .getBreakingChanges(); for (TraitDefinition.BreakingChangeRule rule : rules) { PathChecker checker = new PathChecker( - differences.getNewModel(), - traitShape, - changedShape.getNewShape(), - rule, - events + differences.getNewModel(), + traitShape, + changedShape.getNewShape(), + rule, + events ); checker.check(Node.from(oldTrait), Node.from(newTrait)); } @@ -78,11 +78,11 @@ private static final class PathChecker { private final List segements; PathChecker( - Model model, - Shape trait, - Shape targetShape, - TraitDefinition.BreakingChangeRule rule, - List events + Model model, + Shape trait, + Shape targetShape, + TraitDefinition.BreakingChangeRule rule, + List events ) { this.model = model; this.trait = trait; @@ -118,11 +118,11 @@ private void check(Node left, Node right) { } private void extract( - Map result, - Shape currentShape, - int segmentPosition, - Node currentValue, - String path + Map result, + Shape currentShape, + int segmentPosition, + Node currentValue, + String path ) { // Don't keep crawling when a "" segment is hit or the last segment is hit. if (segmentPosition >= segements.size() || segements.get(segmentPosition).isEmpty()) { @@ -143,22 +143,22 @@ private void extract( currentValue.asObjectNode().ifPresent(v -> { for (Map.Entry entry : v.getStringMap().entrySet()) { extract( - result, - nextShape, - segmentPosition + 1, - entry.getValue(), - path + "/" + entry.getKey() + result, + nextShape, + segmentPosition + 1, + entry.getValue(), + path + "/" + entry.getKey() ); } }); } else if (currentShape.isStructureShape() || currentShape.isUnionShape()) { currentValue.asObjectNode().ifPresent(v -> { extract( - result, - nextShape, - segmentPosition + 1, - v.getMember(segment).orElse(Node.nullNode()), - path + "/" + segment + result, + nextShape, + segmentPosition + 1, + v.getMember(segment).orElse(Node.nullNode()), + path + "/" + segment ); }); } @@ -178,13 +178,13 @@ private void compareResult(String path, Node left, Node right) { } FromSourceLocation location = !right.isNullNode() ? right : targetShape; events.add( - ValidationEvent.builder() - .id(getValidationEventId(type)) - .severity(rule.getDefaultedSeverity()) - .shape(targetShape) - .sourceLocation(location) - .message(message) - .build() + ValidationEvent.builder() + .id(getValidationEventId(type)) + .severity(rule.getDefaultedSeverity()) + .shape(targetShape) + .sourceLocation(location) + .message(message) + .build() ); } } @@ -192,10 +192,10 @@ private void compareResult(String path, Node left, Node right) { private String getValidationEventId(TraitDefinition.ChangeType type) { return String.format( - "%s.%s.%s", - TraitBreakingChange.class.getSimpleName(), - StringUtils.capitalize(type.toString()), - trait.getId() + "%s.%s.%s", + TraitBreakingChange.class.getSimpleName(), + StringUtils.capitalize(type.toString()), + trait.getId() ); } @@ -234,10 +234,10 @@ private String createBreakingMessage(TraitDefinition.ChangeType type, String pat case ADD: if (!path.isEmpty()) { return String.format( - "Added trait contents to `%s` at path `%s` with value %s", - trait.getId(), - path, - rightPretty + "Added trait contents to `%s` at path `%s` with value %s", + trait.getId(), + path, + rightPretty ); } else if (Node.objectNode().equals(right)) { return String.format("Added trait `%s`", trait.getId()); @@ -247,35 +247,35 @@ private String createBreakingMessage(TraitDefinition.ChangeType type, String pat case REMOVE: if (!path.isEmpty()) { return String.format( - "Removed trait contents from `%s` at path `%s`. Removed value: %s", - trait.getId(), - path, - leftPretty + "Removed trait contents from `%s` at path `%s`. Removed value: %s", + trait.getId(), + path, + leftPretty ); } else if (Node.objectNode().equals(left)) { return String.format("Removed trait `%s`", trait.getId()); } else { return String.format( - "Removed trait `%s`. Previous trait value: %s", - trait.getId(), - leftPretty + "Removed trait `%s`. Previous trait value: %s", + trait.getId(), + leftPretty ); } case UPDATE: if (!path.isEmpty()) { return String.format( - "Changed trait contents of `%s` at path `%s` from %s to %s", - trait.getId(), - path, - leftPretty, - rightPretty + "Changed trait contents of `%s` at path `%s` from %s to %s", + trait.getId(), + path, + leftPretty, + rightPretty ); } else { return String.format( - "Changed trait `%s` from %s to %s", - trait.getId(), - leftPretty, - rightPretty + "Changed trait `%s` from %s to %s", + trait.getId(), + leftPretty, + rightPretty ); } default: diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestCase.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestCase.java index ea89cd8330c..151f975d56b 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestCase.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestCase.java @@ -29,12 +29,12 @@ */ public final class SmithyDiffTestCase { private static final Pattern EVENT_PATTERN = Pattern.compile( - "^\\[(?SUPPRESSED|NOTE|WARNING|DANGER|ERROR)] " - + "(?[^ ]+): " - + "?(?.*) " - + "\\| " - + "(?[^)]+)", - Pattern.DOTALL + "^\\[(?SUPPRESSED|NOTE|WARNING|DANGER|ERROR)] " + + "(?[^ ]+): " + + "?(?.*) " + + "\\| " + + "(?[^)]+)", + Pattern.DOTALL ); private final Path path; @@ -47,9 +47,9 @@ public final class SmithyDiffTestCase { * @param expectedEvents The expected diff events to encounter. */ public SmithyDiffTestCase( - Path path, - String name, - List expectedEvents + Path path, + String name, + List expectedEvents ) { this.path = Objects.requireNonNull(path); this.name = Objects.requireNonNull(name); @@ -119,21 +119,21 @@ public List getExpectedEvents() { */ public Result createResult(List actualEvents) { List unmatchedEvents = expectedEvents.stream() - .filter( - expectedEvent -> actualEvents.stream() - .noneMatch(actualEvent -> compareEvents(expectedEvent, actualEvent)) - ) - .collect(Collectors.toList()); + .filter( + expectedEvent -> actualEvents.stream() + .noneMatch(actualEvent -> compareEvents(expectedEvent, actualEvent)) + ) + .collect(Collectors.toList()); List extraEvents = actualEvents.stream() - .filter( - actualEvent -> expectedEvents.stream() - .noneMatch(expectedEvent -> compareEvents(expectedEvent, actualEvent)) - ) - // Exclude suppressed events from needing to be defined as acceptable events. - // However, these can still be defined as required events. - .filter(event -> event.getSeverity() != Severity.SUPPRESSED) - .collect(Collectors.toList()); + .filter( + actualEvent -> expectedEvents.stream() + .noneMatch(expectedEvent -> compareEvents(expectedEvent, actualEvent)) + ) + // Exclude suppressed events from needing to be defined as acceptable events. + // However, these can still be defined as required events. + .filter(event -> event.getSeverity() != Severity.SUPPRESSED) + .collect(Collectors.toList()); return new SmithyDiffTestCase.Result(name, unmatchedEvents, extraEvents); } @@ -147,10 +147,10 @@ private static boolean compareEvents(ValidationEvent expected, ValidationEvent a String comparedMessage = normalizeMessage(expected.getMessage()); return expected.getSeverity() == actual.getSeverity() - && actual.containsId(expected.getId()) - && expected.getShapeId().equals(actual.getShapeId()) - // Normalize new lines. - && normalizedActualMessage.startsWith(comparedMessage); + && actual.containsId(expected.getId()) + && expected.getShapeId().equals(actual.getShapeId()) + // Normalize new lines. + && normalizedActualMessage.startsWith(comparedMessage); } // Newlines in persisted validation events are escaped. @@ -162,23 +162,23 @@ private static List loadExpectedEvents(Path path, String name) String fileName = path.resolve(name + SmithyDiffTestSuite.EVENTS).toString(); String contents = IoUtils.readUtf8File(fileName); return Arrays.stream(contents.split("-----")) - .map(chunk -> chunk.trim()) - .filter(chunk -> !chunk.isEmpty()) - .map(chunk -> parseValidationEvent(chunk, fileName)) - .collect(Collectors.toList()); + .map(chunk -> chunk.trim()) + .filter(chunk -> !chunk.isEmpty()) + .map(chunk -> parseValidationEvent(chunk, fileName)) + .collect(Collectors.toList()); } static ValidationEvent parseValidationEvent(String event, String fileName) { Matcher matcher = EVENT_PATTERN.matcher(event); if (!matcher.find()) { throw new IllegalArgumentException( - format( - "Invalid validation event in file `%s`, the following event did " - + "not match the expected regular expression `%s`: %s", - fileName, - EVENT_PATTERN.pattern(), - event - ) + format( + "Invalid validation event in file `%s`, the following event did " + + "not match the expected regular expression `%s`: %s", + fileName, + EVENT_PATTERN.pattern(), + event + ) ); } @@ -186,10 +186,10 @@ static ValidationEvent parseValidationEvent(String event, String fileName) { SourceLocation location = new SourceLocation("/", 0, 0); ValidationEvent.Builder builder = ValidationEvent.builder() - .severity(Severity.fromString(matcher.group("severity")).get()) - .sourceLocation(location) - .id(matcher.group("id")) - .message(matcher.group("message")); + .severity(Severity.fromString(matcher.group("severity")).get()) + .sourceLocation(location) + .id(matcher.group("id")) + .message(matcher.group("message")); // A shape ID of "-" means no shape. if (!matcher.group("shape").equals("-")) { @@ -208,9 +208,9 @@ public static final class Result { private final Collection extraEvents; Result( - String name, - Collection unmatchedEvents, - Collection extraEvents + String name, + Collection unmatchedEvents, + Collection extraEvents ) { this.name = name; this.unmatchedEvents = Collections.unmodifiableCollection(new TreeSet<>(unmatchedEvents)); @@ -222,18 +222,18 @@ public String toString() { StringBuilder builder = new StringBuilder(); builder - .append( - "============================\n" - + "Model Diff Validation Result\n" - + "============================\n" - ) - .append(name) - .append('\n'); + .append( + "============================\n" + + "Model Diff Validation Result\n" + + "============================\n" + ) + .append(name) + .append('\n'); if (!unmatchedEvents.isEmpty()) { builder.append( - "\nDid not match the following events\n" - + "----------------------------------\n" + "\nDid not match the following events\n" + + "----------------------------------\n" ); for (ValidationEvent event : unmatchedEvents) { builder.append(event.toString()).append("\n\n"); @@ -242,8 +242,8 @@ public String toString() { if (!extraEvents.isEmpty()) { builder.append( - "\nEncountered unexpected events\n" - + "-----------------------------\n" + "\nEncountered unexpected events\n" + + "-----------------------------\n" ); for (ValidationEvent event : extraEvents) { builder.append(event.toString()).append("\n\n"); diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestSuite.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestSuite.java index 5733e787fc4..428065d426c 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestSuite.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestSuite.java @@ -98,9 +98,9 @@ public static Stream defaultParameterizedTestSource(Class contextCl ClassLoader classLoader = contextClass.getClassLoader(); ModelAssembler assembler = Model.assembler(classLoader).discoverModels(classLoader); return SmithyDiffTestSuite.runner() - .setModelAssemblerFactory(assembler::copy) - .addTestCasesFromUrl(contextClass.getResource(DEFAULT_TEST_CASE_LOCATION)) - .parameterizedTestSource(); + .setModelAssemblerFactory(assembler::copy) + .addTestCasesFromUrl(contextClass.getResource(DEFAULT_TEST_CASE_LOCATION)) + .parameterizedTestSource(); } /** @@ -181,16 +181,19 @@ public SmithyDiffTestSuite addTestCasesFromDirectory(Path modelDirectory) { try (Stream files = Files.walk(modelDirectory)) { String modelDirectoryName = modelDirectory.toString(); files - .filter(Files::isRegularFile) - .map(Path::toString) - .filter(fileName -> fileName.endsWith(EVENTS)) - .map( - fileName -> SmithyDiffTestCase.from( - modelDirectory, - fileName.substring(modelDirectoryName.length() + 1, fileName.length() - EVENTS.length()) + .filter(Files::isRegularFile) + .map(Path::toString) + .filter(fileName -> fileName.endsWith(EVENTS)) + .map( + fileName -> SmithyDiffTestCase.from( + modelDirectory, + fileName.substring( + modelDirectoryName.length() + 1, + fileName.length() - EVENTS.length() + ) + ) ) - ) - .forEach(this::addTestCase); + .forEach(this::addTestCase); return this; } catch (IOException e) { throw new RuntimeException(e); @@ -249,10 +252,10 @@ public Stream> testCaseCallables() { private Callable createTestCaseCallable(SmithyDiffTestCase testCase) { return () -> testCase.createResult( - ModelDiff.compare( - getModel(testCase, modelAssemblerFactory.get(), MODEL_A), - getModel(testCase, modelAssemblerFactory.get(), MODEL_B) - ) + ModelDiff.compare( + getModel(testCase, modelAssemblerFactory.get(), MODEL_A), + getModel(testCase, modelAssemblerFactory.get(), MODEL_B) + ) ); } @@ -262,9 +265,9 @@ private static Model getModel(SmithyDiffTestCase testCase, ModelAssembler assemb modelPath = modelPath.resolveSibling(testCase.getName() + infix + EXT_JSON); } return assembler - .addImport(modelPath) - .assemble() - .unwrap(); + .addImport(modelPath) + .assemble() + .unwrap(); } /** @@ -316,7 +319,7 @@ public Result run(ExecutorService executorService) { } private SmithyDiffTestCase.Result waitOnFuture( - Future future + Future future ) throws InterruptedException { try { return future.get(); @@ -360,11 +363,11 @@ public List getFailedResults() { @Override public String toString() { StringBuilder builder = new StringBuilder( - String.format( - "Smithy diff test runner encountered %d successful result(s), and %d failed result(s)", - successCount, - failedResults.size() - ) + String.format( + "Smithy diff test runner encountered %d successful result(s), and %d failed result(s)", + successCount, + failedResults.size() + ) ); failedResults.forEach(failed -> builder.append('\n').append(failed.toString()).append('\n')); return builder.toString(); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/DifferencesTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/DifferencesTest.java index e63540797e4..297329ee08f 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/DifferencesTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/DifferencesTest.java @@ -72,9 +72,9 @@ public void detectsRemovedShapes() { public void detectsChangedShapes() { Shape shape1 = StringShape.builder().id("foo.bar#Baz").build(); Shape shape2 = StringShape.builder() - .id("foo.bar#Baz") - .addTrait(new SensitiveTrait()) - .build(); + .id("foo.bar#Baz") + .addTrait(new SensitiveTrait()) + .build(); Model previous = Model.assembler().addShape(shape1).assemble().unwrap(); Model current = Model.assembler().addShape(shape2).assemble().unwrap(); Differences differences = Differences.detect(previous, current); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/ModelDiffTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/ModelDiffTest.java index 7a26d621ec2..d2130ef87e0 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/ModelDiffTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/ModelDiffTest.java @@ -27,27 +27,27 @@ public void providesValidationResult() { Model oldModel = Model.builder().build(); Model newModel = Model.builder().build(); List oldEvents = Collections.singletonList( - ValidationEvent.builder() - .id("x") - .severity(Severity.ERROR) - .message("Hello") - .build() + ValidationEvent.builder() + .id("x") + .severity(Severity.ERROR) + .message("Hello") + .build() ); List newEvents = Collections.singletonList( - ValidationEvent.builder() - .id("y") - .severity(Severity.ERROR) - .message("Hello") - .build() + ValidationEvent.builder() + .id("y") + .severity(Severity.ERROR) + .message("Hello") + .build() ); ValidatedResult oldResult = new ValidatedResult<>(oldModel, oldEvents); ValidatedResult newResult = new ValidatedResult<>(newModel, newEvents); ModelDiff.Result result = ModelDiff.builder() - .oldModel(oldResult) - .newModel(newResult) - .compare(); + .oldModel(oldResult) + .newModel(newResult) + .compare(); assertThat(result.getOldModelEvents(), equalTo(oldEvents)); assertThat(result.getNewModelEvents(), equalTo(newEvents)); @@ -63,13 +63,13 @@ public void providesValidationResult() { @Test public void testsEquality() { Model oldModel = Model.builder() - .putMetadataProperty("foo", Node.from("baz")) - .addShape(StringShape.builder().id("smithy.example#Str").build()) - .build(); + .putMetadataProperty("foo", Node.from("baz")) + .addShape(StringShape.builder().id("smithy.example#Str").build()) + .build(); Model newModel = Model.builder() - .putMetadataProperty("foo", Node.from("bar")) - .addShape(StringShape.builder().id("smithy.example#Str").addTrait(new SensitiveTrait()).build()) - .build(); + .putMetadataProperty("foo", Node.from("bar")) + .addShape(StringShape.builder().id("smithy.example#Str").addTrait(new SensitiveTrait()).build()) + .build(); ModelDiff.Result result1 = ModelDiff.builder().oldModel(oldModel).newModel(newModel).compare(); ModelDiff.Result result2 = ModelDiff.builder().oldModel(oldModel).newModel(newModel).compare(); @@ -84,8 +84,8 @@ public void testsEquality() { @Test public void findsBreakingChanges() { Model oldModel = Model.builder() - .addShape(StructureShape.builder().id("smithy.example#Str").build()) - .build(); + .addShape(StructureShape.builder().id("smithy.example#Str").build()) + .build(); Model newModel = Model.builder().build(); ModelDiff.Result result = ModelDiff.builder().oldModel(oldModel).newModel(newModel).compare(); @@ -95,8 +95,8 @@ public void findsBreakingChanges() { @Test public void detectsWhenNoBreakingChanges() { Model model = Model.builder() - .addShape(StringShape.builder().id("smithy.example#Str").build()) - .build(); + .addShape(StringShape.builder().id("smithy.example#Str").build()) + .build(); ModelDiff.Result result = ModelDiff.builder().oldModel(model).newModel(model).compare(); assertThat(result.isDiffBreaking(), is(false)); @@ -105,18 +105,18 @@ public void detectsWhenNoBreakingChanges() { @Test public void appliesSuppressionsToDiff() { Model oldModel = Model.assembler() - .addImport(getClass().getResource("suppressions-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("suppressions-a.smithy")) + .assemble() + .unwrap(); Model newModel = Model.assembler() - .addImport(getClass().getResource("suppressions-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("suppressions-b.smithy")) + .assemble() + .unwrap(); ModelDiff.Result result = ModelDiff.builder() - .oldModel(oldModel) - .newModel(newModel) - .compare(); + .oldModel(oldModel) + .newModel(newModel) + .compare(); assertThat(result.isDiffBreaking(), is(false)); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedEntityBindingTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedEntityBindingTest.java index 8f4c15bd9a6..a1fd07576c3 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedEntityBindingTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedEntityBindingTest.java @@ -21,10 +21,10 @@ public class AddedEntityBindingTest { public void detectsAddedOperationToService() { OperationShape o = OperationShape.builder().id("foo.baz#Operation").build(); ServiceShape service1 = ServiceShape.builder() - .version("1") - .id("foo.baz#Service") - .addOperation(o.getId()) - .build(); + .version("1") + .id("foo.baz#Service") + .addOperation(o.getId()) + .build(); ServiceShape service2 = service1.toBuilder().clearOperations().build(); Model modelA = Model.assembler().addShapes(service2, o).assemble().unwrap(); Model modelB = Model.assembler().addShapes(service1, o).assemble().unwrap(); @@ -49,10 +49,10 @@ public void detectsAddedOperationToResource() { public void detectsAddedResourceToService() { ResourceShape r = ResourceShape.builder().id("foo.baz#Resource").build(); ServiceShape service1 = ServiceShape.builder() - .id("foo.baz#Service") - .version("1") - .addResource(r.getId()) - .build(); + .id("foo.baz#Service") + .version("1") + .addResource(r.getId()) + .build(); ServiceShape service2 = service1.toBuilder().clearResources().build(); Model modelA = Model.assembler().addShapes(service2, r).assemble().unwrap(); Model modelB = Model.assembler().addShapes(service1, r).assemble().unwrap(); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedOperationErrorTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedOperationErrorTest.java index 9f2b6c78df6..b4292377e46 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedOperationErrorTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedOperationErrorTest.java @@ -24,15 +24,15 @@ public void detectsAddedErrors() { SourceLocation s1 = new SourceLocation("main.smithy", 1, 2); SourceLocation s2 = new SourceLocation("main.smithy", 3, 4); Shape e1 = StructureShape.builder() - .id("foo.baz#E1") - .addTrait(new ErrorTrait("client")) - .source(s1) - .build(); + .id("foo.baz#E1") + .addTrait(new ErrorTrait("client")) + .source(s1) + .build(); Shape e2 = StructureShape.builder() - .id("foo.baz#E2") - .addTrait(new ErrorTrait("client")) - .source(s2) - .build(); + .id("foo.baz#E2") + .addTrait(new ErrorTrait("client")) + .source(s2) + .build(); OperationShape operation1 = OperationShape.builder().id("foo.baz#Operation").build(); Shape operation2 = operation1.toBuilder().addError(e1.getId()).addError(e2.getId()).build(); Model modelA = Model.assembler().addShapes(operation1, e1, e2).assemble().unwrap(); @@ -42,13 +42,13 @@ public void detectsAddedErrors() { assertThat(TestHelper.findEvents(events, "AddedOperationError").size(), equalTo(2)); assertThat(TestHelper.findEvents(events, "AddedOperationError.E1").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "AddedOperationError.E1").stream().findFirst().get().getSourceLocation(), - equalTo(s1) + TestHelper.findEvents(events, "AddedOperationError.E1").stream().findFirst().get().getSourceLocation(), + equalTo(s1) ); assertThat(TestHelper.findEvents(events, "AddedOperationError.E2").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "AddedOperationError.E2").stream().findFirst().get().getSourceLocation(), - equalTo(s2) + TestHelper.findEvents(events, "AddedOperationError.E2").stream().findFirst().get().getSourceLocation(), + equalTo(s2) ); } } diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedRequiredMemberTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedRequiredMemberTest.java index ed7684b2a8b..3cf28a2bcd3 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedRequiredMemberTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedRequiredMemberTest.java @@ -24,19 +24,19 @@ public class AddedRequiredMemberTest { public void addingRequiredTraitWithoutDefaultIsAnError() { StringShape s = StringShape.builder().id("smithy.example#Str").build(); StructureShape a = StructureShape.builder() - .id("smithy.example#A") - .build(); + .id("smithy.example#A") + .build(); SourceLocation source = new SourceLocation("main.smithy", 1, 2); MemberShape member = MemberShape.builder() - .id(a.getId().withMember("foo")) - .target(s.getId()) - .addTrait(new RequiredTrait()) - .source(source) - .build(); + .id(a.getId().withMember("foo")) + .target(s.getId()) + .addTrait(new RequiredTrait()) + .source(source) + .build(); StructureShape b = StructureShape.builder() - .id("smithy.example#A") - .addMember(member) - .build(); + .id("smithy.example#A") + .addMember(member) + .build(); Model model1 = Model.builder().addShapes(s, a).build(); Model model2 = Model.builder().addShapes(s, b).build(); ModelDiff.Result result = ModelDiff.builder().oldModel(model1).newModel(model2).compare(); @@ -44,19 +44,23 @@ public void addingRequiredTraitWithoutDefaultIsAnError() { assertThat(TestHelper.findEvents(result.getDiffEvents(), Severity.ERROR).size(), equalTo(1)); assertThat(TestHelper.findEvents(result.getDiffEvents(), "AddedRequiredMember").size(), equalTo(1)); assertThat( - TestHelper.findEvents(result.getDiffEvents(), "AddedRequiredMember").get(0).getShapeId().get().toString(), - equalTo("smithy.example#A$foo") + TestHelper.findEvents(result.getDiffEvents(), "AddedRequiredMember") + .get(0) + .getShapeId() + .get() + .toString(), + equalTo("smithy.example#A$foo") ); assertThat( - TestHelper.findEvents(result.getDiffEvents(), "AddedRequiredMember").get(0).getMessage(), - equalTo( - "Adding a new member with the `required` trait " + - "but not the `default` trait is backwards-incompatible." - ) + TestHelper.findEvents(result.getDiffEvents(), "AddedRequiredMember").get(0).getMessage(), + equalTo( + "Adding a new member with the `required` trait " + + "but not the `default` trait is backwards-incompatible." + ) ); assertThat( - TestHelper.findEvents(result.getDiffEvents(), "AddedRequiredMember").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(result.getDiffEvents(), "AddedRequiredMember").get(0).getSourceLocation(), + equalTo(source) ); } @@ -64,15 +68,15 @@ public void addingRequiredTraitWithoutDefaultIsAnError() { public void addingRequiredTraitWithDefaultIsOk() { StringShape s = StringShape.builder().id("smithy.example#Str").build(); StructureShape a = StructureShape.builder() - .id("smithy.example#A") - .build(); + .id("smithy.example#A") + .build(); StructureShape b = StructureShape.builder() - .id("smithy.example#A") - .addMember("foo", s.getId(), b2 -> { - b2.addTrait(new RequiredTrait()); - b2.addTrait(new DefaultTrait(new StringNode("default", SourceLocation.NONE))); - }) - .build(); + .id("smithy.example#A") + .addMember("foo", s.getId(), b2 -> { + b2.addTrait(new RequiredTrait()); + b2.addTrait(new DefaultTrait(new StringNode("default", SourceLocation.NONE))); + }) + .build(); Model model1 = Model.builder().addShapes(s, a).build(); Model model2 = Model.builder().addShapes(s, b).build(); ModelDiff.Result result = ModelDiff.builder().oldModel(model1).newModel(model2).compare(); @@ -84,17 +88,17 @@ public void addingRequiredTraitWithDefaultIsOk() { public void addingRequiredTraitToExistingMember() { StringShape s = StringShape.builder().id("smithy.example#Str").build(); StructureShape a = StructureShape.builder() - .id("smithy.example#A") - .addMember("foo", s.getId()) - .build(); + .id("smithy.example#A") + .addMember("foo", s.getId()) + .build(); StructureShape b = StructureShape.builder() - .id("smithy.example#A") - .addMember( - "foo", - s.getId(), - b2 -> b2.addTrait(new RequiredTrait()) - ) - .build(); + .id("smithy.example#A") + .addMember( + "foo", + s.getId(), + b2 -> b2.addTrait(new RequiredTrait()) + ) + .build(); Model model1 = Model.builder().addShapes(s, a).build(); Model model2 = Model.builder().addShapes(s, b).build(); ModelDiff.Result result = ModelDiff.builder().oldModel(model1).newModel(model2).compare(); @@ -106,9 +110,9 @@ public void addingRequiredTraitToExistingMember() { public void addingNewStructureWithRequiredMemberIsOk() { StringShape s = StringShape.builder().id("smithy.example#Str").build(); StructureShape b = StructureShape.builder() - .id("smithy.example#A") - .addMember("foo", s.getId(), b2 -> b2.addTrait(new RequiredTrait())) - .build(); + .id("smithy.example#A") + .addMember("foo", s.getId(), b2 -> b2.addTrait(new RequiredTrait())) + .build(); Model model1 = Model.builder().addShapes(s).build(); Model model2 = Model.builder().addShapes(s, b).build(); ModelDiff.Result result = ModelDiff.builder().oldModel(model1).newModel(model2).compare(); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedServiceErrorTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedServiceErrorTest.java index 5bcd2db5126..60405032db2 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedServiceErrorTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedServiceErrorTest.java @@ -21,13 +21,13 @@ public class AddedServiceErrorTest { @Test public void detectsAddedErrors() { Shape e1 = StructureShape.builder() - .id("foo.baz#E1") - .addTrait(new ErrorTrait("client")) - .build(); + .id("foo.baz#E1") + .addTrait(new ErrorTrait("client")) + .build(); Shape e2 = StructureShape.builder() - .id("foo.baz#E2") - .addTrait(new ErrorTrait("client")) - .build(); + .id("foo.baz#E2") + .addTrait(new ErrorTrait("client")) + .build(); ServiceShape service1 = ServiceShape.builder().id("foo.baz#S").version("X").build(); ServiceShape service2 = service1.toBuilder().addError(e1.getId()).addError(e2.getId()).build(); Model modelA = Model.assembler().addShapes(service1, e1, e2).assemble().unwrap(); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedShapeTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedShapeTest.java index ef8f60fcb0d..0da30a92649 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedShapeTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedShapeTest.java @@ -48,22 +48,22 @@ public void doesNotEmitForMembersOfAddedContainerShapes() { @Test public void doesNotEmitForMembersOfConvertedEnumShape() { Shape stringWithEnumTrait = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("FOO") - .value("FOO") - .build() - ) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .name("FOO") + .value("FOO") + .build() + ) + .build() + ) + .build(); Shape enumShape = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("FOO", "FOO") - .build(); + .id("foo.baz#Baz") + .addMember("FOO", "FOO") + .build(); Model modelA = Model.assembler().addShapes(stringWithEnumTrait).assemble().unwrap(); Model modelB = Model.assembler().addShapes(enumShape).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -74,22 +74,22 @@ public void doesNotEmitForMembersOfConvertedEnumShape() { @Test public void doesNotEmitForEnumShapeToEnumTrait() { Shape enumShape = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("FOO", "FOO") - .build(); + .id("foo.baz#Baz") + .addMember("FOO", "FOO") + .build(); Shape stringWithEnumTrait = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("FOO") - .value("FOO") - .build() - ) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .name("FOO") + .value("FOO") + .build() + ) + .build() + ) + .build(); Model modelA = Model.assembler().addShapes(enumShape).assemble().unwrap(); Model modelB = Model.assembler().addShapes(stringWithEnumTrait).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -100,37 +100,37 @@ public void doesNotEmitForEnumShapeToEnumTrait() { @Test public void doesNotEmitForEnumTraitToEnumTraitAddedEnum() { Shape stringWithEnumTraitA = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("FOO") - .value("FOO") - .build() - ) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .name("FOO") + .value("FOO") + .build() + ) + .build() + ) + .build(); Shape stringWithEnumTraitB = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("FOO") - .value("FOO") - .build() - ) - .addEnum( - EnumDefinition.builder() - .name("BAR") - .value("BAR") - .build() - ) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .name("FOO") + .value("FOO") + .build() + ) + .addEnum( + EnumDefinition.builder() + .name("BAR") + .value("BAR") + .build() + ) + .build() + ) + .build(); Model modelA = Model.assembler().addShapes(stringWithEnumTraitA).assemble().unwrap(); Model modelB = Model.assembler().addShapes(stringWithEnumTraitB).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -141,14 +141,14 @@ public void doesNotEmitForEnumTraitToEnumTraitAddedEnum() { @Test public void doesEmitForEnumShapeToEnumShapeAddedMember() { Shape enumShapeA = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("FOO", "FOO") - .build(); + .id("foo.baz#Baz") + .addMember("FOO", "FOO") + .build(); Shape enumShapeB = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("FOO", "FOO") - .addMember("BAR", "BAR") - .build(); + .id("foo.baz#Baz") + .addMember("FOO", "FOO") + .addMember("BAR", "BAR") + .build(); Model modelA = Model.assembler().addShapes(enumShapeA).assemble().unwrap(); Model modelB = Model.assembler().addShapes(enumShapeB).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -156,8 +156,8 @@ public void doesEmitForEnumShapeToEnumShapeAddedMember() { assertThat(TestHelper.findEvents(events, "AddedShape").size(), equalTo(1)); assertThat(enumShapeB.getMember("BAR").isPresent(), equalTo(true)); assertThat( - TestHelper.findEvents(events, enumShapeB.getMember("BAR").get().toShapeId()).size(), - equalTo(1) + TestHelper.findEvents(events, enumShapeB.getMember("BAR").get().toShapeId()).size(), + equalTo(1) ); } } diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedTraitDefinitionTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedTraitDefinitionTest.java index 6ce63709620..f19631b41fd 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedTraitDefinitionTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/AddedTraitDefinitionTest.java @@ -22,10 +22,10 @@ public class AddedTraitDefinitionTest { public void detectsAddedTraitDefinition() { SourceLocation source = new SourceLocation("main.smithy", 1, 2); Shape definition = StringShape.builder() - .id("foo.baz#bam") - .addTrait(TraitDefinition.builder().build()) - .source(source) - .build(); + .id("foo.baz#bam") + .addTrait(TraitDefinition.builder().build()) + .source(source) + .build(); Model modelA = Model.assembler().assemble().unwrap(); Model modelB = Model.assembler().addShape(definition).assemble().unwrap(); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedDefaultTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedDefaultTest.java index 4331de04049..9b221607068 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedDefaultTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedDefaultTest.java @@ -19,12 +19,12 @@ public class ChangedDefaultTest { @Test public void errorWhenDefaultIsRemovedFromShape() { String originalModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "@default(0)\n" - + "integer Integer\n"; + + "namespace smithy.example\n" + + "@default(0)\n" + + "integer Integer\n"; String updatedModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "integer Integer\n"; + + "namespace smithy.example\n" + + "integer Integer\n"; Model modelA = Model.assembler().addUnparsedModel("test.smithy", originalModel).assemble().unwrap(); Model modelB = Model.assembler().addUnparsedModel("test.smithy", updatedModel).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -36,12 +36,12 @@ public void errorWhenDefaultIsRemovedFromShape() { @Test public void errorWhenDefaultIsAddedToRoot() { String originalModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "integer Integer\n"; + + "namespace smithy.example\n" + + "integer Integer\n"; String updatedModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "@default(0)\n" - + "integer Integer\n"; + + "namespace smithy.example\n" + + "@default(0)\n" + + "integer Integer\n"; Model modelA = Model.assembler().addUnparsedModel("test.smithy", originalModel).assemble().unwrap(); Model modelB = Model.assembler().addUnparsedModel("test.smithy", updatedModel).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -53,13 +53,13 @@ public void errorWhenDefaultIsAddedToRoot() { @Test public void errorWhenDefaultIsChangedOnRoot() { String originalModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "@default(10)\n" - + "integer Integer\n"; + + "namespace smithy.example\n" + + "@default(10)\n" + + "integer Integer\n"; String updatedModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "@default(20)\n" - + "integer Integer\n"; + + "namespace smithy.example\n" + + "@default(20)\n" + + "integer Integer\n"; Model modelA = Model.assembler().addUnparsedModel("test.smithy", originalModel).assemble().unwrap(); Model modelB = Model.assembler().addUnparsedModel("test.smithy", updatedModel).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -71,15 +71,15 @@ public void errorWhenDefaultIsChangedOnRoot() { @Test public void dangerWhenDefaultIsChangedOnMember() { String originalModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " bar: Integer = 1\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " bar: Integer = 1\n" + + "}\n"; String updatedModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " bar: Integer = 2\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " bar: Integer = 2\n" + + "}\n"; Model modelA = Model.assembler().addUnparsedModel("test.smithy", originalModel).assemble().unwrap(); Model modelB = Model.assembler().addUnparsedModel("test.smithy", updatedModel).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -91,15 +91,15 @@ public void dangerWhenDefaultIsChangedOnMember() { @Test public void errorWhenDefaultIsAddedToMemberWithNoAddedDefault() { String originalModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " bar: Integer\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " bar: Integer\n" + + "}\n"; String updatedModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " bar: Integer = 1\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " bar: Integer = 1\n" + + "}\n"; Model modelA = Model.assembler().addUnparsedModel("test.smithy", originalModel).assemble().unwrap(); Model modelB = Model.assembler().addUnparsedModel("test.smithy", updatedModel).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -112,17 +112,17 @@ public void errorWhenDefaultIsAddedToMemberWithNoAddedDefault() { @Test public void updateModelWithAddedDefault() { String originalModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " @required\n" - + " bar: Integer\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " @required\n" + + " bar: Integer\n" + + "}\n"; String updatedModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " @addedDefault\n" - + " bar: Integer = 1\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " @addedDefault\n" + + " bar: Integer = 1\n" + + "}\n"; Model modelA = Model.assembler().addUnparsedModel("test.smithy", originalModel).assemble().unwrap(); Model modelB = Model.assembler().addUnparsedModel("test.smithy", updatedModel).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -134,15 +134,15 @@ public void updateModelWithAddedDefault() { @Test public void errorWhenDefaultChangesFromZeroToNonZeroValue() { String originalModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " bar: Integer = 0\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " bar: Integer = 0\n" + + "}\n"; String updatedModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " bar: Integer = 1\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " bar: Integer = 1\n" + + "}\n"; Model modelA = Model.assembler().addUnparsedModel("test.smithy", originalModel).assemble().unwrap(); Model modelB = Model.assembler().addUnparsedModel("test.smithy", updatedModel).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -154,15 +154,15 @@ public void errorWhenDefaultChangesFromZeroToNonZeroValue() { @Test public void errorWhenDefaultChangesFromNonZeroToZeroValue() { String originalModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " bar: Integer = 1\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " bar: Integer = 1\n" + + "}\n"; String updatedModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " bar: Integer = 0\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " bar: Integer = 0\n" + + "}\n"; Model modelA = Model.assembler().addUnparsedModel("test.smithy", originalModel).assemble().unwrap(); Model modelB = Model.assembler().addUnparsedModel("test.smithy", updatedModel).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -174,15 +174,15 @@ public void errorWhenDefaultChangesFromNonZeroToZeroValue() { @Test public void addingTheDefaultTraitToNullableMemberEmitsNoEvents() { String originalModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " bar: Integer\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " bar: Integer\n" + + "}\n"; String updatedModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " bar: Integer = null\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " bar: Integer = null\n" + + "}\n"; Model modelA = Model.assembler().addUnparsedModel("test.smithy", originalModel).assemble().unwrap(); Model modelB = Model.assembler().addUnparsedModel("test.smithy", updatedModel).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -194,15 +194,15 @@ public void addingTheDefaultTraitToNullableMemberEmitsNoEvents() { @Test public void changingFromNullDefaultToOneIsBreaking() { String originalModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " bar: Integer = null\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " bar: Integer = null\n" + + "}\n"; String updatedModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " bar: Integer = 1\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " bar: Integer = 1\n" + + "}\n"; Model modelA = Model.assembler().addUnparsedModel("test.smithy", originalModel).assemble().unwrap(); Model modelB = Model.assembler().addUnparsedModel("test.smithy", updatedModel).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -214,15 +214,15 @@ public void changingFromNullDefaultToOneIsBreaking() { @Test public void changingFromNullDefaultToZeroIsBreaking() { String originalModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " bar: Integer = null\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " bar: Integer = null\n" + + "}\n"; String updatedModel = "$version: \"2\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " bar: Integer = 0\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " bar: Integer = 0\n" + + "}\n"; Model modelA = Model.assembler().addUnparsedModel("test.smithy", originalModel).assemble().unwrap(); Model modelB = Model.assembler().addUnparsedModel("test.smithy", updatedModel).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedEnumTraitTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedEnumTraitTest.java index 0d62a3eeb88..2f79ede958d 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedEnumTraitTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedEnumTraitTest.java @@ -25,24 +25,24 @@ public class ChangedEnumTraitTest { public void detectsAppendedEnums() { SourceLocation source = new SourceLocation("main.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum(EnumDefinition.builder().value("foo").build()) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum(EnumDefinition.builder().value("foo").build()) + .build() + ) + .build(); StringShape s2 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum(EnumDefinition.builder().value("foo").build()) - .addEnum(EnumDefinition.builder().value("baz").build()) - .addEnum(EnumDefinition.builder().value("bar").build()) - .sourceLocation(source) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum(EnumDefinition.builder().value("foo").build()) + .addEnum(EnumDefinition.builder().value("baz").build()) + .addEnum(EnumDefinition.builder().value("bar").build()) + .sourceLocation(source) + .build() + ) + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -52,16 +52,16 @@ public void detectsAppendedEnums() { assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.Appended.1").size(), equalTo(1)); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.Appended.2").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.Appended") - .stream() - .allMatch(e -> e.getSeverity() == Severity.NOTE), - equalTo(true) + TestHelper.findEvents(events, "ChangedEnumTrait.Appended") + .stream() + .allMatch(e -> e.getSeverity() == Severity.NOTE), + equalTo(true) ); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.Appended") - .stream() - .allMatch(e -> source.equals(e.getSourceLocation())), - equalTo(true) + TestHelper.findEvents(events, "ChangedEnumTrait.Appended") + .stream() + .allMatch(e -> source.equals(e.getSourceLocation())), + equalTo(true) ); } @@ -69,23 +69,23 @@ public void detectsAppendedEnums() { public void detectsAppendedEnumsEnumTraitNoNameToEnumShape() { SourceLocation source = new SourceLocation("main.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .value("foo") - .build() - ) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .value("foo") + .build() + ) + .build() + ) + .build(); EnumShape s2 = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("foo", "foo") - .addMember("baz", "baz") - .source(source) - .build(); + .id("foo.baz#Baz") + .addMember("foo", "foo") + .addMember("baz", "baz") + .source(source) + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -93,20 +93,20 @@ public void detectsAppendedEnumsEnumTraitNoNameToEnumShape() { assertThat(TestHelper.findEvents(events, "ChangedEnumTrait").size(), equalTo(2)); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSeverity(), - equalTo(Severity.ERROR) + TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSeverity(), + equalTo(Severity.ERROR) ); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSourceLocation(), + equalTo(source) ); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.Appended.1").get(0).getSeverity(), - equalTo(Severity.NOTE) + TestHelper.findEvents(events, "ChangedEnumTrait.Appended.1").get(0).getSeverity(), + equalTo(Severity.NOTE) ); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.Appended.1").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.Appended.1").get(0).getSourceLocation(), + equalTo(source) ); } @@ -114,39 +114,39 @@ public void detectsAppendedEnumsEnumTraitNoNameToEnumShape() { public void detectsAppendedEnumsEnumTraitWithNameToEnumShape() { SourceLocation source = new SourceLocation("main.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("foo") - .value("foo") - .build() - ) - .sourceLocation(source) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .name("foo") + .value("foo") + .build() + ) + .sourceLocation(source) + .build() + ) + .build(); EnumShape s2 = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("foo", "foo") - .addMember("baz", "baz") - .source(source) - .build(); + .id("foo.baz#Baz") + .addMember("foo", "foo") + .addMember("baz", "baz") + .source(source) + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.Appended.1").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait").get(0).getSourceLocation(), + equalTo(source) ); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.Appended") - .stream() - .allMatch(e -> e.getSeverity() == Severity.NOTE), - equalTo(true) + TestHelper.findEvents(events, "ChangedEnumTrait.Appended") + .stream() + .allMatch(e -> e.getSeverity() == Severity.NOTE), + equalTo(true) ); } @@ -154,37 +154,37 @@ public void detectsAppendedEnumsEnumTraitWithNameToEnumShape() { public void detectsRemovedEnums() { SourceLocation source = new SourceLocation("main.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum(EnumDefinition.builder().value("foo").build()) - .addEnum(EnumDefinition.builder().value("baz").build()) - .addEnum(EnumDefinition.builder().value("bat").build()) - .sourceLocation(source) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum(EnumDefinition.builder().value("foo").build()) + .addEnum(EnumDefinition.builder().value("baz").build()) + .addEnum(EnumDefinition.builder().value("bat").build()) + .sourceLocation(source) + .build() + ) + .build(); StringShape s2 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum(EnumDefinition.builder().value("foo").build()) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum(EnumDefinition.builder().value("foo").build()) + .build() + ) + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1").get(0).getSourceLocation(), + equalTo(source) ); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.Removed.2").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.Removed.2").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.Removed.2").get(0).getSourceLocation(), + equalTo(source) ); assertThat(TestHelper.findEvents(events, Severity.ERROR).size(), equalTo(2)); } @@ -194,47 +194,47 @@ public void detectsRemovedEnumsEnumTraitNoNameToEnumShape() { SourceLocation beforeSource = new SourceLocation("before.smithy", 1, 2); SourceLocation afterSource = new SourceLocation("after.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .value("foo") - .build() - ) - .addEnum( - EnumDefinition.builder() - .value("baz") - .build() - ) - .sourceLocation(beforeSource) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .value("foo") + .build() + ) + .addEnum( + EnumDefinition.builder() + .value("baz") + .build() + ) + .sourceLocation(beforeSource) + .build() + ) + .build(); EnumShape s2 = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("foo", "foo") - .source(afterSource) - .build(); + .id("foo.baz#Baz") + .addMember("foo", "foo") + .source(afterSource) + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1").get(0).getSourceLocation(), - equalTo(beforeSource) + TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1").get(0).getSourceLocation(), + equalTo(beforeSource) ); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSourceLocation(), - equalTo(afterSource) + TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSourceLocation(), + equalTo(afterSource) ); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait") - .stream() - .allMatch(e -> e.getSeverity() == Severity.ERROR), - equalTo(true) + TestHelper.findEvents(events, "ChangedEnumTrait") + .stream() + .allMatch(e -> e.getSeverity() == Severity.ERROR), + equalTo(true) ); } @@ -242,43 +242,43 @@ public void detectsRemovedEnumsEnumTraitNoNameToEnumShape() { public void detectsRemovedEnumsEnumTraitWithNameToEnumShape() { SourceLocation source = new SourceLocation("main.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("foo") - .value("foo") - .build() - ) - .addEnum( - EnumDefinition.builder() - .name("baz") - .value("baz") - .build() - ) - .sourceLocation(source) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .name("foo") + .value("foo") + .build() + ) + .addEnum( + EnumDefinition.builder() + .name("baz") + .value("baz") + .build() + ) + .sourceLocation(source) + .build() + ) + .build(); EnumShape s2 = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("foo", "foo") - .build(); + .id("foo.baz#Baz") + .addMember("foo", "foo") + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1").get(0).getSourceLocation(), + equalTo(source) ); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1") - .stream() - .allMatch(e -> e.getSeverity() == Severity.ERROR), - equalTo(true) + TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1") + .stream() + .allMatch(e -> e.getSeverity() == Severity.ERROR), + equalTo(true) ); } @@ -286,37 +286,37 @@ public void detectsRemovedEnumsEnumTraitWithNameToEnumShape() { public void detectsRenamedEnums() { SourceLocation source = new SourceLocation("main.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum(EnumDefinition.builder().value("foo").name("OLD1").build()) - .addEnum(EnumDefinition.builder().value("baz").name("OLD2").build()) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum(EnumDefinition.builder().value("foo").name("OLD1").build()) + .addEnum(EnumDefinition.builder().value("baz").name("OLD2").build()) + .build() + ) + .build(); StringShape s2 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum(EnumDefinition.builder().value("foo").name("NEW1").build()) - .addEnum(EnumDefinition.builder().value("baz").name("NEW2").build()) - .build() - ) - .source(source) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum(EnumDefinition.builder().value("foo").name("NEW1").build()) + .addEnum(EnumDefinition.builder().value("baz").name("NEW2").build()) + .build() + ) + .source(source) + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSourceLocation(), + equalTo(source) ); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.1").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.1").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.1").get(0).getSourceLocation(), + equalTo(source) ); assertThat(TestHelper.findEvents(events, Severity.ERROR).size(), equalTo(2)); } @@ -325,34 +325,34 @@ public void detectsRenamedEnums() { public void detectsRenamedEnumsEnumTraitNoNameToEnumShape() { SourceLocation source = new SourceLocation("main.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .value("foo") - .build() - ) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .value("foo") + .build() + ) + .build() + ) + .build(); EnumShape s2 = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("NEW", "foo") - .source(source) - .build(); + .id("foo.baz#Baz") + .addMember("NEW", "foo") + .source(source) + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSourceLocation(), + equalTo(source) ); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSeverity(), - equalTo(Severity.ERROR) + TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSeverity(), + equalTo(Severity.ERROR) ); } @@ -360,35 +360,35 @@ public void detectsRenamedEnumsEnumTraitNoNameToEnumShape() { public void detectsRenamedEnumsEnumTraitWithNameToEnumShape() { SourceLocation source = new SourceLocation("main.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("OLD") - .value("foo") - .build() - ) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .name("OLD") + .value("foo") + .build() + ) + .build() + ) + .build(); EnumShape s2 = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("NEW", "foo") - .source(source) - .build(); + .id("foo.baz#Baz") + .addMember("NEW", "foo") + .source(source) + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSourceLocation(), + equalTo(source) ); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSeverity(), - equalTo(Severity.ERROR) + TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSeverity(), + equalTo(Severity.ERROR) ); } @@ -396,37 +396,37 @@ public void detectsRenamedEnumsEnumTraitWithNameToEnumShape() { public void detectsInsertedEnums() { SourceLocation source = new SourceLocation("main.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum(EnumDefinition.builder().value("foo").build()) - .sourceLocation(source) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum(EnumDefinition.builder().value("foo").build()) + .sourceLocation(source) + .build() + ) + .build(); StringShape s2 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum(EnumDefinition.builder().value("baz").build()) - .addEnum(EnumDefinition.builder().value("bat").build()) - .addEnum(EnumDefinition.builder().value("foo").build()) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum(EnumDefinition.builder().value("baz").build()) + .addEnum(EnumDefinition.builder().value("bat").build()) + .addEnum(EnumDefinition.builder().value("foo").build()) + .build() + ) + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.0").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.0").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.0").get(0).getSourceLocation(), + equalTo(source) ); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.1").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.1").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.1").get(0).getSourceLocation(), + equalTo(source) ); assertThat(TestHelper.findEvents(events, Severity.ERROR).size(), equalTo(2)); } @@ -435,42 +435,42 @@ public void detectsInsertedEnums() { public void detectsInsertedEnumsBeforeAppendedEnums() { SourceLocation source = new SourceLocation("main.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum(EnumDefinition.builder().value("foo").build()) - .sourceLocation(source) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum(EnumDefinition.builder().value("foo").build()) + .sourceLocation(source) + .build() + ) + .build(); StringShape s2 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum(EnumDefinition.builder().value("baz").build()) - .addEnum(EnumDefinition.builder().value("bat").build()) - .addEnum(EnumDefinition.builder().value("foo").build()) - .addEnum(EnumDefinition.builder().value("bar").build()) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum(EnumDefinition.builder().value("baz").build()) + .addEnum(EnumDefinition.builder().value("bat").build()) + .addEnum(EnumDefinition.builder().value("foo").build()) + .addEnum(EnumDefinition.builder().value("bar").build()) + .build() + ) + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.0").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.0") - .get(0) - .getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.0") + .get(0) + .getSourceLocation(), + equalTo(source) ); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.1").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.1") - .get(0) - .getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.1") + .get(0) + .getSourceLocation(), + equalTo(source) ); assertThat(TestHelper.findEvents(events, Severity.ERROR).size(), equalTo(2)); } @@ -479,23 +479,23 @@ public void detectsInsertedEnumsBeforeAppendedEnums() { public void detectsInsertedEnumsEnumTraitNoNameToEnumShape() { SourceLocation source = new SourceLocation("main.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .value("foo") - .build() - ) - .sourceLocation(source) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .value("foo") + .build() + ) + .sourceLocation(source) + .build() + ) + .build(); EnumShape s2 = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("baz", "baz") - .addMember("foo", "foo") - .build(); + .id("foo.baz#Baz") + .addMember("baz", "baz") + .addMember("foo", "foo") + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -503,14 +503,14 @@ public void detectsInsertedEnumsEnumTraitNoNameToEnumShape() { assertThat(TestHelper.findEvents(events, "ChangedEnumTrait").size(), equalTo(2)); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.0").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.0").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.0").get(0).getSourceLocation(), + equalTo(source) ); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait") - .stream() - .allMatch(e -> e.getSeverity() == Severity.ERROR), - equalTo(true) + TestHelper.findEvents(events, "ChangedEnumTrait") + .stream() + .allMatch(e -> e.getSeverity() == Severity.ERROR), + equalTo(true) ); } @@ -518,38 +518,38 @@ public void detectsInsertedEnumsEnumTraitNoNameToEnumShape() { public void detectsInsertedEnumsEnumTraitWithNameToEnumShape() { SourceLocation source = new SourceLocation("main.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("foo") - .value("foo") - .build() - ) - .sourceLocation(source) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .name("foo") + .value("foo") + .build() + ) + .sourceLocation(source) + .build() + ) + .build(); EnumShape s2 = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("baz", "baz") - .addMember("foo", "foo") - .build(); + .id("foo.baz#Baz") + .addMember("baz", "baz") + .addMember("foo", "foo") + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.0").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.0").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.0").get(0).getSourceLocation(), + equalTo(source) ); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.0") - .stream() - .allMatch(e -> e.getSeverity() == Severity.ERROR), - equalTo(true) + TestHelper.findEvents(events, "ChangedEnumTrait.OrderChanged.0") + .stream() + .allMatch(e -> e.getSeverity() == Severity.ERROR), + equalTo(true) ); } @@ -558,27 +558,27 @@ public void detectsAppendedEnumsAfterRemovedEnums() { SourceLocation beforeSource = new SourceLocation("before.smithy", 1, 2); SourceLocation afterSource = new SourceLocation("after.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum(EnumDefinition.builder().value("old1").build()) - .addEnum(EnumDefinition.builder().value("old2").build()) - .addEnum(EnumDefinition.builder().value("old3").build()) - .sourceLocation(beforeSource) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum(EnumDefinition.builder().value("old1").build()) + .addEnum(EnumDefinition.builder().value("old2").build()) + .addEnum(EnumDefinition.builder().value("old3").build()) + .sourceLocation(beforeSource) + .build() + ) + .build(); StringShape s2 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum(EnumDefinition.builder().value("old1").build()) - .addEnum(EnumDefinition.builder().value("old3").build()) - .addEnum(EnumDefinition.builder().value("new1").build()) - .sourceLocation(afterSource) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum(EnumDefinition.builder().value("old1").build()) + .addEnum(EnumDefinition.builder().value("old3").build()) + .addEnum(EnumDefinition.builder().value("new1").build()) + .sourceLocation(afterSource) + .build() + ) + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List allEvents = ModelDiff.compare(modelA, modelB); @@ -604,35 +604,35 @@ public void detectsAppendedEnumsAfterRemovedEnumsEnumTraitNoNameToEnumShape() { SourceLocation beforeSource = new SourceLocation("before.smithy", 1, 2); SourceLocation afterSource = new SourceLocation("after.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .value("old1") - .build() - ) - .addEnum( - EnumDefinition.builder() - .value("old2") - .build() - ) - .addEnum( - EnumDefinition.builder() - .value("old3") - .build() - ) - .sourceLocation(beforeSource) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .value("old1") + .build() + ) + .addEnum( + EnumDefinition.builder() + .value("old2") + .build() + ) + .addEnum( + EnumDefinition.builder() + .value("old3") + .build() + ) + .sourceLocation(beforeSource) + .build() + ) + .build(); EnumShape s2 = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("old1", "old1") - .addMember("old3", "old3") - .addMember("new1", "new1") - .source(afterSource) - .build(); + .id("foo.baz#Baz") + .addMember("old1", "old1") + .addMember("old3", "old3") + .addMember("new1", "new1") + .source(afterSource) + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -640,31 +640,31 @@ public void detectsAppendedEnumsAfterRemovedEnumsEnumTraitNoNameToEnumShape() { assertThat(TestHelper.findEvents(events, "ChangedEnumTrait").size(), equalTo(4)); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSourceLocation(), - equalTo(afterSource) + TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.0").get(0).getSourceLocation(), + equalTo(afterSource) ); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1").get(0).getSourceLocation(), - equalTo(beforeSource) + TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1").get(0).getSourceLocation(), + equalTo(beforeSource) ); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.2").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.2").get(0).getSourceLocation(), - equalTo(afterSource) + TestHelper.findEvents(events, "ChangedEnumTrait.NameChanged.2").get(0).getSourceLocation(), + equalTo(afterSource) ); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait") - .subList(0, 3) - .stream() - .allMatch(e -> e.getSeverity() == Severity.ERROR), - equalTo(true) + TestHelper.findEvents(events, "ChangedEnumTrait") + .subList(0, 3) + .stream() + .allMatch(e -> e.getSeverity() == Severity.ERROR), + equalTo(true) ); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.Appended.2") - .stream() - .allMatch(e -> e.getSeverity() == Severity.NOTE), - equalTo(true) + TestHelper.findEvents(events, "ChangedEnumTrait.Appended.2") + .stream() + .allMatch(e -> e.getSeverity() == Severity.NOTE), + equalTo(true) ); } @@ -672,37 +672,37 @@ public void detectsAppendedEnumsAfterRemovedEnumsEnumTraitNoNameToEnumShape() { public void detectsAppendedEnumsAfterRemovedEnumsEnumTraitWithNameToEnumShape() { SourceLocation source = new SourceLocation("main.smithy", 1, 2); StringShape s1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("old1") - .value("old1") - .build() - ) - .addEnum( - EnumDefinition.builder() - .name("old2") - .value("old2") - .build() - ) - .addEnum( - EnumDefinition.builder() - .name("old3") - .value("old3") - .build() - ) - .sourceLocation(source) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .name("old1") + .value("old1") + .build() + ) + .addEnum( + EnumDefinition.builder() + .name("old2") + .value("old2") + .build() + ) + .addEnum( + EnumDefinition.builder() + .name("old3") + .value("old3") + .build() + ) + .sourceLocation(source) + .build() + ) + .build(); EnumShape s2 = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("old1", "old1") - .addMember("old3", "old3") - .addMember("new1", "new1") - .build(); + .id("foo.baz#Baz") + .addMember("old1", "old1") + .addMember("old3", "old3") + .addMember("new1", "new1") + .build(); Model modelA = Model.assembler().addShape(s1).assemble().unwrap(); Model modelB = Model.assembler().addShape(s2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -710,20 +710,20 @@ public void detectsAppendedEnumsAfterRemovedEnumsEnumTraitWithNameToEnumShape() assertThat(TestHelper.findEvents(events, "ChangedEnumTrait").size(), equalTo(2)); assertThat(TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1").get(0).getSourceLocation(), + equalTo(source) ); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1") - .stream() - .allMatch(e -> e.getSeverity() == Severity.ERROR), - equalTo(true) + TestHelper.findEvents(events, "ChangedEnumTrait.Removed.1") + .stream() + .allMatch(e -> e.getSeverity() == Severity.ERROR), + equalTo(true) ); assertThat( - TestHelper.findEvents(events, "ChangedEnumTrait.Appended.2") - .stream() - .allMatch(e -> e.getSeverity() == Severity.NOTE), - equalTo(true) + TestHelper.findEvents(events, "ChangedEnumTrait.Appended.2") + .stream() + .allMatch(e -> e.getSeverity() == Severity.NOTE), + equalTo(true) ); } } diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedMemberOrderTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedMemberOrderTest.java index 52a94899fdd..29422744086 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedMemberOrderTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedMemberOrderTest.java @@ -26,16 +26,16 @@ public void detectsOrderChanges() { MemberShape member1 = MemberShape.builder().id("foo.baz#Struct$member1").target(shape1).build(); MemberShape member2 = MemberShape.builder().id("foo.baz#Struct$member2").target(shape1).build(); StructureShape oldStruct = StructureShape.builder() - .id("foo.baz#Struct") - .addMember(member1) - .addMember(member2) - .build(); + .id("foo.baz#Struct") + .addMember(member1) + .addMember(member2) + .build(); StructureShape newStruct = StructureShape.builder() - .id("foo.baz#Struct") - .addMember(member2) - .addMember(member1) - .build(); + .id("foo.baz#Struct") + .addMember(member2) + .addMember(member1) + .build(); Model modelA = Model.assembler().addShapes(shape1, oldStruct).assemble().unwrap(); Model modelB = Model.assembler().addShapes(shape1, newStruct).assemble().unwrap(); @@ -52,18 +52,18 @@ public void detectsOrderInsertionChanges() { MemberShape member1 = MemberShape.builder().id("foo.baz#Struct$member1").target(shape1).build(); MemberShape member2 = MemberShape.builder().id("foo.baz#Struct$member2").target(shape1).build(); StructureShape oldStruct = StructureShape.builder() - .id("foo.baz#Struct") - .addMember(member1) - .addMember(member2) - .build(); + .id("foo.baz#Struct") + .addMember(member1) + .addMember(member2) + .build(); MemberShape member3 = MemberShape.builder().id("foo.baz#Struct$member3").target(shape1).build(); StructureShape newStruct = StructureShape.builder() - .id("foo.baz#Struct") - .addMember(member1) - .addMember(member3) - .addMember(member2) - .build(); + .id("foo.baz#Struct") + .addMember(member1) + .addMember(member3) + .addMember(member2) + .build(); Model modelA = Model.assembler().addShapes(shape1, oldStruct).assemble().unwrap(); Model modelB = Model.assembler().addShapes(shape1, newStruct).assemble().unwrap(); @@ -80,18 +80,18 @@ public void detectsCompatibleChanges() { MemberShape member1 = MemberShape.builder().id("foo.baz#Struct$member1").target(shape1).build(); MemberShape member2 = MemberShape.builder().id("foo.baz#Struct$member2").target(shape1).build(); StructureShape oldStruct = StructureShape.builder() - .id("foo.baz#Struct") - .addMember(member1) - .addMember(member2) - .build(); + .id("foo.baz#Struct") + .addMember(member1) + .addMember(member2) + .build(); MemberShape member3 = MemberShape.builder().id("foo.baz#Struct$member3").target(shape1).build(); StructureShape newStruct = StructureShape.builder() - .id("foo.baz#Struct") - .addMember(member1) - .addMember(member2) - .addMember(member3) - .build(); + .id("foo.baz#Struct") + .addMember(member1) + .addMember(member2) + .addMember(member3) + .build(); Model modelA = Model.assembler().addShapes(shape1, oldStruct).assemble().unwrap(); Model modelB = Model.assembler().addShapes(shape1, newStruct).assemble().unwrap(); @@ -107,15 +107,15 @@ public void ignoresOtherBreakingChanges() { MemberShape member1 = MemberShape.builder().id("foo.baz#Struct$member1").target(shape1).build(); MemberShape member2 = MemberShape.builder().id("foo.baz#Struct$member2").target(shape1).build(); StructureShape oldStruct = StructureShape.builder() - .id("foo.baz#Struct") - .addMember(member1) - .addMember(member2) - .build(); + .id("foo.baz#Struct") + .addMember(member1) + .addMember(member2) + .build(); StructureShape newStruct = StructureShape.builder() - .id("foo.baz#Struct") - .addMember(member1) - .build(); + .id("foo.baz#Struct") + .addMember(member1) + .build(); Model modelA = Model.assembler().addShapes(shape1, oldStruct).assemble().unwrap(); Model modelB = Model.assembler().addShapes(shape1, newStruct).assemble().unwrap(); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedMemberTargetTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedMemberTargetTest.java index c83ec7b4866..324817f32f8 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedMemberTargetTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedMemberTargetTest.java @@ -34,10 +34,10 @@ public void detectsIncompatibleTypeChanges() { ListShape list1 = ListShape.builder().id("foo.baz#List").member(member1).build(); Shape shape2 = TimestampShape.builder().id("foo.baz#Timestamp").build(); MemberShape member2 = MemberShape.builder() - .id("foo.baz#List$member") - .target(shape2.getId()) - .source(source) - .build(); + .id("foo.baz#List$member") + .target(shape2.getId()) + .source(source) + .build(); ListShape list2 = ListShape.builder().id("foo.baz#List").member(member2).build(); Model modelA = Model.assembler().addShapes(shape1, shape2, member1, list1).assemble().unwrap(); Model modelB = Model.assembler().addShapes(shape1, shape2, member2, list2).assemble().unwrap(); @@ -45,8 +45,8 @@ public void detectsIncompatibleTypeChanges() { assertThat(TestHelper.findEvents(events, "ChangedMemberTarget").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getSourceLocation(), + equalTo(source) ); assertThat(TestHelper.findEvents(events, member2.getId()).size(), equalTo(1)); assertThat(TestHelper.findEvents(events, Severity.ERROR).size(), equalTo(1)); @@ -68,12 +68,12 @@ public void detectsIncompatibleTargetChanges() { assertThat(TestHelper.findEvents(events, member2.getId()).size(), equalTo(1)); assertThat(TestHelper.findEvents(events, Severity.ERROR).size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), - equalTo( - "The shape targeted by the member `foo.baz#List$member` changed from " - + "`foo.baz#Shape1` (structure) to `foo.baz#Shape2` (structure). The name of a " - + "structure is significant." - ) + TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), + equalTo( + "The shape targeted by the member `foo.baz#List$member` changed from " + + "`foo.baz#Shape1` (structure) to `foo.baz#Shape2` (structure). The name of a " + + "structure is significant." + ) ); } @@ -93,20 +93,20 @@ public void detectsCompatibleChanges() { assertThat(TestHelper.findEvents(events, member2.getId()).size(), equalTo(1)); assertThat(TestHelper.findEvents(events, Severity.WARNING).size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), - equalTo( - "The shape targeted by the member `foo.baz#List$member` changed from " - + "`foo.baz#String1` (string) to `foo.baz#String2` (string). " - + "This was determined backward compatible." - ) + TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), + equalTo( + "The shape targeted by the member `foo.baz#List$member` changed from " + + "`foo.baz#String1` (string) to `foo.baz#String2` (string). " + + "This was determined backward compatible." + ) ); } @Test public void detectsIncompatibleEnumTraitTargetChange() { EnumTrait enumTrait = EnumTrait.builder() - .addEnum(EnumDefinition.builder().name("FOO").value("foo").build()) - .build(); + .addEnum(EnumDefinition.builder().name("FOO").value("foo").build()) + .build(); StringShape shape1 = StringShape.builder().id("foo.baz#String1").addTrait(enumTrait).build(); MemberShape member1 = MemberShape.builder().id("foo.baz#List$member").target(shape1.getId()).build(); @@ -124,20 +124,20 @@ public void detectsIncompatibleEnumTraitTargetChange() { assertThat(TestHelper.findEvents(events, member2.getId()).size(), equalTo(1)); assertThat(TestHelper.findEvents(events, Severity.ERROR).size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), - equalTo( - "The shape targeted by the member `foo.baz#List$member` changed from `foo.baz#String1` " - + "(string) to `foo.baz#String2` (string). The `smithy.api#enum` trait was found on the " - + "target, so the name of the targeted shape matters for codegen." - ) + TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), + equalTo( + "The shape targeted by the member `foo.baz#List$member` changed from `foo.baz#String1` " + + "(string) to `foo.baz#String2` (string). The `smithy.api#enum` trait was found on the " + + "target, so the name of the targeted shape matters for codegen." + ) ); } @Test public void detectsTraitRemovalOnMemberTarget() { EnumTrait enumTrait = EnumTrait.builder() - .addEnum(EnumDefinition.builder().name("FOO").value("foo").build()) - .build(); + .addEnum(EnumDefinition.builder().name("FOO").value("foo").build()) + .build(); StringShape shape1 = StringShape.builder().id("foo.baz#String1").addTrait(enumTrait).build(); MemberShape member1 = MemberShape.builder().id("foo.baz#List$member").target(shape1.getId()).build(); @@ -155,13 +155,13 @@ public void detectsTraitRemovalOnMemberTarget() { assertThat(TestHelper.findEvents(events, member2.getId()).size(), equalTo(1)); assertThat(TestHelper.findEvents(events, Severity.ERROR).size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), - equalTo( - "The shape targeted by the member `foo.baz#List$member` changed from " - + "`foo.baz#String1` (string) to `foo.baz#String2` (string). The `smithy.api#enum` trait " - + "was found on the target, so the name of the targeted shape matters for codegen. " - + "The targeted shape no longer has the following traits: [smithy.api#enum]." - ) + TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), + equalTo( + "The shape targeted by the member `foo.baz#List$member` changed from " + + "`foo.baz#String1` (string) to `foo.baz#String2` (string). The `smithy.api#enum` trait " + + "was found on the target, so the name of the targeted shape matters for codegen. " + + "The targeted shape no longer has the following traits: [smithy.api#enum]." + ) ); } @@ -183,12 +183,12 @@ public void detectsTraitAddedToMemberTarget() { assertThat(TestHelper.findEvents(events, member2.getId()).size(), equalTo(1)); assertThat(TestHelper.findEvents(events, Severity.ERROR).size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), - equalTo( - "The shape targeted by the member `foo.baz#List$member` changed from `foo.baz#String1` " - + "(string) to `foo.baz#String2` (string). The newly targeted shape now has the " - + "following additional traits: [smithy.api#sensitive]." - ) + TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), + equalTo( + "The shape targeted by the member `foo.baz#List$member` changed from `foo.baz#String1` " + + "(string) to `foo.baz#String2` (string). The newly targeted shape now has the " + + "following additional traits: [smithy.api#sensitive]." + ) ); } @@ -210,216 +210,216 @@ public void detectsTraitChangedOnMemberTarget() { assertThat(TestHelper.findEvents(events, member2.getId()).size(), equalTo(1)); assertThat(TestHelper.findEvents(events, Severity.ERROR).size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), - equalTo( - "The shape targeted by the member `foo.baz#List$member` changed from `foo.baz#String1` " - + "(string) to `foo.baz#String2` (string). The newly targeted shape has traits that " - + "differ from the previous shape: [smithy.api#documentation]." - ) + TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), + equalTo( + "The shape targeted by the member `foo.baz#List$member` changed from `foo.baz#String1` " + + "(string) to `foo.baz#String2` (string). The newly targeted shape has traits that " + + "differ from the previous shape: [smithy.api#documentation]." + ) ); } @Test public void detectsAcceptableListMemberChangesInNestedTargets() { Model modelA = Model.assembler() - .addImport(getClass().getResource("changed-member-target-valid-nested1-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-valid-nested1-a.smithy")) + .assemble() + .unwrap(); Model modelB = Model.assembler() - .addImport(getClass().getResource("changed-member-target-valid-nested1-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-valid-nested1-b.smithy")) + .assemble() + .unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedMemberTarget").size(), equalTo(1)); assertThat(TestHelper.findEvents(events, Severity.WARNING).size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), - equalTo( - "The shape targeted by the member `smithy.example#A$member` changed from " - + "`smithy.example#B1` (list) to `smithy.example#B2` (list). This was determined " - + "backward compatible." - ) + TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), + equalTo( + "The shape targeted by the member `smithy.example#A$member` changed from " + + "`smithy.example#B1` (list) to `smithy.example#B2` (list). This was determined " + + "backward compatible." + ) ); } @Test public void detectsAcceptableMapMemberChangesInNestedTargets() { Model modelA = Model.assembler() - .addImport(getClass().getResource("changed-member-target-valid-nested2-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-valid-nested2-a.smithy")) + .assemble() + .unwrap(); Model modelB = Model.assembler() - .addImport(getClass().getResource("changed-member-target-valid-nested2-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-valid-nested2-b.smithy")) + .assemble() + .unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedMemberTarget").size(), equalTo(1)); assertThat(TestHelper.findEvents(events, Severity.WARNING).size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), - equalTo( - "The shape targeted by the member `smithy.example#A$member` changed from " - + "`smithy.example#B1` (map) to `smithy.example#B2` (map). This was determined " - + "backward compatible." - ) + TestHelper.findEvents(events, "ChangedMemberTarget").get(0).getMessage(), + equalTo( + "The shape targeted by the member `smithy.example#A$member` changed from " + + "`smithy.example#B1` (map) to `smithy.example#B2` (map). This was determined " + + "backward compatible." + ) ); } @Test public void detectsInvalidListMemberChangesInNestedTargets() { Model modelA = Model.assembler() - .addImport(getClass().getResource("changed-member-target-invalid-nested1-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-invalid-nested1-a.smithy")) + .assemble() + .unwrap(); Model modelB = Model.assembler() - .addImport(getClass().getResource("changed-member-target-invalid-nested1-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-invalid-nested1-b.smithy")) + .assemble() + .unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedMemberTarget").size(), equalTo(1)); ValidationEvent event = TestHelper.findEvents(events, "ChangedMemberTarget").get(0); assertThat(event.getSeverity(), equalTo(Severity.ERROR)); assertThat( - event.getMessage(), - equalTo( - "The shape targeted by the member `smithy.example#A$member` changed from " - + "`smithy.example#B1` (list) to `smithy.example#B2` (list). Both the old and new " - + "shapes are a list, but their members have differing traits. The newly targeted " - + "shape now has the following additional traits: [smithy.api#pattern]." - ) + event.getMessage(), + equalTo( + "The shape targeted by the member `smithy.example#A$member` changed from " + + "`smithy.example#B1` (list) to `smithy.example#B2` (list). Both the old and new " + + "shapes are a list, but their members have differing traits. The newly targeted " + + "shape now has the following additional traits: [smithy.api#pattern]." + ) ); } @Test public void detectsInvalidListMemberTargetChange() { Model modelA = Model.assembler() - .addImport(getClass().getResource("changed-member-target-invalid-nested2-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-invalid-nested2-a.smithy")) + .assemble() + .unwrap(); Model modelB = Model.assembler() - .addImport(getClass().getResource("changed-member-target-invalid-nested2-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-invalid-nested2-b.smithy")) + .assemble() + .unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedMemberTarget").size(), equalTo(1)); ValidationEvent event = TestHelper.findEvents(events, "ChangedMemberTarget").get(0); assertThat(event.getSeverity(), equalTo(Severity.ERROR)); assertThat( - event.getMessage(), - equalTo( - "The shape targeted by the member `smithy.example#A$member` changed from " - + "`smithy.example#B1` (list) to `smithy.example#B2` (list). Both the old and new " - + "shapes are a list, but the old shape targeted `smithy.example#MyString` while " - + "the new shape targets `smithy.example#MyString2`." - ) + event.getMessage(), + equalTo( + "The shape targeted by the member `smithy.example#A$member` changed from " + + "`smithy.example#B1` (list) to `smithy.example#B2` (list). Both the old and new " + + "shapes are a list, but the old shape targeted `smithy.example#MyString` while " + + "the new shape targets `smithy.example#MyString2`." + ) ); } @Test public void detectsInvalidMapKeyChangesInNestedTargets() { Model modelA = Model.assembler() - .addImport(getClass().getResource("changed-member-target-invalid-nested-mapkey1-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-invalid-nested-mapkey1-a.smithy")) + .assemble() + .unwrap(); Model modelB = Model.assembler() - .addImport(getClass().getResource("changed-member-target-invalid-nested-mapkey1-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-invalid-nested-mapkey1-b.smithy")) + .assemble() + .unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedMemberTarget").size(), equalTo(1)); ValidationEvent event = TestHelper.findEvents(events, "ChangedMemberTarget").get(0); assertThat(event.getSeverity(), equalTo(Severity.ERROR)); assertThat( - event.getMessage(), - equalTo( - "The shape targeted by the member `smithy.example#A$member` changed from " - + "`smithy.example#B1` (map) to `smithy.example#B2` (map). Both the old and new " - + "shapes are a map, but their key members have differing traits. The newly targeted " - + "shape now has the following additional traits: [smithy.api#pattern]." - ) + event.getMessage(), + equalTo( + "The shape targeted by the member `smithy.example#A$member` changed from " + + "`smithy.example#B1` (map) to `smithy.example#B2` (map). Both the old and new " + + "shapes are a map, but their key members have differing traits. The newly targeted " + + "shape now has the following additional traits: [smithy.api#pattern]." + ) ); } @Test public void detectsInvalidMapKeyTargetChange() { Model modelA = Model.assembler() - .addImport(getClass().getResource("changed-member-target-invalid-nested-mapkey2-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-invalid-nested-mapkey2-a.smithy")) + .assemble() + .unwrap(); Model modelB = Model.assembler() - .addImport(getClass().getResource("changed-member-target-invalid-nested-mapkey2-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-invalid-nested-mapkey2-b.smithy")) + .assemble() + .unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedMemberTarget").size(), equalTo(1)); ValidationEvent event = TestHelper.findEvents(events, "ChangedMemberTarget").get(0); assertThat(event.getSeverity(), equalTo(Severity.ERROR)); assertThat( - event.getMessage(), - equalTo( - "The shape targeted by the member `smithy.example#A$member` changed from " - + "`smithy.example#B1` (map) to `smithy.example#B2` (map). Both the old and new " - + "shapes are a map, but the old shape key targeted `smithy.example#MyString` while " - + "the new shape targets `smithy.example#MyString2`." - ) + event.getMessage(), + equalTo( + "The shape targeted by the member `smithy.example#A$member` changed from " + + "`smithy.example#B1` (map) to `smithy.example#B2` (map). Both the old and new " + + "shapes are a map, but the old shape key targeted `smithy.example#MyString` while " + + "the new shape targets `smithy.example#MyString2`." + ) ); } @Test public void detectsInvalidMapValueChangesInNestedTargets() { Model modelA = Model.assembler() - .addImport(getClass().getResource("changed-member-target-invalid-nested-mapvalue1-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-invalid-nested-mapvalue1-a.smithy")) + .assemble() + .unwrap(); Model modelB = Model.assembler() - .addImport(getClass().getResource("changed-member-target-invalid-nested-mapvalue1-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-invalid-nested-mapvalue1-b.smithy")) + .assemble() + .unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedMemberTarget").size(), equalTo(1)); ValidationEvent event = TestHelper.findEvents(events, "ChangedMemberTarget").get(0); assertThat(event.getSeverity(), equalTo(Severity.ERROR)); assertThat( - event.getMessage(), - equalTo( - "The shape targeted by the member `smithy.example#A$member` changed from " - + "`smithy.example#B1` (map) to `smithy.example#B2` (map). Both the old and new " - + "shapes are a map, but their value members have differing traits. The newly targeted " - + "shape now has the following additional traits: [smithy.api#pattern]." - ) + event.getMessage(), + equalTo( + "The shape targeted by the member `smithy.example#A$member` changed from " + + "`smithy.example#B1` (map) to `smithy.example#B2` (map). Both the old and new " + + "shapes are a map, but their value members have differing traits. The newly targeted " + + "shape now has the following additional traits: [smithy.api#pattern]." + ) ); } @Test public void detectsInvalidMapValueTargetChange() { Model modelA = Model.assembler() - .addImport(getClass().getResource("changed-member-target-invalid-nested-mapvalue2-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-invalid-nested-mapvalue2-a.smithy")) + .assemble() + .unwrap(); Model modelB = Model.assembler() - .addImport(getClass().getResource("changed-member-target-invalid-nested-mapvalue2-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("changed-member-target-invalid-nested-mapvalue2-b.smithy")) + .assemble() + .unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat(TestHelper.findEvents(events, "ChangedMemberTarget").size(), equalTo(1)); ValidationEvent event = TestHelper.findEvents(events, "ChangedMemberTarget").get(0); assertThat(event.getSeverity(), equalTo(Severity.ERROR)); assertThat( - event.getMessage(), - equalTo( - "The shape targeted by the member `smithy.example#A$member` changed from " - + "`smithy.example#B1` (map) to `smithy.example#B2` (map). Both the old and new " - + "shapes are a map, but the old shape value targeted `smithy.example#MyString` while " - + "the new shape targets `smithy.example#MyString2`." - ) + event.getMessage(), + equalTo( + "The shape targeted by the member `smithy.example#A$member` changed from " + + "`smithy.example#B1` (map) to `smithy.example#B2` (map). Both the old and new " + + "shapes are a map, but the old shape value targeted `smithy.example#MyString` while " + + "the new shape targets `smithy.example#MyString2`." + ) ); } } diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedNullabilityTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedNullabilityTest.java index 062dcfa139a..74b8e6db3c3 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedNullabilityTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedNullabilityTest.java @@ -40,23 +40,23 @@ public class ChangedNullabilityTest { public void replacingRequiredTraitWithDefaultIsOk() { StringShape s = StringShape.builder().id("smithy.example#Str").build(); StructureShape a = StructureShape.builder() - .id("smithy.example#A") - .addMember("foo", s.getId(), b1 -> b1.addTrait(new RequiredTrait())) - .build(); + .id("smithy.example#A") + .addMember("foo", s.getId(), b1 -> b1.addTrait(new RequiredTrait())) + .build(); StructureShape b = StructureShape.builder() - .id("smithy.example#A") - .addMember("foo", s.getId(), b2 -> b2.addTrait(new DefaultTrait(Node.from("")))) - .build(); + .id("smithy.example#A") + .addMember("foo", s.getId(), b2 -> b2.addTrait(new DefaultTrait(Node.from("")))) + .build(); Model model1 = Model.builder().addShapes(s, a).build(); Model model2 = Model.builder().addShapes(s, b).build(); ModelDiff.Result result = ModelDiff.builder().oldModel(model1).newModel(model2).compare(); assertThat( - result.getDiffEvents() - .stream() - .filter(event -> event.getId().equals("ChangedNullability")) - .count(), - equalTo(0L) + result.getDiffEvents() + .stream() + .filter(event -> event.getId().equals("ChangedNullability")) + .count(), + equalTo(0L) ); } @@ -64,26 +64,26 @@ public void replacingRequiredTraitWithDefaultIsOk() { public void addingDefaultWithRequiredTraitIsOk() { StringShape s = StringShape.builder().id("smithy.example#Str").build(); StructureShape a = StructureShape.builder() - .id("smithy.example#A") - .addMember("foo", s.getId(), b1 -> b1.addTrait(new DefaultTrait(Node.from("")))) - .build(); + .id("smithy.example#A") + .addMember("foo", s.getId(), b1 -> b1.addTrait(new DefaultTrait(Node.from("")))) + .build(); StructureShape b = StructureShape.builder() - .id("smithy.example#A") - .addMember("foo", s.getId(), b2 -> { - b2.addTrait(new RequiredTrait()); - b2.addTrait(new DefaultTrait(Node.from(""))); - }) - .build(); + .id("smithy.example#A") + .addMember("foo", s.getId(), b2 -> { + b2.addTrait(new RequiredTrait()); + b2.addTrait(new DefaultTrait(Node.from(""))); + }) + .build(); Model model1 = Model.builder().addShapes(s, a).build(); Model model2 = Model.builder().addShapes(s, b).build(); ModelDiff.Result result = ModelDiff.builder().oldModel(model1).newModel(model2).compare(); assertThat( - result.getDiffEvents() - .stream() - .filter(event -> event.getId().equals("ChangedNullability")) - .count(), - equalTo(0L) + result.getDiffEvents() + .stream() + .filter(event -> event.getId().equals("ChangedNullability")) + .count(), + equalTo(0L) ); } @@ -92,35 +92,35 @@ public void detectsInvalidAdditionOfDefaultTrait() { SourceLocation source = new SourceLocation("a.smithy", 5, 6); StringShape s = StringShape.builder().id("smithy.example#Str").build(); StructureShape a = StructureShape.builder() - .id("smithy.example#A") - .addMember("foo", s.getId(), builder -> builder.source(source)) - .source(source) - .build(); + .id("smithy.example#A") + .addMember("foo", s.getId(), builder -> builder.source(source)) + .source(source) + .build(); StructureShape b = StructureShape.builder() - .id("smithy.example#A") - .addMember("foo", s.getId(), builder -> builder.addTrait(new DefaultTrait(Node.from("")))) - .build(); + .id("smithy.example#A") + .addMember("foo", s.getId(), builder -> builder.addTrait(new DefaultTrait(Node.from("")))) + .build(); Model model1 = Model.builder().addShapes(s, a).build(); Model model2 = Model.builder().addShapes(s, b).build(); ModelDiff.Result result = ModelDiff.builder().oldModel(model1).newModel(model2).compare(); assertThat(result.isDiffBreaking(), is(true)); assertThat( - result.getDiffEvents() - .stream() - .filter(event -> event.getSeverity() == Severity.ERROR) - .filter(event -> event.getId().equals("ChangedNullability.AddedDefaultTrait")) - .filter(event -> event.getShapeId().get().equals(a.getAllMembers().get("foo").getId())) - .filter(event -> event.getSourceLocation().equals(source)) - .filter( - event -> event.getMessage() - .contains( - "The @default trait was added to a member that " - + "was not previously @required" + result.getDiffEvents() + .stream() + .filter(event -> event.getSeverity() == Severity.ERROR) + .filter(event -> event.getId().equals("ChangedNullability.AddedDefaultTrait")) + .filter(event -> event.getShapeId().get().equals(a.getAllMembers().get("foo").getId())) + .filter(event -> event.getSourceLocation().equals(source)) + .filter( + event -> event.getMessage() + .contains( + "The @default trait was added to a member that " + + "was not previously @required" + ) ) - ) - .count(), - equalTo(1L) + .count(), + equalTo(1L) ); } @@ -128,25 +128,28 @@ public void detectsInvalidAdditionOfDefaultTrait() { public void removingTheRequiredTraitOnInputStructureIsOk() { StringShape s = StringShape.builder().id("smithy.example#Str").build(); StructureShape a = StructureShape.builder() - .addTrait(new InputTrait()) - .id("smithy.example#A") - .addMember("foo", s.getId(), b1 -> b1.addTrait(new RequiredTrait())) - .build(); + .addTrait(new InputTrait()) + .id("smithy.example#A") + .addMember("foo", s.getId(), b1 -> b1.addTrait(new RequiredTrait())) + .build(); StructureShape b = StructureShape.builder() - .addTrait(new InputTrait()) - .id("smithy.example#A") - .addMember("foo", s.getId()) - .build(); + .addTrait(new InputTrait()) + .id("smithy.example#A") + .addMember("foo", s.getId()) + .build(); Model model1 = Model.builder().addShapes(s, a).build(); Model model2 = Model.builder().addShapes(s, b).build(); ModelDiff.Result result = ModelDiff.builder().oldModel(model1).newModel(model2).compare(); assertThat( - result.getDiffEvents() - .stream() - .filter(event -> event.getId().equals("ChangedNullability.RemovedRequiredTrait.StructureOrUnion")) - .count(), - equalTo(0L) + result.getDiffEvents() + .stream() + .filter( + event -> event.getId() + .equals("ChangedNullability.RemovedRequiredTrait.StructureOrUnion") + ) + .count(), + equalTo(0L) ); } @@ -155,41 +158,41 @@ public void detectsInvalidRemovalOfRequired() { SourceLocation memberSource = new SourceLocation("a.smithy", 7, 7); StringShape s = StringShape.builder().id("smithy.example#Str").build(); MemberShape requiredM = MemberShape.builder() - .id("smithy.example#A$foo") - .target(s) - .addTrait(new RequiredTrait()) - .source(memberSource) - .build(); + .id("smithy.example#A$foo") + .target(s) + .addTrait(new RequiredTrait()) + .source(memberSource) + .build(); MemberShape m = MemberShape.builder().id("smithy.example#A$foo").target(s).source(memberSource).build(); StructureShape a = StructureShape.builder() - .id("smithy.example#A") - .addMember(requiredM) - .build(); + .id("smithy.example#A") + .addMember(requiredM) + .build(); StructureShape b = StructureShape.builder() - .id("smithy.example#A") - .addMember(m) - .build(); + .id("smithy.example#A") + .addMember(m) + .build(); Model model1 = Model.builder().addShapes(s, a, requiredM).build(); Model model2 = Model.builder().addShapes(s, b, m).build(); ModelDiff.Result result = ModelDiff.builder().oldModel(model1).newModel(model2).compare(); assertThat(result.isDiffBreaking(), is(true)); assertThat( - result.getDiffEvents() - .stream() - .filter(event -> event.getSeverity() == Severity.ERROR) - .filter(event -> event.getId().equals("ChangedNullability.RemovedRequiredTrait")) - .filter(event -> event.getShapeId().get().equals(a.getAllMembers().get("foo").getId())) - .filter(event -> event.getSourceLocation().equals(memberSource)) - .filter( - event -> event.getMessage() - .contains( - "The @required trait was removed and not " - + "replaced with the @default trait" + result.getDiffEvents() + .stream() + .filter(event -> event.getSeverity() == Severity.ERROR) + .filter(event -> event.getId().equals("ChangedNullability.RemovedRequiredTrait")) + .filter(event -> event.getShapeId().get().equals(a.getAllMembers().get("foo").getId())) + .filter(event -> event.getSourceLocation().equals(memberSource)) + .filter( + event -> event.getMessage() + .contains( + "The @required trait was removed and not " + + "replaced with the @default trait" + ) ) - ) - .count(), - equalTo(1L) + .count(), + equalTo(1L) ); } @@ -197,10 +200,10 @@ public void detectsInvalidRemovalOfRequired() { public void detectAdditionOfRequiredTrait() { SourceLocation memberSource = new SourceLocation("a.smithy", 5, 6); MemberShape member1 = MemberShape.builder() - .id("foo.baz#Baz$bam") - .target("foo.baz#String") - .source(memberSource) - .build(); + .id("foo.baz#Baz$bam") + .target("foo.baz#String") + .source(memberSource) + .build(); MemberShape member2 = member1.toBuilder().addTrait(new RequiredTrait()).build(); StructureShape shapeA1 = StructureShape.builder().id("foo.baz#Baz").addMember(member1).build(); StructureShape shapeA2 = StructureShape.builder().id("foo.baz#Baz").addMember(member2).build(); @@ -210,13 +213,13 @@ public void detectAdditionOfRequiredTrait() { List events = ModelDiff.compare(modelA, modelB); assertThat( - events.stream() - .filter(event -> event.getSeverity() == Severity.ERROR) - .filter(event -> event.getId().equals("ChangedNullability.AddedRequiredTrait")) - .filter(event -> event.getSourceLocation().equals(memberSource)) - .filter(event -> event.getMessage().contains("The @required trait was added to a member")) - .count(), - equalTo(1L) + events.stream() + .filter(event -> event.getSeverity() == Severity.ERROR) + .filter(event -> event.getId().equals("ChangedNullability.AddedRequiredTrait")) + .filter(event -> event.getSourceLocation().equals(memberSource)) + .filter(event -> event.getMessage().contains("The @required trait was added to a member")) + .count(), + equalTo(1L) ); } @@ -224,11 +227,11 @@ public void detectAdditionOfRequiredTrait() { public void detectAdditionOfClientOptionalTrait() { SourceLocation memberSource = new SourceLocation("a.smithy", 5, 6); MemberShape member1 = MemberShape.builder() - .id("foo.baz#Baz$bam") - .target("foo.baz#String") - .addTrait(new RequiredTrait()) - .source(memberSource) - .build(); + .id("foo.baz#Baz$bam") + .target("foo.baz#String") + .addTrait(new RequiredTrait()) + .source(memberSource) + .build(); MemberShape member2 = member1.toBuilder().addTrait(new ClientOptionalTrait()).build(); StructureShape shapeA1 = StructureShape.builder().id("foo.baz#Baz").addMember(member1).build(); StructureShape shapeA2 = StructureShape.builder().id("foo.baz#Baz").addMember(member2).build(); @@ -238,19 +241,19 @@ public void detectAdditionOfClientOptionalTrait() { List events = ModelDiff.compare(modelA, modelB); assertThat( - events.stream() - .filter(event -> event.getSeverity() == Severity.ERROR) - .filter(event -> event.getId().equals("ChangedNullability.AddedClientOptionalTrait")) - .filter(event -> event.getSourceLocation().equals(memberSource)) - .filter( - event -> event.getMessage() - .contains( - "The @clientOptional trait was added to a " - + "@required member" + events.stream() + .filter(event -> event.getSeverity() == Severity.ERROR) + .filter(event -> event.getId().equals("ChangedNullability.AddedClientOptionalTrait")) + .filter(event -> event.getSourceLocation().equals(memberSource)) + .filter( + event -> event.getMessage() + .contains( + "The @clientOptional trait was added to a " + + "@required member" + ) ) - ) - .count(), - equalTo(1L) + .count(), + equalTo(1L) ); } @@ -258,38 +261,38 @@ public void detectAdditionOfClientOptionalTrait() { public void detectsAdditionOfInputTrait() { SourceLocation structureSource = new SourceLocation("a.smithy", 5, 6); MemberShape member1 = MemberShape.builder() - .id("foo.baz#Baz$bam") - .target("foo.baz#String") - .addTrait(new RequiredTrait()) - .build(); + .id("foo.baz#Baz$bam") + .target("foo.baz#String") + .addTrait(new RequiredTrait()) + .build(); MemberShape member2 = member1.toBuilder().addTrait(new DocumentationTrait("docs")).build(); StructureShape shapeA1 = StructureShape.builder().id("foo.baz#Baz").addMember(member1).build(); StructureShape shapeA2 = StructureShape.builder() - .id("foo.baz#Baz") - .addMember(member2) - .addTrait(new InputTrait()) - .source(structureSource) - .build(); + .id("foo.baz#Baz") + .addMember(member2) + .addTrait(new InputTrait()) + .source(structureSource) + .build(); StringShape target = StringShape.builder().id("foo.baz#String").build(); Model modelA = Model.assembler().addShapes(shapeA1, member1, target).assemble().unwrap(); Model modelB = Model.assembler().addShapes(shapeA2, member2, target).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat( - events.stream() - .filter(event -> event.getSeverity() == Severity.DANGER) - .filter(event -> event.getId().equals("ChangedNullability.AddedInputTrait")) - .filter(event -> event.getSourceLocation().equals(structureSource)) - .filter(event -> event.getMessage().contains("The @input trait was added to")) - .count(), - equalTo(1L) + events.stream() + .filter(event -> event.getSeverity() == Severity.DANGER) + .filter(event -> event.getId().equals("ChangedNullability.AddedInputTrait")) + .filter(event -> event.getSourceLocation().equals(structureSource)) + .filter(event -> event.getMessage().contains("The @input trait was added to")) + .count(), + equalTo(1L) ); assertThat( - events.stream() - .filter(event -> event.getId().contains("ChangedNullability")) - .filter(event -> event.getSourceLocation().equals(structureSource)) - .count(), - equalTo(1L) + events.stream() + .filter(event -> event.getId().contains("ChangedNullability")) + .filter(event -> event.getSourceLocation().equals(structureSource)) + .count(), + equalTo(1L) ); } @@ -297,45 +300,45 @@ public void detectsAdditionOfInputTrait() { public void detectsRemovalOfInputTrait() { SourceLocation structureSource = new SourceLocation("a.smithy", 5, 6); MemberShape member1 = MemberShape.builder() - .id("foo.baz#Baz$bam") - .target("foo.baz#String") - .addTrait(new RequiredTrait()) - .build(); + .id("foo.baz#Baz$bam") + .target("foo.baz#String") + .addTrait(new RequiredTrait()) + .build(); MemberShape member2 = member1.toBuilder() - .addTrait(new DocumentationTrait("docs")) - .build(); + .addTrait(new DocumentationTrait("docs")) + .build(); StructureShape shapeA1 = StructureShape.builder() - .id("foo.baz#Baz") - .addMember(member1) - .addTrait(new InputTrait()) - .build(); + .id("foo.baz#Baz") + .addMember(member1) + .addTrait(new InputTrait()) + .build(); StructureShape shapeA2 = StructureShape.builder() - .id("foo.baz#Baz") - .addMember(member2) - .source(structureSource) - .build(); + .id("foo.baz#Baz") + .addMember(member2) + .source(structureSource) + .build(); StringShape target = StringShape.builder().id("foo.baz#String").build(); Model modelA = Model.assembler().addShapes(shapeA1, member1, target).assemble().unwrap(); Model modelB = Model.assembler().addShapes(shapeA2, member2, target).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); assertThat( - events.stream() - .filter(event -> event.getSeverity() == Severity.ERROR) - .filter(event -> event.getId().equals("ChangedNullability.RemovedInputTrait")) - .filter(event -> event.getSourceLocation().equals(structureSource)) - .filter(event -> event.getMessage().contains("The @input trait was removed from")) - .count(), - equalTo(1L) + events.stream() + .filter(event -> event.getSeverity() == Severity.ERROR) + .filter(event -> event.getId().equals("ChangedNullability.RemovedInputTrait")) + .filter(event -> event.getSourceLocation().equals(structureSource)) + .filter(event -> event.getMessage().contains("The @input trait was removed from")) + .count(), + equalTo(1L) ); } @Test public void doesNotEmitForBackwardCompatibleBoxTraitChanges() { Model old = Model.assembler() - .addImport(getClass().getResource("box-added-to-member.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("box-added-to-member.smithy")) + .assemble() + .unwrap(); ShapeId bazId = ShapeId.from("smithy.example#Example$baz"); ShapeId bamId = ShapeId.from("smithy.example#Example$bam"); @@ -364,14 +367,14 @@ public void doesNotEmitForBackwardCompatibleBoxTraitChanges() { @Test public void doesNotEmitForBackwardCompatibleBoxTraitChangesFromRoundTripping() { Model old = Model.assembler() - .addImport(getClass().getResource("box-added-to-member.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("box-added-to-member.smithy")) + .assemble() + .unwrap(); Model newModel = Model.assembler() - .addDocumentNode(ModelSerializer.builder().build().serialize(old)) - .assemble() - .unwrap(); + .addDocumentNode(ModelSerializer.builder().build().serialize(old)) + .assemble() + .unwrap(); List events = ModelDiff.compare(old, newModel); @@ -382,26 +385,26 @@ public void doesNotEmitForBackwardCompatibleBoxTraitChangesFromRoundTripping() { @Test public void roundTrippedV1ModelHasNoEvents() { String originalModel = "$version: \"1.0\"\n" - + "namespace smithy.example\n" - + "integer MyPrimitiveInteger\n" - + "@box\n" - + "integer MyBoxedInteger\n" - + "structure Foo {\n" - + " a: MyPrimitiveInteger,\n" - + " @box\n" - + " b: MyPrimitiveInteger,\n" - + " c: MyBoxedInteger,\n" - + " @box\n" - + " d: MyBoxedInteger,\n" - + "}\n"; + + "namespace smithy.example\n" + + "integer MyPrimitiveInteger\n" + + "@box\n" + + "integer MyBoxedInteger\n" + + "structure Foo {\n" + + " a: MyPrimitiveInteger,\n" + + " @box\n" + + " b: MyPrimitiveInteger,\n" + + " c: MyBoxedInteger,\n" + + " @box\n" + + " d: MyBoxedInteger,\n" + + "}\n"; Model oldModel = Model.assembler().addUnparsedModel("test.smithy", originalModel).assemble().unwrap(); // Round trip the v1 model and make sure there are no diff events. String unparsedNew = Node.prettyPrintJson(ModelSerializer.builder().build().serialize(oldModel)); Model newModel = Model.assembler() - .addUnparsedModel("test.json", unparsedNew) - .assemble() - .unwrap(); + .addUnparsedModel("test.json", unparsedNew) + .assemble() + .unwrap(); List events = ModelDiff.compare(oldModel, newModel); @@ -413,26 +416,26 @@ public void specialHandlingForRequiredStructureMembers() { SourceLocation memberSource = new SourceLocation("a.smithy", 8, 2); StructureShape structBaz = StructureShape.builder().id("smithy.example#Baz").build(); MemberShape memberBaz = MemberShape.builder() - .id("smithy.example#Foo$baz") - .addTrait(new RequiredTrait()) - .target(structBaz) - .source(memberSource) - .build(); + .id("smithy.example#Foo$baz") + .addTrait(new RequiredTrait()) + .target(structBaz) + .source(memberSource) + .build(); StructureShape structFoo = StructureShape.builder().id("smithy.example#Foo").addMember(memberBaz).build(); Model oldModel = Model.assembler().addShapes(structFoo, structBaz, memberBaz).assemble().unwrap(); Model newModel = ModelTransformer.create() - .replaceShapes( - oldModel, - ListUtils.of( - Shape.shapeToBuilder(oldModel.expectShape(ShapeId.from("smithy.example#Foo$baz"))) - .removeTrait(RequiredTrait.ID) - .build() - ) - ); + .replaceShapes( + oldModel, + ListUtils.of( + Shape.shapeToBuilder(oldModel.expectShape(ShapeId.from("smithy.example#Foo$baz"))) + .removeTrait(RequiredTrait.ID) + .build() + ) + ); List events = TestHelper.findEvents( - ModelDiff.compare(oldModel, newModel), - "ChangedNullability" + ModelDiff.compare(oldModel, newModel), + "ChangedNullability" ); assertThat(events, hasSize(1)); @@ -447,26 +450,26 @@ public void specialHandlingForRequiredUnionMembers() { MemberShape memberB = MemberShape.builder().id("smithy.example#Baz$B").target("smithy.api#String").build(); UnionShape union = UnionShape.builder().id("smithy.example#Baz").addMember(memberA).addMember(memberB).build(); MemberShape memberBaz = MemberShape.builder() - .id("smithy.example#Foo$baz") - .addTrait(new RequiredTrait()) - .target(union) - .source(memberSource) - .build(); + .id("smithy.example#Foo$baz") + .addTrait(new RequiredTrait()) + .target(union) + .source(memberSource) + .build(); StructureShape struct = StructureShape.builder().id("smithy.example#Foo").addMember(memberBaz).build(); Model oldModel = Model.assembler().addShapes(union, struct, memberA, memberB, memberBaz).assemble().unwrap(); Model newModel = ModelTransformer.create() - .replaceShapes( - oldModel, - ListUtils.of( - Shape.shapeToBuilder(oldModel.expectShape(ShapeId.from("smithy.example#Foo$baz"))) - .removeTrait(RequiredTrait.ID) - .build() - ) - ); + .replaceShapes( + oldModel, + ListUtils.of( + Shape.shapeToBuilder(oldModel.expectShape(ShapeId.from("smithy.example#Foo$baz"))) + .removeTrait(RequiredTrait.ID) + .build() + ) + ); List events = TestHelper.findEvents( - ModelDiff.compare(oldModel, newModel), - "ChangedNullability" + ModelDiff.compare(oldModel, newModel), + "ChangedNullability" ); assertThat(events, hasSize(1)); @@ -477,21 +480,21 @@ public void specialHandlingForRequiredUnionMembers() { @Test public void doesNotWarnWhenExtraneousDefaultNullTraitRemoved() { String originalModel = "$version: \"2.0\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " @required\n" - + " baz: Integer = null\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " @required\n" + + " baz: Integer = null\n" + + "}\n"; Model oldModel = Model.assembler().addUnparsedModel("foo.smithy", originalModel).assemble().unwrap(); Model newModel = ModelTransformer.create() - .replaceShapes( - oldModel, - ListUtils.of( - Shape.shapeToBuilder(oldModel.expectShape(ShapeId.from("smithy.example#Foo$baz"))) - .removeTrait(DefaultTrait.ID) - .build() - ) - ); + .replaceShapes( + oldModel, + ListUtils.of( + Shape.shapeToBuilder(oldModel.expectShape(ShapeId.from("smithy.example#Foo$baz"))) + .removeTrait(DefaultTrait.ID) + .build() + ) + ); // The only emitted even should be a warning about the removal of the default trait, which can be ignored // given the effective nullability of the member is unchanged. diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedPaginatedTraitTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedPaginatedTraitTest.java index d170ce9f1a3..37af0c6f366 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedPaginatedTraitTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedPaginatedTraitTest.java @@ -25,9 +25,9 @@ public class ChangedPaginatedTraitTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(ChangedPaginatedTraitTest.class.getResource("paginated-trait-tests.smithy")) - .assemble() - .unwrap(); + .addImport(ChangedPaginatedTraitTest.class.getResource("paginated-trait-tests.smithy")) + .assemble() + .unwrap(); } @Test @@ -41,7 +41,7 @@ public void ignoresUnchangedTraits() { public void detectsRemovalOfTrait() { // Note that this is detected using diff tags. This is more of a sanity check. Model newModel = ModelTransformer.create() - .removeTraitsIf(model, (shape, trait) -> trait instanceof PaginatedTrait); + .removeTraitsIf(model, (shape, trait) -> trait instanceof PaginatedTrait); List events = ModelDiff.compare(model, newModel); List changedTraitEvents = TestHelper.findEvents(events, "TraitBreakingChange"); @@ -54,8 +54,8 @@ public void detectsRemovalOfItems() { // Remove the items member from the new model. Model newModel = ModelTransformer.create().mapTraits(model, (shape, trait) -> { return trait instanceof PaginatedTrait - ? ((PaginatedTrait) trait).toBuilder().items(null).build() - : trait; + ? ((PaginatedTrait) trait).toBuilder().items(null).build() + : trait; }); List events = ModelDiff.compare(model, newModel); @@ -63,10 +63,10 @@ public void detectsRemovalOfItems() { assertThat(changedTraitEvents.size(), equalTo(1)); assertThat( - changedTraitEvents.get(0).getMessage(), - containsString( - "Removed trait contents from `smithy.api#paginated` at path `/items`. Removed value: `things`" - ) + changedTraitEvents.get(0).getMessage(), + containsString( + "Removed trait contents from `smithy.api#paginated` at path `/items`. Removed value: `things`" + ) ); } @@ -75,8 +75,8 @@ public void detectsAdditionOfItems() { // Remove the items member from the old model. Model oldModel = ModelTransformer.create().mapTraits(model, (shape, trait) -> { return trait instanceof PaginatedTrait - ? ((PaginatedTrait) trait).toBuilder().items(null).build() - : trait; + ? ((PaginatedTrait) trait).toBuilder().items(null).build() + : trait; }); List events = ModelDiff.compare(oldModel, model); @@ -84,8 +84,8 @@ public void detectsAdditionOfItems() { assertThat(changedTraitEvents.size(), equalTo(1)); assertThat( - changedTraitEvents.get(0).getMessage(), - containsString("Added trait contents to `smithy.api#paginated` at path `/items` with value `things`") + changedTraitEvents.get(0).getMessage(), + containsString("Added trait contents to `smithy.api#paginated` at path `/items` with value `things`") ); } @@ -94,8 +94,8 @@ public void detectsChangeToItems() { // Change the items value in the new model. Model newModel = ModelTransformer.create().mapTraits(model, (shape, trait) -> { return trait instanceof PaginatedTrait - ? ((PaginatedTrait) trait).toBuilder().items("otherThings").build() - : trait; + ? ((PaginatedTrait) trait).toBuilder().items("otherThings").build() + : trait; }); List events = ModelDiff.compare(model, newModel); @@ -103,10 +103,10 @@ public void detectsChangeToItems() { assertThat(changedTraitEvents.size(), equalTo(1)); assertThat( - changedTraitEvents.get(0).getMessage(), - containsString( - "Changed trait contents of `smithy.api#paginated` at path `/items` from `things` to `otherThings`" - ) + changedTraitEvents.get(0).getMessage(), + containsString( + "Changed trait contents of `smithy.api#paginated` at path `/items` from `things` to `otherThings`" + ) ); } @@ -115,8 +115,8 @@ public void detectsRemovalOfPageSize() { // Remove the pageSize from the new model. Model newModel = ModelTransformer.create().mapTraits(model, (shape, trait) -> { return trait instanceof PaginatedTrait - ? ((PaginatedTrait) trait).toBuilder().pageSize(null).build() - : trait; + ? ((PaginatedTrait) trait).toBuilder().pageSize(null).build() + : trait; }); List events = ModelDiff.compare(model, newModel); @@ -124,10 +124,10 @@ public void detectsRemovalOfPageSize() { assertThat(changedTraitEvents.size(), equalTo(1)); assertThat( - changedTraitEvents.get(0).getMessage(), - containsString( - "Removed trait contents from `smithy.api#paginated` at path `/pageSize`. Removed value: `maxResults`" - ) + changedTraitEvents.get(0).getMessage(), + containsString( + "Removed trait contents from `smithy.api#paginated` at path `/pageSize`. Removed value: `maxResults`" + ) ); } @@ -136,8 +136,8 @@ public void ignoresAdditionOfPageSize() { // Remove the pageSize from the old model, making it detect the addition of a pageSize. Model oldModel = ModelTransformer.create().mapTraits(model, (shape, trait) -> { return trait instanceof PaginatedTrait - ? ((PaginatedTrait) trait).toBuilder().pageSize(null).build() - : trait; + ? ((PaginatedTrait) trait).toBuilder().pageSize(null).build() + : trait; }); List events = ModelDiff.compare(oldModel, model); @@ -151,8 +151,8 @@ public void detectsChangeToPageSize() { // Change the pageSize value in the new model. Model newModel = ModelTransformer.create().mapTraits(model, (shape, trait) -> { return trait instanceof PaginatedTrait - ? ((PaginatedTrait) trait).toBuilder().pageSize("otherMaxResults").build() - : trait; + ? ((PaginatedTrait) trait).toBuilder().pageSize("otherMaxResults").build() + : trait; }); List events = ModelDiff.compare(model, newModel); @@ -160,10 +160,10 @@ public void detectsChangeToPageSize() { assertThat(changedTraitEvents.size(), equalTo(1)); assertThat( - changedTraitEvents.get(0).getMessage(), - containsString( - "Changed trait contents of `smithy.api#paginated` at path `/pageSize` from `maxResults` to `otherMaxResults`" - ) + changedTraitEvents.get(0).getMessage(), + containsString( + "Changed trait contents of `smithy.api#paginated` at path `/pageSize` from `maxResults` to `otherMaxResults`" + ) ); } @@ -171,8 +171,8 @@ public void detectsChangeToPageSize() { public void detectsAnyChangeToInputToken() { Model newModel = ModelTransformer.create().mapTraits(model, (shape, trait) -> { return trait instanceof PaginatedTrait - ? ((PaginatedTrait) trait).toBuilder().inputToken("otherToken").build() - : trait; + ? ((PaginatedTrait) trait).toBuilder().inputToken("otherToken").build() + : trait; }); List events = ModelDiff.compare(model, newModel); @@ -180,10 +180,10 @@ public void detectsAnyChangeToInputToken() { assertThat(changedTraitEvents.size(), equalTo(1)); assertThat( - changedTraitEvents.get(0).getMessage(), - containsString( - "Changed trait contents of `smithy.api#paginated` at path `/inputToken` from `token` to `otherToken`" - ) + changedTraitEvents.get(0).getMessage(), + containsString( + "Changed trait contents of `smithy.api#paginated` at path `/inputToken` from `token` to `otherToken`" + ) ); } @@ -191,8 +191,8 @@ public void detectsAnyChangeToInputToken() { public void detectsAnyChangeToOutputToken() { Model newModel = ModelTransformer.create().mapTraits(model, (shape, trait) -> { return trait instanceof PaginatedTrait - ? ((PaginatedTrait) trait).toBuilder().outputToken("otherToken").build() - : trait; + ? ((PaginatedTrait) trait).toBuilder().outputToken("otherToken").build() + : trait; }); List events = ModelDiff.compare(model, newModel); @@ -200,10 +200,10 @@ public void detectsAnyChangeToOutputToken() { assertThat(changedTraitEvents.size(), equalTo(1)); assertThat( - changedTraitEvents.get(0).getMessage(), - containsString( - "Changed trait contents of `smithy.api#paginated` at path `/outputToken` from `token` to `otherToken`" - ) + changedTraitEvents.get(0).getMessage(), + containsString( + "Changed trait contents of `smithy.api#paginated` at path `/outputToken` from `token` to `otherToken`" + ) ); } } diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedRangeTraitTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedRangeTraitTest.java index 0840031f3b2..c4fc527202b 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedRangeTraitTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedRangeTraitTest.java @@ -22,13 +22,13 @@ public class ChangedRangeTraitTest { @Test public void detectsMinRaised() { Shape i1 = IntegerShape.builder() - .id("foo.baz#Baz") - .addTrait(RangeTrait.builder().min(BigDecimal.valueOf(1)).build()) - .build(); + .id("foo.baz#Baz") + .addTrait(RangeTrait.builder().min(BigDecimal.valueOf(1)).build()) + .build(); Shape i2 = IntegerShape.builder() - .id("foo.baz#Baz") - .addTrait(RangeTrait.builder().min(BigDecimal.valueOf(2)).build()) - .build(); + .id("foo.baz#Baz") + .addTrait(RangeTrait.builder().min(BigDecimal.valueOf(2)).build()) + .build(); Model modelA = Model.assembler().addShapes(i1).assemble().unwrap(); Model modelB = Model.assembler().addShapes(i2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -40,13 +40,13 @@ public void detectsMinRaised() { @Test public void detectsMaxLowered() { Shape i1 = IntegerShape.builder() - .id("foo.baz#Baz") - .addTrait(RangeTrait.builder().max(BigDecimal.valueOf(2)).build()) - .build(); + .id("foo.baz#Baz") + .addTrait(RangeTrait.builder().max(BigDecimal.valueOf(2)).build()) + .build(); Shape i2 = IntegerShape.builder() - .id("foo.baz#Baz") - .addTrait(RangeTrait.builder().max(BigDecimal.valueOf(1)).build()) - .build(); + .id("foo.baz#Baz") + .addTrait(RangeTrait.builder().max(BigDecimal.valueOf(1)).build()) + .build(); Model modelA = Model.assembler().addShapes(i1).assemble().unwrap(); Model modelB = Model.assembler().addShapes(i2).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedShapeTypeTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedShapeTypeTest.java index 342794eba69..825225c1cd0 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedShapeTypeTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ChangedShapeTypeTest.java @@ -40,14 +40,14 @@ public void detectsTypeChanges() { public void ignoresExpectedSetToListMigration() { String rawModel = "$version: \"1.0\"\nnamespace smithy.example\nset Foo { member: String }\n"; Model oldModel = Model.assembler() - .addUnparsedModel("example.smithy", rawModel) - .assemble() - .unwrap(); + .addUnparsedModel("example.smithy", rawModel) + .assemble() + .unwrap(); Node serialized = ModelSerializer.builder().build().serialize(oldModel); Model newModel = Model.assembler() - .addDocumentNode(serialized) - .assemble() - .unwrap(); + .addDocumentNode(serialized) + .assemble() + .unwrap(); List events = ModelDiff.compare(oldModel, newModel); @@ -57,22 +57,22 @@ public void ignoresExpectedSetToListMigration() { @Test public void ignoresExpectedEnumTraitToEnumMigration() { Shape stringWithEnumTrait = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("FOO") - .value("FOO") - .build() - ) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .name("FOO") + .value("FOO") + .build() + ) + .build() + ) + .build(); Shape enumShape = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("FOO", "FOO") - .build(); + .id("foo.baz#Baz") + .addMember("FOO", "FOO") + .build(); Model modelA = Model.assembler().addShapes(stringWithEnumTrait).assemble().unwrap(); Model modelB = Model.assembler().addShapes(enumShape).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -83,31 +83,31 @@ public void ignoresExpectedEnumTraitToEnumMigration() { @Test public void ignoresEnumTraitToEnumTraitMigration() { Shape stringWithEnumTraitA = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("FOO") - .value("FOO") - .build() - ) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .name("FOO") + .value("FOO") + .build() + ) + .build() + ) + .build(); Shape stringWithEnumTraitB = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("FOO") - .value("FOO") - .build() - ) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .name("FOO") + .value("FOO") + .build() + ) + .build() + ) + .build(); Model modelA = Model.assembler().addShapes(stringWithEnumTraitA).assemble().unwrap(); Model modelB = Model.assembler().addShapes(stringWithEnumTraitB).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -118,13 +118,13 @@ public void ignoresEnumTraitToEnumTraitMigration() { @Test public void ignoresEnumToEnumMigration() { Shape enumShapeA = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("FOO", "FOO") - .build(); + .id("foo.baz#Baz") + .addMember("FOO", "FOO") + .build(); Shape enumShapeB = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("FOO", "FOO") - .build(); + .id("foo.baz#Baz") + .addMember("FOO", "FOO") + .build(); Model modelA = Model.assembler().addShapes(enumShapeA).assemble().unwrap(); Model modelB = Model.assembler().addShapes(enumShapeB).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -135,22 +135,22 @@ public void ignoresEnumToEnumMigration() { @Test public void doesNotIgnoreEnumTraitToEnumMigration() { Shape enumShape = EnumShape.builder() - .id("foo.baz#Baz") - .addMember("FOO", "FOO") - .build(); + .id("foo.baz#Baz") + .addMember("FOO", "FOO") + .build(); Shape stringWithEnumTrait = StringShape.builder() - .id("foo.baz#Baz") - .addTrait( - EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("FOO") - .value("FOO") - .build() - ) - .build() - ) - .build(); + .id("foo.baz#Baz") + .addTrait( + EnumTrait.builder() + .addEnum( + EnumDefinition.builder() + .name("FOO") + .value("FOO") + .build() + ) + .build() + ) + .build(); Model modelA = Model.assembler().addShapes(enumShape).assemble().unwrap(); Model modelB = Model.assembler().addShapes(stringWithEnumTrait).assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ModifiedTraitTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ModifiedTraitTest.java index 5915701f1d6..584ee78d174 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ModifiedTraitTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ModifiedTraitTest.java @@ -87,11 +87,11 @@ public void testWithTag(String oldValue, String newValue, String diffType, Strin @ParameterizedTest @MethodSource("data") public void testWithoutDefinition( - String oldValue, - String newValue, - String diffType, - String tag, - String searchString + String oldValue, + String newValue, + String diffType, + String tag, + String searchString ) { TestCaseData data = new TestCaseData(oldValue, newValue); @@ -109,20 +109,20 @@ public void testWithoutDefinition( public static Collection data() { return Arrays.asList( - new String[][]{ - {null, "hi", "Add", "diff.error.add", "Added"}, - {"hi", null, "Remove", "diff.error.remove", "Removed"}, - {"foo", "baz", "Update", "diff.error.update", "Changed"}, - } + new String[][]{ + {null, "hi", "Add", "diff.error.add", "Added"}, + {"hi", null, "Remove", "diff.error.remove", "Removed"}, + {"foo", "baz", "Update", "diff.error.update", "Changed"}, + } ); } private static Shape createDefinition(String tag) { return StringShape.builder() - .id(ID) - .addTrait(TagsTrait.builder().addValue(tag).build()) - .addTrait(TraitDefinition.builder().build()) - .build(); + .id(ID) + .addTrait(TagsTrait.builder().addValue(tag).build()) + .addTrait(TraitDefinition.builder().build()) + .build(); } @Test @@ -139,48 +139,48 @@ public void noEventsForUnmodifiedTraitWithoutDefinition() { @Test public void modifiedShapeNoTag() { Model modelA = Model.assembler() - .addImport(getClass().getResource("trait-test-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("trait-test-a.smithy")) + .assemble() + .unwrap(); Model modelB = Model.assembler() - .addImport(getClass().getResource("trait-test-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("trait-test-b.smithy")) + .assemble() + .unwrap(); List events = TestHelper.findEvents(ModelDiff.compare(modelA, modelB), "ModifiedTrait"); List messages = events.stream().map(ValidationEvent::getMessage).collect(Collectors.toList()); assertThat(events, hasSize(3)); assertThat(events.stream().filter(e -> e.getSeverity() == Severity.WARNING).count(), equalTo(1L)); assertThat( - events.stream().filter(e -> e.getSourceLocation().getFilename().endsWith("a.smithy")).count(), - equalTo(1L) + events.stream().filter(e -> e.getSourceLocation().getFilename().endsWith("a.smithy")).count(), + equalTo(1L) ); assertThat(events.stream().filter(e -> e.getSeverity() == Severity.NOTE).count(), equalTo(2L)); assertThat( - events.stream().filter(e -> e.getSourceLocation().getFilename().endsWith("b.smithy")).count(), - equalTo(2L) + events.stream().filter(e -> e.getSourceLocation().getFilename().endsWith("b.smithy")).count(), + equalTo(2L) ); assertThat( - messages, - containsInAnyOrder( - "Changed trait `smithy.example#b` from `hello` to `hello!`", - "Removed trait `smithy.example#a`. Previous trait value: `{}`", - "Added trait `smithy.example#c` with value `foo`" - ) + messages, + containsInAnyOrder( + "Changed trait `smithy.example#b` from `hello` to `hello!`", + "Removed trait `smithy.example#a`. Previous trait value: `{}`", + "Added trait `smithy.example#c` with value `foo`" + ) ); } @Test public void findsDifferencesInTraitValues() { Model modelA = Model.assembler() - .addImport(getClass().getResource("trait-modified-contents-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("trait-modified-contents-a.smithy")) + .assemble() + .unwrap(); Model modelB = Model.assembler() - .addImport(getClass().getResource("trait-modified-contents-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("trait-modified-contents-b.smithy")) + .assemble() + .unwrap(); List events = TestHelper.findEvents(ModelDiff.compare(modelA, modelB), "ModifiedTrait"); List messages = events.stream().map(ValidationEvent::getMessage).collect(Collectors.toList()); @@ -188,258 +188,258 @@ public void findsDifferencesInTraitValues() { assertThat(events.stream().filter(e -> e.getSeverity() == Severity.ERROR).count(), equalTo(1L)); assertThat(events.stream().filter(e -> e.getSeverity() == Severity.WARNING).count(), equalTo(1L)); assertThat( - events.stream().filter(e -> e.getSourceLocation().getFilename().endsWith("b.smithy")).count(), - equalTo(2L) + events.stream().filter(e -> e.getSourceLocation().getFilename().endsWith("b.smithy")).count(), + equalTo(2L) ); assertThat( - messages, - containsInAnyOrder( - "Added trait contents to `smithy.example#aTrait` at path `/bar` with value `no`", - "Changed trait contents of `smithy.example#aTrait` at path `/baz/foo` from `bye` to `adios`" - ) + messages, + containsInAnyOrder( + "Added trait contents to `smithy.example#aTrait` at path `/bar` with value `no`", + "Changed trait contents of `smithy.example#aTrait` at path `/baz/foo` from `bye` to `adios`" + ) ); } @Test public void findsDifferencesInListTraitValues() { Model modelA = Model.assembler() - .addImport(getClass().getResource("trait-modified-contents-list-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("trait-modified-contents-list-a.smithy")) + .assemble() + .unwrap(); Model modelB = Model.assembler() - .addImport(getClass().getResource("trait-modified-contents-list-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("trait-modified-contents-list-b.smithy")) + .assemble() + .unwrap(); List events = TestHelper.findEvents(ModelDiff.compare(modelA, modelB), "ModifiedTrait"); List messages = events.stream().map(ValidationEvent::getMessage).collect(Collectors.toList()); assertThat(events, hasSize(4)); assertThat( - events.stream() - .filter(e -> e.getMessage().contains("Removed")) - .filter(e -> e.getSourceLocation().getFilename().endsWith("a.smithy")) - .count(), - equalTo(2L) + events.stream() + .filter(e -> e.getMessage().contains("Removed")) + .filter(e -> e.getSourceLocation().getFilename().endsWith("a.smithy")) + .count(), + equalTo(2L) ); assertThat( - events.stream() - .filter(e -> !e.getMessage().contains("Removed")) - .filter(e -> e.getSourceLocation().getFilename().endsWith("b.smithy")) - .count(), - equalTo(2L) + events.stream() + .filter(e -> !e.getMessage().contains("Removed")) + .filter(e -> e.getSourceLocation().getFilename().endsWith("b.smithy")) + .count(), + equalTo(2L) ); assertThat( - messages, - containsInAnyOrder( - "Changed trait contents of `smithy.example#aTrait` at path `/foo/1` from `b` to `B`", - "Added trait contents to `smithy.example#aTrait` at path `/foo/3` with value `4`", - "Removed trait contents from `smithy.example#aTrait` at path `/foo/2`. Removed value: `3`", - String.format( - "Removed trait contents from `smithy.example#aTrait` at path `/foo`. Removed value: %n" - + "```%n" - + "[%n" - + " \"1\",%n" - + " \"2\",%n" - + " \"3\"%n" - + "]%n" - + "```%n" + messages, + containsInAnyOrder( + "Changed trait contents of `smithy.example#aTrait` at path `/foo/1` from `b` to `B`", + "Added trait contents to `smithy.example#aTrait` at path `/foo/3` with value `4`", + "Removed trait contents from `smithy.example#aTrait` at path `/foo/2`. Removed value: `3`", + String.format( + "Removed trait contents from `smithy.example#aTrait` at path `/foo`. Removed value: %n" + + "```%n" + + "[%n" + + " \"1\",%n" + + " \"2\",%n" + + " \"3\"%n" + + "]%n" + + "```%n" + ) ) - ) ); } @Test public void findsDifferencesInSetTraitValues() { Model modelA = Model.assembler() - .addImport(getClass().getResource("trait-modified-contents-set-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("trait-modified-contents-set-a.smithy")) + .assemble() + .unwrap(); Model modelB = Model.assembler() - .addImport(getClass().getResource("trait-modified-contents-set-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("trait-modified-contents-set-b.smithy")) + .assemble() + .unwrap(); List events = TestHelper.findEvents(ModelDiff.compare(modelA, modelB), "ModifiedTrait"); List messages = events.stream().map(ValidationEvent::getMessage).collect(Collectors.toList()); assertThat(events, hasSize(4)); assertThat( - events.stream() - .filter(e -> e.getMessage().contains("Removed")) - .filter(e -> e.getSourceLocation().getFilename().endsWith("a.smithy")) - .count(), - equalTo(2L) + events.stream() + .filter(e -> e.getMessage().contains("Removed")) + .filter(e -> e.getSourceLocation().getFilename().endsWith("a.smithy")) + .count(), + equalTo(2L) ); assertThat( - events.stream() - .filter(e -> !e.getMessage().contains("Removed")) - .filter(e -> e.getSourceLocation().getFilename().endsWith("b.smithy")) - .count(), - equalTo(2L) + events.stream() + .filter(e -> !e.getMessage().contains("Removed")) + .filter(e -> e.getSourceLocation().getFilename().endsWith("b.smithy")) + .count(), + equalTo(2L) ); assertThat( - messages, - containsInAnyOrder( - "Changed trait contents of `smithy.example#aTrait` at path `/foo/1` from `b` to `B`", - "Added trait contents to `smithy.example#aTrait` at path `/foo/3` with value `4`", - "Removed trait contents from `smithy.example#aTrait` at path `/foo/2`. Removed value: `3`", - String.format( - "Removed trait contents from `smithy.example#aTrait` at path `/foo`. " - + "Removed value: %n" - + "```%n" - + "[%n" - + " \"1\",%n" - + " \"2\",%n" - + " \"3\"%n" - + "]%n" - + "```%n" + messages, + containsInAnyOrder( + "Changed trait contents of `smithy.example#aTrait` at path `/foo/1` from `b` to `B`", + "Added trait contents to `smithy.example#aTrait` at path `/foo/3` with value `4`", + "Removed trait contents from `smithy.example#aTrait` at path `/foo/2`. Removed value: `3`", + String.format( + "Removed trait contents from `smithy.example#aTrait` at path `/foo`. " + + "Removed value: %n" + + "```%n" + + "[%n" + + " \"1\",%n" + + " \"2\",%n" + + " \"3\"%n" + + "]%n" + + "```%n" + ) ) - ) ); } @Test public void findsDifferencesInMapTraitValues() { Model modelA = Model.assembler() - .addImport(getClass().getResource("trait-modified-contents-map-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("trait-modified-contents-map-a.smithy")) + .assemble() + .unwrap(); Model modelB = Model.assembler() - .addImport(getClass().getResource("trait-modified-contents-map-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("trait-modified-contents-map-b.smithy")) + .assemble() + .unwrap(); List events = TestHelper.findEvents(ModelDiff.compare(modelA, modelB), "ModifiedTrait"); List messages = events.stream().map(ValidationEvent::getMessage).collect(Collectors.toList()); assertThat(events, hasSize(4)); assertThat( - events.stream() - .filter(e -> e.getMessage().contains("Removed")) - .filter(e -> e.getSourceLocation().getFilename().endsWith("a.smithy")) - .count(), - equalTo(2L) + events.stream() + .filter(e -> e.getMessage().contains("Removed")) + .filter(e -> e.getSourceLocation().getFilename().endsWith("a.smithy")) + .count(), + equalTo(2L) ); assertThat( - events.stream() - .filter(e -> !e.getMessage().contains("Removed")) - .filter(e -> e.getSourceLocation().getFilename().endsWith("b.smithy")) - .count(), - equalTo(2L) + events.stream() + .filter(e -> !e.getMessage().contains("Removed")) + .filter(e -> e.getSourceLocation().getFilename().endsWith("b.smithy")) + .count(), + equalTo(2L) ); assertThat( - messages, - containsInAnyOrder( - "Changed trait contents of `smithy.example#aTrait` at path `/foo/bam` from `b` to `B`", - String.format( - "Removed trait contents from `smithy.example#aTrait` at path `/foo`. " - + "Removed value: %n" - + "```%n" - + "{%n" - + " \"baz\": \"1\",%n" - + " \"bam\": \"2\",%n" - + " \"boo\": \"3\"%n" - + "}%n" - + "```%n" - ), - "Added trait contents to `smithy.example#aTrait` at path `/foo/qux` with value `4`", - "Removed trait contents from `smithy.example#aTrait` at path `/foo/boo`. Removed value: `3`" - ) + messages, + containsInAnyOrder( + "Changed trait contents of `smithy.example#aTrait` at path `/foo/bam` from `b` to `B`", + String.format( + "Removed trait contents from `smithy.example#aTrait` at path `/foo`. " + + "Removed value: %n" + + "```%n" + + "{%n" + + " \"baz\": \"1\",%n" + + " \"bam\": \"2\",%n" + + " \"boo\": \"3\"%n" + + "}%n" + + "```%n" + ), + "Added trait contents to `smithy.example#aTrait` at path `/foo/qux` with value `4`", + "Removed trait contents from `smithy.example#aTrait` at path `/foo/boo`. Removed value: `3`" + ) ); } @Test public void findsDifferencesInUnionTraitValues() { Model modelA = Model.assembler() - .addImport(getClass().getResource("trait-modified-contents-union-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("trait-modified-contents-union-a.smithy")) + .assemble() + .unwrap(); Model modelB = Model.assembler() - .addImport(getClass().getResource("trait-modified-contents-union-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("trait-modified-contents-union-b.smithy")) + .assemble() + .unwrap(); List events = TestHelper.findEvents(ModelDiff.compare(modelA, modelB), "ModifiedTrait"); List messages = events.stream().map(ValidationEvent::getMessage).collect(Collectors.toList()); assertThat(events, hasSize(2)); assertThat( - events.stream().filter(e -> e.getSourceLocation().getFilename().endsWith("b.smithy")).count(), - equalTo(2L) + events.stream().filter(e -> e.getSourceLocation().getFilename().endsWith("b.smithy")).count(), + equalTo(2L) ); assertThat( - messages, - containsInAnyOrder( - "Changed trait contents of `smithy.example#aTrait` at path `/baz/foo` from `a` to `b`", - "Changed trait contents of `smithy.example#aTrait` at path `/baz/baz` from `a` to `b`" - ) + messages, + containsInAnyOrder( + "Changed trait contents of `smithy.example#aTrait` at path `/baz/foo` from `a` to `b`", + "Changed trait contents of `smithy.example#aTrait` at path `/baz/baz` from `a` to `b`" + ) ); } @Test public void findsDifferencesInTraitValuesOfAllSeverities() { Model modelA = Model.assembler() - .addImport(getClass().getResource("trait-modified-all-severities-a.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("trait-modified-all-severities-a.smithy")) + .assemble() + .unwrap(); Model modelB = Model.assembler() - .addImport(getClass().getResource("trait-modified-all-severities-b.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("trait-modified-all-severities-b.smithy")) + .assemble() + .unwrap(); List events = TestHelper.findEvents(ModelDiff.compare(modelA, modelB), "ModifiedTrait"); List messages = events.stream().map(ValidationEvent::getMessage).collect(Collectors.toList()); assertThat(events, hasSize(12)); assertThat( - events.stream() - .filter(e -> e.getMessage().contains("Removed")) - .filter(e -> e.getSourceLocation().getFilename().endsWith("a.smithy")) - .count(), - equalTo(3L) + events.stream() + .filter(e -> e.getMessage().contains("Removed")) + .filter(e -> e.getSourceLocation().getFilename().endsWith("a.smithy")) + .count(), + equalTo(3L) ); assertThat( - events.stream() - .filter(e -> e.getMessage().contains("Changed") || e.getMessage().contains("Added")) - .filter(e -> e.getSourceLocation().getFilename().endsWith("b.smithy")) - .count(), - equalTo(9L) + events.stream() + .filter(e -> e.getMessage().contains("Changed") || e.getMessage().contains("Added")) + .filter(e -> e.getSourceLocation().getFilename().endsWith("b.smithy")) + .count(), + equalTo(9L) ); assertThat( - messages, - containsInAnyOrder( - "Added trait contents to `smithy.example#aTrait` at path `/a` with value `a`", - "Removed trait contents from `smithy.example#aTrait` at path `/b`. Removed value: `a`", - "Changed trait contents of `smithy.example#aTrait` at path `/c` from `a` to `c`", - "Changed trait contents of `smithy.example#aTrait` at path `/d` from `a` to `d`", - "Added trait contents to `smithy.example#aTrait` at path `/e` with value `a`", - "Removed trait contents from `smithy.example#aTrait` at path `/f`. Removed value: `a`", - "Changed trait contents of `smithy.example#aTrait` at path `/g` from `a` to `h`", - "Changed trait contents of `smithy.example#aTrait` at path `/h` from `a` to `h`", - "Added trait contents to `smithy.example#aTrait` at path `/i` with value `a`", - "Removed trait contents from `smithy.example#aTrait` at path `/j`. Removed value: `a`", - "Changed trait contents of `smithy.example#aTrait` at path `/k` from `a` to `k`", - "Changed trait contents of `smithy.example#aTrait` at path `/l` from `a` to `l`" - ) + messages, + containsInAnyOrder( + "Added trait contents to `smithy.example#aTrait` at path `/a` with value `a`", + "Removed trait contents from `smithy.example#aTrait` at path `/b`. Removed value: `a`", + "Changed trait contents of `smithy.example#aTrait` at path `/c` from `a` to `c`", + "Changed trait contents of `smithy.example#aTrait` at path `/d` from `a` to `d`", + "Added trait contents to `smithy.example#aTrait` at path `/e` with value `a`", + "Removed trait contents from `smithy.example#aTrait` at path `/f`. Removed value: `a`", + "Changed trait contents of `smithy.example#aTrait` at path `/g` from `a` to `h`", + "Changed trait contents of `smithy.example#aTrait` at path `/h` from `a` to `h`", + "Added trait contents to `smithy.example#aTrait` at path `/i` with value `a`", + "Removed trait contents from `smithy.example#aTrait` at path `/j`. Removed value: `a`", + "Changed trait contents of `smithy.example#aTrait` at path `/k` from `a` to `k`", + "Changed trait contents of `smithy.example#aTrait` at path `/l` from `a` to `l`" + ) ); } @Test public void letsOtherValidatorsHandleRequiredTrait() { String originalModel = "$version: \"2.0\"\n" - + "namespace smithy.example\n" - + "structure Baz {}\n" - + "structure Foo {\n" - + " @required\n" - + " baz: Baz\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Baz {}\n" + + "structure Foo {\n" + + " @required\n" + + " baz: Baz\n" + + "}\n"; Model oldModel = Model.assembler().addUnparsedModel("foo.smithy", originalModel).assemble().unwrap(); Model newModel = ModelTransformer.create() - .replaceShapes( - oldModel, - ListUtils.of( - Shape.shapeToBuilder(oldModel.expectShape(ShapeId.from("smithy.example#Foo$baz"))) - .removeTrait(RequiredTrait.ID) - .build() - ) - ); + .replaceShapes( + oldModel, + ListUtils.of( + Shape.shapeToBuilder(oldModel.expectShape(ShapeId.from("smithy.example#Foo$baz"))) + .removeTrait(RequiredTrait.ID) + .build() + ) + ); assertThat(TestHelper.findEvents(ModelDiff.compare(oldModel, newModel), "ModifiedTrait"), empty()); } @@ -447,21 +447,21 @@ public void letsOtherValidatorsHandleRequiredTrait() { @Test public void letsTraitBreakingChangeHandleDiffEvents() { String originalModel = "$version: \"2.0\"\n" - + "namespace smithy.example\n" - + "structure Test {\n" - + " @jsonName(\"a\")\n" - + " member: String\n" - + "}"; + + "namespace smithy.example\n" + + "structure Test {\n" + + " @jsonName(\"a\")\n" + + " member: String\n" + + "}"; Model oldModel = Model.assembler().addUnparsedModel("foo.smithy", originalModel).assemble().unwrap(); Model newModel = ModelTransformer.create() - .replaceShapes( - oldModel, - ListUtils.of( - Shape.shapeToBuilder(oldModel.expectShape(ShapeId.from("smithy.example#Test$member"))) - .removeTrait(JsonNameTrait.ID) - .build() - ) - ); + .replaceShapes( + oldModel, + ListUtils.of( + Shape.shapeToBuilder(oldModel.expectShape(ShapeId.from("smithy.example#Test$member"))) + .removeTrait(JsonNameTrait.ID) + .build() + ) + ); assertThat(TestHelper.findEvents(ModelDiff.compare(oldModel, newModel), "ModifiedTrait"), empty()); assertThat(TestHelper.findEvents(ModelDiff.compare(oldModel, newModel), "TraitBreakingChange"), hasSize(1)); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedEntityBindingTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedEntityBindingTest.java index 77c46490f38..d0710f94425 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedEntityBindingTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedEntityBindingTest.java @@ -23,11 +23,11 @@ public void detectsRemovedOperationFromService() { SourceLocation source = new SourceLocation("foo.smithy"); OperationShape o = OperationShape.builder().id("foo.baz#Operation").build(); ServiceShape service1 = ServiceShape.builder() - .version("1") - .id("foo.baz#Service") - .addOperation(o.getId()) - .source(source) - .build(); + .version("1") + .id("foo.baz#Service") + .addOperation(o.getId()) + .source(source) + .build(); ServiceShape service2 = service1.toBuilder().clearOperations().build(); Model modelA = Model.assembler().addShapes(service1, o).assemble().unwrap(); Model modelB = Model.assembler().addShapes(service2, o).assemble().unwrap(); @@ -42,10 +42,10 @@ public void detectsRemovedOperationFromResource() { SourceLocation source = new SourceLocation("foo.smithy"); OperationShape o = OperationShape.builder().id("foo.baz#Operation").build(); ResourceShape r1 = ResourceShape.builder() - .id("foo.baz#Resource") - .addOperation(o.getId()) - .source(source) - .build(); + .id("foo.baz#Resource") + .addOperation(o.getId()) + .source(source) + .build(); ResourceShape r2 = r1.toBuilder().clearOperations().build(); Model modelA = Model.assembler().addShapes(r1, o).assemble().unwrap(); Model modelB = Model.assembler().addShapes(r2, o).assemble().unwrap(); @@ -60,11 +60,11 @@ public void detectsRemovedResourceFromService() { SourceLocation source = new SourceLocation("foo.smithy"); ResourceShape r = ResourceShape.builder().id("foo.baz#Resource").build(); ServiceShape service1 = ServiceShape.builder() - .id("foo.baz#Service") - .version("1") - .addResource(r.getId()) - .source(source) - .build(); + .id("foo.baz#Service") + .version("1") + .addResource(r.getId()) + .source(source) + .build(); ServiceShape service2 = service1.toBuilder().clearResources().build(); Model modelA = Model.assembler().addShapes(service1, r).assemble().unwrap(); Model modelB = Model.assembler().addShapes(service2, r).assemble().unwrap(); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedOperationErrorTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedOperationErrorTest.java index d0b230954ea..8df1f03b209 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedOperationErrorTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedOperationErrorTest.java @@ -24,19 +24,19 @@ public class RemovedOperationErrorTest { public void detectsRemovedErrors() { SourceLocation source = new SourceLocation("foo.smithy"); Shape e1 = StructureShape.builder() - .id("foo.baz#E1") - .addTrait(new ErrorTrait("client")) - .build(); + .id("foo.baz#E1") + .addTrait(new ErrorTrait("client")) + .build(); Shape e2 = StructureShape.builder() - .id("foo.baz#E2") - .addTrait(new ErrorTrait("client")) - .build(); + .id("foo.baz#E2") + .addTrait(new ErrorTrait("client")) + .build(); OperationShape operation1 = OperationShape.builder() - .id("foo.baz#Operation") - .addError(e1) - .addError(e2) - .source(source) - .build(); + .id("foo.baz#Operation") + .addError(e1) + .addError(e2) + .source(source) + .build(); Shape operation2 = operation1.toBuilder().clearErrors().build(); Model modelA = Model.assembler().addShapes(operation1, e1, e2).assemble().unwrap(); Model modelB = Model.assembler().addShapes(operation2, e1, e2).assemble().unwrap(); @@ -48,18 +48,18 @@ public void detectsRemovedErrors() { assertThat(TestHelper.findEvents(events, "RemovedOperationError.E1").size(), equalTo(1)); assertThat(TestHelper.findEvents(events, "RemovedOperationError.E2").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "RemovedOperationError").get(0).toString(), - startsWith( - "[WARNING] foo.baz#Operation: The `foo.baz#E1` error was removed " + - "from the `foo.baz#Operation` operation. | RemovedOperationError" - ) + TestHelper.findEvents(events, "RemovedOperationError").get(0).toString(), + startsWith( + "[WARNING] foo.baz#Operation: The `foo.baz#E1` error was removed " + + "from the `foo.baz#Operation` operation. | RemovedOperationError" + ) ); assertThat( - TestHelper.findEvents(events, "RemovedOperationError").get(1).toString(), - startsWith( - "[WARNING] foo.baz#Operation: The `foo.baz#E2` error was removed " + - "from the `foo.baz#Operation` operation. | RemovedOperationError" - ) + TestHelper.findEvents(events, "RemovedOperationError").get(1).toString(), + startsWith( + "[WARNING] foo.baz#Operation: The `foo.baz#E2` error was removed " + + "from the `foo.baz#Operation` operation. | RemovedOperationError" + ) ); } } diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedServiceErrorTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedServiceErrorTest.java index c1cc64c9c63..36a98de1d19 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedServiceErrorTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedServiceErrorTest.java @@ -21,19 +21,19 @@ public class RemovedServiceErrorTest { @Test public void detectsRemovedErrors() { Shape e1 = StructureShape.builder() - .id("foo.baz#E1") - .addTrait(new ErrorTrait("client")) - .build(); + .id("foo.baz#E1") + .addTrait(new ErrorTrait("client")) + .build(); Shape e2 = StructureShape.builder() - .id("foo.baz#E2") - .addTrait(new ErrorTrait("client")) - .build(); + .id("foo.baz#E2") + .addTrait(new ErrorTrait("client")) + .build(); ServiceShape service1 = ServiceShape.builder() - .id("foo.baz#S") - .version("X") - .addError(e1) - .addError(e2) - .build(); + .id("foo.baz#S") + .version("X") + .addError(e1) + .addError(e2) + .build(); ServiceShape service2 = service1.toBuilder().clearErrors().build(); Model modelA = Model.assembler().addShapes(service1, e1, e2).assemble().unwrap(); Model modelB = Model.assembler().addShapes(service2, e1, e2).assemble().unwrap(); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedShapeTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedShapeTest.java index 9a7d8c32ca2..4629dcfc1e1 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedShapeTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedShapeTest.java @@ -52,18 +52,18 @@ public void detectsShapeRemoval() { @Test public void emitsWarningsForScalarShapes() { Shape[] scalarShapes = new Shape[]{ - IntegerShape.builder().id("foo.baz#BazOne").build(), - BigDecimalShape.builder().id("foo.baz#BazTwo").build(), - BigIntegerShape.builder().id("foo.baz#BazThree").build(), - BlobShape.builder().id("foo.baz#BazFour").build(), - BooleanShape.builder().id("foo.baz#BazFive").build(), - ByteShape.builder().id("foo.baz#BazSix").build(), - DoubleShape.builder().id("foo.baz#BazSeven").build(), - FloatShape.builder().id("foo.baz#BazEight").build(), - ShortShape.builder().id("foo.baz#BazNine").build(), - TimestampShape.builder().id("foo.baz#BazTen").build(), - LongShape.builder().id("foo.baz#BazEleven").build(), - StringShape.builder().id("foo.baz#BazTwelve").build() + IntegerShape.builder().id("foo.baz#BazOne").build(), + BigDecimalShape.builder().id("foo.baz#BazTwo").build(), + BigIntegerShape.builder().id("foo.baz#BazThree").build(), + BlobShape.builder().id("foo.baz#BazFour").build(), + BooleanShape.builder().id("foo.baz#BazFive").build(), + ByteShape.builder().id("foo.baz#BazSix").build(), + DoubleShape.builder().id("foo.baz#BazSeven").build(), + FloatShape.builder().id("foo.baz#BazEight").build(), + ShortShape.builder().id("foo.baz#BazNine").build(), + TimestampShape.builder().id("foo.baz#BazTen").build(), + LongShape.builder().id("foo.baz#BazEleven").build(), + StringShape.builder().id("foo.baz#BazTwelve").build() }; Model modelA = Model.assembler().addShapes(scalarShapes).assemble().unwrap(); Model modelB = Model.assembler().assemble().unwrap(); @@ -71,17 +71,17 @@ public void emitsWarningsForScalarShapes() { assertThat(TestHelper.findEvents(events, "RemovedShape.ScalarShape").size(), equalTo(12)); assertThat( - "Scalar removals should be WARNING severity", - events.stream().allMatch(event -> Severity.WARNING.equals(event.getSeverity())) + "Scalar removals should be WARNING severity", + events.stream().allMatch(event -> Severity.WARNING.equals(event.getSeverity())) ); } @Test public void emitsErrorForEnumString() { Shape shapeA1 = StringShape.builder() - .id("foo.baz#Baz") - .addTrait(EnumTrait.builder().addEnum(EnumDefinition.builder().value("val").build()).build()) - .build(); + .id("foo.baz#Baz") + .addTrait(EnumTrait.builder().addEnum(EnumDefinition.builder().value("val").build()).build()) + .build(); Model modelA = Model.assembler().addShapes(shapeA1).assemble().unwrap(); Model modelB = Model.assembler().addShapes().assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); @@ -94,9 +94,9 @@ public void emitsErrorForEnumString() { @Test public void emitsErrorForIntEnum() { Shape shapeA1 = IntEnumShape.builder() - .id("foo.baz#Baz") - .addMember("FOO", 1) - .build(); + .id("foo.baz#Baz") + .addMember("FOO", 1) + .build(); Model modelA = Model.assembler().addShapes(shapeA1).assemble().unwrap(); Model modelB = Model.assembler().addShapes().assemble().unwrap(); List events = ModelDiff.compare(modelA, modelB); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedTraitDefinitionTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedTraitDefinitionTest.java index d16a109bff1..0c58f5cf3ac 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedTraitDefinitionTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/RemovedTraitDefinitionTest.java @@ -22,9 +22,9 @@ public class RemovedTraitDefinitionTest { public void detectsRemovedTraitDefinition() { SourceLocation source = new SourceLocation("bar.smithy"); Shape definition = StringShape.builder() - .id("foo.baz#bam") - .addTrait(TraitDefinition.builder().sourceLocation(source).build()) - .build(); + .id("foo.baz#bam") + .addTrait(TraitDefinition.builder().sourceLocation(source).build()) + .build(); Model modelA = Model.assembler().addShape(definition).assemble().unwrap(); Model modelB = Model.assembler().assemble().unwrap(); @@ -32,8 +32,8 @@ public void detectsRemovedTraitDefinition() { assertThat(TestHelper.findEvents(events, "RemovedTraitDefinition").size(), equalTo(1)); assertThat( - TestHelper.findEvents(events, "RemovedTraitDefinition").get(0).getSourceLocation(), - equalTo(source) + TestHelper.findEvents(events, "RemovedTraitDefinition").get(0).getSourceLocation(), + equalTo(source) ); } } diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ServiceRenameTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ServiceRenameTest.java index abce7760d07..374fa2cc837 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ServiceRenameTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/ServiceRenameTest.java @@ -27,29 +27,29 @@ public class ServiceRenameTest { @BeforeAll public static void before() { operation = OperationShape.builder() - .id("smithy.example#O") - .build(); + .id("smithy.example#O") + .build(); service = ServiceShape.builder() - .id("smithy.example#S") - .version("1") - .addOperation(operation) - .build(); + .id("smithy.example#S") + .version("1") + .addOperation(operation) + .build(); } @Test public void detectsRenameRemoved() { SourceLocation source = new SourceLocation("foo.smithy"); ServiceShape service1 = service.toBuilder() - .putRename(operation.getId(), "O1") - .build(); + .putRename(operation.getId(), "O1") + .build(); Model modelA = Model.builder() - .addShapes(operation, service1) - .build(); + .addShapes(operation, service1) + .build(); ServiceShape service2 = service.toBuilder() - .clearRename() - .source(source) - .build(); + .clearRename() + .source(source) + .build(); Model modelB = modelA.toBuilder().addShape(service2).build(); List events = ModelDiff.compare(modelA, modelB); @@ -63,16 +63,16 @@ public void detectsRenameRemoved() { public void detectsRenameChange() { SourceLocation source = new SourceLocation("foo.smithy"); ServiceShape service1 = service.toBuilder() - .putRename(operation.getId(), "O1") - .build(); + .putRename(operation.getId(), "O1") + .build(); Model modelA = Model.builder() - .addShapes(operation, service1) - .build(); + .addShapes(operation, service1) + .build(); ServiceShape service2 = service.toBuilder() - .putRename(operation.getId(), "O2") - .source(source) - .build(); + .putRename(operation.getId(), "O2") + .source(source) + .build(); Model modelB = modelA.toBuilder().addShape(service2).build(); List events = ModelDiff.compare(modelA, modelB); @@ -86,13 +86,13 @@ public void detectsRenameChange() { public void detectsRenameAdded() { SourceLocation source = new SourceLocation("foo.smithy"); Model modelA = Model.builder() - .addShapes(operation, service) - .build(); + .addShapes(operation, service) + .build(); ServiceShape service2 = service.toBuilder() - .putRename(operation.getId(), "O2") - .source(source) - .build(); + .putRename(operation.getId(), "O2") + .source(source) + .build(); Model modelB = modelA.toBuilder().addShape(service2).build(); List events = ModelDiff.compare(modelA, modelB); @@ -106,11 +106,11 @@ public void detectsRenameAdded() { @Test public void ignoresSameRenames() { ServiceShape service1 = service.toBuilder() - .putRename(operation.getId(), "O1") - .build(); + .putRename(operation.getId(), "O1") + .build(); Model model = Model.builder() - .addShapes(operation, service1) - .build(); + .addShapes(operation, service1) + .build(); List events = ModelDiff.compare(model, model); assertThat(TestHelper.findEvents(events, "ServiceRename"), empty()); @@ -119,18 +119,18 @@ public void ignoresSameRenames() { @Test public void ignoresRenamesOfNewShapes() { ServiceShape service1 = service.toBuilder() - .removeOperation(operation.getId()) - .build(); + .removeOperation(operation.getId()) + .build(); Model modelA = Model.builder() - .addShapes(operation, service1) - .build(); + .addShapes(operation, service1) + .build(); ServiceShape service2 = service.toBuilder() - .putRename(operation.getId(), "Oo") - .build(); + .putRename(operation.getId(), "Oo") + .build(); Model modelB = Model.builder() - .addShapes(service2, service1) - .build(); + .addShapes(service2, service1) + .build(); List events = ModelDiff.compare(modelA, modelB); diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/TestHelper.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/TestHelper.java index 00ac0dfb75d..90e7fbdb51e 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/TestHelper.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/TestHelper.java @@ -13,19 +13,19 @@ public final class TestHelper { public static List findEvents(List events, String eventId) { return events.stream() - .filter(event -> event.containsId(eventId)) - .collect(Collectors.toList()); + .filter(event -> event.containsId(eventId)) + .collect(Collectors.toList()); } public static List findEvents(List events, Severity severity) { return events.stream() - .filter(event -> event.getSeverity() == severity) - .collect(Collectors.toList()); + .filter(event -> event.getSeverity() == severity) + .collect(Collectors.toList()); } public static List findEvents(List events, ToShapeId shapeId) { return events.stream() - .filter(event -> event.getShapeId().filter(id -> id.toShapeId().equals(shapeId)).isPresent()) - .collect(Collectors.toList()); + .filter(event -> event.getShapeId().filter(id -> id.toShapeId().equals(shapeId)).isPresent()) + .collect(Collectors.toList()); } } diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/TraitBreakingChangeTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/TraitBreakingChangeTest.java index fe0965972ed..17eef3fbc34 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/TraitBreakingChangeTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/evaluators/TraitBreakingChangeTest.java @@ -41,14 +41,14 @@ public void detectsBreakingChangeWhenRemoved() { } private void validate( - String modelFile, - Function mapper, - Consumer> consumer + String modelFile, + Function mapper, + Consumer> consumer ) { Model modelA = Model.assembler() - .addImport(getClass().getResource("trait-breaking-change/" + modelFile)) - .assemble() - .unwrap(); + .addImport(getClass().getResource("trait-breaking-change/" + modelFile)) + .assemble() + .unwrap(); // Find the example shape, transform it, and create a new model. StringShape example = modelA.expectShape(EXAMPLE_SHAPE, StringShape.class); @@ -63,13 +63,13 @@ private void validate( @Test public void detectsBreakingChangeWhenAdded() { validate( - "trait-added.smithy", - shape -> shape.addTrait(new DynamicTrait(EXAMPLE_TRAIT, Node.objectNode())).build(), - events -> { - assertThat(events, hasSize(1)); - assertThat(events.get(0).getId(), equalTo("TraitBreakingChange.Add.smithy.example#exampleTrait")); - assertThat(events.get(0).getMessage(), equalTo("Added trait `smithy.example#exampleTrait`")); - } + "trait-added.smithy", + shape -> shape.addTrait(new DynamicTrait(EXAMPLE_TRAIT, Node.objectNode())).build(), + events -> { + assertThat(events, hasSize(1)); + assertThat(events.get(0).getId(), equalTo("TraitBreakingChange.Add.smithy.example#exampleTrait")); + assertThat(events.get(0).getMessage(), equalTo("Added trait `smithy.example#exampleTrait`")); + } ); } @@ -106,8 +106,8 @@ public void canIncludeCustomMessage() { assertThat(events, hasSize(1)); assertThat(events.get(0).getId(), equalTo("TraitBreakingChange.Remove.smithy.example#exampleTrait")); assertThat( - events.get(0).getMessage(), - equalTo("Removed trait `smithy.example#exampleTrait`; This is bad!") + events.get(0).getMessage(), + equalTo("Removed trait `smithy.example#exampleTrait`; This is bad!") ); }); } @@ -115,108 +115,123 @@ public void canIncludeCustomMessage() { @Test public void canPathIntoListMembers() { validate( - "trait-list-members.smithy", - shape -> shape.addTrait(new DynamicTrait(EXAMPLE_TRAIT, Node.fromStrings("a", "B", "c"))).build(), - events -> { - assertThat(events, hasSize(1)); - assertThat(events.get(0).getId(), equalTo("TraitBreakingChange.Update.smithy.example#exampleTrait")); - assertThat( - events.get(0).getMessage(), - equalTo( - "Changed trait contents of `smithy.example#exampleTrait` at path `/1` " - + "from `b` to `B`" - ) - ); - } + "trait-list-members.smithy", + shape -> shape.addTrait(new DynamicTrait(EXAMPLE_TRAIT, Node.fromStrings("a", "B", "c"))).build(), + events -> { + assertThat(events, hasSize(1)); + assertThat( + events.get(0).getId(), + equalTo("TraitBreakingChange.Update.smithy.example#exampleTrait") + ); + assertThat( + events.get(0).getMessage(), + equalTo( + "Changed trait contents of `smithy.example#exampleTrait` at path `/1` " + + "from `b` to `B`" + ) + ); + } ); } @Test public void canPathIntoMapKeys() { validate( - "trait-map-keys.smithy", - shape -> shape.addTrait(new DynamicTrait(EXAMPLE_TRAIT, Node.objectNode().withMember("a", "A"))) - .build(), - events -> { - assertThat(events, hasSize(1)); - assertThat(events.get(0).getId(), equalTo("TraitBreakingChange.Remove.smithy.example#exampleTrait")); - assertThat( - events.get(0).getMessage(), - equalTo( - "Removed trait contents from `smithy.example#exampleTrait` at path `/b`. " - + "Removed value: `B`" - ) - ); - } + "trait-map-keys.smithy", + shape -> shape.addTrait(new DynamicTrait(EXAMPLE_TRAIT, Node.objectNode().withMember("a", "A"))) + .build(), + events -> { + assertThat(events, hasSize(1)); + assertThat( + events.get(0).getId(), + equalTo("TraitBreakingChange.Remove.smithy.example#exampleTrait") + ); + assertThat( + events.get(0).getMessage(), + equalTo( + "Removed trait contents from `smithy.example#exampleTrait` at path `/b`. " + + "Removed value: `B`" + ) + ); + } ); } @Test public void canPathIntoMapValues() { validate( - "trait-map-values.smithy", - shape -> { - Trait trait = new DynamicTrait( - EXAMPLE_TRAIT, - Node.objectNode().withMember("a", "A").withMember("b", "_B_") - ); - return shape.addTrait(trait).build(); - }, - events -> { - assertThat(events, hasSize(1)); - assertThat(events.get(0).getId(), equalTo("TraitBreakingChange.Update.smithy.example#exampleTrait")); - assertThat( - events.get(0).getMessage(), - equalTo( - "Changed trait contents of `smithy.example#exampleTrait` at path `/b` " - + "from `B` to `_B_`" - ) - ); - } + "trait-map-values.smithy", + shape -> { + Trait trait = new DynamicTrait( + EXAMPLE_TRAIT, + Node.objectNode().withMember("a", "A").withMember("b", "_B_") + ); + return shape.addTrait(trait).build(); + }, + events -> { + assertThat(events, hasSize(1)); + assertThat( + events.get(0).getId(), + equalTo("TraitBreakingChange.Update.smithy.example#exampleTrait") + ); + assertThat( + events.get(0).getMessage(), + equalTo( + "Changed trait contents of `smithy.example#exampleTrait` at path `/b` " + + "from `B` to `_B_`" + ) + ); + } ); } @Test public void canPathIntoStructureMembers() { validate( - "trait-structure-members.smithy", - shape -> { - Trait trait = new DynamicTrait(EXAMPLE_TRAIT, Node.objectNode()); - return shape.addTrait(trait).build(); - }, - events -> { - assertThat(events, hasSize(1)); - assertThat(events.get(0).getId(), equalTo("TraitBreakingChange.Remove.smithy.example#exampleTrait")); - assertThat( - events.get(0).getMessage(), - equalTo( - "Removed trait contents from `smithy.example#exampleTrait` at path " - + "`/foo/bar`. Removed value: `hi`" - ) - ); - } + "trait-structure-members.smithy", + shape -> { + Trait trait = new DynamicTrait(EXAMPLE_TRAIT, Node.objectNode()); + return shape.addTrait(trait).build(); + }, + events -> { + assertThat(events, hasSize(1)); + assertThat( + events.get(0).getId(), + equalTo("TraitBreakingChange.Remove.smithy.example#exampleTrait") + ); + assertThat( + events.get(0).getMessage(), + equalTo( + "Removed trait contents from `smithy.example#exampleTrait` at path " + + "`/foo/bar`. Removed value: `hi`" + ) + ); + } ); } @Test public void canPathIntoUnionMembers() { validate( - "trait-union-members.smithy", - shape -> { - Trait trait = new DynamicTrait(EXAMPLE_TRAIT, Node.objectNode().withMember("foo", "bye")); - return shape.addTrait(trait).build(); - }, - events -> { - assertThat(events, hasSize(1)); - assertThat(events.get(0).getId(), equalTo("TraitBreakingChange.Update.smithy.example#exampleTrait")); - assertThat( - events.get(0).getMessage(), - equalTo( - "Changed trait contents of `smithy.example#exampleTrait` at path " - + "`/foo` from `hi` to `bye`" - ) - ); - } + "trait-union-members.smithy", + shape -> { + Trait trait = new DynamicTrait(EXAMPLE_TRAIT, Node.objectNode().withMember("foo", "bye")); + return shape.addTrait(trait).build(); + }, + events -> { + assertThat(events, hasSize(1)); + assertThat( + events.get(0).getId(), + equalTo("TraitBreakingChange.Update.smithy.example#exampleTrait") + ); + assertThat( + events.get(0).getMessage(), + equalTo( + "Changed trait contents of `smithy.example#exampleTrait` at path " + + "`/foo` from `hi` to `bye`" + ) + ); + } ); } } diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestCaseTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestCaseTest.java index fe195d4eb0d..3fb9d462c65 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestCaseTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestCaseTest.java @@ -22,8 +22,8 @@ public class SmithyDiffTestCaseTest { @Test public void validatesThatEventsAreValid() { IllegalArgumentException e = assertThrows( - IllegalArgumentException.class, - () -> SmithyDiffTestCase.parseValidationEvent("[ERROR] - m", "filename") + IllegalArgumentException.class, + () -> SmithyDiffTestCase.parseValidationEvent("[ERROR] - m", "filename") ); assertTrue(e.getMessage().contains("`filename`")); @@ -43,15 +43,15 @@ public void throwsOnNonExistentFiles() { @Test public void matchesMessageUsingPrefix() { ValidationEvent actual = ValidationEvent.builder() - .id("FooBar") - .severity(Severity.DANGER) - .message("This is a test") - .build(); + .id("FooBar") + .severity(Severity.DANGER) + .message("This is a test") + .build(); ValidationEvent expected = actual.toBuilder().message("This is").build(); SmithyDiffTestCase testCase = new SmithyDiffTestCase( - Paths.get("."), - "test", - Collections.singletonList(expected) + Paths.get("."), + "test", + Collections.singletonList(expected) ); SmithyDiffTestCase.Result result = testCase.createResult(Collections.singletonList(actual)); @@ -61,15 +61,15 @@ public void matchesMessageUsingPrefix() { @Test public void failsWhenMessageDoesNotMatchPrefix() { ValidationEvent actual = ValidationEvent.builder() - .id("FooBar") - .severity(Severity.DANGER) - .message("Not a test") - .build(); + .id("FooBar") + .severity(Severity.DANGER) + .message("Not a test") + .build(); ValidationEvent expected = actual.toBuilder().message("This is").build(); SmithyDiffTestCase testCase = new SmithyDiffTestCase( - Paths.get("."), - "test", - Collections.singletonList(expected) + Paths.get("."), + "test", + Collections.singletonList(expected) ); SmithyDiffTestCase.Result result = testCase.createResult(Collections.singletonList(actual)); @@ -79,11 +79,11 @@ public void failsWhenMessageDoesNotMatchPrefix() { @Test public void matchesOnShapeId() { ValidationEvent actual = ValidationEvent.builder() - .id("FooBar") - .severity(Severity.DANGER) - .message("abc") - .shapeId(ShapeId.from("foo.baz#Bar")) - .build(); + .id("FooBar") + .severity(Severity.DANGER) + .message("abc") + .shapeId(ShapeId.from("foo.baz#Bar")) + .build(); SmithyDiffTestCase testCase = new SmithyDiffTestCase(Paths.get("."), "test", Collections.singletonList(actual)); SmithyDiffTestCase.Result result = testCase.createResult(Collections.singletonList(actual)); @@ -93,16 +93,16 @@ public void matchesOnShapeId() { @Test public void failsWhenShapeIdDoesNotMatch() { ValidationEvent actual = ValidationEvent.builder() - .id("FooBar") - .severity(Severity.DANGER) - .message("abc") - .shapeId(ShapeId.from("foo.baz#Bar")) - .build(); + .id("FooBar") + .severity(Severity.DANGER) + .message("abc") + .shapeId(ShapeId.from("foo.baz#Bar")) + .build(); ValidationEvent expected = actual.toBuilder().shapeId(null).build(); SmithyDiffTestCase testCase = new SmithyDiffTestCase( - Paths.get("."), - "test", - Collections.singletonList(expected) + Paths.get("."), + "test", + Collections.singletonList(expected) ); SmithyDiffTestCase.Result result = testCase.createResult(Collections.singletonList(actual)); @@ -112,66 +112,66 @@ public void failsWhenShapeIdDoesNotMatch() { @Test public void multilineEventsPrintedWhenFormatting() { ValidationEvent e1 = ValidationEvent.builder() - .id("FooBar") - .severity(Severity.DANGER) - .message( - "1: first line\n" - + "1: second line\n" - + "1: third line\n" - ) - .shapeId(ShapeId.from("foo.baz#Bar")) - .build(); + .id("FooBar") + .severity(Severity.DANGER) + .message( + "1: first line\n" + + "1: second line\n" + + "1: third line\n" + ) + .shapeId(ShapeId.from("foo.baz#Bar")) + .build(); ValidationEvent e2 = ValidationEvent.builder() - .id("FooBar") - .severity(Severity.DANGER) - .message( - "2: first line\n" - + "2: second line\n" - + "2: third line\n" - ) - .shapeId(ShapeId.from("foo.baz#Bar")) - .build(); + .id("FooBar") + .severity(Severity.DANGER) + .message( + "2: first line\n" + + "2: second line\n" + + "2: third line\n" + ) + .shapeId(ShapeId.from("foo.baz#Bar")) + .build(); SmithyDiffTestCase.Result result = new SmithyDiffTestCase.Result( - "test", - ListUtils.of(e1, e2), - ListUtils.of(e1, e2) + "test", + ListUtils.of(e1, e2), + ListUtils.of(e1, e2) ); assertThat( - result.toString(), - equalTo( - "============================\n" - + "Model Diff Validation Result\n" - + "============================\n" - + "test\n" - + "\n" - + "Did not match the following events\n" - + "----------------------------------\n" - + "[DANGER] foo.baz#Bar: 1: first line\n" - + "1: second line\n" - + "1: third line\n" - + " | FooBar N/A:0:0\n" - + "\n" - + "[DANGER] foo.baz#Bar: 2: first line\n" - + "2: second line\n" - + "2: third line\n" - + " | FooBar N/A:0:0\n" - + "\n" - + "\n" - + "Encountered unexpected events\n" - + "-----------------------------\n" - + "[DANGER] foo.baz#Bar: 1: first line\n" - + "1: second line\n" - + "1: third line\n" - + " | FooBar N/A:0:0\n" - + "\n" - + "[DANGER] foo.baz#Bar: 2: first line\n" - + "2: second line\n" - + "2: third line\n" - + " | FooBar N/A:0:0\n" - + "\n" - ) + result.toString(), + equalTo( + "============================\n" + + "Model Diff Validation Result\n" + + "============================\n" + + "test\n" + + "\n" + + "Did not match the following events\n" + + "----------------------------------\n" + + "[DANGER] foo.baz#Bar: 1: first line\n" + + "1: second line\n" + + "1: third line\n" + + " | FooBar N/A:0:0\n" + + "\n" + + "[DANGER] foo.baz#Bar: 2: first line\n" + + "2: second line\n" + + "2: third line\n" + + " | FooBar N/A:0:0\n" + + "\n" + + "\n" + + "Encountered unexpected events\n" + + "-----------------------------\n" + + "[DANGER] foo.baz#Bar: 1: first line\n" + + "1: second line\n" + + "1: third line\n" + + " | FooBar N/A:0:0\n" + + "\n" + + "[DANGER] foo.baz#Bar: 2: first line\n" + + "2: second line\n" + + "2: third line\n" + + " | FooBar N/A:0:0\n" + + "\n" + ) ); } } diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestSuiteTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestSuiteTest.java index 7ca41e8040f..caa1e13e76d 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestSuiteTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/testrunner/SmithyDiffTestSuiteTest.java @@ -19,8 +19,8 @@ public class SmithyDiffTestSuiteTest { public void throwsWhenFailed() { try { SmithyDiffTestSuite.runner() - .addTestCasesFromUrl(getClass().getResource("testrunner/invalid")) - .run(); + .addTestCasesFromUrl(getClass().getResource("testrunner/invalid")) + .run(); fail("Expected to throw"); } catch (SmithyDiffTestSuite.Error e) { assertThat(e.result.getSuccessCount(), is(1)); @@ -33,8 +33,8 @@ public void throwsWhenFailed() { @Test public void runsCaseWithFile() { SmithyDiffTestSuite.Result result = SmithyDiffTestSuite.runner() - .addTestCasesFromUrl(getClass().getResource("testrunner/valid")) - .run(); + .addTestCasesFromUrl(getClass().getResource("testrunner/valid")) + .run(); assertThat(result.getFailedResults().size(), is(0)); assertThat(result.getSuccessCount(), is(3)); diff --git a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ExpressionProblem.java b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ExpressionProblem.java index 528c6578bba..43a8cde4ce9 100644 --- a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ExpressionProblem.java +++ b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ExpressionProblem.java @@ -58,9 +58,9 @@ public boolean equals(Object o) { } ExpressionProblem problem = (ExpressionProblem) o; return severity == problem.severity - && line == problem.line - && column == problem.column - && message.equals(problem.message); + && line == problem.line + && column == problem.column + && message.equals(problem.message); } @Override diff --git a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ExpressionSerializer.java b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ExpressionSerializer.java index 0c50eb3e5f7..9b9958c9ff4 100644 --- a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ExpressionSerializer.java +++ b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ExpressionSerializer.java @@ -162,8 +162,8 @@ private void visitLiteral(LiteralExpression expression, boolean nestedInsideLite Set> objectEntries = expression.expectObjectValue().entrySet(); for (Map.Entry objectEntry : objectEntries) { builder.append('"') - .append(sanitizeString(objectEntry.getKey(), true)) - .append("\": "); + .append(sanitizeString(objectEntry.getKey(), true)) + .append("\": "); LiteralExpression exp = LiteralExpression.from(objectEntry.getValue()); visitLiteral(exp, true); if (oi++ < objectEntries.size() - 1) { @@ -174,8 +174,8 @@ private void visitLiteral(LiteralExpression expression, boolean nestedInsideLite break; case STRING: builder.append('"') - .append(sanitizeString(expression.expectStringValue(), true)) - .append('"'); + .append(sanitizeString(expression.expectStringValue(), true)) + .append('"'); break; case BOOLEAN: builder.append(expression.expectBooleanValue()); @@ -361,12 +361,12 @@ public Void visitSubexpression(Subexpression expression) { // These expression need to be preceded by a "." in a binary expression. private boolean rhsNeedsDot(JmespathExpression expression) { return expression instanceof FieldExpression - || expression instanceof MultiSelectHashExpression - || expression instanceof MultiSelectListExpression - || expression instanceof ObjectProjectionExpression - || expression instanceof FunctionExpression - || (expression instanceof BinaryExpression - && rhsNeedsDot(((BinaryExpression) expression).getLeft())); + || expression instanceof MultiSelectHashExpression + || expression instanceof MultiSelectListExpression + || expression instanceof ObjectProjectionExpression + || expression instanceof FunctionExpression + || (expression instanceof BinaryExpression + && rhsNeedsDot(((BinaryExpression) expression).getLeft())); } } } diff --git a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/Lexer.java b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/Lexer.java index 43e71d71031..0b62f8ca921 100644 --- a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/Lexer.java +++ b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/Lexer.java @@ -174,8 +174,8 @@ private char expect(char... tokens) { } StringBuilder message = new StringBuilder("Found '") - .append(peekSingleCharForMessage()) - .append("', but expected one of the following tokens:"); + .append(peekSingleCharForMessage()) + .append("', but expected one of the following tokens:"); for (char c : tokens) { message.append(' ').append('\'').append(c).append('\''); } @@ -287,10 +287,10 @@ private Token parseString() { expect('"'); String value = consumeInsideString(); return new Token( - TokenType.IDENTIFIER, - new LiteralExpression(value, currentLine, currentColumn), - currentLine, - currentColumn + TokenType.IDENTIFIER, + new LiteralExpression(value, currentLine, currentColumn), + currentLine, + currentColumn ); } @@ -408,10 +408,10 @@ private Token parseRawStringLiteral() { skip(); String result = builder.toString(); return new Token( - TokenType.LITERAL, - new LiteralExpression(result, currentLine, currentColumn), - currentLine, - currentColumn + TokenType.LITERAL, + new LiteralExpression(result, currentLine, currentColumn), + currentLine, + currentColumn ); } else { builder.append(peek()); diff --git a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/Parser.java b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/Parser.java index 47fb1c6ed9d..a286cdca417 100644 --- a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/Parser.java +++ b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/Parser.java @@ -38,37 +38,37 @@ final class Parser { /** Tokens that can start an expression. */ private static final TokenType[] NUD_TOKENS = { - TokenType.CURRENT, - TokenType.IDENTIFIER, - TokenType.LITERAL, - TokenType.STAR, - TokenType.LBRACE, - TokenType.LBRACKET, - TokenType.FLATTEN, - TokenType.EXPREF, - TokenType.NOT, - TokenType.FILTER, - TokenType.LPAREN + TokenType.CURRENT, + TokenType.IDENTIFIER, + TokenType.LITERAL, + TokenType.STAR, + TokenType.LBRACE, + TokenType.LBRACKET, + TokenType.FLATTEN, + TokenType.EXPREF, + TokenType.NOT, + TokenType.FILTER, + TokenType.LPAREN }; /** Tokens that can follow led tokens. */ private static final TokenType[] LED_TOKENS = { - TokenType.DOT, - TokenType.LBRACKET, - TokenType.OR, - TokenType.AND, - TokenType.PIPE, - TokenType.FLATTEN, - TokenType.FILTER, - TokenType.EQUAL, - TokenType.NOT_EQUAL, - TokenType.GREATER_THAN, - TokenType.GREATER_THAN_EQUAL, - TokenType.LESS_THAN, - TokenType.LESS_THAN_EQUAL, - // While not found in the led() method, a led LPAREN is handled - // when parsing a nud identifier because it creates a function. - TokenType.LPAREN + TokenType.DOT, + TokenType.LBRACKET, + TokenType.OR, + TokenType.AND, + TokenType.PIPE, + TokenType.FLATTEN, + TokenType.FILTER, + TokenType.EQUAL, + TokenType.NOT_EQUAL, + TokenType.GREATER_THAN, + TokenType.GREATER_THAN_EQUAL, + TokenType.LESS_THAN, + TokenType.LESS_THAN_EQUAL, + // While not found in the led() method, a led LPAREN is handled + // when parsing a nud identifier because it creates a function. + TokenType.LPAREN }; private final String expression; @@ -361,10 +361,10 @@ private JmespathExpression parseComparator(ComparatorType comparatorType, Jmespa // Parses the right hand side of a ".". private JmespathExpression parseDotRhs(int lbp) { Token token = iterator.expectPeek( - TokenType.LBRACKET, - TokenType.LBRACE, - TokenType.STAR, - TokenType.IDENTIFIER + TokenType.LBRACKET, + TokenType.LBRACE, + TokenType.STAR, + TokenType.IDENTIFIER ); if (token.type == TokenType.LBRACKET) { @@ -387,11 +387,11 @@ private JmespathExpression parseFilter(JmespathExpression left) { iterator.expect(TokenType.RBRACKET); JmespathExpression conditionRhs = parseProjectionRhs(TokenType.FILTER.lbp); return new FilterProjectionExpression( - left, - condition, - conditionRhs, - condition.getLine(), - condition.getColumn() + left, + condition, + conditionRhs, + condition.getLine(), + condition.getColumn() ); } } diff --git a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/RuntimeType.java b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/RuntimeType.java index f5365104129..d57a3e8ec02 100644 --- a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/RuntimeType.java +++ b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/RuntimeType.java @@ -146,8 +146,8 @@ public String toString() { } public abstract LiteralExpression compare( - LiteralExpression left, - LiteralExpression right, - ComparatorType comparator + LiteralExpression left, + LiteralExpression right, + ComparatorType comparator ); } diff --git a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/TokenIterator.java b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/TokenIterator.java index ed090b582ec..c8035bf0a3f 100644 --- a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/TokenIterator.java +++ b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/TokenIterator.java @@ -38,8 +38,8 @@ Token peek() { Token peek(int offset) { return position + offset < tokens.size() - ? tokens.get(position + offset) - : null; + ? tokens.get(position + offset) + : null; } Token expectNotEof() { diff --git a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/TypeChecker.java b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/TypeChecker.java index 7685fa347fd..bca9b2f175a 100644 --- a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/TypeChecker.java +++ b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/TypeChecker.java @@ -56,12 +56,12 @@ final class TypeChecker implements ExpressionVisitor { FUNCTIONS.put("abs", new FunctionDefinition(NUMBER, isNumber)); FUNCTIONS.put("avg", new FunctionDefinition(NUMBER, listOfType(RuntimeType.NUMBER))); FUNCTIONS.put( - "contains", - new FunctionDefinition( - BOOLEAN, - oneOf(RuntimeType.ARRAY, RuntimeType.STRING), - isAny - ) + "contains", + new FunctionDefinition( + BOOLEAN, + oneOf(RuntimeType.ARRAY, RuntimeType.STRING), + isAny + ) ); FUNCTIONS.put("ceil", new FunctionDefinition(NUMBER, isNumber)); FUNCTIONS.put("ends_with", new FunctionDefinition(NUMBER, isString, isString)); @@ -69,11 +69,11 @@ final class TypeChecker implements ExpressionVisitor { FUNCTIONS.put("join", new FunctionDefinition(STRING, isString, listOfType(RuntimeType.STRING))); FUNCTIONS.put("keys", new FunctionDefinition(ARRAY, isType(RuntimeType.OBJECT))); FUNCTIONS.put( - "length", - new FunctionDefinition( - NUMBER, - oneOf(RuntimeType.STRING, RuntimeType.ARRAY, RuntimeType.OBJECT) - ) + "length", + new FunctionDefinition( + NUMBER, + oneOf(RuntimeType.STRING, RuntimeType.ARRAY, RuntimeType.OBJECT) + ) ); // TODO: Support expression reference return type validation? FUNCTIONS.put("map", new FunctionDefinition(ARRAY, isType(RuntimeType.EXPRESSION), isArray)); @@ -163,12 +163,12 @@ public LiteralExpression visitField(FieldExpression expression) { return current.getObjectField(expression.getName()); } else { danger( - expression, - String.format( - "Object field '%s' does not exist in object with properties %s", - expression.getName(), - current.expectObjectValue().keySet() - ) + expression, + String.format( + "Object field '%s' does not exist in object with properties %s", + expression.getName(), + current.expectObjectValue().keySet() + ) ); return NULL; } @@ -176,12 +176,12 @@ public LiteralExpression visitField(FieldExpression expression) { if (current.getType() != RuntimeType.ANY) { danger( - expression, - String.format( - "Object field '%s' extraction performed on %s", - expression.getName(), - current.getType() - ) + expression, + String.format( + "Object field '%s' extraction performed on %s", + expression.getName(), + current.getType() + ) ); } @@ -196,12 +196,12 @@ public LiteralExpression visitIndex(IndexExpression expression) { if (current.getType() != RuntimeType.ANY) { danger( - expression, - String.format( - "Array index '%s' extraction performed on %s", - expression.getIndex(), - current.getType() - ) + expression, + String.format( + "Array index '%s' extraction performed on %s", + expression.getIndex(), + current.getType() + ) ); } @@ -377,11 +377,11 @@ public LiteralExpression visitFunction(FunctionExpression expression) { // Positional argument arity must match. if (arguments.size() < def.arguments.size() - || (def.variadic == null && arguments.size() > def.arguments.size())) { + || (def.variadic == null && arguments.size() > def.arguments.size())) { err( - expression, - expression.getName() + " function expected " + def.arguments.size() - + " arguments, but was given " + arguments.size() + expression, + expression.getName() + " function expected " + def.arguments.size() + + " arguments, but was given " + arguments.size() ); } else { for (int i = 0; i < arguments.size(); i++) { @@ -393,8 +393,8 @@ public LiteralExpression visitFunction(FunctionExpression expression) { } if (error != null) { err( - expression.getArguments().get(i), - expression.getName() + " function argument " + i + " error: " + error + expression.getArguments().get(i), + expression.getName() + " function argument " + i + " error: " + error ); } } diff --git a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/ComparatorExpression.java b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/ComparatorExpression.java index f6b60cf8aa7..98239749f7b 100644 --- a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/ComparatorExpression.java +++ b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/ComparatorExpression.java @@ -23,11 +23,11 @@ public ComparatorExpression(ComparatorType comparator, JmespathExpression left, } public ComparatorExpression( - ComparatorType comparator, - JmespathExpression left, - JmespathExpression right, - int line, - int column + ComparatorType comparator, + JmespathExpression left, + JmespathExpression right, + int line, + int column ) { super(left, right, line, column); this.comparator = comparator; @@ -56,8 +56,8 @@ public boolean equals(Object o) { } ComparatorExpression that = (ComparatorExpression) o; return getLeft().equals(that.getLeft()) - && getRight().equals(that.getRight()) - && getComparator().equals(that.getComparator()); + && getRight().equals(that.getRight()) + && getComparator().equals(that.getComparator()); } @Override @@ -68,7 +68,7 @@ public int hashCode() { @Override public String toString() { return "ComparatorExpression{comparator='" + getComparator() + '\'' - + ", left=" + getLeft() - + ", right=" + getRight() + '}'; + + ", left=" + getLeft() + + ", right=" + getRight() + '}'; } } diff --git a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/FilterProjectionExpression.java b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/FilterProjectionExpression.java index dad146acc22..964271c35c4 100644 --- a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/FilterProjectionExpression.java +++ b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/FilterProjectionExpression.java @@ -27,19 +27,19 @@ public final class FilterProjectionExpression extends BinaryExpression { private final JmespathExpression comparison; public FilterProjectionExpression( - JmespathExpression left, - JmespathExpression comparison, - JmespathExpression right + JmespathExpression left, + JmespathExpression comparison, + JmespathExpression right ) { this(left, comparison, right, 1, 1); } public FilterProjectionExpression( - JmespathExpression left, - JmespathExpression comparison, - JmespathExpression right, - int line, - int column + JmespathExpression left, + JmespathExpression comparison, + JmespathExpression right, + int line, + int column ) { super(left, right, line, column); this.comparison = comparison; @@ -63,8 +63,8 @@ public boolean equals(Object o) { } FilterProjectionExpression that = (FilterProjectionExpression) o; return getComparison().equals(that.getComparison()) - && getLeft().equals(that.getLeft()) - && getRight().equals(that.getRight()); + && getLeft().equals(that.getLeft()) + && getRight().equals(that.getRight()); } @Override @@ -75,8 +75,8 @@ public int hashCode() { @Override public String toString() { return "FilterProjectionExpression{" - + "comparison=" + comparison - + ", left=" + getLeft() - + ", right=" + getRight() + '}'; + + "comparison=" + comparison + + ", left=" + getLeft() + + ", right=" + getRight() + '}'; } } diff --git a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/LiteralExpression.java b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/LiteralExpression.java index 0466295011d..dfa2fcc63b3 100644 --- a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/LiteralExpression.java +++ b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/LiteralExpression.java @@ -152,8 +152,8 @@ public RuntimeType getType() { public LiteralExpression getObjectField(String name) { Map values = expectObjectValue(); return values.containsKey(name) - ? new LiteralExpression(values.get(name)) - : new LiteralExpression(null); + ? new LiteralExpression(values.get(name)) + : new LiteralExpression(null); } /** @@ -184,8 +184,8 @@ public LiteralExpression getArrayIndex(int index) { } return index >= 0 && values.size() > index - ? new LiteralExpression(values.get(index)) - : new LiteralExpression(null); + ? new LiteralExpression(values.get(index)) + : new LiteralExpression(null); } /** diff --git a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/SliceExpression.java b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/SliceExpression.java index 5a97a0db1b0..6e045dd94fd 100644 --- a/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/SliceExpression.java +++ b/smithy-jmespath/src/main/java/software/amazon/smithy/jmespath/ast/SliceExpression.java @@ -58,8 +58,8 @@ public boolean equals(Object o) { } SliceExpression sliceNode = (SliceExpression) o; return Objects.equals(getStart(), sliceNode.getStart()) - && Objects.equals(getStop(), sliceNode.getStop()) - && getStep() == sliceNode.getStep(); + && Objects.equals(getStop(), sliceNode.getStop()) + && getStep() == sliceNode.getStep(); } @Override diff --git a/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/ExpressionSerializerTest.java b/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/ExpressionSerializerTest.java index a08329360f9..d623054562a 100644 --- a/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/ExpressionSerializerTest.java +++ b/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/ExpressionSerializerTest.java @@ -32,73 +32,73 @@ public void serializesExpressions(String expressionString, String expectedString public static Collection shapeSource() { return Arrays.asList( - new Object[][]{ - // Current node - {"@", "@"}, - - // Identifiers - {"foo", "\"foo\""}, - {"\"a\\\"b\"", "\"a\\\"b\""}, - {"\"a\\\\b\"", "\"a\\\\b\""}, - - // Array index - {"[0]", "[0]"}, - {"[10]", "[10]"}, - - // Array slices - {"[0:]", "[0::1]"}, // projection that contains the slice - {"[0:].foo", "[0::1].\"foo\""}, - - // Subexpressions - {"foo | bar", "\"foo\" | \"bar\""}, - {"foo.bar", "\"foo\".\"bar\""}, - {"foo.bar.baz", "\"foo\".\"bar\".\"baz\""}, - {"foo | bar | baz", "\"foo\" | \"bar\" | \"baz\""}, - {"foo | bar | baz | \"a.b\"", "\"foo\" | \"bar\" | \"baz\" | \"a.b\""}, - - // Object projections - {"*", "*"}, - {"foo.*", "\"foo\".*"}, - {"foo.* | @", "\"foo\".* | @"}, - {"foo.*.bar", "\"foo\".*.\"bar\""}, - {"foo.*.bar | bam", "\"foo\".*.\"bar\" | \"bam\""}, - - // Array projections / flatten - {"[]", "@[]"}, - {"foo[]", "\"foo\"[]"}, - {"foo[].bar", "\"foo\"[].\"bar\""}, - {"foo[] | bar", "\"foo\"[] | \"bar\""}, - - // Not - {"!@", "!(@)"}, - {"!foo.bar", "!(\"foo\").\"bar\""}, // this expression in nonsensical, but valid. - - // And - {"@ && @", "(@ && @)"}, - {"foo.bar && foo.baz", "(\"foo\".\"bar\" && \"foo\".\"baz\")"}, - - // Or - {"@ || @", "(@ || @)"}, - {"foo.bar || foo.baz", "(\"foo\".\"bar\" || \"foo\".\"baz\")"}, - - // functions - {"length(@)", "length(@)"}, - {"ends_with(@, @)", "ends_with(@, @)"}, - {"min_by(@, &foo)", "min_by(@, &(\"foo\"))"}, - - // comparator - {"@ == @", "@ == @"}, - - // multi-select list - {"[@]", "[@]"}, - {"[@, @]", "[@, @]"}, - - // multi-select hash - {"{foo: foo, bar: bar}", "{\"foo\": \"foo\", \"bar\": \"bar\"}"}, - - // Filter expressions. - {"foo[?bar > baz][?qux > baz]", "\"foo\"[?\"bar\" > \"baz\"][?\"qux\" > \"baz\"]"} - } + new Object[][]{ + // Current node + {"@", "@"}, + + // Identifiers + {"foo", "\"foo\""}, + {"\"a\\\"b\"", "\"a\\\"b\""}, + {"\"a\\\\b\"", "\"a\\\\b\""}, + + // Array index + {"[0]", "[0]"}, + {"[10]", "[10]"}, + + // Array slices + {"[0:]", "[0::1]"}, // projection that contains the slice + {"[0:].foo", "[0::1].\"foo\""}, + + // Subexpressions + {"foo | bar", "\"foo\" | \"bar\""}, + {"foo.bar", "\"foo\".\"bar\""}, + {"foo.bar.baz", "\"foo\".\"bar\".\"baz\""}, + {"foo | bar | baz", "\"foo\" | \"bar\" | \"baz\""}, + {"foo | bar | baz | \"a.b\"", "\"foo\" | \"bar\" | \"baz\" | \"a.b\""}, + + // Object projections + {"*", "*"}, + {"foo.*", "\"foo\".*"}, + {"foo.* | @", "\"foo\".* | @"}, + {"foo.*.bar", "\"foo\".*.\"bar\""}, + {"foo.*.bar | bam", "\"foo\".*.\"bar\" | \"bam\""}, + + // Array projections / flatten + {"[]", "@[]"}, + {"foo[]", "\"foo\"[]"}, + {"foo[].bar", "\"foo\"[].\"bar\""}, + {"foo[] | bar", "\"foo\"[] | \"bar\""}, + + // Not + {"!@", "!(@)"}, + {"!foo.bar", "!(\"foo\").\"bar\""}, // this expression in nonsensical, but valid. + + // And + {"@ && @", "(@ && @)"}, + {"foo.bar && foo.baz", "(\"foo\".\"bar\" && \"foo\".\"baz\")"}, + + // Or + {"@ || @", "(@ || @)"}, + {"foo.bar || foo.baz", "(\"foo\".\"bar\" || \"foo\".\"baz\")"}, + + // functions + {"length(@)", "length(@)"}, + {"ends_with(@, @)", "ends_with(@, @)"}, + {"min_by(@, &foo)", "min_by(@, &(\"foo\"))"}, + + // comparator + {"@ == @", "@ == @"}, + + // multi-select list + {"[@]", "[@]"}, + {"[@, @]", "[@, @]"}, + + // multi-select hash + {"{foo: foo, bar: bar}", "{\"foo\": \"foo\", \"bar\": \"bar\"}"}, + + // Filter expressions. + {"foo[?bar > baz][?qux > baz]", "\"foo\"[?\"bar\" > \"baz\"][?\"qux\" > \"baz\"]"} + } ); } @@ -124,6 +124,6 @@ public void canSerializeEveryValidExpressionFromFile(String line) { // The serialized string my be different, but the AST must be the same. public static Stream validExpressions() { return new NewLineExpressionsDataSource().validTests() - .map(line -> new Object[]{line}); + .map(line -> new Object[]{line}); } } diff --git a/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/NewLineExpressionsDataSource.java b/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/NewLineExpressionsDataSource.java index 50fc61cad35..4916e76bec0 100644 --- a/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/NewLineExpressionsDataSource.java +++ b/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/NewLineExpressionsDataSource.java @@ -22,14 +22,14 @@ public Stream invalidTests() { private Stream readFile(InputStream stream) { return new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)) - .lines() - .map(line -> { - if (line.endsWith(",")) { - return line.substring(0, line.length() - 1); - } else { - return line; - } - }) - .map(line -> Lexer.tokenize(line).next().value.expectStringValue()); + .lines() + .map(line -> { + if (line.endsWith(",")) { + return line.substring(0, line.length() - 1); + } else { + return line; + } + }) + .map(line -> Lexer.tokenize(line).next().value.expectStringValue()); } } diff --git a/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/ParserTest.java b/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/ParserTest.java index 27e871940a7..65e229b824d 100644 --- a/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/ParserTest.java +++ b/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/ParserTest.java @@ -38,8 +38,8 @@ public class ParserTest { @Test public void throwsOnInvalidNudToken() { JmespathException e = Assertions.assertThrows( - JmespathException.class, - () -> JmespathExpression.parse("|| a") + JmespathException.class, + () -> JmespathExpression.parse("|| a") ); assertThat(e.getMessage(), containsString("but found '||'")); @@ -53,34 +53,34 @@ public void parsesNudField() { @Test public void parsesFunctionExpression() { assertThat( - JmespathExpression.parse("length(@)"), - equalTo( - new FunctionExpression("length", Collections.singletonList(new CurrentExpression())) - ) + JmespathExpression.parse("length(@)"), + equalTo( + new FunctionExpression("length", Collections.singletonList(new CurrentExpression())) + ) ); } @Test public void parsesFunctionWithMultipleArguments() { assertThat( - JmespathExpression.parse("starts_with(@, 'foo')"), - equalTo( - new FunctionExpression( - "starts_with", - Arrays.asList( - new CurrentExpression(), - new LiteralExpression("foo") - ) + JmespathExpression.parse("starts_with(@, 'foo')"), + equalTo( + new FunctionExpression( + "starts_with", + Arrays.asList( + new CurrentExpression(), + new LiteralExpression("foo") + ) + ) ) - ) ); } @Test public void detectsIllegalTrailingCommaInFunctionExpression() { JmespathException e = Assertions.assertThrows( - JmespathException.class, - () -> JmespathExpression.parse("lenght(@,)") + JmespathException.class, + () -> JmespathExpression.parse("lenght(@,)") ); assertThat(e.getMessage(), containsString("Invalid token after ',': ')'")); @@ -89,26 +89,26 @@ public void detectsIllegalTrailingCommaInFunctionExpression() { @Test public void parsesNudWildcardIndex() { assertThat( - JmespathExpression.parse("[*]"), - equalTo( - new ProjectionExpression( - new CurrentExpression(), - new CurrentExpression() + JmespathExpression.parse("[*]"), + equalTo( + new ProjectionExpression( + new CurrentExpression(), + new CurrentExpression() + ) ) - ) ); } @Test public void parsesNudStar() { assertThat( - JmespathExpression.parse("*"), - equalTo( - new ObjectProjectionExpression( - new CurrentExpression(), - new CurrentExpression() + JmespathExpression.parse("*"), + equalTo( + new ObjectProjectionExpression( + new CurrentExpression(), + new CurrentExpression() + ) ) - ) ); } @@ -130,36 +130,36 @@ public void parsesNudIndex() { @Test public void parsesNudFlatten() { assertThat( - JmespathExpression.parse("[].foo"), - equalTo( - new ProjectionExpression( - new FlattenExpression(new CurrentExpression()), - new FieldExpression("foo") + JmespathExpression.parse("[].foo"), + equalTo( + new ProjectionExpression( + new FlattenExpression(new CurrentExpression()), + new FieldExpression("foo") + ) ) - ) ); } @Test public void parsesNudMultiSelectList() { assertThat( - JmespathExpression.parse("[foo, bar]"), - equalTo( - new MultiSelectListExpression( - Arrays.asList( - new FieldExpression("foo"), - new FieldExpression("bar") - ) + JmespathExpression.parse("[foo, bar]"), + equalTo( + new MultiSelectListExpression( + Arrays.asList( + new FieldExpression("foo"), + new FieldExpression("bar") + ) + ) ) - ) ); } @Test public void detectsIllegalTrailingCommaInNudMultiSelectList() { JmespathException e = Assertions.assertThrows( - JmespathException.class, - () -> JmespathExpression.parse("[foo,]") + JmespathException.class, + () -> JmespathExpression.parse("[foo,]") ); assertThat(e.getMessage(), containsString("Invalid token after ',': ']'")); @@ -172,58 +172,58 @@ public void parsesNudMultiSelectHash() { expressionMap.put("baz", new Subexpression(new FieldExpression("bam"), new FieldExpression("boo"))); assertThat( - JmespathExpression.parse("{foo: bar, baz: bam.boo}"), - equalTo( - new MultiSelectHashExpression(expressionMap) - ) + JmespathExpression.parse("{foo: bar, baz: bam.boo}"), + equalTo( + new MultiSelectHashExpression(expressionMap) + ) ); } @Test public void parsesNudAmpersand() { assertThat( - JmespathExpression.parse("&foo[1]"), - equalTo( - new ExpressionTypeExpression( - new Subexpression( - new FieldExpression("foo"), - new IndexExpression(1) - ) + JmespathExpression.parse("&foo[1]"), + equalTo( + new ExpressionTypeExpression( + new Subexpression( + new FieldExpression("foo"), + new IndexExpression(1) + ) + ) ) - ) ); } @Test public void parsesNudNot() { assertThat( - JmespathExpression.parse("!foo[1]"), - equalTo( - new NotExpression( - new Subexpression( - new FieldExpression("foo"), - new IndexExpression(1) - ) + JmespathExpression.parse("!foo[1]"), + equalTo( + new NotExpression( + new Subexpression( + new FieldExpression("foo"), + new IndexExpression(1) + ) + ) ) - ) ); } @Test public void parsesNudFilter() { assertThat( - JmespathExpression.parse("[?foo == `true`]"), - equalTo( - new FilterProjectionExpression( - new CurrentExpression(), - new ComparatorExpression( - ComparatorType.EQUAL, - new FieldExpression("foo"), - new LiteralExpression(true) - ), - new CurrentExpression() + JmespathExpression.parse("[?foo == `true`]"), + equalTo( + new FilterProjectionExpression( + new CurrentExpression(), + new ComparatorExpression( + ComparatorType.EQUAL, + new FieldExpression("foo"), + new LiteralExpression(true) + ), + new CurrentExpression() + ) ) - ) ); } @@ -231,18 +231,18 @@ public void parsesNudFilter() { public void parsesNudFilterWithComparators() { for (ComparatorType type : ComparatorType.values()) { assertThat( - JmespathExpression.parse("[?foo " + type + " `true`]"), - equalTo( - new FilterProjectionExpression( - new CurrentExpression(), - new ComparatorExpression( - type, - new FieldExpression("foo"), - new LiteralExpression(true) - ), - new CurrentExpression() + JmespathExpression.parse("[?foo " + type + " `true`]"), + equalTo( + new FilterProjectionExpression( + new CurrentExpression(), + new ComparatorExpression( + type, + new FieldExpression("foo"), + new LiteralExpression(true) + ), + new CurrentExpression() + ) ) - ) ); } } @@ -250,77 +250,77 @@ public void parsesNudFilterWithComparators() { @Test public void parsesNudLparen() { assertThat( - JmespathExpression.parse("(foo | bar)"), - equalTo( - new Subexpression( - new FieldExpression("foo"), - new FieldExpression("bar") + JmespathExpression.parse("(foo | bar)"), + equalTo( + new Subexpression( + new FieldExpression("foo"), + new FieldExpression("bar") + ) ) - ) ); } @Test public void parsesSubexpressions() { assertThat( - JmespathExpression.parse("foo.bar.baz"), - equalTo( - new Subexpression( - new Subexpression( - new FieldExpression("foo"), - new FieldExpression("bar") - ), - new FieldExpression("baz") + JmespathExpression.parse("foo.bar.baz"), + equalTo( + new Subexpression( + new Subexpression( + new FieldExpression("foo"), + new FieldExpression("bar") + ), + new FieldExpression("baz") + ) ) - ) ); } @Test public void parsesSubexpressionsWithQuotedIdentifier() { assertThat( - JmespathExpression.parse("foo.\"1\""), - equalTo( - new Subexpression(new FieldExpression("foo"), new FieldExpression("1")) - ) + JmespathExpression.parse("foo.\"1\""), + equalTo( + new Subexpression(new FieldExpression("foo"), new FieldExpression("1")) + ) ); } @Test public void parsesMultiSelectHashAfterDot() { assertThat( - JmespathExpression.parse("foo.{bar: baz}"), - equalTo( - new Subexpression( - new FieldExpression("foo"), - new MultiSelectHashExpression( - Collections.singletonMap("bar", new FieldExpression("baz")) - ) + JmespathExpression.parse("foo.{bar: baz}"), + equalTo( + new Subexpression( + new FieldExpression("foo"), + new MultiSelectHashExpression( + Collections.singletonMap("bar", new FieldExpression("baz")) + ) + ) ) - ) ); } @Test public void parsesMultiSelectListAfterDot() { assertThat( - JmespathExpression.parse("foo.[bar]"), - equalTo( - new Subexpression( - new FieldExpression("foo"), - new MultiSelectListExpression( - Collections.singletonList(new FieldExpression("bar")) - ) + JmespathExpression.parse("foo.[bar]"), + equalTo( + new Subexpression( + new FieldExpression("foo"), + new MultiSelectListExpression( + Collections.singletonList(new FieldExpression("bar")) + ) + ) ) - ) ); } @Test public void requiresExpressionToFollowDot() { JmespathException e = Assertions.assertThrows( - JmespathException.class, - () -> JmespathExpression.parse("foo.") + JmespathException.class, + () -> JmespathExpression.parse("foo.") ); assertThat(e.getMessage(), containsString("but found EOF")); @@ -329,143 +329,143 @@ public void requiresExpressionToFollowDot() { @Test public void parsesPipeExpressions() { assertThat( - JmespathExpression.parse("foo.bar.baz"), - equalTo( - new Subexpression( - new Subexpression( - new FieldExpression("foo"), - new FieldExpression("bar") - ), - new FieldExpression("baz") + JmespathExpression.parse("foo.bar.baz"), + equalTo( + new Subexpression( + new Subexpression( + new FieldExpression("foo"), + new FieldExpression("bar") + ), + new FieldExpression("baz") + ) ) - ) ); } @Test public void parsesOrExpressions() { assertThat( - JmespathExpression.parse("foo || bar || baz"), - equalTo( - new OrExpression( - new OrExpression( - new FieldExpression("foo"), - new FieldExpression("bar") - ), - new FieldExpression("baz") + JmespathExpression.parse("foo || bar || baz"), + equalTo( + new OrExpression( + new OrExpression( + new FieldExpression("foo"), + new FieldExpression("bar") + ), + new FieldExpression("baz") + ) ) - ) ); } @Test public void parsesAndExpressions() { assertThat( - JmespathExpression.parse("foo && bar && baz"), - equalTo( - new AndExpression( - new AndExpression( - new FieldExpression("foo"), - new FieldExpression("bar") - ), - new FieldExpression("baz") + JmespathExpression.parse("foo && bar && baz"), + equalTo( + new AndExpression( + new AndExpression( + new FieldExpression("foo"), + new FieldExpression("bar") + ), + new FieldExpression("baz") + ) ) - ) ); } @Test public void parsesProjections() { assertThat( - JmespathExpression.parse("foo.*.bar[*] || baz"), - equalTo( - new OrExpression( - new ObjectProjectionExpression( - new FieldExpression("foo"), - new ProjectionExpression( - new FieldExpression("bar"), - new CurrentExpression() + JmespathExpression.parse("foo.*.bar[*] || baz"), + equalTo( + new OrExpression( + new ObjectProjectionExpression( + new FieldExpression("foo"), + new ProjectionExpression( + new FieldExpression("bar"), + new CurrentExpression() + ) + ), + new FieldExpression("baz") ) - ), - new FieldExpression("baz") ) - ) ); } @Test public void parsesLedFlattenProjection() { assertThat( - JmespathExpression.parse("a[].b"), - equalTo( - new ProjectionExpression( - new FlattenExpression(new FieldExpression("a")), - new FieldExpression("b") + JmespathExpression.parse("a[].b"), + equalTo( + new ProjectionExpression( + new FlattenExpression(new FieldExpression("a")), + new FieldExpression("b") + ) ) - ) ); } @Test public void parsesLedFilterProjection() { assertThat( - JmespathExpression.parse("a[?b > c].d"), - equalTo( - new FilterProjectionExpression( - new FieldExpression("a"), - new ComparatorExpression( - ComparatorType.GREATER_THAN, - new FieldExpression("b"), - new FieldExpression("c") - ), - new FieldExpression("d") + JmespathExpression.parse("a[?b > c].d"), + equalTo( + new FilterProjectionExpression( + new FieldExpression("a"), + new ComparatorExpression( + ComparatorType.GREATER_THAN, + new FieldExpression("b"), + new FieldExpression("c") + ), + new FieldExpression("d") + ) ) - ) ); } @Test public void parsesLedProjectionIntoIndex() { assertThat( - JmespathExpression.parse("a.*[1].b"), - equalTo( - new ObjectProjectionExpression( - new FieldExpression("a"), - new Subexpression( - new IndexExpression(1), - new FieldExpression("b") - ) + JmespathExpression.parse("a.*[1].b"), + equalTo( + new ObjectProjectionExpression( + new FieldExpression("a"), + new Subexpression( + new IndexExpression(1), + new FieldExpression("b") + ) + ) ) - ) ); } @Test public void parsesLedProjectionIntoFilterProjection() { assertThat( - JmespathExpression.parse("a.*[?foo == bar]"), - equalTo( - new ObjectProjectionExpression( - new FieldExpression("a"), - new FilterProjectionExpression( - new CurrentExpression(), - new ComparatorExpression( - ComparatorType.EQUAL, - new FieldExpression("foo"), - new FieldExpression("bar") - ), - new CurrentExpression() - ) + JmespathExpression.parse("a.*[?foo == bar]"), + equalTo( + new ObjectProjectionExpression( + new FieldExpression("a"), + new FilterProjectionExpression( + new CurrentExpression(), + new ComparatorExpression( + ComparatorType.EQUAL, + new FieldExpression("foo"), + new FieldExpression("bar") + ), + new CurrentExpression() + ) + ) ) - ) ); } @Test public void validatesValidLedProjectionRhs() { JmespathException e = Assertions.assertThrows( - JmespathException.class, - () -> JmespathExpression.parse("a.**") + JmespathException.class, + () -> JmespathExpression.parse("a.**") ); assertThat(e.getMessage(), containsString("Invalid projection")); @@ -474,75 +474,75 @@ public void validatesValidLedProjectionRhs() { @Test public void parsesSlices() { assertThat( - JmespathExpression.parse("[1:3].foo"), - equalTo( - new ProjectionExpression( - new SliceExpression(1, 3, 1), - new FieldExpression("foo") + JmespathExpression.parse("[1:3].foo"), + equalTo( + new ProjectionExpression( + new SliceExpression(1, 3, 1), + new FieldExpression("foo") + ) ) - ) ); } @Test public void parsesSlicesWithStep() { assertThat( - JmespathExpression.parse("[5:10:2]"), - equalTo( - new ProjectionExpression( - new SliceExpression(5, 10, 2), - new CurrentExpression() + JmespathExpression.parse("[5:10:2]"), + equalTo( + new ProjectionExpression( + new SliceExpression(5, 10, 2), + new CurrentExpression() + ) ) - ) ); } @Test public void parsesSlicesWithNegativeStep() { assertThat( - JmespathExpression.parse("[10:5:-1]"), - equalTo( - new ProjectionExpression( - new SliceExpression(10, 5, -1), - new CurrentExpression() + JmespathExpression.parse("[10:5:-1]"), + equalTo( + new ProjectionExpression( + new SliceExpression(10, 5, -1), + new CurrentExpression() + ) ) - ) ); } @Test public void parsesSlicesWithStepAndNoStop() { assertThat( - JmespathExpression.parse("[10::5]"), - equalTo( - new ProjectionExpression( - new SliceExpression(10, null, 5), - new CurrentExpression() + JmespathExpression.parse("[10::5]"), + equalTo( + new ProjectionExpression( + new SliceExpression(10, null, 5), + new CurrentExpression() + ) ) - ) ); } @Test public void parsesSlicesWithStartAndNoStepOrEnd() { assertThat( - JmespathExpression.parse("[10::]"), - equalTo( - new ProjectionExpression( - new SliceExpression(10, null, 1), - new CurrentExpression() + JmespathExpression.parse("[10::]"), + equalTo( + new ProjectionExpression( + new SliceExpression(10, null, 1), + new CurrentExpression() + ) ) - ) ); assertThat( - JmespathExpression.parse("[10:]"), - equalTo( - new ProjectionExpression( - new SliceExpression(10, null, 1), - new CurrentExpression() + JmespathExpression.parse("[10:]"), + equalTo( + new ProjectionExpression( + new SliceExpression(10, null, 1), + new CurrentExpression() + ) ) - ) ); } diff --git a/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/TokenIteratorTest.java b/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/TokenIteratorTest.java index 4a9b7b27264..ec0b4cf2d69 100644 --- a/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/TokenIteratorTest.java +++ b/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/TokenIteratorTest.java @@ -20,9 +20,9 @@ public class TokenIteratorTest { @Test public void peeksAndIterates() { List tokens = Arrays.asList( - new Token(TokenType.DOT, null, 1, 1), - new Token(TokenType.STAR, null, 1, 2), - new Token(TokenType.FLATTEN, null, 1, 3) + new Token(TokenType.DOT, null, 1, 1), + new Token(TokenType.STAR, null, 1, 2), + new Token(TokenType.FLATTEN, null, 1, 3) ); TokenIterator iterator = new TokenIterator(tokens); @@ -51,9 +51,9 @@ public void throwsWhenNoMoreTokens() { @Test public void peeksAhead() { List tokens = Arrays.asList( - new Token(TokenType.DOT, null, 1, 1), - new Token(TokenType.STAR, null, 1, 2), - new Token(TokenType.FLATTEN, null, 1, 3) + new Token(TokenType.DOT, null, 1, 1), + new Token(TokenType.STAR, null, 1, 2), + new Token(TokenType.FLATTEN, null, 1, 3) ); TokenIterator iterator = new TokenIterator(tokens); @@ -66,9 +66,9 @@ public void peeksAhead() { @Test public void expectsTokensWithValidResults() { List tokens = Arrays.asList( - new Token(TokenType.DOT, null, 1, 1), - new Token(TokenType.STAR, null, 1, 2), - new Token(TokenType.FLATTEN, null, 1, 3) + new Token(TokenType.DOT, null, 1, 1), + new Token(TokenType.STAR, null, 1, 2), + new Token(TokenType.FLATTEN, null, 1, 3) ); TokenIterator iterator = new TokenIterator(tokens); @@ -81,13 +81,13 @@ public void expectsTokensWithValidResults() { public void expectsTokensWithInvalidResultBecauseEmpty() { TokenIterator iterator = new TokenIterator(Collections.emptyList()); JmespathException e = Assertions.assertThrows( - JmespathException.class, - () -> iterator.expect(TokenType.DOT) + JmespathException.class, + () -> iterator.expect(TokenType.DOT) ); assertThat( - e.getMessage(), - equalTo("Syntax error at line 1 column 1: Expected '.', but found EOF") + e.getMessage(), + equalTo("Syntax error at line 1 column 1: Expected '.', but found EOF") ); } @@ -95,13 +95,13 @@ public void expectsTokensWithInvalidResultBecauseEmpty() { public void expectsOneOrMoreTokensWithInvalidResultBecauseEmpty() { TokenIterator iterator = new TokenIterator(Collections.emptyList()); JmespathException e = Assertions.assertThrows( - JmespathException.class, - () -> iterator.expect(TokenType.DOT, TokenType.EXPREF) + JmespathException.class, + () -> iterator.expect(TokenType.DOT, TokenType.EXPREF) ); assertThat( - e.getMessage(), - equalTo("Syntax error at line 1 column 1: Expected ['.', '&'], but found EOF") + e.getMessage(), + equalTo("Syntax error at line 1 column 1: Expected ['.', '&'], but found EOF") ); } @@ -111,13 +111,13 @@ public void expectsTokensWithInvalidResultBecauseEof() { TokenIterator iterator = new TokenIterator(tokens); iterator.next(); JmespathException e = Assertions.assertThrows( - JmespathException.class, - () -> iterator.expect(TokenType.DOT) + JmespathException.class, + () -> iterator.expect(TokenType.DOT) ); assertThat( - e.getMessage(), - equalTo("Syntax error at line 1 column 1: Expected '.', but found EOF") + e.getMessage(), + equalTo("Syntax error at line 1 column 1: Expected '.', but found EOF") ); } @@ -127,13 +127,13 @@ public void expectsOneOrMoreTokensWithInvalidResultBecauseEof() { TokenIterator iterator = new TokenIterator(tokens); iterator.next(); JmespathException e = Assertions.assertThrows( - JmespathException.class, - () -> iterator.expect(TokenType.DOT, TokenType.EXPREF) + JmespathException.class, + () -> iterator.expect(TokenType.DOT, TokenType.EXPREF) ); assertThat( - e.getMessage(), - equalTo("Syntax error at line 1 column 1: Expected ['.', '&'], but found EOF") + e.getMessage(), + equalTo("Syntax error at line 1 column 1: Expected ['.', '&'], but found EOF") ); } @@ -142,13 +142,13 @@ public void expectsTokensWithInvalidResultBecauseWrongType() { List tokens = Collections.singletonList(new Token(TokenType.DOT, null, 1, 1)); TokenIterator iterator = new TokenIterator(tokens); JmespathException e = Assertions.assertThrows( - JmespathException.class, - () -> iterator.expect(TokenType.STAR) + JmespathException.class, + () -> iterator.expect(TokenType.STAR) ); assertThat( - e.getMessage(), - equalTo("Syntax error at line 1 column 1: Expected '*', but found '.'") + e.getMessage(), + equalTo("Syntax error at line 1 column 1: Expected '*', but found '.'") ); } @@ -157,13 +157,13 @@ public void expectsOneOrMoreTokensWithInvalidResultBecauseWrongType() { List tokens = Collections.singletonList(new Token(TokenType.DOT, null, 1, 1)); TokenIterator iterator = new TokenIterator(tokens); JmespathException e = Assertions.assertThrows( - JmespathException.class, - () -> iterator.expect(TokenType.STAR, TokenType.EXPREF) + JmespathException.class, + () -> iterator.expect(TokenType.STAR, TokenType.EXPREF) ); assertThat( - e.getMessage(), - equalTo("Syntax error at line 1 column 1: Expected ['*', '&'], but found '.'") + e.getMessage(), + equalTo("Syntax error at line 1 column 1: Expected ['*', '&'], but found '.'") ); } } diff --git a/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/TypeCheckerTest.java b/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/TypeCheckerTest.java index e218c64bc3e..10eb12b9b40 100644 --- a/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/TypeCheckerTest.java +++ b/smithy-jmespath/src/test/java/software/amazon/smithy/jmespath/TypeCheckerTest.java @@ -17,11 +17,11 @@ public class TypeCheckerTest { private List check(String expr) { return JmespathExpression.parse(expr) - .lint() - .getProblems() - .stream() - .map(ExpressionProblem::toString) - .collect(Collectors.toList()); + .lint() + .getProblems() + .stream() + .map(ExpressionProblem::toString) + .collect(Collectors.toList()); } @Test @@ -47,52 +47,52 @@ public void detectsFlatteningNonArray() { @Test public void detectsBadFlattenExpression() { assertThat( - check("[].[`true` | foo]"), - contains("[DANGER] Object field 'foo' extraction performed on boolean (1:14)") + check("[].[`true` | foo]"), + contains("[DANGER] Object field 'foo' extraction performed on boolean (1:14)") ); } @Test public void detectsInvalidExpressionsInMultiSelectLists() { assertThat( - check("`true` | [foo, [1], {bar: foo}]"), - containsInAnyOrder( - "[DANGER] Object field 'foo' extraction performed on boolean (1:11)", - "[DANGER] Array index '1' extraction performed on boolean (1:17)", - "[DANGER] Object field 'foo' extraction performed on boolean (1:27)" - ) + check("`true` | [foo, [1], {bar: foo}]"), + containsInAnyOrder( + "[DANGER] Object field 'foo' extraction performed on boolean (1:11)", + "[DANGER] Array index '1' extraction performed on boolean (1:17)", + "[DANGER] Object field 'foo' extraction performed on boolean (1:27)" + ) ); } @Test public void detectsInvalidExpressionsInMultiSelectHash() { assertThat( - check("`true` | {foo: [1], bar: foo}"), - containsInAnyOrder( - "[DANGER] Array index '1' extraction performed on boolean (1:17)", - "[DANGER] Object field 'foo' extraction performed on boolean (1:26)" - ) + check("`true` | {foo: [1], bar: foo}"), + containsInAnyOrder( + "[DANGER] Array index '1' extraction performed on boolean (1:17)", + "[DANGER] Object field 'foo' extraction performed on boolean (1:26)" + ) ); } @Test public void detectsInvalidComparisonExpressions() { assertThat( - check("`true` | foo == [1]"), - containsInAnyOrder( - "[DANGER] Object field 'foo' extraction performed on boolean (1:10)", - "[DANGER] Array index '1' extraction performed on boolean (1:18)" - ) + check("`true` | foo == [1]"), + containsInAnyOrder( + "[DANGER] Object field 'foo' extraction performed on boolean (1:10)", + "[DANGER] Array index '1' extraction performed on boolean (1:18)" + ) ); } @Test public void detectsInvalidExpressionReferences() { assertThat( - check("&(`true` | foo)"), - containsInAnyOrder( - "[DANGER] Object field 'foo' extraction performed on boolean (1:12)" - ) + check("&(`true` | foo)"), + containsInAnyOrder( + "[DANGER] Object field 'foo' extraction performed on boolean (1:12)" + ) ); } @@ -109,50 +109,50 @@ public void detectsValidField() { @Test public void detectsInvalidAndLhs() { assertThat( - check("(`true` | foo) && baz"), - containsInAnyOrder( - "[DANGER] Object field 'foo' extraction performed on boolean (1:11)" - ) + check("(`true` | foo) && baz"), + containsInAnyOrder( + "[DANGER] Object field 'foo' extraction performed on boolean (1:11)" + ) ); } @Test public void detectsInvalidAndRhs() { assertThat( - check("foo && (`true` | foo)"), - containsInAnyOrder( - "[DANGER] Object field 'foo' extraction performed on boolean (1:18)" - ) + check("foo && (`true` | foo)"), + containsInAnyOrder( + "[DANGER] Object field 'foo' extraction performed on boolean (1:18)" + ) ); } @Test public void detectsInvalidOrLhs() { assertThat( - check("(`true` | foo) || baz"), - containsInAnyOrder( - "[DANGER] Object field 'foo' extraction performed on boolean (1:11)" - ) + check("(`true` | foo) || baz"), + containsInAnyOrder( + "[DANGER] Object field 'foo' extraction performed on boolean (1:11)" + ) ); } @Test public void detectsInvalidOrRhs() { assertThat( - check("foo || (`true` | foo)"), - containsInAnyOrder( - "[DANGER] Object field 'foo' extraction performed on boolean (1:18)" - ) + check("foo || (`true` | foo)"), + containsInAnyOrder( + "[DANGER] Object field 'foo' extraction performed on boolean (1:18)" + ) ); } @Test public void detectsInvalidNot() { assertThat( - check("`true` | !foo"), - containsInAnyOrder( - "[DANGER] Object field 'foo' extraction performed on boolean (1:11)" - ) + check("`true` | !foo"), + containsInAnyOrder( + "[DANGER] Object field 'foo' extraction performed on boolean (1:11)" + ) ); } @@ -164,20 +164,20 @@ public void detectsValidNot() { @Test public void detectsMissingProperty() { assertThat( - check("`{}` | foo"), - containsInAnyOrder( - "[DANGER] Object field 'foo' does not exist in object with properties [] (1:8)" - ) + check("`{}` | foo"), + containsInAnyOrder( + "[DANGER] Object field 'foo' does not exist in object with properties [] (1:8)" + ) ); } @Test public void detectsInvalidSlice() { assertThat( - check("`true` | [1:10]"), - containsInAnyOrder( - "[DANGER] Slice performed on boolean (1:11)" - ) + check("`true` | [1:10]"), + containsInAnyOrder( + "[DANGER] Slice performed on boolean (1:11)" + ) ); } @@ -189,30 +189,30 @@ public void detectsValidSlice() { @Test public void detectsInvalidFilterProjectionLhs() { assertThat( - check("`true` | [?baz == bar]"), - containsInAnyOrder( - "[DANGER] Filter projection performed on boolean (1:19)" - ) + check("`true` | [?baz == bar]"), + containsInAnyOrder( + "[DANGER] Filter projection performed on boolean (1:19)" + ) ); } @Test public void detectsInvalidFilterProjectionRhs() { assertThat( - check("[?baz == bar].[`true` | bam]"), - containsInAnyOrder( - "[DANGER] Object field 'bam' extraction performed on boolean (1:25)" - ) + check("[?baz == bar].[`true` | bam]"), + containsInAnyOrder( + "[DANGER] Object field 'bam' extraction performed on boolean (1:25)" + ) ); } @Test public void detectsInvalidFilterProjectionComparison() { assertThat( - check("[?(`true` | baz) == bar]"), - containsInAnyOrder( - "[DANGER] Object field 'baz' extraction performed on boolean (1:13)" - ) + check("[?(`true` | baz) == bar]"), + containsInAnyOrder( + "[DANGER] Object field 'baz' extraction performed on boolean (1:13)" + ) ); } @@ -224,10 +224,10 @@ public void detectsInvalidFunction() { @Test public void detectsInvalidFunctionArity() { assertThat( - check("length(@, @)"), - containsInAnyOrder( - "[ERROR] length function expected 1 arguments, but was given 2 (1:1)" - ) + check("length(@, @)"), + containsInAnyOrder( + "[ERROR] length function expected 1 arguments, but was given 2 (1:1)" + ) ); } @@ -250,59 +250,59 @@ public void detectsSuccessfulStaticArguments() { @Test public void detectsInvalidStaticArguments() { assertThat( - check("length(`true`)"), - containsInAnyOrder( - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:8)" - ) + check("length(`true`)"), + containsInAnyOrder( + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:8)" + ) ); assertThat( - check("starts_with(`true`, `false`)"), - containsInAnyOrder( - "[ERROR] starts_with function argument 0 error: Expected argument to be string, but found boolean (1:13)", - "[ERROR] starts_with function argument 1 error: Expected argument to be string, but found boolean (1:21)" - ) + check("starts_with(`true`, `false`)"), + containsInAnyOrder( + "[ERROR] starts_with function argument 0 error: Expected argument to be string, but found boolean (1:13)", + "[ERROR] starts_with function argument 1 error: Expected argument to be string, but found boolean (1:21)" + ) ); assertThat( - check("avg(`[\"a\", false]`)"), - containsInAnyOrder( - "[ERROR] avg function argument 0 error: Expected an array of number, but found string at index 0 (1:5)" - ) + check("avg(`[\"a\", false]`)"), + containsInAnyOrder( + "[ERROR] avg function argument 0 error: Expected an array of number, but found string at index 0 (1:5)" + ) ); } @Test public void detectsInvalidArgumentThatExpectedArray() { assertThat( - check("avg(`true`)"), - containsInAnyOrder( - "[ERROR] avg function argument 0 error: Expected argument to be an array, but found boolean (1:5)" - ) + check("avg(`true`)"), + containsInAnyOrder( + "[ERROR] avg function argument 0 error: Expected argument to be an array, but found boolean (1:5)" + ) ); } @Test public void detectsInvalidUseOfStaticObjects() { assertThat( - check("{foo: `true`}.length(foo)"), - containsInAnyOrder( - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:22)" - ) + check("{foo: `true`}.length(foo)"), + containsInAnyOrder( + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:22)" + ) ); assertThat( - check("{foo: `true`} | floor(@)"), - containsInAnyOrder( - "[ERROR] floor function argument 0 error: Expected argument to be number, but found object (1:23)" - ) + check("{foo: `true`} | floor(@)"), + containsInAnyOrder( + "[ERROR] floor function argument 0 error: Expected argument to be number, but found object (1:23)" + ) ); } @Test public void detectsWhenTooFewArgumentsAreGiven() { assertThat( - check("length()"), - containsInAnyOrder( - "[ERROR] length function expected 1 arguments, but was given 0 (1:1)" - ) + check("length()"), + containsInAnyOrder( + "[ERROR] length function expected 1 arguments, but was given 0 (1:1)" + ) ); } @@ -325,10 +325,10 @@ public void unknownAndResultIsPermittedAsAny() { @Test public void detectsInvalidAndResult() { assertThat( - check("length(a && `true`)"), - contains( - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:10)" - ) + check("length(a && `true`)"), + contains( + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:10)" + ) ); } @@ -350,41 +350,41 @@ public void flattenFiltersOutNullValuesAndMergesArrays() { @Test public void canDetectInvalidIndexResultsStatically() { assertThat( - check("`[null, true]` | length([0]) || length([1])"), - containsInAnyOrder( - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:26)", - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:41)" - ) + check("`[null, true]` | length([0]) || length([1])"), + containsInAnyOrder( + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:26)", + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:41)" + ) ); } @Test public void analyzesValidObjectProjectionRhs() { assertThat( - check("`{\"foo\": [\"hi\"]}`.*.nope"), - containsInAnyOrder( - "[DANGER] Object field 'nope' extraction performed on array (1:21)" - ) + check("`{\"foo\": [\"hi\"]}`.*.nope"), + containsInAnyOrder( + "[DANGER] Object field 'nope' extraction performed on array (1:21)" + ) ); } @Test public void detectsInvalidObjectProjectionRhs() { assertThat( - check("`{\"foo\": [true]}`.*[0].length(@)"), - containsInAnyOrder( - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:31)" - ) + check("`{\"foo\": [true]}`.*[0].length(@)"), + containsInAnyOrder( + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:31)" + ) ); } @Test public void detectsInvalidFilterProjectionRhsFunction() { assertThat( - check("`[{\"foo\": true}, {\"foo\": false}]`[?foo == `true`].foo | length([0])"), - containsInAnyOrder( - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:65)" - ) + check("`[{\"foo\": true}, {\"foo\": false}]`[?foo == `true`].foo | length([0])"), + containsInAnyOrder( + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:65)" + ) ); } @@ -393,11 +393,11 @@ public void comparesBooleans() { assertThat(check("`[{\"foo\": true}, {\"foo\": false}]`[?foo == `true`] | length(to_string([0]))"), empty()); assertThat(check("`[{\"foo\": true}, {\"foo\": false}]`[?foo != `true`] | length(to_string([0]))"), empty()); assertThat( - check("`[{\"foo\": true}, {\"foo\": false}]`[?foo < `true`] | length([0])"), - containsInAnyOrder( - "[WARNING] Invalid comparator '<' for boolean (1:42)", - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:60)" - ) + check("`[{\"foo\": true}, {\"foo\": false}]`[?foo < `true`] | length([0])"), + containsInAnyOrder( + "[WARNING] Invalid comparator '<' for boolean (1:42)", + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:60)" + ) ); } @@ -406,11 +406,11 @@ public void comparesStrings() { assertThat(check("`[{\"foo\": \"a\"}, {\"foo\": \"b\"}]`[?foo == 'a'] | length(to_string([0]))"), empty()); assertThat(check("`[{\"foo\": \"a\"}, {\"foo\": \"b\"}]`[?foo != 'a'] | length(to_string([0]))"), empty()); assertThat( - check("`[{\"foo\": \"a\"}, {\"foo\": \"b\"}]`[?foo > 'a'] | length([0])"), - containsInAnyOrder( - "[WARNING] Invalid comparator '>' for string (1:39)", - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:54)" - ) + check("`[{\"foo\": \"a\"}, {\"foo\": \"b\"}]`[?foo > 'a'] | length([0])"), + containsInAnyOrder( + "[WARNING] Invalid comparator '>' for string (1:39)", + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:54)" + ) ); } @@ -423,20 +423,20 @@ public void comparesNumbers() { assertThat(check("`[{\"foo\": 1}, {\"foo\": 2}]`[?foo < `2`].foo | abs([0])"), empty()); assertThat(check("`[{\"foo\": 1}, {\"foo\": 2}]`[?foo <= `2`].foo | abs([0])"), empty()); assertThat( - check("`[{\"foo\": 1}, {\"foo\": 2}]`[?foo < `0`].foo | abs([0])"), - containsInAnyOrder( - "[ERROR] abs function argument 0 error: Expected argument to be number, but found null (1:51)" - ) + check("`[{\"foo\": 1}, {\"foo\": 2}]`[?foo < `0`].foo | abs([0])"), + containsInAnyOrder( + "[ERROR] abs function argument 0 error: Expected argument to be number, but found null (1:51)" + ) ); } @Test public void comparisonsBetweenIncompatibleTypesIsFalse() { assertThat( - check("`[{\"foo\": 1}, {\"foo\": 2}]`[?foo == `true`].foo | abs([0])"), - containsInAnyOrder( - "[ERROR] abs function argument 0 error: Expected argument to be number, but found null (1:55)" - ) + check("`[{\"foo\": 1}, {\"foo\": 2}]`[?foo == `true`].foo | abs([0])"), + containsInAnyOrder( + "[ERROR] abs function argument 0 error: Expected argument to be number, but found null (1:55)" + ) ); } @@ -445,38 +445,38 @@ public void comparesNulls() { assertThat(check("length(`null` == `null` && 'hi')"), empty()); assertThat(check("length(`null` != `null` || 'hi')"), empty()); assertThat( - check("length(`null` != `null` && 'hi')"), - contains( - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:25)" - ) + check("length(`null` != `null` && 'hi')"), + contains( + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:25)" + ) ); assertThat( - check("length(`null` > `null` && 'hi')"), - containsInAnyOrder( - "[WARNING] Invalid comparator '>' for null (1:17)", - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:24)" - ) + check("length(`null` > `null` && 'hi')"), + containsInAnyOrder( + "[WARNING] Invalid comparator '>' for null (1:17)", + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:24)" + ) ); assertThat( - check("length(`null` >= `null` && 'hi')"), - containsInAnyOrder( - "[WARNING] Invalid comparator '>=' for null (1:18)", - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:25)" - ) + check("length(`null` >= `null` && 'hi')"), + containsInAnyOrder( + "[WARNING] Invalid comparator '>=' for null (1:18)", + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:25)" + ) ); assertThat( - check("length(`null` < `null` && 'hi')"), - containsInAnyOrder( - "[WARNING] Invalid comparator '<' for null (1:17)", - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:24)" - ) + check("length(`null` < `null` && 'hi')"), + containsInAnyOrder( + "[WARNING] Invalid comparator '<' for null (1:17)", + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:24)" + ) ); assertThat( - check("length(`null` <= `null` && 'hi')"), - containsInAnyOrder( - "[WARNING] Invalid comparator '<=' for null (1:18)", - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:25)" - ) + check("length(`null` <= `null` && 'hi')"), + containsInAnyOrder( + "[WARNING] Invalid comparator '<=' for null (1:18)", + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:25)" + ) ); } @@ -490,38 +490,38 @@ public void comparesArrays() { assertThat(check("length(`[1,2]` == `[1,2]` && 'hi')"), empty()); assertThat(check("length(`[1]` != `[1,2]` && 'hi')"), empty()); assertThat( - check("length(`[1]` != `[1]` && 'hi')"), - contains( - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:23)" - ) + check("length(`[1]` != `[1]` && 'hi')"), + contains( + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:23)" + ) ); assertThat( - check("length(`[1]` > `[2]` && 'hi')"), - containsInAnyOrder( - "[WARNING] Invalid comparator '>' for array (1:16)", - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:22)" - ) + check("length(`[1]` > `[2]` && 'hi')"), + containsInAnyOrder( + "[WARNING] Invalid comparator '>' for array (1:16)", + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:22)" + ) ); assertThat( - check("length(`[1]` >= `[2]` && 'hi')"), - containsInAnyOrder( - "[WARNING] Invalid comparator '>=' for array (1:17)", - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:23)" - ) + check("length(`[1]` >= `[2]` && 'hi')"), + containsInAnyOrder( + "[WARNING] Invalid comparator '>=' for array (1:17)", + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:23)" + ) ); assertThat( - check("length(`[1]` < `[2]` && 'hi')"), - containsInAnyOrder( - "[WARNING] Invalid comparator '<' for array (1:16)", - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:22)" - ) + check("length(`[1]` < `[2]` && 'hi')"), + containsInAnyOrder( + "[WARNING] Invalid comparator '<' for array (1:16)", + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:22)" + ) ); assertThat( - check("length(`[1]` <= `[2]` && 'hi')"), - containsInAnyOrder( - "[WARNING] Invalid comparator '<=' for array (1:17)", - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:23)" - ) + check("length(`[1]` <= `[2]` && 'hi')"), + containsInAnyOrder( + "[WARNING] Invalid comparator '<=' for array (1:17)", + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:23)" + ) ); } @@ -530,72 +530,72 @@ public void comparesObjects() { assertThat(check("length(`{}` == `{}` && 'hi')"), empty()); assertThat(check("length(`{\"foo\":true}` != `{}` && 'hi')"), empty()); assertThat( - check("length(`[1]` != `[1]` && 'hi')"), - contains( - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:23)" - ) + check("length(`[1]` != `[1]` && 'hi')"), + contains( + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found boolean (1:23)" + ) ); assertThat( - check("length(`{\"foo\":true}` > `{}` && 'hi')"), - containsInAnyOrder( - "[WARNING] Invalid comparator '>' for object (1:25)", - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:30)" - ) + check("length(`{\"foo\":true}` > `{}` && 'hi')"), + containsInAnyOrder( + "[WARNING] Invalid comparator '>' for object (1:25)", + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:30)" + ) ); assertThat( - check("length(`{\"foo\":true}` >= `{}` && 'hi')"), - containsInAnyOrder( - "[WARNING] Invalid comparator '>=' for object (1:26)", - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:31)" - ) + check("length(`{\"foo\":true}` >= `{}` && 'hi')"), + containsInAnyOrder( + "[WARNING] Invalid comparator '>=' for object (1:26)", + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:31)" + ) ); assertThat( - check("length(`{\"foo\":true}` < `{}` && 'hi')"), - containsInAnyOrder( - "[WARNING] Invalid comparator '<' for object (1:25)", - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:30)" - ) + check("length(`{\"foo\":true}` < `{}` && 'hi')"), + containsInAnyOrder( + "[WARNING] Invalid comparator '<' for object (1:25)", + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:30)" + ) ); assertThat( - check("length(`{\"foo\":true}` <= `{}` && 'hi')"), - containsInAnyOrder( - "[WARNING] Invalid comparator '<=' for object (1:26)", - "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:31)" - ) + check("length(`{\"foo\":true}` <= `{}` && 'hi')"), + containsInAnyOrder( + "[WARNING] Invalid comparator '<=' for object (1:26)", + "[ERROR] length function argument 0 error: Expected one of [string, array, object], but found null (1:31)" + ) ); } @Test public void falseyLhsIsReturnedFromAnd() { assertThat( - check("ceil(`[]` && `0.9`)"), - contains( - "[ERROR] ceil function argument 0 error: Expected argument to be number, but found array (1:11)" - ) + check("ceil(`[]` && `0.9`)"), + contains( + "[ERROR] ceil function argument 0 error: Expected argument to be number, but found array (1:11)" + ) ); assertThat( - check("ceil(`{}` && `0.9`)"), - contains( - "[ERROR] ceil function argument 0 error: Expected argument to be number, but found object (1:11)" - ) + check("ceil(`{}` && `0.9`)"), + contains( + "[ERROR] ceil function argument 0 error: Expected argument to be number, but found object (1:11)" + ) ); assertThat( - check("ceil(`\"\"` && `0.9`)"), - contains( - "[ERROR] ceil function argument 0 error: Expected argument to be number, but found string (1:11)" - ) + check("ceil(`\"\"` && `0.9`)"), + contains( + "[ERROR] ceil function argument 0 error: Expected argument to be number, but found string (1:11)" + ) ); assertThat( - check("ceil(`false` && `0.9`)"), - contains( - "[ERROR] ceil function argument 0 error: Expected argument to be number, but found boolean (1:14)" - ) + check("ceil(`false` && `0.9`)"), + contains( + "[ERROR] ceil function argument 0 error: Expected argument to be number, but found boolean (1:14)" + ) ); assertThat( - check("ceil(`null` && `0.9`)"), - contains( - "[ERROR] ceil function argument 0 error: Expected argument to be number, but found null (1:13)" - ) + check("ceil(`null` && `0.9`)"), + contains( + "[ERROR] ceil function argument 0 error: Expected argument to be number, but found null (1:13)" + ) ); } } diff --git a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/DeconflictingStrategy.java b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/DeconflictingStrategy.java index 7e2217da612..09175068800 100644 --- a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/DeconflictingStrategy.java +++ b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/DeconflictingStrategy.java @@ -67,12 +67,12 @@ final class DeconflictingStrategy implements RefStrategy { if (scrubbedModel.getShape(reversePointers.get(pointer)).isPresent()) { String deconflictedPointer = deconflict(shape, pointer, reversePointers); LOGGER.info( - () -> String.format( - "De-conflicted `%s` JSON schema pointer from `%s` to `%s`", - shape.getId(), - pointer, - deconflictedPointer - ) + () -> String.format( + "De-conflicted `%s` JSON schema pointer from `%s` to `%s`", + shape.getId(), + pointer, + deconflictedPointer + ) ); pointers.put(shape.getId(), deconflictedPointer); reversePointers.put(deconflictedPointer, shape.getId()); @@ -85,31 +85,31 @@ final class DeconflictingStrategy implements RefStrategy { // don't have a corresponding definition. private boolean isIgnoredShape(Shape shape) { return (shape instanceof SimpleShape && !shape.hasTrait(EnumTrait.class)) - || shape.isResourceShape() - || shape.isServiceShape() - || shape.isOperationShape() - || shape.isMemberShape() - || (Prelude.isPreludeShape(shape) && shape.hasTrait(PrivateTrait.class)); + || shape.isResourceShape() + || shape.isServiceShape() + || shape.isOperationShape() + || shape.isMemberShape() + || (Prelude.isPreludeShape(shape) && shape.hasTrait(PrivateTrait.class)); } private String deconflict(Shape shape, String pointer, Map reversePointers) { LOGGER.info( - () -> String.format( - "Attempting to de-conflict `%s` JSON schema pointer `%s` that conflicts with `%s`", - shape.getId(), - pointer, - reversePointers.get(pointer) - ) + () -> String.format( + "Attempting to de-conflict `%s` JSON schema pointer `%s` that conflicts with `%s`", + shape.getId(), + pointer, + reversePointers.get(pointer) + ) ); if (!isSafeToDeconflict(shape)) { throw new ConflictingShapeNameException( - String.format( - "Shape %s conflicts with %s using a JSON schema pointer of %s", - shape, - reversePointers.get(pointer), - pointer - ) + String.format( + "Shape %s conflicts with %s using a JSON schema pointer of %s", + shape, + reversePointers.get(pointer), + pointer + ) ); } @@ -126,12 +126,12 @@ private String deconflict(Shape shape, String pointer, Map reve if (reversePointers.containsKey(updatedPointer)) { // Note: I don't know if this can ever actually happen... but just in case. throw new ConflictingShapeNameException( - String.format( - "Unable to de-conflict shape %s because the de-conflicted name resolves " - + "to another generated name: %s", - shape, - updatedPointer - ) + String.format( + "Unable to de-conflict shape %s because the de-conflicted name resolves " + + "to another generated name: %s", + shape, + updatedPointer + ) ); } diff --git a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/DefaultRefStrategy.java b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/DefaultRefStrategy.java index 13e7fb7f567..ecb2ddd966b 100644 --- a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/DefaultRefStrategy.java +++ b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/DefaultRefStrategy.java @@ -58,8 +58,8 @@ final class DefaultRefStrategy implements RefStrategy { this.config = config; rootPointer = computePointer(config); serviceContext = Optional.ofNullable(config.getService()) - .map(shape -> model.expectShape(shape, ServiceShape.class)) - .orElse(null); + .map(shape -> model.expectShape(shape, ServiceShape.class)) + .orElse(null); } private static String computePointer(JsonSchemaConfig config) { @@ -101,13 +101,13 @@ private String createMemberPointer(MemberShape member) { return parentPointer + "/items"; case MAP: return member.getMemberName().equals("key") - ? parentPointer + "/propertyNames" - : parentPointer + "/additionalProperties"; + ? parentPointer + "/propertyNames" + : parentPointer + "/additionalProperties"; default: // union | structure return parentPointer + "/properties/" + propertyNamingStrategy.toPropertyName( - container, - member, - config + container, + member, + config ); } } @@ -170,7 +170,7 @@ public boolean isInlined(Shape shape) { private String stripNonAlphaNumericCharsIfNecessary(String result) { return config.getAlphanumericOnlyRefs() - ? NON_ALPHA_NUMERIC.matcher(result).replaceAll("") - : result; + ? NON_ALPHA_NUMERIC.matcher(result).replaceAll("") + : result; } } diff --git a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaConfig.java b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaConfig.java index bddd36513bd..f758895d579 100644 --- a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaConfig.java +++ b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaConfig.java @@ -339,9 +339,9 @@ public void setService(ShapeId service) { public Optional detectJsonTimestampFormat(Shape shape) { if (shape.isTimestampShape() || shape.hasTrait(TimestampFormatTrait.class)) { return Optional.of( - shape.getTrait(TimestampFormatTrait.class) - .map(TimestampFormatTrait::getValue) - .orElseGet(() -> getDefaultTimestampFormat().toString()) + shape.getTrait(TimestampFormatTrait.class) + .map(TimestampFormatTrait::getValue) + .orElseGet(() -> getDefaultTimestampFormat().toString()) ); } return Optional.empty(); diff --git a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaConverter.java b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaConverter.java index 4e784ce8818..18f39f70f47 100644 --- a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaConverter.java +++ b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaConverter.java @@ -38,7 +38,7 @@ public final class JsonSchemaConverter implements ToSmithyBuilder mappers = new ArrayList<>(); @@ -75,26 +75,26 @@ private JsonSchemaConverter(Builder builder) { rootShape = null; } else { rootShape = builder.model.getShape(builder.rootShape) - .orElseThrow( - () -> new SmithyJsonSchemaException( - "Invalid root shape (shape not found): " + builder.rootShape - ) - ); + .orElseThrow( + () -> new SmithyJsonSchemaException( + "Invalid root shape (shape not found): " + builder.rootShape + ) + ); } LOGGER.fine("Creating JSON ref strategy"); Model refModel = config.isEnableOutOfServiceReferences() - ? this.model - : scopeModelToService(model, config.getService()); + ? this.model + : scopeModelToService(model, config.getService()); unitTargetedByUnion = refModel.shapes(UnionShape.class) - .anyMatch(u -> u.members().stream().anyMatch(m -> m.getTarget().equals(UnitTypeTrait.UNIT))); + .anyMatch(u -> u.members().stream().anyMatch(m -> m.getTarget().equals(UnitTypeTrait.UNIT))); refStrategy = RefStrategy.createDefaultStrategy( - refModel, - config, - propertyNamingStrategy, - new FilterPreludeUnit(unitTargetedByUnion) + refModel, + config, + propertyNamingStrategy, + new FilterPreludeUnit(unitTargetedByUnion) ); // Combine custom mappers with the discovered mappers and sort them. @@ -103,10 +103,10 @@ private JsonSchemaConverter(Builder builder) { realizedMappers.add(new TimestampMapper()); realizedMappers.sort(Comparator.comparing(JsonSchemaMapper::getOrder)); LOGGER.fine( - () -> "Adding the following JSON schema mappers: " + realizedMappers.stream() - .map(Object::getClass) - .map(Class::getCanonicalName) - .collect(Collectors.joining(", ")) + () -> "Adding the following JSON schema mappers: " + realizedMappers.stream() + .map(Object::getClass) + .map(Class::getCanonicalName) + .collect(Collectors.joining(", ")) ); visitor = new JsonSchemaShapeVisitor(this.model, this, realizedMappers); @@ -114,15 +114,15 @@ private JsonSchemaConverter(Builder builder) { rootDefinitionPointer = config.getDefinitionPointer(); rootDefinitionSegments = countSegments(rootDefinitionPointer); LOGGER.fine( - () -> "Using the following root JSON schema pointer: " + rootDefinitionPointer - + " (" + rootDefinitionSegments + " segments)" + () -> "Using the following root JSON schema pointer: " + rootDefinitionPointer + + " (" + rootDefinitionSegments + " segments)" ); } private static Model createUpdatedModel( - Model model, - Shape rootShape, - Predicate predicate + Model model, + Shape rootShape, + Predicate predicate ) { ModelTransformer transformer = ModelTransformer.create(); @@ -130,10 +130,10 @@ private static Model createUpdatedModel( LOGGER.fine(() -> "Filtering out shapes that are not connected to " + rootShape); Set connected = new Walker(model).walkShapes(rootShape); LOGGER.fine( - () -> "Only generating the following JSON schema shapes: " + connected.stream() - .map(Shape::getId) - .map(ShapeId::toString) - .collect(Collectors.joining(", ")) + () -> "Only generating the following JSON schema shapes: " + connected.stream() + .map(Shape::getId) + .map(ShapeId::toString) + .collect(Collectors.joining(", ")) ); model = transformer.filterShapes(model, connected::contains); } @@ -195,7 +195,7 @@ public void setConfig(JsonSchemaConfig config) { */ public String toPropertyName(MemberShape member) { Shape containingShape = model.getShape(member.getContainer()) - .orElseThrow(() -> new SmithyJsonSchemaException("Invalid member: " + member)); + .orElseThrow(() -> new SmithyJsonSchemaException("Invalid member: " + member)); return propertyNamingStrategy.toPropertyName(containingShape, member, config); } @@ -225,7 +225,7 @@ public String toPointer(ToShapeId id) { */ public boolean isTopLevelPointer(String pointer) { return pointer.startsWith(rootDefinitionPointer) - && countSegments(pointer) == rootDefinitionSegments + 1; + && countSegments(pointer) == rootDefinitionSegments + 1; } /** @@ -259,28 +259,28 @@ public SchemaDocument convert() { Model updatedModel = createUpdatedModel(model, rootShape, shapePredicate); model.shapes() - // Only generate shapes that passed through each predicate. - .filter(shape -> updatedModel.getShape(shape.getId()).isPresent()) - // Don't generate members. - .filter(FunctionalUtils.not(Shape::isMemberShape)) - // Don't write the root shape to the definitions. - .filter((shape -> rootShape == null || !shape.getId().equals(rootShape.getId()))) - // Don't convert unsupported shapes. - .filter(FunctionalUtils.not(this::isUnsupportedShapeType)) - // Ignore prelude shapes. - .filter(s -> s.getId().equals(UnitTypeTrait.UNIT) && unitTargetedByUnion || !Prelude.isPreludeShape(s)) - // Do not generate inlined shapes in the definitions map. - .filter(FunctionalUtils.not(refStrategy::isInlined)) - // Create a pair of pointer and shape. - .map(shape -> Pair.of(toPointer(shape), shape)) - // Only add definitions if they are at the top-level and not inlined. - .filter(pair -> isTopLevelPointer(pair.getLeft())) - // Create the pointer to the shape and schema object. - .map(pair -> { - LOGGER.fine(() -> "Converting " + pair.getRight() + " to JSON schema at " + pair.getLeft()); - return Pair.of(pair.getLeft(), pair.getRight().accept(visitor)); - }) - .forEach(pair -> builder.putDefinition(pair.getLeft(), pair.getRight())); + // Only generate shapes that passed through each predicate. + .filter(shape -> updatedModel.getShape(shape.getId()).isPresent()) + // Don't generate members. + .filter(FunctionalUtils.not(Shape::isMemberShape)) + // Don't write the root shape to the definitions. + .filter((shape -> rootShape == null || !shape.getId().equals(rootShape.getId()))) + // Don't convert unsupported shapes. + .filter(FunctionalUtils.not(this::isUnsupportedShapeType)) + // Ignore prelude shapes. + .filter(s -> s.getId().equals(UnitTypeTrait.UNIT) && unitTargetedByUnion || !Prelude.isPreludeShape(s)) + // Do not generate inlined shapes in the definitions map. + .filter(FunctionalUtils.not(refStrategy::isInlined)) + // Create a pair of pointer and shape. + .map(shape -> Pair.of(toPointer(shape), shape)) + // Only add definitions if they are at the top-level and not inlined. + .filter(pair -> isTopLevelPointer(pair.getLeft())) + // Create the pointer to the shape and schema object. + .map(pair -> { + LOGGER.fine(() -> "Converting " + pair.getRight() + " to JSON schema at " + pair.getLeft()); + return Pair.of(pair.getLeft(), pair.getRight().accept(visitor)); + }) + .forEach(pair -> builder.putDefinition(pair.getLeft(), pair.getRight())); LOGGER.fine(() -> "Completed JSON schema document conversion (root shape: " + rootShape + ")"); @@ -321,12 +321,12 @@ private void addExtensions(SchemaDocument.Builder builder) { @Override public Builder toBuilder() { return builder() - .model(model) - .propertyNamingStrategy(propertyNamingStrategy) - .config(config) - .rootShape(rootShape == null ? null : rootShape.getId()) - .shapePredicate(shapePredicate) - .mappers(mappers); + .model(model) + .propertyNamingStrategy(propertyNamingStrategy) + .config(config) + .rootShape(rootShape == null ? null : rootShape.getId()) + .shapePredicate(shapePredicate) + .mappers(mappers); } public static final class Builder implements SmithyBuilder { diff --git a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaMapperContext.java b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaMapperContext.java index ba2ad31da91..3c13e02cfdd 100644 --- a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaMapperContext.java +++ b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaMapperContext.java @@ -16,9 +16,9 @@ public class JsonSchemaMapperContext { private final JsonSchemaConfig config; JsonSchemaMapperContext( - Model model, - Shape shape, - JsonSchemaConfig config + Model model, + Shape shape, + JsonSchemaConfig config ) { this.model = model; this.shape = shape; diff --git a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaShapeVisitor.java b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaShapeVisitor.java index e7c50204cb5..4a122bfc4b4 100644 --- a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaShapeVisitor.java +++ b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaShapeVisitor.java @@ -116,21 +116,21 @@ public Schema mapShape(MapShape shape) { switch (mapStrategy) { case PROPERTY_NAMES: return buildSchema( - shape, - createBuilder(shape, "object") - .propertyNames(createRef(shape.getKey())) - .additionalProperties(createRef(shape.getValue())) + shape, + createBuilder(shape, "object") + .propertyNames(createRef(shape.getKey())) + .additionalProperties(createRef(shape.getValue())) ); case PATTERN_PROPERTIES: String keyPattern = shape.getKey() - .getMemberTrait(model, PatternTrait.class) - .map(PatternTrait::getPattern) - .map(Pattern::pattern) - .orElse(".+"); + .getMemberTrait(model, PatternTrait.class) + .map(PatternTrait::getPattern) + .map(Pattern::pattern) + .orElse(".+"); return buildSchema( - shape, - createBuilder(shape, "object") - .putPatternProperty(keyPattern, createRef(shape.getValue())) + shape, + createBuilder(shape, "object") + .putPatternProperty(keyPattern, createRef(shape.getValue())) ); default: throw new SmithyJsonSchemaException(String.format("Unsupported map strategy: %s", mapStrategy)); @@ -179,13 +179,13 @@ private Schema buildFloatSchema(Shape shape) { } Schema nonNumericValues = Schema.builder() - .type("string") - .enumValues(NON_NUMERIC_FLOAT_VALUES) - .build(); + .type("string") + .enumValues(NON_NUMERIC_FLOAT_VALUES) + .build(); Schema.Builder nonNumericNumberBuilder = createBuilder(shape, "number") - .type(null) - .oneOf(ListUtils.of(numberBuilder.build(), nonNumericValues)); + .type(null) + .oneOf(ListUtils.of(numberBuilder.build(), nonNumericValues)); return buildSchema(shape, nonNumericNumberBuilder); } @@ -240,12 +240,12 @@ public Schema unionShape(UnionShape shape) { for (MemberShape member : shape.getAllMembers().values()) { String memberName = converter.toPropertyName(member); schemas.add( - Schema.builder() - .type("object") - .title(memberName) - .required(ListUtils.of(memberName)) - .putProperty(memberName, createRef(member)) - .build() + Schema.builder() + .type("object") + .title(memberName) + .required(ListUtils.of(memberName)) + .putProperty(memberName, createRef(member)) + .build() ); } return buildSchema(shape, createBuilder(shape, "object").type(null).oneOf(schemas)); @@ -267,7 +267,7 @@ public Schema memberShape(MemberShape memberShape) { private Shape getTarget(MemberShape member) { return model.getShape(member.getTarget()) - .orElseThrow(() -> new SmithyJsonSchemaException("Unable to find the shape targeted by " + member)); + .orElseThrow(() -> new SmithyJsonSchemaException("Unable to find the shape targeted by " + member)); } private Schema.Builder createBuilder(Shape shape, String defaultType) { @@ -285,17 +285,17 @@ private Schema.Builder updateBuilder(Shape shape, Schema.Builder builder) { descriptionMessage(shape).ifPresent(builder::description); shape.getTrait(TitleTrait.class) - .map(TitleTrait::getValue) - .ifPresent(builder::title); + .map(TitleTrait::getValue) + .ifPresent(builder::title); shape.getTrait(MediaTypeTrait.class) - .map(MediaTypeTrait::getValue) - .ifPresent(builder::contentMediaType); + .map(MediaTypeTrait::getValue) + .ifPresent(builder::contentMediaType); shape.getMemberTrait(model, PatternTrait.class) - .map(PatternTrait::getPattern) - .map(Pattern::pattern) - .ifPresent(builder::pattern); + .map(PatternTrait::getPattern) + .map(Pattern::pattern) + .ifPresent(builder::pattern); shape.getMemberTrait(model, RangeTrait.class).ifPresent(t -> { t.getMin().ifPresent(builder::minimum); @@ -305,8 +305,8 @@ private Schema.Builder updateBuilder(Shape shape, Schema.Builder builder) { shape.getMemberTrait(model, LengthTrait.class).ifPresent(t -> { // The current shape or target for members dictates how this translates. Shape targetShape = shape.asMemberShape() - .flatMap(target -> model.getShape(target.getTarget())) - .orElse(shape); + .flatMap(target -> model.getShape(target.getTarget())) + .orElse(shape); if (targetShape.isListShape() || targetShape.isSetShape()) { t.getMin().map(Long::intValue).ifPresent(builder::minItems); t.getMax().map(Long::intValue).ifPresent(builder::maxItems); @@ -324,8 +324,8 @@ private Schema.Builder updateBuilder(Shape shape, Schema.Builder builder) { } shape.getTrait(EnumTrait.class) - .map(EnumTrait::getEnumDefinitionValues) - .ifPresent(builder::enumValues); + .map(EnumTrait::getEnumDefinitionValues) + .ifPresent(builder::enumValues); if (shape.isIntEnumShape() && !converter.getConfig().getDisableIntEnums()) { builder.intEnumValues(shape.asIntEnumShape().get().getEnumValues().values()); @@ -345,17 +345,17 @@ private Schema.Builder updateBuilder(Shape shape, Schema.Builder builder) { private Optional descriptionMessage(Shape shape) { StringBuilder builder = new StringBuilder(); shape - .getTrait(DocumentationTrait.class) - .ifPresent( - trait -> builder.append(trait.getValue()) - ); + .getTrait(DocumentationTrait.class) + .ifPresent( + trait -> builder.append(trait.getValue()) + ); shape - .getTrait(DeprecatedTrait.class) - .ifPresent( - trait -> builder - .append("\n") - .append(trait.getDeprecatedDescription(shape.getType())) - ); + .getTrait(DeprecatedTrait.class) + .ifPresent( + trait -> builder + .append("\n") + .append(trait.getDeprecatedDescription(shape.getType())) + ); String description = builder.toString().trim(); return description.isEmpty() ? Optional.empty() : Optional.of(description); } diff --git a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/RefStrategy.java b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/RefStrategy.java index e7ec53d1759..54531a7dcc1 100644 --- a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/RefStrategy.java +++ b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/RefStrategy.java @@ -64,10 +64,10 @@ interface RefStrategy { * @return Returns the created strategy. */ static RefStrategy createDefaultStrategy( - Model model, - JsonSchemaConfig config, - PropertyNamingStrategy propertyNamingStrategy, - Predicate shapePredicate + Model model, + JsonSchemaConfig config, + PropertyNamingStrategy propertyNamingStrategy, + Predicate shapePredicate ) { RefStrategy delegate = new DefaultRefStrategy(model, config, propertyNamingStrategy); return new DeconflictingStrategy(model, delegate, shapePredicate); diff --git a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/Schema.java b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/Schema.java index 9a6285162c4..8a9d1b97c1b 100644 --- a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/Schema.java +++ b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/Schema.java @@ -340,58 +340,58 @@ public Node toNode() { } ObjectNode.Builder result = Node.objectNodeBuilder() - .withOptionalMember("type", getType().map(Node::from)) - .withOptionalMember("$ref", getRef().map(Node::from)) - .withOptionalMember("const", getConstValue()) - .withOptionalMember("default", getDefaultValue()) - - .withOptionalMember("multipleOf", getMultipleOf().map(Node::from)) - .withOptionalMember("maximum", getMaximum().map(Node::from)) - .withOptionalMember("exclusiveMaximum", getExclusiveMaximum().map(Node::from)) - .withOptionalMember("minimum", getMinimum().map(Node::from)) - .withOptionalMember("exclusiveMinimum", getExclusiveMinimum().map(Node::from)) - - .withOptionalMember("items", getItems().map(ToNode::toNode)) - .withOptionalMember("maxItems", getMaxItems().map(Node::from)) - .withOptionalMember("minItems", getMinItems().map(Node::from)) - .withOptionalMember("uniqueItems", uniqueItems ? Optional.of(Node.from(true)) : Optional.empty()) - - .withOptionalMember("maxLength", getMaxLength().map(Node::from)) - .withOptionalMember("minLength", getMinLength().map(Node::from)) - .withOptionalMember("pattern", getPattern().map(Node::from)) - - .withOptionalMember("additionalProperties", getAdditionalProperties().map(Schema::toNode)) - .withOptionalMember("propertyNames", getPropertyNames().map(Schema::toNode)) - .withOptionalMember("maxProperties", getMaxProperties().map(Node::from)) - .withOptionalMember("minProperties", getMinProperties().map(Node::from)) - - .withOptionalMember("not", getNot().map(Schema::toNode)) - - .withOptionalMember("comment", getComment().map(Node::from)) - .withOptionalMember("examples", getExamples()) - .withOptionalMember("deprecated", this.deprecated ? Optional.of(Node.from(true)) : Optional.empty()) - .withOptionalMember("title", getTitle().map(Node::from)) - .withOptionalMember("description", getDescription().map(Node::from)) - .withOptionalMember("format", getFormat().map(Node::from)) - - .withOptionalMember("contentEncoding", getContentEncoding().map(Node::from)) - .withOptionalMember("contentMediaType", getContentMediaType().map(Node::from)); + .withOptionalMember("type", getType().map(Node::from)) + .withOptionalMember("$ref", getRef().map(Node::from)) + .withOptionalMember("const", getConstValue()) + .withOptionalMember("default", getDefaultValue()) + + .withOptionalMember("multipleOf", getMultipleOf().map(Node::from)) + .withOptionalMember("maximum", getMaximum().map(Node::from)) + .withOptionalMember("exclusiveMaximum", getExclusiveMaximum().map(Node::from)) + .withOptionalMember("minimum", getMinimum().map(Node::from)) + .withOptionalMember("exclusiveMinimum", getExclusiveMinimum().map(Node::from)) + + .withOptionalMember("items", getItems().map(ToNode::toNode)) + .withOptionalMember("maxItems", getMaxItems().map(Node::from)) + .withOptionalMember("minItems", getMinItems().map(Node::from)) + .withOptionalMember("uniqueItems", uniqueItems ? Optional.of(Node.from(true)) : Optional.empty()) + + .withOptionalMember("maxLength", getMaxLength().map(Node::from)) + .withOptionalMember("minLength", getMinLength().map(Node::from)) + .withOptionalMember("pattern", getPattern().map(Node::from)) + + .withOptionalMember("additionalProperties", getAdditionalProperties().map(Schema::toNode)) + .withOptionalMember("propertyNames", getPropertyNames().map(Schema::toNode)) + .withOptionalMember("maxProperties", getMaxProperties().map(Node::from)) + .withOptionalMember("minProperties", getMinProperties().map(Node::from)) + + .withOptionalMember("not", getNot().map(Schema::toNode)) + + .withOptionalMember("comment", getComment().map(Node::from)) + .withOptionalMember("examples", getExamples()) + .withOptionalMember("deprecated", this.deprecated ? Optional.of(Node.from(true)) : Optional.empty()) + .withOptionalMember("title", getTitle().map(Node::from)) + .withOptionalMember("description", getDescription().map(Node::from)) + .withOptionalMember("format", getFormat().map(Node::from)) + + .withOptionalMember("contentEncoding", getContentEncoding().map(Node::from)) + .withOptionalMember("contentMediaType", getContentMediaType().map(Node::from)); if (!properties.isEmpty()) { result.withMember( - "properties", - properties.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, e -> e.getValue().toNode())) + "properties", + properties.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, e -> e.getValue().toNode())) ); } if (!patternProperties.isEmpty()) { result.withMember( - "patternProperties", - patternProperties.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, e -> e.getValue().toNode())) + "patternProperties", + patternProperties.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, e -> e.getValue().toNode())) ); } @@ -471,8 +471,8 @@ public Optional selectSchema(String... segments) { case "properties": // Grab the property name if present, and skip 2 segments. return segments.length == 1 - ? Optional.empty() - : getRecursiveSchema(getProperty(segments[1]), segments, 2); + ? Optional.empty() + : getRecursiveSchema(getProperty(segments[1]), segments, 2); case "allOf": return getSchemaFromArray(allOf, segments); case "anyOf": @@ -508,8 +508,8 @@ private Optional getSchemaFromArray(List schemaArray, String[] s try { int position = segments[1].equals("-") ? schemaArray.size() - 1 : Integer.parseInt(segments[1]); return position > -1 && position < schemaArray.size() - ? getRecursiveSchema(Optional.of(schemaArray.get(position)), segments, 2) - : Optional.empty(); + ? getRecursiveSchema(Optional.of(schemaArray.get(position)), segments, 2) + : Optional.empty(); } catch (NumberFormatException e) { throw new SmithyJsonSchemaException("Invalid JSON pointer number: " + e.getMessage()); } @@ -518,50 +518,50 @@ private Optional getSchemaFromArray(List schemaArray, String[] s @Override public Builder toBuilder() { Builder builder = new Builder() - .ref(ref) - .type(type) - .enumValues(enumValues) - .intEnumValues(intEnumValues) - .constValue(constValue) - .defaultValue(defaultValue) - - .multipleOf(multipleOf) - .maximum(maximum) - .exclusiveMaximum(exclusiveMaximum) - .minimum(minimum) - .exclusiveMinimum(exclusiveMinimum) - - .maxLength(maxLength) - .minLength(minLength) - .pattern(pattern) - - .items(items) - .maxItems(maxItems) - .minItems(minItems) - .uniqueItems(uniqueItems) - - .required(required) - .additionalProperties(additionalProperties) - .maxProperties(maxProperties) - .minProperties(minProperties) - .propertyNames(propertyNames) - - .allOf(allOf) - .anyOf(anyOf) - .oneOf(oneOf) - .not(not) - - .title(title) - .description(description) - .format(format) - .readOnly(readOnly) - .writeOnly(writeOnly) - .comment(comment) - .examples(examples) - .deprecated(deprecated) - - .contentEncoding(contentEncoding) - .contentMediaType(contentMediaType); + .ref(ref) + .type(type) + .enumValues(enumValues) + .intEnumValues(intEnumValues) + .constValue(constValue) + .defaultValue(defaultValue) + + .multipleOf(multipleOf) + .maximum(maximum) + .exclusiveMaximum(exclusiveMaximum) + .minimum(minimum) + .exclusiveMinimum(exclusiveMinimum) + + .maxLength(maxLength) + .minLength(minLength) + .pattern(pattern) + + .items(items) + .maxItems(maxItems) + .minItems(minItems) + .uniqueItems(uniqueItems) + + .required(required) + .additionalProperties(additionalProperties) + .maxProperties(maxProperties) + .minProperties(minProperties) + .propertyNames(propertyNames) + + .allOf(allOf) + .anyOf(anyOf) + .oneOf(oneOf) + .not(not) + + .title(title) + .description(description) + .format(format) + .readOnly(readOnly) + .writeOnly(writeOnly) + .comment(comment) + .examples(examples) + .deprecated(deprecated) + + .contentEncoding(contentEncoding) + .contentMediaType(contentMediaType); properties.forEach(builder::putProperty); patternProperties.forEach(builder::putPatternProperty); extensions.forEach(builder::putExtension); @@ -1011,7 +1011,7 @@ Builder applyNode(String key, Node node) { break; case "intEnum": this.intEnumValues( - node.expectArrayNode().getElementsAs((e) -> e.expectNumberNode().getValue().intValue()) + node.expectArrayNode().getElementsAs((e) -> e.expectNumberNode().getValue().intValue()) ); break; case "const": @@ -1067,8 +1067,8 @@ Builder applyNode(String key, Node node) { break; case "properties": node.expectObjectNode() - .getMembers() - .forEach((k, v) -> this.putProperty(k.getValue(), Schema.fromNode(v))); + .getMembers() + .forEach((k, v) -> this.putProperty(k.getValue(), Schema.fromNode(v))); break; case "additionalProperties": this.additionalProperties(Schema.fromNode(node)); @@ -1078,8 +1078,8 @@ Builder applyNode(String key, Node node) { break; case "patternProperties": node.expectObjectNode() - .getMembers() - .forEach((k, v) -> this.putPatternProperty(k.getValue(), Schema.fromNode(v))); + .getMembers() + .forEach((k, v) -> this.putPatternProperty(k.getValue(), Schema.fromNode(v))); break; case "allOf": this.allOf(node.expectArrayNode().getElementsAs(Schema::fromNode)); diff --git a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/SchemaComparator.java b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/SchemaComparator.java index b79280ceb2f..d901fcb0ddb 100644 --- a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/SchemaComparator.java +++ b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/SchemaComparator.java @@ -15,56 +15,56 @@ */ final class SchemaComparator implements Comparator, Serializable { private static final List ORDERED_KEYS = Arrays.asList( - // Document: - "$schema", - "$id", + // Document: + "$schema", + "$id", - // Schemas - "$ref", - "type", - "enum", - "const", + // Schemas + "$ref", + "type", + "enum", + "const", - "multipleOf", - "maximum", - "exclusiveMaximum", - "minimum", - "exclusiveMinimum", + "multipleOf", + "maximum", + "exclusiveMaximum", + "minimum", + "exclusiveMinimum", - "maxLength", - "minLength", - "pattern", + "maxLength", + "minLength", + "pattern", - "items", - "maxItems", - "minItems", - "uniqueItems", + "items", + "maxItems", + "minItems", + "uniqueItems", - "maxProperties", - "minProperties", - "required", - "properties", - "additionalProperties", - "propertyNames", + "maxProperties", + "minProperties", + "required", + "properties", + "additionalProperties", + "propertyNames", - "allOf", - "anyOf", - "oneOf", - "not", + "allOf", + "anyOf", + "oneOf", + "not", - "title", - "description", - "format", - "readOnly", - "writeOnly", - "comment", - "examples", + "title", + "description", + "format", + "readOnly", + "writeOnly", + "comment", + "examples", - "contentEncoding", - "contentMediaType", + "contentEncoding", + "contentMediaType", - // Document: Always place definitions after the root node. - "definitions" + // Document: Always place definitions after the root node. + "definitions" ); @Override diff --git a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/SchemaDocument.java b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/SchemaDocument.java index a27d61051d9..dbc084de958 100644 --- a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/SchemaDocument.java +++ b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/SchemaDocument.java @@ -61,20 +61,20 @@ public Node toNode() { } else { NodePointer pointer = parseCheckedPointer(entry.getKey()); definitionNode = pointer - .addWithIntermediateValues(definitionNode, entry.getValue().toNode()) - .expectObjectNode(); + .addWithIntermediateValues(definitionNode, entry.getValue().toNode()) + .expectObjectNode(); } } } return Node.objectNodeBuilder() - .withOptionalMember("$id", getIdKeyword().map(Node::from)) - .withOptionalMember("$schema", getSchemaKeyword().map(Node::from)) - .merge(rootSchema.toNode().expectObjectNode()) - .merge(extensions) - .merge(definitionNode) - .build() - .withDeepSortedKeys(new SchemaComparator()); + .withOptionalMember("$id", getIdKeyword().map(Node::from)) + .withOptionalMember("$schema", getSchemaKeyword().map(Node::from)) + .merge(rootSchema.toNode().expectObjectNode()) + .merge(extensions) + .merge(definitionNode) + .build() + .withDeepSortedKeys(new SchemaComparator()); } private NodePointer parseCheckedPointer(String pointer) { @@ -88,10 +88,10 @@ private NodePointer parseCheckedPointer(String pointer) { @Override public Builder toBuilder() { Builder builder = builder() - .idKeyword(idKeyword) - .schemaKeyword(schemaKeyword) - .rootSchema(rootSchema) - .extensions(extensions); + .idKeyword(idKeyword) + .schemaKeyword(schemaKeyword) + .rootSchema(rootSchema) + .extensions(extensions); definitions.forEach(builder::putDefinition); return builder; } @@ -205,10 +205,10 @@ public boolean equals(Object o) { SchemaDocument that = (SchemaDocument) o; return Objects.equals(idKeyword, that.idKeyword) - && Objects.equals(schemaKeyword, that.schemaKeyword) - && rootSchema.equals(that.rootSchema) - && definitions.equals(that.definitions) - && extensions.equals(that.extensions); + && Objects.equals(schemaKeyword, that.schemaKeyword) + && rootSchema.equals(that.rootSchema) + && definitions.equals(that.definitions) + && extensions.equals(that.extensions); } @Override diff --git a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/DeconflictingStrategyTest.java b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/DeconflictingStrategyTest.java index b5ac2ee21b4..81faf862fb0 100644 --- a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/DeconflictingStrategyTest.java +++ b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/DeconflictingStrategyTest.java @@ -33,7 +33,7 @@ public void canDeconflictNamesWhereListsAreActuallyDifferent() { PropertyNamingStrategy propertyNamingStrategy = PropertyNamingStrategy.createDefaultStrategy(); RefStrategy strategy = RefStrategy - .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); + .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); assertThat(strategy.toPointer(a.getId()), equalTo("#/definitions/Page")); assertThat(strategy.toPointer(b.getId()), equalTo("#/definitions/PageComFoo")); } @@ -55,7 +55,7 @@ public void deconflictingStrategyPassesThroughToDelegate() { Model model = Model.builder().build(); PropertyNamingStrategy propertyNamingStrategy = PropertyNamingStrategy.createDefaultStrategy(); RefStrategy strategy = RefStrategy - .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); + .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); assertThat(strategy.toPointer(ShapeId.from("com.foo#Nope")), equalTo("#/definitions/Nope")); } @@ -78,10 +78,10 @@ public void doesNotDetectUnitConflictsWhenPreludeUnitIsFiltered() { PropertyNamingStrategy propertyNamingStrategy = PropertyNamingStrategy.createDefaultStrategy(); RefStrategy.createDefaultStrategy( - model, - new JsonSchemaConfig(), - propertyNamingStrategy, - new JsonSchemaConverter.FilterPreludeUnit(false) + model, + new JsonSchemaConfig(), + propertyNamingStrategy, + new JsonSchemaConverter.FilterPreludeUnit(false) ); } @@ -94,10 +94,10 @@ public void detectsUnitConflictsWithNonPreludeUnitsNoMatterWhat() { Assertions.assertThrows(ConflictingShapeNameException.class, () -> { RefStrategy.createDefaultStrategy( - model, - new JsonSchemaConfig(), - propertyNamingStrategy, - new JsonSchemaConverter.FilterPreludeUnit(false) + model, + new JsonSchemaConfig(), + propertyNamingStrategy, + new JsonSchemaConverter.FilterPreludeUnit(false) ); }); } @@ -108,7 +108,7 @@ public void excludesPrivatePreludeShapes() { Model model = Model.assembler().addShapes(a).assemble().unwrap(); PropertyNamingStrategy propertyNamingStrategy = PropertyNamingStrategy.createDefaultStrategy(); RefStrategy strategy = RefStrategy - .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); + .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); assertThat(strategy.toPointer(a.getId()), equalTo("#/definitions/Severity")); } @@ -116,22 +116,22 @@ public void excludesPrivatePreludeShapes() { public void excludesTraitDefinitions() { StringShape member = StringShape.builder().id("com.foo#String").build(); StructureShape matcher = StructureShape.builder() - .id("com.foo#Matcher") - .addMember("member", member.getId()) - .build(); + .id("com.foo#Matcher") + .addMember("member", member.getId()) + .build(); StructureShape matcherForTrait = StructureShape.builder() - .id("com.bar#Matcher") - .addTrait(new PrivateTrait()) - .build(); + .id("com.bar#Matcher") + .addTrait(new PrivateTrait()) + .build(); StructureShape trait = StructureShape.builder() - .id("com.bar#Trait") - .addTrait(TraitDefinition.builder().build()) - .addMember("matcher", matcherForTrait.toShapeId()) - .build(); + .id("com.bar#Trait") + .addTrait(TraitDefinition.builder().build()) + .addMember("matcher", matcherForTrait.toShapeId()) + .build(); Model model = Model.assembler().addShapes(trait, matcherForTrait, matcher, member).assemble().unwrap(); PropertyNamingStrategy propertyNamingStrategy = PropertyNamingStrategy.createDefaultStrategy(); RefStrategy strategy = RefStrategy - .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); + .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); assertThat(strategy.toPointer(matcher.getId()), equalTo("#/definitions/Matcher")); } } diff --git a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/DefaultRefStrategyTest.java b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/DefaultRefStrategyTest.java index a2171e6ee34..daf8cb3a8de 100644 --- a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/DefaultRefStrategyTest.java +++ b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/DefaultRefStrategyTest.java @@ -24,10 +24,10 @@ public class DefaultRefStrategyTest { @Test public void usesDefaultPointer() { RefStrategy ref = RefStrategy.createDefaultStrategy( - Model.builder().build(), - new JsonSchemaConfig(), - propertyNamingStrategy, - alwaysTrue() + Model.builder().build(), + new JsonSchemaConfig(), + propertyNamingStrategy, + alwaysTrue() ); String pointer = ref.toPointer(ShapeId.from("smithy.example#Foo")); @@ -39,7 +39,7 @@ public void usesCustomPointerAndAppendsSlashWhenNecessary() { JsonSchemaConfig config = new JsonSchemaConfig(); config.setDefinitionPointer("#/components/schemas"); RefStrategy ref = RefStrategy - .createDefaultStrategy(Model.builder().build(), config, propertyNamingStrategy, alwaysTrue()); + .createDefaultStrategy(Model.builder().build(), config, propertyNamingStrategy, alwaysTrue()); String pointer = ref.toPointer(ShapeId.from("smithy.example#Foo")); assertThat(pointer, equalTo("#/components/schemas/Foo")); @@ -50,7 +50,7 @@ public void usesCustomPointerAndOmitsSlashWhenNecessary() { JsonSchemaConfig config = new JsonSchemaConfig(); config.setDefinitionPointer("#/components/schemas"); RefStrategy ref = RefStrategy - .createDefaultStrategy(Model.builder().build(), config, propertyNamingStrategy, alwaysTrue()); + .createDefaultStrategy(Model.builder().build(), config, propertyNamingStrategy, alwaysTrue()); String pointer = ref.toPointer(ShapeId.from("smithy.example#Foo")); assertThat(pointer, equalTo("#/components/schemas/Foo")); @@ -61,7 +61,7 @@ public void stripsNonAlphanumericCharactersWhenRequested() { JsonSchemaConfig config = new JsonSchemaConfig(); config.setAlphanumericOnlyRefs(true); RefStrategy ref = RefStrategy - .createDefaultStrategy(Model.builder().build(), config, propertyNamingStrategy, alwaysTrue()); + .createDefaultStrategy(Model.builder().build(), config, propertyNamingStrategy, alwaysTrue()); String pointer = ref.toPointer(ShapeId.from("smithy.example#Foo_Bar")); assertThat(pointer, equalTo("#/definitions/FooBar")); @@ -71,16 +71,16 @@ public void stripsNonAlphanumericCharactersWhenRequested() { public void addsListAndSetMembers() { StringShape string = StringShape.builder().id("foo.bar#String").build(); MemberShape member = MemberShape.builder() - .id("foo.bar#Scripts$member") - .target("foo.bar#String") - .build(); + .id("foo.bar#Scripts$member") + .target("foo.bar#String") + .build(); ListShape list = ListShape.builder() - .id("foo.bar#Scripts") - .member(member) - .build(); + .id("foo.bar#Scripts") + .member(member) + .build(); Model model = Model.builder().addShapes(string, list, member).build(); RefStrategy ref = RefStrategy - .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); + .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); String pointer = ref.toPointer(member.getId()); assertThat(pointer, equalTo("#/definitions/Scripts/items")); @@ -90,21 +90,21 @@ public void addsListAndSetMembers() { public void addsMapMembers() { StringShape string = StringShape.builder().id("foo.bar#String").build(); MemberShape key = MemberShape.builder() - .id("foo.bar#Scripts$key") - .target("foo.bar#String") - .build(); + .id("foo.bar#Scripts$key") + .target("foo.bar#String") + .build(); MemberShape value = MemberShape.builder() - .id("foo.bar#Scripts$value") - .target("foo.bar#String") - .build(); + .id("foo.bar#Scripts$value") + .target("foo.bar#String") + .build(); MapShape map = MapShape.builder() - .id("foo.bar#Scripts") - .key(key) - .value(value) - .build(); + .id("foo.bar#Scripts") + .key(key) + .value(value) + .build(); Model model = Model.builder().addShapes(string, map, key, value).build(); RefStrategy ref = RefStrategy - .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); + .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); assertThat(ref.toPointer(key.getId()), equalTo("#/definitions/Scripts/propertyNames")); assertThat(ref.toPointer(value.getId()), equalTo("#/definitions/Scripts/additionalProperties")); @@ -114,16 +114,16 @@ public void addsMapMembers() { public void addsStructureMembers() { StringShape string = StringShape.builder().id("foo.bar#String").build(); MemberShape member = MemberShape.builder() - .id("foo.bar#Scripts$pages") - .target("foo.bar#String") - .build(); + .id("foo.bar#Scripts$pages") + .target("foo.bar#String") + .build(); StructureShape struct = StructureShape.builder() - .id("foo.bar#Scripts") - .addMember(member) - .build(); + .id("foo.bar#Scripts") + .addMember(member) + .build(); Model model = Model.builder().addShapes(string, struct, member).build(); RefStrategy ref = RefStrategy - .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); + .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); assertThat(ref.toPointer(struct.getId()), equalTo("#/definitions/Scripts")); assertThat(ref.toPointer(member.getId()), equalTo("#/definitions/Scripts/properties/pages")); @@ -132,15 +132,15 @@ public void addsStructureMembers() { @Test public void usesRefForStructureMembers() { StructureShape baz = StructureShape.builder() - .id("foo.bar#Baz") - .addMember("bam", ShapeId.from("foo.bar#Bam")) - .build(); + .id("foo.bar#Baz") + .addMember("bam", ShapeId.from("foo.bar#Bam")) + .build(); StructureShape bam = StructureShape.builder() - .id("foo.bar#Bam") - .build(); + .id("foo.bar#Bam") + .build(); Model model = Model.builder().addShapes(baz, bam).build(); RefStrategy ref = RefStrategy - .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); + .createDefaultStrategy(model, new JsonSchemaConfig(), propertyNamingStrategy, alwaysTrue()); assertThat(ref.toPointer(baz.getMember("bam").get().getId()), equalTo("#/definitions/Bam")); } @@ -148,9 +148,9 @@ public void usesRefForStructureMembers() { @Test public void usesServiceRenames() { Model model = Model.assembler() - .addImport(getClass().getResource("service-renames.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("service-renames.json")) + .assemble() + .unwrap(); JsonSchemaConfig config = new JsonSchemaConfig(); config.setService(ShapeId.from("smithy.example#MyService")); RefStrategy ref = RefStrategy.createDefaultStrategy(model, config, propertyNamingStrategy, alwaysTrue()); diff --git a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/JsonSchemaConverterTest.java b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/JsonSchemaConverterTest.java index 0e50645fb21..1dbf109e361 100644 --- a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/JsonSchemaConverterTest.java +++ b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/JsonSchemaConverterTest.java @@ -62,9 +62,9 @@ public class JsonSchemaConverterTest { @Test public void dealsWithRecursion() { Model model = Model.assembler() - .addImport(getClass().getResource("recursive.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("recursive.json")) + .assemble() + .unwrap(); SchemaDocument document = JsonSchemaConverter.builder().model(model).build().convert(); assertThat(document.getDefinitions().keySet(), not(empty())); } @@ -72,15 +72,15 @@ public void dealsWithRecursion() { @Test public void integrationTestV07() { Model model = Model.assembler() - .addImport(getClass().getResource("test-service.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("test-service.json")) + .assemble() + .unwrap(); SchemaDocument document = JsonSchemaConverter.builder().model(model).build().convert(); assertThat(document.getDefinitions().keySet(), not(empty())); Node expected = Node.parse( - IoUtils.toUtf8String(getClass().getResourceAsStream("test-service.jsonschema.v07.json")) + IoUtils.toUtf8String(getClass().getResourceAsStream("test-service.jsonschema.v07.json")) ); Node.assertEquals(document.toNode(), expected); } @@ -88,22 +88,22 @@ public void integrationTestV07() { @Test public void integrationTestV2020_12() { Model model = Model.assembler() - .addImport(getClass().getResource("test-service.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("test-service.json")) + .assemble() + .unwrap(); JsonSchemaConfig testConfig = new JsonSchemaConfig(); testConfig.setJsonSchemaVersion(JsonSchemaVersion.DRAFT2020_12); SchemaDocument document = JsonSchemaConverter.builder() - .config(testConfig) - .model(model) - .build() - .convert(); + .config(testConfig) + .model(model) + .build() + .convert(); assertThat(document.getDefinitions().keySet(), not(empty())); Node expected = Node.parse( - IoUtils.toUtf8String(getClass().getResourceAsStream("test-service.jsonschema.v2020.json")) + IoUtils.toUtf8String(getClass().getResourceAsStream("test-service.jsonschema.v2020.json")) ); Node.assertEquals(document.toNode(), expected); } @@ -111,19 +111,19 @@ public void integrationTestV2020_12() { @Test public void canConvertShapesThatAreOnlyInTheClosureOfShape() { Model model = Model.assembler() - .addImport(getClass().getResource("multiple-closures.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("multiple-closures.json")) + .assemble() + .unwrap(); SchemaDocument document1 = JsonSchemaConverter.builder() - .model(model) - .rootShape(ShapeId.from("com.foo#StructureA")) - .build() - .convert(); + .model(model) + .rootShape(ShapeId.from("com.foo#StructureA")) + .build() + .convert(); SchemaDocument document2 = JsonSchemaConverter.builder() - .model(model) - .rootShape(ShapeId.from("com.foo#StructureB")) - .build() - .convert(); + .model(model) + .rootShape(ShapeId.from("com.foo#StructureB")) + .build() + .convert(); assertThat(document1.getDefinitions().keySet(), containsInAnyOrder("#/definitions/ReferencedA")); assertThat(document2.getDefinitions().keySet(), containsInAnyOrder("#/definitions/ReferencedB")); @@ -132,26 +132,26 @@ public void canConvertShapesThatAreOnlyInTheClosureOfShape() { @Test public void canConvertShapesThatHaveConflictsOutsideOfClosure() { Model model = Model.assembler() - .addImport(getClass().getResource("multiple-closures-with-conflicting-shapes.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("multiple-closures-with-conflicting-shapes.json")) + .assemble() + .unwrap(); JsonSchemaConfig config1 = new JsonSchemaConfig(); config1.setService(ShapeId.from("com.foo#ServiceA")); SchemaDocument document1 = JsonSchemaConverter.builder() - .model(model) - .rootShape(ShapeId.from("com.foo#ServiceA")) - .config(config1) - .build() - .convert(); + .model(model) + .rootShape(ShapeId.from("com.foo#ServiceA")) + .config(config1) + .build() + .convert(); JsonSchemaConfig config2 = new JsonSchemaConfig(); config2.setService(ShapeId.from("com.bar#ServiceB")); SchemaDocument document2 = JsonSchemaConverter.builder() - .model(model) - .rootShape(ShapeId.from("com.bar#ServiceB")) - .config(config2) - .build() - .convert(); + .model(model) + .rootShape(ShapeId.from("com.bar#ServiceB")) + .config(config2) + .build() + .convert(); Schema string1Def = document1.getDefinitions().get("#/definitions/ConflictString"); assertNotNull(string1Def); @@ -166,14 +166,14 @@ public void canConvertShapesThatHaveConflictsOutsideOfClosure() { public void canFilterShapesWithCustomPredicate() { Predicate predicate = shape -> !shape.getId().getName().equals("Foo"); Model model = Model.builder() - .addShape(StructureShape.builder().id("smithy.example#Foo").build()) - .addShape(StructureShape.builder().id("smithy.example#Baz").build()) - .build(); + .addShape(StructureShape.builder().id("smithy.example#Foo").build()) + .addShape(StructureShape.builder().id("smithy.example#Baz").build()) + .build(); SchemaDocument doc = JsonSchemaConverter.builder() - .shapePredicate(predicate) - .model(model) - .build() - .convert(); + .shapePredicate(predicate) + .model(model) + .build() + .convert(); assertFalse(doc.getDefinition("#/definitions/Foo").isPresent()); assertTrue(doc.getDefinition("#/definitions/Baz").isPresent()); @@ -184,22 +184,22 @@ public void canUseCustomPropertyNamingStrategy() { StringShape string = StringShape.builder().id("smithy.example#String").build(); MemberShape member = MemberShape.builder().id("smithy.example#Foo$bar").target(string).build(); StructureShape struct = StructureShape.builder() - .id("smithy.example#Foo") - .addMember(member) - .build(); + .id("smithy.example#Foo") + .addMember(member) + .build(); Model model = Model.builder().addShapes(struct, member, string).build(); PropertyNamingStrategy strategy = (container, memberShape, conf) -> { return memberShape.getMemberName().toUpperCase(Locale.US); }; SchemaDocument doc = JsonSchemaConverter.builder() - .propertyNamingStrategy(strategy) - .model(model) - .build() - .convert(); + .propertyNamingStrategy(strategy) + .model(model) + .build() + .convert(); assertThat( - doc.getDefinition("#/definitions/Foo").get().getProperties().keySet(), - contains("BAR") + doc.getDefinition("#/definitions/Foo").get().getProperties().keySet(), + contains("BAR") ); } @@ -240,8 +240,8 @@ public Schema.Builder updateSchema(JsonSchemaMapperContext context, Schema.Build @Test public void excludesServiceShapes() { Model model = Model.builder() - .addShape(ServiceShape.builder().id("smithy.example#Service").version("X").build()) - .build(); + .addShape(ServiceShape.builder().id("smithy.example#Service").version("X").build()) + .build(); SchemaDocument doc = JsonSchemaConverter.builder().model(model).build().convert(); assertThat(doc.getDefinitions().keySet(), empty()); @@ -250,8 +250,8 @@ public void excludesServiceShapes() { @Test public void excludesPrivateShapes() { Model model = Model.builder() - .addShape(StringShape.builder().id("smithy.example#String").addTrait(new PrivateTrait()).build()) - .build(); + .addShape(StringShape.builder().id("smithy.example#String").addTrait(new PrivateTrait()).build()) + .build(); SchemaDocument doc = JsonSchemaConverter.builder().model(model).build().convert(); assertThat(doc.getDefinitions().keySet(), empty()); @@ -289,22 +289,22 @@ public void convertsBlobToString() { @Test public void convertsNumbersToNumber() { List shapes = ListUtils.of( - ByteShape.builder().id("smithy.example#Number").build(), - ShortShape.builder().id("smithy.example#Number").build(), - IntegerShape.builder().id("smithy.example#Number").build(), - LongShape.builder().id("smithy.example#Number").build(), - FloatShape.builder().id("smithy.example#Number").build(), - DoubleShape.builder().id("smithy.example#Number").build(), - BigIntegerShape.builder().id("smithy.example#Number").build(), - BigDecimalShape.builder().id("smithy.example#Number").build() + ByteShape.builder().id("smithy.example#Number").build(), + ShortShape.builder().id("smithy.example#Number").build(), + IntegerShape.builder().id("smithy.example#Number").build(), + LongShape.builder().id("smithy.example#Number").build(), + FloatShape.builder().id("smithy.example#Number").build(), + DoubleShape.builder().id("smithy.example#Number").build(), + BigIntegerShape.builder().id("smithy.example#Number").build(), + BigDecimalShape.builder().id("smithy.example#Number").build() ); for (Shape shape : shapes) { Model model = Model.builder().addShape(shape).build(); SchemaDocument document = JsonSchemaConverter.builder() - .model(model) - .build() - .convertShape(shape); + .model(model) + .build() + .convertShape(shape); assertThat(document.getRootSchema().getType().get(), equalTo("number")); } @@ -315,17 +315,17 @@ public void convertsIntegersWhenConfigSet() { JsonSchemaConfig config = new JsonSchemaConfig(); config.setUseIntegerType(true); Model model = Model.assembler() - .addImport(getClass().getResource("integer-types.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("integer-types.smithy")) + .assemble() + .unwrap(); SchemaDocument document = JsonSchemaConverter.builder() - .model(model) - .config(config) - .build() - .convert(); + .model(model) + .config(config) + .build() + .convert(); Node expected = Node.parse( - IoUtils.toUtf8String(getClass().getResourceAsStream("integer-types.jsonschema.v07.json")) + IoUtils.toUtf8String(getClass().getResourceAsStream("integer-types.jsonschema.v07.json")) ); Node.assertEquals(document.toNode(), expected); } @@ -333,14 +333,14 @@ public void convertsIntegersWhenConfigSet() { @Test public void supportsRangeTrait() { IntegerShape shape = IntegerShape.builder() - .id("smithy.example#Number") - .addTrait(RangeTrait.builder().min(BigDecimal.valueOf(10)).max(BigDecimal.valueOf(100)).build()) - .build(); + .id("smithy.example#Number") + .addTrait(RangeTrait.builder().min(BigDecimal.valueOf(10)).max(BigDecimal.valueOf(100)).build()) + .build(); Model model = Model.builder().addShape(shape).build(); SchemaDocument document = JsonSchemaConverter.builder() - .model(model) - .build() - .convertShape(shape); + .model(model) + .build() + .convertShape(shape); assertThat(document.getRootSchema().getType().get(), equalTo("number")); assertThat(document.getRootSchema().getMinimum().get(), equalTo(BigDecimal.valueOf(10))); @@ -359,9 +359,9 @@ public void convertsBooleanToBoolean() { @Test public void supportsStringLengthTrait() { StringShape shape = StringShape.builder() - .id("smithy.example#String") - .addTrait(LengthTrait.builder().min(10L).max(100L).build()) - .build(); + .id("smithy.example#String") + .addTrait(LengthTrait.builder().min(10L).max(100L).build()) + .build(); Model model = Model.builder().addShape(shape).build(); SchemaDocument document = JsonSchemaConverter.builder().model(model).build().convertShape(shape); @@ -375,21 +375,21 @@ public void supportsStringLengthTrait() { public void supportsListAndSetLengthTrait() { StringShape string = StringShape.builder().id("smithy.api#String").build(); MemberShape member = MemberShape.builder() - .id("smithy.example#Collection$member") - .target("smithy.api#String") - .addTrait(LengthTrait.builder().min(10L).max(100L).build()) - .build(); + .id("smithy.example#Collection$member") + .target("smithy.api#String") + .addTrait(LengthTrait.builder().min(10L).max(100L).build()) + .build(); List shapes = ListUtils.of( - ListShape.builder().id("smithy.example#Collection").addMember(member).build(), - SetShape.builder().id("smithy.example#Collection").addMember(member).build() + ListShape.builder().id("smithy.example#Collection").addMember(member).build(), + SetShape.builder().id("smithy.example#Collection").addMember(member).build() ); for (Shape shape : shapes) { Model model = Model.builder().addShapes(shape, string).build(); SchemaDocument document = JsonSchemaConverter.builder() - .model(model) - .build() - .convertShape(shape); + .model(model) + .build() + .convertShape(shape); Schema def = document.getRootSchema(); @@ -407,11 +407,11 @@ public void supportsMapLengthTrait() { MemberShape key = MemberShape.builder().id("smithy.example#Map$key").target("smithy.api#String").build(); MemberShape value = MemberShape.builder().id("smithy.example#Map$value").target("smithy.api#String").build(); MapShape shape = MapShape.builder() - .id("smithy.example#Map") - .key(key) - .value(value) - .addTrait(LengthTrait.builder().min(10L).max(100L).build()) - .build(); + .id("smithy.example#Map") + .key(key) + .value(value) + .addTrait(LengthTrait.builder().min(10L).max(100L).build()) + .build(); Model model = Model.builder().addShapes(string, shape, key, value).build(); SchemaDocument document = JsonSchemaConverter.builder().model(model).build().convertShape(shape); Schema schema = document.getRootSchema(); @@ -425,10 +425,10 @@ public void supportsUniqueItemsOnLists() { StringShape string = StringShape.builder().id("smithy.api#String").build(); MemberShape member = MemberShape.builder().id("smithy.example#List$member").target("smithy.api#String").build(); ListShape shape = ListShape.builder() - .id("smithy.example#List") - .addMember(member) - .addTrait(new UniqueItemsTrait()) - .build(); + .id("smithy.example#List") + .addMember(member) + .addTrait(new UniqueItemsTrait()) + .build(); Model model = Model.builder().addShapes(string, shape, member).build(); SchemaDocument document = JsonSchemaConverter.builder().model(model).build().convertShape(shape); @@ -440,9 +440,9 @@ public void supportsUniqueItemsOnLists() { public void supportsPatternTrait() { String pattern = "^[A-Z]+$"; StringShape string = StringShape.builder() - .id("smithy.api#String") - .addTrait(new PatternTrait(pattern)) - .build(); + .id("smithy.api#String") + .addTrait(new PatternTrait(pattern)) + .build(); Model model = Model.builder().addShapes(string).build(); SchemaDocument document = JsonSchemaConverter.builder().model(model).build().convertShape(string); Schema schema = document.getRootSchema(); @@ -454,9 +454,9 @@ public void supportsPatternTrait() { public void supportsMediaType() { String mediaType = "application/json"; StringShape string = StringShape.builder() - .id("smithy.api#String") - .addTrait(new MediaTypeTrait(mediaType)) - .build(); + .id("smithy.api#String") + .addTrait(new MediaTypeTrait(mediaType)) + .build(); Model model = Model.builder().addShapes(string).build(); SchemaDocument document = JsonSchemaConverter.builder().model(model).build().convertShape(string); Schema schema = document.getRootSchema(); @@ -468,9 +468,9 @@ public void supportsMediaType() { public void supportsTitle() { String title = "Hello"; StringShape string = StringShape.builder() - .id("smithy.api#String") - .addTrait(new TitleTrait(title)) - .build(); + .id("smithy.api#String") + .addTrait(new TitleTrait(title)) + .build(); Model model = Model.builder().addShapes(string).build(); SchemaDocument document = JsonSchemaConverter.builder().model(model).build().convertShape(string); Schema schema = document.getRootSchema(); @@ -482,9 +482,9 @@ public void supportsTitle() { public void supportsDocumentation() { String docs = "Hello"; StringShape string = StringShape.builder() - .id("smithy.api#String") - .addTrait(new DocumentationTrait(docs)) - .build(); + .id("smithy.api#String") + .addTrait(new DocumentationTrait(docs)) + .build(); Model model = Model.builder().addShapes(string).build(); SchemaDocument document = JsonSchemaConverter.builder().model(model).build().convertShape(string); Schema schema = document.getRootSchema(); @@ -496,9 +496,9 @@ public void supportsDocumentation() { @SuppressWarnings("deprecation") public void supportsEnum() { StringShape string = StringShape.builder() - .id("smithy.api#String") - .addTrait(EnumTrait.builder().addEnum(EnumDefinition.builder().value("foo").build()).build()) - .build(); + .id("smithy.api#String") + .addTrait(EnumTrait.builder().addEnum(EnumDefinition.builder().value("foo").build()).build()) + .build(); Model model = Model.builder().addShapes(string).build(); SchemaDocument document = JsonSchemaConverter.builder().model(model).build().convertShape(string); Schema schema = document.getRootSchema(); @@ -529,10 +529,10 @@ public void supportsUnionObject() { JsonSchemaConfig config = new JsonSchemaConfig(); config.setUnionStrategy(JsonSchemaConfig.UnionStrategy.OBJECT); SchemaDocument document = JsonSchemaConverter.builder() - .config(config) - .model(model) - .build() - .convertShape(union); + .config(config) + .model(model) + .build() + .convertShape(union); Schema schema = document.getRootSchema(); assertThat(schema.getOneOf(), empty()); @@ -549,10 +549,10 @@ public void supportsUnionStructure() { JsonSchemaConfig config = new JsonSchemaConfig(); config.setUnionStrategy(JsonSchemaConfig.UnionStrategy.STRUCTURE); SchemaDocument document = JsonSchemaConverter.builder() - .config(config) - .model(model) - .build() - .convertShape(union); + .config(config) + .model(model) + .build() + .convertShape(union); Schema schema = document.getRootSchema(); assertThat(schema.getOneOf(), empty()); @@ -585,10 +585,10 @@ public void supportsInlineMapPropertyNames() { JsonSchemaConfig config = new JsonSchemaConfig(); config.setUseInlineMaps(true); SchemaDocument document = JsonSchemaConverter.builder() - .config(config) - .model(model) - .build() - .convertShape(container); + .config(config) + .model(model) + .build() + .convertShape(container); Schema schema = document.getRootSchema(); assertThat(schema.getProperties().containsKey("map"), equalTo(true)); @@ -607,18 +607,18 @@ public void supportsMapPatternProperties() { StringShape string = StringShape.builder().id(shapeId).build(); String pattern = "[a-z]{1,16}"; StringShape key = StringShape.builder() - .id("a.b#Key") - .addTrait(new PatternTrait(pattern)) - .build(); + .id("a.b#Key") + .addTrait(new PatternTrait(pattern)) + .build(); MapShape map = MapShape.builder().id("a.b#Map").key(key.getId()).value(shapeId).build(); Model model = Model.builder().addShapes(map, key, string).build(); JsonSchemaConfig config = new JsonSchemaConfig(); config.setMapStrategy(JsonSchemaConfig.MapStrategy.PATTERN_PROPERTIES); SchemaDocument document = JsonSchemaConverter.builder() - .config(config) - .model(model) - .build() - .convertShape(map); + .config(config) + .model(model) + .build() + .convertShape(map); Schema schema = document.getRootSchema(); assertThat(schema.getPatternProperties().size(), equalTo(1)); @@ -632,9 +632,9 @@ public void supportsInlineMapPatternProperties() { StringShape string = StringShape.builder().id(shapeId).build(); String pattern = "[a-z]{1,16}"; StringShape key = StringShape.builder() - .id("a.b#Key") - .addTrait(new PatternTrait(pattern)) - .build(); + .id("a.b#Key") + .addTrait(new PatternTrait(pattern)) + .build(); MapShape map = MapShape.builder().id("a.b#Map").key(key.getId()).value(shapeId).build(); StructureShape container = StructureShape.builder().id("a.b#Container").addMember("map", map.getId()).build(); Model model = Model.builder().addShapes(container, map, key, string).build(); @@ -642,10 +642,10 @@ public void supportsInlineMapPatternProperties() { config.setUseInlineMaps(true); config.setMapStrategy(JsonSchemaConfig.MapStrategy.PATTERN_PROPERTIES); SchemaDocument document = JsonSchemaConverter.builder() - .config(config) - .model(model) - .build() - .convertShape(container); + .config(config) + .model(model) + .build() + .convertShape(container); Schema schema = document.getRootSchema(); assertThat(schema.getProperties().containsKey("map"), equalTo(true)); @@ -666,10 +666,10 @@ public void supportsMapPatternPropertiesWithDefaultPattern() { JsonSchemaConfig config = new JsonSchemaConfig(); config.setMapStrategy(JsonSchemaConfig.MapStrategy.PATTERN_PROPERTIES); SchemaDocument document = JsonSchemaConverter.builder() - .config(config) - .model(model) - .build() - .convertShape(map); + .config(config) + .model(model) + .build() + .convertShape(map); Schema schema = document.getRootSchema(); assertThat(schema.getPatternProperties().size(), equalTo(1)); @@ -680,15 +680,15 @@ public void supportsMapPatternPropertiesWithDefaultPattern() { @Test public void sensitiveTraitHasNoImpact() { StringShape string1 = StringShape.builder() - .id("smithy.api#String") - .addTrait(new SensitiveTrait()) - .build(); + .id("smithy.api#String") + .addTrait(new SensitiveTrait()) + .build(); Model model1 = Model.builder().addShapes(string1).build(); SchemaDocument document1 = JsonSchemaConverter.builder().model(model1).build().convertShape(string1); StringShape string2 = StringShape.builder() - .id("smithy.api#String") - .build(); + .id("smithy.api#String") + .build(); Model model2 = Model.builder().addShapes(string2).build(); SchemaDocument document2 = JsonSchemaConverter.builder().model(model2).build().convertShape(string2); @@ -698,13 +698,13 @@ public void sensitiveTraitHasNoImpact() { @Test public void convertingToBuilderGivesSameResult() { Model model = Model.assembler() - .addImport(getClass().getResource("test-service.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("test-service.json")) + .assemble() + .unwrap(); JsonSchemaConverter converter = JsonSchemaConverter.builder() - .model(model) - .rootShape(ShapeId.from("example.rest#RestService")) - .build(); + .model(model) + .rootShape(ShapeId.from("example.rest#RestService")) + .build(); SchemaDocument document1 = converter.convert(); SchemaDocument document2 = converter.toBuilder().build().convert(); @@ -754,12 +754,12 @@ public void setBaz(String baz) { @Test public void removesMixins() { Model model = Model.assembler() - .addImport(getClass().getResource("model-with-mixins.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("model-with-mixins.smithy")) + .assemble() + .unwrap(); JsonSchemaConverter converter = JsonSchemaConverter.builder() - .model(model) - .build(); + .model(model) + .build(); NodePointer mixin = NodePointer.parse("/definitions/Mixin"); NodePointer properties = NodePointer.parse("/definitions/UsesMixin/properties"); @@ -770,24 +770,24 @@ public void removesMixins() { // The mixin was flattened. assertThat( - properties.getValue(document.toNode()).expectObjectNode().getStringMap().keySet(), - containsInAnyOrder("foo", "baz") + properties.getValue(document.toNode()).expectObjectNode().getStringMap().keySet(), + containsInAnyOrder("foo", "baz") ); } @Test public void appliesDefaultsByDefault() { Model model = Model.assembler() - .addImport(getClass().getResource("default-values.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("default-values.smithy")) + .assemble() + .unwrap(); SchemaDocument document = JsonSchemaConverter.builder() - .model(model) - .build() - .convert(); + .model(model) + .build() + .convert(); Node expected = Node.parse( - IoUtils.toUtf8String(getClass().getResourceAsStream("default-values.jsonschema.v07.json")) + IoUtils.toUtf8String(getClass().getResourceAsStream("default-values.jsonschema.v07.json")) ); Node.assertEquals(document.toNode(), expected); } @@ -795,19 +795,19 @@ public void appliesDefaultsByDefault() { @Test public void defaultsCanBeDisabled() { Model model = Model.assembler() - .addImport(getClass().getResource("default-values.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("default-values.smithy")) + .assemble() + .unwrap(); JsonSchemaConfig config = new JsonSchemaConfig(); config.setDisableDefaultValues(true); SchemaDocument document = JsonSchemaConverter.builder() - .config(config) - .model(model) - .build() - .convert(); + .config(config) + .model(model) + .build() + .convert(); Node expected = Node.parse( - IoUtils.toUtf8String(getClass().getResourceAsStream("default-values-disabled.jsonschema.v07.json")) + IoUtils.toUtf8String(getClass().getResourceAsStream("default-values-disabled.jsonschema.v07.json")) ); Node.assertEquals(document.toNode(), expected); } @@ -815,16 +815,16 @@ public void defaultsCanBeDisabled() { @Test public void supportsIntEnumsByDefault() { Model model = Model.assembler() - .addImport(getClass().getResource("int-enums.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("int-enums.smithy")) + .assemble() + .unwrap(); SchemaDocument document = JsonSchemaConverter.builder() - .model(model) - .build() - .convert(); + .model(model) + .build() + .convert(); Node expected = Node.parse( - IoUtils.toUtf8String(getClass().getResourceAsStream("int-enums.jsonschema.v07.json")) + IoUtils.toUtf8String(getClass().getResourceAsStream("int-enums.jsonschema.v07.json")) ); Node.assertEquals(document.toNode(), expected); } @@ -832,19 +832,19 @@ public void supportsIntEnumsByDefault() { @Test public void intEnumsCanBeDisabled() { Model model = Model.assembler() - .addImport(getClass().getResource("int-enums.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("int-enums.smithy")) + .assemble() + .unwrap(); JsonSchemaConfig config = new JsonSchemaConfig(); config.setDisableIntEnums(true); SchemaDocument document = JsonSchemaConverter.builder() - .config(config) - .model(model) - .build() - .convert(); + .config(config) + .model(model) + .build() + .convert(); Node expected = Node.parse( - IoUtils.toUtf8String(getClass().getResourceAsStream("int-enums-disabled.jsonschema.v07.json")) + IoUtils.toUtf8String(getClass().getResourceAsStream("int-enums-disabled.jsonschema.v07.json")) ); Node.assertEquals(document.toNode(), expected); } @@ -853,28 +853,28 @@ public void intEnumsCanBeDisabled() { public void supportsDeprecatedTraitOnAStruct() { StringShape string = StringShape.builder().id("smithy.api#String").build(); StructureShape shape = StructureShape.builder() - .id(ShapeId.from("a.b#C")) - .addMember( - MemberShape.builder() - .id(ShapeId.from("a.b#C$member")) - .target(string.getId()) - .build() - ) - .addTrait( - DeprecatedTrait.builder() - .message("I'm deprecated") - .since("sinceVersion") - .build() - ) - .build(); + .id(ShapeId.from("a.b#C")) + .addMember( + MemberShape.builder() + .id(ShapeId.from("a.b#C$member")) + .target(string.getId()) + .build() + ) + .addTrait( + DeprecatedTrait.builder() + .message("I'm deprecated") + .since("sinceVersion") + .build() + ) + .build(); Model model = Model.builder().addShapes(shape, string).build(); JsonSchemaConfig config = new JsonSchemaConfig(); config.setJsonSchemaVersion(JsonSchemaVersion.DRAFT2020_12); SchemaDocument document = JsonSchemaConverter.builder() - .model(model) - .config(config) - .build() - .convertShape(shape); + .model(model) + .config(config) + .build() + .convertShape(shape); assertThat(document.getRootSchema().isDeprecated(), equalTo(true)); } @@ -883,28 +883,28 @@ public void supportsDeprecatedTraitOnAStruct() { public void dontAddDeprecatedTraitOnAStructWhenOldVersion() { StringShape string = StringShape.builder().id("smithy.api#String").build(); StructureShape shape = StructureShape.builder() - .id(ShapeId.from("a.b#C")) - .addMember( - MemberShape.builder() - .id(ShapeId.from("a.b#C$member")) - .target(string.getId()) - .build() - ) - .addTrait( - DeprecatedTrait.builder() - .message("I'm deprecated") - .since("sinceVersion") - .build() - ) - .build(); + .id(ShapeId.from("a.b#C")) + .addMember( + MemberShape.builder() + .id(ShapeId.from("a.b#C$member")) + .target(string.getId()) + .build() + ) + .addTrait( + DeprecatedTrait.builder() + .message("I'm deprecated") + .since("sinceVersion") + .build() + ) + .build(); Model model = Model.builder().addShapes(shape, string).build(); JsonSchemaConfig config = new JsonSchemaConfig(); config.setJsonSchemaVersion(JsonSchemaVersion.DRAFT07); SchemaDocument document = JsonSchemaConverter.builder() - .model(model) - .config(config) - .build() - .convertShape(shape); + .model(model) + .config(config) + .build() + .convertShape(shape); assertThat(document.getRootSchema().isDeprecated(), equalTo(false)); } @@ -913,28 +913,28 @@ public void dontAddDeprecatedTraitOnAStructWhenOldVersion() { public void supportsDeprecatedTraitOnAMember() { StringShape string = StringShape.builder().id("smithy.api#String").build(); StructureShape shape = StructureShape.builder() - .id(ShapeId.from("a.b#C")) - .addMember( - MemberShape.builder() - .id(ShapeId.from("a.b#C$member")) - .target(string.getId()) - .addTrait( - DeprecatedTrait.builder() - .message("I'm deprecated") - .since("sinceVersion") - .build() - ) - .build() - ) - .build(); + .id(ShapeId.from("a.b#C")) + .addMember( + MemberShape.builder() + .id(ShapeId.from("a.b#C$member")) + .target(string.getId()) + .addTrait( + DeprecatedTrait.builder() + .message("I'm deprecated") + .since("sinceVersion") + .build() + ) + .build() + ) + .build(); Model model = Model.builder().addShapes(shape, string).build(); JsonSchemaConfig config = new JsonSchemaConfig(); config.setJsonSchemaVersion(JsonSchemaVersion.DRAFT2020_12); SchemaDocument document = JsonSchemaConverter.builder() - .model(model) - .config(config) - .build() - .convertShape(shape); + .model(model) + .config(config) + .build() + .convertShape(shape); Schema memberSchema = document.getRootSchema().getProperties().get("member"); assertThat(memberSchema.isDeprecated(), equalTo(true)); @@ -944,28 +944,28 @@ public void supportsDeprecatedTraitOnAMember() { public void dontAddDeprecatedTraitOnAMemberWhenOldVersion() { StringShape string = StringShape.builder().id("smithy.api#String").build(); StructureShape shape = StructureShape.builder() - .id(ShapeId.from("a.b#C")) - .addMember( - MemberShape.builder() - .id(ShapeId.from("a.b#C$member")) - .target(string.getId()) - .addTrait( - DeprecatedTrait.builder() - .message("I'm deprecated") - .since("sinceVersion") - .build() - ) - .build() - ) - .build(); + .id(ShapeId.from("a.b#C")) + .addMember( + MemberShape.builder() + .id(ShapeId.from("a.b#C$member")) + .target(string.getId()) + .addTrait( + DeprecatedTrait.builder() + .message("I'm deprecated") + .since("sinceVersion") + .build() + ) + .build() + ) + .build(); Model model = Model.builder().addShapes(shape, string).build(); JsonSchemaConfig config = new JsonSchemaConfig(); config.setJsonSchemaVersion(JsonSchemaVersion.DRAFT07); SchemaDocument document = JsonSchemaConverter.builder() - .model(model) - .config(config) - .build() - .convertShape(shape); + .model(model) + .config(config) + .build() + .convertShape(shape); Schema memberSchema = document.getRootSchema().getProperties().get("member"); assertThat(memberSchema.isDeprecated(), equalTo(false)); @@ -974,20 +974,20 @@ public void dontAddDeprecatedTraitOnAMemberWhenOldVersion() { @Test public void canAddMemberDocumentation() { Model model = Model.assembler() - .addImport(getClass().getResource("member-documentation.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("member-documentation.smithy")) + .assemble() + .unwrap(); JsonSchemaConfig config = new JsonSchemaConfig(); config.setAddReferenceDescriptions(true); SchemaDocument document = JsonSchemaConverter.builder() - .config(config) - .model(model) - .build() - .convert(); + .config(config) + .model(model) + .build() + .convert(); Node expected = Node.parse( - IoUtils.toUtf8String(getClass().getResourceAsStream("member-documentation.jsonschema.json")) + IoUtils.toUtf8String(getClass().getResourceAsStream("member-documentation.jsonschema.json")) ); Node.assertEquals(document.toNode(), expected); } @@ -995,16 +995,16 @@ public void canAddMemberDocumentation() { @Test public void appliesTitlesCorrectly() { Model model = Model.assembler() - .addImport(getClass().getResource("title-added.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("title-added.smithy")) + .assemble() + .unwrap(); SchemaDocument document = JsonSchemaConverter.builder() - .model(model) - .build() - .convert(); + .model(model) + .build() + .convert(); Node expected = Node.parse( - IoUtils.toUtf8String(getClass().getResourceAsStream("title-added.jsonschema.v07.json")) + IoUtils.toUtf8String(getClass().getResourceAsStream("title-added.jsonschema.v07.json")) ); Node.assertEquals(document.toNode(), expected); } diff --git a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/PropertyNamingStrategyTest.java b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/PropertyNamingStrategyTest.java index 613641219c6..9bab2516efa 100644 --- a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/PropertyNamingStrategyTest.java +++ b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/PropertyNamingStrategyTest.java @@ -17,10 +17,10 @@ public class PropertyNamingStrategyTest { public void defaultStrategyUsesJsonNameTraitIfConfigured() { PropertyNamingStrategy strategy = PropertyNamingStrategy.createDefaultStrategy(); MemberShape member = MemberShape.builder() - .id("smithy.example#Structure$foo") - .target("a.b#C") - .addTrait(new JsonNameTrait("FOO")) - .build(); + .id("smithy.example#Structure$foo") + .target("a.b#C") + .addTrait(new JsonNameTrait("FOO")) + .build(); StructureShape struct = StructureShape.builder().id("smithy.example#Structure").addMember(member).build(); JsonSchemaConfig config = new JsonSchemaConfig(); config.setUseJsonName(true); @@ -33,10 +33,10 @@ public void defaultStrategyUsesJsonNameTraitIfConfigured() { public void defaultStrategyIgnoresJsonNameTraitIfNotConfigured() { PropertyNamingStrategy strategy = PropertyNamingStrategy.createDefaultStrategy(); MemberShape member = MemberShape.builder() - .id("smithy.example#Structure$foo") - .target("a.b#C") - .addTrait(new JsonNameTrait("FOO")) - .build(); + .id("smithy.example#Structure$foo") + .target("a.b#C") + .addTrait(new JsonNameTrait("FOO")) + .build(); StructureShape struct = StructureShape.builder().id("smithy.example#Structure").addMember(member).build(); JsonSchemaConfig config = new JsonSchemaConfig(); String memberName = strategy.toPropertyName(struct, member, config); @@ -59,10 +59,10 @@ public void defaultStrategyUsesMemberName() { public void memberNameStrategyUsesMemberName() { PropertyNamingStrategy strategy = PropertyNamingStrategy.createMemberNameStrategy(); MemberShape member = MemberShape.builder() - .id("smithy.example#Structure$foo") - .target("a.b#C") - .addTrait(new JsonNameTrait("FOO")) - .build(); + .id("smithy.example#Structure$foo") + .target("a.b#C") + .addTrait(new JsonNameTrait("FOO")) + .build(); StructureShape struct = StructureShape.builder().id("smithy.example#Structure").addMember(member).build(); JsonSchemaConfig config = new JsonSchemaConfig(); String memberName = strategy.toPropertyName(struct, member, config); diff --git a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/SchemaDocumentTest.java b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/SchemaDocumentTest.java index 98a63955d5d..aca738f3733 100644 --- a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/SchemaDocumentTest.java +++ b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/SchemaDocumentTest.java @@ -43,8 +43,8 @@ public void canSetSchemaKeyword() { @Test public void canSetRootSchema() { SchemaDocument document = SchemaDocument.builder() - .rootSchema(Schema.builder().type("string").build()) - .build(); + .rootSchema(Schema.builder().type("string").build()) + .build(); ObjectNode node = document.toNode().expectObjectNode(); assertThat(document.getRootSchema().getType().get(), equalTo("string")); @@ -67,17 +67,17 @@ public void canAddExtensions() { @Test public void canAddDefinitions() { SchemaDocument document = SchemaDocument.builder() - .putDefinition("#/definitions/foo", Schema.builder().type("string").build()) - .putDefinition("#/definitions/bar", Schema.builder().type("string").build()) - .build(); + .putDefinition("#/definitions/foo", Schema.builder().type("string").build()) + .putDefinition("#/definitions/bar", Schema.builder().type("string").build()) + .build(); ObjectNode node = document.toNode().expectObjectNode(); assertThat(document.getDefinitions().values(), hasSize(2)); assertTrue(document.getDefinition("#/definitions/foo").isPresent()); assertTrue(document.getDefinition("#/definitions/bar").isPresent()); assertThat( - node.getObjectMember("definitions").get().getMembers().keySet(), - containsInAnyOrder(Node.from("bar"), Node.from("foo")) + node.getObjectMember("definitions").get().getMembers().keySet(), + containsInAnyOrder(Node.from("bar"), Node.from("foo")) ); assertThat(document.toBuilder().build(), equalTo(document)); } @@ -85,8 +85,8 @@ public void canAddDefinitions() { @Test public void skipsDefinitionsNotRelative() { SchemaDocument document = SchemaDocument.builder() - .putDefinition("http://foo.com/bar", Schema.builder().type("string").build()) - .build(); + .putDefinition("http://foo.com/bar", Schema.builder().type("string").build()) + .build(); ObjectNode node = document.toNode().expectObjectNode(); assertThat(document.getDefinitions().values(), hasSize(1)); @@ -98,8 +98,8 @@ public void skipsDefinitionsNotRelative() { public void unescapesJsonPointers() { Schema schema = Schema.builder().type("string").build(); SchemaDocument document = SchemaDocument.builder() - .putDefinition("#/definitions/~foo", schema) - .build(); + .putDefinition("#/definitions/~foo", schema) + .build(); assertThat(document.getDefinition("#/definitions/~0foo"), equalTo(Optional.of(schema))); } @@ -110,8 +110,8 @@ public void retrievesNestedSchemas() { Schema array = Schema.builder().items(string).build(); Schema complex = Schema.builder().putProperty("foo", array).build(); SchemaDocument document = SchemaDocument.builder() - .putDefinition("#/definitions/complex", complex) - .build(); + .putDefinition("#/definitions/complex", complex) + .build(); assertThat(document.getDefinition("#/definitions/complex"), equalTo(Optional.of(complex))); assertThat(document.getDefinition("#/definitions/complex/properties/foo"), equalTo(Optional.of(array))); @@ -122,8 +122,8 @@ public void retrievesNestedSchemas() { public void emptyPointerReturnsRootSchema() { Schema string = Schema.builder().type("string").build(); SchemaDocument document = SchemaDocument.builder() - .rootSchema(string) - .build(); + .rootSchema(string) + .build(); assertThat(document.getDefinition(""), equalTo(Optional.of(string))); assertThat(document.getDefinition("#"), equalTo(Optional.of(string))); diff --git a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/SchemaTest.java b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/SchemaTest.java index 8e2877ba0db..a0b9f421ba2 100644 --- a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/SchemaTest.java +++ b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/SchemaTest.java @@ -29,40 +29,40 @@ public class SchemaTest { public void canRemoveSettings() { Schema.Builder builder = Schema.builder(); Set values = SetUtils.of( - "const", - "default", - "enum", - "multipleOf", - "maximum", - "exclusiveMaximum", - "minimum", - "exclusiveMinimum", - "maxLength", - "minLength", - "pattern", - "items", - "maxItems", - "minItems", - "uniqueItems", - "properties", - "additionalProperties", - "required", - "maxProperties", - "minProperties", - "propertyNames", - "allOf", - "anyOf", - "oneOf", - "not", - "title", - "description", - "format", - "readOnly", - "writeOnly", - "comment", - "contentEncoding", - "contentMediaType", - "examples" + "const", + "default", + "enum", + "multipleOf", + "maximum", + "exclusiveMaximum", + "minimum", + "exclusiveMinimum", + "maxLength", + "minLength", + "pattern", + "items", + "maxItems", + "minItems", + "uniqueItems", + "properties", + "additionalProperties", + "required", + "maxProperties", + "minProperties", + "propertyNames", + "allOf", + "anyOf", + "oneOf", + "not", + "title", + "description", + "format", + "readOnly", + "writeOnly", + "comment", + "contentEncoding", + "contentMediaType", + "examples" ); for (String value : values) { @@ -178,9 +178,9 @@ public void ignoresNegativeNumericPositions() { @Test public void maintainsPropertyOrder() { Schema schema = Schema.builder() - .putProperty("foo", Schema.builder().build()) - .putProperty("bar", Schema.builder().build()) - .build(); + .putProperty("foo", Schema.builder().build()) + .putProperty("bar", Schema.builder().build()) + .build(); assertThat(schema.getProperties().keySet(), contains("foo", "bar")); } @@ -188,13 +188,13 @@ public void maintainsPropertyOrder() { @Test public void removingPropertiesRemovesRequiredPropertiesToo() { Schema schema = Schema.builder() - .removeProperty("notThere") - .required(null) - .putProperty("foo", Schema.builder().build()) - .putProperty("bar", Schema.builder().build()) - .required(ListUtils.of("foo", "bar")) - .removeProperty("foo") - .build(); + .removeProperty("notThere") + .required(null) + .putProperty("foo", Schema.builder().build()) + .putProperty("bar", Schema.builder().build()) + .required(ListUtils.of("foo", "bar")) + .removeProperty("foo") + .build(); assertThat(schema.getProperties().keySet(), contains("bar")); assertThat(schema.getRequired(), contains("bar")); @@ -203,18 +203,18 @@ public void removingPropertiesRemovesRequiredPropertiesToo() { @Test public void mergesEnumValuesWhenConvertingToNode() { Schema schema = Schema.builder() - .enumValues(ListUtils.of("foo", "bar")) - .intEnumValues(ListUtils.of(1, 2)) - .build(); + .enumValues(ListUtils.of("foo", "bar")) + .intEnumValues(ListUtils.of(1, 2)) + .build(); ArrayNode node = schema.toNode().asObjectNode().get().expectArrayMember("enum"); assertThat( - node.getElements(), - containsInAnyOrder( - Node.from("foo"), - Node.from("bar"), - Node.from(1), - Node.from(2) - ) + node.getElements(), + containsInAnyOrder( + Node.from("foo"), + Node.from("bar"), + Node.from(1), + Node.from(2) + ) ); } } diff --git a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/SupportNonNumericFloatsTest.java b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/SupportNonNumericFloatsTest.java index 3be16addc79..176aa492dc1 100644 --- a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/SupportNonNumericFloatsTest.java +++ b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/SupportNonNumericFloatsTest.java @@ -17,24 +17,24 @@ public class SupportNonNumericFloatsTest { @Test public void addsNonNumericFloatSupport() { Model model = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("non-numeric-floats.json")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("non-numeric-floats.json")) + .assemble() + .unwrap(); JsonSchemaConfig config = new JsonSchemaConfig(); config.setSupportNonNumericFloats(true); SchemaDocument result = JsonSchemaConverter.builder() - .config(config) - .model(model) - .build() - .convert(); + .config(config) + .model(model) + .build() + .convert(); assertThat(result.getDefinitions().keySet(), not(empty())); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("non-numeric-floats.jsonschema.v07.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("non-numeric-floats.jsonschema.v07.json") + ) ); Node.assertEquals(result, expectedNode); } diff --git a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/TimestampMapperTest.java b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/TimestampMapperTest.java index 89e751afe22..521951179d4 100644 --- a/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/TimestampMapperTest.java +++ b/smithy-jsonschema/src/test/java/software/amazon/smithy/jsonschema/TimestampMapperTest.java @@ -16,9 +16,9 @@ public class TimestampMapperTest { @Test public void convertsDateTimeToStringAndDateTimeFormat() { TimestampShape shape = TimestampShape.builder() - .id("smithy.example#Timestamp") - .addTrait(new TimestampFormatTrait(TimestampFormatTrait.DATE_TIME)) - .build(); + .id("smithy.example#Timestamp") + .addTrait(new TimestampFormatTrait(TimestampFormatTrait.DATE_TIME)) + .build(); Schema schema = new TimestampMapper().updateSchema(shape, Schema.builder(), new JsonSchemaConfig()).build(); assertThat(schema.getType().get(), equalTo("string")); @@ -28,9 +28,9 @@ public void convertsDateTimeToStringAndDateTimeFormat() { @Test public void convertsHttpDateToString() { TimestampShape shape = TimestampShape.builder() - .id("smithy.example#Timestamp") - .addTrait(new TimestampFormatTrait(TimestampFormatTrait.HTTP_DATE)) - .build(); + .id("smithy.example#Timestamp") + .addTrait(new TimestampFormatTrait(TimestampFormatTrait.HTTP_DATE)) + .build(); Schema schema = new TimestampMapper().updateSchema(shape, Schema.builder(), new JsonSchemaConfig()).build(); assertThat(schema.getType().get(), equalTo("string")); @@ -40,9 +40,9 @@ public void convertsHttpDateToString() { @Test public void convertsEpochSecondsToNumber() { TimestampShape shape = TimestampShape.builder() - .id("smithy.example#Timestamp") - .addTrait(new TimestampFormatTrait(TimestampFormatTrait.EPOCH_SECONDS)) - .build(); + .id("smithy.example#Timestamp") + .addTrait(new TimestampFormatTrait(TimestampFormatTrait.EPOCH_SECONDS)) + .build(); Schema schema = new TimestampMapper().updateSchema(shape, Schema.builder(), new JsonSchemaConfig()).build(); assertThat(schema.getType().get(), equalTo("number")); @@ -52,9 +52,9 @@ public void convertsEpochSecondsToNumber() { @Test public void convertsEpochUnknownToNumber() { TimestampShape shape = TimestampShape.builder() - .id("smithy.example#Timestamp") - .addTrait(new TimestampFormatTrait("epoch-millis")) - .build(); + .id("smithy.example#Timestamp") + .addTrait(new TimestampFormatTrait("epoch-millis")) + .build(); Schema schema = new TimestampMapper().updateSchema(shape, Schema.builder(), new JsonSchemaConfig()).build(); assertThat(schema.getType().get(), equalTo("number")); @@ -75,8 +75,8 @@ public void supportsDefaultTimestampFormat() { @Test public void assumesDateTimeStringWhenNoFormatOrDefaultPresent() { TimestampShape shape = TimestampShape.builder() - .id("smithy.example#Timestamp") - .build(); + .id("smithy.example#Timestamp") + .build(); Schema schema = new TimestampMapper().updateSchema(shape, Schema.builder(), new JsonSchemaConfig()).build(); assertThat(schema.getType().get(), equalTo("string")); diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/AbbreviationNameValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/AbbreviationNameValidator.java index 5dfc4b489e5..0709fe20a01 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/AbbreviationNameValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/AbbreviationNameValidator.java @@ -65,8 +65,8 @@ private AbbreviationNameValidator(Config config) { @Override public List validate(Model model) { return model.shapes() - .flatMap(shape -> validateShapeName(model, shape)) - .collect(Collectors.toList()); + .flatMap(shape -> validateShapeName(model, shape)) + .collect(Collectors.toList()); } private Stream validateShapeName(Model model, Shape shape) { @@ -81,8 +81,8 @@ private Stream validateShapeName(Model model, Shape shape) { String descriptor = shape.isMemberShape() ? "member" : "shape"; String name = shape.asMemberShape() - .map(MemberShape::getMemberName) - .orElseGet(() -> shape.getId().getName()); + .map(MemberShape::getMemberName) + .orElseGet(() -> shape.getId().getName()); String recommendedName = createRecommendedName(name); if (recommendedName.equals(name)) { @@ -90,16 +90,16 @@ private Stream validateShapeName(Model model, Shape shape) { } return Stream.of( - danger( - shape, - format( - "%s name, `%s`, contains invalid abbreviations. Change this %s name to `%s`", - descriptor, - name, - descriptor, - recommendedName + danger( + shape, + format( + "%s name, `%s`, contains invalid abbreviations. Change this %s name to `%s`", + descriptor, + name, + descriptor, + recommendedName + ) ) - ) ); } diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/CamelCaseValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/CamelCaseValidator.java index 08c8560cccb..e2a831dff45 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/CamelCaseValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/CamelCaseValidator.java @@ -126,39 +126,39 @@ public List validate(Model model) { // Normal shapes are expected to be upper camel. model.shapes() - .filter(FunctionalUtils.not(Shape::isMemberShape)) - .filter(shape -> !shape.hasTrait(TraitDefinition.class)) - .filter(shape -> !MemberNameHandling.UPPER.getRegex().matcher(shape.getId().getName()).find()) - .map( - shape -> danger( - shape, - format( - "%s shape name, `%s`, is not %s camel case", - shape.getType(), - shape.getId().getName(), - MemberNameHandling.UPPER - ) + .filter(FunctionalUtils.not(Shape::isMemberShape)) + .filter(shape -> !shape.hasTrait(TraitDefinition.class)) + .filter(shape -> !MemberNameHandling.UPPER.getRegex().matcher(shape.getId().getName()).find()) + .map( + shape -> danger( + shape, + format( + "%s shape name, `%s`, is not %s camel case", + shape.getType(), + shape.getId().getName(), + MemberNameHandling.UPPER + ) + ) ) - ) - .forEach(events::add); + .forEach(events::add); // Trait shapes are expected to be lower camel. model.shapes() - .filter(shape -> shape.hasTrait(TraitDefinition.class)) - .filter(shape -> !shape.hasTrait(AuthDefinitionTrait.class)) - .filter(shape -> !shape.hasTrait(ProtocolDefinitionTrait.class)) - .filter(shape -> !MemberNameHandling.LOWER.getRegex().matcher(shape.getId().getName()).find()) - .map( - shape -> danger( - shape, - format( - "%s trait definition, `%s`, is not lower camel case", - shape.getType(), - shape.getId().getName() - ) + .filter(shape -> shape.hasTrait(TraitDefinition.class)) + .filter(shape -> !shape.hasTrait(AuthDefinitionTrait.class)) + .filter(shape -> !shape.hasTrait(ProtocolDefinitionTrait.class)) + .filter(shape -> !MemberNameHandling.LOWER.getRegex().matcher(shape.getId().getName()).find()) + .map( + shape -> danger( + shape, + format( + "%s trait definition, `%s`, is not lower camel case", + shape.getType(), + shape.getId().getName() + ) + ) ) - ) - .forEach(events::add); + .forEach(events::add); // First validate each service's closure's member shape member names Set seenShapes = new HashSet<>(); @@ -167,30 +167,30 @@ public List validate(Model model) { Walker walker = new Walker(model); walker.iterateShapes(serviceShape).forEachRemaining(serviceClosure::add); List memberShapes = serviceClosure.stream() - .filter(Shape::isMemberShape) - .map(shape -> (MemberShape) shape) - .collect(Collectors.toList()); + .filter(Shape::isMemberShape) + .map(shape -> (MemberShape) shape) + .collect(Collectors.toList()); events.addAll(validateCamelCasing(model, memberShapes, serviceShape.getId().getName())); seenShapes.addAll(memberShapes); } // Next get all other member shapes (ex. trait shape members) and validate per namespace grouping Map> memberShapesByNamespace = model.toSet(MemberShape.class) - .stream() - .filter(memberShape -> !seenShapes.contains(memberShape)) - .collect( - Collectors.groupingBy( - memberShape -> memberShape.getContainer().getNamespace() - ) - ); + .stream() + .filter(memberShape -> !seenShapes.contains(memberShape)) + .collect( + Collectors.groupingBy( + memberShape -> memberShape.getContainer().getNamespace() + ) + ); for (Map.Entry> memberShapeGrouping : memberShapesByNamespace.entrySet()) { events.addAll( - validateCamelCasing( - model, - memberShapeGrouping.getValue(), - memberShapeGrouping.getKey() + " namespace" - ) + validateCamelCasing( + model, + memberShapeGrouping.getValue(), + memberShapeGrouping.getKey() + " namespace" + ) ); } @@ -209,7 +209,7 @@ private List validateCamelCasing(Model model, List // Also exclude list and map members as their names are constant. Shape container = model.expectShape(memberShape.getContainer()); if (!container.isEnumShape() && !container.isIntEnumShape() - && !container.isListShape() && !container.isMapShape()) { + && !container.isListShape() && !container.isMapShape()) { if (MemberNameHandling.UPPER.getRegex().matcher(memberShape.getMemberName()).find()) { upperCamelMemberNamesCount++; } else { @@ -242,19 +242,19 @@ private List validateCamelCasing(Model model, List String finalMemberNameHandling = memberNameHandling; return violatingMemberShapes.stream() - .map( - shape -> danger( - shape, - format( - "Member shape member name, `%s`, is not %s camel case;" - + " members in the %s must all use %s camel case.", - shape.getMemberName(), - finalMemberNameHandling, - scope, - finalMemberNameHandling - ) + .map( + shape -> danger( + shape, + format( + "Member shape member name, `%s`, is not %s camel case;" + + " members in the %s must all use %s camel case.", + shape.getMemberName(), + finalMemberNameHandling, + scope, + finalMemberNameHandling + ) + ) ) - ) - .collect(Collectors.toList()); + .collect(Collectors.toList()); } } diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/InputOutputStructureReuseValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/InputOutputStructureReuseValidator.java index 5ad2019ea3f..f8c3722637f 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/InputOutputStructureReuseValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/InputOutputStructureReuseValidator.java @@ -44,40 +44,40 @@ public List validate(Model model) { } private void validateInputOutputSet( - OperationShape operation, - StructureShape input, - StructureShape output, - List events + OperationShape operation, + StructureShape input, + StructureShape output, + List events ) { if (!input.hasTrait(InputTrait.class)) { events.add( - warning( - input, - String.format( - "This structure is the input of `%s`, but it is not marked with the " - + "@input trait. The @input trait gives operations more flexibility to " - + "evolve their top-level input members in ways that would otherwise " - + "be backward incompatible.", - operation.getId() - ), - INPUT, - operation.getId().getName() - ) + warning( + input, + String.format( + "This structure is the input of `%s`, but it is not marked with the " + + "@input trait. The @input trait gives operations more flexibility to " + + "evolve their top-level input members in ways that would otherwise " + + "be backward incompatible.", + operation.getId() + ), + INPUT, + operation.getId().getName() + ) ); } if (!output.hasTrait(OutputTrait.class)) { events.add( - warning( - output, - String.format( - "This structure is the output of `%s`, but it is not marked with " - + "the @output trait.", - operation.getId() - ), - OUTPUT, - operation.getId().getName() - ) + warning( + output, + String.format( + "This structure is the output of `%s`, but it is not marked with " + + "the @output trait.", + operation.getId() + ), + OUTPUT, + operation.getId().getName() + ) ); } } diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingClientOptionalTrait.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingClientOptionalTrait.java index 784cb286186..86ae0ad4289 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingClientOptionalTrait.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingClientOptionalTrait.java @@ -91,14 +91,14 @@ public List validate(Model model) { events.add(danger(member, "@required members must also be marked with the @clientOptional trait")); } else if (config.onRequiredStructureOrUnion && isTargetingStructureOrUnion(model, member)) { events.add( - danger( - member, - "@required members that target a structure or union must be marked with " - + "the @clientOptional trait. Not using the @clientOptional trait here " - + "is risky because there is no backward compatible way to replace the " - + "@required trait with the @default trait if the member ever needs to " - + "be made optional." - ) + danger( + member, + "@required members that target a structure or union must be marked with " + + "the @clientOptional trait. Not using the @clientOptional trait here " + + "is risky because there is no backward compatible way to replace the " + + "@required trait with the @default trait if the member ever needs to " + + "be made optional." + ) ); } } diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingPaginatedTraitValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingPaginatedTraitValidator.java index 0f051daa9be..3e67746be41 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingPaginatedTraitValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingPaginatedTraitValidator.java @@ -51,26 +51,26 @@ public final class MissingPaginatedTraitValidator extends AbstractValidator { private static final Set DEFAULT_VERBS_REQUIRE = SetUtils.of("list", "search"); private static final Set DEFAULT_VERBS_SUGGEST = SetUtils.of("describe", "get"); private static final Set DEFAULT_INPUT_MEMBERS = SetUtils.of( - "maxresults", - "maxitems", - "pagesize", - "limit", - "nexttoken", - "pagetoken", - "token", - "marker" + "maxresults", + "maxitems", + "pagesize", + "limit", + "nexttoken", + "pagetoken", + "token", + "marker" ); private static final Set DEFAULT_OUTPUT_MEMBERS = SetUtils.of( - "nexttoken", - "pagetoken", - "token", - "marker", - "nextpage", - "nextpagetoken", - "position", - "nextmarker", - "paginationtoken", - "nextpagemarker" + "nexttoken", + "pagetoken", + "token", + "marker", + "nextpage", + "nextpagetoken", + "position", + "nextmarker", + "paginationtoken", + "nextpagemarker" ); public static final class Config { @@ -151,8 +151,8 @@ public Provider() { } private static final String DISCLAIMER = "Paginating operations that can return potentially unbounded lists " - + "of data helps to maintain a predictable SLA and helps to prevent " - + "operational issues in the future."; + + "of data helps to maintain a predictable SLA and helps to prevent " + + "operational issues in the future."; private final Config config; @@ -162,23 +162,23 @@ private MissingPaginatedTraitValidator(Config config) { private static Optional findMember(Collection haystack, Collection needles) { return haystack.stream() - .filter(member -> needles.contains(member.toLowerCase(Locale.US))) - .findFirst(); + .filter(member -> needles.contains(member.toLowerCase(Locale.US))) + .findFirst(); } @Override public List validate(Model model) { OperationIndex operationIndex = OperationIndex.of(model); return model.shapes(OperationShape.class) - .filter(shape -> !shape.getTrait(PaginatedTrait.class).isPresent()) - .flatMap(shape -> validateShape(model, operationIndex, shape)) - .collect(Collectors.toList()); + .filter(shape -> !shape.getTrait(PaginatedTrait.class).isPresent()) + .flatMap(shape -> validateShape(model, operationIndex, shape)) + .collect(Collectors.toList()); } private Stream validateShape( - Model model, - OperationIndex operationIndex, - OperationShape operation + Model model, + OperationIndex operationIndex, + OperationShape operation ) { List words = ValidationUtils.splitCamelCaseWord(operation.getId().getName()); String verb = words.get(0).toLowerCase(Locale.US); @@ -186,60 +186,60 @@ private Stream validateShape( // The presence of "verbsRequirePagination" immediately qualifies the operation as needing `paginated`. if (config.getVerbsRequirePagination().contains(verb)) { return Stream.of( - danger( - operation, - format( - "The verb of this operation, `%s`, requires that the operation is marked with the " - + "`paginated` trait. %s", - verb, - DISCLAIMER + danger( + operation, + format( + "The verb of this operation, `%s`, requires that the operation is marked with the " + + "`paginated` trait. %s", + verb, + DISCLAIMER + ) ) - ) ); } StructureShape input = operationIndex.expectInputShape(operation.getId()); Optional member = findMember( - input.getAllMembers().keySet(), - config.getInputMembersRequirePagination() + input.getAllMembers().keySet(), + config.getInputMembersRequirePagination() ); if (member.isPresent()) { return Stream.of( - danger( - operation, - format( - "This operation contains an input member, `%s`, that requires that the operation is " - + "marked with the `paginated` trait. %s", - member.get(), - DISCLAIMER + danger( + operation, + format( + "This operation contains an input member, `%s`, that requires that the operation is " + + "marked with the `paginated` trait. %s", + member.get(), + DISCLAIMER + ) ) - ) ); } StructureShape output = operationIndex.expectOutputShape(operation.getId()); return findMember(output.getAllMembers().keySet(), config.getOutputMembersRequirePagination()) - .map( - outputMember -> Stream.of( - danger( - operation, - format( - "This operation contains an output member, `%s`, that requires that the " - + "operation is marked with the `paginated` trait. %s", - outputMember, - DISCLAIMER + .map( + outputMember -> Stream.of( + danger( + operation, + format( + "This operation contains an output member, `%s`, that requires that the " + + "operation is marked with the `paginated` trait. %s", + outputMember, + DISCLAIMER + ) + ) ) - ) ) - ) - .orElseGet(() -> suggestPagination(verb, operation, output, model)); + .orElseGet(() -> suggestPagination(verb, operation, output, model)); } private Stream suggestPagination( - String verb, - OperationShape operation, - StructureShape output, - Model model + String verb, + OperationShape operation, + StructureShape output, + Model model ) { if (!config.getVerbsSuggestPagination().contains(verb)) { return Stream.empty(); @@ -247,26 +247,26 @@ private Stream suggestPagination( // We matched a verb, but only suggest pagination if there's a top-level output member that's a list. boolean hasListMember = output.getAllMembers() - .values() - .stream() - .map(MemberShape::getTarget) - .flatMap(id -> OptionalUtils.stream(model.getShape(id))) - .anyMatch(Shape::isListShape); + .values() + .stream() + .map(MemberShape::getTarget) + .flatMap(id -> OptionalUtils.stream(model.getShape(id))) + .anyMatch(Shape::isListShape); if (!hasListMember) { return Stream.empty(); } return Stream.of( - warning( - operation, - format( - "The verb of this operation, `%s`, and the presence of a top-level list member in its " - + "output, suggests that the operation should have the `paginated` trait. %s", - verb, - DISCLAIMER + warning( + operation, + format( + "The verb of this operation, `%s`, and the presence of a top-level list member in its " + + "output, suggests that the operation should have the `paginated` trait. %s", + verb, + DISCLAIMER + ) ) - ) ); } } diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingSensitiveTraitValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingSensitiveTraitValidator.java index 7ba294f095a..b9177efc00b 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingSensitiveTraitValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingSensitiveTraitValidator.java @@ -24,38 +24,38 @@ */ public final class MissingSensitiveTraitValidator extends AbstractValidator { static final Set DEFAULT_SENSITIVE_TERMS = SetUtils.of( - "account number", - "bank", - "billing address", - "birth", - "birth day", - "citizenship", - "credentials", - "credit card", - "csc", - "driver license", - "drivers license", - "email", - "ethnicity", - "first name", - "gender", - "insurance", - "ip address", - "last name", - "maiden name", - "mailing address", - "pass phrase", - "pass word", - "passport", - "phone", - "religion", - "secret", - "sexual orientation", - "social security", - "ssn", - "tax payer", - "telephone", - "zip code" + "account number", + "bank", + "billing address", + "birth", + "birth day", + "citizenship", + "credentials", + "credit card", + "csc", + "driver license", + "drivers license", + "email", + "ethnicity", + "first name", + "gender", + "insurance", + "ip address", + "last name", + "maiden name", + "mailing address", + "pass phrase", + "pass word", + "passport", + "phone", + "religion", + "secret", + "sexual orientation", + "social security", + "ssn", + "tax payer", + "telephone", + "zip code" ); private final WordBoundaryMatcher wordMatcher; @@ -65,7 +65,7 @@ public Provider() { super(MissingSensitiveTraitValidator.class, node -> { NodeMapper mapper = new NodeMapper(); return new MissingSensitiveTraitValidator( - mapper.deserialize(node, MissingSensitiveTraitValidator.Config.class) + mapper.deserialize(node, MissingSensitiveTraitValidator.Config.class) ); }); } @@ -100,8 +100,8 @@ private MissingSensitiveTraitValidator(Config config) { if (config.getExcludeDefaults() && config.getTerms().isEmpty()) { //This configuration combination makes the validator a no-op. throw new IllegalArgumentException( - "Cannot set 'excludeDefaults' to true and leave " - + "'terms' unspecified." + "Cannot set 'excludeDefaults' to true and leave " + + "'terms' unspecified." ); } @@ -136,24 +136,24 @@ private List scanShapes(Model model) { Shape targetShape = model.expectShape(memberShape.getTarget()); if (!containingShape.hasTrait(SensitiveTrait.class) - && !containingShape.isEnumShape() - && !targetShape.hasTrait(SensitiveTrait.class)) { + && !containingShape.isEnumShape() + && !targetShape.hasTrait(SensitiveTrait.class)) { Optional optionalValidationEvent = detectSensitiveTerms( - memberShape.getMemberName(), - memberShape + memberShape.getMemberName(), + memberShape ); optionalValidationEvent.ifPresent(validationEvents::add); } } else if (!shape.isOperationShape() - && !shape.isServiceShape() - && !shape.isResourceShape() - && !shape.hasTrait(SensitiveTrait.class)) { - Optional optionalValidationEvent = detectSensitiveTerms( - shape.toShapeId().getName(), - shape - ); - optionalValidationEvent.ifPresent(validationEvents::add); - } + && !shape.isServiceShape() + && !shape.isResourceShape() + && !shape.hasTrait(SensitiveTrait.class)) { + Optional optionalValidationEvent = detectSensitiveTerms( + shape.toShapeId().getName(), + shape + ); + optionalValidationEvent.ifPresent(validationEvents::add); + } } return validationEvents; @@ -164,16 +164,16 @@ private Optional detectSensitiveTerms(String name, Shape shape) if (matchedTerm.isPresent()) { String message = shape.isMemberShape() - ? String.format( - "This member possibly contains sensitive data but neither the enclosing nor target" - + " shape are marked with the sensitive trait (based on the presence of '%s')", - matchedTerm.get() - ) - : String.format( - "This shape possibly contains sensitive data but is not marked " - + "with the sensitive trait (based on the presence of '%s')", - matchedTerm.get() - ); + ? String.format( + "This member possibly contains sensitive data but neither the enclosing nor target" + + " shape are marked with the sensitive trait (based on the presence of '%s')", + matchedTerm.get() + ) + : String.format( + "This shape possibly contains sensitive data but is not marked " + + "with the sensitive trait (based on the presence of '%s')", + matchedTerm.get() + ); return Optional.of(warning(shape, message)); } else { return Optional.empty(); diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/NoninclusiveTermsValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/NoninclusiveTermsValidator.java index e27f45cbdde..b6772e1b22b 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/NoninclusiveTermsValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/NoninclusiveTermsValidator.java @@ -32,14 +32,14 @@ */ public final class NoninclusiveTermsValidator extends AbstractValidator { static final Map> BUILT_IN_NONINCLUSIVE_TERMS = MapUtils.of( - "master", - ListUtils.of("primary", "parent", "main"), - "slave", - ListUtils.of("secondary", "replica", "clone", "child"), - "blacklist", - ListUtils.of("denyList"), - "whitelist", - ListUtils.of("allowList") + "master", + ListUtils.of("primary", "parent", "main"), + "slave", + ListUtils.of("secondary", "replica", "clone", "child"), + "blacklist", + ListUtils.of("denyList"), + "whitelist", + ListUtils.of("allowList") ); public static final class Provider extends ValidatorService.Provider { @@ -47,7 +47,7 @@ public Provider() { super(NoninclusiveTermsValidator.class, node -> { NodeMapper mapper = new NodeMapper(); return new NoninclusiveTermsValidator( - mapper.deserialize(node, NoninclusiveTermsValidator.Config.class) + mapper.deserialize(node, NoninclusiveTermsValidator.Config.class) ); }); } @@ -92,8 +92,8 @@ private NoninclusiveTermsValidator(Config config) { if (config.getTerms().isEmpty()) { //This configuration combination makes the validator a no-op. throw new IllegalArgumentException( - "Cannot set 'excludeDefaults' to true and leave " - + "'terms' empty or unspecified." + "Cannot set 'excludeDefaults' to true and leave " + + "'terms' empty or unspecified." ); } termsMap = Collections.unmodifiableMap(config.getTerms()); @@ -138,101 +138,101 @@ private Collection getValidationEvents(TextInstance instance) { } private ValidationEvent constructValidationEvent( - TextInstance instance, - List replacements, - String matchedText + TextInstance instance, + List replacements, + String matchedText ) { String replacementAddendum = getReplacementAddendum(matchedText, replacements); switch (instance.getLocationType()) { case NAMESPACE: //Cannot use any warning() overloads because there is no shape associated with the event. return ValidationEvent.builder() - .severity(Severity.WARNING) - .sourceLocation(SourceLocation.none()) - .id( - getName() + "." + NAMESPACE + "." + instance.getText() - + "." + matchedText.toLowerCase(Locale.US) - ) - .message( - String.format( - "%s namespace uses a non-inclusive term `%s`.%s", - instance.getText(), - matchedText, - replacementAddendum + .severity(Severity.WARNING) + .sourceLocation(SourceLocation.none()) + .id( + getName() + "." + NAMESPACE + "." + instance.getText() + + "." + matchedText.toLowerCase(Locale.US) + ) + .message( + String.format( + "%s namespace uses a non-inclusive term `%s`.%s", + instance.getText(), + matchedText, + replacementAddendum + ) ) - ) - .build(); + .build(); case APPLIED_TRAIT: ValidationEvent validationEvent = warning( - instance.getShape(), - instance.getTrait().getSourceLocation(), - "" + instance.getShape(), + instance.getTrait().getSourceLocation(), + "" ); String idiomaticTraitName = Trait.getIdiomaticTraitName(instance.getTrait()); if (instance.getTraitPropertyPath().isEmpty()) { return validationEvent.toBuilder() - .message( - String.format( - "'%s' trait has a value that contains a non-inclusive term `%s`.%s", - idiomaticTraitName, - matchedText, - replacementAddendum + .message( + String.format( + "'%s' trait has a value that contains a non-inclusive term `%s`.%s", + idiomaticTraitName, + matchedText, + replacementAddendum + ) ) - ) - .id( - getName() + "." + TRAIT + "." - + matchedText.toLowerCase(Locale.US) + "." + idiomaticTraitName - ) - .build(); + .id( + getName() + "." + TRAIT + "." + + matchedText.toLowerCase(Locale.US) + "." + idiomaticTraitName + ) + .build(); } else { String valuePropertyPathFormatted = formatPropertyPath(instance.getTraitPropertyPath()); return validationEvent.toBuilder() - .message( - String.format( - "'%s' trait value at path {%s} contains a non-inclusive term `%s`.%s", - idiomaticTraitName, - valuePropertyPathFormatted, - matchedText, - replacementAddendum + .message( + String.format( + "'%s' trait value at path {%s} contains a non-inclusive term `%s`.%s", + idiomaticTraitName, + valuePropertyPathFormatted, + matchedText, + replacementAddendum + ) ) - ) - .id( - getName() + "." + TRAIT + "." + matchedText.toLowerCase(Locale.US) - + "." + idiomaticTraitName + "." + valuePropertyPathFormatted - ) - .build(); + .id( + getName() + "." + TRAIT + "." + matchedText.toLowerCase(Locale.US) + + "." + idiomaticTraitName + "." + valuePropertyPathFormatted + ) + .build(); } case SHAPE: default: return warning( - instance.getShape(), - instance.getShape().getSourceLocation(), - String.format( - "%s shape uses a non-inclusive term `%s`.%s", - StringUtils.capitalize(instance.getShape().getType().toString()), - matchedText, - replacementAddendum - ), - SHAPE, - matchedText.toLowerCase(Locale.US) + instance.getShape(), + instance.getShape().getSourceLocation(), + String.format( + "%s shape uses a non-inclusive term `%s`.%s", + StringUtils.capitalize(instance.getShape().getType().toString()), + matchedText, + replacementAddendum + ), + SHAPE, + matchedText.toLowerCase(Locale.US) ); } } private static String getReplacementAddendum(String matchedText, List replacements) { List caseCorrectedEntryValue = replacements.stream() - .map( - replacement -> Character.isUpperCase(matchedText.charAt(0)) - ? StringUtils.capitalize(replacement) - : StringUtils.uncapitalize(replacement) - ) - .collect(Collectors.toList()); + .map( + replacement -> Character.isUpperCase(matchedText.charAt(0)) + ? StringUtils.capitalize(replacement) + : StringUtils.uncapitalize(replacement) + ) + .collect(Collectors.toList()); String replacementAddendum = !replacements.isEmpty() - ? String.format( - " Consider using one of the following terms instead: %s", - ValidationUtils.tickedList(caseCorrectedEntryValue) - ) - : ""; + ? String.format( + " Consider using one of the following terms instead: %s", + ValidationUtils.tickedList(caseCorrectedEntryValue) + ) + : ""; return replacementAddendum; } diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/RepeatedShapeNameValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/RepeatedShapeNameValidator.java index a58d211cb50..b7bf5edeaf1 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/RepeatedShapeNameValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/RepeatedShapeNameValidator.java @@ -55,9 +55,9 @@ private RepeatedShapeNameValidator(Config config) { public List validate(Model model) { List events = new ArrayList<>(); model.shapes(StructureShape.class) - .forEach(shape -> events.addAll(validateNames(model, shape, shape.getMemberNames()))); + .forEach(shape -> events.addAll(validateNames(model, shape, shape.getMemberNames()))); model.shapes(UnionShape.class) - .forEach(shape -> events.addAll(validateNames(model, shape, shape.getMemberNames()))); + .forEach(shape -> events.addAll(validateNames(model, shape, shape.getMemberNames()))); return events; } @@ -65,9 +65,9 @@ private List validateNames(Model model, Shape shape, Collection String shapeName = shape.getId().getName(); String lowerCaseShapeName = shapeName.toLowerCase(Locale.US); return memberNames.stream() - .filter(memberName -> nameConflicts(lowerCaseShapeName, memberName)) - .map(memberName -> repeatedMemberName(model, shape, shapeName, memberName)) - .collect(Collectors.toList()); + .filter(memberName -> nameConflicts(lowerCaseShapeName, memberName)) + .map(memberName -> repeatedMemberName(model, shape, shapeName, memberName)) + .collect(Collectors.toList()); } private boolean nameConflicts(String lowerCaseShapeName, String memberName) { @@ -83,25 +83,25 @@ private ValidationEvent repeatedMemberName(Model model, Shape shape, String shap Shape member = model.expectShape(shape.getId().withMember(memberName)); if (config.getExactMatch()) { return warning( - member, - String.format( - "The `%s` %s shape repeats its name in the member `%s`; %2$s member names should not be " - + "equal to the %2$s name.", - shapeName, - shape.getType(), - memberName - ) + member, + String.format( + "The `%s` %s shape repeats its name in the member `%s`; %2$s member names should not be " + + "equal to the %2$s name.", + shapeName, + shape.getType(), + memberName + ) ); } else { return warning( - member, - String.format( - "The `%s` %s shape repeats its name in the member `%s`; %2$s member names should not be " - + "prefixed with the %2$s name.", - shapeName, - shape.getType(), - memberName - ) + member, + String.format( + "The `%s` %s shape repeats its name in the member `%s`; %2$s member names should not be " + + "prefixed with the %2$s name.", + shapeName, + shape.getType(), + memberName + ) ); } } diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/ReservedWordsValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/ReservedWordsValidator.java index f792aca5360..53d42e938a4 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/ReservedWordsValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/ReservedWordsValidator.java @@ -120,8 +120,8 @@ private void validate(Model model, List events) { private Optional validateShape(Shape shape) { String name = shape.asMemberShape() - .map(MemberShape::getMemberName) - .orElseGet(() -> shape.getId().getName()); + .map(MemberShape::getMemberName) + .orElseGet(() -> shape.getId().getName()); return isReservedWord(name) ? Optional.of(emit(shape, name, reason)) : Optional.empty(); } @@ -138,11 +138,11 @@ private boolean isReservedWord(String word) { private ValidationEvent emit(Shape shape, String word, String reason) { return ValidationEvent.builder() - .severity(Severity.DANGER) - .id(ValidatorService.determineValidatorName(ReservedWordsValidator.class)) - .shape(shape) - .message(format("The word `%s` is reserved. %s", word, reason)) - .build(); + .severity(Severity.DANGER) + .id(ValidatorService.determineValidatorName(ReservedWordsValidator.class)) + .shape(shape) + .message(format("The word `%s` is reserved. %s", word, reason)) + .build(); } } diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/ShouldHaveUsedTimestampValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/ShouldHaveUsedTimestampValidator.java index 020aa8df821..b6b92286de5 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/ShouldHaveUsedTimestampValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/ShouldHaveUsedTimestampValidator.java @@ -81,13 +81,13 @@ public Provider() { } private static final List DEFAULT_PATTERNS = ListUtils.of( - Pattern.compile("^.*[Tt]imestamp.*$"), // contains the string "timestamp" - Pattern.compile("^[Tt]ime([_A-Z].*)?$"), // begins with the word "time" - Pattern.compile("^[Dd]ate([_A-Z].*)?$"), // begins with the word "date" - Pattern.compile("^.*([a-z]T|_[Tt])ime$"), // ends with the word "time" - Pattern.compile("^.*([a-z]D|_[Dd])ate$"), // ends with the word "date" - Pattern.compile("^.*([a-z]A|_[Aa])t$"), // ends with the word "at" - Pattern.compile("^.*([a-z]O|_[Oo])n$") // ends with the word "on" + Pattern.compile("^.*[Tt]imestamp.*$"), // contains the string "timestamp" + Pattern.compile("^[Tt]ime([_A-Z].*)?$"), // begins with the word "time" + Pattern.compile("^[Dd]ate([_A-Z].*)?$"), // begins with the word "date" + Pattern.compile("^.*([a-z]T|_[Tt])ime$"), // ends with the word "time" + Pattern.compile("^.*([a-z]D|_[Dd])ate$"), // ends with the word "date" + Pattern.compile("^.*([a-z]A|_[Aa])t$"), // ends with the word "at" + Pattern.compile("^.*([a-z]O|_[Oo])n$") // ends with the word "on" ); private final List patterns = new ArrayList<>(DEFAULT_PATTERNS); @@ -128,58 +128,58 @@ public List enumShape(EnumShape shape) { } private List validateStructure( - StructureShape structure, - Model model + StructureShape structure, + Model model ) { return structure - .getAllMembers() - .entrySet() - .stream() - .flatMap(entry -> validateTargetShape(entry.getKey(), entry.getValue(), model)) - .collect(Collectors.toList()); + .getAllMembers() + .entrySet() + .stream() + .flatMap(entry -> validateTargetShape(entry.getKey(), entry.getValue(), model)) + .collect(Collectors.toList()); } private List validateUnion( - UnionShape union, - Model model + UnionShape union, + Model model ) { return union - .getAllMembers() - .entrySet() - .stream() - .flatMap(entry -> validateTargetShape(entry.getKey(), entry.getValue(), model)) - .collect(Collectors.toList()); + .getAllMembers() + .entrySet() + .stream() + .flatMap(entry -> validateTargetShape(entry.getKey(), entry.getValue(), model)) + .collect(Collectors.toList()); } private Stream validateTargetShape( - String name, - MemberShape memberShape, - Model model + String name, + MemberShape memberShape, + Model model ) { return OptionalUtils.stream( - model.getShape(memberShape.getTarget()) - .flatMap(targetShape -> validateName(name, targetShape, memberShape, patterns, model)) + model.getShape(memberShape.getTarget()) + .flatMap(targetShape -> validateName(name, targetShape, memberShape, patterns, model)) ); } private List validateSimpleShape( - Shape shape + Shape shape ) { String name = shape.getId().getName(); return patterns - .stream() - .filter(pattern -> pattern.matcher(name).matches()) - .map(matcher -> buildEvent(shape, name, shape.getType())) - .collect(Collectors.toList()); + .stream() + .filter(pattern -> pattern.matcher(name).matches()) + .map(matcher -> buildEvent(shape, name, shape.getType())) + .collect(Collectors.toList()); } private Optional validateName( - String name, - Shape targetShape, - Shape context, - List patterns, - Model model + String name, + Shape targetShape, + Shape context, + List patterns, + Model model ) { ShapeType type = targetShape.getType(); if (type == ShapeType.TIMESTAMP || type == ShapeType.ENUM) { @@ -190,28 +190,28 @@ private Optional validateName( } } return patterns - .stream() - .filter(pattern -> pattern.matcher(name).matches()) - .map(matcher -> buildEvent(context, name, type)) - .findAny(); + .stream() + .filter(pattern -> pattern.matcher(name).matches()) + .map(matcher -> buildEvent(context, name, type)) + .findAny(); } private boolean onlyContainsTimestamps(Shape shape, Model model) { return shape.getAllMembers() - .values() - .stream() - .map(memberShape -> model.getShape(memberShape.getTarget())) - .filter(Optional::isPresent) - .map(Optional::get) - .allMatch(Shape::isTimestampShape); + .values() + .stream() + .map(memberShape -> model.getShape(memberShape.getTarget())) + .filter(Optional::isPresent) + .map(Optional::get) + .allMatch(Shape::isTimestampShape); } private ValidationEvent buildEvent(Shape context, String name, ShapeType type) { return danger( - context, - context.isMemberShape() - ? String.format("Member `%s` is named like a timestamp but references a `%s` shape", name, type) - : String.format("Shape `%s` is named like a timestamp but is a `%s` shape.", name, type) + context, + context.isMemberShape() + ? String.format("Member `%s` is named like a timestamp but references a `%s` shape", name, type) + : String.format("Shape `%s` is named like a timestamp but is a `%s` shape.", name, type) ); } } diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/StandardOperationVerbValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/StandardOperationVerbValidator.java index 00910e8c84d..b89d82512ad 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/StandardOperationVerbValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/StandardOperationVerbValidator.java @@ -89,9 +89,9 @@ public Provider() { Config config = new NodeMapper().deserialize(node, Config.class); if (config.getVerbs().isEmpty() && config.getSuggestAlternatives().isEmpty()) { throw new SourceException( - "Either verbs or suggestAlternatives must be set when configuring " - + "StandardOperationVerb", - node + "Either verbs or suggestAlternatives must be set when configuring " + + "StandardOperationVerb", + node ); } return new StandardOperationVerbValidator(config); @@ -108,8 +108,8 @@ private StandardOperationVerbValidator(Config config) { @Override public List validate(Model model) { return model.shapes(OperationShape.class) - .flatMap(shape -> OptionalUtils.stream(validateShape(shape, config))) - .collect(Collectors.toList()); + .flatMap(shape -> OptionalUtils.stream(validateShape(shape, config))) + .collect(Collectors.toList()); } private Optional validateShape(OperationShape operation, Config config) { @@ -122,13 +122,13 @@ private Optional validateShape(OperationShape operation, Config name = words.get(0); } else if (words.size() == 1) { return Optional.of( - danger( - operation, - format( - "Operation name consists of only a verb prefix: %s", - operation.getId().getName() + danger( + operation, + format( + "Operation name consists of only a verb prefix: %s", + operation.getId().getName() + ) ) - ) ); } else { foundPrefix = words.get(0); @@ -137,25 +137,25 @@ private Optional validateShape(OperationShape operation, Config if (config.getSuggestAlternatives().containsKey(name)) { return Optional.of( - danger( - operation, - format( - "%s Consider using one of the following verbs instead: %s", - createMessagePrefix(operation, name, foundPrefix), - tickedList(config.getSuggestAlternatives().get(name)) + danger( + operation, + format( + "%s Consider using one of the following verbs instead: %s", + createMessagePrefix(operation, name, foundPrefix), + tickedList(config.getSuggestAlternatives().get(name)) + ) ) - ) ); } else if (!config.getVerbs().contains(name)) { return Optional.of( - danger( - operation, - format( - "%s Expected one of the following verbs: %s", - createMessagePrefix(operation, name, foundPrefix), - tickedList(config.getVerbs()) + danger( + operation, + format( + "%s Expected one of the following verbs: %s", + createMessagePrefix(operation, name, foundPrefix), + tickedList(config.getVerbs()) + ) ) - ) ); } else { return Optional.empty(); diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/StutteredShapeNameValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/StutteredShapeNameValidator.java index 1d628986bfe..823adc41142 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/StutteredShapeNameValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/StutteredShapeNameValidator.java @@ -30,9 +30,9 @@ public Provider() { public List validate(Model model) { List events = new ArrayList<>(); model.shapes(StructureShape.class) - .forEach(shape -> events.addAll(validateNames(model, shape, shape.getMemberNames()))); + .forEach(shape -> events.addAll(validateNames(model, shape, shape.getMemberNames()))); model.shapes(UnionShape.class) - .forEach(shape -> events.addAll(validateNames(model, shape, shape.getMemberNames()))); + .forEach(shape -> events.addAll(validateNames(model, shape, shape.getMemberNames()))); return events; } @@ -40,25 +40,25 @@ private List validateNames(Model model, Shape shape, Collection String shapeName = shape.getId().getName(); String lowerCaseShapeName = shapeName.toLowerCase(Locale.US); return memberNames.stream() - .filter(memberName -> memberName.toLowerCase(Locale.US).startsWith(lowerCaseShapeName)) - .map(memberName -> stutteredMemberName(model, shape, shapeName, memberName)) - .collect(Collectors.toList()); + .filter(memberName -> memberName.toLowerCase(Locale.US).startsWith(lowerCaseShapeName)) + .map(memberName -> stutteredMemberName(model, shape, shapeName, memberName)) + .collect(Collectors.toList()); } private ValidationEvent stutteredMemberName(Model model, Shape shape, String shapeName, String memberName) { Shape member = model.getShape(shape.getId().withMember(memberName)) - .orElseThrow( - () -> new RuntimeException("Invalid member name for shape: " + shape + ", " + memberName) - ); + .orElseThrow( + () -> new RuntimeException("Invalid member name for shape: " + shape + ", " + memberName) + ); return warning( - member, - String.format( - "The `%s` %s shape stutters its name in the member `%s`; %2$s member names should not be " - + "prefixed with the %2$s name.", - shapeName, - shape.getType(), - memberName - ) + member, + String.format( + "The `%s` %s shape stutters its name in the member `%s`; %2$s member names should not be " + + "prefixed with the %2$s name.", + shapeName, + shape.getType(), + memberName + ) ); } } diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/WordBoundaryMatcher.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/WordBoundaryMatcher.java index 6db82ab7b06..f77b10d775c 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/WordBoundaryMatcher.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/WordBoundaryMatcher.java @@ -114,7 +114,7 @@ private static String parseWordPattern(String pattern) { } } else if (!Character.isLetterOrDigit(c)) { throw new IllegalArgumentException( - "Invalid non-alphanumeric characters in word boundary search:" + pattern + "Invalid non-alphanumeric characters in word boundary search:" + pattern ); } else { previousSpace = false; diff --git a/smithy-linters/src/test/java/software/amazon/smithy/linters/WildcardMatcherTest.java b/smithy-linters/src/test/java/software/amazon/smithy/linters/WildcardMatcherTest.java index dc068d88dce..99cca205cd4 100644 --- a/smithy-linters/src/test/java/software/amazon/smithy/linters/WildcardMatcherTest.java +++ b/smithy-linters/src/test/java/software/amazon/smithy/linters/WildcardMatcherTest.java @@ -27,37 +27,37 @@ public void matchesPatterns(String text, String pattern, boolean match) { public static Stream patternProvider() { return Stream.of( - // Can't match empty or null. - Arguments.of("", "foo", false), - Arguments.of(null, "foo", false), + // Can't match empty or null. + Arguments.of("", "foo", false), + Arguments.of(null, "foo", false), - // Not a contains match - Arguments.of("foo", "*hello*", false), + // Not a contains match + Arguments.of("foo", "*hello*", false), - // Good contains matches. - Arguments.of("__accessKeyId__", "*accesskeyid*", true), - Arguments.of("accessKeyId", "*accesskeyid*", true), - Arguments.of("hello", "*hello*", true), - Arguments.of("foo_hello_there", "*hello*", true), + // Good contains matches. + Arguments.of("__accessKeyId__", "*accesskeyid*", true), + Arguments.of("accessKeyId", "*accesskeyid*", true), + Arguments.of("hello", "*hello*", true), + Arguments.of("foo_hello_there", "*hello*", true), - // Not a prefix match. - Arguments.of("foo", "hello*", false), + // Not a prefix match. + Arguments.of("foo", "hello*", false), - // Good prefix matches. - Arguments.of("accessKeyId", "accesskeyid*", true), - Arguments.of("hello", "hello*", true), - Arguments.of("hello_there", "hello*", true), + // Good prefix matches. + Arguments.of("accessKeyId", "accesskeyid*", true), + Arguments.of("hello", "hello*", true), + Arguments.of("hello_there", "hello*", true), - // Not a suffix match. - Arguments.of("foo", "*hello", false), + // Not a suffix match. + Arguments.of("foo", "*hello", false), - // Good suffix matches. - Arguments.of("accessKeyId", "*accesskeyid", true), - Arguments.of("hello", "*hello", true), - Arguments.of("well_hello", "*hello", true), + // Good suffix matches. + Arguments.of("accessKeyId", "*accesskeyid", true), + Arguments.of("hello", "*hello", true), + Arguments.of("well_hello", "*hello", true), - // An exact match. - Arguments.of("string", "string", true) + // An exact match. + Arguments.of("string", "string", true) ); } @@ -67,9 +67,9 @@ public void validatesSyntax(String invalidPattern) { WildcardMatcher matcher = new WildcardMatcher(); IllegalArgumentException e = Assertions.assertThrows( - IllegalArgumentException.class, - () -> matcher.addSearch(invalidPattern), - invalidPattern + IllegalArgumentException.class, + () -> matcher.addSearch(invalidPattern), + invalidPattern ); // All syntax errors should show the invalid pattern. @@ -78,10 +78,10 @@ public void validatesSyntax(String invalidPattern) { public static Stream invalidPatternProvider() { return Stream.of( - Arguments.of("*"), - Arguments.of("**foo"), - Arguments.of("foo*bar"), - Arguments.of("") + Arguments.of("*"), + Arguments.of("**foo"), + Arguments.of("foo*bar"), + Arguments.of("") ); } } diff --git a/smithy-linters/src/test/java/software/amazon/smithy/linters/WordBoundaryMatcherTest.java b/smithy-linters/src/test/java/software/amazon/smithy/linters/WordBoundaryMatcherTest.java index 35aa9980a50..c5576812f25 100644 --- a/smithy-linters/src/test/java/software/amazon/smithy/linters/WordBoundaryMatcherTest.java +++ b/smithy-linters/src/test/java/software/amazon/smithy/linters/WordBoundaryMatcherTest.java @@ -27,52 +27,52 @@ public void matchesPatterns(String text, String pattern, boolean match) { public static Stream patternProvider() { return Stream.of( - // Can't match empty or null. - Arguments.of("", "access key id", false), - Arguments.of(null, "access key id", false), - - // Good word matches. - Arguments.of("accessKeyId", "access key id", true), - Arguments.of("accesskeyid", "access key id", true), - Arguments.of("access_key_id", "access key id", true), - Arguments.of("access_key_ID", "access key id", true), - Arguments.of("accessKey__Id", "access key id", true), - - // Tricky word boundary matches. - Arguments.of("accessKey__Id", "access key id", true), - Arguments.of("accessKey__Id", "access key id", true), - Arguments.of("accessKey__Id", "access key id", true), - Arguments.of("accessKey__Id", "access key id", true), - Arguments.of("accessKey__Id", "access key id", true), - Arguments.of("accessKey__Id", "access key id", true), - Arguments.of("accessKey__Id", "access key id", true), - Arguments.of("access:Key:Id", "access key id", true), - Arguments.of("access Key Id", "access key id", true), - Arguments.of("access-Key-Id", "access key id", true), - Arguments.of("access.Key.Id200", "access key id", true), - Arguments.of("AccessKeyIDValue", "access key id", true), - Arguments.of("__AccessKeyIDValue__", "access key id", true), - Arguments.of("zip", "zip", true), - Arguments.of("unzip", "zip", false), - Arguments.of("zipCode", "zip", true), - - // No match because zipcode is parsed as one word. - Arguments.of("zipcode", "zip", false), - - // No match is found because "accesskey_id" is split into "accesskey id" - Arguments.of("foo accesskey_id", "access key id", false), - - // Cases where no match is found and the word counts differ. - Arguments.of("string", "this is too long to match", false), - Arguments.of("this is not a match", "no", false), - - // An exact match. - Arguments.of("string", "string", true), - - Arguments.of("foo_bar_baz", "bar", true), - Arguments.of("foo_baz_bar", "bar", true), - Arguments.of("foo_bazbar", "bar", false), - Arguments.of("bazbarbaz", "bar", false) + // Can't match empty or null. + Arguments.of("", "access key id", false), + Arguments.of(null, "access key id", false), + + // Good word matches. + Arguments.of("accessKeyId", "access key id", true), + Arguments.of("accesskeyid", "access key id", true), + Arguments.of("access_key_id", "access key id", true), + Arguments.of("access_key_ID", "access key id", true), + Arguments.of("accessKey__Id", "access key id", true), + + // Tricky word boundary matches. + Arguments.of("accessKey__Id", "access key id", true), + Arguments.of("accessKey__Id", "access key id", true), + Arguments.of("accessKey__Id", "access key id", true), + Arguments.of("accessKey__Id", "access key id", true), + Arguments.of("accessKey__Id", "access key id", true), + Arguments.of("accessKey__Id", "access key id", true), + Arguments.of("accessKey__Id", "access key id", true), + Arguments.of("access:Key:Id", "access key id", true), + Arguments.of("access Key Id", "access key id", true), + Arguments.of("access-Key-Id", "access key id", true), + Arguments.of("access.Key.Id200", "access key id", true), + Arguments.of("AccessKeyIDValue", "access key id", true), + Arguments.of("__AccessKeyIDValue__", "access key id", true), + Arguments.of("zip", "zip", true), + Arguments.of("unzip", "zip", false), + Arguments.of("zipCode", "zip", true), + + // No match because zipcode is parsed as one word. + Arguments.of("zipcode", "zip", false), + + // No match is found because "accesskey_id" is split into "accesskey id" + Arguments.of("foo accesskey_id", "access key id", false), + + // Cases where no match is found and the word counts differ. + Arguments.of("string", "this is too long to match", false), + Arguments.of("this is not a match", "no", false), + + // An exact match. + Arguments.of("string", "string", true), + + Arguments.of("foo_bar_baz", "bar", true), + Arguments.of("foo_baz_bar", "bar", true), + Arguments.of("foo_bazbar", "bar", false), + Arguments.of("bazbarbaz", "bar", false) ); } @@ -82,9 +82,9 @@ public void validatesSyntax(String invalidPattern) { WordBoundaryMatcher matcher = new WordBoundaryMatcher(); IllegalArgumentException e = Assertions.assertThrows( - IllegalArgumentException.class, - () -> matcher.addSearch(invalidPattern), - invalidPattern + IllegalArgumentException.class, + () -> matcher.addSearch(invalidPattern), + invalidPattern ); // All syntax errors should show the invalid pattern. @@ -93,11 +93,11 @@ public void validatesSyntax(String invalidPattern) { public static Stream invalidPatternProvider() { return Stream.of( - Arguments.of("foo bar"), - Arguments.of(" foo bar "), - Arguments.of(" foo"), - Arguments.of("foo_bar"), // non alphanumeric - Arguments.of("foo+bar") // non alphanumeric + Arguments.of("foo bar"), + Arguments.of(" foo bar "), + Arguments.of(" foo"), + Arguments.of("foo_bar"), // non alphanumeric + Arguments.of("foo+bar") // non alphanumeric ); } } diff --git a/smithy-model/src/jmh/java/software/amazon/smithy/model/jmh/KnowledgeIndicies.java b/smithy-model/src/jmh/java/software/amazon/smithy/model/jmh/KnowledgeIndicies.java index a5d87be3f05..27a2b869e3f 100644 --- a/smithy-model/src/jmh/java/software/amazon/smithy/model/jmh/KnowledgeIndicies.java +++ b/smithy-model/src/jmh/java/software/amazon/smithy/model/jmh/KnowledgeIndicies.java @@ -19,8 +19,8 @@ @Warmup(iterations = 3) @Measurement( - iterations = 3, - timeUnit = TimeUnit.MICROSECONDS + iterations = 3, + timeUnit = TimeUnit.MICROSECONDS ) @BenchmarkMode(Mode.AverageTime) @Fork(1) @@ -32,11 +32,11 @@ public static class IndiciesState { @Setup public void prepare() { model = Model.assembler() - .addImport(KnowledgeIndicies.class.getResource("test-model.smithy")) - .disableValidation() - .assemble() - .getResult() - .get(); + .addImport(KnowledgeIndicies.class.getResource("test-model.smithy")) + .disableValidation() + .assemble() + .getResult() + .get(); } } diff --git a/smithy-model/src/jmh/java/software/amazon/smithy/model/jmh/Selectors.java b/smithy-model/src/jmh/java/software/amazon/smithy/model/jmh/Selectors.java index 7ea82bad5a6..adbd9288f5b 100644 --- a/smithy-model/src/jmh/java/software/amazon/smithy/model/jmh/Selectors.java +++ b/smithy-model/src/jmh/java/software/amazon/smithy/model/jmh/Selectors.java @@ -27,8 +27,8 @@ @Warmup(iterations = 3) @Measurement( - iterations = 3, - timeUnit = TimeUnit.MICROSECONDS + iterations = 3, + timeUnit = TimeUnit.MICROSECONDS ) @BenchmarkMode(Mode.AverageTime) @Fork(1) @@ -46,29 +46,29 @@ public static class SelectorState { @Setup public void prepare() { model = Model.assembler() - .addImport(Selectors.class.getResource("http-model.smithy")) - .assemble() - .getResult() - .get(); + .addImport(Selectors.class.getResource("http-model.smithy")) + .assemble() + .getResult() + .get(); } private Selector createSuboptimalHttpBindingIncompatibilitySelector() { return Selector.parse( - "$service(service) ${service}\n" - + "$operations(~> operation)\n" - + ":test(${operations}[trait|http])\n" - + "${operations}\n" - + ":not([trait|http])" + "$service(service) ${service}\n" + + "$operations(~> operation)\n" + + ":test(${operations}[trait|http])\n" + + "${operations}\n" + + ":not([trait|http])" ); } private Selector createHttpBindingIncompatibilitySelector() { return Selector.parse( - "service\n" - + "$operations(~> operation)\n" - + ":test(${operations}[trait|http])\n" - + "${operations}\n" - + ":not([trait|http])" + "service\n" + + "$operations(~> operation)\n" + + ":test(${operations}[trait|http])\n" + + "${operations}\n" + + ":not([trait|http])" ); } } @@ -76,27 +76,27 @@ private Selector createHttpBindingIncompatibilitySelector() { @Benchmark public Model loadsIdlModelWithoutValidation(SelectorState state) { return Model.assembler() - .addImport(Selectors.class.getResource(state.testIdlModelLocation)) - .disableValidation() - .assemble() - .unwrap(); + .addImport(Selectors.class.getResource(state.testIdlModelLocation)) + .disableValidation() + .assemble() + .unwrap(); } @Benchmark public Model loadsIdlModelWithValidation(SelectorState state) { return Model.assembler() - .addImport(Selectors.class.getResource(state.testIdlModelLocation)) - .assemble() - .unwrap(); + .addImport(Selectors.class.getResource(state.testIdlModelLocation)) + .assemble() + .unwrap(); } @Benchmark public Model loadsJsonModelWithoutValidation(SelectorState state) { return Model.assembler() - .addImport(Selectors.class.getResource(state.testJsonModelLocation)) - .disableValidation() - .assemble() - .unwrap(); + .addImport(Selectors.class.getResource(state.testJsonModelLocation)) + .disableValidation() + .assemble() + .unwrap(); } // Benchmarks just parsing the selector. @@ -133,6 +133,6 @@ public Set evaluateHttpBindingManually(SelectorState state) { } return operations.stream().filter(shape -> !shape.hasTrait(HttpTrait.class)); }) - .collect(Collectors.toSet()); + .collect(Collectors.toSet()); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/Model.java b/smithy-model/src/main/java/software/amazon/smithy/model/Model.java index 1a09bbe7aaa..6d26248857c 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/Model.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/Model.java @@ -124,8 +124,8 @@ public static ModelAssembler assembler() { */ public static ModelAssembler assembler(ClassLoader classLoader) { return new ModelAssembler() - .traitFactory(TraitFactory.createServiceFactory(classLoader)) - .validatorFactory(ValidatorFactory.createServiceFactory(classLoader)); + .traitFactory(TraitFactory.createServiceFactory(classLoader)) + .validatorFactory(ValidatorFactory.createServiceFactory(classLoader)); } /** @@ -700,10 +700,10 @@ public Optional getShape(ShapeId id) { */ public Shape expectShape(ShapeId id) { return getShape(id).orElseThrow( - () -> new ExpectationNotMetException( - "Shape not found in model: " + id, - SourceLocation.NONE - ) + () -> new ExpectationNotMetException( + "Shape not found in model: " + id, + SourceLocation.NONE + ) ); } @@ -725,13 +725,13 @@ public T expectShape(ShapeId id, Class type) { } throw new ExpectationNotMetException( - String.format( - "Expected shape `%s` to be an instance of `%s`, but found `%s`", - id, - type.getSimpleName(), - shape.getType() - ), - shape + String.format( + "Expected shape `%s` to be an instance of `%s`, but found `%s`", + id, + type.getSimpleName(), + shape.getType() + ), + shape ); } @@ -839,8 +839,8 @@ public int hashCode() { @Override public Builder toBuilder() { return builder() - .metadata(getMetadata()) - .addShapes(this); + .metadata(getMetadata()) + .addShapes(this); } /** @@ -858,15 +858,15 @@ public T getKnowledge(Class type) { return type.getConstructor(Model.class).newInstance(this); } catch (NoSuchMethodException e) { String message = String.format( - "KnowledgeIndex for type `%s` does not expose a public constructor that accepts a Model", - type + "KnowledgeIndex for type `%s` does not expose a public constructor that accepts a Model", + type ); throw new RuntimeException(message, e); } catch (ReflectiveOperationException e) { String message = String.format( - "Unable to create a KnowledgeIndex for type `%s`: %s", - type, - e.getMessage() + "Unable to create a KnowledgeIndex for type `%s`: %s", + type, + e.getMessage() ); throw new RuntimeException(message, e); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/SourceLocation.java b/smithy-model/src/main/java/software/amazon/smithy/model/SourceLocation.java index b882bc1a676..b2019bdbba9 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/SourceLocation.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/SourceLocation.java @@ -66,8 +66,8 @@ public SourceLocation getSourceLocation() { @Override public String toString() { return filename.isEmpty() - ? String.format("[%d, %d]", line, column) - : String.format("%s [%d, %d]", filename, line, column); + ? String.format("[%d, %d]", line, column) + : String.format("%s [%d, %d]", filename, line, column); } @Override diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/BottomUpIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/BottomUpIndex.java index 96c4f60bfd6..3c0b2da2122 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/BottomUpIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/BottomUpIndex.java @@ -41,10 +41,10 @@ public BottomUpIndex(Model model) { } private void collectPaths( - Map> paths, - Deque path, - Shape current, - NeighborProvider neighborProvider + Map> paths, + Deque path, + Shape current, + NeighborProvider neighborProvider ) { for (Relationship relationship : neighborProvider.getNeighbors(current)) { Shape neighbor = relationship.expectNeighborShape(); @@ -82,8 +82,8 @@ public static BottomUpIndex of(Model model) { */ public List getAllParents(ToShapeId service, ToShapeId operationOrResource) { Map> serviceBindings = parentBindings.getOrDefault( - service.toShapeId(), - Collections.emptyMap() + service.toShapeId(), + Collections.emptyMap() ); List entities = serviceBindings.get(operationOrResource.toShapeId()); return entities == null ? Collections.emptyList() : Collections.unmodifiableList(entities); @@ -112,7 +112,7 @@ public Optional getEntityBinding(ToShapeId service, ToShapeId opera */ public Optional getResourceBinding(ToShapeId service, ToShapeId operationOrResource) { return getEntityBinding(service, operationOrResource) - .filter(ResourceShape.class::isInstance) - .map(ResourceShape.class::cast); + .filter(ResourceShape.class::isInstance) + .map(ResourceShape.class::cast); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/EventStreamIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/EventStreamIndex.java index ee6059a72e5..1f000cc9297 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/EventStreamIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/EventStreamIndex.java @@ -45,10 +45,10 @@ public static EventStreamIndex of(Model model) { } private void computeEvents( - Model model, - OperationShape operation, - StructureShape shape, - Map infoMap + Model model, + OperationShape operation, + StructureShape shape, + Map infoMap ) { for (MemberShape member : shape.getAllMembers().values()) { Shape target = model.expectShape(member.getTarget()); @@ -91,10 +91,10 @@ public Optional getOutputInfo(ToShapeId operationShape) { } private Optional createEventStreamInfo( - Model model, - OperationShape operation, - StructureShape structure, - MemberShape member + Model model, + OperationShape operation, + StructureShape structure, + MemberShape member ) { Shape eventStreamTarget = model.expectShape(member.getTarget()); @@ -112,12 +112,12 @@ private Optional createEventStreamInfo( } else { // If the event target is an invalid type, then we can't create the indexed result. LOGGER.severe( - () -> String.format( - "Skipping event stream info for %s because the %s member target %s is not a structure or union", - operation.getId(), - member.getMemberName(), - member.getTarget() - ) + () -> String.format( + "Skipping event stream info for %s because the %s member target %s is not a structure or union", + operation.getId(), + member.getMemberName(), + member.getTarget() + ) ); return Optional.empty(); } @@ -135,16 +135,16 @@ private Optional createEventStreamInfo( } return Optional.of( - new EventStreamInfo( - operation, - eventStreamTarget.expectTrait(StreamingTrait.class), - structure, - member, - eventStreamTarget, - initialMembers, - initialTargets, - events - ) + new EventStreamInfo( + operation, + eventStreamTarget.expectTrait(StreamingTrait.class), + structure, + member, + eventStreamTarget, + initialMembers, + initialTargets, + events + ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/EventStreamInfo.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/EventStreamInfo.java index 1004a282ef1..d51168548c5 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/EventStreamInfo.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/EventStreamInfo.java @@ -27,14 +27,14 @@ public final class EventStreamInfo { private final StreamingTrait streamingTrait; EventStreamInfo( - OperationShape operation, - StreamingTrait streamingTrait, - StructureShape structure, - MemberShape eventStreamMember, - Shape eventStreamTarget, - Map initialMembers, - Map initialTargets, - Map events + OperationShape operation, + StreamingTrait streamingTrait, + StructureShape structure, + MemberShape eventStreamMember, + Shape eventStreamTarget, + Map initialMembers, + Map initialTargets, + Map events ) { this.operation = operation; this.streamingTrait = streamingTrait; @@ -176,9 +176,9 @@ public boolean equals(Object o) { EventStreamInfo that = (EventStreamInfo) o; return operation.getId().equals(that.operation.getId()) - && structure.getId().equals(that.structure.getId()) - && eventStreamMember.getId().equals(that.eventStreamMember.getId()) - && initialMembers.equals(that.initialMembers); + && structure.getId().equals(that.structure.getId()) + && eventStreamMember.getId().equals(that.eventStreamMember.getId()) + && initialMembers.equals(that.initialMembers); } @Override diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/HttpBinding.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/HttpBinding.java index 346824fe7e9..1a1ceea942d 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/HttpBinding.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/HttpBinding.java @@ -72,8 +72,8 @@ public boolean equals(Object other) { } else { HttpBinding otherBinding = (HttpBinding) other; return getMember().equals(otherBinding.getMember()) - && getLocation() == otherBinding.getLocation() - && getLocationName().equals(otherBinding.getLocationName()); + && getLocation() == otherBinding.getLocation() + && getLocationName().equals(otherBinding.getLocationName()); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/HttpBindingIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/HttpBindingIndex.java index 5bd2e634899..be3e0c30a50 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/HttpBindingIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/HttpBindingIndex.java @@ -80,11 +80,11 @@ public static HttpBindingIndex of(Model model) { */ public static boolean hasHttpRequestBindings(Shape shape) { return shape.hasTrait(HttpHeaderTrait.class) - || shape.hasTrait(HttpPrefixHeadersTrait.class) - || shape.hasTrait(HttpPayloadTrait.class) - || shape.hasTrait(HttpQueryTrait.class) - || shape.hasTrait(HttpQueryParamsTrait.class) - || shape.hasTrait(HttpLabelTrait.class); + || shape.hasTrait(HttpPrefixHeadersTrait.class) + || shape.hasTrait(HttpPayloadTrait.class) + || shape.hasTrait(HttpQueryTrait.class) + || shape.hasTrait(HttpQueryParamsTrait.class) + || shape.hasTrait(HttpLabelTrait.class); } /** @@ -96,19 +96,19 @@ public static boolean hasHttpRequestBindings(Shape shape) { */ public static boolean hasHttpResponseBindings(Shape shape) { return shape.hasTrait(HttpHeaderTrait.class) - || shape.hasTrait(HttpPrefixHeadersTrait.class) - || shape.hasTrait(HttpPayloadTrait.class) - || shape.hasTrait(HttpResponseCodeTrait.class); + || shape.hasTrait(HttpPrefixHeadersTrait.class) + || shape.hasTrait(HttpPayloadTrait.class) + || shape.hasTrait(HttpResponseCodeTrait.class); } private HttpTrait getHttpTrait(ToShapeId operation) { ShapeId id = operation.toShapeId(); return getModel().getShape(id) - .orElseThrow(() -> new IllegalArgumentException(id + " is not a valid shape")) - .asOperationShape() - .orElseThrow(() -> new IllegalArgumentException(id + " is not an operation shape")) - .getTrait(HttpTrait.class) - .orElseThrow(() -> new IllegalArgumentException(id + " has no http binding trait")); + .orElseThrow(() -> new IllegalArgumentException(id + " is not a valid shape")) + .asOperationShape() + .orElseThrow(() -> new IllegalArgumentException(id + " is not an operation shape")) + .getTrait(HttpTrait.class) + .orElseThrow(() -> new IllegalArgumentException(id + " has no http binding trait")); } private Model getModel() { @@ -148,8 +148,8 @@ public int getResponseCode(ToShapeId shapeOrId) { public Map getRequestBindings(ToShapeId operationShapeOrId) { ShapeId id = operationShapeOrId.toShapeId(); return requestBindings.getOrDefault(id, Collections.emptyList()) - .stream() - .collect(Collectors.toMap(HttpBinding::getMemberName, Function.identity())); + .stream() + .collect(Collectors.toMap(HttpBinding::getMemberName, Function.identity())); } /** @@ -163,9 +163,9 @@ public Map getRequestBindings(ToShapeId operationShapeOrId) public List getRequestBindings(ToShapeId operationShapeOrId, HttpBinding.Location requestLocation) { ShapeId id = operationShapeOrId.toShapeId(); return requestBindings.getOrDefault(id, Collections.emptyList()) - .stream() - .filter(binding -> binding.getLocation() == requestLocation) - .collect(Collectors.toList()); + .stream() + .filter(binding -> binding.getLocation() == requestLocation) + .collect(Collectors.toList()); } /** @@ -178,8 +178,8 @@ public List getRequestBindings(ToShapeId operationShapeOrId, HttpBi public Map getResponseBindings(ToShapeId shapeOrId) { ShapeId id = shapeOrId.toShapeId(); return responseBindings.getOrDefault(id, Collections.emptyList()) - .stream() - .collect(Collectors.toMap(HttpBinding::getMemberName, Function.identity())); + .stream() + .collect(Collectors.toMap(HttpBinding::getMemberName, Function.identity())); } /** @@ -195,9 +195,9 @@ public Map getResponseBindings(ToShapeId shapeOrId) { public List getResponseBindings(ToShapeId shapeOrId, HttpBinding.Location bindingLocation) { ShapeId id = shapeOrId.toShapeId(); return responseBindings.getOrDefault(id, Collections.emptyList()) - .stream() - .filter(binding -> binding.getLocation() == bindingLocation) - .collect(Collectors.toList()); + .stream() + .filter(binding -> binding.getLocation() == bindingLocation) + .collect(Collectors.toList()); } /** @@ -210,28 +210,28 @@ public List getResponseBindings(ToShapeId shapeOrId, HttpBinding.Lo * @return Returns the determined timestamp format. */ public TimestampFormatTrait.Format determineTimestampFormat( - ToShapeId member, - HttpBinding.Location location, - TimestampFormatTrait.Format defaultFormat + ToShapeId member, + HttpBinding.Location location, + TimestampFormatTrait.Format defaultFormat ) { Model model = getModel(); return model.getShape(member.toShapeId()) - // Use the timestampFormat trait on the member or target if present. - .flatMap(shape -> shape.getMemberTrait(model, TimestampFormatTrait.class)) - .map(TimestampFormatTrait::getFormat) - .orElseGet(() -> { - // Determine the format based on the location. - switch (location) { - case PREFIX_HEADERS: - case HEADER: - return TimestampFormatTrait.Format.HTTP_DATE; - case QUERY: - case LABEL: - return TimestampFormatTrait.Format.DATE_TIME; - default: - return defaultFormat; - } - }); + // Use the timestampFormat trait on the member or target if present. + .flatMap(shape -> shape.getMemberTrait(model, TimestampFormatTrait.class)) + .map(TimestampFormatTrait::getFormat) + .orElseGet(() -> { + // Determine the format based on the location. + switch (location) { + case PREFIX_HEADERS: + case HEADER: + return TimestampFormatTrait.Format.HTTP_DATE; + case QUERY: + case LABEL: + return TimestampFormatTrait.Format.DATE_TIME; + default: + return defaultFormat; + } + }); } /** @@ -277,9 +277,9 @@ public Optional determineRequestContentType(ToShapeId operation, String * @return Returns the optionally resolved content-type of the request. */ public Optional determineRequestContentType( - ToShapeId operation, - String documentContentType, - String eventStreamContentType + ToShapeId operation, + String documentContentType, + String eventStreamContentType ) { Collection bindings = getRequestBindings(operation).values(); return Optional.ofNullable(determineContentType(bindings, documentContentType, eventStreamContentType)); @@ -330,18 +330,18 @@ public Optional determineResponseContentType(ToShapeId operationOrError, * @return Returns the optionally resolved content-type of the response. */ public Optional determineResponseContentType( - ToShapeId operationOrError, - String documentContentType, - String eventStreamContentType + ToShapeId operationOrError, + String documentContentType, + String eventStreamContentType ) { Collection bindings = getResponseBindings(operationOrError).values(); return Optional.ofNullable(determineContentType(bindings, documentContentType, eventStreamContentType)); } private String determineContentType( - Collection bindings, - String documentContentType, - String eventStreamContentType + Collection bindings, + String documentContentType, + String eventStreamContentType ) { Model model = getModel(); @@ -359,17 +359,17 @@ private String determineContentType( } else if (StreamingTrait.isEventStream(target)) { return eventStreamContentType; } else if (target.isDocumentShape() || target.isStructureShape() || target.isUnionShape() - || target.isListShape() || target.isMapShape()) { - // Document type and structure targets are always the document content-type. - return documentContentType; - } else if (target.getTrait(MediaTypeTrait.class).isPresent()) { - // Use the @mediaType trait if available. - return target.getTrait(MediaTypeTrait.class).get().getValue(); - } else if (target.isBlobShape()) { - return "application/octet-stream"; - } else if (target.isStringShape()) { - return "text/plain"; - } + || target.isListShape() || target.isMapShape()) { + // Document type and structure targets are always the document content-type. + return documentContentType; + } else if (target.getTrait(MediaTypeTrait.class).isPresent()) { + // Use the @mediaType trait if available. + return target.getTrait(MediaTypeTrait.class).get().getValue(); + } else if (target.isBlobShape()) { + return "application/octet-stream"; + } else if (target.isStringShape()) { + return "text/plain"; + } } } @@ -399,7 +399,7 @@ public boolean hasResponseBody(ToShapeId operation) { private boolean hasPayloadBindings(Collection bindings) { for (HttpBinding binding : bindings) { if (binding.getLocation() == HttpBinding.Location.DOCUMENT - || binding.getLocation() == HttpBinding.Location.PAYLOAD) { + || binding.getLocation() == HttpBinding.Location.PAYLOAD) { return true; } } @@ -442,12 +442,12 @@ private List createStructureBindings(StructureShape struct, boolean } else if (!isRequest && member.getTrait(HttpResponseCodeTrait.class).isPresent()) { HttpResponseCodeTrait trait = member.getTrait(HttpResponseCodeTrait.class).get(); bindings.add( - new HttpBinding( - member, - HttpBinding.Location.RESPONSE_CODE, - member.getMemberName(), - trait - ) + new HttpBinding( + member, + HttpBinding.Location.RESPONSE_CODE, + member.getMemberName(), + trait + ) ); } else { unbound.add(member); @@ -457,15 +457,15 @@ private List createStructureBindings(StructureShape struct, boolean if (!unbound.isEmpty()) { if (foundPayload) { unbound.forEach( - member -> bindings.add( - new HttpBinding(member, HttpBinding.Location.UNBOUND, member.getMemberName(), null) - ) + member -> bindings.add( + new HttpBinding(member, HttpBinding.Location.UNBOUND, member.getMemberName(), null) + ) ); } else { unbound.forEach( - member -> bindings.add( - new HttpBinding(member, HttpBinding.Location.DOCUMENT, member.getMemberName(), null) - ) + member -> bindings.add( + new HttpBinding(member, HttpBinding.Location.DOCUMENT, member.getMemberName(), null) + ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/IdentifierBindingIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/IdentifierBindingIndex.java index 9ae7620d454..f655167b079 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/IdentifierBindingIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/IdentifierBindingIndex.java @@ -64,8 +64,8 @@ public static IdentifierBindingIndex of(Model model) { */ public BindingType getOperationBindingType(ToShapeId resource, ToShapeId operation) { return Optional.ofNullable(bindingTypes.get(resource.toShapeId())) - .flatMap(resourceMap -> Optional.ofNullable(resourceMap.get(operation.toShapeId()))) - .orElse(BindingType.NONE); + .flatMap(resourceMap -> Optional.ofNullable(resourceMap.get(operation.toShapeId()))) + .orElse(BindingType.NONE); } /** @@ -79,9 +79,9 @@ public BindingType getOperationBindingType(ToShapeId resource, ToShapeId operati */ public Map getOperationInputBindings(ToShapeId resource, ToShapeId operation) { return Optional.ofNullable(inputBindings.get(resource.toShapeId())) - .flatMap(resourceMap -> Optional.ofNullable(resourceMap.get(operation.toShapeId()))) - .map(Collections::unmodifiableMap) - .orElseGet(Collections::emptyMap); + .flatMap(resourceMap -> Optional.ofNullable(resourceMap.get(operation.toShapeId()))) + .map(Collections::unmodifiableMap) + .orElseGet(Collections::emptyMap); } /** @@ -95,9 +95,9 @@ public Map getOperationInputBindings(ToShapeId resource, ToShape */ public Map getOperationOutputBindings(ToShapeId resource, ToShapeId operation) { return Optional.ofNullable(outputBindings.get(resource.toShapeId())) - .flatMap(resourceMap -> Optional.ofNullable(resourceMap.get(operation.toShapeId()))) - .map(Collections::unmodifiableMap) - .orElseGet(Collections::emptyMap); + .flatMap(resourceMap -> Optional.ofNullable(resourceMap.get(operation.toShapeId()))) + .map(Collections::unmodifiableMap) + .orElseGet(Collections::emptyMap); } /** @@ -123,37 +123,37 @@ private void processResource(ResourceShape resource, OperationIndex operationInd resource.getAllOperations().forEach(operationId -> { // Ignore broken models in this index. Map computedInputBindings = operationIndex.getInputShape(operationId) - .map(inputShape -> computeBindings(resource, inputShape)) - .orElse(Collections.emptyMap()); + .map(inputShape -> computeBindings(resource, inputShape)) + .orElse(Collections.emptyMap()); inputBindings.get(resource.getId()).put(operationId, computedInputBindings); allIdentifiers.addAll(computedInputBindings.keySet()); Map computedOutputBindings = operationIndex.getOutputShape(operationId) - .map(outputShape -> computeBindings(resource, outputShape)) - .orElse(Collections.emptyMap()); + .map(outputShape -> computeBindings(resource, outputShape)) + .orElse(Collections.emptyMap()); outputBindings.get(resource.getId()).put(operationId, computedOutputBindings); allIdentifiers.addAll(computedOutputBindings.keySet()); bindingTypes.get(resource.getId()) - .put( - operationId, - isCollection(resource, operationId) - ? BindingType.COLLECTION - : BindingType.INSTANCE - ); + .put( + operationId, + isCollection(resource, operationId) + ? BindingType.COLLECTION + : BindingType.INSTANCE + ); }); } private boolean isCollection(ResourceShape resource, ToShapeId operationId) { return resource.getCollectionOperations().contains(operationId.toShapeId()) - || (resource.getCreate().isPresent() && resource.getCreate().get().toShapeId().equals(operationId)) - || (resource.getList().isPresent() && resource.getList().get().toShapeId().equals(operationId)); + || (resource.getCreate().isPresent() && resource.getCreate().get().toShapeId().equals(operationId)) + || (resource.getList().isPresent() && resource.getList().get().toShapeId().equals(operationId)); } private boolean isImplicitIdentifierBinding(MemberShape member, ResourceShape resource) { return resource.getIdentifiers().containsKey(member.getMemberName()) - && member.getTrait(RequiredTrait.class).isPresent() - && member.getTarget().equals(resource.getIdentifiers().get(member.getMemberName())); + && member.getTrait(RequiredTrait.class).isPresent() + && member.getTarget().equals(resource.getIdentifiers().get(member.getMemberName())); } private Map computeBindings(ResourceShape resource, StructureShape shape) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/NeighborProviderIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/NeighborProviderIndex.java index e105b913a41..b8eed08ac1f 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/NeighborProviderIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/NeighborProviderIndex.java @@ -57,7 +57,7 @@ public NeighborProvider getProviderWithTraitRelationships() { result = providerWithTraits; if (result == null) { providerWithTraits = result = NeighborProvider.cached( - NeighborProvider.withTraitRelationships(model, provider) + NeighborProvider.withTraitRelationships(model, provider) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/NullableIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/NullableIndex.java index bdebfe7d105..120d30cf8ef 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/NullableIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/NullableIndex.java @@ -86,7 +86,7 @@ boolean isStructureMemberOptional(StructureShape container, MemberShape member, @Override boolean isStructureMemberOptional(StructureShape container, MemberShape member, Shape target) { return container.hasTrait(InputTrait.class) - || CLIENT_ZERO_VALUE_V1_NO_INPUT.isStructureMemberOptional(container, member, target); + || CLIENT_ZERO_VALUE_V1_NO_INPUT.isStructureMemberOptional(container, member, target); } }, @@ -290,10 +290,10 @@ public static boolean isDefaultZeroValueOfTypeInV1(Node defaultValue, ShapeType switch (targetType) { case BOOLEAN: return defaultValue - .asBooleanNode() - .map(BooleanNode::getValue) - .filter(value -> !value) - .isPresent(); + .asBooleanNode() + .map(BooleanNode::getValue) + .filter(value -> !value) + .isPresent(); case BYTE: case SHORT: case INTEGER: diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/OperationIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/OperationIndex.java index 1b14de1775e..db7bc9f5284 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/OperationIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/OperationIndex.java @@ -116,11 +116,11 @@ public Optional getInputShape(ToShapeId operation) { */ public StructureShape expectInputShape(ToShapeId operation) { return getInputShape(operation).orElseThrow( - () -> new ExpectationNotMetException( - "Cannot get the input of `" + operation.toShapeId() + "` because " - + "it is not an operation shape in the model.", - SourceLocation.NONE - ) + () -> new ExpectationNotMetException( + "Cannot get the input of `" + operation.toShapeId() + "` because " + + "it is not an operation shape in the model.", + SourceLocation.NONE + ) ); } @@ -136,8 +136,8 @@ public StructureShape expectInputShape(ToShapeId operation) { */ public Map getInputMembers(ToShapeId operation) { return getInputShape(operation) - .map(input -> input.getAllMembers()) - .orElse(Collections.emptyMap()); + .map(input -> input.getAllMembers()) + .orElse(Collections.emptyMap()); } /** @@ -212,11 +212,11 @@ public Optional getOutputShape(ToShapeId operation) { */ public StructureShape expectOutputShape(ToShapeId operation) { return getOutputShape(operation).orElseThrow( - () -> new ExpectationNotMetException( - "Cannot get the output of `" + operation.toShapeId() + "` because " - + "it is not an operation shape in the model.", - SourceLocation.NONE - ) + () -> new ExpectationNotMetException( + "Cannot get the output of `" + operation.toShapeId() + "` because " + + "it is not an operation shape in the model.", + SourceLocation.NONE + ) ); } @@ -232,8 +232,8 @@ public StructureShape expectOutputShape(ToShapeId operation) { */ public Map getOutputMembers(ToShapeId operation) { return getOutputShape(operation) - .map(output -> output.getAllMembers()) - .orElse(Collections.emptyMap()); + .map(output -> output.getAllMembers()) + .orElse(Collections.emptyMap()); } /** diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PaginatedIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PaginatedIndex.java index a8539d720bb..e2375e7bf95 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PaginatedIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PaginatedIndex.java @@ -58,19 +58,19 @@ public static PaginatedIndex of(Model model) { } private Optional create( - Model model, - ServiceShape service, - OperationIndex opIndex, - OperationShape operation, - PaginatedTrait trait + Model model, + ServiceShape service, + OperationIndex opIndex, + OperationShape operation, + PaginatedTrait trait ) { StructureShape input = opIndex.expectInputShape(operation.getId()); StructureShape output = opIndex.expectOutputShape(operation.getId()); MemberShape inputToken = trait.getInputToken().flatMap(input::getMember).orElse(null); List outputTokenPath = trait.getOutputToken() - .map(path -> PaginatedTrait.resolveFullPath(path, model, output)) - .orElse(ListUtils.of()); + .map(path -> PaginatedTrait.resolveFullPath(path, model, output)) + .orElse(ListUtils.of()); if (inputToken == null || outputTokenPath.isEmpty()) { return Optional.empty(); @@ -78,26 +78,26 @@ private Optional create( MemberShape pageSizeMember = trait.getPageSize().flatMap(input::getMember).orElse(null); List itemsMemberPath = trait.getItems() - .map(path -> PaginatedTrait.resolveFullPath(path, model, output)) - .orElse(ListUtils.of()); + .map(path -> PaginatedTrait.resolveFullPath(path, model, output)) + .orElse(ListUtils.of()); return Optional.of( - new PaginationInfo( - service, - operation, - input, - output, - trait, - inputToken, - outputTokenPath, - pageSizeMember, - itemsMemberPath - ) + new PaginationInfo( + service, + operation, + input, + output, + trait, + inputToken, + outputTokenPath, + pageSizeMember, + itemsMemberPath + ) ); } public Optional getPaginationInfo(ToShapeId service, ToShapeId operation) { return Optional.ofNullable(paginationInfo.get(service.toShapeId())) - .flatMap(mappings -> Optional.ofNullable(mappings.get(operation.toShapeId()))); + .flatMap(mappings -> Optional.ofNullable(mappings.get(operation.toShapeId()))); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PaginationInfo.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PaginationInfo.java index 266ee5acf39..477944a8e0f 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PaginationInfo.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PaginationInfo.java @@ -28,15 +28,15 @@ public final class PaginationInfo { private final List items; PaginationInfo( - ServiceShape service, - OperationShape operation, - StructureShape input, - StructureShape output, - PaginatedTrait paginatedTrait, - MemberShape inputToken, - List outputToken, - MemberShape pageSize, - List items + ServiceShape service, + OperationShape operation, + StructureShape input, + StructureShape output, + PaginatedTrait paginatedTrait, + MemberShape inputToken, + List outputToken, + MemberShape pageSize, + List items ) { this.service = service; this.operation = operation; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PropertyBindingIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PropertyBindingIndex.java index a8a2f3a03a9..35ce91db47e 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PropertyBindingIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PropertyBindingIndex.java @@ -52,21 +52,21 @@ private PropertyBindingIndex(Model model) { operationToInputPropertiesShape.put(operationShapeId, inputPropertiesShape.getId()); for (MemberShape memberShape : inputPropertiesShape.members()) { if (identifierIndex.getOperationInputBindings(resourceShape, operationShape) - .values() - .contains(memberShape.getMemberName())) { + .values() + .contains(memberShape.getMemberName())) { memberShapeDoesNotRequireProperty.put(memberShape.toShapeId(), true); } else { memberShapeDoesNotRequireProperty.put( - memberShape.toShapeId(), - doesNotRequireProperty(memberShape) + memberShape.toShapeId(), + doesNotRequireProperty(memberShape) ); } if (doesMemberShapeRequireProperty(memberShape) - || propertyNames.contains(memberShape.getMemberName())) { + || propertyNames.contains(memberShape.getMemberName())) { memberShapeToPropertyName.put( - memberShape.getId(), - getPropertyTraitName(memberShape) - .orElse(memberShape.getMemberName()) + memberShape.getId(), + getPropertyTraitName(memberShape) + .orElse(memberShape.getMemberName()) ); } } @@ -81,22 +81,22 @@ private PropertyBindingIndex(Model model) { operationToOutputPropertiesShape.put(operationShapeId, outputPropertiesShape.getId()); for (MemberShape memberShape : outputPropertiesShape.members()) { if (identifierIndex.getOperationOutputBindings(resourceShape, operationShape) - .values() + .values() - .contains(memberShape.getMemberName())) { + .contains(memberShape.getMemberName())) { memberShapeDoesNotRequireProperty.put(memberShape.toShapeId(), true); } else { memberShapeDoesNotRequireProperty.put( - memberShape.toShapeId(), - doesNotRequireProperty(memberShape) + memberShape.toShapeId(), + doesNotRequireProperty(memberShape) ); } if (doesMemberShapeRequireProperty(memberShape) - || propertyNames.contains(memberShape.getMemberName())) { + || propertyNames.contains(memberShape.getMemberName())) { memberShapeToPropertyName.put( - memberShape.getId(), - getPropertyTraitName(memberShape) - .orElse(memberShape.getMemberName()) + memberShape.getId(), + getPropertyTraitName(memberShape) + .orElse(memberShape.getMemberName()) ); } } @@ -150,8 +150,8 @@ public boolean isMemberShapeProperty(MemberShape memberShape) { public StructureShape getOutputPropertiesShape(OperationShape operation) { Model model = getModel(); return getPropertiesShape( - operationIndex.getOutputMembers(operation).values(), - model.expectShape(operation.getOutputShape(), StructureShape.class) + operationIndex.getOutputMembers(operation).values(), + model.expectShape(operation.getOutputShape(), StructureShape.class) ); } @@ -167,8 +167,8 @@ public StructureShape getOutputPropertiesShape(OperationShape operation) { public StructureShape getInputPropertiesShape(OperationShape operation) { Model model = getModel(); return getPropertiesShape( - operationIndex.getInputMembers(operation).values(), - model.expectShape(operation.getInputShape(), StructureShape.class) + operationIndex.getInputMembers(operation).values(), + model.expectShape(operation.getInputShape(), StructureShape.class) ); } @@ -189,10 +189,10 @@ private Model getModel() { private Set computeNotPropertyTraits() { Model model = getModel(); return model.getShapesWithTrait(NotPropertyTrait.class) - .stream() - .filter(shape -> shape.hasTrait(TraitDefinition.class)) - .map(shape -> shape.toShapeId()) - .collect(Collectors.toSet()); + .stream() + .filter(shape -> shape.hasTrait(TraitDefinition.class)) + .map(shape -> shape.toShapeId()) + .collect(Collectors.toSet()); } private Optional getPropertyTraitName(MemberShape memberShape) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/ServiceIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/ServiceIndex.java index 5750b9205cf..061a9749108 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/ServiceIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/ServiceIndex.java @@ -92,18 +92,18 @@ public Map getProtocols(ToShapeId service) { private Map getTraitMapInSet(ToShapeId service, Set haystack) { return getModel() - .getShape(service.toShapeId()) - .flatMap(Shape::asServiceShape) - .map(shape -> { - Map result = new TreeMap<>(); - for (Trait trait : shape.getAllTraits().values()) { - if (haystack.contains(trait.toShapeId())) { - result.put(trait.toShapeId(), trait); + .getShape(service.toShapeId()) + .flatMap(Shape::asServiceShape) + .map(shape -> { + Map result = new TreeMap<>(); + for (Trait trait : shape.getAllTraits().values()) { + if (haystack.contains(trait.toShapeId())) { + result.put(trait.toShapeId(), trait); + } } - } - return result; - }) - .orElse(Collections.emptyMap()); + return result; + }) + .orElse(Collections.emptyMap()); } private Model getModel() { @@ -150,21 +150,21 @@ public Map getAuthSchemes(ToShapeId service) { */ public Map getEffectiveAuthSchemes(ToShapeId service) { return getModel() - .getShape(service.toShapeId()) - .flatMap(Shape::asServiceShape) - .map(shape -> { - Map result = getAuthTraitValues(shape, shape); - if (result == null) { - result = new TreeMap<>(); - for (Map.Entry traitEntry : shape.getAllTraits().entrySet()) { - if (authTraits.contains(traitEntry.getKey())) { - result.put(traitEntry.getKey(), traitEntry.getValue()); + .getShape(service.toShapeId()) + .flatMap(Shape::asServiceShape) + .map(shape -> { + Map result = getAuthTraitValues(shape, shape); + if (result == null) { + result = new TreeMap<>(); + for (Map.Entry traitEntry : shape.getAllTraits().entrySet()) { + if (authTraits.contains(traitEntry.getKey())) { + result.put(traitEntry.getKey(), traitEntry.getValue()); + } } } - } - return result; - }) - .orElse(Collections.emptyMap()); + return result; + }) + .orElse(Collections.emptyMap()); } /** @@ -217,22 +217,22 @@ public Map getEffectiveAuthSchemes(ToShapeId service, AuthScheme */ public Map getEffectiveAuthSchemes(ToShapeId service, ToShapeId operation) { Shape serviceShape = getModel() - .getShape(service.toShapeId()) - .flatMap(Shape::asServiceShape) - .orElse(null); + .getShape(service.toShapeId()) + .flatMap(Shape::asServiceShape) + .orElse(null); if (serviceShape == null) { return Collections.emptyMap(); } return getModel() - .getShape(operation.toShapeId()) - .flatMap(Shape::asOperationShape) - .map(operationShape -> { - Map result = getAuthTraitValues(serviceShape, operationShape); - return result != null ? result : getEffectiveAuthSchemes(service); - }) - .orElse(Collections.emptyMap()); + .getShape(operation.toShapeId()) + .flatMap(Shape::asOperationShape) + .map(operationShape -> { + Map result = getAuthTraitValues(serviceShape, operationShape); + return result != null ? result : getEffectiveAuthSchemes(service); + }) + .orElse(Collections.emptyMap()); } /** @@ -258,9 +258,9 @@ public Map getEffectiveAuthSchemes(ToShapeId service, ToShapeId * @return Returns a map of the trait shape ID to the auth trait itself. */ public Map getEffectiveAuthSchemes( - ToShapeId service, - ToShapeId operation, - AuthSchemeMode authSchemeMode + ToShapeId service, + ToShapeId operation, + AuthSchemeMode authSchemeMode ) { Map authSchemes = getEffectiveAuthSchemes(service, operation); if (authSchemeMode == AuthSchemeMode.NO_AUTH_AWARE) { @@ -274,9 +274,9 @@ public Map getEffectiveAuthSchemes( private boolean hasOptionalAuth(ToShapeId operation) { return getModel() - .getShape(operation.toShapeId()) - .filter(shape -> shape.hasTrait(OptionalAuthTrait.class)) - .isPresent(); + .getShape(operation.toShapeId()) + .filter(shape -> shape.hasTrait(OptionalAuthTrait.class)) + .isPresent(); } private static Map getAuthTraitValues(Shape service, Shape subject) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/TextIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/TextIndex.java index cc1d4b07b42..9e5abb7860c 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/TextIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/TextIndex.java @@ -35,8 +35,8 @@ public TextIndex(Model model) { // Validating the prelude is a feature for internal-only Smithy development Node validatePreludeNode = model.getMetadata().get(TraitValueValidator.VALIDATE_PRELUDE); boolean validatePrelude = validatePreludeNode != null - ? validatePreludeNode.expectBooleanNode().getValue() - : false; + ? validatePreludeNode.expectBooleanNode().getValue() + : false; for (final Shape shape : model.toSet()) { if (validatePrelude || !Prelude.isPreludeShape(shape)) { @@ -57,78 +57,78 @@ public Collection getTextInstances() { } private static void computeShapeTextInstances( - Shape shape, - Collection textInstances, - Model model + Shape shape, + Collection textInstances, + Model model ) { textInstances.add(TextInstance.createShapeInstance(shape)); for (Trait trait : shape.getAllTraits().values()) { model.getShape(trait.toShapeId()).ifPresent(traitShape -> { computeTextInstancesForAppliedTrait( - trait.toNode(), - trait, - shape, - textInstances, - new ArrayDeque<>(), - model, - traitShape + trait.toNode(), + trait, + shape, + textInstances, + new ArrayDeque<>(), + model, + traitShape ); }); } } private static void computeTextInstancesForAppliedTrait( - Node node, - Trait trait, - Shape parentShape, - Collection textInstances, - Deque propertyPath, - Model model, - Shape currentTraitPropertyShape + Node node, + Trait trait, + Shape parentShape, + Collection textInstances, + Deque propertyPath, + Model model, + Shape currentTraitPropertyShape ) { if (trait.toShapeId().equals(ReferencesTrait.ID)) { //Skip ReferenceTrait because it is referring to other shape names already being checked } else if (node.isStringNode()) { textInstances.add( - TextInstance.createTraitInstance( - node.expectStringNode().getValue(), - parentShape, - trait, - propertyPath - ) + TextInstance.createTraitInstance( + node.expectStringNode().getValue(), + parentShape, + trait, + propertyPath + ) ); } else if (node.isObjectNode()) { ObjectNode objectNode = node.expectObjectNode(); objectNode.getStringMap().entrySet().forEach(memberEntry -> { propertyPath.offerLast(memberEntry.getKey()); Shape memberTypeShape = getChildMemberShapeType( - memberEntry.getKey(), - model, - currentTraitPropertyShape + memberEntry.getKey(), + model, + currentTraitPropertyShape ); if (memberTypeShape == null) { //This means the "property" key value isn't modeled in the trait's structure/shape definition //and this text instance is unique propertyPath.offerLast("key"); textInstances.add( - TextInstance.createTraitInstance( - memberEntry.getKey(), - parentShape, - trait, - propertyPath - ) + TextInstance.createTraitInstance( + memberEntry.getKey(), + parentShape, + trait, + propertyPath + ) ); propertyPath.removeLast(); } computeTextInstancesForAppliedTrait( - memberEntry.getValue(), - trait, - parentShape, - textInstances, - propertyPath, - model, - memberTypeShape + memberEntry.getValue(), + trait, + parentShape, + textInstances, + propertyPath, + model, + memberTypeShape ); propertyPath.removeLast(); }); @@ -137,18 +137,18 @@ private static void computeTextInstancesForAppliedTrait( for (Node nodeElement : node.expectArrayNode().getElements()) { propertyPath.offerLast(Integer.toString(index)); Shape memberTypeShape = getChildMemberShapeType( - null, - model, - currentTraitPropertyShape + null, + model, + currentTraitPropertyShape ); computeTextInstancesForAppliedTrait( - nodeElement, - trait, - parentShape, - textInstances, - propertyPath, - model, - memberTypeShape + nodeElement, + trait, + parentShape, + textInstances, + propertyPath, + model, + memberTypeShape ); propertyPath.removeLast(); ++index; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/TextInstance.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/TextInstance.java index 2fd9cf793b2..73dcda5bc00 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/TextInstance.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/TextInstance.java @@ -23,19 +23,19 @@ public final class TextInstance { private final List traitPropertyPath; private TextInstance( - final TextLocationType locationType, - final String text, - final Shape shape, - final Trait trait, - final Deque traitPropertyPath + final TextLocationType locationType, + final String text, + final Shape shape, + final Trait trait, + final Deque traitPropertyPath ) { this.locationType = locationType; this.text = text; this.shape = shape; this.trait = trait; this.traitPropertyPath = traitPropertyPath != null - ? ListUtils.copyOf(traitPropertyPath) - : ListUtils.of(); + ? ListUtils.copyOf(traitPropertyPath) + : ListUtils.of(); } static TextInstance createNamespaceText(String namespace) { @@ -46,13 +46,13 @@ static TextInstance createNamespaceText(String namespace) { static TextInstance createShapeInstance(Shape shape) { Objects.requireNonNull(shape, "'shape' must be specified"); return new TextInstance( - TextLocationType.SHAPE, - shape.getId() - .getMember() - .orElseGet(() -> shape.getId().getName()), - shape, - null, - null + TextLocationType.SHAPE, + shape.getId() + .getMember() + .orElseGet(() -> shape.getId().getName()), + shape, + null, + null ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ApplyMixin.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ApplyMixin.java index 340175cb6b3..7d4ee0eb6e3 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ApplyMixin.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ApplyMixin.java @@ -36,10 +36,10 @@ final class ApplyMixin implements ShapeModifier { @Override public void modifyMember( - AbstractShapeBuilder shapeBuilder, - MemberShape.Builder memberBuilder, - Function> unclaimedTraits, - Function shapeMap + AbstractShapeBuilder shapeBuilder, + MemberShape.Builder memberBuilder, + Function> unclaimedTraits, + Function shapeMap ) { // The target could have been set by resource based properties. if (memberBuilder.getTarget() != null) { @@ -50,8 +50,8 @@ public void modifyMember( Shape mixinShape = shapeMap.apply(mixin); if (mixinShape == null) { throw new SourceException( - "Cannot apply mixin to " + memberBuilder.getId() + ": " + mixin + " not found", - memberBuilder + "Cannot apply mixin to " + memberBuilder.getId() + ": " + mixin + " not found", + memberBuilder ); } @@ -61,16 +61,16 @@ public void modifyMember( @Override public void modifyShape( - AbstractShapeBuilder builder, - Map memberBuilders, - Function> unclaimedTraits, - Function shapeMap + AbstractShapeBuilder builder, + Map memberBuilders, + Function> unclaimedTraits, + Function shapeMap ) { Shape mixinShape = shapeMap.apply(mixin); if (mixinShape == null) { throw new SourceException( - "Cannot apply mixin to " + builder.getId() + ": " + mixin + " not found", - builder + "Cannot apply mixin to " + builder.getId() + ": " + mixin + " not found", + builder ); } @@ -91,8 +91,8 @@ public void modifyShape( if (!previous.getMixins().isEmpty()) { MemberShape.Builder previouslyAddedBuilder = previous.toBuilder(); introducedMember = previouslyAddedBuilder - .addMixin(member) - .build(); + .addMixin(member) + .build(); if (!previous.getTarget().equals(member.getTarget())) { mixinMemberConflict(previouslyAddedBuilder, member); } @@ -110,12 +110,12 @@ public void modifyShape( // Build local member copies before adding mixins if traits // were introduced to inherited mixin members. introducedMember = MemberShape.builder() - .id(targetId) - .target(member.getTarget()) - .source(member.getSourceLocation()) - .addTraits(introducedTraits.values()) - .addMixin(member) - .build(); + .id(targetId) + .target(member.getTarget()) + .source(member.getSourceLocation()) + .addTraits(introducedTraits.values()) + .addMixin(member) + .build(); } } @@ -132,13 +132,13 @@ private void mixinMemberConflict(MemberShape.Builder conflict, MemberShape other events = new ArrayList<>(); } events.add( - ValidationEvent.builder() - .severity(Severity.ERROR) - .id(Validator.MODEL_ERROR) - .shapeId(conflict.getId()) - .sourceLocation(conflict.getSourceLocation()) - .message("Member conflicts with an inherited mixin member: `" + other.getId() + "`") - .build() + ValidationEvent.builder() + .severity(Severity.ERROR) + .id(Validator.MODEL_ERROR) + .shapeId(conflict.getId()) + .sourceLocation(conflict.getSourceLocation()) + .message("Member conflicts with an inherited mixin member: `" + other.getId() + "`") + .build() ); } @@ -153,8 +153,8 @@ void putPotentiallyIntroducedTrait(ShapeId target, Trait trait) { } Map shapeUnclaimedTraits = potentiallyIntroducedTraits.computeIfAbsent( - target, - id -> new LinkedHashMap<>() + target, + id -> new LinkedHashMap<>() ); shapeUnclaimedTraits.put(trait.toShapeId(), trait); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ApplyResourceBasedTargets.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ApplyResourceBasedTargets.java index 79189123aac..f8a4132bc28 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ApplyResourceBasedTargets.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ApplyResourceBasedTargets.java @@ -37,10 +37,10 @@ final class ApplyResourceBasedTargets implements ShapeModifier { @Override public void modifyMember( - AbstractShapeBuilder shapeBuilder, - MemberShape.Builder memberBuilder, - Function> unclaimedTraits, - Function shapeMap + AbstractShapeBuilder shapeBuilder, + MemberShape.Builder memberBuilder, + Function> unclaimedTraits, + Function shapeMap ) { // Fast-fail the common case of the target having already been set. if (memberBuilder.getTarget() != null) { @@ -50,9 +50,9 @@ public void modifyMember( Shape fromShape = shapeMap.apply(resourceId); if (fromShape == null) { throw new SourceException( - "Cannot apply resource to elided member " + memberBuilder.getId() + ": " - + resourceId + " not found", - memberBuilder + "Cannot apply resource to elided member " + memberBuilder.getId() + ": " + + resourceId + " not found", + memberBuilder ); } @@ -72,17 +72,17 @@ public void modifyMember( private void fromShapeIsNotResource(MemberShape.Builder memberBuilder, Shape fromShape) { String message = String.format( - "The target of the `for` production must be a resource shape, but found a %s shape: %s", - fromShape.getType(), - resourceId + "The target of the `for` production must be a resource shape, but found a %s shape: %s", + fromShape.getType(), + resourceId ); ValidationEvent event = ValidationEvent.builder() - .id(Validator.MODEL_ERROR) - .severity(Severity.ERROR) - .shapeId(memberBuilder.getId()) - .sourceLocation(memberBuilder.getSourceLocation()) - .message(message) - .build(); + .id(Validator.MODEL_ERROR) + .severity(Severity.ERROR) + .shapeId(memberBuilder.getId()) + .sourceLocation(memberBuilder.getSourceLocation()) + .message(message) + .build(); if (events == null) { events = new ArrayList<>(1); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/AstModelLoader.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/AstModelLoader.java index e4ba3db6203..1e8c4ea2d33 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/AstModelLoader.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/AstModelLoader.java @@ -72,38 +72,38 @@ final class AstModelLoader { private static final Set MEMBER_PROPERTIES = SetUtils.of(TARGET, TRAITS); private static final Set REFERENCE_PROPERTIES = SetUtils.of(TARGET); private static final Set OPERATION_PROPERTY_NAMES = SetUtils.of( - TYPE, - "input", - "output", - ERRORS, - TRAITS, - MIXINS + TYPE, + "input", + "output", + ERRORS, + TRAITS, + MIXINS ); private static final Set RESOURCE_PROPERTIES = SetUtils.of( - TYPE, - "create", - "read", - "update", - "delete", - "list", - "put", - "identifiers", - "resources", - "operations", - "collectionOperations", - "properties", - TRAITS, - MIXINS + TYPE, + "create", + "read", + "update", + "delete", + "list", + "put", + "identifiers", + "resources", + "operations", + "collectionOperations", + "properties", + TRAITS, + MIXINS ); private static final Set SERVICE_PROPERTIES = SetUtils.of( - TYPE, - "version", - "operations", - "resources", - "rename", - ERRORS, - TRAITS, - MIXINS + TYPE, + "version", + "operations", + "resources", + "rename", + ERRORS, + TRAITS, + MIXINS ); private final Version modelVersion; @@ -224,14 +224,14 @@ private void applyTraits(ShapeId id, ObjectNode traits) { // that a null value provided in the AST is not coerced in the same way // as an omitted value in the IDL (e.g., "@foo"). operations.accept( - new LoadOperation.ApplyTrait( - modelVersion, - traitNode.getKey().getSourceLocation(), - id.getNamespace(), - id, - traitId, - traitNode.getValue() - ) + new LoadOperation.ApplyTrait( + modelVersion, + traitNode.getKey().getSourceLocation(), + id.getNamespace(), + id, + traitId, + traitNode.getValue() + ) ); } } @@ -254,9 +254,9 @@ private void loadOptionalMember(LoadOperation.DefineShape operation, ShapeId id, } private LoadOperation.DefineShape loadCollection( - ShapeId id, - ObjectNode node, - CollectionShape.Builder builder + ShapeId id, + ObjectNode node, + CollectionShape.Builder builder ) { LoaderUtils.checkForAdditionalProperties(node, id, COLLECTION_PROPERTY_NAMES).ifPresent(this::emit); applyShapeTraits(id, node); @@ -287,9 +287,9 @@ private LoadOperation.DefineShape loadOperation(ShapeId id, ObjectNode node) { LoaderUtils.checkForAdditionalProperties(node, id, OPERATION_PROPERTY_NAMES).ifPresent(this::emit); applyShapeTraits(id, node); OperationShape.Builder builder = OperationShape.builder() - .id(id) - .source(node.getSourceLocation()) - .addErrors(loadOptionalTargetList(id, node, ERRORS)); + .id(id) + .source(node.getSourceLocation()) + .addErrors(loadOptionalTargetList(id, node, ERRORS)); loadOptionalTarget(id, node, "input").ifPresent(builder::input); loadOptionalTarget(id, node, "output").ifPresent(builder::output); LoadOperation.DefineShape operation = createShape(builder); @@ -324,15 +324,16 @@ private LoadOperation.DefineShape loadResource(ShapeId id, ObjectNode node) { node.getObjectMember("properties").ifPresent(properties -> { if (!modelVersion.supportsResourceProperties()) { emit( - ValidationEvent.builder() - .sourceLocation(properties.getSourceLocation()) - .id(Validator.MODEL_ERROR) - .severity(Severity.ERROR) - .message( - "Resource properties can only be used with Smithy version 2 or later. " - + "Attempted to use resource properties with version `" + modelVersion + "`." - ) - .build() + ValidationEvent.builder() + .sourceLocation(properties.getSourceLocation()) + .id(Validator.MODEL_ERROR) + .severity(Severity.ERROR) + .message( + "Resource properties can only be used with Smithy version 2 or later. " + + "Attempted to use resource properties with version `" + modelVersion + + "`." + ) + .build() ); } for (Map.Entry entry : properties.getMembers().entrySet()) { @@ -372,9 +373,9 @@ static void loadServiceRenameIntoBuilder(ServiceShape.Builder builder, ObjectNod } private LoadOperation.DefineShape loadSimpleShape( - ShapeId id, - ObjectNode node, - AbstractShapeBuilder builder + ShapeId id, + ObjectNode node, + AbstractShapeBuilder builder ) { LoaderUtils.checkForAdditionalProperties(node, id, SIMPLE_PROPERTY_NAMES).ifPresent(this::emit); applyShapeTraits(id, node); @@ -385,9 +386,9 @@ private LoadOperation.DefineShape loadSimpleShape( } private LoadOperation.DefineShape loadNamedMemberShape( - ShapeId id, - ObjectNode node, - AbstractShapeBuilder builder + ShapeId id, + ObjectNode node, + AbstractShapeBuilder builder ) { LoaderUtils.checkForAdditionalProperties(node, id, NAMED_MEMBER_SHAPE_PROPERTY_NAMES).ifPresent(this::emit); builder.id(id).source(node.getSourceLocation()); @@ -401,9 +402,9 @@ private void finishLoadingNamedMemberShapeMembers(LoadOperation.DefineShape oper ObjectNode memberObject = node.getObjectMember(MEMBERS).orElse(Node.objectNode()); for (Map.Entry entry : memberObject.getStringMap().entrySet()) { loadMember( - operation, - operation.toShapeId().withMember(entry.getKey()), - entry.getValue().expectObjectNode() + operation, + operation.toShapeId().withMember(entry.getKey()), + entry.getValue().expectObjectNode() ); } addMixins(operation, node); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/DefaultTokenizer.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/DefaultTokenizer.java index 249773fad1c..6e3cc37ee9b 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/DefaultTokenizer.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/DefaultTokenizer.java @@ -93,9 +93,9 @@ public final CharSequence getCurrentTokenStringSlice() { return getCurrentTokenLexeme(); } else { throw syntax( - "The current token must be string or identifier but found: " - + currentTokenType.getDebug(getCurrentTokenLexeme()), - getCurrentTokenLocation() + "The current token must be string or identifier but found: " + + currentTokenType.getDebug(getCurrentTokenLexeme()), + getCurrentTokenLocation() ); } } @@ -105,9 +105,9 @@ public final Number getCurrentTokenNumberValue() { getCurrentToken(); if (currentTokenNumber == null) { throw syntax( - "The current token must be number but found: " - + currentTokenType.getDebug(getCurrentTokenLexeme()), - getCurrentTokenLocation() + "The current token must be number but found: " + + currentTokenType.getDebug(getCurrentTokenLexeme()), + getCurrentTokenLocation() ); } return currentTokenNumber; @@ -118,9 +118,9 @@ public final String getCurrentTokenError() { getCurrentToken(); if (currentTokenType != IdlToken.ERROR) { throw syntax( - "The current token must be an error but found: " - + currentTokenType.getDebug(getCurrentTokenLexeme()), - getCurrentTokenLocation() + "The current token must be an error but found: " + + currentTokenType.getDebug(getCurrentTokenLexeme()), + getCurrentTokenLocation() ); } return currentTokenError == null ? "" : currentTokenError; @@ -258,9 +258,9 @@ public IdlToken next() { private ModelSyntaxException syntax(String message, SourceLocation location) { return new ModelSyntaxException( - "Syntax error at line " + location.getLine() + ", column " - + location.getColumn() + ": " + message, - location + "Syntax error at line " + location.getLine() + ", column " + + location.getColumn() + ": " + message, + location ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlInternalTokenizer.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlInternalTokenizer.java index 3e7f81d2c5d..73b9f4ca964 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlInternalTokenizer.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlInternalTokenizer.java @@ -97,9 +97,9 @@ void expectAndSkipSpaces() { void expectAndSkipWhitespace() { if (!getCurrentToken().isWhitespace()) { throw LoaderUtils.idlSyntaxError( - "Expected one or more whitespace characters, but found " - + getCurrentToken().getDebug(getCurrentTokenLexeme()), - getCurrentTokenLocation() + "Expected one or more whitespace characters, but found " + + getCurrentToken().getDebug(getCurrentTokenLexeme()), + getCurrentTokenLocation() ); } skipWsAndDocs(); @@ -135,9 +135,9 @@ void expectAndSkipBr() { break; default: throw LoaderUtils.idlSyntaxError( - "Expected a line break, but found " - + getCurrentToken().getDebug(getCurrentTokenLexeme()), - getCurrentTokenLocation() + "Expected a line break, but found " + + getCurrentToken().getDebug(getCurrentTokenLexeme()), + getCurrentTokenLocation() ); } } @@ -145,10 +145,10 @@ void expectAndSkipBr() { void clearDocCommentLinesForBr() { if (!docCommentLines.isEmpty()) { validationEventListener.accept( - LoaderUtils.emitBadDocComment( - getCurrentTokenLocation(), - removePendingDocCommentLines() - ) + LoaderUtils.emitBadDocComment( + getCurrentTokenLocation(), + removePendingDocCommentLines() + ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlModelLoader.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlModelLoader.java index e14be7e643d..9f9a6f6811c 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlModelLoader.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlModelLoader.java @@ -64,26 +64,26 @@ final class IdlModelLoader { private static final int MAX_NESTING_LEVEL = 64; static final Collection RESOURCE_PROPERTY_NAMES = ListUtils.of( - TYPE_KEY, - CREATE_KEY, - READ_KEY, - UPDATE_KEY, - DELETE_KEY, - LIST_KEY, - IDENTIFIERS_KEY, - RESOURCES_KEY, - OPERATIONS_KEY, - PUT_KEY, - PROPERTIES_KEY, - COLLECTION_OPERATIONS_KEY + TYPE_KEY, + CREATE_KEY, + READ_KEY, + UPDATE_KEY, + DELETE_KEY, + LIST_KEY, + IDENTIFIERS_KEY, + RESOURCES_KEY, + OPERATIONS_KEY, + PUT_KEY, + PROPERTIES_KEY, + COLLECTION_OPERATIONS_KEY ); static final List SERVICE_PROPERTY_NAMES = ListUtils.of( - TYPE_KEY, - VERSION_KEY, - OPERATIONS_KEY, - RESOURCES_KEY, - RENAME_KEY, - ERRORS_KEY + TYPE_KEY, + VERSION_KEY, + OPERATIONS_KEY, + RESOURCES_KEY, + RENAME_KEY, + ERRORS_KEY ); private static final Set SHAPE_TYPES = new HashSet<>(); @@ -152,8 +152,8 @@ String internString(CharSequence sequence) { void increaseNestingLevel() { if (++nesting > MAX_NESTING_LEVEL) { throw LoaderUtils.idlSyntaxError( - "Parser exceeded maximum allowed depth of " + MAX_NESTING_LEVEL, - tokenizer.getCurrentTokenLocation() + "Parser exceeded maximum allowed depth of " + MAX_NESTING_LEVEL, + tokenizer.getCurrentTokenLocation() ); } } @@ -172,8 +172,8 @@ void addForwardReference(String id, BiFunction 0 && memberPosition < id.length() - 1) { addForwardReference( - id.substring(0, memberPosition), - (resolved, type) -> receiver.apply(resolved.withMember(id.substring(memberPosition + 1)), type) + id.substring(0, memberPosition), + (resolved, type) -> receiver.apply(resolved.withMember(id.substring(memberPosition + 1)), type) ); } else { String resolved = useShapes.containsKey(id) ? useShapes.get(id).toString() : id; @@ -211,14 +211,14 @@ private void onDeferredTrait(ShapeId target, String traitName, Node traitValue, addForwardReference(traitName, (traitId, type) -> { Node coerced = coerceTraitValue(traitValue, isAnnotation, type); addOperation( - new LoadOperation.ApplyTrait( - modelVersion, - traitValue.getSourceLocation(), - expectNamespace(), - target, - traitId, - coerced - ) + new LoadOperation.ApplyTrait( + modelVersion, + traitValue.getSourceLocation(), + expectNamespace(), + target, + traitId, + coerced + ) ); return null; }); @@ -279,18 +279,18 @@ private void parseControlSection() { break; default: emit( - ValidationEvent.builder() - .id(Validator.MODEL_ERROR) - .sourceLocation(value) - .severity(Severity.WARNING) - .message( - format( - "Unknown control statement `%s` with value `%s", - key, - Node.printJson(value) - ) - ) - .build() + ValidationEvent.builder() + .id(Validator.MODEL_ERROR) + .sourceLocation(value) + .severity(Severity.WARNING) + .message( + format( + "Unknown control statement `%s` with value `%s", + key, + Node.printJson(value) + ) + ) + .build() ); break; } @@ -305,8 +305,8 @@ private void parseControlSection() { private void onVersion(Node value) { if (!value.isStringNode()) { value.expectStringNode( - () -> "The $version control statement must have a string value, but found " - + Node.printJson(value) + () -> "The $version control statement must have a string value, but found " + + Node.printJson(value) ); } @@ -364,8 +364,8 @@ private void parseShapeSection() { parseSubsequentShapeStatements(); } else if (tokenizer.hasNext()) { throw syntax( - "Expected a namespace definition but found " - + tokenizer.getCurrentToken().getDebug(tokenizer.getCurrentTokenLexeme()) + "Expected a namespace definition but found " + + tokenizer.getCurrentToken().getDebug(tokenizer.getCurrentTokenLexeme()) ); } } @@ -403,11 +403,11 @@ private void parseUseSection() { return null; } else { return ValidationEvent.builder() - .id(Validator.MODEL_ERROR) - .severity(Severity.WARNING) - .sourceLocation(idLocation) - .message("Use statement refers to undefined shape: " + id) - .build(); + .id(Validator.MODEL_ERROR) + .severity(Severity.WARNING) + .sourceLocation(idLocation) + .message("Use statement refers to undefined shape: " + id) + .build(); } }); @@ -457,10 +457,10 @@ private void parseApplyStatement(List traits) { for (IdlTraitParser.Result trait : traitsToApply) { String traitNameString = internString(trait.getTraitName()); onDeferredTrait( - id, - traitNameString, - trait.getValue(), - trait.getTraitType() == IdlTraitParser.TraitType.ANNOTATION + id, + traitNameString, + trait.getValue(), + trait.getTraitType() == IdlTraitParser.TraitType.ANNOTATION ); } }); @@ -476,11 +476,11 @@ private void parseFirstShapeStatement(SourceLocation possibleDocCommentLocation) List traits = IdlTraitParser.parseDocsAndTraitsBeforeShape(this, false); if (docLines != null) { traits.add( - new IdlTraitParser.Result( - DocumentationTrait.ID.toString(), - new StringNode(docLines, possibleDocCommentLocation), - IdlTraitParser.TraitType.DOC_COMMENT - ) + new IdlTraitParser.Result( + DocumentationTrait.ID.toString(), + new StringNode(docLines, possibleDocCommentLocation), + IdlTraitParser.TraitType.DOC_COMMENT + ) ); } if (parseShapeDefinition(traits, docLines != null)) { @@ -549,10 +549,10 @@ private boolean parseShapeDefinition(List traits, boolean // but don't fail. if (traits.size() == 1) { emit( - LoaderUtils.emitBadDocComment( - tokenizer.getCurrentTokenLocation(), - traits.get(0).getValue().expectStringNode().getValue() - ) + LoaderUtils.emitBadDocComment( + tokenizer.getCurrentTokenLocation(), + traits.get(0).getValue().expectStringNode().getValue() + ) ); return false; } else { @@ -577,7 +577,7 @@ private void parseShapeOrApply(List traits) { } ShapeType type = ShapeType.fromString(shapeType) - .orElseThrow(() -> syntax("Unknown shape type: " + shapeType)); + .orElseThrow(() -> syntax("Unknown shape type: " + shapeType)); tokenizer.next(); tokenizer.expectAndSkipSpaces(); ShapeId id = parseShapeName(); @@ -632,10 +632,10 @@ private void addTraits(ShapeId id, List traits) { for (IdlTraitParser.Result result : traits) { String traitName = internString(result.getTraitName()); onDeferredTrait( - id, - traitName, - result.getValue(), - result.getTraitType() == IdlTraitParser.TraitType.ANNOTATION + id, + traitName, + result.getValue(), + result.getTraitType() == IdlTraitParser.TraitType.ANNOTATION ); } } @@ -676,9 +676,9 @@ private void parseMixins(LoadOperation.DefineShape operation) { if (!modelVersion.supportsMixins()) { throw syntax( - operation.toShapeId(), - "Mixins can only be used with Smithy version 2 or later. " - + "Attempted to use mixins with version `" + modelVersion + "`." + operation.toShapeId(), + "Mixins can only be used with Smithy version 2 or later. " + + "Attempted to use mixins with version `" + modelVersion + "`." ); } @@ -713,7 +713,7 @@ private void parseEnumShape(ShapeId id, SourceLocation location, AbstractShapeBu while (tokenizer.getCurrentToken() != IdlToken.EOF && tokenizer.getCurrentToken() != IdlToken.RBRACE) { List memberTraits = IdlTraitParser - .parseDocsAndTraitsBeforeShape(this, true); + .parseDocsAndTraitsBeforeShape(this, true); SourceLocation memberLocation = tokenizer.getCurrentTokenLocation(); tokenizer.expect(IdlToken.IDENTIFIER); String memberName = internString(tokenizer.getCurrentTokenLexeme()); @@ -723,9 +723,9 @@ private void parseEnumShape(ShapeId id, SourceLocation location, AbstractShapeBu } MemberShape.Builder memberBuilder = MemberShape.builder() - .id(id.withMember(memberName)) - .source(memberLocation) - .target(UnitTypeTrait.UNIT); + .id(id.withMember(memberName)) + .source(memberLocation) + .target(UnitTypeTrait.UNIT); operation.addMember(memberBuilder); addTraits(memberBuilder.getId(), memberTraits); @@ -790,7 +790,7 @@ private void parseMember(LoadOperation.DefineShape operation, Set define // Handle the case of a dangling documentation comment followed by "}". if (tokenizer.getCurrentToken() == IdlToken.RBRACE) { if (memberTraits.size() == 1 - && memberTraits.get(0).getTraitType() == IdlTraitParser.TraitType.DOC_COMMENT) { + && memberTraits.get(0).getTraitType() == IdlTraitParser.TraitType.DOC_COMMENT) { IdlTraitParser.Result danglingDocComment = memberTraits.get(0); SourceLocation sourceLocation = danglingDocComment.getValue().getSourceLocation(); String value = danglingDocComment.getValue().toString(); @@ -867,10 +867,10 @@ private void parseForResource(LoadOperation.DefineShape operation) { if (!modelVersion.supportsTargetElision()) { throw syntax( - operation.toShapeId(), - "Structures can only be bound to resources with Smithy version 2 or " - + "later. Attempted to bind a structure to a resource with version `" - + modelVersion + "`." + operation.toShapeId(), + "Structures can only be bound to resources with Smithy version 2 or " + + "later. Attempted to bind a structure to a resource with version `" + + modelVersion + "`." ); } @@ -947,9 +947,9 @@ private void parseResourceStatement(ShapeId id, SourceLocation location) { shapeNode.getObjectMember(PROPERTIES_KEY).ifPresent(properties -> { if (!modelVersion.supportsResourceProperties()) { throw syntax( - id, - "Resource properties can only be used with Smithy version 2 or later. " - + "Attempted to use resource properties with version `" + modelVersion + "`." + id, + "Resource properties can only be used with Smithy version 2 or later. " + + "Attempted to use resource properties with version `" + modelVersion + "`." ); } for (Map.Entry entry : properties.getMembers().entrySet()) { @@ -986,9 +986,9 @@ private void parseOperationStatement(ShapeId id, SourceLocation location) { IdlToken nextInput = tokenizer.expect(IdlToken.COLON, IdlToken.WALRUS); tokenizer.next(); IdlTraitParser.Result inputTrait = new IdlTraitParser.Result( - InputTrait.ID.toString(), - Node.objectNode(), - IdlTraitParser.TraitType.ANNOTATION + InputTrait.ID.toString(), + Node.objectNode(), + IdlTraitParser.TraitType.ANNOTATION ); parseInlineableOperationMember(id, nextInput, operationInputSuffix, builder::input, inputTrait); break; @@ -996,9 +996,9 @@ private void parseOperationStatement(ShapeId id, SourceLocation location) { IdlToken nextOutput = tokenizer.expect(IdlToken.COLON, IdlToken.WALRUS); tokenizer.next(); IdlTraitParser.Result outputTrait = new IdlTraitParser.Result( - OutputTrait.ID.toString(), - Node.objectNode(), - IdlTraitParser.TraitType.ANNOTATION + OutputTrait.ID.toString(), + Node.objectNode(), + IdlTraitParser.TraitType.ANNOTATION ); parseInlineableOperationMember(id, nextOutput, operationOutputSuffix, builder::output, outputTrait); break; @@ -1020,18 +1020,18 @@ private void parseOperationStatement(ShapeId id, SourceLocation location) { } private void parseInlineableOperationMember( - ShapeId id, - IdlToken token, - String suffix, - Consumer consumer, - IdlTraitParser.Result defaultTrait + ShapeId id, + IdlToken token, + String suffix, + Consumer consumer, + IdlTraitParser.Result defaultTrait ) { if (token == IdlToken.WALRUS) { if (!modelVersion.supportsInlineOperationIO()) { throw syntax( - id, - "Inlined operation inputs and outputs can only be used with Smithy version 2 or " - + "later. Attempted to use inlined IO with version `" + modelVersion + "`." + id, + "Inlined operation inputs and outputs can only be used with Smithy version 2 or " + + "later. Attempted to use inlined IO with version `" + modelVersion + "`." ); } // Remove any pending, invalid docs that may have come before the inline shape. diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlNodeParser.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlNodeParser.java index b1a62b68f6b..7752b804835 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlNodeParser.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlNodeParser.java @@ -53,12 +53,12 @@ static Node expectAndSkipNode(IdlModelLoader loader) { static Node expectAndSkipNode(IdlModelLoader loader, SourceLocation location) { IdlInternalTokenizer tokenizer = loader.getTokenizer(); IdlToken token = tokenizer.expect( - IdlToken.STRING, - IdlToken.TEXT_BLOCK, - IdlToken.NUMBER, - IdlToken.IDENTIFIER, - IdlToken.LBRACE, - IdlToken.LBRACKET + IdlToken.STRING, + IdlToken.TEXT_BLOCK, + IdlToken.NUMBER, + IdlToken.IDENTIFIER, + IdlToken.LBRACE, + IdlToken.LBRACKET ); switch (token) { @@ -93,8 +93,8 @@ static Node expectAndSkipNode(IdlModelLoader loader, SourceLocation location) { static Node createIdentifier(IdlModelLoader loader, String identifier, SourceLocation location) { Keyword keyword = Keyword.from(identifier); return keyword == null - ? createSyntacticShapeId(loader, identifier, location) - : keyword.createNode(location); + ? createSyntacticShapeId(loader, identifier, location) + : keyword.createNode(location); } private enum Keyword { @@ -134,9 +134,9 @@ static Keyword from(String keyword) { } private static Node createSyntacticShapeId( - IdlModelLoader loader, - String identifier, - SourceLocation location + IdlModelLoader loader, + String identifier, + SourceLocation location ) { // Unquoted node values syntactically are assumed to be references to shapes. A lazy string node is // used because the shape ID may not be able to be resolved until after the entire model is loaded. @@ -148,19 +148,19 @@ private static Node createSyntacticShapeId( return null; } else { return ValidationEvent.builder() - .id(SYNTACTIC_SHAPE_ID_TARGET) - .severity(Severity.DANGER) - .message( - String.format( - "Syntactic shape ID `%s` does not resolve to a valid shape ID: " - + "`%s`. Did you mean to quote this string? Are you missing a " - + "model file?", - identifier, - id + .id(SYNTACTIC_SHAPE_ID_TARGET) + .severity(Severity.DANGER) + .message( + String.format( + "Syntactic shape ID `%s` does not resolve to a valid shape ID: " + + "`%s`. Did you mean to quote this string? Are you missing a " + + "model file?", + identifier, + id + ) ) - ) - .sourceLocation(location) - .build(); + .sourceLocation(location) + .build(); } }); return pair.left; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlStringLexer.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlStringLexer.java index 44edab13405..f47ffd5eca3 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlStringLexer.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlStringLexer.java @@ -278,11 +278,11 @@ private static boolean isValidNormalCharacter(char c, boolean isTextBlock) { // QuotedChar grammar: // https://smithy.io/2.0/spec/idl.html#grammar-token-smithy-QuotedChar return c == '\t' - || c == '\n' - || c == '\r' - || (c >= 0x20 && c <= 0x21) // space - "!" - || (isTextBlock && c == 0x22) // DQUOTE is allowed in text_block - || (c >= 0x23 && c <= 0x5b) // "#" - "[" - || c >= 0x5d; // "]"+ + || c == '\n' + || c == '\r' + || (c >= 0x20 && c <= 0x21) // space - "!" + || (isTextBlock && c == 0x22) // DQUOTE is allowed in text_block + || (c >= 0x23 && c <= 0x5b) // "#" - "[" + || c >= 0x5d; // "]"+ } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlTraitParser.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlTraitParser.java index cc0bb591961..053a906bf01 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlTraitParser.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/IdlTraitParser.java @@ -158,12 +158,12 @@ static Result expectAndSkipTrait(IdlModelLoader loader) { private static Node parseTraitValueBody(IdlModelLoader loader, SourceLocation location) { IdlInternalTokenizer tokenizer = loader.getTokenizer(); tokenizer.expect( - IdlToken.LBRACE, - IdlToken.LBRACKET, - IdlToken.TEXT_BLOCK, - IdlToken.STRING, - IdlToken.NUMBER, - IdlToken.IDENTIFIER + IdlToken.LBRACE, + IdlToken.LBRACKET, + IdlToken.TEXT_BLOCK, + IdlToken.STRING, + IdlToken.NUMBER, + IdlToken.IDENTIFIER ); switch (tokenizer.getCurrentToken()) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoadOperation.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoadOperation.java index ed908aed591..fc2c6fbd20c 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoadOperation.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoadOperation.java @@ -76,12 +76,12 @@ static final class ApplyTrait extends LoadOperation { final SourceLocation location; ApplyTrait( - Version version, - SourceLocation location, - String namespace, - ShapeId target, - ShapeId trait, - Node value + Version version, + SourceLocation location, + String namespace, + ShapeId target, + ShapeId trait, + Node value ) { super(version); this.namespace = namespace; @@ -93,12 +93,12 @@ static final class ApplyTrait extends LoadOperation { static ApplyTrait from(ShapeId target, Trait trait) { return new ApplyTrait( - Version.UNKNOWN, - trait.getSourceLocation(), - target.getNamespace(), - target, - trait.toShapeId(), - trait.toNode() + Version.UNKNOWN, + trait.getSourceLocation(), + target.getNamespace(), + target, + trait.toShapeId(), + trait.toNode() ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoadOperationProcessor.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoadOperationProcessor.java index 4254755441a..6574e49a3ea 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoadOperationProcessor.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoadOperationProcessor.java @@ -34,11 +34,11 @@ final class LoadOperationProcessor implements Consumer { private final Map modelVersions = new HashMap<>(); LoadOperationProcessor( - TraitFactory traitFactory, - Model prelude, - boolean allowUnknownTraits, - Consumer validationEventListener, - ValidationEventDecorator decorator + TraitFactory traitFactory, + Model prelude, + boolean allowUnknownTraits, + Consumer validationEventListener, + ValidationEventDecorator decorator ) { // Emit events as the come in. this.events = new ArrayList() { @@ -95,7 +95,7 @@ public void event(LoadOperation.Event operation) { public void modelVersion(LoadOperation.ModelVersion operation) { // Don't attempt to assign versions based on N/A or "" source locations. if (!operation.getSourceLocation().equals(SourceLocation.none()) - && !operation.getSourceLocation().getFilename().isEmpty()) { + && !operation.getSourceLocation().getFilename().isEmpty()) { modelVersions.put(operation.getSourceLocation().getFilename(), operation.version); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderShapeMap.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderShapeMap.java index 15b0663bf48..cfe7c5caa92 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderShapeMap.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderShapeMap.java @@ -159,8 +159,8 @@ void moveCreatedShapeToOperations(ShapeId shapeId, Consumer proce } void buildShapesAndClaimMixinTraits( - Model.Builder modelBuilder, - Function> unclaimedTraits + Model.Builder modelBuilder, + Function> unclaimedTraits ) { Function createdShapeMap = id -> modelBuilder.getCurrentShapes().get(id); @@ -177,10 +177,10 @@ void buildShapesAndClaimMixinTraits( // Build each pending shape in the wrapper and perform conflict resolution. private void buildIntoModel( - ShapeWrapper wrapper, - Model.Builder builder, - Function> unclaimedTraits, - Function createdShapeMap + ShapeWrapper wrapper, + Model.Builder builder, + Function> unclaimedTraits, + Function createdShapeMap ) { Shape built = null; for (LoadOperation.DefineShape shape : wrapper) { @@ -253,21 +253,21 @@ private void emitUnresolved(LoadOperation.DefineShape shape, Set unreso } events.add( - ValidationEvent.builder() - .id(Validator.MODEL_ERROR) - .severity(Severity.ERROR) - .shapeId(shape.toShapeId()) - .sourceLocation(shape) - .message(message.toString()) - .build() + ValidationEvent.builder() + .id(Validator.MODEL_ERROR) + .severity(Severity.ERROR) + .shapeId(shape.toShapeId()) + .sourceLocation(shape) + .message(message.toString()) + .build() ); } private boolean anyMissingTransitiveDependencies( - ShapeId current, - List resolved, - Set unresolved, - Set visited + ShapeId current, + List resolved, + Set unresolved, + Set visited ) { if (resolved.contains(current)) { return false; @@ -291,18 +291,18 @@ private boolean anyMissingTransitiveDependencies( private boolean validateShapeVersion(LoadOperation.DefineShape operation) { if (!operation.version.isShapeTypeSupported(operation.getShapeType())) { events.add( - ValidationEvent.builder() - .severity(Severity.ERROR) - .id(Validator.MODEL_ERROR) - .shapeId(operation.toShapeId()) - .sourceLocation(operation) - .message( - String.format( - "%s shapes cannot be used in Smithy version " + operation.version, - operation.getShapeType() - ) - ) - .build() + ValidationEvent.builder() + .severity(Severity.ERROR) + .id(Validator.MODEL_ERROR) + .shapeId(operation.toShapeId()) + .sourceLocation(operation) + .message( + String.format( + "%s shapes cannot be used in Smithy version " + operation.version, + operation.getShapeType() + ) + ) + .build() ); return false; } @@ -326,9 +326,9 @@ private boolean validateConflicts(ShapeId id, Shape built, Shape previous) { joiner.add("Left has trait " + tid); } else if (!previous.getAllTraits().get(tid).equals(t)) { joiner.add( - "Left trait " + tid + " differs from right trait. " - + Node.printJson(t.toNode()) + " vs " - + Node.printJson(previous.getAllTraits().get(tid).toNode()) + "Left trait " + tid + " differs from right trait. " + + Node.printJson(t.toNode()) + " vs " + + Node.printJson(previous.getAllTraits().get(tid).toNode()) ); } }); @@ -340,32 +340,32 @@ private boolean validateConflicts(ShapeId id, Shape built, Shape previous) { } if (!built.getAllMembers().equals(previous.getAllMembers())) { joiner.add( - "Members differ: " + built.getAllMembers().keySet() - + " vs " + previous.getAllMembers().keySet() + "Members differ: " + built.getAllMembers().keySet() + + " vs " + previous.getAllMembers().keySet() ); } events.add( - LoaderUtils.onShapeConflict( - id, - built.getSourceLocation(), - previous.getSourceLocation(), - joiner.toString() - ) + LoaderUtils.onShapeConflict( + id, + built.getSourceLocation(), + previous.getSourceLocation(), + joiner.toString() + ) ); return false; } else if (!LoaderUtils.isSameLocation(built, previous)) { events.add( - ValidationEvent.builder() - .id(Validator.MODEL_ERROR + ".IgnoredDuplicateDefinition") - .severity(Severity.NOTE) - .sourceLocation(previous.getSourceLocation()) - .shapeId(id) - .message( - "Ignoring duplicate but equivalent shape definition: " + id - + " defined at " + built.getSourceLocation() + " and " - + previous.getSourceLocation() - ) - .build() + ValidationEvent.builder() + .id(Validator.MODEL_ERROR + ".IgnoredDuplicateDefinition") + .severity(Severity.NOTE) + .sourceLocation(previous.getSourceLocation()) + .shapeId(id) + .message( + "Ignoring duplicate but equivalent shape definition: " + id + + " defined at " + built.getSourceLocation() + " and " + + previous.getSourceLocation() + ) + .build() ); } } @@ -373,9 +373,9 @@ private boolean validateConflicts(ShapeId id, Shape built, Shape previous) { } private Shape buildShape( - LoadOperation.DefineShape defineShape, - Function> traitClaimer, - Function createdShapeMap + LoadOperation.DefineShape defineShape, + Function> traitClaimer, + Function createdShapeMap ) { try { AbstractShapeBuilder builder = defineShape.builder(); @@ -415,16 +415,16 @@ private MemberShape buildMember(MemberShape.Builder builder) { } catch (IllegalStateException e) { if (builder.getTarget() == null) { events.add( - ValidationEvent.builder() - .severity(Severity.ERROR) - .id(Validator.MODEL_ERROR) - .shapeId(builder.getId()) - .sourceLocation(builder) - .message( - "Member target was elided, but no bound resource or mixin contained a matching " - + "identifier or member name." - ) - .build() + ValidationEvent.builder() + .severity(Severity.ERROR) + .id(Validator.MODEL_ERROR) + .shapeId(builder.getId()) + .sourceLocation(builder) + .message( + "Member target was elided, but no bound resource or mixin contained a matching " + + "identifier or member name." + ) + .build() ); return null; } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderTraitMap.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderTraitMap.java index 580c7dcf8a1..534ee14d0e7 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderTraitMap.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderTraitMap.java @@ -56,8 +56,8 @@ void applyTraitsToNonMixinsInShapeMap(LoaderShapeMap shapeMap) { // will have already converted the built shape into a pending shape. boolean found = shapeMap.isShapePending(target); Iterable rootShapes = found - ? shapeMap.get(root) - : Collections::emptyIterator; + ? shapeMap.get(root) + : Collections::emptyIterator; for (Map.Entry traitEntry : entry.getValue().entrySet()) { ShapeId traitId = traitEntry.getKey(); @@ -88,7 +88,7 @@ void applyTraitsToNonMixinsInShapeMap(LoaderShapeMap shapeMap) { // If the member wasn't found, then it might be a mixin member that is synthesized later. if (!foundMember) { unclaimed.computeIfAbsent(target.withMember(memberName), id -> new LinkedHashMap<>()) - .put(traitId, created); + .put(traitId, created); } } else if (found) { // Apply the trait to each shape contained in the shape map for the given target. @@ -105,54 +105,54 @@ void applyTraitsToNonMixinsInShapeMap(LoaderShapeMap shapeMap) { private Trait createTrait(ShapeId target, ShapeId traitId, Node traitValue) { try { return traitFactory.createTrait(traitId, target, traitValue) - .orElseGet(() -> new DynamicTrait(traitId, traitValue)); + .orElseGet(() -> new DynamicTrait(traitId, traitValue)); } catch (SourceException e) { String message = format("Error creating trait `%s`: ", Trait.getIdiomaticTraitName(traitId)); events.add(ValidationEvent.fromSourceException(e, message, target)); return null; } catch (RuntimeException e) { events.add( - ValidationEvent.builder() - .id(MODEL_ERROR) - .severity(ERROR) - .shapeId(target) - .sourceLocation(traitValue) - .message( - format( - "Error creating trait `%s`: %s", - Trait.getIdiomaticTraitName(traitId), - e.getMessage() - ) - ) - .build() + ValidationEvent.builder() + .id(MODEL_ERROR) + .severity(ERROR) + .shapeId(target) + .sourceLocation(traitValue) + .message( + format( + "Error creating trait `%s`: %s", + Trait.getIdiomaticTraitName(traitId), + e.getMessage() + ) + ) + .build() ); return null; } } private void validateTraitIsKnown( - ShapeId target, - ShapeId traitId, - Trait trait, - SourceLocation sourceLocation, - LoaderShapeMap shapeMap + ShapeId target, + ShapeId traitId, + Trait trait, + SourceLocation sourceLocation, + LoaderShapeMap shapeMap ) { if (!shapeMap.isRootShapeDefined(traitId) && (trait == null || !trait.isSynthetic())) { Severity severity = allowUnknownTraits ? Severity.WARNING : Severity.ERROR; events.add( - ValidationEvent.builder() - .id(Validator.MODEL_ERROR + UNRESOLVED_TRAIT_SUFFIX) - .severity(severity) - .sourceLocation(sourceLocation) - .shapeId(target) - .message( - String.format( - "Unable to resolve trait `%s`. If this is a custom trait, then it must be " - + "defined before it can be used in a model.", - traitId - ) - ) - .build() + ValidationEvent.builder() + .id(Validator.MODEL_ERROR + UNRESOLVED_TRAIT_SUFFIX) + .severity(severity) + .sourceLocation(sourceLocation) + .shapeId(target) + .message( + String.format( + "Unable to resolve trait `%s`. If this is a custom trait, then it must be " + + "defined before it can be used in a model.", + traitId + ) + ) + .build() ); } } @@ -181,18 +181,18 @@ void emitUnclaimedTraits() { } for (Map.Entry traitEntry : entry.getValue().entrySet()) { events.add( - ValidationEvent.builder() - .id(Validator.MODEL_ERROR) - .severity(Severity.ERROR) - .sourceLocation(traitEntry.getValue()) - .message( - String.format( - "Trait `%s` applied to unknown shape `%s`", - Trait.getIdiomaticTraitName(traitEntry.getKey()), - entry.getKey() - ) - ) - .build() + ValidationEvent.builder() + .id(Validator.MODEL_ERROR) + .severity(Severity.ERROR) + .sourceLocation(traitEntry.getValue()) + .message( + String.format( + "Trait `%s` applied to unknown shape `%s`", + Trait.getIdiomaticTraitName(traitEntry.getKey()), + entry.getKey() + ) + ) + .build() ); } } @@ -202,17 +202,17 @@ void add(LoadOperation.ApplyTrait operation) { if (validateTraitVersion(operation)) { if (isAppliedToPreludeOutsidePrelude(operation)) { String message = String.format( - "Cannot apply `%s` to an immutable prelude shape defined in `smithy.api`.", - operation.trait + "Cannot apply `%s` to an immutable prelude shape defined in `smithy.api`.", + operation.trait ); events.add( - ValidationEvent.builder() - .severity(Severity.ERROR) - .id(Validator.MODEL_ERROR) - .sourceLocation(operation) - .shapeId(operation.target) - .message(message) - .build() + ValidationEvent.builder() + .severity(Severity.ERROR) + .id(Validator.MODEL_ERROR) + .sourceLocation(operation) + .shapeId(operation.target) + .message(message) + .build() ); } else { Map current = traits.computeIfAbsent(operation.target, id -> new LinkedHashMap<>()); @@ -224,9 +224,9 @@ void add(LoadOperation.ApplyTrait operation) { private boolean validateTraitVersion(LoadOperation.ApplyTrait operation) { ValidationEvent event = operation.version.validateVersionedTrait( - operation.target, - operation.trait, - operation.value + operation.target, + operation.trait, + operation.value ); if (event != null) { events.add(event); @@ -236,7 +236,7 @@ private boolean validateTraitVersion(LoadOperation.ApplyTrait operation) { private boolean isAppliedToPreludeOutsidePrelude(LoadOperation.ApplyTrait operation) { return !operation.namespace.equals(Prelude.NAMESPACE) - && operation.target.getNamespace().equals(Prelude.NAMESPACE); + && operation.target.getNamespace().equals(Prelude.NAMESPACE); } private Node mergeTraits(ShapeId target, ShapeId traitId, Node previous, Node updated) { @@ -253,11 +253,11 @@ private Node mergeTraits(ShapeId target, ShapeId traitId, Node previous, Node up // added to a subsequent ModelAssembler, and then model discovery is // performed again using the same classpath. LOGGER.finest( - () -> String.format( - "Ignoring duplicate %s trait value on %s at same exact location", - traitId, - target - ) + () -> String.format( + "Ignoring duplicate %s trait value on %s at same exact location", + traitId, + target + ) ); return previous; } @@ -270,22 +270,22 @@ private Node mergeTraits(ShapeId target, ShapeId traitId, Node previous, Node up return previous; } else { events.add( - ValidationEvent.builder() - .id(Validator.MODEL_ERROR) - .severity(Severity.ERROR) - .sourceLocation(updated) - .shapeId(target) - .message( - String.format( - "Conflicting `%s` trait found on shape `%s`. The previous trait was " - + "defined at `%s`, and a conflicting trait was defined at `%s`.", - traitId, - target, - previous.getSourceLocation(), - updated.getSourceLocation() - ) - ) - .build() + ValidationEvent.builder() + .id(Validator.MODEL_ERROR) + .severity(Severity.ERROR) + .sourceLocation(updated) + .shapeId(target) + .message( + String.format( + "Conflicting `%s` trait found on shape `%s`. The previous trait was " + + "defined at `%s`, and a conflicting trait was defined at `%s`.", + traitId, + target, + previous.getSourceLocation(), + updated.getSourceLocation() + ) + ) + .build() ); return previous; } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderUtils.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderUtils.java index 5d4e78fce5f..a4bce447967 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderUtils.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderUtils.java @@ -33,19 +33,19 @@ private LoaderUtils() {} * @return Returns an optionally created event. */ static Optional checkForAdditionalProperties( - ObjectNode node, - ShapeId shape, - Collection properties + ObjectNode node, + ShapeId shape, + Collection properties ) { try { node.expectNoAdditionalProperties(properties); return Optional.empty(); } catch (ExpectationNotMetException e) { ValidationEvent event = ValidationEvent.fromSourceException(e) - .toBuilder() - .shapeId(shape) - .severity(Severity.WARNING) - .build(); + .toBuilder() + .shapeId(shape) + .severity(Severity.WARNING) + .build(); return Optional.of(event); } } @@ -65,12 +65,12 @@ static ValidationEvent onShapeConflict(ShapeId id, SourceLocation a, SourceLocat formatted += ". " + message; } return ValidationEvent.builder() - .id(Validator.MODEL_ERROR) - .severity(Severity.ERROR) - .sourceLocation(b) - .shapeId(id) - .message(formatted) - .build(); + .id(Validator.MODEL_ERROR) + .severity(Severity.ERROR) + .sourceLocation(b) + .shapeId(id) + .message(formatted) + .build(); } /** @@ -104,16 +104,16 @@ static boolean containsErrorEvents(List events) { static ValidationEvent emitBadDocComment(SourceLocation location, String comments) { String message = "Found documentation comments ('///') attached to nothing. Documentation comments must " - + "appear on their own lines, directly before shapes and members, and before any traits."; + + "appear on their own lines, directly before shapes and members, and before any traits."; if (comments != null) { message += " The invalid comments were: " + comments; } return ValidationEvent.builder() - .id(BAD_DOCUMENTATION_COMMENT) - .severity(Severity.WARNING) - .message(message) - .sourceLocation(location) - .build(); + .id(BAD_DOCUMENTATION_COMMENT) + .severity(Severity.WARNING) + .message(message) + .sourceLocation(location) + .build(); } static String idlExpectMessage(IdlTokenizer tokenizer, IdlToken... tokens) { @@ -123,9 +123,9 @@ static String idlExpectMessage(IdlTokenizer tokenizer, IdlToken... tokens) { result.append(tokenizer.getCurrentTokenError()); } else if (tokens.length == 1) { result.append("Expected ") - .append(tokens[0].getDebug()) - .append(" but found ") - .append(current.getDebug(tokenizer.getCurrentTokenLexeme())); + .append(tokens[0].getDebug()) + .append(" but found ") + .append(current.getDebug(tokenizer.getCurrentTokenLexeme())); } else { result.append("Expected one of "); for (IdlToken token : tokens) { @@ -143,16 +143,16 @@ static ModelSyntaxException idlSyntaxError(String message, SourceLocation locati static ModelSyntaxException idlSyntaxError(ShapeId shape, String message, SourceLocation location) { return ModelSyntaxException.builder() - .message( - format( - "Syntax error at line %d, column %d: %s", - location.getLine(), - location.getColumn(), - message + .message( + format( + "Syntax error at line %d, column %d: %s", + location.getLine(), + location.getColumn(), + message + ) ) - ) - .sourceLocation(location) - .shapeId(shape) - .build(); + .sourceLocation(location) + .shapeId(shape) + .build(); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/MetadataContainer.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/MetadataContainer.java index e326350d5e3..09a9e40c641 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/MetadataContainer.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/MetadataContainer.java @@ -60,19 +60,19 @@ void putMetadata(String key, Node value, List events) { data.put(key, new ArrayNode(merged, value.getSourceLocation())); } else if (!previous.equals(value)) { events.add( - ValidationEvent.builder() - .id(Validator.MODEL_ERROR) - .severity(Severity.ERROR) - .sourceLocation(value) - .message( - format( - "Metadata conflict for key `%s`. Defined in both `%s` and `%s`", - key, - value.getSourceLocation(), - previous.getSourceLocation() - ) - ) - .build() + ValidationEvent.builder() + .id(Validator.MODEL_ERROR) + .severity(Severity.ERROR) + .sourceLocation(value) + .message( + format( + "Metadata conflict for key `%s`. Defined in both `%s` and `%s`", + key, + value.getSourceLocation(), + previous.getSourceLocation() + ) + ) + .build() ); } else { LOGGER.fine(() -> "Ignoring duplicate metadata definition of " + key); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelAssembler.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelAssembler.java index 32b128daac9..367313b7cf1 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelAssembler.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelAssembler.java @@ -208,8 +208,8 @@ public ModelAssembler addValidator(Validator validator) { */ public ModelAssembler addUnparsedModel(String sourceLocation, String model) { inputStreamModels.put( - sourceLocation, - () -> new ByteArrayInputStream(model.getBytes(StandardCharsets.UTF_8)) + sourceLocation, + () -> new ByteArrayInputStream(model.getBytes(StandardCharsets.UTF_8)) ); return this; } @@ -251,9 +251,9 @@ public ModelAssembler addImport(Path importPath) { if (Files.isDirectory(importPath)) { try ( - Stream files = Files.walk(importPath, FileVisitOption.FOLLOW_LINKS) - .filter(p -> !p.equals(importPath)) - .filter(p -> Files.isDirectory(p) || Files.isRegularFile(p)) + Stream files = Files.walk(importPath, FileVisitOption.FOLLOW_LINKS) + .filter(p -> !p.equals(importPath)) + .filter(p -> Files.isDirectory(p) || Files.isRegularFile(p)) ) { files.forEach(this::addImport); } catch (IOException e) { @@ -266,8 +266,8 @@ public ModelAssembler addImport(Path importPath) { return Files.newInputStream(importPath); } catch (IOException e) { throw new ModelImportException( - "Unable to import Smithy model from " + importPath + ": " + e.getMessage(), - e + "Unable to import Smithy model from " + importPath + ": " + e.getMessage(), + e ); } }); @@ -513,11 +513,11 @@ public ValidatedResult assemble() { // As issues are encountered, they are decorated and then emitted. LoadOperationProcessor processor = new LoadOperationProcessor( - traitFactory, - prelude, - areUnknownTraitsAllowed(), - validationEventListener, - decorator + traitFactory, + prelude, + areUnknownTraitsAllowed(), + validationEventListener, + decorator ); List events = processor.events(); @@ -574,13 +574,13 @@ public ValidatedResult assemble() { try { List mergedEvents = ModelValidator.builder() - .addValidators(validators) - .validatorFactory(validatorFactory, decorator) - .eventListener(validationEventListener) - .includeEvents(events) - .legacyValidationMode((boolean) properties.getOrDefault("LEGACY_VALIDATION_MODE", false)) - .build() - .validate(transformed); + .addValidators(validators) + .validatorFactory(validatorFactory, decorator) + .eventListener(validationEventListener) + .includeEvents(events) + .legacyValidationMode((boolean) properties.getOrDefault("LEGACY_VALIDATION_MODE", false)) + .build() + .validate(transformed); return new ValidatedResult<>(transformed, mergedEvents); } catch (SourceException e) { events.add(ValidationEvent.fromSourceException(e)); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelDiscovery.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelDiscovery.java index e3f74a62f96..b35076079e6 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelDiscovery.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelDiscovery.java @@ -207,9 +207,9 @@ private static Set parseManifest(URL location) throws IOException { connection.setUseCaches(false); try ( - InputStream input = connection.getInputStream(); BufferedReader reader = new BufferedReader( - new InputStreamReader(input, StandardCharsets.UTF_8) - ) + InputStream input = connection.getInputStream(); BufferedReader reader = new BufferedReader( + new InputStreamReader(input, StandardCharsets.UTF_8) + ) ) { for (;;) { String line = reader.readLine(); @@ -220,11 +220,11 @@ private static Set parseManifest(URL location) throws IOException { // Ignore comments. } else if (!isValidateResourceLine(line)) { throw new ModelManifestException( - format( - "Illegal Smithy model manifest syntax found in `%s`: `%s`", - location, - line - ) + format( + "Illegal Smithy model manifest syntax found in `%s`: `%s`", + location, + line + ) ); } else { models.add(line); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelInteropTransformer.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelInteropTransformer.java index 377a8fee003..f4e63c493fa 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelInteropTransformer.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelInteropTransformer.java @@ -49,14 +49,14 @@ final class ModelInteropTransformer { /** Shape types in Smithy 1.0 that had a default value. */ private static final EnumSet HAD_DEFAULT_VALUE_IN_1_0 = EnumSet.of( - ShapeType.BYTE, - ShapeType.SHORT, - ShapeType.INTEGER, - ShapeType.LONG, - ShapeType.FLOAT, - ShapeType.DOUBLE, - ShapeType.BOOLEAN, - ShapeType.INT_ENUM + ShapeType.BYTE, + ShapeType.SHORT, + ShapeType.INTEGER, + ShapeType.LONG, + ShapeType.FLOAT, + ShapeType.DOUBLE, + ShapeType.BOOLEAN, + ShapeType.INT_ENUM ); // intEnum is actually an integer in v1, but the ShapeType is different. private final Model model; @@ -119,10 +119,10 @@ private boolean shouldV1MemberHaveDefaultTrait(MemberShape member, Shape target) // Only when the targeted shape had a default value by default in v1 or if // the member targets a streaming blob, which implies a default in 2.0 return (HAD_DEFAULT_VALUE_IN_1_0.contains(target.getType()) || streamingBlobNeedsDefault(member, target)) - // Don't re-add the @default trait - && !member.hasTrait(DefaultTrait.ID) - // Don't add a @default trait if the member or target are considered boxed in v1. - && memberAndTargetAreNotAlreadyExplicitlyBoxed(member, target); + // Don't re-add the @default trait + && !member.hasTrait(DefaultTrait.ID) + // Don't add a @default trait if the member or target are considered boxed in v1. + && memberAndTargetAreNotAlreadyExplicitlyBoxed(member, target); } private boolean streamingBlobNeedsDefault(MemberShape member, Shape target) { @@ -155,7 +155,7 @@ private void patchV2MemberForV1Support(MemberShape member, Shape target) { private boolean v2ShapeNeedsBoxTrait(MemberShape member, Shape target) { return isMemberInherentlyBoxedInV1(member) - && memberAndTargetAreNotAlreadyExplicitlyBoxed(member, target); + && memberAndTargetAreNotAlreadyExplicitlyBoxed(member, target); } // Only apply box to members where the trait can be applied. @@ -181,9 +181,9 @@ private boolean memberDoesNotHaveDefaultZeroValueTrait(MemberShape member, Shape } static void patchShapeBeforeBuilding( - LoadOperation.DefineShape defineShape, - AbstractShapeBuilder builder, - List events + LoadOperation.DefineShape defineShape, + AbstractShapeBuilder builder, + List events ) { handleBoxing(defineShape, builder); } @@ -208,7 +208,7 @@ private static void handleBoxing(LoadOperation.DefineShape defineShape, Abstract Trait defaultTrait = builder.getAllTraits().get(DefaultTrait.ID); Node defaultValue = defaultTrait == null ? null : defaultTrait.toNode(); boolean isDefaultZeroValue = NullableIndex - .isDefaultZeroValueOfTypeInV1(defaultValue, defineShape.getShapeType()); + .isDefaultZeroValueOfTypeInV1(defaultValue, defineShape.getShapeType()); if (!isDefaultZeroValue) { builder.addTrait(new BoxTrait()); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelLoader.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelLoader.java index 2c714856beb..03499e0d747 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelLoader.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelLoader.java @@ -48,12 +48,12 @@ private ModelLoader() {} * @throws SourceException if there is an error reading from the contents. */ static boolean load( - TraitFactory traitFactory, - Map properties, - String filename, - Consumer operationConsumer, - Supplier contentSupplier, - Function stringTable + TraitFactory traitFactory, + Map properties, + String filename, + Consumer operationConsumer, + Supplier contentSupplier, + Function stringTable ) { try { if (filename.endsWith(".smithy")) { @@ -92,8 +92,8 @@ static boolean loadParsedNode(Node node, Consumer operationConsum Version version = Version.fromString(versionNode.getValue()); if (version == null) { throw new ModelSyntaxException( - "Unsupported Smithy version number: " + versionNode.getValue(), - versionNode + "Unsupported Smithy version number: " + versionNode.getValue(), + versionNode ); } else { new AstModelLoader(version, model).parse(operationConsumer); @@ -109,11 +109,11 @@ static boolean loadParsedNode(Node node, Consumer operationConsum // Allows importing JAR files by discovering models inside a JAR file. // This is similar to model discovery, but done using an explicit import. private static void loadJar( - TraitFactory traitFactory, - Map properties, - String filename, - Consumer operationConsumer, - Function stringTable + TraitFactory traitFactory, + Map properties, + String filename, + Consumer operationConsumer, + Function stringTable ) { URL manifestUrl = ModelDiscovery.createSmithyJarManifestUrl(filename); LOGGER.fine(() -> "Loading Smithy model imports from JAR: " + manifestUrl); @@ -147,8 +147,8 @@ private static void loadJar( private static ModelImportException throwIoJarException(URL model, Throwable e) { return new ModelImportException( - String.format("Error loading Smithy model from URL `%s`: %s", model, e.getMessage()), - e + String.format("Error loading Smithy model from URL `%s`: %s", model, e.getMessage()), + e ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelValidator.java index 07d1efc4e1c..304f75f9ad9 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ModelValidator.java @@ -55,16 +55,16 @@ final class ModelValidator implements Validator { // Lazy initialization holder class idiom to hold a default validator factory. private static final class LazyValidatorFactoryHolder { static final ValidatorFactory INSTANCE = ValidatorFactory.createServiceFactory( - ModelAssembler.class.getClassLoader() + ModelAssembler.class.getClassLoader() ); } /** If these validators fail, then many others will too. Validate these first. */ private static final Map, Validator> CORRECTNESS_VALIDATORS = MapUtils.of( - TargetValidator.class, - new TargetValidator(), - ResourceCycleValidator.class, - new ResourceCycleValidator() + TargetValidator.class, + new TargetValidator(), + ResourceCycleValidator.class, + new ResourceCycleValidator() ); private final ValidatorFactory validatorFactory; @@ -148,8 +148,8 @@ public Builder addValidator(Validator validator) { * @return Returns the builder. */ public Builder validatorFactory( - ValidatorFactory validatorFactory, - ValidationEventDecorator validationEventDecorator + ValidatorFactory validatorFactory, + ValidationEventDecorator validationEventDecorator ) { this.validatorFactory = Objects.requireNonNull(validatorFactory); this.validationEventDecorator = validationEventDecorator; @@ -222,12 +222,12 @@ private LoadedModelValidator(Model model, ModelValidator validator) { ModelBasedEventDecorator modelBasedEventDecorator = new ModelBasedEventDecorator(); ValidatedResult result = modelBasedEventDecorator.createDecorator(model); this.validationEventDecorator = result.getResult() - .map( - decorator -> ValidationEventDecorator.compose( - ListUtils.of(decorator, validator.validationEventDecorator) + .map( + decorator -> ValidationEventDecorator.compose( + ListUtils.of(decorator, validator.validationEventDecorator) + ) ) - ) - .orElse(validator.validationEventDecorator); + .orElse(validator.validationEventDecorator); // Events encountered while loading suppressions and overrides have been modified by everything the // modelBasedEventDecorator knows about, but has not been modified by any custom decorator (if any). @@ -250,7 +250,7 @@ private LoadedModelValidator(Model model, ModelValidator validator) { private void loadModelValidators(ValidatorFactory validatorFactory) { // Load validators defined in metadata. ValidatedResult> loaded = ValidationLoader - .loadValidators(model.getMetadata()); + .loadValidators(model.getMetadata()); pushEvents(loaded.getValidationEvents()); List definitions = loaded.getResult().orElseGet(Collections::emptyList); ValidatorFromDefinitionFactory factory = new ValidatorFromDefinitionFactory(validatorFactory); @@ -270,12 +270,12 @@ private void loadModelValidators(ValidatorFactory validatorFactory) { // Unknown validators don't fail the build! private static ValidationEvent unknownValidatorError(String name, SourceLocation location) { return ValidationEvent.builder() - // Per the spec, the eventID is "UnknownValidator_". - .id("UnknownValidator_" + name) - .severity(Severity.WARNING) - .sourceLocation(location) - .message("Unable to locate a validator named `" + name + "`") - .build(); + // Per the spec, the eventID is "UnknownValidator_". + .id("UnknownValidator_" + name) + .severity(Severity.WARNING) + .sourceLocation(location) + .message("Unable to locate a validator named `" + name + "`") + .build(); } private void pushEvents(List source) { @@ -317,10 +317,10 @@ private List validate() { private List streamEvents(Stream validators) { return validators - .flatMap(validator -> validator.validate(model).stream()) - .filter(this::filterPrelude) - .map(this::updateAndEmitEvent) - .collect(Collectors.toList()); + .flatMap(validator -> validator.validate(model).stream()) + .filter(this::filterPrelude) + .map(this::updateAndEmitEvent) + .collect(Collectors.toList()); } private boolean filterPrelude(ValidationEvent event) { @@ -328,8 +328,8 @@ private boolean filterPrelude(ValidationEvent event) { // This prevents custom validators from unnecessarily needing to worry about prelude shapes and trait // definitions, but still allows for validation events when the prelude is broken. return event.getSeverity() == Severity.ERROR || !event.getShapeId() - .filter(Prelude::isPreludeShape) - .isPresent(); + .filter(Prelude::isPreludeShape) + .isPresent(); } } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ParserUtils.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ParserUtils.java index d0378ca098f..f5008380445 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ParserUtils.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ParserUtils.java @@ -56,7 +56,7 @@ public static String parseNumber(SimpleParser parser) { } if (parser.consumeWhile(ParserUtils::isDigit) == 0) { throw parser.syntax( - createInvalidString(parser, startPosition, "'e', '+', and '-' must be followed by a digit") + createInvalidString(parser, startPosition, "'e', '+', and '-' must be followed by a digit") ); } } @@ -165,8 +165,8 @@ public static void consumeIdentifier(SimpleParser parser) { private static RuntimeException invalidIdentifier(SimpleParser parser) { throw parser.syntax( - "Expected a valid identifier character, but found '" - + parser.peekSingleCharForMessage() + '\'' + "Expected a valid identifier character, but found '" + + parser.peekSingleCharForMessage() + '\'' ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/Prelude.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/Prelude.java index 7e1235214b8..cad71d20921 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/Prelude.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/Prelude.java @@ -50,8 +50,8 @@ public static boolean isPreludeShape(ToShapeId id) { */ public static boolean isPublicPreludeShape(ToShapeId id) { return getPreludeModel().getShape(id.toShapeId()) - .filter(shape -> !shape.hasTrait(PrivateTrait.class)) - .isPresent(); + .filter(shape -> !shape.hasTrait(PrivateTrait.class)) + .isPresent(); } // Used by the ModelAssembler to load the prelude into another visitor. @@ -65,27 +65,27 @@ private static final class PreludeHolder { private static Model loadPrelude() { return Model.assembler() - .disablePrelude() - // Model validation is disabled when loading the prelude - // because the prelude is validated during unit tests and - // the prelude is immutable. However, if the prelude is - // broken for whatever reason, ERROR events encountered - // when performing model validation that uses the prelude - // will still cause an error, meaning the prelude is still - // validated when actually loading and using other models. - .disableValidation() - .traitFactory(ModelAssembler.LazyTraitFactoryHolder.INSTANCE) - .addImport(Prelude.class.getResource("prelude.smithy")) - // Patch in synthetic box traits for v1 compatibility. - .addTrait(ShapeId.from("smithy.api#Boolean"), new BoxTrait()) - .addTrait(ShapeId.from("smithy.api#Byte"), new BoxTrait()) - .addTrait(ShapeId.from("smithy.api#Short"), new BoxTrait()) - .addTrait(ShapeId.from("smithy.api#Integer"), new BoxTrait()) - .addTrait(ShapeId.from("smithy.api#Long"), new BoxTrait()) - .addTrait(ShapeId.from("smithy.api#Float"), new BoxTrait()) - .addTrait(ShapeId.from("smithy.api#Double"), new BoxTrait()) - .assemble() - .unwrap(); + .disablePrelude() + // Model validation is disabled when loading the prelude + // because the prelude is validated during unit tests and + // the prelude is immutable. However, if the prelude is + // broken for whatever reason, ERROR events encountered + // when performing model validation that uses the prelude + // will still cause an error, meaning the prelude is still + // validated when actually loading and using other models. + .disableValidation() + .traitFactory(ModelAssembler.LazyTraitFactoryHolder.INSTANCE) + .addImport(Prelude.class.getResource("prelude.smithy")) + // Patch in synthetic box traits for v1 compatibility. + .addTrait(ShapeId.from("smithy.api#Boolean"), new BoxTrait()) + .addTrait(ShapeId.from("smithy.api#Byte"), new BoxTrait()) + .addTrait(ShapeId.from("smithy.api#Short"), new BoxTrait()) + .addTrait(ShapeId.from("smithy.api#Integer"), new BoxTrait()) + .addTrait(ShapeId.from("smithy.api#Long"), new BoxTrait()) + .addTrait(ShapeId.from("smithy.api#Float"), new BoxTrait()) + .addTrait(ShapeId.from("smithy.api#Double"), new BoxTrait()) + .assemble() + .unwrap(); } } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ShapeModifier.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ShapeModifier.java index 3b377156e53..25f49da3415 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ShapeModifier.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ShapeModifier.java @@ -29,10 +29,10 @@ interface ShapeModifier { * @param shapeMap A function that returns a shape for a given ID, or null. */ default void modifyMember( - AbstractShapeBuilder shapeBuilder, - MemberShape.Builder memberBuilder, - Function> unclaimedTraits, - Function shapeMap + AbstractShapeBuilder shapeBuilder, + MemberShape.Builder memberBuilder, + Function> unclaimedTraits, + Function shapeMap ) { } @@ -47,10 +47,10 @@ default void modifyMember( * @param shapeMap A function that returns a shape for a given ID, or null. */ default void modifyShape( - AbstractShapeBuilder builder, - Map memberBuilders, - Function> unclaimedTraits, - Function shapeMap + AbstractShapeBuilder builder, + Map memberBuilders, + Function> unclaimedTraits, + Function shapeMap ) { } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidationLoader.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidationLoader.java index 323dbb40bd6..5355bf22b23 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidationLoader.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidationLoader.java @@ -23,13 +23,13 @@ final class ValidationLoader { private static final List SEVERITIES = ListUtils.of("DANGER", "WARNING", "NOTE"); private static final List VALIDATOR_PROPERTIES = ListUtils.of( - "name", - "id", - "message", - "severity", - "namespaces", - "selector", - "configuration" + "name", + "id", + "message", + "severity", + "namespaces", + "selector", + "configuration" ); private ValidationLoader() {} @@ -47,7 +47,7 @@ static ValidatedResult> loadValidators(Map value.expectOneOf(SEVERITIES)) - .map(value -> Severity.fromString(value).get()) - .orElse(null); + .map(value -> value.expectOneOf(SEVERITIES)) + .map(value -> Severity.fromString(value).get()) + .orElse(null); node.getMember("namespaces").ifPresent(value -> def.namespaces.addAll(loadArrayOfString("namespaces", value))); def.configuration = node.getObjectMember("configuration").orElse(Node.objectNode()); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidatorDefinition.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidatorDefinition.java index aa55a6b585e..c1fda22c7f7 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidatorDefinition.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidatorDefinition.java @@ -44,9 +44,9 @@ List map(Model model, List events) { // If there's a selector, create a list of candidate shape IDs that can be emitted. if (selector != null) { candidates = selector - .shapes(model) - .map(Shape::getId) - .collect(Collectors.toSet()); + .shapes(model) + .map(Shape::getId) + .collect(Collectors.toSet()); } for (ValidationEvent event : events) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidatorFromDefinitionFactory.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidatorFromDefinitionFactory.java index d1881ce74b0..c4836d270d3 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidatorFromDefinitionFactory.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidatorFromDefinitionFactory.java @@ -26,27 +26,29 @@ final class ValidatorFromDefinitionFactory { ValidatedResult loadValidator(ValidatorDefinition definition) { try { return delegate.createValidator(definition.name, definition.configuration) - .map(validator -> ValidatedResult.fromValue(mapValidator(definition, validator))) - .orElseGet(ValidatedResult::empty); + .map(validator -> ValidatedResult.fromValue(mapValidator(definition, validator))) + .orElseGet(ValidatedResult::empty); } catch (SourceException e) { return ValidatedResult.fromErrors( - ListUtils.of( - ValidationEvent.fromSourceException( - e, - format("Error creating `%s` validator: ", definition.name) + ListUtils.of( + ValidationEvent.fromSourceException( + e, + format("Error creating `%s` validator: ", definition.name) + ) ) - ) ); } catch (RuntimeException e) { return ValidatedResult.fromErrors( - ListUtils.of( - ValidationEvent.builder() - .id(Validator.MODEL_ERROR) - .sourceLocation(definition.sourceLocation) - .severity(Severity.ERROR) - .message(format("Error creating `%s` validator: %s", definition.name, e.getMessage())) - .build() - ) + ListUtils.of( + ValidationEvent.builder() + .id(Validator.MODEL_ERROR) + .sourceLocation(definition.sourceLocation) + .severity(Severity.ERROR) + .message( + format("Error creating `%s` validator: %s", definition.name, e.getMessage()) + ) + .build() + ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/Version.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/Version.java index 6a6ca869fac..48bfacaa148 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/Version.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/Version.java @@ -98,10 +98,10 @@ ValidationEvent validateVersionedTrait(ShapeId target, ShapeId traitId, Node val String errorMessage = null; if (traitId.equals(MixinTrait.ID)) { errorMessage = String.format( - "Mixins can only be used in Smithy 2.0 or later. Attempted to apply " - + "a @mixin trait to `%s` in a model file using version `%s`.", - target, - this + "Mixins can only be used in Smithy 2.0 or later. Attempted to apply " + + "a @mixin trait to `%s` in a model file using version `%s`.", + target, + this ); } else if (traitId.equals(DefaultTrait.ID)) { errorMessage = "The @default trait can only be used in Smithy 2.0 or later"; @@ -109,12 +109,12 @@ ValidationEvent validateVersionedTrait(ShapeId target, ShapeId traitId, Node val if (errorMessage != null) { return ValidationEvent.builder() - .severity(Severity.ERROR) - .id(Validator.MODEL_ERROR) - .shapeId(target) - .sourceLocation(value) - .message(errorMessage) - .build(); + .severity(Severity.ERROR) + .id(Validator.MODEL_ERROR) + .shapeId(target) + .sourceLocation(value) + .message(errorMessage) + .build(); } return null; @@ -167,20 +167,20 @@ boolean isDeprecated() { ValidationEvent validateVersionedTrait(ShapeId target, ShapeId traitId, Node value) { if (traitId.equals(BoxTrait.ID)) { return ValidationEvent.builder() - .id(Validator.MODEL_ERROR) - .severity(Severity.ERROR) - .shapeId(target) - .sourceLocation(value) - .message("@box is not supported in Smithy IDL 2.0") - .build(); + .id(Validator.MODEL_ERROR) + .severity(Severity.ERROR) + .shapeId(target) + .sourceLocation(value) + .message("@box is not supported in Smithy IDL 2.0") + .build(); } else if (traitId.equals(EnumTrait.ID)) { return ValidationEvent.builder() - .id(Validator.MODEL_DEPRECATION) - .severity(Severity.WARNING) - .shapeId(target) - .sourceLocation(value) - .message("The enum trait is deprecated. Smithy 2.0 models should use the enum shape.") - .build(); + .id(Validator.MODEL_DEPRECATION) + .severity(Severity.WARNING) + .shapeId(target) + .sourceLocation(value) + .message("The enum trait is deprecated. Smithy 2.0 models should use the enum shape.") + .build(); } return null; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/sourcecontext/DefaultSourceLoader.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/sourcecontext/DefaultSourceLoader.java index 9aa6b4faa1e..6817d69c277 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/sourcecontext/DefaultSourceLoader.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/sourcecontext/DefaultSourceLoader.java @@ -190,7 +190,7 @@ private List parseMemberShape(SourceLocation location, MemberShape member) SourceLocation containerLocation = container.getSourceLocation(); // Some basic checking to ensure the member after the container in the same file. if (containerLocation.getFilename().equals(location.getFilename()) - && containerLocation.getLine() < location.getLine()) { + && containerLocation.getLine() < location.getLine()) { List result = new ArrayList<>(2); addLineIfValid(containerLocation.getLine(), result); addLineIfValid(location.getLine(), result); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/IdRefShapeRelationships.java b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/IdRefShapeRelationships.java index 05bcc307df9..f713eef57b2 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/IdRefShapeRelationships.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/IdRefShapeRelationships.java @@ -66,17 +66,17 @@ private void addRelationships(Shape traitDef, NodeQuery query) { Node node = trait.toNode(); // Invalid shape ids are handled by the idRef trait validator, so ignore them here. query.execute(node) - .forEach( - n -> n.asStringNode() - .flatMap(StringNode::asShapeId) - .flatMap(model::getShape) - .map(referenced -> Relationship.create(shape, RelationshipType.ID_REF, referenced)) - .ifPresent( - rel -> relationships - .computeIfAbsent(rel.getShape().getId(), id -> new HashSet<>()) - .add(rel) - ) - ); + .forEach( + n -> n.asStringNode() + .flatMap(StringNode::asShapeId) + .flatMap(model::getShape) + .map(referenced -> Relationship.create(shape, RelationshipType.ID_REF, referenced)) + .ifPresent( + rel -> relationships + .computeIfAbsent(rel.getShape().getId(), id -> new HashSet<>()) + .add(rel) + ) + ); }); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborProvider.java b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborProvider.java index 4f72c087e8c..a395025087c 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborProvider.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborProvider.java @@ -72,8 +72,8 @@ static NeighborProvider withTraitRelationships(Model model, NeighborProvider nei relationships = new ArrayList<>(relationships); for (ShapeId trait : shape.getAllTraits().keySet()) { Relationship traitRel = model.getShape(trait) - .map(target -> Relationship.create(shape, RelationshipType.TRAIT, target)) - .orElseGet(() -> Relationship.createInvalid(shape, RelationshipType.TRAIT, trait)); + .map(target -> Relationship.create(shape, RelationshipType.TRAIT, target)) + .orElseGet(() -> Relationship.createInvalid(shape, RelationshipType.TRAIT, trait)); relationships.add(traitRel); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborVisitor.java b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborVisitor.java index 5304e5d214b..989428727da 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborVisitor.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborVisitor.java @@ -48,8 +48,8 @@ public List getNeighbors(Shape shape) { @Override public List getDefault(Shape shape) { return shape.getMixins().isEmpty() - ? Collections.emptyList() - : initializeRelationships(shape, 0); + ? Collections.emptyList() + : initializeRelationships(shape, 0); } private List initializeRelationships(Shape shape, int knownMemberCount) { @@ -97,7 +97,7 @@ private void push(List result, Shape container, RelationshipType t @Override public List resourceShape(ResourceShape shape) { int neededSize = shape.getAllOperations().size() + shape.getResources().size() - + shape.getIdentifiers().size() + shape.getProperties().size(); + + shape.getIdentifiers().size() + shape.getProperties().size(); List result = initializeRelationships(shape, neededSize); shape.getIdentifiers().forEach((k, v) -> push(result, shape, RelationshipType.IDENTIFIER, v)); shape.getProperties().forEach((k, v) -> push(result, shape, RelationshipType.PROPERTY, v)); @@ -120,8 +120,8 @@ public List operationShape(OperationShape shape) { // Calculate the number of relationships up front. int assumedRelationshipCount = shape.getErrors().size() - + (input == null ? 0 : 1) - + (output == null ? 0 : 1); + + (input == null ? 0 : 1) + + (output == null ? 0 : 1); List result = initializeRelationships(shape, assumedRelationshipCount); if (input != null) { @@ -219,7 +219,7 @@ private Relationship relationship(Shape shape, RelationshipType type, MemberShap private Relationship relationship(Shape shape, RelationshipType type, ShapeId neighborShapeId) { return model.getShape(neighborShapeId) - .map(target -> Relationship.create(shape, type, target)) - .orElseGet(() -> Relationship.createInvalid(shape, type, neighborShapeId)); + .map(target -> Relationship.create(shape, type, target)) + .orElseGet(() -> Relationship.createInvalid(shape, type, neighborShapeId)); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/Relationship.java b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/Relationship.java index 8975ec497a9..e56f9509a1c 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/Relationship.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/Relationship.java @@ -25,10 +25,10 @@ public final class Relationship { private final Shape neighborShape; private Relationship( - Shape shape, - RelationshipType relationshipType, - ShapeId neighborShapeId, - Shape neighborShape + Shape shape, + RelationshipType relationshipType, + ShapeId neighborShapeId, + Shape neighborShape ) { this.shape = Objects.requireNonNull(shape); this.relationshipType = Objects.requireNonNull(relationshipType); @@ -143,11 +143,11 @@ public RelationshipDirection getDirection() { @Override public String toString() { return String.format( - "[Relationship shape=\"%s\" type=\"%s\" neighbor=\"%s\" neighborPresent=%b]", - shape.getId(), - relationshipType, - neighborShapeId, - neighborShape != null + "[Relationship shape=\"%s\" type=\"%s\" neighbor=\"%s\" neighborPresent=%b]", + shape.getId(), + relationshipType, + neighborShapeId, + neighborShape != null ); } @@ -158,9 +158,9 @@ public boolean equals(Object other) { } Relationship otherRelationship = (Relationship) other; return shape.equals(otherRelationship.shape) - && relationshipType.equals(otherRelationship.relationshipType) - && neighborShapeId.equals(otherRelationship.neighborShapeId) - && Objects.equals(neighborShape, otherRelationship.neighborShape); + && relationshipType.equals(otherRelationship.relationshipType) + && neighborShapeId.equals(otherRelationship.neighborShapeId) + && Objects.equals(neighborShape, otherRelationship.neighborShape); } @Override diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedShapes.java b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedShapes.java index 0a9192ee8de..9ca4566d726 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedShapes.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedShapes.java @@ -86,9 +86,9 @@ public Set compute(Model model) { Set result = new HashSet<>(); for (Shape shape : model.toSet()) { if (!shape.isMemberShape() - && !connected.contains(shape.getId()) - && !Prelude.isPreludeShape(shape) - && keepFilter.test(shape)) { + && !connected.contains(shape.getId()) + && !Prelude.isPreludeShape(shape) + && keepFilter.test(shape)) { result.add(shape); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitions.java b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitions.java index 22b07e42d87..4f8b7eff52a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitions.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitions.java @@ -45,22 +45,22 @@ public Set compute(Model model) { // Begin with a mutable set of all trait definitions contained in the model Set unused = model.getShapesWithTrait(TraitDefinition.class) - .stream() - // Exclude prelude traits -- these are defined by Smithy, not by the model itself - .filter(FunctionalUtils.not(Prelude::isPreludeShape)) - .collect(Collectors.toSet()); + .stream() + // Exclude prelude traits -- these are defined by Smithy, not by the model itself + .filter(FunctionalUtils.not(Prelude::isPreludeShape)) + .collect(Collectors.toSet()); // Find all traits used directly or indirectly by a service shape and remove // their definitions from the unused set. model.shapes(ServiceShape.class) - .flatMap(service -> walker.walkShapes(service).stream()) - .distinct() - .map(Shape::getAllTraits) - .flatMap(traits -> traits.keySet().stream()) - .distinct() - .flatMap(traitId -> getTraitShapes(model, traitId).stream()) - .filter(keepFilter) - .forEach(unused::remove); + .flatMap(service -> walker.walkShapes(service).stream()) + .distinct() + .map(Shape::getAllTraits) + .flatMap(traits -> traits.keySet().stream()) + .distinct() + .flatMap(traitId -> getTraitShapes(model, traitId).stream()) + .filter(keepFilter) + .forEach(unused::remove); return unused; } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/node/ArrayNode.java b/smithy-model/src/main/java/software/amazon/smithy/model/node/ArrayNode.java index 8978601be7d..26ad60ecc74 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/node/ArrayNode.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/node/ArrayNode.java @@ -37,7 +37,7 @@ public final class ArrayNode extends Node implements Iterable, ToSmithyBui * "class X cannot be cast to class Y ..." */ private static final Pattern CAST_PATTERN_TYPE = Pattern.compile( - "^.* to(?: class)? software\\.amazon\\.smithy\\.model\\.node\\.([A-Za-z]+).*$" + "^.* to(?: class)? software\\.amazon\\.smithy\\.model\\.node\\.([A-Za-z]+).*$" ); private final List elements; @@ -49,8 +49,8 @@ public ArrayNode(List elements, SourceLocation sourceLocation) { ArrayNode(List elements, SourceLocation sourceLocation, boolean defensiveCopy) { super(sourceLocation); this.elements = defensiveCopy - ? ListUtils.copyOf(elements) - : Collections.unmodifiableList(elements); + ? ListUtils.copyOf(elements) + : Collections.unmodifiableList(elements); } private ArrayNode(Builder builder) { @@ -114,8 +114,8 @@ public List getElements() { */ public Optional get(int index) { return elements.size() > index && index > -1 - ? Optional.of(elements.get(index)) - : Optional.empty(); + ? Optional.of(elements.get(index)) + : Optional.empty(); } /** @@ -196,18 +196,18 @@ public List getElementsAs(Function f) { String message = e.getMessage(); Matcher matcher = CAST_PATTERN_TYPE.matcher(message); String formatted = matcher.matches() - ? String.format( - "Expected array element %d to be a %s but found %s.", - i, - nodeClassToSimpleTypeName(matcher.group(1)), - nodeClassToSimpleTypeName(elements.get(i).getClass().getSimpleName()) - ) - : String.format( - "Array element at position %d is an invalid type `%s`: %s", - i, - nodeClassToSimpleTypeName(elements.get(i).getClass().getSimpleName()), - e.getMessage() - ); + ? String.format( + "Expected array element %d to be a %s but found %s.", + i, + nodeClassToSimpleTypeName(matcher.group(1)), + nodeClassToSimpleTypeName(elements.get(i).getClass().getSimpleName()) + ) + : String.format( + "Array element at position %d is an invalid type `%s`: %s", + i, + nodeClassToSimpleTypeName(elements.get(i).getClass().getSimpleName()), + e.getMessage() + ); throw new ExpectationNotMetException(formatted, elements.get(i)); } } @@ -233,9 +233,9 @@ public ArrayNode merge(ArrayNode other) { List result = new ArrayList<>(elements); result.addAll(other.elements); return new ArrayNode( - result, - getSourceLocation() != SourceLocation.NONE ? getSourceLocation() : other.getSourceLocation(), - false + result, + getSourceLocation() != SourceLocation.NONE ? getSourceLocation() : other.getSourceLocation(), + false ); } @@ -254,13 +254,13 @@ public static Collector, ArrayNode> collect() { */ public static Collector, ArrayNode> collect(SourceLocation sloc) { return Collector.of( - ArrayList::new, - (results, entry) -> results.add(entry.toNode()), - (left, right) -> { - left.addAll(right); - return left; - }, - results -> new ArrayNode(results, sloc, false) + ArrayList::new, + (results, entry) -> results.add(entry.toNode()), + (left, right) -> { + left.addAll(right); + return left; + }, + results -> new ArrayNode(results, sloc, false) ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/node/DefaultNodeDeserializers.java b/smithy-model/src/main/java/software/amazon/smithy/model/node/DefaultNodeDeserializers.java index 7f7e6141ce3..b9400414520 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/node/DefaultNodeDeserializers.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/node/DefaultNodeDeserializers.java @@ -72,8 +72,8 @@ static Class classFromType(Type type) { private static final ObjectCreatorFactory EXACT_CREATOR_FACTORY = (nodeType, targetType, nodeMapper) -> { Class targetClass = classFromType(targetType); if (targetClass != null - && Node.class.isAssignableFrom(targetClass) - && targetClass.isAssignableFrom(nodeType.getNodeClass())) { + && Node.class.isAssignableFrom(targetClass) + && targetClass.isAssignableFrom(nodeType.getNodeClass())) { return (node, target, pointer, mapper) -> node; } else { return null; @@ -204,19 +204,19 @@ private ReflectiveSupplier> createSupplier(Type targetType) { if (targetClass != null) { // Create an ArrayList for most cases of lists or iterables. if (targetClass == List.class - || targetClass == Collection.class - || targetClass == Object.class - || targetClass == ArrayList.class - || targetClass == Iterable.class) { + || targetClass == Collection.class + || targetClass == Object.class + || targetClass == ArrayList.class + || targetClass == Iterable.class) { return ArrayList::new; } else if (targetClass == Set.class - || targetClass == HashSet.class - || targetClass == LinkedHashSet.class) { - // Special casing for Set or HashSet. - return LinkedHashSet::new; - } else if (Collection.class.isAssignableFrom(targetClass)) { - return createSupplierFromReflection(targetClass); - } + || targetClass == HashSet.class + || targetClass == LinkedHashSet.class) { + // Special casing for Set or HashSet. + return LinkedHashSet::new; + } else if (Collection.class.isAssignableFrom(targetClass)) { + return createSupplierFromReflection(targetClass); + } } return null; @@ -234,9 +234,9 @@ private ReflectiveSupplier> createSupplierFromReflection(Clas // We *could* pass here and try to let the next deserializer take a crack, but that would // probably never work in practice and results in a less descriptive error message. throw new NodeDeserializationException( - "Unable to find a zero-arg constructor for Collection " + into.getName(), - SourceLocation.NONE, - e + "Unable to find a zero-arg constructor for Collection " + into.getName(), + SourceLocation.NONE, + e ); } } @@ -288,16 +288,16 @@ public NodeMapper.ObjectCreator getCreator(NodeType nodeType, Type target, NodeM for (Map.Entry entry : objectNode.getMembers().entrySet()) { String keyValue = entry.getKey().getValue(); Object key = mapper.deserializeNext( - entry.getKey(), - pointer + "/(key:" + keyValue + ")", - keyType, - mapper + entry.getKey(), + pointer + "/(key:" + keyValue + ")", + keyType, + mapper ); Object value = mapper.deserializeNext( - entry.getValue(), - pointer + "/" + keyValue, - valueType, - mapper + entry.getValue(), + pointer + "/" + keyValue, + valueType, + mapper ); map.put(key, value); } @@ -329,9 +329,9 @@ private ReflectiveSupplier> createSupplierFromReflection(Cla // We *could* pass here and try to let the next deserializer take a crack, but that would // probably never work in practice and results in a less descriptive error message. throw new NodeDeserializationException( - "Unable to find a zero-arg constructor for Map " + into.getName(), - SourceLocation.NONE, - e + "Unable to find a zero-arg constructor for Map " + into.getName(), + SourceLocation.NONE, + e ); } } @@ -344,17 +344,17 @@ private ReflectiveSupplier> createSupplierFromReflection(Cla if (targetClass != null && !nodeMapper.getDisableFromNode().contains(targetClass)) { for (Method method : targetClass.getMethods()) { if ((method.getName().equals("fromNode")) - && targetClass.isAssignableFrom(method.getReturnType()) - && method.getParameters().length == 1 - && Node.class.isAssignableFrom(method.getParameters()[0].getType()) - && Modifier.isStatic(method.getModifiers())) { + && targetClass.isAssignableFrom(method.getReturnType()) + && method.getParameters().length == 1 + && Node.class.isAssignableFrom(method.getParameters()[0].getType()) + && Modifier.isStatic(method.getModifiers())) { return (node, targetType, pointer, mapper) -> { try { return method.invoke(null, node); } catch (ReflectiveOperationException e) { String message = "Unable to deserialize Node using fromNode method: " + getCauseMessage(e); throw NodeDeserializationException - .fromReflectiveContext(targetType, pointer, node, e, message); + .fromReflectiveContext(targetType, pointer, node, e, message); } }; } @@ -368,11 +368,11 @@ static final class BeanMapper { private static final ConcurrentMap, String>, Method> SETTER_CACHE = new ConcurrentHashMap<>(); static void apply( - Object value, - Node node, - Type target, - String pointer, - NodeMapper mapper + Object value, + Node node, + Type target, + String pointer, + NodeMapper mapper ) throws ReflectiveOperationException { for (Map.Entry entry : node.expectObjectNode().getStringMap().entrySet()) { Method setter = findSetter(target, entry.getKey()); @@ -380,10 +380,10 @@ static void apply( mapper.getWhenMissingSetter().handle(target, pointer, entry.getKey(), entry.getValue()); } else { Object member = mapper.deserializeNext( - entry.getValue(), - pointer + "/" + entry.getKey(), - setter.getParameters()[0].getParameterizedType(), - mapper + entry.getValue(), + pointer + "/" + entry.getKey(), + setter.getParameters()[0].getParameterizedType(), + mapper ); setter.invoke(value, member); } @@ -474,9 +474,9 @@ private static boolean isBeanOrBuilderSetter(Method method, Class type, Strin for (Method method : targetClass.getMethods()) { if ((method.getName().equals("builder")) - && SmithyBuilder.class.isAssignableFrom(method.getReturnType()) - && method.getParameters().length == 0 - && Modifier.isStatic(method.getModifiers())) { + && SmithyBuilder.class.isAssignableFrom(method.getReturnType()) + && method.getParameters().length == 0 + && Modifier.isStatic(method.getModifiers())) { method.setAccessible(true); return (node, targetType, pointer, mapper) -> { try { @@ -495,8 +495,8 @@ private static boolean isBeanOrBuilderSetter(Method method, Class type, Strin }; private static void applySourceLocation( - Object object, - FromSourceLocation sourceLocation + Object object, + FromSourceLocation sourceLocation ) throws ReflectiveOperationException { Method setter = BeanMapper.findSetter(object.getClass(), "sourceLocation"); if (setter != null) { @@ -515,8 +515,8 @@ private static void applySourceLocation( // TODO: we could potentially add support for this if it's not too complicated. if (targetClass.getEnclosingClass() != null && !Modifier.isStatic(targetClass.getModifiers())) { throw new NodeDeserializationException( - "Cannot create non-static inner class: " + targetClass.getCanonicalName(), - SourceLocation.NONE + "Cannot create non-static inner class: " + targetClass.getCanonicalName(), + SourceLocation.NONE ); } @@ -531,11 +531,11 @@ private static void applySourceLocation( return value; } catch (ReflectiveOperationException e) { throw NodeDeserializationException.fromReflectiveContext( - targetType, - pointer, - node, - e, - "Unable to deserialize a Node when invoking target constructor: " + getCauseMessage(e) + targetType, + pointer, + node, + e, + "Unable to deserialize a Node when invoking target constructor: " + getCauseMessage(e) ); } }; @@ -571,11 +571,11 @@ private static void applySourceLocation( } throw NodeDeserializationException.fromContext( - targetClass, - pointer, - node, - null, - "Expected one of the following enum strings: " + names + targetClass, + pointer, + node, + null, + "Expected one of the following enum strings: " + names ); }; }; @@ -588,16 +588,16 @@ private interface FromStringClassFactory { // This mirrors the simpler behaviors allowed in Jackson. // See https://github.com/FasterXML/jackson-databind/blob/ab583fb2319ee33ef6b548b720afec84265d40a7/src/main/java/com/fasterxml/jackson/databind/deser/std/FromStringDeserializer.java private static final Map FROM_STRING_CLASSES = MapUtils.of( - URL.class, - URL::new, - URI.class, - URI::new, - Pattern.class, - Pattern::compile, - Path.class, - Paths::get, - File.class, - File::new + URL.class, + URL::new, + URI.class, + URI::new, + Pattern.class, + Pattern::compile, + Path.class, + Paths::get, + File.class, + File::new ); private static final ObjectCreatorFactory FROM_STRING = (nodeType, target, nodeMapper) -> { @@ -624,18 +624,18 @@ private interface FromStringClassFactory { // If we ever open up the API, then we should consider making the priority // more explicit by adding it to the ObjectCreatorFactory interface. private static final List DEFAULT_FACTORIES = ListUtils.of( - EXACT_CREATOR_FACTORY, - NULL_CREATOR, - FROM_NODE_CREATOR, - BOOLEAN_CREATOR_FACTORY, - FROM_STRING, - STRING_CREATOR, - ENUM_CREATOR, - NUMBER_CREATOR, - COLLECTION_CREATOR, - MAP_CREATOR, - FROM_BUILDER_CREATOR, - BEAN_CREATOR + EXACT_CREATOR_FACTORY, + NULL_CREATOR, + FROM_NODE_CREATOR, + BOOLEAN_CREATOR_FACTORY, + FROM_STRING, + STRING_CREATOR, + ENUM_CREATOR, + NUMBER_CREATOR, + COLLECTION_CREATOR, + MAP_CREATOR, + FROM_BUILDER_CREATOR, + BEAN_CREATOR ); static final ObjectCreatorFactory DEFAULT_CHAIN = (nodeType, target, nodeMapper) -> { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/node/DefaultNodeSerializers.java b/smithy-model/src/main/java/software/amazon/smithy/model/node/DefaultNodeSerializers.java index 932dd73b751..9878474cba9 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/node/DefaultNodeSerializers.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/node/DefaultNodeSerializers.java @@ -187,8 +187,8 @@ public Node serialize(Map value, Set serializedObjects, NodeMapper mappe mappings.put((StringNode) key, mapper.serialize(entry.getValue(), serializedObjects)); } else { throw new NodeSerializationException( - "Unable to write Map key because it was not serialized as a string: " - + entry.getKey() + " -> " + Node.printJson(key) + "Unable to write Map key because it was not serialized as a string: " + + entry.getKey() + " -> " + Node.printJson(key) ); } } @@ -338,11 +338,11 @@ public Node serialize(Object value, Set serializedObjects, NodeMapper ma // If this isn't done, I observed that the message of ReflectiveOperationException is null. String causeMessage = e.getCause() != null ? e.getCause().getMessage() : e.getMessage(); String message = String.format( - "Error serializing `%s` field of %s using %s(): %s", - entry.getKey(), - value.getClass().getName(), - entry.getValue().getName(), - causeMessage + "Error serializing `%s` field of %s using %s(): %s", + entry.getKey(), + value.getClass().getName(), + entry.getValue().getName(), + causeMessage ); throw new NodeSerializationException(message, e); } @@ -392,22 +392,22 @@ private boolean canSerialize(NodeMapper mapper, Node value) { // If we ever open up the API, then we should consider making the priority // more explicit by adding it to the Serializer interface. static final List SERIALIZERS = ListUtils.of( - TO_NODE_SERIALIZER, - OPTIONAL_SERIALIZER, - STRING_SERIALIZER, - BOOLEAN_SERIALIZER, - NUMBER_SERIALIZER, - MAP_SERIALIZER, - ARRAY_SERIALIZER, - SHAPE_ID_SERIALIZER, - ENUM_SERIALIZER, - URL_SERIALIZER, - URI_SERIALIZER, - PATTERN_SERIALIZER, - PATH_SERIALIZER, - FILE_SERIALIZER, - // Lots of things implement iterable that have specialized serialization. - ITERABLE_SERIALIZER + TO_NODE_SERIALIZER, + OPTIONAL_SERIALIZER, + STRING_SERIALIZER, + BOOLEAN_SERIALIZER, + NUMBER_SERIALIZER, + MAP_SERIALIZER, + ARRAY_SERIALIZER, + SHAPE_ID_SERIALIZER, + ENUM_SERIALIZER, + URL_SERIALIZER, + URI_SERIALIZER, + PATTERN_SERIALIZER, + PATH_SERIALIZER, + FILE_SERIALIZER, + // Lots of things implement iterable that have specialized serialization. + ITERABLE_SERIALIZER ); private DefaultNodeSerializers() {} diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/node/Node.java b/smithy-model/src/main/java/software/amazon/smithy/model/node/Node.java index db3b08fcc0d..15f78bc576f 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/node/Node.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/node/Node.java @@ -296,7 +296,7 @@ public static NullNode nullNode() { */ public static List loadArrayOfString(String descriptor, Node node) { return node.expectArrayNode(() -> "Expected `" + descriptor + "` to be an array of strings. Found {type}.") - .getElementsAs(StringNode::getValue); + .getElementsAs(StringNode::getValue); } /** @@ -315,13 +315,13 @@ public static void assertEquals(ToNode actual, ToNode expected) { Node expectedNode = expected.toNode(); if (!actualNode.equals(expectedNode)) { throw new ExpectationNotMetException( - String.format( - "Actual node did not match expected Node.%nActual:%n%s%nExpected:%n%s%nDiff: %s", - Node.prettyPrintJson(actualNode), - Node.prettyPrintJson(expectedNode), - String.join(System.lineSeparator(), diff(actualNode, expectedNode)) - ), - actualNode + String.format( + "Actual node did not match expected Node.%nActual:%n%s%nExpected:%n%s%nDiff: %s", + Node.prettyPrintJson(actualNode), + Node.prettyPrintJson(expectedNode), + String.join(System.lineSeparator(), diff(actualNode, expectedNode)) + ), + actualNode ); } } @@ -677,8 +677,8 @@ public final Node toNode() { private String expandMessage(String message, String expectedType) { return (message == null - ? format("Expected %s, but found {type}.", expectedType) - : message).replace("{type}", getType().toString()); + ? format("Expected %s, but found {type}.", expectedType) + : message).replace("{type}", getType().toString()); } /** @@ -719,9 +719,9 @@ public Node objectNode(ObjectNode node) { @Override public Node arrayNode(ArrayNode node) { return node.getElements() - .stream() - .map(element -> sortNode(element, keyComparator)) - .collect(ArrayNode.collect(node.getSourceLocation())); + .stream() + .map(element -> sortNode(element, keyComparator)) + .collect(ArrayNode.collect(node.getSourceLocation())); } }); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/node/NodeDeserializationException.java b/smithy-model/src/main/java/software/amazon/smithy/model/node/NodeDeserializationException.java index c844e80ecdf..10a297bd315 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/node/NodeDeserializationException.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/node/NodeDeserializationException.java @@ -31,11 +31,11 @@ public NodeDeserializationException(String message, SourceLocation sourceLocatio * @return Returns the created exception. */ static NodeDeserializationException fromReflectiveContext( - Type into, - String pointer, - Node node, - ReflectiveOperationException previous, - String message + Type into, + String pointer, + Node node, + ReflectiveOperationException previous, + String message ) { if (previous.getCause() instanceof NodeDeserializationException) { return (NodeDeserializationException) previous.getCause(); @@ -55,11 +55,11 @@ static NodeDeserializationException fromReflectiveContext( * @return Returns the created exception. */ static NodeDeserializationException fromContext( - Type into, - String pointer, - Node node, - Throwable previous, - String message + Type into, + String pointer, + Node node, + Throwable previous, + String message ) { String formattedMessage = NodeMapper.createErrorMessage(into, pointer, node, message); return new NodeDeserializationException(formattedMessage, node.getSourceLocation(), previous); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/node/NodeDiff.java b/smithy-model/src/main/java/software/amazon/smithy/model/node/NodeDiff.java index d4acebbf185..03eff308e00 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/node/NodeDiff.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/node/NodeDiff.java @@ -21,8 +21,8 @@ final class NodeDiff { static List diff(ToNode actual, ToNode expected) { return new NodeDiff().findDifferences(actual.toNode(), expected.toNode(), "") - .sorted() - .collect(Collectors.toList()); + .sorted() + .collect(Collectors.toList()); } private Stream findDifferences(Node actual, Node expected, String prefix) { @@ -32,14 +32,14 @@ private Stream findDifferences(Node actual, Node expected, String prefix if (!actual.getType().equals(expected.getType())) { return Stream.of( - String.format( - "[%s]: Expected node of type `%s` but found node of type `%s`.%n%nExpected: %s%n%n Found: %s", - prefix, - expected.getType(), - actual.getType(), - nodeToJson(expected, true), - nodeToJson(actual, true) - ) + String.format( + "[%s]: Expected node of type `%s` but found node of type `%s`.%n%nExpected: %s%n%n Found: %s", + prefix, + expected.getType(), + actual.getType(), + nodeToJson(expected, true), + nodeToJson(actual, true) + ) ); } @@ -50,12 +50,12 @@ private Stream findDifferences(Node actual, Node expected, String prefix return findDifferences(actual.expectArrayNode(), expected.expectArrayNode(), prefix); default: return Stream.of( - String.format( - "[%s]: Expected `%s` but found `%s`", - prefix, - nodeToJson(expected, false), - nodeToJson(actual, false) - ) + String.format( + "[%s]: Expected `%s` but found `%s`", + prefix, + nodeToJson(expected, false), + nodeToJson(actual, false) + ) ); } } @@ -63,26 +63,26 @@ private Stream findDifferences(Node actual, Node expected, String prefix private Stream findDifferences(ObjectNode actual, ObjectNode expected, String prefix) { List differences = new ArrayList<>(); Set actualKeys = actual.getMembers() - .keySet() - .stream() - .map(StringNode::getValue) - .collect(Collectors.toSet()); + .keySet() + .stream() + .map(StringNode::getValue) + .collect(Collectors.toSet()); Set expectedKeys = expected.getMembers() - .keySet() - .stream() - .map(StringNode::getValue) - .collect(Collectors.toSet()); + .keySet() + .stream() + .map(StringNode::getValue) + .collect(Collectors.toSet()); Set extraKeys = new HashSet<>(actualKeys); extraKeys.removeAll(expectedKeys); for (String extraKey : extraKeys) { differences.add( - String.format( - "[%s]: Extra key `%s` encountered with content: %s", - prefix, - extraKey, - nodeToJson(actual.expectMember(extraKey), true) - ) + String.format( + "[%s]: Extra key `%s` encountered with content: %s", + prefix, + extraKey, + nodeToJson(actual.expectMember(extraKey), true) + ) ); } @@ -96,15 +96,15 @@ private Stream findDifferences(ObjectNode actual, ObjectNode expected, S sharedKeys.retainAll(expectedKeys); return Stream.concat( - differences.stream(), - sharedKeys.stream() - .flatMap( - key -> findDifferences( - actual.expectMember(key), - expected.expectMember(key), - String.format("%s/%s", prefix, key.replace("^", "^^").replace("/", "^/")) - ) - ) + differences.stream(), + sharedKeys.stream() + .flatMap( + key -> findDifferences( + actual.expectMember(key), + expected.expectMember(key), + String.format("%s/%s", prefix, key.replace("^", "^^").replace("/", "^/")) + ) + ) ); } @@ -115,37 +115,37 @@ private Stream findDifferences(ArrayNode actual, ArrayNode expected, Str for (int i = expectedElements.size(); i < actualElements.size(); i++) { differences.add( - String.format( - "[%s]: Extra element encountered in list at position %d: %s", - prefix, - i, - nodeToJson(actualElements.get(i), true) - ) + String.format( + "[%s]: Extra element encountered in list at position %d: %s", + prefix, + i, + nodeToJson(actualElements.get(i), true) + ) ); } for (int i = actualElements.size(); i < expectedElements.size(); i++) { differences.add( - String.format( - "[%s]: Expected element (position %d) not encountered in list: %s", - prefix, - i, - nodeToJson(expectedElements.get(i), true) - ) + String.format( + "[%s]: Expected element (position %d) not encountered in list: %s", + prefix, + i, + nodeToJson(expectedElements.get(i), true) + ) ); } return Stream.concat( - differences.stream(), - IntStream.range(0, Math.min(actualElements.size(), expectedElements.size())) - .boxed() - .flatMap( - i -> findDifferences( - actualElements.get(i), - expectedElements.get(i), - String.format("%s[%d]", prefix, i) - ) - ) + differences.stream(), + IntStream.range(0, Math.min(actualElements.size(), expectedElements.size())) + .boxed() + .flatMap( + i -> findDifferences( + actualElements.get(i), + expectedElements.get(i), + String.format("%s[%d]", prefix, i) + ) + ) ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/node/NodeMapper.java b/smithy-model/src/main/java/software/amazon/smithy/model/node/NodeMapper.java index 4b9301a9e84..c4dab7780cf 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/node/NodeMapper.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/node/NodeMapper.java @@ -84,14 +84,14 @@ public void handle(Type into, String pointer, String property, Node value) { private static String createMessage(String property, String pointer, Type into, Node node) { String location = node.getSourceLocation() == SourceLocation.NONE - ? "" - : " " + node.getSourceLocation().toString().trim(); + ? "" + : " " + node.getSourceLocation().toString().trim(); return format( - "Deserialization error at %s%s: unable to find setter method for `%s` on %s", - getNormalizedPointer(pointer), - location, - property, - into.getTypeName() + "Deserialization error at %s%s: unable to find setter method for `%s` on %s", + getNormalizedPointer(pointer), + location, + property, + into.getTypeName() ); } } @@ -470,9 +470,9 @@ public T deserializeInto(Node value, T objectToMutate) { * @see #deserialize(Node, Class) */ public , U, V extends Collection> V deserializeCollection( - Node value, - Class into, - Class members + Node value, + Class into, + Class members ) { ParameterizedType type = new ParameterizedType() { @Override @@ -511,9 +511,9 @@ public Type getOwnerType() { * @see #deserialize(Node, Class) */ public , U, V extends Map> V deserializeMap( - Node value, - Class into, - Class members + Node value, + Class into, + Class members ) { ParameterizedType type = new ParameterizedType() { @Override @@ -572,11 +572,11 @@ T deserializeNext(Node value, String pointer, Type into, NodeMapper mapper) } private static NodeDeserializationException createError( - Type into, - String pointer, - Node node, - String message, - Throwable cause + Type into, + String pointer, + Node node, + String message, + Throwable cause ) { String errorMessage = createErrorMessage(into, pointer, node, message); return new NodeDeserializationException(errorMessage, node.getSourceLocation(), cause); @@ -584,10 +584,10 @@ private static NodeDeserializationException createError( static String createErrorMessage(Type into, String pointer, Node node, String message) { String formatted = String.format( - "Deserialization error at %s: unable to create %s from %s", - getNormalizedPointer(pointer), - into.getTypeName(), - Node.printJson(node) + "Deserialization error at %s: unable to create %s from %s", + getNormalizedPointer(pointer), + into.getTypeName(), + Node.printJson(node) ); if (message != null) { formatted += ": " + message; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/node/NodePointer.java b/smithy-model/src/main/java/software/amazon/smithy/model/node/NodePointer.java index b45ea1731d7..57d6bf73c7f 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/node/NodePointer.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/node/NodePointer.java @@ -225,24 +225,24 @@ private Node addValue(Node container, Node value, int partPosition, boolean inte return addArrayMember(part, isLast, container.expectArrayNode(), value, partPosition, intermediate); } else { LOGGER.warning( - () -> String.format( - "Attempted to add a value through JSON pointer `%s`, but segment %d targets %s", - toString(), - partPosition, - Node.printJson(container) - ) + () -> String.format( + "Attempted to add a value through JSON pointer `%s`, but segment %d targets %s", + toString(), + partPosition, + Node.printJson(container) + ) ); return container; } } private Node addObjectMember( - String part, - boolean isLast, - ObjectNode container, - Node value, - int partPosition, - boolean intermediate + String part, + boolean isLast, + ObjectNode container, + Node value, + int partPosition, + boolean intermediate ) { if (isLast) { return container.withMember(part, value); @@ -258,24 +258,24 @@ private Node addObjectMember( return container.withMember(part, synthesized); } else { LOGGER.warning( - () -> String.format( - "Attempted to add a value through JSON pointer `%s`, but `%s` could not be found in %s", - toString(), - part, - Node.printJson(container) - ) + () -> String.format( + "Attempted to add a value through JSON pointer `%s`, but `%s` could not be found in %s", + toString(), + part, + Node.printJson(container) + ) ); return container; } } private Node addArrayMember( - String part, - boolean isLast, - ArrayNode container, - Node value, - int partPosition, - boolean intermediate + String part, + boolean isLast, + ArrayNode container, + Node value, + int partPosition, + boolean intermediate ) { if (!isLast) { // "-" is a special case for the last element. @@ -310,12 +310,12 @@ private Node addArrayMember( private void logInvalidArrayIndex(Node container, int partInt) { LOGGER.warning( - () -> String.format( - "Attempted to add a value through JSON pointer `%s`, but index %d could not be set in %s", - toString(), - partInt, - Node.printJson(container) - ) + () -> String.format( + "Attempted to add a value through JSON pointer `%s`, but index %d could not be set in %s", + toString(), + partInt, + Node.printJson(container) + ) ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/node/NumberNode.java b/smithy-model/src/main/java/software/amazon/smithy/model/node/NumberNode.java index f9fea578fbe..16256bd3162 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/node/NumberNode.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/node/NumberNode.java @@ -38,28 +38,28 @@ private BigDecimal toBigDecimal(Number value) { if (value instanceof BigDecimal) { return (BigDecimal) value; } else if (value instanceof Integer || value instanceof Long || value instanceof Short - || value instanceof Byte) { - return BigDecimal.valueOf(value.longValue()); - } else if (value instanceof Float || value instanceof Double) { - double d = value.doubleValue(); - if (Double.isNaN(d)) { - isNaN = true; - return null; - } else if (Double.isInfinite(d)) { - if (stringCache.startsWith("-")) { - isNegativeInfinity = true; + || value instanceof Byte) { + return BigDecimal.valueOf(value.longValue()); + } else if (value instanceof Float || value instanceof Double) { + double d = value.doubleValue(); + if (Double.isNaN(d)) { + isNaN = true; + return null; + } else if (Double.isInfinite(d)) { + if (stringCache.startsWith("-")) { + isNegativeInfinity = true; + } else { + isPositiveInfinity = true; + } + return null; } else { - isPositiveInfinity = true; + return BigDecimal.valueOf(d); } - return null; + } else if (value instanceof BigInteger) { + return new BigDecimal((BigInteger) value); } else { - return BigDecimal.valueOf(d); + return new BigDecimal(stringCache); } - } else if (value instanceof BigInteger) { - return new BigDecimal((BigInteger) value); - } else { - return new BigDecimal(stringCache); - } } /** @@ -179,9 +179,9 @@ public boolean equals(Object other) { } else { NumberNode o = (NumberNode) other; return isNaN == o.isNaN - && isPositiveInfinity == o.isPositiveInfinity - && isNegativeInfinity == o.isNegativeInfinity - && Objects.equals(value, o.value); + && isPositiveInfinity == o.isPositiveInfinity + && isNegativeInfinity == o.isNegativeInfinity + && Objects.equals(value, o.value); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/node/ObjectNode.java b/smithy-model/src/main/java/software/amazon/smithy/model/node/ObjectNode.java index d96af1e0ed6..72f13854b0c 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/node/ObjectNode.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/node/ObjectNode.java @@ -47,8 +47,8 @@ public ObjectNode(Map members, SourceLocation sourceLocation) ObjectNode(Map nodeMap, SourceLocation sourceLocation, boolean defensiveCopy) { super(sourceLocation); this.nodeMap = defensiveCopy - ? Collections.unmodifiableMap(new LinkedHashMap<>(nodeMap)) - : Collections.unmodifiableMap(nodeMap); + ? Collections.unmodifiableMap(new LinkedHashMap<>(nodeMap)) + : Collections.unmodifiableMap(nodeMap); } private ObjectNode(Builder builder) { @@ -215,9 +215,9 @@ public Optional getMember(String memberName) { */ public Map getMembersByPrefix(String prefix) { return getStringMap().entrySet() - .stream() - .filter(entry -> entry.getKey().startsWith(prefix)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + .stream() + .filter(entry -> entry.getKey().startsWith(prefix)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } /** @@ -248,7 +248,7 @@ public Map getStringMap() { */ public Optional getStringMember(String memberName) { return getMember(memberName) - .map(n -> n.expectStringNode(() -> format("Expected `%s` to be a string; found {type}", memberName))); + .map(n -> n.expectStringNode(() -> format("Expected `%s` to be a string; found {type}", memberName))); } /** @@ -274,7 +274,7 @@ public String getStringMemberOrDefault(String memberName, String defaultValue) { */ public Optional getNumberMember(String memberName) { return getMember(memberName) - .map(n -> n.expectNumberNode(() -> format("Expected `%s` to be a number; found {type}", memberName))); + .map(n -> n.expectNumberNode(() -> format("Expected `%s` to be a number; found {type}", memberName))); } /** @@ -300,7 +300,7 @@ public Number getNumberMemberOrDefault(String memberName, Number defaultValue) { */ public Optional getArrayMember(String memberName) { return getMember(memberName) - .map(n -> n.expectArrayNode(() -> format("Expected `%s` to be an array; found {type}", memberName))); + .map(n -> n.expectArrayNode(() -> format("Expected `%s` to be an array; found {type}", memberName))); } /** @@ -313,7 +313,7 @@ public Optional getArrayMember(String memberName) { */ public Optional getObjectMember(String memberName) { return getMember(memberName) - .map(n -> n.expectObjectNode(() -> format("Expected `%s` to be an object; found {type}", memberName))); + .map(n -> n.expectObjectNode(() -> format("Expected `%s` to be an object; found {type}", memberName))); } /** @@ -326,7 +326,7 @@ public Optional getObjectMember(String memberName) { */ public Optional getBooleanMember(String memberName) { return getMember(memberName) - .map(n -> n.expectBooleanNode(() -> format("Expected `%s` to be a boolean; found {type}", memberName))); + .map(n -> n.expectBooleanNode(() -> format("Expected `%s` to be a boolean; found {type}", memberName))); } /** @@ -404,7 +404,7 @@ public Node expectMember(String name, Supplier errorMessage) { */ public ArrayNode expectArrayMember(String name) { return expectMember(name) - .expectArrayNode(() -> format("Expected `%s` member to be an array, but found {type}.", name)); + .expectArrayNode(() -> format("Expected `%s` member to be an array, but found {type}.", name)); } /** @@ -416,7 +416,7 @@ public ArrayNode expectArrayMember(String name) { */ public BooleanNode expectBooleanMember(String name) { return expectMember(name) - .expectBooleanNode(() -> format("Expected `%s` member to be a boolean, but found {type}.", name)); + .expectBooleanNode(() -> format("Expected `%s` member to be a boolean, but found {type}.", name)); } /** @@ -428,7 +428,7 @@ public BooleanNode expectBooleanMember(String name) { */ public NullNode expectNullMember(String name) { return expectMember(name) - .expectNullNode(() -> format("Expected `%s` member to be null, but found {type}.", name)); + .expectNullNode(() -> format("Expected `%s` member to be null, but found {type}.", name)); } /** @@ -440,7 +440,7 @@ public NullNode expectNullMember(String name) { */ public NumberNode expectNumberMember(String name) { return expectMember(name) - .expectNumberNode(() -> format("Expected `%s` member to be a number, but found {type}.", name)); + .expectNumberNode(() -> format("Expected `%s` member to be a number, but found {type}.", name)); } /** @@ -452,7 +452,7 @@ public NumberNode expectNumberMember(String name) { */ public ObjectNode expectObjectMember(String name) { return expectMember(name) - .expectObjectNode(() -> format("Expected `%s` member to be an object, but found {type}.", name)); + .expectObjectNode(() -> format("Expected `%s` member to be an object, but found {type}.", name)); } /** @@ -464,7 +464,7 @@ public ObjectNode expectObjectMember(String name) { */ public StringNode expectStringMember(String name) { return expectMember(name) - .expectStringNode(() -> format("Expected `%s` member to be a string, but found {type}.", name)); + .expectStringNode(() -> format("Expected `%s` member to be a string, but found {type}.", name)); } /** @@ -481,12 +481,12 @@ public ObjectNode expectNoAdditionalProperties(Collection allowedPropert Set additional = new HashSet<>(getStringMap().keySet()); additional.removeAll(allowedProperties); throw new ExpectationNotMetException( - String.format( - "Expected an object with possible properties of %s, but found additional properties: %s", - ValidationUtils.tickedList(allowedProperties), - ValidationUtils.tickedList(additional) - ), - this + String.format( + "Expected an object with possible properties of %s, but found additional properties: %s", + ValidationUtils.tickedList(allowedProperties), + ValidationUtils.tickedList(additional) + ), + this ); } } @@ -711,9 +711,9 @@ public ObjectNode merge(ObjectNode other) { Map result = new LinkedHashMap<>(getMembers()); result.putAll(other.nodeMap); return new ObjectNode( - result, - getSourceLocation() != SourceLocation.NONE ? getSourceLocation() : other.getSourceLocation(), - false + result, + getSourceLocation() != SourceLocation.NONE ? getSourceLocation() : other.getSourceLocation(), + false ); // Use the constructor that doesn't re-copy. } @@ -726,18 +726,18 @@ public ObjectNode merge(ObjectNode other) { * @return Returns the created collector. */ public static Collector, ObjectNode> collect( - Function keyMapper, - Function valueMapper + Function keyMapper, + Function valueMapper ) { return Collector.of( - LinkedHashMap::new, - (results, entry) -> results.put(keyMapper.apply(entry), valueMapper.apply(entry).toNode()), - (left, right) -> { - left.putAll(right); - return left; - }, - // Use the constructor that doesn't need to re-copy. - results -> new ObjectNode(results, SourceLocation.NONE, false) + LinkedHashMap::new, + (results, entry) -> results.put(keyMapper.apply(entry), valueMapper.apply(entry).toNode()), + (left, right) -> { + left.putAll(right); + return left; + }, + // Use the constructor that doesn't need to re-copy. + results -> new ObjectNode(results, SourceLocation.NONE, false) ); } @@ -750,8 +750,8 @@ public static Collector, ObjectNode> collect( * @return Returns the created collector. */ public static Collector, ObjectNode> collectStringKeys( - Function keyMapper, - Function valueMapper + Function keyMapper, + Function valueMapper ) { return collect(entry -> from(keyMapper.apply(entry)), valueMapper); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/node/StringNode.java b/smithy-model/src/main/java/software/amazon/smithy/model/node/StringNode.java index 8f87329ec1e..67c790f2be0 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/node/StringNode.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/node/StringNode.java @@ -54,8 +54,8 @@ public StringNode(String value, SourceLocation sourceLocation) { */ @SmithyInternalApi public static Pair> createLazyString( - String placeholder, - SourceLocation sourceLocation + String placeholder, + SourceLocation sourceLocation ) { StringNode result = new StringNode(placeholder, sourceLocation); return Pair.of(result, result::updateValue); @@ -127,12 +127,12 @@ public String expectOneOf(String... validValues) { public String expectOneOf(Collection validValues) { if (!validValues.contains(value)) { throw new ExpectationNotMetException( - String.format( - "Expected one of %s; got `%s`.", - ValidationUtils.tickedList(validValues), - value - ), - this + String.format( + "Expected one of %s; got `%s`.", + ValidationUtils.tickedList(validValues), + value + ), + this ); } return value; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/node/internal/JsonParser.java b/smithy-model/src/main/java/software/amazon/smithy/model/node/internal/JsonParser.java index db1b202238b..5a45ece9207 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/node/internal/JsonParser.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/node/internal/JsonParser.java @@ -528,8 +528,8 @@ private boolean isDigit() { private boolean isHexDigit() { return current >= '0' && current <= '9' - || current >= 'a' && current <= 'f' - || current >= 'A' && current <= 'F'; + || current >= 'a' && current <= 'f' + || current >= 'A' && current <= 'F'; } private boolean isEndOfText() { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/node/internal/JsonWriter.java b/smithy-model/src/main/java/software/amazon/smithy/model/node/internal/JsonWriter.java index bcaf6dd9252..20b7846b01b 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/node/internal/JsonWriter.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/node/internal/JsonWriter.java @@ -21,22 +21,22 @@ class JsonWriter { private static final char[] UNICODE_2028_CHARS = {'\\', 'u', '2', '0', '2', '8'}; private static final char[] UNICODE_2029_CHARS = {'\\', 'u', '2', '0', '2', '9'}; private static final char[] HEX_DIGITS = { - '0', - '1', - '2', - '3', - '4', - '5', - '6', - '7', - '8', - '9', - 'a', - 'b', - 'c', - 'd', - 'e', - 'f'}; + '0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + 'a', + 'b', + 'c', + 'd', + 'e', + 'f'}; final Writer writer; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/pattern/SmithyPattern.java b/smithy-model/src/main/java/software/amazon/smithy/model/pattern/SmithyPattern.java index 125dca6525e..7b744218b26 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/pattern/SmithyPattern.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/pattern/SmithyPattern.java @@ -64,7 +64,7 @@ public final List getSegments() { */ public final List getLabels() { return Collections.unmodifiableList( - segments.stream().filter(Segment::isLabel).collect(Collectors.toList()) + segments.stream().filter(Segment::isLabel).collect(Collectors.toList()) ); } @@ -77,9 +77,9 @@ public final List getLabels() { public final Optional getLabel(String name) { String searchKey = name.toLowerCase(Locale.US); return segments.stream() - .filter(Segment::isLabel) - .filter(label -> label.getContent().toLowerCase(Locale.US).equals(searchKey)) - .findFirst(); + .filter(Segment::isLabel) + .filter(label -> label.getContent().toLowerCase(Locale.US).equals(searchKey)) + .findFirst(); } /** @@ -150,11 +150,11 @@ private void checkForDuplicateLabels() { segments.forEach(segment -> { if (segment.isLabel() && !labels.add(segment.getContent().toLowerCase(Locale.US))) { throw new InvalidPatternException( - format( - "Label `%s` is defined more than once in pattern: %s", - segment.getContent(), - pattern - ) + format( + "Label `%s` is defined more than once in pattern: %s", + segment.getContent(), + pattern + ) ); } }); @@ -241,16 +241,16 @@ private void checkForInvalidContents(Integer offset) { throw new InvalidPatternException("Segments must not be empty" + offsetString); } else if (content.contains("{") || content.contains("}")) { throw new InvalidPatternException( - "Literal segments must not contain `{` or `}` characters. Found segment `" - + content + "`" + offsetString + "Literal segments must not contain `{` or `}` characters. Found segment `" + + content + "`" + offsetString ); } } else if (content.isEmpty()) { throw new InvalidPatternException("Empty label declaration in pattern" + offsetString + "."); } else if (!ShapeId.isValidIdentifier(content)) { throw new InvalidPatternException( - "Invalid label name in pattern: '" + content + "'" + offsetString - + ". Labels must contain value identifiers." + "Invalid label name in pattern: '" + content + "'" + offsetString + + ". Labels must contain value identifiers." ); } } @@ -267,8 +267,8 @@ public static Segment parse(String content, int offset) { if (content.length() >= 2 && content.charAt(0) == '{' && content.charAt(content.length() - 1) == '}') { Type labelType = content.charAt(content.length() - 2) == '+' ? Type.GREEDY_LABEL : Type.LABEL; content = labelType == Type.GREEDY_LABEL - ? content.substring(1, content.length() - 2) - : content.substring(1, content.length() - 1); + ? content.substring(1, content.length() - 2) + : content.substring(1, content.length() - 1); return new Segment(content, labelType, offset); } else { return new Segment(content, Type.LITERAL, offset); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/pattern/UriPattern.java b/smithy-model/src/main/java/software/amazon/smithy/model/pattern/UriPattern.java index e602ecd3498..a25aa969e44 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/pattern/UriPattern.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/pattern/UriPattern.java @@ -136,7 +136,7 @@ public boolean conflictsWith(UriPattern otherPattern) { continue; } if (segment.isLiteral() && otherSegment.isLiteral() - && segment.getContent().equals(otherSegment.getContent())) { + && segment.getContent().equals(otherSegment.getContent())) { continue; } return false; @@ -151,9 +151,9 @@ public boolean conflictsWith(UriPattern otherPattern) { public List> getConflictingLabelSegments(UriPattern otherPattern) { Map conflictingSegments = getConflictingLabelSegmentsMap(otherPattern); return conflictingSegments.entrySet() - .stream() - .map(entry -> Pair.of(entry.getKey(), entry.getValue())) - .collect(Collectors.toList()); + .stream() + .map(entry -> Pair.of(entry.getKey(), entry.getValue())) + .collect(Collectors.toList()); } @Override diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/selector/AttributeComparator.java b/smithy-model/src/main/java/software/amazon/smithy/model/selector/AttributeComparator.java index 5fb6fe714ae..0624f030c06 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/selector/AttributeComparator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/selector/AttributeComparator.java @@ -120,7 +120,7 @@ static BigDecimal parseNumber(String token) { static boolean existsCheck(AttributeValue a, AttributeValue b, boolean caseInsensitive) { String bString = b.toString(); return (a.isPresent() && bString.equals("true")) - || (!a.isPresent() && b.toString().equals("false")); + || (!a.isPresent() && b.toString().equals("false")); } static boolean areBothProjections(AttributeValue a, AttributeValue b) { @@ -129,16 +129,16 @@ static boolean areBothProjections(AttributeValue a, AttributeValue b) { static boolean subset(AttributeValue a, AttributeValue b, boolean caseInsensitive) { return areBothProjections(a, b) - && isSubset(a.getFlattenedValues(), b.getFlattenedValues(), caseInsensitive); + && isSubset(a.getFlattenedValues(), b.getFlattenedValues(), caseInsensitive); } // Note that projections with different sizes can still be subsets since // they operate like Sets<> where multiple instances of the same value // are treated as a single value. static boolean isSubset( - Collection aValues, - Collection bValues, - boolean caseInsensitive + Collection aValues, + Collection bValues, + boolean caseInsensitive ) { for (AttributeValue aValue : aValues) { boolean foundMatch = false; @@ -166,7 +166,7 @@ static boolean properSubset(AttributeValue a, AttributeValue b, boolean caseInse Collection aValues = a.getFlattenedValues(); Collection bValues = b.getFlattenedValues(); return isSubset(aValues, bValues, caseInsensitive) - && !isSubset(bValues, aValues, caseInsensitive); + && !isSubset(bValues, aValues, caseInsensitive); } // {A} is equal to {B} if they are both subsets of one another. @@ -178,7 +178,7 @@ static boolean setEquals(AttributeValue a, AttributeValue b, boolean caseInsensi Collection aValues = a.getFlattenedValues(); Collection bValues = b.getFlattenedValues(); return isSubset(aValues, bValues, caseInsensitive) - && isSubset(bValues, aValues, caseInsensitive); + && isSubset(bValues, aValues, caseInsensitive); } static boolean setNotEquals(AttributeValue a, AttributeValue b, boolean caseInsensitive) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/selector/AttributeSelector.java b/smithy-model/src/main/java/software/amazon/smithy/model/selector/AttributeSelector.java index 105a8d04c3d..4d47f622670 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/selector/AttributeSelector.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/selector/AttributeSelector.java @@ -26,10 +26,10 @@ final class AttributeSelector implements InternalSelector { private final Function> optimizer; AttributeSelector( - List path, - List expected, - AttributeComparator comparator, - boolean caseInsensitive + List path, + List expected, + AttributeComparator comparator, + boolean caseInsensitive ) { this.path = path; this.caseInsensitive = caseInsensitive; @@ -49,9 +49,9 @@ final class AttributeSelector implements InternalSelector { // This optimization can only be applied when there's no comparator, // and it doesn't matter how deep into the trait the selector descends. if (comparator == null - && path.size() >= 2 - && path.get(0).equals("trait") // only match on traits - && !path.get(1).startsWith("(")) { // don't match projections + && path.size() >= 2 + && path.get(0).equals("trait") // only match on traits + && !path.get(1).startsWith("(")) { // don't match projections optimizer = model -> { // The trait name might be relative to the prelude, so ensure it's absolute. String absoluteShapeId = Trait.makeAbsoluteName(path.get(1)); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/selector/AttributeValueImpl.java b/smithy-model/src/main/java/software/amazon/smithy/model/selector/AttributeValueImpl.java index c854e7a2868..acb4d1e1db7 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/selector/AttributeValueImpl.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/selector/AttributeValueImpl.java @@ -140,9 +140,9 @@ public AttributeValue getProperty(String key) { return AttributeValue.literal(objectNode.getMembers().size()); default: return value.expectObjectNode() - .getMember(key) - .map(NodeValue::new) - .orElse(EMPTY); + .getMember(key) + .map(NodeValue::new) + .orElse(EMPTY); } case ARRAY: ArrayNode arrayNode = value.expectArrayNode(); @@ -238,9 +238,9 @@ public String toMessageString() { // Returns a comma separated (with a space), sorted list of each flattened // value's debug string. str = getFlattenedValues().stream() - .map(AttributeValue::toMessageString) - .sorted() - .collect(Collectors.joining(", ", "[", "]")); + .map(AttributeValue::toMessageString) + .sorted() + .collect(Collectors.joining(", ", "[", "]")); messageString = str; } return str; @@ -340,8 +340,8 @@ public AttributeValue getProperty(String property) { return AttributeValue.literal(id.getNamespace()); case "member": return id.getMember() - .map(Literal::new) - .orElse(EMPTY); + .map(Literal::new) + .orElse(EMPTY); case LENGTH: // Length returns the length of the shape ID. return AttributeValue.literal(id.toString().length()); @@ -402,8 +402,8 @@ public AttributeValue getProperty(String property) { // A normal property getter. This allows relative trait shape IDs // and absolute IDs. Relative IDs resolve to 'smithy.api'. return shape.findTrait(ShapeId.from(Trait.makeAbsoluteName(property))) - .map(trait -> new NodeValue(trait.toNode())) - .orElse(EMPTY); + .map(trait -> new NodeValue(trait.toNode())) + .orElse(EMPTY); } } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/selector/NeighborSelector.java b/smithy-model/src/main/java/software/amazon/smithy/model/selector/NeighborSelector.java index b405a219a36..b34b652fcfc 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/selector/NeighborSelector.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/selector/NeighborSelector.java @@ -42,8 +42,8 @@ protected Response emit(Context context, Relationship rel, Receiver next) { @Override protected Function neighborFactory(boolean includeTraits) { return includeTraits - ? context -> context.neighborIndex.getProviderWithTraitRelationships() - : context -> context.neighborIndex.getProvider(); + ? context -> context.neighborIndex.getProviderWithTraitRelationships() + : context -> context.neighborIndex.getProvider(); } }, REVERSE { @@ -55,8 +55,8 @@ protected Response emit(Context context, Relationship rel, Receiver next) { @Override protected Function neighborFactory(boolean includeTraits) { return includeTraits - ? context -> context.neighborIndex.getReverseProviderWithTraitRelationships() - : context -> context.neighborIndex.getReverseProvider(); + ? context -> context.neighborIndex.getReverseProviderWithTraitRelationships() + : context -> context.neighborIndex.getReverseProvider(); } }; @@ -121,8 +121,8 @@ public Response push(Context context, Shape shape, Receiver next) { private boolean matches(Relationship rel) { return rel.getRelationshipType() != RelationshipType.MEMBER_CONTAINER - && rel.getNeighborShape().isPresent() - && relTypesMatchesRel(relTypes, rel); + && rel.getNeighborShape().isPresent() + && relTypesMatchesRel(relTypes, rel); } private static boolean relTypesMatchesRel(List relTypes, Relationship rel) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/selector/PathFinder.java b/smithy-model/src/main/java/software/amazon/smithy/model/selector/PathFinder.java index e9969ed3c9a..456e26e0fbb 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/selector/PathFinder.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/selector/PathFinder.java @@ -159,8 +159,8 @@ public Optional createPathToOutputMember(ToShapeId operationId, String mem private Optional createPathTo(ToShapeId operationId, String memberName, RelationshipType rel) { OperationShape operation = model.getShape(operationId.toShapeId()) - .flatMap(Shape::asOperationShape) - .orElse(null); + .flatMap(Shape::asOperationShape) + .orElse(null); if (operation == null) { return Optional.empty(); @@ -307,12 +307,12 @@ public Shape getStartShape() { public Shape getEndShape() { Relationship last = tail(); return last.getNeighborShape() - .orElseThrow( - () -> new SourceException( - "Relationship points to a shape that is invalid: " + last, - last.getShape() - ) - ); + .orElseThrow( + () -> new SourceException( + "Relationship points to a shape that is invalid: " + last, + last.getShape() + ) + ); } private Relationship tail() { @@ -338,12 +338,12 @@ public String toString() { result.append(" > "); } else { result.append(" -[") - .append( - rel.getRelationshipType() - .getSelectorLabel() - .orElseGet(() -> rel.getRelationshipType().toString()) - ) - .append("]-> "); + .append( + rel.getRelationshipType() + .getSelectorLabel() + .orElseGet(() -> rel.getRelationshipType().toString()) + ) + .append("]-> "); } result.append("[id|").append(rel.getNeighborShapeId()).append("]"); } @@ -360,10 +360,10 @@ private static final class Search { private final Predicate filter; Search( - NeighborProvider provider, - Shape startingShape, - Collection candidates, - Predicate filter + NeighborProvider provider, + Shape startingShape, + Collection candidates, + Predicate filter ) { this.startingShape = startingShape; this.candidates = candidates; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/selector/ScopedAttributeSelector.java b/smithy-model/src/main/java/software/amazon/smithy/model/selector/ScopedAttributeSelector.java index a859ea87bb6..ff11f1c7c80 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/selector/ScopedAttributeSelector.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/selector/ScopedAttributeSelector.java @@ -22,10 +22,10 @@ static final class Assertion { private final boolean caseInsensitive; Assertion( - ScopedFactory lhs, - AttributeComparator comparator, - List rhs, - boolean caseInsensitive + ScopedFactory lhs, + AttributeComparator comparator, + List rhs, + boolean caseInsensitive ) { this.lhs = lhs; this.comparator = comparator; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/selector/Selector.java b/smithy-model/src/main/java/software/amazon/smithy/model/selector/Selector.java index 00641603d63..14833fd00d3 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/selector/Selector.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/selector/Selector.java @@ -258,8 +258,8 @@ public Set selectShapes() { @Deprecated public void selectMatches(BiConsumer>> matchConsumer) { selector.consumeMatches( - Objects.requireNonNull(model, "model not set"), - m -> matchConsumer.accept(m.getShape(), m) + Objects.requireNonNull(model, "model not set"), + m -> matchConsumer.accept(m.getShape(), m) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/selector/SelectorParser.java b/smithy-model/src/main/java/software/amazon/smithy/model/selector/SelectorParser.java index fe5d2afdb87..aa398444675 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/selector/SelectorParser.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/selector/SelectorParser.java @@ -133,7 +133,7 @@ private InternalSelector createSelector() { return new ShapeTypeCategorySelector(CollectionShape.class); default: ShapeType shape = ShapeType.fromString(identifier) - .orElseThrow(() -> syntax("Unknown shape type: " + identifier)); + .orElseThrow(() -> syntax("Unknown shape type: " + identifier)); return new ShapeTypeSelector(shape); } } else if (peek() == Character.MIN_VALUE) { @@ -201,12 +201,12 @@ private List parseSelectorDirectedRelationships() { // Tolerate unknown relationships, but log a warning. if (!REL_TYPES.contains(next)) { LOGGER.warning( - String.format( - "Unknown relationship type '%s' found near %s. Expected one of: %s", - next, - position() - next.length(), - REL_TYPES - ) + String.format( + "Unknown relationship type '%s' found near %s. Expected one of: %s", + next, + position() - next.length(), + REL_TYPES + ) ); } @@ -225,11 +225,11 @@ private InternalSelector parseSelectorFunction() { case "not": if (selectors.size() != 1) { throw new SelectorSyntaxException( - "The :not function requires a single selector argument", - input().toString(), - functionPosition, - line(), - column() + "The :not function requires a single selector argument", + input().toString(), + functionPosition, + line(), + column() ); } return new NotSelector(selectors.get(0)); @@ -240,22 +240,22 @@ private InternalSelector parseSelectorFunction() { case "in": if (selectors.size() != 1) { throw new SelectorSyntaxException( - "The :in function requires a single selector argument", - input().toString(), - functionPosition, - line(), - column() + "The :in function requires a single selector argument", + input().toString(), + functionPosition, + line(), + column() ); } return new InSelector(selectors.get(0)); case "root": if (selectors.size() != 1) { throw new SelectorSyntaxException( - "The :root function requires a single selector argument", - input().toString(), - functionPosition, - line(), - column() + "The :root function requires a single selector argument", + input().toString(), + functionPosition, + line(), + column() ); } InternalSelector root = new RootSelector(selectors.get(0), roots.size()); @@ -264,22 +264,22 @@ private InternalSelector parseSelectorFunction() { case "topdown": if (selectors.size() > 2) { throw new SelectorSyntaxException( - "The :topdown function accepts 1 or 2 selectors, but found " + selectors.size(), - input().toString(), - functionPosition, - line(), - column() + "The :topdown function accepts 1 or 2 selectors, but found " + selectors.size(), + input().toString(), + functionPosition, + line(), + column() ); } return new TopDownSelector(selectors); case "recursive": if (selectors.size() != 1) { throw new SelectorSyntaxException( - "The :recursive function requires a single selector argument", - input().toString(), - functionPosition, - line(), - column() + "The :recursive function requires a single selector argument", + input().toString(), + functionPosition, + line(), + column() ); } return new RecursiveSelector(selectors.get(0)); @@ -288,11 +288,11 @@ private InternalSelector parseSelectorFunction() { return IsSelector.of(selectors); default: LOGGER.warning( - String.format( - "Unknown function name `%s` found in selector: %s", - name, - input() - ) + String.format( + "Unknown function name `%s` found in selector: %s", + name, + input() + ) ); return (context, shape, next) -> InternalSelector.Response.CONTINUE; } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/selector/ShapeTypeSelector.java b/smithy-model/src/main/java/software/amazon/smithy/model/selector/ShapeTypeSelector.java index 3d66e99f8b7..6ce990a600b 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/selector/ShapeTypeSelector.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/selector/ShapeTypeSelector.java @@ -34,7 +34,7 @@ public Collection getStartingShapes(Model model) { @Override public ContainsShape containsShapeOptimization(Context context, Shape shape) { return context.getModel().toSet(shapeType.getShapeClass()).contains(shape) - ? ContainsShape.YES - : ContainsShape.NO; + ? ContainsShape.YES + : ContainsShape.NO; } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/selector/TopDownSelector.java b/smithy-model/src/main/java/software/amazon/smithy/model/selector/TopDownSelector.java index 5f23181f271..af6254b4e59 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/selector/TopDownSelector.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/selector/TopDownSelector.java @@ -61,7 +61,7 @@ private Response pushMatch(boolean qualified, Context context, Shape shape, Rece for (Relationship rel : context.neighborIndex.getProvider().getNeighbors(shape)) { if (rel.getNeighborShape().isPresent() && !rel.getNeighborShapeId().equals(shape.getId())) { if (rel.getRelationshipType() == RelationshipType.RESOURCE - || rel.getRelationshipType() == RelationshipType.OPERATION) { + || rel.getRelationshipType() == RelationshipType.OPERATION) { if (pushMatch(qualified, context, rel.getNeighborShape().get(), next, visited) == Response.STOP) { return Response.STOP; } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/selector/WrappedSelector.java b/smithy-model/src/main/java/software/amazon/smithy/model/selector/WrappedSelector.java index e03cbdd4f49..2c8ee86ee26 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/selector/WrappedSelector.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/selector/WrappedSelector.java @@ -141,10 +141,10 @@ private List> computeRoots(Model model) { // Eagerly compute a root subexpression. private Set evalRoot( - Model model, - NeighborProviderIndex index, - InternalSelector selector, - List> results + Model model, + NeighborProviderIndex index, + InternalSelector selector, + List> results ) { Collection shapesToEmit = selector.getStartingShapes(model); Context isolatedContext = new Context(model, index, results); @@ -161,9 +161,9 @@ private Set evalRoot( } private void pushShapes( - Model model, - Collection startingShapes, - InternalSelector.Receiver acceptor + Model model, + Collection startingShapes, + InternalSelector.Receiver acceptor ) { Objects.requireNonNull(startingShapes); Context context = new Context(model, NeighborProviderIndex.of(model), computeRoots(model)); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/AbstractShapeBuilder.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/AbstractShapeBuilder.java index 5c9159cfd46..90feb5d532f 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/AbstractShapeBuilder.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/AbstractShapeBuilder.java @@ -26,7 +26,7 @@ * @param Shape being created. */ public abstract class AbstractShapeBuilder, S extends Shape> - implements SmithyBuilder, FromSourceLocation { + implements SmithyBuilder, FromSourceLocation { private ShapeId id; private final BuilderRef> traits = BuilderRef.forUnorderedMap(); @@ -214,11 +214,11 @@ public Optional getMember(String memberName) { */ public B addMember(MemberShape member) { throw new UnsupportedOperationException( - String.format( - "Member `%s` cannot be added to %s", - member.getId(), - getClass().getName() - ) + String.format( + "Member `%s` cannot be added to %s", + member.getId(), + getClass().getName() + ) ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/CollectionShape.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/CollectionShape.java index 1cfb81ad752..f8e4924a059 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/CollectionShape.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/CollectionShape.java @@ -63,7 +63,7 @@ public final Map getAllMembers() { * @param Shape type being created. */ public abstract static class Builder, S extends CollectionShape> - extends AbstractShapeBuilder { + extends AbstractShapeBuilder { private MemberShape member; @@ -95,9 +95,9 @@ public B member(MemberShape member) { if (member != null && !member.getMemberName().equals("member")) { String shapeTypeName = StringUtils.capitalize(this.getShapeType().toString()); String message = String.format( - "%s shapes may only have a `member` member, but found `%s`", - shapeTypeName, - member.getMemberName() + "%s shapes may only have a `member` member, but found `%s`", + shapeTypeName, + member.getMemberName() ); throw new SourceException(message, member); } @@ -127,8 +127,8 @@ public B member(ShapeId target, Consumer memberUpdater) { } MemberShape.Builder builder = MemberShape.builder() - .target(target) - .id(getId().withMember("member")); + .target(target) + .id(getId().withMember("member")); if (memberUpdater != null) { memberUpdater.accept(builder); @@ -165,12 +165,12 @@ public B flattenMixins() { location = existing.getSourceLocation(); } member = MemberShape.builder() - .id(getId().withMember(mixinMember.getMemberName())) - .target(mixinMember.getTarget()) - .addTraits(mixinMember.getAllTraits().values()) - .addTraits(localTraits) - .source(location) - .build(); + .id(getId().withMember(mixinMember.getMemberName())) + .target(mixinMember.getTarget()) + .addTraits(mixinMember.getAllTraits().values()) + .addTraits(localTraits) + .source(location) + .build(); } return super.flattenMixins(); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/EntityShape.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/EntityShape.java index 9e030e576f7..cbba359099d 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/EntityShape.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/EntityShape.java @@ -126,7 +126,7 @@ public boolean equals(Object other) { * @param Shape type being created. */ public abstract static class Builder, S extends EntityShape> - extends AbstractShapeBuilder { + extends AbstractShapeBuilder { private final BuilderRef> resources = BuilderRef.forOrderedSet(); private final BuilderRef> operations = BuilderRef.forOrderedSet(); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/EnumShape.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/EnumShape.java index 0e1663f4332..6417629436a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/EnumShape.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/EnumShape.java @@ -39,10 +39,10 @@ public final class EnumShape extends StringShape { private EnumShape(Builder builder) { super(builder); members = NamedMemberUtils.computeMixinMembers( - builder.getMixins(), - builder.members, - getId(), - getSourceLocation() + builder.getMixins(), + builder.members, + getId(), + getSourceLocation() ); validateMemberShapeIds(); if (members.size() < 1) { @@ -137,9 +137,9 @@ public static Optional fromStringShape(StringShape shape, boolean syn stringWithoutEnumTrait.updateBuilder(enumBuilder); try { return Optional.of( - enumBuilder - .setMembersFromEnumTrait(shape.expectTrait(EnumTrait.class), synthesizeNames) - .build() + enumBuilder + .setMembersFromEnumTrait(shape.expectTrait(EnumTrait.class), synthesizeNames) + .build() ); } catch (IllegalStateException e) { LOGGER.info(String.format("Unable to convert `%s` to an enum: %s", shape.getId(), e)); @@ -174,10 +174,10 @@ public static boolean canConvertToEnum(StringShape shape, boolean synthesizeEnum if (!shape.hasTrait(EnumTrait.class)) { LOGGER.info( - String.format( - "Unable to convert string shape `%s` to enum shape because it doesn't have an enum trait.", - shape.getId() - ) + String.format( + "Unable to convert string shape `%s` to enum shape because it doesn't have an enum trait.", + shape.getId() + ) ); return false; } @@ -185,11 +185,11 @@ public static boolean canConvertToEnum(StringShape shape, boolean synthesizeEnum EnumTrait trait = shape.expectTrait(EnumTrait.class); if (!trait.hasNames() && !synthesizeEnumNames) { LOGGER.info( - String.format( - "Unable to convert string shape `%s` to enum shape because it doesn't define names. The " - + "`synthesizeNames` option may be able to synthesize the names for you.", - shape.getId() - ) + String.format( + "Unable to convert string shape `%s` to enum shape because it doesn't define names. The " + + "`synthesizeNames` option may be able to synthesize the names for you.", + shape.getId() + ) ); return false; } @@ -197,12 +197,12 @@ public static boolean canConvertToEnum(StringShape shape, boolean synthesizeEnum for (EnumDefinition definition : trait.getValues()) { if (!canConvertEnumDefinitionToMember(definition, synthesizeEnumNames)) { LOGGER.info( - String.format( - "Unable to convert string shape `%s` to enum shape because it has at least one value which " - + "cannot be safely synthesized into a name: %s", - shape.getId(), - definition.getValue() - ) + String.format( + "Unable to convert string shape `%s` to enum shape because it has at least one value which " + + "cannot be safely synthesized into a name: %s", + shape.getId(), + definition.getValue() + ) ); return false; } @@ -226,9 +226,9 @@ public static boolean canConvertToEnum(StringShape shape, boolean synthesizeEnum * or empty if conversion is impossible. */ static Optional memberFromEnumDefinition( - EnumDefinition definition, - ShapeId parentId, - boolean synthesizeName + EnumDefinition definition, + ShapeId parentId, + boolean synthesizeName ) { String name; if (!definition.getName().isPresent()) { @@ -243,9 +243,9 @@ static Optional memberFromEnumDefinition( try { MemberShape.Builder builder = MemberShape.builder() - .id(parentId.withMember(name)) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue(definition.getValue()).build()); + .id(parentId.withMember(name)) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue(definition.getValue()).build()); definition.getDocumentation().ifPresent(docs -> builder.addTrait(new DocumentationTrait(docs))); if (!definition.getTags().isEmpty()) { @@ -272,7 +272,7 @@ static Optional memberFromEnumDefinition( */ static boolean canConvertEnumDefinitionToMember(EnumDefinition definition, boolean withSynthesizedNames) { return definition.getName().isPresent() - || (withSynthesizedNames && CONVERTABLE_VALUE.matcher(definition.getValue()).find()); + || (withSynthesizedNames && CONVERTABLE_VALUE.matcher(definition.getValue()).find()); } /** @@ -285,16 +285,16 @@ static EnumDefinition enumDefinitionFromMember(MemberShape member) { EnumDefinition.Builder builder = EnumDefinition.builder().name(member.getMemberName()); String traitValue = member - .getTrait(EnumValueTrait.class) - .flatMap(EnumValueTrait::getStringValue) - .orElseThrow(() -> new IllegalStateException("Enum definitions can only be made for string enums.")); + .getTrait(EnumValueTrait.class) + .flatMap(EnumValueTrait::getStringValue) + .orElseThrow(() -> new IllegalStateException("Enum definitions can only be made for string enums.")); builder.value(traitValue); member.getTrait(DocumentationTrait.class).ifPresent(docTrait -> builder.documentation(docTrait.getValue())); member.getTrait(DeprecatedTrait.class).ifPresent(deprecatedTrait -> builder.deprecated(true)); List tags = member.getTrait(TagsTrait.class) - .map(StringListTrait::getValues) - .orElse(Collections.emptyList()); + .map(StringListTrait::getValues) + .orElse(Collections.emptyList()); builder.tags(tags); if (member.hasTrait(InternalTrait.class) && !tags.contains("internal")) { @@ -315,10 +315,10 @@ public static final class Builder extends StringShape.Builder { public EnumShape build() { // Collect members from enum and mixins Map aggregatedMembers = NamedMemberUtils.computeMixinMembers( - getMixins(), - members, - getId(), - getSourceLocation() + getMixins(), + members, + getId(), + getSourceLocation() ); addSyntheticEnumTrait(aggregatedMembers.values()); return new EnumShape(this, aggregatedMembers); @@ -388,11 +388,11 @@ public Builder setMembersFromEnumTrait(EnumTrait trait, boolean synthesizeNames) addMember(member.get()); } else { throw new IllegalStateException( - String.format( - "Unable to convert enum trait entry with name: `%s` and value `%s` to an enum member.", - definition.getName().orElse(""), - definition.getValue() - ) + String.format( + "Unable to convert enum trait entry with name: `%s` and value `%s` to an enum member.", + definition.getName().orElse(""), + definition.getValue() + ) ); } } @@ -446,17 +446,17 @@ public Builder clearMembers() { public Builder addMember(MemberShape member) { if (!member.getTarget().equals(UnitTypeTrait.UNIT)) { throw new SourceException( - String.format( - "Enum members may only target `smithy.api#Unit`, but found `%s`", - member.getTarget() - ), - getSourceLocation() + String.format( + "Enum members may only target `smithy.api#Unit`, but found `%s`", + member.getTarget() + ), + getSourceLocation() ); } if (!member.hasTrait(EnumValueTrait.ID)) { member = member.toBuilder() - .addTrait(EnumValueTrait.builder().stringValue(member.getMemberName()).build()) - .build(); + .addTrait(EnumValueTrait.builder().stringValue(member.getMemberName()).build()) + .build(); } members.get().put(member.getMemberName(), member); @@ -488,9 +488,9 @@ public Builder addMember(String memberName, String enumValue, Consumer memberUpdater) } MemberShape.Builder builder = MemberShape.builder() - .target(target) - .id(getId().withMember("key")); + .target(target) + .id(getId().withMember("key")); if (memberUpdater != null) { memberUpdater.accept(builder); @@ -277,8 +277,8 @@ public Builder value(ShapeId target, Consumer memberUpdater } MemberShape.Builder builder = MemberShape.builder() - .target(target) - .id(getId().withMember("value")); + .target(target) + .id(getId().withMember("value")); if (memberUpdater != null) { memberUpdater.accept(builder); @@ -311,13 +311,13 @@ public Builder flattenMixins() { } addMember( - MemberShape.builder() - .id(getId().withMember(member.getMemberName())) - .target(member.getTarget()) - .addTraits(member.getAllTraits().values()) - .addTraits(localTraits) - .source(location) - .build() + MemberShape.builder() + .id(getId().withMember(member.getMemberName())) + .target(member.getTarget()) + .addTraits(member.getAllTraits().values()) + .addTraits(localTraits) + .source(location) + .build() ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/MemberShape.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/MemberShape.java index 82a750bb700..e6a20b04e70 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/MemberShape.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/MemberShape.java @@ -115,16 +115,16 @@ public boolean equals(Object other) { @Override public Optional getMemberTrait(Model model, Class trait) { return OptionalUtils.or( - getTrait(trait), - () -> model.getShape(getTarget()).flatMap(targetedShape -> targetedShape.getTrait(trait)) + getTrait(trait), + () -> model.getShape(getTarget()).flatMap(targetedShape -> targetedShape.getTrait(trait)) ); } @Override public Optional findMemberTrait(Model model, String traitName) { return OptionalUtils.or( - findTrait(traitName), - () -> model.getShape(getTarget()).flatMap(targetedShape -> targetedShape.findTrait(traitName)) + findTrait(traitName), + () -> model.getShape(getTarget()).flatMap(targetedShape -> targetedShape.findTrait(traitName)) ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ModelSerializer.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ModelSerializer.java index 69298915f8b..9bd8186de09 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ModelSerializer.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ModelSerializer.java @@ -54,11 +54,11 @@ public final class ModelSerializer { // default traits from the output, whereas the downgradeToV1 transform only removes unnecessary default traits // that don't correlate to boxing in V1 models. private static final Set V2_TRAITS_TO_FILTER_FROM_V1 = SetUtils.of( - DefaultTrait.ID, - AddedDefaultTrait.ID, - ClientOptionalTrait.ID, - PropertyTrait.ID, - NotPropertyTrait.ID + DefaultTrait.ID, + AddedDefaultTrait.ID, + ClientOptionalTrait.ID, + PropertyTrait.ID, + NotPropertyTrait.ID ); private final Predicate metadataFilter; @@ -104,8 +104,8 @@ public ObjectNode serialize(Model model) { } ObjectNode.Builder builder = Node.objectNodeBuilder() - .withMember("smithy", Node.from(version)) - .withOptionalMember("metadata", createMetadata(model).map(Node::withDeepSortedKeys)); + .withMember("smithy", Node.from(version)) + .withOptionalMember("metadata", createMetadata(model).map(Node::withDeepSortedKeys)); // Sort shapes by ID. Map shapes = new TreeMap<>(); @@ -121,7 +121,7 @@ public ObjectNode serialize(Model model) { if (!shapeSerializer.mixinMemberTraits.isEmpty()) { for (MemberShape member : shapeSerializer.mixinMemberTraits) { Map introducedTraits = createIntroducedTraitsMap( - member.getIntroducedTraits().values() + member.getIntroducedTraits().values() ); if (!introducedTraits.isEmpty()) { ObjectNode.Builder applyBuilder = Node.objectNodeBuilder(); @@ -142,10 +142,10 @@ public ObjectNode serialize(Model model) { private Optional createMetadata(Model model) { // Grab metadata, filter by key using the predicate. Map metadata = model.getMetadata() - .entrySet() - .stream() - .filter(entry -> metadataFilter.test(entry.getKey())) - .collect(Collectors.toMap(entry -> Node.from(entry.getKey()), Map.Entry::getValue)); + .entrySet() + .stream() + .filter(entry -> metadataFilter.test(entry.getKey())) + .collect(Collectors.toMap(entry -> Node.from(entry.getKey()), Map.Entry::getValue)); return metadata.isEmpty() ? Optional.empty() : Optional.of(new ObjectNode(metadata, SourceLocation.NONE)); } @@ -285,7 +285,7 @@ private final class ShapeSerializer extends ShapeVisitor.Default { private ObjectNode.Builder createTypedBuilder(Shape shape) { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withMember("type", Node.from(shape.getType().toString())); + .withMember("type", Node.from(shape.getType().toString())); if (!shape.getMixins().isEmpty()) { List mixins = new ArrayList<>(shape.getMixins().size()); @@ -345,13 +345,13 @@ public Node mapShape(MapShape shape) { @Override public Node operationShape(OperationShape shape) { return serializeAllTraits( - shape, - createTypedBuilder(shape) - .withMember("input", serializeReference(shape.getInputShape())) - .withMember("output", serializeReference(shape.getOutputShape())) - .withOptionalMember("errors", createOptionalIdList(shape.getIntroducedErrors())) + shape, + createTypedBuilder(shape) + .withMember("input", serializeReference(shape.getInputShape())) + .withMember("output", serializeReference(shape.getOutputShape())) + .withOptionalMember("errors", createOptionalIdList(shape.getIntroducedErrors())) ) - .build(); + .build(); } @Override @@ -361,42 +361,45 @@ public Node resourceShape(ResourceShape shape) { if (shape.hasIdentifiers()) { Stream> ids = shape.getIdentifiers().entrySet().stream(); identifiers = Optional.of( - ids.collect( - ObjectNode.collectStringKeys( - Map.Entry::getKey, - entry -> serializeReference(entry.getValue()) + ids.collect( + ObjectNode.collectStringKeys( + Map.Entry::getKey, + entry -> serializeReference(entry.getValue()) + ) ) - ) ); } if (shape.hasProperties()) { Stream> props = shape.getProperties().entrySet().stream(); properties = Optional.of( - props.collect( - ObjectNode.collectStringKeys( - Map.Entry::getKey, - entry -> serializeReference(entry.getValue()) + props.collect( + ObjectNode.collectStringKeys( + Map.Entry::getKey, + entry -> serializeReference(entry.getValue()) + ) ) - ) ); } return serializeAllTraits( - shape, - createTypedBuilder(shape) - .withOptionalMember("identifiers", identifiers) - .withOptionalMember("properties", properties) - .withOptionalMember("put", shape.getPut().map(this::serializeReference)) - .withOptionalMember("create", shape.getCreate().map(this::serializeReference)) - .withOptionalMember("read", shape.getRead().map(this::serializeReference)) - .withOptionalMember("update", shape.getUpdate().map(this::serializeReference)) - .withOptionalMember("delete", shape.getDelete().map(this::serializeReference)) - .withOptionalMember("list", shape.getList().map(this::serializeReference)) - .withOptionalMember("operations", createOptionalIdList(shape.getIntroducedOperations())) - .withOptionalMember("collectionOperations", createOptionalIdList(shape.getCollectionOperations())) - .withOptionalMember("resources", createOptionalIdList(shape.getIntroducedResources())) + shape, + createTypedBuilder(shape) + .withOptionalMember("identifiers", identifiers) + .withOptionalMember("properties", properties) + .withOptionalMember("put", shape.getPut().map(this::serializeReference)) + .withOptionalMember("create", shape.getCreate().map(this::serializeReference)) + .withOptionalMember("read", shape.getRead().map(this::serializeReference)) + .withOptionalMember("update", shape.getUpdate().map(this::serializeReference)) + .withOptionalMember("delete", shape.getDelete().map(this::serializeReference)) + .withOptionalMember("list", shape.getList().map(this::serializeReference)) + .withOptionalMember("operations", createOptionalIdList(shape.getIntroducedOperations())) + .withOptionalMember( + "collectionOperations", + createOptionalIdList(shape.getCollectionOperations()) + ) + .withOptionalMember("resources", createOptionalIdList(shape.getIntroducedResources())) ) - .build(); + .build(); } @Override @@ -429,9 +432,9 @@ private Optional createOptionalIdList(Collection list) { } Node result = list.stream() - .sorted() - .map(this::serializeReference) - .collect(ArrayNode.collect()); + .sorted() + .map(this::serializeReference) + .collect(ArrayNode.collect()); return Optional.of(result); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/NamedMemberUtils.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/NamedMemberUtils.java index 39f9e960eb0..9f901743f0c 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/NamedMemberUtils.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/NamedMemberUtils.java @@ -21,10 +21,10 @@ private NamedMemberUtils() { } static Map computeMixinMembers( - Map mixins, - BuilderRef> members, - ShapeId shapeId, - SourceLocation sourceLocation + Map mixins, + BuilderRef> members, + ShapeId shapeId, + SourceLocation sourceLocation ) { if (mixins.isEmpty()) { return members.copy(); @@ -50,22 +50,22 @@ static Map computeMixinMembers( if (previouslyDefined != null) { validateMixinMemberConflict(member, previouslyDefined); computedMembers.put( - name, - previouslyDefined.toBuilder() - .source(member.getSourceLocation()) - .addMixin(member) - .addTraits(member.getAllTraits().values()) - .build() + name, + previouslyDefined.toBuilder() + .source(member.getSourceLocation()) + .addMixin(member) + .addTraits(member.getAllTraits().values()) + .build() ); } else { computedMembers.put( - name, - MemberShape.builder() - .id(shapeId.withMember(name)) - .target(member.getTarget()) - .source(member.getSourceLocation()) - .addMixin(member) - .build() + name, + MemberShape.builder() + .id(shapeId.withMember(name)) + .target(member.getTarget()) + .source(member.getSourceLocation()) + .addMixin(member) + .build() ); } } @@ -90,10 +90,10 @@ private static MemberShape rebuildMemberMixins(MemberShape member, Collection flattenMixins( - Map members, - Map mixins, - ShapeId shapeId, - SourceLocation sourceLocation + Map members, + Map mixins, + ShapeId shapeId, + SourceLocation sourceLocation ) { // Ensure that the members are ordered, mixin members first, followed by local members. Map orderedMembers = new LinkedHashMap<>(); @@ -116,14 +116,14 @@ static Set flattenMixins( validateMixinMemberConflict(member, previouslyDefined); } orderedMembers.put( - memberName, - MemberShape.builder() - .id(shapeId.withMember(memberName)) - .target(member.getTarget()) - .addTraits(previousTraits) - .addTraits(member.getAllTraits().values()) - .source(member.getSourceLocation()) - .build() + memberName, + MemberShape.builder() + .id(shapeId.withMember(memberName)) + .target(member.getTarget()) + .addTraits(previousTraits) + .addTraits(member.getAllTraits().values()) + .source(member.getSourceLocation()) + .build() ); } } @@ -133,11 +133,11 @@ static Set flattenMixins( MemberShape existing = entry.getValue(); MemberShape needUpdate = orderedMembers.get(memberName); orderedMembers.put( - memberName, - needUpdate.toBuilder() - .source(existing.getSourceLocation()) - .addTraits(existing.getIntroducedTraits().values()) - .build() + memberName, + needUpdate.toBuilder() + .source(existing.getSourceLocation()) + .addTraits(existing.getIntroducedTraits().values()) + .build() ); } @@ -150,9 +150,9 @@ static Set flattenMixins( static void validateMixinMemberConflict(MemberShape member, MemberShape previouslyDefined) { if (!previouslyDefined.getTarget().equals(member.getTarget())) { throw new SourceException( - "Member conflicts with an inherited mixin member: `" - + previouslyDefined.getId() + "`", - member + "Member conflicts with an inherited mixin member: `" + + previouslyDefined.getId() + "`", + member ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/NamedMembersShapeBuilder.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/NamedMembersShapeBuilder.java index 169ca7e2f77..6fa673f0886 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/NamedMembersShapeBuilder.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/NamedMembersShapeBuilder.java @@ -16,7 +16,7 @@ * @param Shape type being created. */ abstract class NamedMembersShapeBuilder, S extends Shape> - extends AbstractShapeBuilder { + extends AbstractShapeBuilder { protected final BuilderRef> members = BuilderRef.forOrderedMap(); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/OperationShape.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/OperationShape.java index dc9ac8d9e17..c3b45408259 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/OperationShape.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/OperationShape.java @@ -52,13 +52,13 @@ private OperationShape(Builder builder) { if (hasTrait(MixinTrait.ID) && (!input.equals(UnitTypeTrait.UNIT) || !output.equals(UnitTypeTrait.UNIT))) { throw new SourceException( - String.format( - "Operation shapes with the mixin trait MUST target `%s` for their input and output. Operation " - + "mixin shape `%s` defines one or both of these properties.", - UnitTypeTrait.UNIT, - getId() - ), - builder.getSourceLocation() + String.format( + "Operation shapes with the mixin trait MUST target `%s` for their input and output. Operation " + + "mixin shape `%s` defines one or both of these properties.", + UnitTypeTrait.UNIT, + getId() + ), + builder.getSourceLocation() ); } } @@ -70,9 +70,9 @@ public static Builder builder() { @Override public Builder toBuilder() { return updateBuilder(builder()) - .input(input) - .output(output) - .errors(getIntroducedErrors()); + .input(input) + .output(output) + .errors(getIntroducedErrors()); } @Override @@ -193,8 +193,8 @@ public boolean equals(Object other) { } else { OperationShape otherShape = (OperationShape) other; return input.equals(otherShape.input) - && output.equals(otherShape.output) - && errors.equals(otherShape.errors); + && output.equals(otherShape.output) + && errors.equals(otherShape.errors); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ResourceShape.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ResourceShape.java index 4bbe02d3f27..417739eb482 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ResourceShape.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ResourceShape.java @@ -53,21 +53,21 @@ private ResourceShape(Builder builder) { getList().ifPresent(allOperations::add); if (hasTrait(MixinTrait.ID) && (!getIdentifiers().isEmpty() - || getPut().isPresent() - || getCreate().isPresent() - || getRead().isPresent() - || getUpdate().isPresent() - || getDelete().isPresent() - || getList().isPresent() - || !getProperties().isEmpty() - || !getOperations().isEmpty() - || !getResources().isEmpty())) { + || getPut().isPresent() + || getCreate().isPresent() + || getRead().isPresent() + || getUpdate().isPresent() + || getDelete().isPresent() + || getList().isPresent() + || !getProperties().isEmpty() + || !getOperations().isEmpty() + || !getResources().isEmpty())) { throw new IllegalStateException( - String.format( - "Resource shapes with the mixin trait may not define any properties. Resource mixin shape `%s` " - + "defines one or more properties.", - getId() - ) + String.format( + "Resource shapes with the mixin trait may not define any properties. Resource mixin shape `%s` " + + "defines one or more properties.", + getId() + ) ); } } @@ -79,14 +79,14 @@ public static Builder builder() { @Override public Builder toBuilder() { Builder builder = updateBuilder(builder()) - .identifiers(getIdentifiers()) - .properties(properties) - .put(put) - .create(create) - .read(read) - .update(update) - .delete(delete) - .list(list); + .identifiers(getIdentifiers()) + .properties(properties) + .put(put) + .create(create) + .read(read) + .update(update) + .delete(delete) + .list(list); getOperations().forEach(builder::addOperation); getCollectionOperations().forEach(builder::addCollectionOperation); getResources().forEach(builder::addResource); @@ -212,13 +212,13 @@ public boolean equals(Object other) { ResourceShape otherShape = (ResourceShape) other; return identifiers.equals(otherShape.identifiers) - && Objects.equals(properties, otherShape.properties) - && Objects.equals(create, otherShape.create) - && Objects.equals(put, otherShape.put) - && Objects.equals(read, otherShape.read) - && Objects.equals(update, otherShape.update) - && Objects.equals(delete, otherShape.delete) - && Objects.equals(list, otherShape.list); + && Objects.equals(properties, otherShape.properties) + && Objects.equals(create, otherShape.create) + && Objects.equals(put, otherShape.put) + && Objects.equals(read, otherShape.read) + && Objects.equals(update, otherShape.update) + && Objects.equals(delete, otherShape.delete) + && Objects.equals(list, otherShape.list); } /** diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ServiceShape.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ServiceShape.java index c8c68be62af..cf635c0698c 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ServiceShape.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ServiceShape.java @@ -78,11 +78,11 @@ public static Builder builder() { @Override public Builder toBuilder() { return updateBuilder(builder()) - .version(introducedVersion) - .errors(introducedErrors) - .rename(introducedRename) - .operations(getIntroducedOperations()) - .resources(getIntroducedResources()); + .version(introducedVersion) + .errors(introducedErrors) + .rename(introducedRename) + .operations(getIntroducedOperations()) + .resources(getIntroducedResources()); } @Override @@ -103,8 +103,8 @@ public boolean equals(Object other) { ServiceShape o = (ServiceShape) other; return version.equals(o.version) - && rename.equals(o.rename) - && errors.equals(o.errors); + && rename.equals(o.rename) + && errors.equals(o.errors); } @Override diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/Shape.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/Shape.java index 0a72acafa4f..e8e4a091fa7 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/Shape.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/Shape.java @@ -91,14 +91,14 @@ protected void validateMixins(Map mixins, Map in if (!invalid.isEmpty()) { String invalidList = String.join("`, `", invalid); throw new SourceException( - String.format( - "Mixins may only be mixed into shapes of the same type. The following mixins were applied to the " - + "%s shape `%s` which are not %1$s shapes: [`%s`]", - getType(), - getId(), - invalidList - ), - source + String.format( + "Mixins may only be mixed into shapes of the same type. The following mixins were applied to the " + + "%s shape `%s` which are not %1$s shapes: [`%s`]", + getType(), + getId(), + invalidList + ), + source ); } } @@ -154,21 +154,21 @@ private MemberShape getRequiredMixinMember(AbstractShapeBuilder builder, S } return MemberShape.builder() - .id(getId().withMember(requiredMemberName)) - .target(mostRecentMember.getTarget()) - .source(getSourceLocation()) - .addMixin(mostRecentMember) - .build(); + .id(getId().withMember(requiredMemberName)) + .target(mostRecentMember.getTarget()) + .source(getSourceLocation()) + .addMixin(mostRecentMember) + .build(); } private SourceException missingRequiredMembersException(List missingMembersNames) { String missingRequired = missingMembersNames.size() > 1 ? "members" : "member"; String missingMembers = String.join(", ", missingMembersNames); String message = String.format( - "Missing required %s of shape `%s`: %s", - missingRequired, - getId(), - missingMembers + "Missing required %s of shape `%s`: %s", + missingRequired, + getId(), + missingMembers ); return new SourceException(message, getSourceLocation()); } @@ -182,22 +182,22 @@ private void validateShapeId(boolean expectMember) { if (expectMember) { if (!getId().hasMember()) { throw new SourceException( - String.format( - "Shapes of type `%s` must contain a member in their shape ID. Found `%s`", - getType(), - getId() - ), - getSourceLocation() + String.format( + "Shapes of type `%s` must contain a member in their shape ID. Found `%s`", + getType(), + getId() + ), + getSourceLocation() ); } } else if (getId().hasMember()) { throw new SourceException( - String.format( - "Shapes of type `%s` cannot contain a member in their shape ID. Found `%s`", - getType(), - getId() - ), - getSourceLocation() + String.format( + "Shapes of type `%s` cannot contain a member in their shape ID. Found `%s`", + getType(), + getId() + ), + getSourceLocation() ); } } @@ -207,14 +207,14 @@ protected final void validateMemberShapeIds() { if (!member.getId().toString().startsWith(getId().toString())) { ShapeId expected = getId().withMember(member.getMemberName()); throw new SourceException( - String.format( - "Expected the `%s` member of `%s` to have an ID of `%s` but found `%s`", - member.getMemberName(), - getId(), - expected, - member.getId() - ), - getSourceLocation() + String.format( + "Expected the `%s` member of `%s` to have an ID of `%s` but found `%s`", + member.getMemberName(), + getId(), + expected, + member.getId() + ), + getSourceLocation() ); } } @@ -345,14 +345,14 @@ public final Optional getTrait(Class traitClass) { */ public final T expectTrait(Class traitClass) { return getTrait(traitClass).orElseThrow( - () -> new ExpectationNotMetException( - String.format( - "Expected shape `%s` to have a trait `%s`", - getId(), - traitClass.getCanonicalName() - ), - this - ) + () -> new ExpectationNotMetException( + String.format( + "Expected shape `%s` to have a trait `%s`", + getId(), + traitClass.getCanonicalName() + ), + this + ) ); } @@ -853,11 +853,11 @@ public boolean equals(Object o) { Shape other = (Shape) o; return getType() == other.getType() - && getId().equals(other.getId()) - && getMemberNames().equals(other.getMemberNames()) - && getAllMembers().equals(other.getAllMembers()) - && getAllTraits().equals(other.getAllTraits()) - && mixins.equals(other.mixins); + && getId().equals(other.getId()) + && getMemberNames().equals(other.getMemberNames()) + && getAllMembers().equals(other.getAllMembers()) + && getAllTraits().equals(other.getAllTraits()) + && mixins.equals(other.mixins); } /** diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ShapeId.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ShapeId.java index 00a0c570ace..c4440bc8c3b 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ShapeId.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ShapeId.java @@ -169,8 +169,8 @@ public static ShapeId fromParts(String namespace, String name, String member) { private static void validateParts(String absoluteId, String namespace, String name, String member) { if (!isValidNamespace(namespace) - || !isValidIdentifier(name) - || (member != null && !isValidIdentifier(member))) { + || !isValidIdentifier(name) + || (member != null && !isValidIdentifier(member))) { throw new ShapeIdSyntaxException("Invalid shape ID: " + absoluteId); } } @@ -417,16 +417,16 @@ private static final class ShapeIdFactory { // A simple LRU cache based on LinkedHashMap, wrapped in a synchronized map. nonPreludeCache = Collections.synchronizedMap( - new LinkedHashMap( - NON_PRELUDE_MAX_SIZE + 1, - 1.0f, - true - ) { - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - return this.size() > NON_PRELUDE_MAX_SIZE; + new LinkedHashMap( + NON_PRELUDE_MAX_SIZE + 1, + 1.0f, + true + ) { + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return this.size() > NON_PRELUDE_MAX_SIZE; + } } - } ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ShapeVisitor.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ShapeVisitor.java index fca81dda11b..6bd59fcd9c8 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ShapeVisitor.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ShapeVisitor.java @@ -199,24 +199,24 @@ abstract class DataShapeVisitor implements ShapeVisitor { @Override public R operationShape(OperationShape shape) { throw new IllegalArgumentException( - "DataShapeVisitor cannot be use to visit " - + "Operation Shapes. Attempted to visit: " + shape + "DataShapeVisitor cannot be use to visit " + + "Operation Shapes. Attempted to visit: " + shape ); } @Override public R resourceShape(ResourceShape shape) { throw new IllegalArgumentException( - "DataShapeVisitor cannot be use to visit " - + "Resource Shapes. Attempted to visit: " + shape + "DataShapeVisitor cannot be use to visit " + + "Resource Shapes. Attempted to visit: " + shape ); } @Override public R serviceShape(ServiceShape shape) { throw new IllegalArgumentException( - "DataShapeVisitor cannot be use to visit " - + "Service Shapes. Attempted to visit: " + shape + "DataShapeVisitor cannot be use to visit " + + "Service Shapes. Attempted to visit: " + shape ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/SmithyIdlComponentOrder.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/SmithyIdlComponentOrder.java index 77b8c0be4bb..eec0ef30b90 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/SmithyIdlComponentOrder.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/SmithyIdlComponentOrder.java @@ -73,7 +73,7 @@ Comparator> metadataComparator() { } private static final class SourceComparator - implements Comparator, Serializable { + implements Comparator, Serializable { @Override public int compare(T a, T b) { SourceLocation left = a.getSourceLocation(); @@ -98,22 +98,22 @@ public int compare(Map.Entry a, Map.Entry b) { */ private static final class PreferredShapeComparator implements Comparator, Serializable { private static final Map PRIORITY = MapUtils.of( - ShapeType.SERVICE, - 0, - ShapeType.RESOURCE, - 1, - ShapeType.OPERATION, - 2, - ShapeType.STRUCTURE, - 3, - ShapeType.UNION, - 4, - ShapeType.LIST, - 5, - ShapeType.SET, - 6, - ShapeType.MAP, - 7 + ShapeType.SERVICE, + 0, + ShapeType.RESOURCE, + 1, + ShapeType.OPERATION, + 2, + ShapeType.STRUCTURE, + 3, + ShapeType.UNION, + 4, + ShapeType.LIST, + 5, + ShapeType.SET, + 6, + ShapeType.MAP, + 7 ); @Override diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/SmithyIdlModelSerializer.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/SmithyIdlModelSerializer.java index 4f6f19629e5..531c706b515 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/SmithyIdlModelSerializer.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/SmithyIdlModelSerializer.java @@ -139,12 +139,12 @@ private SmithyIdlModelSerializer(Builder builder) { */ public Map serialize(Model model) { Map result = model.shapes() - .filter(FunctionalUtils.not(Shape::isMemberShape)) - .filter(shapeFilter) - .collect(Collectors.groupingBy(shapePlacer)) - .entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, entry -> serialize(model, entry.getValue()))); + .filter(FunctionalUtils.not(Shape::isMemberShape)) + .filter(shapeFilter) + .collect(Collectors.groupingBy(shapePlacer)) + .entrySet() + .stream() + .collect(Collectors.toMap(Map.Entry::getKey, entry -> serialize(model, entry.getValue()))); // If there is no metadata, do not create metadata file if (model.getMetadata().isEmpty()) { return result; @@ -157,27 +157,27 @@ public Map serialize(Model model) { } if (result.isEmpty()) { return Collections.singletonMap( - metadataPath, - serializeHeader( - model, - null, - Collections.emptySet(), - inlineInputSuffix, - inlineOutputSuffix, - true - ) + metadataPath, + serializeHeader( + model, + null, + Collections.emptySet(), + inlineInputSuffix, + inlineOutputSuffix, + true + ) ); } else { result.put( - metadataPath, - serializeHeader( - model, - null, - Collections.emptySet(), - inlineInputSuffix, - inlineOutputSuffix, - true - ) + metadataPath, + serializeHeader( + model, + null, + Collections.emptySet(), + inlineInputSuffix, + inlineOutputSuffix, + true + ) ); } return result; @@ -185,8 +185,8 @@ public Map serialize(Model model) { private String serialize(Model fullModel, Collection shapes) { Set namespaces = shapes.stream() - .map(shape -> shape.getId().getNamespace()) - .collect(Collectors.toSet()); + .map(shape -> shape.getId().getNamespace()) + .collect(Collectors.toSet()); if (namespaces.size() != 1) { throw new RuntimeException("All shapes in a single file must share a namespace."); } @@ -198,42 +198,42 @@ private String serialize(Model fullModel, Collection shapes) { Pair inlineSuffixes = determineInlineSuffixes(fullModel, shapes); Set inlineableShapes = getInlineableShapes( - fullModel, - shapes, - inlineSuffixes.getLeft(), - inlineSuffixes.getRight() + fullModel, + shapes, + inlineSuffixes.getLeft(), + inlineSuffixes.getRight() ); ShapeSerializer shapeSerializer = new ShapeSerializer( - codeWriter, - nodeSerializer, - traitFilter, - fullModel, - inlineableShapes, - componentOrder + codeWriter, + nodeSerializer, + traitFilter, + fullModel, + inlineableShapes, + componentOrder ); Comparator comparator = componentOrder.shapeComparator(); shapes.stream() - .filter(FunctionalUtils.not(Shape::isMemberShape)) - .filter(shape -> !inlineableShapes.contains(shape.getId())) - .sorted(comparator) - .forEach(shape -> shape.accept(shapeSerializer)); + .filter(FunctionalUtils.not(Shape::isMemberShape)) + .filter(shape -> !inlineableShapes.contains(shape.getId())) + .sorted(comparator) + .forEach(shape -> shape.accept(shapeSerializer)); String header = serializeHeader( - fullModel, - namespace, - shapes, - inlineSuffixes.getLeft(), - inlineSuffixes.getRight(), - false + fullModel, + namespace, + shapes, + inlineSuffixes.getLeft(), + inlineSuffixes.getRight(), + false ); return header + codeWriter; } private Set getInlineableShapes( - Model fullModel, - Collection shapes, - String inputSuffix, - String outputSuffix + Model fullModel, + Collection shapes, + String inputSuffix, + String outputSuffix ) { OperationIndex operationIndex = OperationIndex.of(fullModel); Set inlineableShapes = new HashSet<>(); @@ -245,14 +245,14 @@ private Set getInlineableShapes( if (!operation.getInputShape().equals(UnitTypeTrait.UNIT)) { Shape inputShape = fullModel.expectShape(operation.getInputShape()); if (shapes.contains(inputShape) && shouldInlineInputShape(operationIndex, inputShape) - && inputShape.getId().getName().equals(operation.getId().getName() + inputSuffix)) { + && inputShape.getId().getName().equals(operation.getId().getName() + inputSuffix)) { inlineableShapes.add(operation.getInputShape()); } } if (!operation.getOutputShape().equals(UnitTypeTrait.UNIT)) { Shape outputShape = fullModel.expectShape(operation.getOutputShape()); if (shapes.contains(outputShape) && shouldInlineOutputShape(operationIndex, outputShape) - && outputShape.getId().getName().equals(operation.getId().getName() + outputSuffix)) { + && outputShape.getId().getName().equals(operation.getId().getName() + outputSuffix)) { inlineableShapes.add(operation.getOutputShape()); } } @@ -263,13 +263,13 @@ private Set getInlineableShapes( private boolean shouldInlineInputShape(OperationIndex operationIndex, Shape target) { // Only allow coercion if the shape is only used as one input. return target.hasTrait(InputTrait.ID) - || (shouldCoerceInlineIo && operationIndex.getInputBindings(target).size() == 1); + || (shouldCoerceInlineIo && operationIndex.getInputBindings(target).size() == 1); } private boolean shouldInlineOutputShape(OperationIndex operationIndex, Shape target) { // Only allow coercion if the shape is only used as one output. return target.hasTrait(OutputTrait.ID) - || (shouldCoerceInlineIo && operationIndex.getOutputBindings(target).size() == 1); + || (shouldCoerceInlineIo && operationIndex.getOutputBindings(target).size() == 1); } private Pair determineInlineSuffixes(Model fullModel, Collection shapes) { @@ -302,25 +302,25 @@ private Pair determineInlineSuffixes(Model fullModel, Collection } String inputSuffix = inputSuffixes.entrySet() - .stream() - .max(Map.Entry.comparingByValue()) - .map(Map.Entry::getKey) - .orElse(inlineInputSuffix); + .stream() + .max(Map.Entry.comparingByValue()) + .map(Map.Entry::getKey) + .orElse(inlineInputSuffix); String outputSuffix = outputSuffixes.entrySet() - .stream() - .max(Map.Entry.comparingByValue()) - .map(Map.Entry::getKey) - .orElse(inlineOutputSuffix); + .stream() + .max(Map.Entry.comparingByValue()) + .map(Map.Entry::getKey) + .orElse(inlineOutputSuffix); return Pair.of(inputSuffix, outputSuffix); } private String serializeHeader( - Model fullModel, - String namespace, - Collection shapes, - String inputSuffix, - String outputSuffix, - boolean addMetadata + Model fullModel, + String namespace, + Collection shapes, + String inputSuffix, + String outputSuffix, + boolean addMetadata ) { SmithyCodeWriter codeWriter = new SmithyCodeWriter(null, fullModel); codeWriter.write("$$version: \"$L\"", Model.MODEL_VERSION); @@ -341,24 +341,24 @@ private String serializeHeader( NodeSerializer nodeSerializer = new NodeSerializer(codeWriter, fullModel); Comparator> comparator = componentOrder.metadataComparator(); fullModel.getMetadata() - .entrySet() - .stream() - .filter(entry -> metadataFilter.test(entry.getKey())) - .sorted(comparator) - .forEach(entry -> { - codeWriter.trimTrailingSpaces(false) - .writeInline("metadata $K = ", entry.getKey()) - .trimTrailingSpaces(); - nodeSerializer.serialize(entry.getValue()); - codeWriter.write(""); - }); + .entrySet() + .stream() + .filter(entry -> metadataFilter.test(entry.getKey())) + .sorted(comparator) + .forEach(entry -> { + codeWriter.trimTrailingSpaces(false) + .writeInline("metadata $K = ", entry.getKey()) + .trimTrailingSpaces(); + nodeSerializer.serialize(entry.getValue()); + codeWriter.write(""); + }); } if (namespace != null) { codeWriter.write("namespace $L", namespace) - .write("") - // We want the extra blank line to separate the header and the model contents. - .trimBlankLines(-1); + .write("") + // We want the extra blank line to separate the header and the model contents. + .trimBlankLines(-1); } return codeWriter.toString(); @@ -568,12 +568,12 @@ private static final class ShapeSerializer extends ShapeVisitor.Default { private final SmithyIdlComponentOrder componentOrder; ShapeSerializer( - SmithyCodeWriter codeWriter, - NodeSerializer nodeSerializer, - Predicate traitFilter, - Model model, - Set inlineableShapes, - SmithyIdlComponentOrder componentOrder + SmithyCodeWriter codeWriter, + NodeSerializer nodeSerializer, + Predicate traitFilter, + Model model, + Set inlineableShapes, + SmithyIdlComponentOrder componentOrder ) { this.codeWriter = codeWriter; this.nodeSerializer = nodeSerializer; @@ -715,31 +715,31 @@ private void serializeTraits(Map traits, TraitFeature... traitFe Comparator traitComparator = componentOrder.toShapeIdComparator(); traits.values() - .stream() - .filter(trait -> noSpecialDocsSyntax || !(trait instanceof DocumentationTrait)) - // The default and enumValue traits are serialized using the assignment syntactic sugar. - .filter(trait -> { - if (trait instanceof EnumValueTrait) { - return false; - } else { - // Default traits are serialized normally for non-members, but omitted for members. - return !isMember || !(trait instanceof DefaultTrait); - } - }) - .filter(traitFilter) - .sorted(traitComparator) - .forEach(this::serializeTrait); + .stream() + .filter(trait -> noSpecialDocsSyntax || !(trait instanceof DocumentationTrait)) + // The default and enumValue traits are serialized using the assignment syntactic sugar. + .filter(trait -> { + if (trait instanceof EnumValueTrait) { + return false; + } else { + // Default traits are serialized normally for non-members, but omitted for members. + return !isMember || !(trait instanceof DefaultTrait); + } + }) + .filter(traitFilter) + .sorted(traitComparator) + .forEach(this::serializeTrait); } private void serializeDocumentation(String documentation) { // The documentation trait has a special syntax, which we always want to use. codeWriter - .pushState() - // See https://github.com/smithy-lang/smithy/issues/2115 - .trimTrailingSpaces(false) - .setNewlinePrefix("/// ") - .write(documentation.replace("$", "$$")) - .popState(); + .pushState() + // See https://github.com/smithy-lang/smithy/issues/2115 + .trimTrailingSpaces(false) + .setNewlinePrefix("/// ") + .write(documentation.replace("$", "$$")) + .popState(); } private void serializeTrait(Trait trait) { @@ -837,16 +837,16 @@ public Void resourceShape(ResourceShape shape) { if (!shape.getIdentifiers().isEmpty()) { codeWriter.openBlock("identifiers: {"); shape.getIdentifiers() - .entrySet() - .stream() - .sorted(Map.Entry.comparingByKey()) - .forEach( - entry -> codeWriter.write( - "$L: $I", - entry.getKey(), - entry.getValue() - ) - ); + .entrySet() + .stream() + .sorted(Map.Entry.comparingByKey()) + .forEach( + entry -> codeWriter.write( + "$L: $I", + entry.getKey(), + entry.getValue() + ) + ); codeWriter.closeBlock("}"); } @@ -1073,8 +1073,8 @@ private void serializeKeyValuePairs(ObjectNode node, Shape shape) { members = Collections.emptyMap(); } else { members = shape.members() - .stream() - .collect(Collectors.toMap(MemberShape::getMemberName, Function.identity())); + .stream() + .collect(Collectors.toMap(MemberShape::getMemberName, Function.identity())); } node.getMembers().forEach((name, value) -> { @@ -1182,11 +1182,11 @@ private boolean conflictsWithLocalNamespace(ShapeId shapeId) { private boolean shouldImport(ShapeId shapeId) { return !conflictsWithLocalNamespace(shapeId) - // It's easier to simply never import something that conflicts with the prelude, because - // if we did then we'd have to somehow handle rewriting all existing references to the - // prelude shape that it conflicts with. - && !conflictsWithPreludeNamespace(shapeId) - && !conflictsWithImports(shapeId); + // It's easier to simply never import something that conflicts with the prelude, because + // if we did then we'd have to somehow handle rewriting all existing references to the + // prelude shape that it conflicts with. + && !conflictsWithPreludeNamespace(shapeId) + && !conflictsWithImports(shapeId); } @@ -1233,9 +1233,9 @@ public String toString() { return contents; } String importString = imports.stream() - .sorted() - .map(shapeId -> String.format("use %s", shapeId.toString())) - .collect(Collectors.joining("\n")); + .sorted() + .map(shapeId -> String.format("use %s", shapeId.toString())) + .collect(Collectors.joining("\n")); return importString + "\n\n" + contents; } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/StructureShape.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/StructureShape.java index c11961d49cd..9de09dfbdbf 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/StructureShape.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/StructureShape.java @@ -18,10 +18,10 @@ public final class StructureShape extends Shape implements ToSmithyBuilder Builder that is building the trait. */ public abstract class AbstractTraitBuilder - implements SmithyBuilder { + implements SmithyBuilder { SourceLocation sourceLocation = SourceLocation.NONE; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/AnnotationTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/AnnotationTrait.java index c0bf0563592..130bb2054f1 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/AnnotationTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/AnnotationTrait.java @@ -85,11 +85,11 @@ public T createTrait(ShapeId id, Node value) { } throw new ExpectationNotMetException( - String.format( - "Annotation traits must be an object or omitted in the IDL, but found %s", - value.getType() - ), - value + String.format( + "Annotation traits must be an object or omitted in the IDL, but found %s", + value.getType() + ), + value ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/AuthDefinitionTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/AuthDefinitionTrait.java index d5e32635ebd..f602b18a013 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/AuthDefinitionTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/AuthDefinitionTrait.java @@ -45,9 +45,9 @@ protected Node createNode() { builder.sourceLocation(getSourceLocation()); if (!traits.isEmpty()) { ArrayNode ids = traits.stream() - .map(ShapeId::toString) - .map(Node::from) - .collect(ArrayNode.collect()); + .map(ShapeId::toString) + .map(Node::from) + .collect(ArrayNode.collect()); builder.withMember("traits", ids); } return builder.build(); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/AuthTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/AuthTrait.java index 488e86c3800..396fcc4b868 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/AuthTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/AuthTrait.java @@ -76,8 +76,8 @@ public Trait createTrait(ShapeId target, Node value) { @Override protected Node createNode() { return getValueSet().stream() - .map(ShapeId::toString) - .map(Node::from) - .collect(ArrayNode.collect(getSourceLocation())); + .map(ShapeId::toString) + .map(Node::from) + .collect(ArrayNode.collect(getSourceLocation())); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/CorsTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/CorsTrait.java index fb3f85e1751..1df3fd813c3 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/CorsTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/CorsTrait.java @@ -55,40 +55,40 @@ public Set getAdditionalExposedHeaders() { @Override public Builder toBuilder() { return builder() - .sourceLocation(getSourceLocation()) - .origin(origin) - .maxAge(maxAge) - .additionalAllowedHeaders(additionalAllowedHeaders) - .additionalExposedHeaders(additionalExposedHeaders); + .sourceLocation(getSourceLocation()) + .origin(origin) + .maxAge(maxAge) + .additionalAllowedHeaders(additionalAllowedHeaders) + .additionalExposedHeaders(additionalExposedHeaders); } @Override protected Node createNode() { return new ObjectNode(MapUtils.of(), getSourceLocation()) - .withOptionalMember( - "origin", - Optional.of(origin) - .filter(val -> !val.equals(DEFAULT_ORIGIN)) - .map(Node::from) - ) - .withOptionalMember( - "maxAge", - Optional.of(maxAge) - .filter(val -> !val.equals(DEFAULT_MAX_AGE)) - .map(Node::from) - ) - .withOptionalMember( - "additionalAllowedHeaders", - Optional.of(additionalAllowedHeaders) - .filter(FunctionalUtils.not(Set::isEmpty)) - .map(Node::fromStrings) - ) - .withOptionalMember( - "additionalExposedHeaders", - Optional.of(additionalExposedHeaders) - .filter(FunctionalUtils.not(Set::isEmpty)) - .map(Node::fromStrings) - ); + .withOptionalMember( + "origin", + Optional.of(origin) + .filter(val -> !val.equals(DEFAULT_ORIGIN)) + .map(Node::from) + ) + .withOptionalMember( + "maxAge", + Optional.of(maxAge) + .filter(val -> !val.equals(DEFAULT_MAX_AGE)) + .map(Node::from) + ) + .withOptionalMember( + "additionalAllowedHeaders", + Optional.of(additionalAllowedHeaders) + .filter(FunctionalUtils.not(Set::isEmpty)) + .map(Node::fromStrings) + ) + .withOptionalMember( + "additionalExposedHeaders", + Optional.of(additionalExposedHeaders) + .filter(FunctionalUtils.not(Set::isEmpty)) + .map(Node::fromStrings) + ); } // Avoid inconsequential equality issues due to empty vs not empty sets. @@ -101,9 +101,9 @@ public boolean equals(Object other) { } else { CorsTrait trait = (CorsTrait) other; return origin.equals(trait.origin) - && maxAge == trait.maxAge - && additionalAllowedHeaders.equals(trait.additionalAllowedHeaders) - && additionalExposedHeaders.equals(trait.additionalExposedHeaders); + && maxAge == trait.maxAge + && additionalAllowedHeaders.equals(trait.additionalAllowedHeaders) + && additionalExposedHeaders.equals(trait.additionalExposedHeaders); } } @@ -161,18 +161,18 @@ public ShapeId getShapeId() { public CorsTrait createTrait(ShapeId target, Node value) { Builder builder = builder().sourceLocation(value); value.expectObjectNode() - .getStringMember("origin", builder::origin) - .getNumberMember("maxAge", n -> builder.maxAge(n.intValue())) - .getMember( - "additionalAllowedHeaders", - Node::expectArrayNode, - a -> builder.additionalAllowedHeaders(stringSetFromNode(a)) - ) - .getMember( - "additionalExposedHeaders", - Node::expectArrayNode, - a -> builder.additionalExposedHeaders(stringSetFromNode(a)) - ); + .getStringMember("origin", builder::origin) + .getNumberMember("maxAge", n -> builder.maxAge(n.intValue())) + .getMember( + "additionalAllowedHeaders", + Node::expectArrayNode, + a -> builder.additionalAllowedHeaders(stringSetFromNode(a)) + ) + .getMember( + "additionalExposedHeaders", + Node::expectArrayNode, + a -> builder.additionalExposedHeaders(stringSetFromNode(a)) + ); CorsTrait result = builder.build(); result.setNodeCache(value); return result; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/DeprecatedTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/DeprecatedTrait.java index 93bc0fdc1c8..476a125a577 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/DeprecatedTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/DeprecatedTrait.java @@ -36,8 +36,8 @@ public Provider() { public Trait createTrait(ShapeId target, Node value) { DeprecatedTrait.Builder builder = builder().sourceLocation(value); value.expectObjectNode() - .getStringMember("since", builder::since) - .getStringMember("message", builder::message); + .getStringMember("since", builder::since) + .getStringMember("message", builder::message); DeprecatedTrait result = builder.build(); result.setNodeCache(value); return result; @@ -79,8 +79,8 @@ public String getDeprecatedDescription(ShapeType shapeType) { @Override protected Node createNode() { return new ObjectNode(MapUtils.of(), getSourceLocation()) - .withOptionalMember("since", getSince().map(Node::from)) - .withOptionalMember("message", getMessage().map(Node::from)); + .withOptionalMember("since", getSince().map(Node::from)) + .withOptionalMember("message", getMessage().map(Node::from)); } @Override diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/EffectiveTraitQuery.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/EffectiveTraitQuery.java index 3d2534eaacb..6eb41b370d1 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/EffectiveTraitQuery.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/EffectiveTraitQuery.java @@ -65,9 +65,9 @@ public static Builder builder() { @Override public Builder toBuilder() { return builder() - .model(model) - .traitClass(traitClass) - .inheritFromContainer(inheritFromContainer); + .model(model) + .traitClass(traitClass) + .inheritFromContainer(inheritFromContainer); } /** diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/EndpointTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/EndpointTrait.java index 4d40dd5e0c9..31917cd79af 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/EndpointTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/EndpointTrait.java @@ -39,7 +39,7 @@ private EndpointTrait(Builder builder) { if (token.equals("{")) { if (!segments.isEmpty() && segments.get(segments.size() - 1).isLabel()) { throw new InvalidPatternException( - format("Host labels must not be adjacent in a pattern. Found %s", hostPrefix) + format("Host labels must not be adjacent in a pattern. Found %s", hostPrefix) ); } // If we found a label, grab the content and the close brace @@ -58,10 +58,10 @@ private EndpointTrait(Builder builder) { } this.hostPrefix = SmithyPattern.builder() - .allowsGreedyLabels(false) - .segments(segments) - .pattern(hostPrefix) - .build(); + .allowsGreedyLabels(false) + .segments(segments) + .pattern(hostPrefix) + .build(); } public static final class Provider extends AbstractTrait.Provider { @@ -98,7 +98,7 @@ public Builder toBuilder() { @Override protected Node createNode() { return new ObjectNode(Collections.emptyMap(), getSourceLocation()) - .withMember("hostPrefix", Node.from(hostPrefix.toString())); + .withMember("hostPrefix", Node.from(hostPrefix.toString())); } public static final class Builder extends AbstractTraitBuilder { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/EnumDefinition.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/EnumDefinition.java index a8d9b1cf7db..7624cd79af2 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/EnumDefinition.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/EnumDefinition.java @@ -60,8 +60,8 @@ public boolean isDeprecated() { public Node toNode() { ObjectNode.Builder builder = Node.objectNodeBuilder(); builder.withMember("value", getValue()) - .withOptionalMember("name", getName().map(Node::from)) - .withOptionalMember("documentation", getDocumentation().map(Node::from)); + .withOptionalMember("name", getName().map(Node::from)) + .withOptionalMember("documentation", getDocumentation().map(Node::from)); if (!tags.isEmpty()) { builder.withMember("tags", Node.fromStrings(getTags())); @@ -77,11 +77,11 @@ public Node toNode() { public static EnumDefinition fromNode(Node node) { EnumDefinition.Builder builder = EnumDefinition.builder(); node.expectObjectNode() - .expectStringMember("value", builder::value) - .getStringMember("name", builder::name) - .getStringMember("documentation", builder::documentation) - .getBooleanMember("deprecated", builder::deprecated) - .getArrayMember("tags", StringNode::getValue, builder::tags); + .expectStringMember("value", builder::value) + .getStringMember("name", builder::name) + .getStringMember("documentation", builder::documentation) + .getBooleanMember("deprecated", builder::deprecated) + .getArrayMember("tags", StringNode::getValue, builder::tags); return builder.build(); } @@ -93,11 +93,11 @@ public List getTags() { @Override public Builder toBuilder() { return builder() - .name(name) - .value(value) - .tags(tags) - .documentation(documentation) - .deprecated(deprecated); + .name(name) + .value(value) + .tags(tags) + .documentation(documentation) + .deprecated(deprecated); } @Override @@ -108,10 +108,10 @@ public boolean equals(Object other) { EnumDefinition otherEnum = (EnumDefinition) other; return value.equals(otherEnum.value) - && Objects.equals(name, otherEnum.name) - && Objects.equals(documentation, otherEnum.documentation) - && tags.equals(otherEnum.tags) - && deprecated == otherEnum.deprecated; + && Objects.equals(name, otherEnum.name) + && Objects.equals(documentation, otherEnum.documentation) + && tags.equals(otherEnum.tags) + && deprecated == otherEnum.deprecated; } @Override diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/EnumValueTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/EnumValueTrait.java index 1b74384ecef..7c94bbf1c30 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/EnumValueTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/EnumValueTrait.java @@ -45,10 +45,10 @@ public Optional getStringValue() { */ public String expectStringValue() { return getStringValue().orElseThrow( - () -> new ExpectationNotMetException( - "Expected string value was not set.", - this - ) + () -> new ExpectationNotMetException( + "Expected string value was not set.", + this + ) ); } @@ -69,10 +69,10 @@ public Optional getIntValue() { */ public int expectIntValue() { return getIntValue().orElseThrow( - () -> new ExpectationNotMetException( - "Expected integer value was not set.", - this - ) + () -> new ExpectationNotMetException( + "Expected integer value was not set.", + this + ) ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/ErrorTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/ErrorTrait.java index 186b9289b02..38b1a43b92d 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/ErrorTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/ErrorTrait.java @@ -19,11 +19,11 @@ public ErrorTrait(String value, SourceLocation sourceLocation) { if (!isClientError() && !isServerError()) { throw new SourceException( - String.format( - "error trait must be set to client or server, found `%s`", - getValue() - ), - sourceLocation + String.format( + "error trait must be set to client or server, found `%s`", + getValue() + ), + sourceLocation ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/ExamplesTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/ExamplesTrait.java index 24a94c6ef4e..f777b8369d6 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/ExamplesTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/ExamplesTrait.java @@ -163,9 +163,9 @@ public boolean getAllowConstraintErrors() { @Override public Node toNode() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withMember("title", Node.from(title)) - .withOptionalMember("documentation", getDocumentation().map(Node::from)) - .withOptionalMember("error", getError().map(ErrorExample::toNode)); + .withMember("title", Node.from(title)) + .withOptionalMember("documentation", getDocumentation().map(Node::from)) + .withOptionalMember("error", getError().map(ErrorExample::toNode)); if (!input.isEmpty()) { builder.withMember("input", input); @@ -191,8 +191,8 @@ public boolean equals(Object o) { } Example example = (Example) o; return allowConstraintErrors == example.allowConstraintErrors && Objects.equals(title, example.title) - && Objects.equals(documentation, example.documentation) && Objects.equals(input, example.input) - && Objects.equals(output, example.output) && Objects.equals(error, example.error); + && Objects.equals(documentation, example.documentation) && Objects.equals(input, example.input) + && Objects.equals(output, example.output) && Objects.equals(error, example.error); } @Override @@ -203,11 +203,11 @@ public int hashCode() { @Override public Builder toBuilder() { return new Builder().documentation(documentation) - .title(title) - .input(input) - .output(output) - .error(error) - .allowConstraintErrors(allowConstraintErrors); + .title(title) + .input(input) + .output(output) + .error(error) + .allowConstraintErrors(allowConstraintErrors); } public static Builder builder() { @@ -274,8 +274,8 @@ public ErrorExample(Builder builder) { public static ErrorExample fromNode(Node node) { ErrorExample.Builder builder = builder(); node.expectObjectNode() - .expectMember("shapeId", ShapeId::fromNode, builder::shapeId) - .expectObjectMember("content", builder::content); + .expectMember("shapeId", ShapeId::fromNode, builder::shapeId) + .expectObjectMember("content", builder::content); return builder.build(); } @@ -296,9 +296,9 @@ public ObjectNode getContent() { @Override public Node toNode() { return ObjectNode.objectNodeBuilder() - .withMember("shapeId", shapeId.toString()) - .withMember("content", content) - .build(); + .withMember("shapeId", shapeId.toString()) + .withMember("content", content) + .build(); } @Override @@ -365,12 +365,12 @@ public ExamplesTrait createTrait(ShapeId target, Node value) { private static Example exampleFromNode(ObjectNode node) { Example.Builder builder = Example.builder(); node.expectObjectNode() - .getStringMember("title", builder::title) - .getStringMember("documentation", builder::documentation) - .getObjectMember("input", builder::input) - .getObjectMember("output", builder::output) - .getMember("error", ErrorExample::fromNode, builder::error) - .getBooleanMember("allowConstraintErrors", builder::allowConstraintErrors); + .getStringMember("title", builder::title) + .getStringMember("documentation", builder::documentation) + .getObjectMember("input", builder::input) + .getObjectMember("output", builder::output) + .getMember("error", ErrorExample::fromNode, builder::error) + .getBooleanMember("allowConstraintErrors", builder::allowConstraintErrors); return builder.build(); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/ExternalDocumentationTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/ExternalDocumentationTrait.java index 844873aa80b..c3a1dbdd046 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/ExternalDocumentationTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/ExternalDocumentationTrait.java @@ -21,7 +21,7 @@ * Provides named links to external documentation. */ public final class ExternalDocumentationTrait extends AbstractTrait - implements ToSmithyBuilder { + implements ToSmithyBuilder { public static final ShapeId ID = ShapeId.from("smithy.api#externalDocumentation"); @@ -40,13 +40,13 @@ private static String validateUrl(String name, String url, SourceLocation locati return url; } catch (MalformedURLException e) { throw new SourceException( - String.format( - "Each externalDocumentation value must be a valid URL. " - + "Found \"%s\" for name \"%s\"", - url, - name - ), - location + String.format( + "Each externalDocumentation value must be a valid URL. " + + "Found \"%s\" for name \"%s\"", + url, + name + ), + location ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/HttpApiKeyAuthTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/HttpApiKeyAuthTrait.java index ac544d4f18b..355cf98c1fd 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/HttpApiKeyAuthTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/HttpApiKeyAuthTrait.java @@ -45,19 +45,19 @@ public Location getIn() { @Override public Builder toBuilder() { return builder() - .sourceLocation(getSourceLocation()) - .scheme(getScheme().orElse(null)) - .name(getName()) - .in(getIn()); + .sourceLocation(getSourceLocation()) + .scheme(getScheme().orElse(null)) + .name(getName()) + .in(getIn()); } @Override protected Node createNode() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withMember("name", getName()) - .withMember("in", getIn().toString()) - .withOptionalMember("scheme", getScheme().map(Node::from)); + .sourceLocation(getSourceLocation()) + .withMember("name", getName()) + .withMember("in", getIn().toString()) + .withOptionalMember("scheme", getScheme().map(Node::from)); return builder.build(); } @@ -99,9 +99,9 @@ public Provider() { public Trait createTrait(ShapeId target, Node value) { Builder builder = builder().sourceLocation(value.getSourceLocation()); value.expectObjectNode() - .getStringMember("scheme", builder::scheme) - .expectStringMember("name", builder::name) - .getStringMember("in", s -> builder.in(Location.from(s))); + .getStringMember("scheme", builder::scheme) + .expectStringMember("name", builder::name) + .getStringMember("in", s -> builder.in(Location.from(s))); HttpApiKeyAuthTrait result = builder.build(); result.setNodeCache(value); return result; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/HttpTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/HttpTrait.java index 7f7334124c9..a282375bec6 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/HttpTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/HttpTrait.java @@ -36,9 +36,9 @@ public Provider() { public Trait createTrait(ShapeId target, Node value) { HttpTrait.Builder builder = builder().sourceLocation(value); value.expectObjectNode() - .expectStringMember("uri", s -> builder.uri(UriPattern.parse(s))) - .expectStringMember("method", builder::method) - .getNumberMember("code", n -> builder.code(n.intValue())); + .expectStringMember("uri", s -> builder.uri(UriPattern.parse(s))) + .expectStringMember("method", builder::method) + .getNumberMember("code", n -> builder.code(n.intValue())); HttpTrait result = builder.build(); result.setNodeCache(value); return result; @@ -60,11 +60,11 @@ public int getCode() { @Override protected Node createNode() { return Node.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withMember("method", Node.from(method)) - .withMember("uri", Node.from(uri.toString())) - .withMember("code", Node.from(code)) - .build(); + .sourceLocation(getSourceLocation()) + .withMember("method", Node.from(method)) + .withMember("uri", Node.from(uri.toString())) + .withMember("code", Node.from(code)) + .build(); } /** @@ -89,8 +89,8 @@ public boolean equals(Object other) { } else { HttpTrait trait = (HttpTrait) other; return method.equals(trait.method) - && uri.equals(trait.uri) - && code == trait.code; + && uri.equals(trait.uri) + && code == trait.code; } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/IdRefTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/IdRefTrait.java index 9ad30790656..35d80848dff 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/IdRefTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/IdRefTrait.java @@ -54,20 +54,20 @@ public Optional getErrorMessage() { @Override public Builder toBuilder() { return builder().sourceLocation(getSourceLocation()) - .failWhenMissing(failWhenMissing) - .selector(selector) - .errorMessage(errorMessage); + .failWhenMissing(failWhenMissing) + .selector(selector) + .errorMessage(errorMessage); } @Override protected Node createNode() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withOptionalMember( - "selector", - Optional.ofNullable(selector).map(Selector::toString).map(Node::from) - ) - .withOptionalMember("errorMessage", getErrorMessage().map(Node::from)); + .sourceLocation(getSourceLocation()) + .withOptionalMember( + "selector", + Optional.ofNullable(selector).map(Selector::toString).map(Node::from) + ) + .withOptionalMember("errorMessage", getErrorMessage().map(Node::from)); if (failWhenMissing) { builder = builder.withMember("failWhenMissing", Node.from(true)); } @@ -116,9 +116,9 @@ public ShapeId getShapeId() { public IdRefTrait createTrait(ShapeId target, Node value) { Builder builder = builder().sourceLocation(value); value.expectObjectNode() - .getMember("selector", Selector::fromNode, builder::selector) - .getBooleanMember("failWhenMissing", builder::failWhenMissing) - .getStringMember("errorMessage", builder::errorMessage); + .getMember("selector", Selector::fromNode, builder::selector) + .getBooleanMember("failWhenMissing", builder::failWhenMissing) + .getStringMember("errorMessage", builder::errorMessage); IdRefTrait result = builder.build(); result.setNodeCache(value); return result; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/LengthTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/LengthTrait.java index 35f20cc63ee..f79d4bac477 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/LengthTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/LengthTrait.java @@ -51,8 +51,8 @@ public Optional getMax() { @Override protected Node createNode() { return new ObjectNode(MapUtils.of(), getSourceLocation()) - .withOptionalMember("min", getMin().map(Node::from)) - .withOptionalMember("max", getMax().map(Node::from)); + .withOptionalMember("min", getMin().map(Node::from)) + .withOptionalMember("max", getMax().map(Node::from)); } @Override @@ -100,8 +100,8 @@ public ShapeId getShapeId() { public LengthTrait createTrait(ShapeId target, Node value) { LengthTrait.Builder builder = builder().sourceLocation(value.getSourceLocation()); value.expectObjectNode() - .getNumberMember("min", n -> builder.min(n.longValue())) - .getNumberMember("max", n -> builder.max(n.longValue())); + .getNumberMember("min", n -> builder.min(n.longValue())) + .getNumberMember("max", n -> builder.max(n.longValue())); LengthTrait result = builder.build(); result.setNodeCache(value); return result; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/MixinTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/MixinTrait.java index a9da3f67c28..aad516feb10 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/MixinTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/MixinTrait.java @@ -50,16 +50,16 @@ protected Node createNode() { } return Node.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withMember("localTraits", Node.fromNodes(nonImplicitValues)) - .build(); + .sourceLocation(getSourceLocation()) + .withMember("localTraits", Node.fromNodes(nonImplicitValues)) + .build(); } @Override public Builder toBuilder() { return builder() - .sourceLocation(getSourceLocation()) - .localTraits(localTraits); + .sourceLocation(getSourceLocation()) + .localTraits(localTraits); } /** diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/PaginatedTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/PaginatedTrait.java index e80c2bc16c9..2c376a8c7d3 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/PaginatedTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/PaginatedTrait.java @@ -86,9 +86,9 @@ public Optional getPageSize() { */ @Deprecated public static Optional resolvePath( - String path, - Model model, - StructureShape shape + String path, + Model model, + StructureShape shape ) { List memberShapes = resolveFullPath(path, model, shape); if (memberShapes.size() == 0) { @@ -111,9 +111,9 @@ public static Optional resolvePath( * as an empty list. */ public static List resolveFullPath( - String path, - Model model, - StructureShape shape + String path, + Model model, + StructureShape shape ) { List memberShapes = new ArrayList<>(); @@ -127,7 +127,7 @@ public static List resolveFullPath( } memberShapes.add(memberShape.get()); container = model.getShape(memberShape.get().getTarget()) - .flatMap(Shape::asStructureShape); + .flatMap(Shape::asStructureShape); } return memberShapes; } @@ -150,31 +150,31 @@ public PaginatedTrait merge(PaginatedTrait other) { } return builder() - .inputToken(inputToken != null ? inputToken : other.inputToken) - .outputToken(outputToken != null ? outputToken : other.outputToken) - .pageSize(pageSize != null ? pageSize : other.pageSize) - .items(items != null ? items : other.items) - .sourceLocation(getSourceLocation()) - .build(); + .inputToken(inputToken != null ? inputToken : other.inputToken) + .outputToken(outputToken != null ? outputToken : other.outputToken) + .pageSize(pageSize != null ? pageSize : other.pageSize) + .items(items != null ? items : other.items) + .sourceLocation(getSourceLocation()) + .build(); } @Override protected Node createNode() { return new ObjectNode(MapUtils.of(), getSourceLocation()) - .withOptionalMember("inputToken", getInputToken().map(Node::from)) - .withOptionalMember("outputToken", getOutputToken().map(Node::from)) - .withOptionalMember("items", getItems().map(Node::from)) - .withOptionalMember("pageSize", getPageSize().map(Node::from)); + .withOptionalMember("inputToken", getInputToken().map(Node::from)) + .withOptionalMember("outputToken", getOutputToken().map(Node::from)) + .withOptionalMember("items", getItems().map(Node::from)) + .withOptionalMember("pageSize", getPageSize().map(Node::from)); } @Override public Builder toBuilder() { return builder() - .sourceLocation(getSourceLocation()) - .items(items) - .inputToken(inputToken) - .outputToken(outputToken) - .pageSize(pageSize); + .sourceLocation(getSourceLocation()) + .items(items) + .inputToken(inputToken) + .outputToken(outputToken) + .pageSize(pageSize); } /** @@ -229,10 +229,10 @@ public ShapeId getShapeId() { public PaginatedTrait createTrait(ShapeId target, Node value) { Builder builder = builder().sourceLocation(value); value.expectObjectNode() - .getStringMember("pageSize", builder::pageSize) - .getStringMember("items", builder::items) - .getStringMember("inputToken", builder::inputToken) - .getStringMember("outputToken", builder::outputToken); + .getStringMember("pageSize", builder::pageSize) + .getStringMember("items", builder::items) + .getStringMember("inputToken", builder::inputToken) + .getStringMember("outputToken", builder::outputToken); PaginatedTrait result = builder.build(); result.setNodeCache(value); return result; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/PatternTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/PatternTrait.java index 78d2e547312..a3bdfa60878 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/PatternTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/PatternTrait.java @@ -48,8 +48,8 @@ private static Pattern compilePattern(String value, FromSourceLocation sourceLoc return Pattern.compile(value); } catch (PatternSyntaxException e) { throw new SourceException( - "Invalid pattern trait regular expression: `" + value + "`. " + e.getMessage(), - sourceLocation + "Invalid pattern trait regular expression: `" + value + "`. " + e.getMessage(), + sourceLocation ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/PropertyTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/PropertyTrait.java index 9f5b787fadf..ede81a0de23 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/PropertyTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/PropertyTrait.java @@ -28,9 +28,9 @@ public Optional getName() { @Override protected Node createNode() { return Node.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withOptionalMember("name", getName().map(Node::from)) - .build(); + .sourceLocation(getSourceLocation()) + .withOptionalMember("name", getName().map(Node::from)) + .build(); } public static Builder builder() { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/ProtocolDefinitionTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/ProtocolDefinitionTrait.java index b72e5c2c201..0574bf2ba43 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/ProtocolDefinitionTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/ProtocolDefinitionTrait.java @@ -57,9 +57,9 @@ protected Node createNode() { builder.sourceLocation(getSourceLocation()); if (!traits.isEmpty()) { ArrayNode ids = traits.stream() - .map(ShapeId::toString) - .map(Node::from) - .collect(ArrayNode.collect()); + .map(ShapeId::toString) + .map(Node::from) + .collect(ArrayNode.collect()); builder.withMember("traits", ids); if (noInlineDocumentSupport) { @@ -72,9 +72,9 @@ protected Node createNode() { @Override public Builder toBuilder() { return builder() - .sourceLocation(getSourceLocation()) - .traits(traits) - .noInlineDocumentSupport(noInlineDocumentSupport); + .sourceLocation(getSourceLocation()) + .traits(traits) + .noInlineDocumentSupport(noInlineDocumentSupport); } public static final class Provider extends AbstractTrait.Provider { @@ -86,8 +86,8 @@ public Provider() { public ProtocolDefinitionTrait createTrait(ShapeId target, Node value) { Builder builder = builder().sourceLocation(value); value.expectObjectNode() - .getArrayMember("traits", ShapeId::fromNode, builder::traits) - .getBooleanMember("noInlineDocumentSupport", builder::noInlineDocumentSupport); + .getArrayMember("traits", ShapeId::fromNode, builder::traits) + .getBooleanMember("noInlineDocumentSupport", builder::noInlineDocumentSupport); ProtocolDefinitionTrait result = builder.build(); result.setNodeCache(value); return result; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/RangeTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/RangeTrait.java index a66e6180dbb..fe703441b08 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/RangeTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/RangeTrait.java @@ -52,8 +52,8 @@ public Optional getMax() { @Override protected Node createNode() { return new ObjectNode(MapUtils.of(), getSourceLocation()) - .withOptionalMember("min", getMin().map(Node::from)) - .withOptionalMember("max", getMax().map(Node::from)); + .withOptionalMember("min", getMin().map(Node::from)) + .withOptionalMember("max", getMax().map(Node::from)); } @Override @@ -101,8 +101,8 @@ public ShapeId getShapeId() { public RangeTrait createTrait(ShapeId target, Node value) { Builder builder = builder().sourceLocation(value.getSourceLocation()); value.expectObjectNode() - .getMember("min", Provider::convertToBigDecimal, builder::min) - .getMember("max", Provider::convertToBigDecimal, builder::max); + .getMember("min", Provider::convertToBigDecimal, builder::min) + .getMember("max", Provider::convertToBigDecimal, builder::max); RangeTrait result = builder.build(); result.setNodeCache(value); return result; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/RecommendedTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/RecommendedTrait.java index 48855aa5f68..2b9351cb411 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/RecommendedTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/RecommendedTrait.java @@ -33,7 +33,7 @@ public Optional getReason() { @Override protected Node createNode() { return new ObjectNode(MapUtils.of(), getSourceLocation()) - .withOptionalMember("reason", getReason().map(Node::from)); + .withOptionalMember("reason", getReason().map(Node::from)); } @Override diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/ReferencesTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/ReferencesTrait.java index b914611950a..f63c7dbbc88 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/ReferencesTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/ReferencesTrait.java @@ -57,8 +57,8 @@ public List getReferences() { */ public List getResourceReferences(ShapeId shapeId) { return getReferences().stream() - .filter(reference -> reference.getResource().equals(shapeId)) - .collect(Collectors.toList()); + .filter(reference -> reference.getResource().equals(shapeId)) + .collect(Collectors.toList()); } @Override @@ -198,9 +198,9 @@ public boolean equals(Object o) { Reference reference = (Reference) o; return resource.equals(reference.resource) - && Objects.equals(ids, reference.ids) - && Objects.equals(service, reference.service) - && Objects.equals(rel, reference.rel); + && Objects.equals(ids, reference.ids) + && Objects.equals(service, reference.service) + && Objects.equals(rel, reference.rel); } @Override @@ -211,16 +211,16 @@ public int hashCode() { @Override public Node toNode() { return Node.objectNodeBuilder() - .withMember("resource", Node.from(resource.toString())) - .withOptionalMember( - "ids", - ids.isEmpty() - ? Optional.empty() - : Optional.of(ObjectNode.fromStringMap(getIds())) - ) - .withOptionalMember("service", getService().map(ShapeId::toString).map(Node::from)) - .withOptionalMember("rel", getRel().map(Node::from)) - .build(); + .withMember("resource", Node.from(resource.toString())) + .withOptionalMember( + "ids", + ids.isEmpty() + ? Optional.empty() + : Optional.of(ObjectNode.fromStringMap(getIds())) + ) + .withOptionalMember("service", getService().map(ShapeId::toString).map(Node::from)) + .withOptionalMember("rel", getRel().map(Node::from)) + .build(); } /** @@ -282,16 +282,16 @@ public ReferencesTrait createTrait(ShapeId target, Node value) { private static Reference referenceFromNode(ObjectNode referenceProperties) { Reference.Builder builder = Reference.builder(); referenceProperties.expectObjectNode() - .expectMember("resource", ShapeId::fromNode, builder::resource) - .getObjectMember("ids", object -> { - Map result = new LinkedHashMap<>(object.size()); - object.getStringMap().forEach((k, v) -> { - result.put(k, v.expectStringNode().getValue()); - }); - builder.ids(result); - }) - .getMember("service", ShapeId::fromNode, builder::service) - .getStringMember("rel", builder::rel); + .expectMember("resource", ShapeId::fromNode, builder::resource) + .getObjectMember("ids", object -> { + Map result = new LinkedHashMap<>(object.size()); + object.getStringMap().forEach((k, v) -> { + result.put(k, v.expectStringNode().getValue()); + }); + builder.ids(result); + }) + .getMember("service", ShapeId::fromNode, builder::service) + .getStringMember("rel", builder::rel); return builder.build(); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/RequestCompressionTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/RequestCompressionTrait.java index 8a3d62c05d5..d736ee94ab2 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/RequestCompressionTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/RequestCompressionTrait.java @@ -23,13 +23,13 @@ public final class RequestCompressionTrait extends AbstractTrait implements ToSm * Set of supported compression algorithm encoding values. */ public static final Set SUPPORTED_COMPRESSION_ALGORITHMS = SetUtils.of( - // NOTE: When a new encoding is supported, add the encoding to - // `multiple-encodings.smithy` - // TODO: When the next encoding value after "gzip" is added, remove the - // duplicate "gzip" value in `multiple-encodings.smithy`. Also, add - // validation to make sure encoding values are unique. Then remove - // this TODO item. - "gzip" + // NOTE: When a new encoding is supported, add the encoding to + // `multiple-encodings.smithy` + // TODO: When the next encoding value after "gzip" is added, remove the + // duplicate "gzip" value in `multiple-encodings.smithy`. Also, add + // validation to make sure encoding values are unique. Then remove + // this TODO item. + "gzip" ); public static final String ENCODINGS = "encodings"; @@ -64,9 +64,9 @@ public Trait createTrait(ShapeId target, Node value) { @Override protected Node createNode() { return ObjectNode.objectNodeBuilder() - .sourceLocation(getSourceLocation()) - .withMember(ENCODINGS, Node.fromStrings(getEncodings())) - .build(); + .sourceLocation(getSourceLocation()) + .withMember(ENCODINGS, Node.fromStrings(getEncodings())) + .build(); } public static Builder builder() { @@ -76,12 +76,12 @@ public static Builder builder() { @Override public Builder toBuilder() { return new Builder() - .sourceLocation(getSourceLocation()) - .encodings(encodings); + .sourceLocation(getSourceLocation()) + .encodings(encodings); } public static final class Builder - extends AbstractTraitBuilder { + extends AbstractTraitBuilder { private final BuilderRef> encodings = BuilderRef.forList(); private Builder() {} diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/StringListTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/StringListTrait.java index 10235d0a281..6b6a3260a45 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/StringListTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/StringListTrait.java @@ -70,7 +70,7 @@ public final List getValues() { * Abstract builder to build a StringList trait. */ public abstract static class Builder - extends AbstractTraitBuilder { + extends AbstractTraitBuilder { private final BuilderRef> values = BuilderRef.forList(); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/Trait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/Trait.java index c7bd7c18343..f1cbd437e11 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/Trait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/Trait.java @@ -82,8 +82,8 @@ default boolean isSynthetic() { */ @Deprecated static Stream> flatMapStream( - S shape, - Class traitClass + S shape, + Class traitClass ) { return OptionalUtils.stream(shape.getTrait(traitClass).map(t -> Pair.of(shape, t))); } @@ -97,8 +97,8 @@ static Stream> flatMapStream( */ static String getIdiomaticTraitName(String traitName) { return traitName.startsWith("smithy.api#") - ? traitName.substring("smithy.api#".length()) - : traitName; + ? traitName.substring("smithy.api#".length()) + : traitName; } /** diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/TraitDefinition.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/TraitDefinition.java index 075e06f7198..a3edae167cc 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/TraitDefinition.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/TraitDefinition.java @@ -48,10 +48,10 @@ public Node toNode() { public static StructurallyExclusive fromNode(Node node) { String value = node.expectStringNode() - .expectOneOf( - StructurallyExclusive.MEMBER.toString(), - StructurallyExclusive.TARGET.toString() - ); + .expectOneOf( + StructurallyExclusive.MEMBER.toString(), + StructurallyExclusive.TARGET.toString() + ); return StructurallyExclusive.valueOf(value.toUpperCase(Locale.ENGLISH)); } } @@ -106,9 +106,9 @@ public boolean equals(Object obj) { if (obj instanceof BreakingChangeRule) { BreakingChangeRule other = (BreakingChangeRule) obj; return Objects.equals(path, other.path) - && Objects.equals(severity, other.severity) - && Objects.equals(message, other.message) - && change == other.change; + && Objects.equals(severity, other.severity) + && Objects.equals(message, other.message) + && change == other.change; } else { return false; } @@ -122,11 +122,11 @@ public String toString() { @Override public Node toNode() { return Node.objectNodeBuilder() - .withOptionalMember("path", getPath().map(NodePointer::toString).map(Node::from)) - .withOptionalMember("severity", getSeverity().map(Severity::toNode)) - .withMember("change", change.toNode()) - .withOptionalMember("message", getMessage().map(Node::from)) - .build(); + .withOptionalMember("path", getPath().map(NodePointer::toString).map(Node::from)) + .withOptionalMember("severity", getSeverity().map(Severity::toNode)) + .withMember("change", change.toNode()) + .withOptionalMember("message", getMessage().map(Node::from)) + .build(); } /** @@ -213,10 +213,10 @@ public static Builder builder() { @Override public Builder toBuilder() { Builder builder = builder() - .sourceLocation(getSourceLocation()) - .selector(selector) - .structurallyExclusive(structurallyExclusive) - .breakingChanges(breakingChanges); + .sourceLocation(getSourceLocation()) + .selector(selector) + .structurallyExclusive(structurallyExclusive) + .breakingChanges(breakingChanges); conflicts.forEach(builder::addConflict); return builder; } @@ -279,17 +279,17 @@ protected Node createNode() { if (!conflicts.isEmpty()) { builder.withMember( - "conflicts", - conflicts.stream() - .map(ShapeId::toString) - .map(Node::from) - .collect(ArrayNode.collect()) + "conflicts", + conflicts.stream() + .map(ShapeId::toString) + .map(Node::from) + .collect(ArrayNode.collect()) ); } builder.withOptionalMember( - "structurallyExclusive", - getStructurallyExclusive().map(StructurallyExclusive::toNode) + "structurallyExclusive", + getStructurallyExclusive().map(StructurallyExclusive::toNode) ); if (!breakingChanges.isEmpty()) { @@ -311,9 +311,9 @@ public boolean equals(Object other) { } else { TraitDefinition od = (TraitDefinition) other; return selector.equals(od.selector) - && conflicts.equals(od.conflicts) - && Objects.equals(structurallyExclusive, od.structurallyExclusive) - && breakingChanges.equals(od.breakingChanges); + && conflicts.equals(od.conflicts) + && Objects.equals(structurallyExclusive, od.structurallyExclusive) + && breakingChanges.equals(od.breakingChanges); } } @@ -394,14 +394,14 @@ public TraitDefinition createTrait(ShapeId target, Node value) { ObjectNode members = value.isNullNode() ? Node.objectNode() : value.expectObjectNode(); Builder builder = builder().sourceLocation(value); members.expectObjectNode() - .getMember("selector", Selector::fromNode, builder::selector) - .getMember("structurallyExclusive", StructurallyExclusive::fromNode, builder::structurallyExclusive) - .getArrayMember("conflicts", nodes -> { - for (Node element : nodes) { - builder.addConflict(element.expectStringNode().getValue()); - } - }) - .getArrayMember("breakingChanges", BreakingChangeRule::fromNode, builder::breakingChanges); + .getMember("selector", Selector::fromNode, builder::selector) + .getMember("structurallyExclusive", StructurallyExclusive::fromNode, builder::structurallyExclusive) + .getArrayMember("conflicts", nodes -> { + for (Node element : nodes) { + builder.addConflict(element.expectStringNode().getValue()); + } + }) + .getArrayMember("breakingChanges", BreakingChangeRule::fromNode, builder::breakingChanges); TraitDefinition result = builder.build(); result.setNodeCache(value); return result; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/TraitFactory.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/TraitFactory.java index 2fa8b34c06e..46a87db1101 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/TraitFactory.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/TraitFactory.java @@ -39,7 +39,7 @@ static TraitFactory createServiceFactory(Iterable services) { Map serviceMap = new HashMap<>(); services.forEach(service -> serviceMap.put(service.getShapeId(), service)); return (name, target, value) -> Optional.ofNullable(serviceMap.get(name)) - .map(provider -> provider.createTrait(target, value)); + .map(provider -> provider.createTrait(target, value)); } /** diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/TraitValidatorsTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/TraitValidatorsTrait.java index 7fb461a2f06..758d38860be 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/TraitValidatorsTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/TraitValidatorsTrait.java @@ -118,8 +118,8 @@ public boolean equals(Object o) { } Validator validator = (Validator) o; return selector.equals(validator.selector) - && Objects.equals(message, validator.message) - && severity == validator.severity; + && Objects.equals(message, validator.message) + && severity == validator.severity; } @Override diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/XmlNamespaceTrait.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/XmlNamespaceTrait.java index b2f1f3a5913..427a9f7795f 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/XmlNamespaceTrait.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/XmlNamespaceTrait.java @@ -39,8 +39,8 @@ public Optional getPrefix() { @Override protected Node createNode() { return new ObjectNode(MapUtils.of(), getSourceLocation()) - .withMember("uri", Node.from(uri)) - .withOptionalMember("prefix", getPrefix().map(Node::from)); + .withMember("uri", Node.from(uri)) + .withOptionalMember("prefix", getPrefix().map(Node::from)); } /** @@ -53,9 +53,9 @@ public static Builder builder() { @Override public Builder toBuilder() { return builder() - .sourceLocation(getSourceLocation()) - .uri(uri) - .prefix(prefix); + .sourceLocation(getSourceLocation()) + .uri(uri) + .prefix(prefix); } /** @@ -93,8 +93,8 @@ public ShapeId getShapeId() { public XmlNamespaceTrait createTrait(ShapeId target, Node value) { Builder builder = builder().sourceLocation(value); value.expectObjectNode() - .expectStringMember("uri", builder::uri) - .getStringMember("prefix", builder::prefix); + .expectStringMember("uri", builder::uri) + .getStringMember("prefix", builder::prefix); XmlNamespaceTrait result = builder.build(); result.setNodeCache(value); return result; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/AddClientOptional.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/AddClientOptional.java index 70042f8f237..90a2a516a38 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/AddClientOptional.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/AddClientOptional.java @@ -43,8 +43,8 @@ Model transform(ModelTransformer transformer, Model model) { boolean hasInputTrait = container.hasTrait(InputTrait.class); boolean targetsShapeWithNoZeroValue = target.isStructureShape() || target.isUnionShape(); boolean isEffectivelyClientOptional = hasInputTrait - || !(member.hasTrait(RequiredTrait.class) || member.hasTrait(DefaultTrait.class)) - || (targetsShapeWithNoZeroValue && applyWhenNoDefaultValue); + || !(member.hasTrait(RequiredTrait.class) || member.hasTrait(DefaultTrait.class)) + || (targetsShapeWithNoZeroValue && applyWhenNoDefaultValue); if (isEffectivelyClientOptional) { return member.toBuilder().addTrait(new ClientOptionalTrait(member.getSourceLocation())).build(); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/ChangeShapeType.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/ChangeShapeType.java index 46d02454862..89a7b344bfc 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/ChangeShapeType.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/ChangeShapeType.java @@ -76,8 +76,8 @@ Model transform(ModelTransformer transformer, Model model) { if (shapeToType.containsKey(shape.getId())) { ShapeType targetType = shapeToType.get(shape.getId()); return targetType == shape.getType() - ? shape - : shape.accept(new Retype(targetType, synthesizeEnumNames)); + ? shape + : shape.accept(new Retype(targetType, synthesizeEnumNames)); } else { return shape; } @@ -172,10 +172,10 @@ public Shape stringShape(StringShape shape) { return enumShape.get(); } throw invalidType( - shape, - to, - "Strings can only be converted to enums if they have an enum " - + "trait where each enum definition has a name." + shape, + to, + "Strings can only be converted to enums if they have an enum " + + "trait where each enum definition has a name." ); } return copyToSimpleShape(to, shape); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/CreateDedicatedInputAndOutput.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/CreateDedicatedInputAndOutput.java index a336ce4128a..19934ee8a98 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/CreateDedicatedInputAndOutput.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/CreateDedicatedInputAndOutput.java @@ -57,12 +57,12 @@ Model transform(ModelTransformer transformer, Model model) { OperationShape.Builder builder = operation.toBuilder(); if (inputChanged) { LOGGER.fine( - () -> String.format( - "Updating operation input of %s from %s to %s", - operation.getId(), - input.getId(), - updatedInput.getId() - ) + () -> String.format( + "Updating operation input of %s from %s to %s", + operation.getId(), + input.getId(), + updatedInput.getId() + ) ); updates.add(updatedInput); builder.input(updatedInput); @@ -75,12 +75,12 @@ Model transform(ModelTransformer transformer, Model model) { } if (outputChanged) { LOGGER.fine( - () -> String.format( - "Updating operation output of %s from %s to %s", - operation.getId(), - output.getId(), - updatedOutput.getId() - ) + () -> String.format( + "Updating operation output of %s from %s to %s", + operation.getId(), + output.getId(), + updatedOutput.getId() + ) ); updates.add(updatedOutput); builder.output(updatedOutput); @@ -102,10 +102,10 @@ Model transform(ModelTransformer transformer, Model model) { } private StructureShape createdUpdatedInput( - Model model, - OperationShape operation, - StructureShape input, - NeighborProvider reverse + Model model, + OperationShape operation, + StructureShape input, + NeighborProvider reverse ) { if (input.hasTrait(InputTrait.class)) { return renameShapeIfNeeded(model, input, operation, inputSuffix); @@ -119,10 +119,10 @@ private StructureShape createdUpdatedInput( } private StructureShape createdUpdatedOutput( - Model model, - OperationShape operation, - StructureShape output, - NeighborProvider reverse + Model model, + OperationShape operation, + StructureShape output, + NeighborProvider reverse ) { if (output.hasTrait(OutputTrait.class)) { return renameShapeIfNeeded(model, output, operation, outputSuffix); @@ -136,15 +136,15 @@ private StructureShape createdUpdatedOutput( } private StructureShape renameShapeIfNeeded( - Model model, - StructureShape struct, - OperationShape operation, - String suffix + Model model, + StructureShape struct, + OperationShape operation, + String suffix ) { // Check if the shape already has the desired name. ShapeId expectedName = ShapeId.fromParts( - operation.getId().getNamespace(), - operation.getId().getName() + suffix + operation.getId().getNamespace(), + operation.getId().getName() + suffix ); if (struct.getId().equals(expectedName)) { return struct; @@ -154,9 +154,9 @@ private StructureShape renameShapeIfNeeded( ShapeId newId = createSyntheticShapeId(model, operation, suffix); return struct.toBuilder() - .id(newId) - .addTrait(new OriginalShapeIdTrait(struct.getId())) - .build(); + .id(newId) + .addTrait(new OriginalShapeIdTrait(struct.getId())) + .build(); } private boolean isDedicatedHeuristic(OperationShape operation, StructureShape struct, NeighborProvider reverse) { @@ -173,24 +173,24 @@ private boolean isSingularReference(NeighborProvider reverse, Shape shape, Shape // We need to exclude inverted edges like MEMBER_CONTAINER, and only look for directed // edges to the expected shape. return reverse.getNeighbors(shape) - .stream() - .filter(relationship -> relationship.getDirection() == RelationshipDirection.DIRECTED) - .allMatch(relationship -> relationship.getShape().equals(expectedReferencingShape)); + .stream() + .filter(relationship -> relationship.getDirection() == RelationshipDirection.DIRECTED) + .allMatch(relationship -> relationship.getShape().equals(expectedReferencingShape)); } private static StructureShape createSyntheticShape( - Model model, - OperationShape operation, - String suffix, - StructureShape source, - Trait inputOutputTrait + Model model, + OperationShape operation, + String suffix, + StructureShape source, + Trait inputOutputTrait ) { ShapeId newId = createSyntheticShapeId(model, operation, suffix); // Special handling for copying unit types (that, you don't copy unit types) StructureShape.Builder builder = source.getId().equals(UnitTypeTrait.UNIT) - ? StructureShape.builder() - : source.toBuilder(); + ? StructureShape.builder() + : source.toBuilder(); builder.source(source.getSourceLocation()); builder.id(newId); @@ -205,28 +205,28 @@ private static StructureShape createSyntheticShape( } private static ShapeId createSyntheticShapeId( - Model model, - OperationShape operation, - String suffix + Model model, + OperationShape operation, + String suffix ) { // Synthesize an input shape as a dedicated copy of the existing input. ShapeId newId = ShapeId.fromParts( - operation.getId().getNamespace(), - operation.getId().getName() + suffix + operation.getId().getNamespace(), + operation.getId().getName() + suffix ); if (model.getShapeIds().contains(newId)) { ShapeId deconflicted = resolveConflict(newId, suffix); if (model.getShapeIds().contains(deconflicted)) { throw new ModelTransformException( - String.format( - "Unable to generate a synthetic %s shape for the %s operation. The %s shape already exists " - + "in the model, and the conflict resolver also returned a shape ID that already exists: %s", - suffix, - operation.getId(), - newId, - deconflicted - ) + String.format( + "Unable to generate a synthetic %s shape for the %s operation. The %s shape already exists " + + "in the model, and the conflict resolver also returned a shape ID that already exists: %s", + suffix, + operation.getId(), + newId, + deconflicted + ) ); } newId = deconflicted; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/DeconflictErrorsWithSharedStatusCode.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/DeconflictErrorsWithSharedStatusCode.java index 983eacf9d5c..500091096a0 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/DeconflictErrorsWithSharedStatusCode.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/DeconflictErrorsWithSharedStatusCode.java @@ -52,8 +52,8 @@ Model transform(ModelTransformer transformer, Model model) { for (ShapeId errorId : operation.getErrors()) { StructureShape error = model.expectShape(errorId, StructureShape.class); Integer statusCode = error.hasTrait(HttpErrorTrait.ID) - ? error.getTrait(HttpErrorTrait.class).get().getCode() - : error.getTrait(ErrorTrait.class).get().getDefaultHttpStatusCode(); + ? error.getTrait(HttpErrorTrait.class).get().getCode() + : error.getTrait(ErrorTrait.class).get().getDefaultHttpStatusCode(); statusCodesToErrors.computeIfAbsent(statusCode, k -> new ArrayList<>()).add(error); } @@ -64,9 +64,9 @@ Model transform(ModelTransformer transformer, Model model) { List errors = statusCodeToErrors.getValue(); // Create a new top-level synthetic error and all the shapes that need replaced for it. Pair> syntheticErrorPair = synthesizeErrorUnion( - operation.getId().getName(), - statusCodeToErrors.getKey(), - errors + operation.getId().getName(), + statusCodeToErrors.getKey(), + errors ); for (StructureShape error : errors) { replacementOperation.removeError(error.getId()); @@ -88,49 +88,49 @@ Model transform(ModelTransformer transformer, Model model) { // Return synthetic error, along with any updated shapes. private Pair> synthesizeErrorUnion( - String operationName, - Integer statusCode, - List errors + String operationName, + Integer statusCode, + List errors ) { List replacementShapes = new ArrayList<>(); StructureShape.Builder errorResponse = StructureShape.builder(); ShapeId errorResponseId = ShapeId.fromParts( - forService.getId().getNamespace(), - operationName + statusCode + "Error" + forService.getId().getNamespace(), + operationName + statusCode + "Error" ); errorResponse.id(errorResponseId); errorResponse.addTraits(getErrorTraitsFromStatusCode(statusCode)); Map headerTraitMap = new HashMap<>(); UnionShape.Builder errorUnion = UnionShape.builder() - .id( - ShapeId.fromParts(errorResponseId.getNamespace(), errorResponseId.getName() + "Content") - ); + .id( + ShapeId.fromParts(errorResponseId.getNamespace(), errorResponseId.getName() + "Content") + ); for (StructureShape error : errors) { StructureShape newError = createNewError(error, headerTraitMap); replacementShapes.add(newError); MemberShape newErrorMember = MemberShape.builder() - .id(errorUnion.getId().withMember(newError.getId().getName())) - .target(newError.getId()) - .build(); + .id(errorUnion.getId().withMember(newError.getId().getName())) + .target(newError.getId()) + .build(); replacementShapes.add(newErrorMember); errorUnion.addMember(newErrorMember); } UnionShape union = errorUnion.build(); replacementShapes.add(union); errorResponse.addMember( - MemberShape.builder() - .id(errorResponseId.withMember("errorUnion")) - .target(union.getId()) - .build() + MemberShape.builder() + .id(errorResponseId.withMember("errorUnion")) + .target(union.getId()) + .build() ); // Add members with hoisted HttpHeader traits. for (Map.Entry entry : headerTraitMap.entrySet()) { errorResponse.addMember( - MemberShape.builder() - .id(errorResponseId.withMember(entry.getKey())) - .addTrait(entry.getValue()) - .target("smithy.api#String") - .build() + MemberShape.builder() + .id(errorResponseId.withMember(entry.getKey())) + .addTrait(entry.getValue()) + .target("smithy.api#String") + .build() ); } StructureShape built = errorResponse.build(); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/DowngradeToV1.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/DowngradeToV1.java index 6e0780aa1b9..b1ff57a2186 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/DowngradeToV1.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/DowngradeToV1.java @@ -91,10 +91,10 @@ private Model removeUnnecessaryDefaults(ModelTransformer transformer, Model mode for (Shape shape : model.getShapesWithTrait(DefaultTrait.class)) { if (removeDefaultFromShape(shape, model)) { updates.add( - Shape.shapeToBuilder(shape) - .removeTrait(DefaultTrait.ID) - .removeTrait(AddedDefaultTrait.ID) - .build() + Shape.shapeToBuilder(shape) + .removeTrait(DefaultTrait.ID) + .removeTrait(AddedDefaultTrait.ID) + .build() ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeDate.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeDate.java index 967b8dc9b50..efed90563c2 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeDate.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeDate.java @@ -17,7 +17,7 @@ final class FilterDeprecatedRelativeDate { private static final Logger LOGGER = Logger.getLogger(FilterDeprecatedRelativeDate.class.getName()); // YYYY-MM-DD calendar date with optional hyphens. private static final Pattern ISO_8601_DATE_REGEX = Pattern.compile( - "^([0-9]{4})-?(1[0-2]|0[1-9])-?(3[01]|0[1-9]|[12][0-9])$" + "^([0-9]{4})-?(1[0-2]|0[1-9])-?(3[01]|0[1-9]|[12][0-9])$" ); private final String relativeDate; @@ -25,9 +25,9 @@ final class FilterDeprecatedRelativeDate { FilterDeprecatedRelativeDate(String relativeDate) { if (relativeDate != null && !isIso8601Date(relativeDate)) { throw new IllegalArgumentException( - "Provided relativeDate: `" - + relativeDate - + "` does not match ISO8601 calendar date format (YYYY-MM-DD)." + "Provided relativeDate: `" + + relativeDate + + "` does not match ISO8601 calendar date format (YYYY-MM-DD)." ); } this.relativeDate = relativeDate != null ? relativeDate.replace("-", "") : null; @@ -51,9 +51,9 @@ Model transform(ModelTransformer transformer, Model model) { // Compare lexicographical ordering without hyphens. if (relativeDate.compareTo(since.replace("-", "")) > 0) { LOGGER.fine( - "Filtering deprecated shape: `" - + shape + "`" - + ". Shape was deprecated as of: " + since + "Filtering deprecated shape: `" + + shape + "`" + + ". Shape was deprecated as of: " + since ); shapesToRemove.add(shape); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeVersion.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeVersion.java index f9ef30eab7a..c30d5a81cb9 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeVersion.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeVersion.java @@ -21,8 +21,8 @@ final class FilterDeprecatedRelativeVersion { * @see SemVer */ private static final Pattern SEMVER_REGEX = Pattern.compile( - "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)" - + "(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$" + "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)" + + "(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$" ); private final String relativeVersion; @@ -30,9 +30,9 @@ final class FilterDeprecatedRelativeVersion { FilterDeprecatedRelativeVersion(String relativeVersion) { if (relativeVersion != null && !isSemVer(relativeVersion)) { throw new IllegalArgumentException( - "Provided relativeDate: `" - + relativeVersion - + "` is not a valid ." + "Provided relativeDate: `" + + relativeVersion + + "` is not a valid ." ); } this.relativeVersion = relativeVersion; @@ -57,9 +57,9 @@ Model transform(ModelTransformer transformer, Model model) { if (isSemVer(since)) { if (compareSemVer(relativeVersion, since) > 0) { LOGGER.fine( - "Filtering deprecated shape: `" - + shape + "`" - + ". Shape was deprecated as of version: " + since + "Filtering deprecated shape: `" + + shape + "`" + + ". Shape was deprecated as of version: " + since ); shapesToRemove.add(shape); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterMetadata.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterMetadata.java index befea0f8982..b9d0620ba22 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterMetadata.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterMetadata.java @@ -27,10 +27,10 @@ Model transform(Model model) { Model.Builder builder = model.toBuilder(); builder.clearMetadata(); model.getMetadata() - .entrySet() - .stream() - .filter(predicate) - .forEach(e -> builder.putMetadataProperty(e.getKey(), e.getValue())); + .entrySet() + .stream() + .filter(predicate) + .forEach(e -> builder.putMetadataProperty(e.getKey(), e.getValue())); return builder.build(); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterShapes.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterShapes.java index c6adf43d8b3..46d1d6a4bd5 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterShapes.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterShapes.java @@ -27,28 +27,28 @@ final class FilterShapes { FilterShapes(Predicate predicate) { this.predicate = predicate - // Don't ever filter out prelude shapes. - .or(shape -> Prelude.isPreludeShape(shape.getId())); + // Don't ever filter out prelude shapes. + .or(shape -> Prelude.isPreludeShape(shape.getId())); } Model transform(ModelTransformer transformer, Model model) { return transformer.removeShapes( - model, - model.shapes() - .filter(shape -> canFilterShape(model, shape)) - .filter(FunctionalUtils.not(predicate)) - .collect(Collectors.toSet()) + model, + model.shapes() + .filter(shape -> canFilterShape(model, shape)) + .filter(FunctionalUtils.not(predicate)) + .collect(Collectors.toSet()) ); } private static boolean canFilterShape(Model model, Shape shape) { return !shape.isMemberShape() || model.getShape(shape.asMemberShape().get().getContainer()) - .filter( - container -> container.isStructureShape() - || container.isUnionShape() - || container.isEnumShape() - || container.isIntEnumShape() - ) - .isPresent(); + .filter( + container -> container.isStructureShape() + || container.isUnionShape() + || container.isEnumShape() + || container.isIntEnumShape() + ) + .isPresent(); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterTraits.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterTraits.java index b0f6d7b55e5..c3919778ce4 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterTraits.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterTraits.java @@ -33,13 +33,13 @@ Model transform(ModelTransformer transformer, Model model) { private Shape filterTraits(Shape shape) { List keepTraits = shape.getAllTraits() - .values() - .stream() - .filter(trait -> predicate.test(shape, trait)) - .collect(Collectors.toList()); + .values() + .stream() + .filter(trait -> predicate.test(shape, trait)) + .collect(Collectors.toList()); return keepTraits.size() == shape.getAllTraits().size() - ? shape - : Shape.shapeToBuilder(shape).clearTraits().addTraits(keepTraits).build(); + ? shape + : Shape.shapeToBuilder(shape).clearTraits().addTraits(keepTraits).build(); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/FlattenPaginationInfo.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/FlattenPaginationInfo.java index a194a59a5cd..53de36c6e9b 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/FlattenPaginationInfo.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/FlattenPaginationInfo.java @@ -38,8 +38,8 @@ public Model transform(ModelTransformer transformer, Model model) { for (OperationShape operationShape : model.getOperationShapesWithTrait(PaginatedTrait.class)) { PaginationInfo paginationInfo = paginatedIndex.getPaginationInfo(service, operationShape).get(); OperationShape updatedShape = operationShape.toBuilder() - .addTrait(paginationInfo.getPaginatedTrait()) - .build(); + .addTrait(paginationInfo.getPaginatedTrait()) + .build(); updatedShapes.add(updatedShape); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/MakeIdempotencyTokenClientOptional.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/MakeIdempotencyTokenClientOptional.java index aa5d191504a..f60a036dad6 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/MakeIdempotencyTokenClientOptional.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/MakeIdempotencyTokenClientOptional.java @@ -19,9 +19,9 @@ private MakeIdempotencyTokenClientOptional() {} public static Model transform(Model model) { return ModelTransformer.create().mapShapes(model, shape -> { if (shape.isMemberShape() - && shape.hasTrait(RequiredTrait.class) - && shape.hasTrait(IdempotencyTokenTrait.class) - && !shape.hasTrait(ClientOptionalTrait.class)) { + && shape.hasTrait(RequiredTrait.class) + && shape.hasTrait(IdempotencyTokenTrait.class) + && !shape.hasTrait(ClientOptionalTrait.class)) { return Shape.shapeToBuilder(shape).addTrait(new ClientOptionalTrait()).build(); } return shape; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/MapShapes.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/MapShapes.java index b613badd279..13eb9a0576c 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/MapShapes.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/MapShapes.java @@ -29,25 +29,28 @@ final class MapShapes { Model transform(ModelTransformer transformer, Model model) { return transformer.replaceShapes( - model, - model.shapes() - .flatMap(shape -> { - Shape mapped = Objects.requireNonNull(mapper.apply(shape), "Shape mapper must not return null"); - if (mapped.equals(shape)) { - return Stream.empty(); - } else if (!mapped.getId().equals(shape.getId())) { - throw new ModelTransformException( - String.format( - "Mapped shapes must have the same shape ID. Expected %s, but found %s", - shape.getId(), - mapped.getId() - ) - ); - } else { - return Stream.of(mapped); - } - }) - .collect(Collectors.toSet()) + model, + model.shapes() + .flatMap(shape -> { + Shape mapped = Objects.requireNonNull( + mapper.apply(shape), + "Shape mapper must not return null" + ); + if (mapped.equals(shape)) { + return Stream.empty(); + } else if (!mapped.getId().equals(shape.getId())) { + throw new ModelTransformException( + String.format( + "Mapped shapes must have the same shape ID. Expected %s, but found %s", + shape.getId(), + mapped.getId() + ) + ); + } else { + return Stream.of(mapped); + } + }) + .collect(Collectors.toSet()) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/MarkAndSweep.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/MarkAndSweep.java index 5cccdc5fb97..bcc07941430 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/MarkAndSweep.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/MarkAndSweep.java @@ -120,22 +120,22 @@ Set getTargetedFrom(Shape shape) { private Stream findRelationshipsTo(Shape shape) { return reverseProvider.getNeighbors(shape) - .stream() - // We are only interested in references to this shape from - // other shapes, not references to this shape that the shape - // contains (like members). - .filter(rel -> { - RelationshipType type = rel.getRelationshipType(); - return type.getDirection() == RelationshipDirection.DIRECTED && !type.isMemberBinding(); - }) - // Don't allow recursive member references to exclude themselves. - // This check ensures that recursive member references don't exclude - // themselves from being marked by seeing if the relationship is a member - // target (e.g., an aggregate shape that targets a member) - .filter( - rel -> rel.getRelationshipType() != RelationshipType.MEMBER_TARGET - || !rel.getShape().getId().withoutMember().equals(rel.getNeighborShapeId()) - ); + .stream() + // We are only interested in references to this shape from + // other shapes, not references to this shape that the shape + // contains (like members). + .filter(rel -> { + RelationshipType type = rel.getRelationshipType(); + return type.getDirection() == RelationshipDirection.DIRECTED && !type.isMemberBinding(); + }) + // Don't allow recursive member references to exclude themselves. + // This check ensures that recursive member references don't exclude + // themselves from being marked by seeing if the relationship is a member + // target (e.g., an aggregate shape that targets a member) + .filter( + rel -> rel.getRelationshipType() != RelationshipType.MEMBER_TARGET + || !rel.getShape().getId().withoutMember().equals(rel.getNeighborShapeId()) + ); } } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/ModelTransformer.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/ModelTransformer.java index b9d88f7a321..d7f7682b97b 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/ModelTransformer.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/ModelTransformer.java @@ -142,8 +142,8 @@ public Model removeShapesIf(Model model, Predicate predicate) { * @return Returns the transformed model.base. */ public Model renameShapes( - Model model, - Map renamed + Model model, + Map renamed ) { return this.renameShapes(model, renamed, () -> Model.assembler().disableValidation()); } @@ -161,9 +161,9 @@ public Model renameShapes( * @return Returns the transformed model. */ public Model renameShapes( - Model model, - Map renamed, - Supplier modelAssemblerSupplier + Model model, + Map renamed, + Supplier modelAssemblerSupplier ) { return new RenameShapes(renamed, modelAssemblerSupplier).transform(this, model); } @@ -261,10 +261,10 @@ public Model mapTraits(Model model, BiFunction mapper) { */ public Model mapTraits(Model model, List> mappers) { return mapTraits( - model, - mappers.stream() - .reduce((a, b) -> (s, t) -> b.apply(s, a.apply(s, t))) - .orElse((s, t) -> t) + model, + mappers.stream() + .reduce((a, b) -> (s, t) -> b.apply(s, a.apply(s, t))) + .orElse((s, t) -> t) ); } @@ -427,10 +427,10 @@ public Model getModelWithoutTraitShapes(Model model, Predicate keepFilter // model, grabbing shapes from the original model, and building a new // Model. scrubTraitDefinitions(model, keepFilter).shapes() - .map(Shape::getId) - .map(model::getShape) - .map(Optional::get) - .forEach(builder::addShape); + .map(Shape::getId) + .map(model::getShape) + .map(Optional::get) + .forEach(builder::addShape); return builder.build(); } @@ -494,9 +494,9 @@ public Model changeShapeType(Model model, Map shapeToType) { * @throws ModelTransformException if an incompatible type transform is attempted. */ public Model changeShapeType( - Model model, - Map shapeToType, - ChangeShapeTypeOption... changeShapeTypeOptions + Model model, + Map shapeToType, + ChangeShapeTypeOption... changeShapeTypeOptions ) { boolean synthesizeNames = ChangeShapeTypeOption.SYNTHESIZE_ENUM_NAMES.hasFeature(changeShapeTypeOptions); return new ChangeShapeType(shapeToType, synthesizeNames).transform(this, model); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/RemoveInvalidDefaults.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/RemoveInvalidDefaults.java index 65660ce79e7..47ac97ad0c5 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/RemoveInvalidDefaults.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/RemoveInvalidDefaults.java @@ -34,7 +34,7 @@ Model transform(ModelTransformer transformer, Model model) { if (defaultTrait.toNode().isNumberNode()) { defaultTrait.toNode().expectNumberNode().asBigDecimal().ifPresent(value -> { if (rangeTrait.getMin().filter(min -> value.compareTo(min) < 0).isPresent() - || rangeTrait.getMin().filter(max -> value.compareTo(max) > 0).isPresent()) { + || rangeTrait.getMin().filter(max -> value.compareTo(max) > 0).isPresent()) { invalidDefaults.add(shape); } }); @@ -53,9 +53,9 @@ private Shape modify(Shape shape, Model model, Set otherShapes) { // To show up here, the shape has to have a range trait, or the target has to have one. RangeTrait rangeTrait = shape.getMemberTrait(model, RangeTrait.class).get(); LOGGER.info( - () -> "Removing default trait from " + shape.getId() - + " because of an incompatible range trait: " - + Node.printJson(rangeTrait.toNode()) + () -> "Removing default trait from " + shape.getId() + + " because of an incompatible range trait: " + + Node.printJson(rangeTrait.toNode()) ); // Members that target a shape with a default value need to set their default to null to override it. @@ -63,9 +63,9 @@ private Shape modify(Shape shape, Model model, Set otherShapes) { if (shape.isMemberShape()) { MemberShape member = shape.asMemberShape().get(); boolean targetHasDefault = model.getShape(member.getTarget()) - // Treat target shapes that will have their default removed as if it doesn't have a default. - .filter(target -> !otherShapes.contains(target) && target.hasTrait(DefaultTrait.class)) - .isPresent(); + // Treat target shapes that will have their default removed as if it doesn't have a default. + .filter(target -> !otherShapes.contains(target) && target.hasTrait(DefaultTrait.class)) + .isPresent(); if (targetHasDefault) { return member.toBuilder().addTrait(new DefaultTrait(Node.nullNode())).build(); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/RenameShapes.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/RenameShapes.java index 32ef33fd734..62c1f2f02b6 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/RenameShapes.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/RenameShapes.java @@ -49,9 +49,9 @@ Model transform(ModelTransformer transformer, Model model) { // Creates a set that will be used for checking if a string value needs to be renamed or not. Set toRename = renamed.keySet() - .stream() - .map(ShapeId::toString) - .collect(Collectors.toSet()); + .stream() + .map(ShapeId::toString) + .collect(Collectors.toSet()); // TODO: this transform serializes the model, then deserializes it. Because of this, if the model // contained sets via loading a 1.0 model, then the set will be serialized in a 2.0 as a list. @@ -78,10 +78,10 @@ Model transform(ModelTransformer transformer, Model model) { } private Model retypeListsBackToSets( - ModelTransformer transformer, - Model model, - Set sets, - Map renamed + ModelTransformer transformer, + Model model, + Set sets, + Map renamed ) { if (sets.isEmpty()) { return model; @@ -114,18 +114,18 @@ protected Node getDefault(Node node) { @Override public Node arrayNode(ArrayNode node) { return node.getElements() - .stream() - .map(element -> element.accept(this)) - .collect(ArrayNode.collect()); + .stream() + .map(element -> element.accept(this)) + .collect(ArrayNode.collect()); } @Override public Node objectNode(ObjectNode node) { return node.getMembers() - .entrySet() - .stream() - .map(entry -> Pair.of(entry.getKey().accept(this), entry.getValue().accept(this))) - .collect(ObjectNode.collect(pair -> pair.getLeft().expectStringNode(), Pair::getRight)); + .entrySet() + .stream() + .map(entry -> Pair.of(entry.getKey().accept(this), entry.getValue().accept(this))) + .collect(ObjectNode.collect(pair -> pair.getLeft().expectStringNode(), Pair::getRight)); } @Override diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/ReplaceShapes.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/ReplaceShapes.java index a61d9c9e6b6..b44ad9fb4f4 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/ReplaceShapes.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/ReplaceShapes.java @@ -119,12 +119,12 @@ private void assertShapeTypeChangesSound(Model model, Collection shouldRe model.getShape(shape.getId()).ifPresent(previousShape -> { if (shape.getType() != previousShape.getType() && !isReplacementValid(shape, previousShape)) { throw new ModelTransformException( - String.format( - "Cannot change the type of %s from %s to %s", - previousShape.getId(), - previousShape.getType(), - shape.getType() - ) + String.format( + "Cannot change the type of %s from %s to %s", + previousShape.getId(), + previousShape.getType(), + shape.getType() + ) ); } }); @@ -186,8 +186,8 @@ private void updateMixins(Model model, Model.Builder builder, Collection List sorted = sorter.dequeueSortedShapes(); for (ShapeId toRebuild : sorted) { Shape shape = updatedShapes.containsKey(toRebuild) - ? updatedShapes.get(toRebuild) - : model.expectShape(toRebuild); + ? updatedShapes.get(toRebuild) + : model.expectShape(toRebuild); if (!shape.getMixins().isEmpty()) { // We don't clear mixins here because a shape might have an inherited // mixin member that was updated with an applied trait. Clearing mixins @@ -196,8 +196,8 @@ private void updateMixins(Model model, Model.Builder builder, Collection AbstractShapeBuilder shapeBuilder = Shape.shapeToBuilder(shape); for (ShapeId mixin : shape.getMixins()) { Shape mixinShape = updatedShapes.containsKey(mixin) - ? updatedShapes.get(mixin) - : model.expectShape(mixin); + ? updatedShapes.get(mixin) + : model.expectShape(mixin); shapeBuilder.addMixin(mixinShape); } Shape rebuilt = shapeBuilder.build(); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/ScrubTraitDefinitions.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/ScrubTraitDefinitions.java index 2674db07a27..657bb8a7c7a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/ScrubTraitDefinitions.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/ScrubTraitDefinitions.java @@ -40,18 +40,18 @@ Model transform(ModelTransformer transformer, Model model) { Model transform(ModelTransformer transformer, Model model, Predicate keepFilter) { // Find all trait definition shapes, excluding those to be kept, and private shapes in the prelude. Set toMark = Stream.concat( - model.shapes().filter(shape -> isTraitDefinitionToRemove(shape, keepFilter)), - model.shapes().filter(shape -> Prelude.isPreludeShape(shape) && shape.hasTrait(PrivateTrait.class)) + model.shapes().filter(shape -> isTraitDefinitionToRemove(shape, keepFilter)), + model.shapes().filter(shape -> Prelude.isPreludeShape(shape) && shape.hasTrait(PrivateTrait.class)) ).collect(Collectors.toSet()); MarkAndSweep markAndSweep = new MarkAndSweep( - // Mark shapes for removal that are private or remaining trait definitions. - context -> { - toMark.forEach(context::markShape); - toMark.clear(); - }, - // Don't remove public prelude shapes. - ScrubTraitDefinitions::notPublicPreludeShape + // Mark shapes for removal that are private or remaining trait definitions. + context -> { + toMark.forEach(context::markShape); + toMark.clear(); + }, + // Don't remove public prelude shapes. + ScrubTraitDefinitions::notPublicPreludeShape ); // Removing shapes that are traits automatically removes applications of that trait from other shapes. diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanBindings.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanBindings.java index e67f2c192f9..71f602876ca 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanBindings.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanBindings.java @@ -25,13 +25,13 @@ public final class CleanBindings implements ModelTransformerPlugin { @Override public Model onRemove(ModelTransformer transformer, Collection shapes, Model model) { Set removedResources = shapes.stream() - .filter(Shape::isResourceShape) - .map(Shape::getId) - .collect(Collectors.toSet()); + .filter(Shape::isResourceShape) + .map(Shape::getId) + .collect(Collectors.toSet()); Set removedOperations = shapes.stream() - .filter(Shape::isOperationShape) - .map(Shape::getId) - .collect(Collectors.toSet()); + .filter(Shape::isOperationShape) + .map(Shape::getId) + .collect(Collectors.toSet()); Set toReplace = getServicesToUpdate(model, removedResources, removedOperations); toReplace.addAll(getResourcesToUpdate(model, removedResources, removedOperations)); @@ -40,32 +40,32 @@ public Model onRemove(ModelTransformer transformer, Collection shapes, Mo private Set getServicesToUpdate(Model model, Set resources, Set operations) { return model.shapes(ServiceShape.class) - .filter( - service -> containsAny(service.getResources(), resources) - || containsAny(service.getOperations(), operations) - ) - .map(service -> { - ServiceShape.Builder builder = service.toBuilder(); - resources.forEach(builder::removeResource); - operations.forEach(builder::removeOperation); - return builder.build(); - }) - .collect(Collectors.toSet()); + .filter( + service -> containsAny(service.getResources(), resources) + || containsAny(service.getOperations(), operations) + ) + .map(service -> { + ServiceShape.Builder builder = service.toBuilder(); + resources.forEach(builder::removeResource); + operations.forEach(builder::removeOperation); + return builder.build(); + }) + .collect(Collectors.toSet()); } private Set getResourcesToUpdate(Model model, Set resources, Set operations) { return model.shapes(ResourceShape.class) - .filter( - resource -> containsAny(resource.getAllOperations(), operations) - || containsAny(resource.getResources(), resources) - ) - .map(resource -> { - ResourceShape.Builder builder = resource.toBuilder(); - resources.forEach(builder::removeResource); - operations.forEach(builder::removeFromAllOperationBindings); - return builder.build(); - }) - .collect(Collectors.toSet()); + .filter( + resource -> containsAny(resource.getAllOperations(), operations) + || containsAny(resource.getResources(), resources) + ) + .map(resource -> { + ResourceShape.Builder builder = resource.toBuilder(); + resources.forEach(builder::removeResource); + operations.forEach(builder::removeFromAllOperationBindings); + return builder.build(); + }) + .collect(Collectors.toSet()); } private boolean containsAny(Set haystack, Set needles) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanOperationStructures.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanOperationStructures.java index d78bb385f75..ca066dafc4c 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanOperationStructures.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanOperationStructures.java @@ -29,13 +29,13 @@ public Model onRemove(ModelTransformer transformer, Collection removed, M private Collection getModifiedOperations(Model model, Collection removed) { return model.shapes(OperationShape.class) - .flatMap(operation -> { - OperationShape result = transformErrors(removed, operation); - result = transformInput(removed, result); - result = transformOutput(removed, result); - return result.equals(operation) ? Stream.empty() : Stream.of(result); - }) - .collect(Collectors.toList()); + .flatMap(operation -> { + OperationShape result = transformErrors(removed, operation); + result = transformInput(removed, result); + result = transformOutput(removed, result); + return result.equals(operation) ? Stream.empty() : Stream.of(result); + }) + .collect(Collectors.toList()); } private OperationShape transformInput(Collection removed, OperationShape operation) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanServiceRenames.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanServiceRenames.java index 6660be5a811..3a5ebaa30b0 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanServiceRenames.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanServiceRenames.java @@ -29,8 +29,8 @@ public Model onRemove(ModelTransformer transformer, Collection shapes, Mo for (Shape shape : shapes) { if (service.getRename().containsKey(shape.getId())) { updatedServices - .computeIfAbsent(service.getId(), id -> service.toBuilder()) - .removeRename(shape); + .computeIfAbsent(service.getId(), id -> service.toBuilder()) + .removeRename(shape); } } }); @@ -40,9 +40,9 @@ public Model onRemove(ModelTransformer transformer, Collection shapes, Mo } Set shapesToReplace = updatedServices.values() - .stream() - .map(ServiceShape.Builder::build) - .collect(Collectors.toSet()); + .stream() + .map(ServiceShape.Builder::build) + .collect(Collectors.toSet()); return transformer.replaceShapes(model, shapesToReplace); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanStructureAndUnionMembers.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanStructureAndUnionMembers.java index 403753f93b0..2ee926c63e1 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanStructureAndUnionMembers.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanStructureAndUnionMembers.java @@ -110,25 +110,25 @@ private Collection getUnionReplacements(Model model, Collection re * @return Returns a list of shapes that need to be modified in the model. */ private Collection createUpdatedShapes( - Model model, - Collection removed, - Function> containerShapeMapper, - Function>, S> entryMapperAndFactory + Model model, + Collection removed, + Function> containerShapeMapper, + Function>, S> entryMapperAndFactory ) { return removed.stream() - .flatMap(shape -> OptionalUtils.stream(shape.asMemberShape())) - .flatMap( - member -> OptionalUtils.stream( - model.getShape(member.getContainer()) - .flatMap(containerShapeMapper) - .map(container -> Pair.of(container, member)) + .flatMap(shape -> OptionalUtils.stream(shape.asMemberShape())) + .flatMap( + member -> OptionalUtils.stream( + model.getShape(member.getContainer()) + .flatMap(containerShapeMapper) + .map(container -> Pair.of(container, member)) + ) ) - ) - .collect(groupingBy(Pair::getLeft, mapping(Pair::getRight, Collectors.toList()))) - .entrySet() - .stream() - .map(entryMapperAndFactory) - .collect(Collectors.toList()); + .collect(groupingBy(Pair::getLeft, mapping(Pair::getRight, Collectors.toList()))) + .entrySet() + .stream() + .map(entryMapperAndFactory) + .collect(Collectors.toList()); } /** @@ -144,13 +144,13 @@ private Collection findMembersThatNeedRemoval(Model model, Collection removedIds = removed.stream().map(Shape::getId).collect(Collectors.toSet()); Collection removeMembers = new HashSet<>(); model.shapes(StructureShape.class) - .flatMap(shape -> shape.getAllMembers().values().stream()) - .filter(value -> removedIds.contains(value.getTarget())) - .forEach(removeMembers::add); + .flatMap(shape -> shape.getAllMembers().values().stream()) + .filter(value -> removedIds.contains(value.getTarget())) + .forEach(removeMembers::add); model.shapes(UnionShape.class) - .flatMap(shape -> shape.getAllMembers().values().stream()) - .filter(value -> removedIds.contains(value.getTarget())) - .forEach(removeMembers::add); + .flatMap(shape -> shape.getAllMembers().values().stream()) + .filter(value -> removedIds.contains(value.getTarget())) + .forEach(removeMembers::add); return removeMembers; } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanTraitDefinitions.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanTraitDefinitions.java index 0a818c0d185..a104e142aca 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanTraitDefinitions.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanTraitDefinitions.java @@ -42,9 +42,9 @@ private Set getAuthDefShapesToReplace(Model model, Set removedSh // If the list of traits on the AuthDefinitionTrait has changed due to a trait shape being // removed from the model, return a new version of the shape with a new version of the trait. shapes.add( - structure.toBuilder() - .addTrait(authDefTrait.toBuilder().traits(newTraits).build()) - .build() + structure.toBuilder() + .addTrait(authDefTrait.toBuilder().traits(newTraits).build()) + .build() ); } } @@ -64,9 +64,9 @@ private Set getProtocolDefShapesToReplace(Model model, Set remov // being removed from the model, return a new version of the shape with a new version of // the trait. shapes.add( - structure.toBuilder() - .addTrait(protocolDefinitionTrait.toBuilder().traits(newTraits).build()) - .build() + structure.toBuilder() + .addTrait(protocolDefinitionTrait.toBuilder().traits(newTraits).build()) + .build() ); } } @@ -75,7 +75,7 @@ private Set getProtocolDefShapesToReplace(Model model, Set remov private List excludeTraitsInSet(List traits, Set shapeIds) { return traits.stream() - .filter(trait -> !shapeIds.contains(trait)) - .collect(Collectors.toList()); + .filter(trait -> !shapeIds.contains(trait)) + .collect(Collectors.toList()); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/RemoveTraits.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/RemoveTraits.java index d33487002e5..8c750783be0 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/RemoveTraits.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/RemoveTraits.java @@ -28,9 +28,9 @@ public Model onRemove(ModelTransformer transformer, Collection shapes, Mo // Find all shapes with the "@trait" trait to ensure references to it are removed // from other shapes. Set removedTraits = shapes.stream() - .filter(shape -> shape.hasTrait(TraitDefinition.class)) - .map(Shape::getId) - .collect(Collectors.toSet()); + .filter(shape -> shape.hasTrait(TraitDefinition.class)) + .map(Shape::getId) + .collect(Collectors.toSet()); if (removedTraits.isEmpty()) { return model; @@ -42,18 +42,18 @@ public Model onRemove(ModelTransformer transformer, Collection shapes, Mo private List determineShapesToUpdate(Model model, Set removedTraits) { List shapes = model.shapes() - .filter(shape -> !removedTraits.contains(shape.getId())) - .filter(shape -> isShapeInNeedOfUpdate(shape, removedTraits)) - .map(shape -> removeTraitsFromShape(shape, removedTraits)) - .collect(Collectors.toList()); + .filter(shape -> !removedTraits.contains(shape.getId())) + .filter(shape -> isShapeInNeedOfUpdate(shape, removedTraits)) + .map(shape -> removeTraitsFromShape(shape, removedTraits)) + .collect(Collectors.toList()); if (!shapes.isEmpty()) { LOGGER.fine( - () -> String.format( - "Replacing shapes %s that need the following traits removed: %s", - shapes, - removedTraits - ) + () -> String.format( + "Replacing shapes %s that need the following traits removed: %s", + shapes, + removedTraits + ) ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/AbstractValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/AbstractValidator.java index d624eab7d23..c4308a3dd42 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/AbstractValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/AbstractValidator.java @@ -18,418 +18,418 @@ public String getName() { } protected final ValidationEvent error( - Shape shape, - String message + Shape shape, + String message ) { return createEvent(Severity.ERROR, shape, shape.getSourceLocation(), message); } protected final ValidationEvent error( - Shape shape, - String message, - String eventIdSubpart1 + Shape shape, + String message, + String eventIdSubpart1 ) { return createEvent(Severity.ERROR, shape, shape.getSourceLocation(), message, eventIdSubpart1); } protected final ValidationEvent error( - Shape shape, - String message, - String eventIdSubpart1, - String eventIdSubpart2 + Shape shape, + String message, + String eventIdSubpart1, + String eventIdSubpart2 ) { return createEvent(Severity.ERROR, shape, shape.getSourceLocation(), message, eventIdSubpart1, eventIdSubpart2); } protected final ValidationEvent error( - Shape shape, - String message, - String eventIdSubpart1, - String eventIdSubpart2, - String eventIdSubpart3 + Shape shape, + String message, + String eventIdSubpart1, + String eventIdSubpart2, + String eventIdSubpart3 ) { return createEvent( - Severity.ERROR, - shape, - shape.getSourceLocation(), - message, - eventIdSubpart1, - eventIdSubpart2, - eventIdSubpart3 + Severity.ERROR, + shape, + shape.getSourceLocation(), + message, + eventIdSubpart1, + eventIdSubpart2, + eventIdSubpart3 ); } protected final ValidationEvent error( - Shape shape, - FromSourceLocation location, - String message + Shape shape, + FromSourceLocation location, + String message ) { return createEvent(Severity.ERROR, shape, location, message); } protected final ValidationEvent error( - Shape shape, - FromSourceLocation location, - String message, - String eventIdSubpart1 + Shape shape, + FromSourceLocation location, + String message, + String eventIdSubpart1 ) { return createEvent(Severity.ERROR, shape, location, message, eventIdSubpart1); } protected final ValidationEvent error( - Shape shape, - FromSourceLocation location, - String message, - String eventIdSubpart1, - String eventIdSubpart2 + Shape shape, + FromSourceLocation location, + String message, + String eventIdSubpart1, + String eventIdSubpart2 ) { return createEvent(Severity.ERROR, shape, location, message, eventIdSubpart1, eventIdSubpart2); } protected final ValidationEvent error( - Shape shape, - FromSourceLocation location, - String message, - String eventIdSubpart1, - String eventIdSubpart2, - String eventIdSubpart3 + Shape shape, + FromSourceLocation location, + String message, + String eventIdSubpart1, + String eventIdSubpart2, + String eventIdSubpart3 ) { return createEvent(Severity.ERROR, shape, location, message, eventIdSubpart1, eventIdSubpart2, eventIdSubpart3); } protected final ValidationEvent danger( - Shape shape, - String message + Shape shape, + String message ) { return createEvent(Severity.DANGER, shape, shape.getSourceLocation(), message); } protected final ValidationEvent danger( - Shape shape, - String message, - String eventIdSubpart1 + Shape shape, + String message, + String eventIdSubpart1 ) { return createEvent(Severity.DANGER, shape, shape.getSourceLocation(), message, eventIdSubpart1); } protected final ValidationEvent danger( - Shape shape, - String message, - String eventIdSubpart1, - String eventIdSubpart2 + Shape shape, + String message, + String eventIdSubpart1, + String eventIdSubpart2 ) { return createEvent( - Severity.DANGER, - shape, - shape.getSourceLocation(), - message, - eventIdSubpart1, - eventIdSubpart2 + Severity.DANGER, + shape, + shape.getSourceLocation(), + message, + eventIdSubpart1, + eventIdSubpart2 ); } protected final ValidationEvent danger( - Shape shape, - String message, - String eventIdSubpart1, - String eventIdSubpart2, - String eventIdSubpart3 + Shape shape, + String message, + String eventIdSubpart1, + String eventIdSubpart2, + String eventIdSubpart3 ) { return createEvent( - Severity.DANGER, - shape, - shape.getSourceLocation(), - message, - eventIdSubpart1, - eventIdSubpart2, - eventIdSubpart3 + Severity.DANGER, + shape, + shape.getSourceLocation(), + message, + eventIdSubpart1, + eventIdSubpart2, + eventIdSubpart3 ); } protected final ValidationEvent danger( - Shape shape, - FromSourceLocation location, - String message + Shape shape, + FromSourceLocation location, + String message ) { return createEvent(Severity.DANGER, shape, location, message); } protected final ValidationEvent danger( - Shape shape, - FromSourceLocation location, - String message, - String eventIdSubpart1 + Shape shape, + FromSourceLocation location, + String message, + String eventIdSubpart1 ) { return createEvent(Severity.DANGER, shape, location, message, eventIdSubpart1); } protected final ValidationEvent danger( - Shape shape, - FromSourceLocation location, - String message, - String eventIdSubpart1, - String eventIdSubpart2 + Shape shape, + FromSourceLocation location, + String message, + String eventIdSubpart1, + String eventIdSubpart2 ) { return createEvent(Severity.DANGER, shape, location, message, eventIdSubpart1, eventIdSubpart2); } protected final ValidationEvent danger( - Shape shape, - FromSourceLocation location, - String message, - String eventIdSubpart1, - String eventIdSubpart2, - String eventIdSubpart3 + Shape shape, + FromSourceLocation location, + String message, + String eventIdSubpart1, + String eventIdSubpart2, + String eventIdSubpart3 ) { return createEvent( - Severity.DANGER, - shape, - location, - message, - eventIdSubpart1, - eventIdSubpart2, - eventIdSubpart3 + Severity.DANGER, + shape, + location, + message, + eventIdSubpart1, + eventIdSubpart2, + eventIdSubpart3 ); } protected final ValidationEvent warning( - Shape shape, - String message + Shape shape, + String message ) { return createEvent(Severity.WARNING, shape, shape.getSourceLocation(), message); } protected final ValidationEvent warning( - Shape shape, - String message, - String eventIdSubpart1 + Shape shape, + String message, + String eventIdSubpart1 ) { return createEvent(Severity.WARNING, shape, shape.getSourceLocation(), message, eventIdSubpart1); } protected final ValidationEvent warning( - Shape shape, - String message, - String eventIdSubpart1, - String eventIdSubpart2 + Shape shape, + String message, + String eventIdSubpart1, + String eventIdSubpart2 ) { return createEvent( - Severity.WARNING, - shape, - shape.getSourceLocation(), - message, - eventIdSubpart1, - eventIdSubpart2 + Severity.WARNING, + shape, + shape.getSourceLocation(), + message, + eventIdSubpart1, + eventIdSubpart2 ); } protected final ValidationEvent warning( - Shape shape, - String message, - String eventIdSubpart1, - String eventIdSubpart2, - String eventIdSubpart3 + Shape shape, + String message, + String eventIdSubpart1, + String eventIdSubpart2, + String eventIdSubpart3 ) { return createEvent( - Severity.WARNING, - shape, - shape.getSourceLocation(), - message, - eventIdSubpart1, - eventIdSubpart2, - eventIdSubpart3 + Severity.WARNING, + shape, + shape.getSourceLocation(), + message, + eventIdSubpart1, + eventIdSubpart2, + eventIdSubpart3 ); } protected final ValidationEvent warning( - Shape shape, - FromSourceLocation location, - String message + Shape shape, + FromSourceLocation location, + String message ) { return createEvent(Severity.WARNING, shape, location, message); } protected final ValidationEvent warning( - Shape shape, - FromSourceLocation location, - String message, - String eventIdSubpart1 + Shape shape, + FromSourceLocation location, + String message, + String eventIdSubpart1 ) { return createEvent(Severity.WARNING, shape, location, message, eventIdSubpart1); } protected final ValidationEvent warning( - Shape shape, - FromSourceLocation location, - String message, - String eventIdSubpart1, - String eventIdSubpart2 + Shape shape, + FromSourceLocation location, + String message, + String eventIdSubpart1, + String eventIdSubpart2 ) { return createEvent(Severity.WARNING, shape, location, message, eventIdSubpart1, eventIdSubpart2); } protected final ValidationEvent warning( - Shape shape, - FromSourceLocation location, - String message, - String eventIdSubpart1, - String eventIdSubpart2, - String eventIdSubpart3 + Shape shape, + FromSourceLocation location, + String message, + String eventIdSubpart1, + String eventIdSubpart2, + String eventIdSubpart3 ) { return createEvent( - Severity.WARNING, - shape, - location, - message, - eventIdSubpart1, - eventIdSubpart2, - eventIdSubpart3 + Severity.WARNING, + shape, + location, + message, + eventIdSubpart1, + eventIdSubpart2, + eventIdSubpart3 ); } protected final ValidationEvent note( - Shape shape, - String message + Shape shape, + String message ) { return createEvent(Severity.NOTE, shape, shape.getSourceLocation(), message); } protected final ValidationEvent note( - Shape shape, - String message, - String eventIdSubpart1 + Shape shape, + String message, + String eventIdSubpart1 ) { return createEvent(Severity.NOTE, shape, shape.getSourceLocation(), message, eventIdSubpart1); } protected final ValidationEvent note( - Shape shape, - String message, - String eventIdSubpart1, - String eventIdSubpart2 + Shape shape, + String message, + String eventIdSubpart1, + String eventIdSubpart2 ) { return createEvent(Severity.NOTE, shape, shape.getSourceLocation(), message, eventIdSubpart1, eventIdSubpart2); } protected final ValidationEvent note( - Shape shape, - String message, - String eventIdSubpart1, - String eventIdSubpart2, - String eventIdSubpart3 + Shape shape, + String message, + String eventIdSubpart1, + String eventIdSubpart2, + String eventIdSubpart3 ) { return createEvent( - Severity.NOTE, - shape, - shape.getSourceLocation(), - message, - eventIdSubpart1, - eventIdSubpart2, - eventIdSubpart3 + Severity.NOTE, + shape, + shape.getSourceLocation(), + message, + eventIdSubpart1, + eventIdSubpart2, + eventIdSubpart3 ); } protected final ValidationEvent note( - Shape shape, - FromSourceLocation location, - String message + Shape shape, + FromSourceLocation location, + String message ) { return createEvent(Severity.NOTE, shape, location, message); } protected final ValidationEvent note( - Shape shape, - FromSourceLocation location, - String message, - String eventIdSubpart1 + Shape shape, + FromSourceLocation location, + String message, + String eventIdSubpart1 ) { return createEvent(Severity.NOTE, shape, location, message, eventIdSubpart1); } protected final ValidationEvent note( - Shape shape, - FromSourceLocation location, - String message, - String eventIdSubpart1, - String eventIdSubpart2 + Shape shape, + FromSourceLocation location, + String message, + String eventIdSubpart1, + String eventIdSubpart2 ) { return createEvent(Severity.NOTE, shape, location, message, eventIdSubpart1, eventIdSubpart2); } protected final ValidationEvent note( - Shape shape, - FromSourceLocation location, - String message, - String eventIdSubpart1, - String eventIdSubpart2, - String eventIdSubpart3 + Shape shape, + FromSourceLocation location, + String message, + String eventIdSubpart1, + String eventIdSubpart2, + String eventIdSubpart3 ) { return createEvent(Severity.NOTE, shape, location, message, eventIdSubpart1, eventIdSubpart2, eventIdSubpart3); } protected final ValidationEvent createEvent( - Severity severity, - Shape shape, - FromSourceLocation loc, - String message + Severity severity, + Shape shape, + FromSourceLocation loc, + String message ) { return ValidationEvent.builder() - .severity(severity) - .message(message) - .shapeId(shape.getId()) - .sourceLocation(loc.getSourceLocation()) - .id(getName()) - .build(); + .severity(severity) + .message(message) + .shapeId(shape.getId()) + .sourceLocation(loc.getSourceLocation()) + .id(getName()) + .build(); } protected final ValidationEvent createEvent( - Severity severity, - Shape shape, - FromSourceLocation loc, - String message, - String eventIdSubpart1 + Severity severity, + Shape shape, + FromSourceLocation loc, + String message, + String eventIdSubpart1 ) { return ValidationEvent.builder() - .severity(severity) - .message(message) - .shapeId(shape.getId()) - .sourceLocation(loc.getSourceLocation()) - .id(getName() + "." + eventIdSubpart1) - .build(); + .severity(severity) + .message(message) + .shapeId(shape.getId()) + .sourceLocation(loc.getSourceLocation()) + .id(getName() + "." + eventIdSubpart1) + .build(); } protected final ValidationEvent createEvent( - Severity severity, - Shape shape, - FromSourceLocation loc, - String message, - String eventIdSubpart1, - String eventIdSubpart2 + Severity severity, + Shape shape, + FromSourceLocation loc, + String message, + String eventIdSubpart1, + String eventIdSubpart2 ) { return ValidationEvent.builder() - .severity(severity) - .message(message) - .shapeId(shape.getId()) - .sourceLocation(loc.getSourceLocation()) - .id(getName() + "." + eventIdSubpart1 + "." + eventIdSubpart2) - .build(); + .severity(severity) + .message(message) + .shapeId(shape.getId()) + .sourceLocation(loc.getSourceLocation()) + .id(getName() + "." + eventIdSubpart1 + "." + eventIdSubpart2) + .build(); } protected final ValidationEvent createEvent( - Severity severity, - Shape shape, - FromSourceLocation loc, - String message, - String eventIdSubpart1, - String eventIdSubpart2, - String eventIdSubpart3 + Severity severity, + Shape shape, + FromSourceLocation loc, + String message, + String eventIdSubpart1, + String eventIdSubpart2, + String eventIdSubpart3 ) { return ValidationEvent.builder() - .severity(severity) - .message(message) - .shapeId(shape.getId()) - .sourceLocation(loc.getSourceLocation()) - .id(getName() + "." + eventIdSubpart1 + "." + eventIdSubpart2 + "." + eventIdSubpart3) - .build(); + .severity(severity) + .message(message) + .shapeId(shape.getId()) + .sourceLocation(loc.getSourceLocation()) + .id(getName() + "." + eventIdSubpart1 + "." + eventIdSubpart2 + "." + eventIdSubpart3) + .build(); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/ContextualValidationEventFormatter.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/ContextualValidationEventFormatter.java index 36352e496dd..91632296911 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/ContextualValidationEventFormatter.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/ContextualValidationEventFormatter.java @@ -38,10 +38,10 @@ public String format(ValidationEvent event) { StringWriter writer = new StringWriter(); Formatter formatter = new Formatter(writer); formatter.format( - "%s: %s (%s)%n", - event.getSeverity(), - event.getShapeId().map(ShapeId::toString).orElse("-"), - event.getId() + "%s: %s (%s)%n", + event.getSeverity(), + event.getShapeId().map(ShapeId::toString).orElse("-"), + event.getId() ); if (event.getSourceLocation() != SourceLocation.NONE) { @@ -56,9 +56,9 @@ public String format(ValidationEvent event) { formatter.format(" |%n"); // Show the line number and source code line. formatter.format( - "%4d | %s%n", - event.getSourceLocation().getLine(), - lines.iterator().next().getContent() + "%4d | %s%n", + event.getSourceLocation().getLine(), + lines.iterator().next().getContent() ); // Add a carat to point to the column of the error. formatter.format(" | %" + event.getSourceLocation().getColumn() + "s%n", "^"); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/LineValidationEventFormatter.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/LineValidationEventFormatter.java index 7a11f6c9056..46140c75542 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/LineValidationEventFormatter.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/LineValidationEventFormatter.java @@ -24,14 +24,14 @@ public String format(ValidationEvent event) { } return String.format( - "[%s] %s: %s | %s %s:%s:%s", - event.getSeverity(), - event.getShapeId().map(ShapeId::toString).orElse("-"), - message, - event.getId(), - event.getSourceLocation().getFilename(), - event.getSourceLocation().getLine(), - event.getSourceLocation().getColumn() + "[%s] %s: %s | %s %s:%s:%s", + event.getSeverity(), + event.getShapeId().map(ShapeId::toString).orElse("-"), + message, + event.getId(), + event.getSourceLocation().getFilename(), + event.getSourceLocation().getLine(), + event.getSourceLocation().getColumn() ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/NodeValidationVisitor.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/NodeValidationVisitor.java index 0181c33274f..1af0b7df66a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/NodeValidationVisitor.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/NodeValidationVisitor.java @@ -178,15 +178,15 @@ private NodeValidationVisitor traverse(String segment, Node node) { @Override public List blobShape(BlobShape shape) { return value.asStringNode() - .map(stringNode -> applyPlugins(shape)) - .orElseGet(() -> invalidShape(shape, NodeType.STRING)); + .map(stringNode -> applyPlugins(shape)) + .orElseGet(() -> invalidShape(shape, NodeType.STRING)); } @Override public List booleanShape(BooleanShape shape) { return value.isBooleanNode() - ? applyPlugins(shape) - : invalidShape(shape, NodeType.BOOLEAN); + ? applyPlugins(shape) + : invalidShape(shape, NodeType.BOOLEAN); } @Override @@ -216,55 +216,55 @@ public List bigIntegerShape(BigIntegerShape shape) { private List validateNaturalNumber(Shape shape, Long min, Long max) { return value.asNumberNode() - .map(number -> { - if (number.isFloatingPointNumber()) { - return ListUtils.of( - event( - String.format( - "%s shapes must not have floating point values, but found `%s` provided for `%s`", - shape.getType(), - number.getValue(), - shape.getId() - ) - ) - ); - } + .map(number -> { + if (number.isFloatingPointNumber()) { + return ListUtils.of( + event( + String.format( + "%s shapes must not have floating point values, but found `%s` provided for `%s`", + shape.getType(), + number.getValue(), + shape.getId() + ) + ) + ); + } - Long numberValue = number.getValue().longValue(); - if (min != null && numberValue < min) { - return ListUtils.of( - event( - String.format( - "%s value must be > %d, but found %d", - shape.getType(), - min, - numberValue - ) - ) - ); - } else if (max != null && numberValue > max) { - return ListUtils.of( - event( - String.format( - "%s value must be < %d, but found %d", - shape.getType(), - max, - numberValue - ) - ) - ); - } else { - return applyPlugins(shape); - } - }) - .orElseGet(() -> invalidShape(shape, NodeType.NUMBER)); + Long numberValue = number.getValue().longValue(); + if (min != null && numberValue < min) { + return ListUtils.of( + event( + String.format( + "%s value must be > %d, but found %d", + shape.getType(), + min, + numberValue + ) + ) + ); + } else if (max != null && numberValue > max) { + return ListUtils.of( + event( + String.format( + "%s value must be < %d, but found %d", + shape.getType(), + max, + numberValue + ) + ) + ); + } else { + return applyPlugins(shape); + } + }) + .orElseGet(() -> invalidShape(shape, NodeType.NUMBER)); } @Override public List floatShape(FloatShape shape) { return value.isNumberNode() || value.isStringNode() - ? applyPlugins(shape) - : invalidShape(shape, NodeType.NUMBER); + ? applyPlugins(shape) + : invalidShape(shape, NodeType.NUMBER); } @Override @@ -276,22 +276,22 @@ public List documentShape(DocumentShape shape) { @Override public List doubleShape(DoubleShape shape) { return value.isNumberNode() || value.isStringNode() - ? applyPlugins(shape) - : invalidShape(shape, NodeType.NUMBER); + ? applyPlugins(shape) + : invalidShape(shape, NodeType.NUMBER); } @Override public List bigDecimalShape(BigDecimalShape shape) { return value.isNumberNode() - ? applyPlugins(shape) - : invalidShape(shape, NodeType.NUMBER); + ? applyPlugins(shape) + : invalidShape(shape, NodeType.NUMBER); } @Override public List stringShape(StringShape shape) { return value.asStringNode() - .map(string -> applyPlugins(shape)) - .orElseGet(() -> invalidShape(shape, NodeType.STRING)); + .map(string -> applyPlugins(shape)) + .orElseGet(() -> invalidShape(shape, NodeType.STRING)); } @Override @@ -302,107 +302,107 @@ public List timestampShape(TimestampShape shape) { @Override public List listShape(ListShape shape) { return value.asArrayNode() - .map(array -> { - MemberShape member = shape.getMember(); - List events = applyPlugins(shape); - // Each element creates a context with a numeric index (e.g., "foo.0.baz", "foo.1.baz", etc.). - for (int i = 0; i < array.getElements().size(); i++) { - events.addAll(member.accept(traverse(String.valueOf(i), array.getElements().get(i)))); - } - return events; - }) - .orElseGet(() -> invalidShape(shape, NodeType.ARRAY)); + .map(array -> { + MemberShape member = shape.getMember(); + List events = applyPlugins(shape); + // Each element creates a context with a numeric index (e.g., "foo.0.baz", "foo.1.baz", etc.). + for (int i = 0; i < array.getElements().size(); i++) { + events.addAll(member.accept(traverse(String.valueOf(i), array.getElements().get(i)))); + } + return events; + }) + .orElseGet(() -> invalidShape(shape, NodeType.ARRAY)); } @Override public List mapShape(MapShape shape) { return value.asObjectNode() - .map(object -> { - List events = applyPlugins(shape); - for (Map.Entry entry : object.getMembers().entrySet()) { - String key = entry.getKey().getValue(); - events.addAll(traverse(key + " (map-key)", entry.getKey()).memberShape(shape.getKey())); - events.addAll(traverse(key, entry.getValue()).memberShape(shape.getValue())); - } - return events; - }) - .orElseGet(() -> invalidShape(shape, NodeType.OBJECT)); - } - - @Override - public List structureShape(StructureShape shape) { - return value.asObjectNode() - .map(object -> { - List events = applyPlugins(shape); - Map members = shape.getAllMembers(); - - for (Map.Entry entry : object.getStringMap().entrySet()) { - String entryKey = entry.getKey(); - Node entryValue = entry.getValue(); - if (!members.containsKey(entryKey)) { - String message = String.format( - "Invalid structure member `%s` found for `%s`", - entryKey, - shape.getId() - ); - events.add(event(message, Severity.WARNING, shape.getId().toString(), entryKey)); - } else { - events.addAll(traverse(entryKey, entryValue).memberShape(members.get(entryKey))); + .map(object -> { + List events = applyPlugins(shape); + for (Map.Entry entry : object.getMembers().entrySet()) { + String key = entry.getKey().getValue(); + events.addAll(traverse(key + " (map-key)", entry.getKey()).memberShape(shape.getKey())); + events.addAll(traverse(key, entry.getValue()).memberShape(shape.getValue())); } - } - - for (MemberShape member : members.values()) { - if (member.isRequired() && !object.getMember(member.getMemberName()).isPresent()) { - Severity severity = this.validationContext.hasFeature(Feature.ALLOW_CONSTRAINT_ERRORS) - ? Severity.WARNING - : Severity.ERROR; - events.add( - event( - String.format( - "Missing required structure member `%s` for `%s`", - member.getMemberName(), - shape.getId() - ), - severity - ) - ); - } - } - return events; - }) - .orElseGet(() -> invalidShape(shape, NodeType.OBJECT)); + return events; + }) + .orElseGet(() -> invalidShape(shape, NodeType.OBJECT)); } @Override - public List unionShape(UnionShape shape) { + public List structureShape(StructureShape shape) { return value.asObjectNode() - .map(object -> { - List events = applyPlugins(shape); - if (object.size() > 1) { - events.add(event("union values can contain a value for only a single member")); - } else { + .map(object -> { + List events = applyPlugins(shape); Map members = shape.getAllMembers(); + for (Map.Entry entry : object.getStringMap().entrySet()) { String entryKey = entry.getKey(); Node entryValue = entry.getValue(); if (!members.containsKey(entryKey)) { - events.add( - event( - String.format( - "Invalid union member `%s` found for `%s`", - entryKey, - shape.getId() - ) - ) + String message = String.format( + "Invalid structure member `%s` found for `%s`", + entryKey, + shape.getId() ); + events.add(event(message, Severity.WARNING, shape.getId().toString(), entryKey)); } else { events.addAll(traverse(entryKey, entryValue).memberShape(members.get(entryKey))); } } - } - return events; - }) - .orElseGet(() -> invalidShape(shape, NodeType.OBJECT)); + + for (MemberShape member : members.values()) { + if (member.isRequired() && !object.getMember(member.getMemberName()).isPresent()) { + Severity severity = this.validationContext.hasFeature(Feature.ALLOW_CONSTRAINT_ERRORS) + ? Severity.WARNING + : Severity.ERROR; + events.add( + event( + String.format( + "Missing required structure member `%s` for `%s`", + member.getMemberName(), + shape.getId() + ), + severity + ) + ); + } + } + return events; + }) + .orElseGet(() -> invalidShape(shape, NodeType.OBJECT)); + } + + @Override + public List unionShape(UnionShape shape) { + return value.asObjectNode() + .map(object -> { + List events = applyPlugins(shape); + if (object.size() > 1) { + events.add(event("union values can contain a value for only a single member")); + } else { + Map members = shape.getAllMembers(); + for (Map.Entry entry : object.getStringMap().entrySet()) { + String entryKey = entry.getKey(); + Node entryValue = entry.getValue(); + if (!members.containsKey(entryKey)) { + events.add( + event( + String.format( + "Invalid union member `%s` found for `%s`", + entryKey, + shape.getId() + ) + ) + ); + } else { + events.addAll(traverse(entryKey, entryValue).memberShape(members.get(entryKey))); + } + } + } + return events; + }) + .orElseGet(() -> invalidShape(shape, NodeType.OBJECT)); } @Override @@ -426,31 +426,31 @@ public List checkNullMember(MemberShape shape) { switch (model.expectShape(shape.getContainer()).getType()) { case LIST: return ListUtils.of( - event( - String.format( - "Non-sparse list shape `%s` cannot contain null values", - shape.getContainer() + event( + String.format( + "Non-sparse list shape `%s` cannot contain null values", + shape.getContainer() + ) ) - ) ); case MAP: return ListUtils.of( - event( - String.format( - "Non-sparse map shape `%s` cannot contain null values", - shape.getContainer() + event( + String.format( + "Non-sparse map shape `%s` cannot contain null values", + shape.getContainer() + ) ) - ) ); case STRUCTURE: return ListUtils.of( - event( - String.format( - "Required structure member `%s` for `%s` cannot be null", - shape.getMemberName(), - shape.getContainer() + event( + String.format( + "Required structure member `%s` for `%s` cannot be null", + shape.getMemberName(), + shape.getContainer() + ) ) - ) ); default: break; @@ -484,11 +484,11 @@ private List invalidShape(Shape shape, NodeType expectedType) { } String message = String.format( - "Expected %s value for %s shape, `%s`; found %s value", - expectedType, - shape.getType(), - shape.getId(), - value.getType() + "Expected %s value for %s shape, `%s`; found %s value", + expectedType, + shape.getType(), + shape.getId(), + value.getType() ); if (value.isStringNode()) { message += ", `" + value.expectStringNode().getValue() + "`"; @@ -513,43 +513,43 @@ private ValidationEvent event(String message, Severity severity, String... addit } private ValidationEvent event( - String message, - Severity severity, - SourceLocation sourceLocation, - String... additionalEventIdParts + String message, + Severity severity, + SourceLocation sourceLocation, + String... additionalEventIdParts ) { return ValidationEvent.builder() - .id( - additionalEventIdParts.length > 0 - ? eventId + "." + String.join(".", additionalEventIdParts) - : eventId - ) - .severity(severity) - .sourceLocation(sourceLocation) - .shapeId(eventShapeId) - .message(startingContext.isEmpty() ? message : startingContext + ": " + message) - .build(); + .id( + additionalEventIdParts.length > 0 + ? eventId + "." + String.join(".", additionalEventIdParts) + : eventId + ) + .severity(severity) + .sourceLocation(sourceLocation) + .shapeId(eventShapeId) + .message(startingContext.isEmpty() ? message : startingContext + ": " + message) + .build(); } private List applyPlugins(Shape shape) { List events = new ArrayList<>(); timestampValidationStrategy.apply( - shape, - value, - validationContext, - (location, severity, message, additionalEventIdParts) -> events.add( - event(message, severity, location.getSourceLocation(), additionalEventIdParts) - ) - ); - - for (NodeValidatorPlugin plugin : BUILTIN) { - plugin.apply( shape, value, validationContext, (location, severity, message, additionalEventIdParts) -> events.add( - event(message, severity, location.getSourceLocation(), additionalEventIdParts) + event(message, severity, location.getSourceLocation(), additionalEventIdParts) ) + ); + + for (NodeValidatorPlugin plugin : BUILTIN) { + plugin.apply( + shape, + value, + validationContext, + (location, severity, message, additionalEventIdParts) -> events.add( + event(message, severity, location.getSourceLocation(), additionalEventIdParts) + ) ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidatedResult.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidatedResult.java index 9cf36de0262..370b4e72e26 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidatedResult.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidatedResult.java @@ -96,8 +96,8 @@ public List getValidationEvents() { */ public List getValidationEvents(Severity severity) { return getValidationEvents().stream() - .filter(event -> event.getSeverity() == severity) - .collect(Collectors.toList()); + .filter(event -> event.getSeverity() == severity) + .collect(Collectors.toList()); } /** diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidatedResultException.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidatedResultException.java index 2bca6da359c..6ad40708557 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidatedResultException.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidatedResultException.java @@ -16,8 +16,8 @@ public class ValidatedResultException extends RuntimeException { public ValidatedResultException(List events) { super( - "Result contained ERROR severity validation events: \n" - + events.stream().map(ValidationEvent::toString).sorted().collect(Collectors.joining("\n")) + "Result contained ERROR severity validation events: \n" + + events.stream().map(ValidationEvent::toString).sorted().collect(Collectors.joining("\n")) ); this.events = events; } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidationEvent.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidationEvent.java index 0ff43ce4641..6f940ee3c14 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidationEvent.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidationEvent.java @@ -29,7 +29,7 @@ * a message, severity, and eventId. */ public final class ValidationEvent - implements FromSourceLocation, Comparable, ToNode, ToSmithyBuilder { + implements FromSourceLocation, Comparable, ToNode, ToSmithyBuilder { private static final ValidationEventFormatter DEFAULT_FORMATTER = new LineValidationEventFormatter(); private final SourceLocation sourceLocation; private final String message; @@ -78,8 +78,8 @@ public static ValidationEvent fromSourceException(SourceException exception) { public static ValidationEvent fromSourceException(SourceException exception, String prefix) { // Extract shape IDs from exceptions that implement ToShapeId. ShapeId id = (exception instanceof ToShapeId) - ? ((ToShapeId) exception).toShapeId() - : null; + ? ((ToShapeId) exception).toShapeId() + : null; return fromSourceException(exception, prefix, id); } @@ -94,12 +94,12 @@ public static ValidationEvent fromSourceException(SourceException exception, Str public static ValidationEvent fromSourceException(SourceException exception, String prefix, ShapeId shapeId) { // Get the message without source location since it's in the event. return ValidationEvent.builder() - .id(MODEL_ERROR) - .severity(ERROR) - .message(prefix + exception.getMessageWithoutLocation()) - .sourceLocation(exception.getSourceLocation()) - .shapeId(shapeId) - .build(); + .id(MODEL_ERROR) + .severity(ERROR) + .message(prefix + exception.getMessageWithoutLocation()) + .sourceLocation(exception.getSourceLocation()) + .shapeId(shapeId) + .build(); } @Override @@ -146,12 +146,12 @@ public boolean equals(Object o) { ValidationEvent other = (ValidationEvent) o; return sourceLocation.equals(other.sourceLocation) - && message.equals(other.message) - && severity.equals(other.severity) - && eventId.equals(other.eventId) - && getShapeId().equals(other.getShapeId()) - && getSuppressionReason().equals(other.getSuppressionReason()) - && getHint().equals(other.getHint()); + && message.equals(other.message) + && severity.equals(other.severity) + && eventId.equals(other.eventId) + && getShapeId().equals(other.getShapeId()) + && getSuppressionReason().equals(other.getSuppressionReason()) + && getHint().equals(other.getHint()); } @Override @@ -172,16 +172,16 @@ public String toString() { @Override public Node toNode() { return Node.objectNodeBuilder() - .withMember("id", Node.from(getId())) - .withMember("severity", Node.from(getSeverity().toString())) - .withOptionalMember("shapeId", getShapeId().map(Object::toString).map(Node::from)) - .withMember("message", Node.from(getMessage())) - .withOptionalMember("suppressionReason", getSuppressionReason().map(Node::from)) - .withOptionalMember("hint", getHint().map(Node::from)) - .withMember("filename", Node.from(getSourceLocation().getFilename())) - .withMember("line", Node.from(getSourceLocation().getLine())) - .withMember("column", Node.from(getSourceLocation().getColumn())) - .build(); + .withMember("id", Node.from(getId())) + .withMember("severity", Node.from(getSeverity().toString())) + .withOptionalMember("shapeId", getShapeId().map(Object::toString).map(Node::from)) + .withMember("message", Node.from(getMessage())) + .withOptionalMember("suppressionReason", getSuppressionReason().map(Node::from)) + .withOptionalMember("hint", getHint().map(Node::from)) + .withMember("filename", Node.from(getSourceLocation().getFilename())) + .withMember("line", Node.from(getSourceLocation().getLine())) + .withMember("column", Node.from(getSourceLocation().getColumn())) + .build(); } public static ValidationEvent fromNode(Node node) { @@ -191,17 +191,17 @@ public static ValidationEvent fromNode(Node node) { // representation of a ValidationEvent. Expect that and default the // other properties. SourceLocation location = new SourceLocation( - objectNode.expectStringMember("filename").getValue(), - objectNode.getNumberMemberOrDefault("line", 0).intValue(), - objectNode.getNumberMemberOrDefault("column", 0).intValue() + objectNode.expectStringMember("filename").getValue(), + objectNode.getNumberMemberOrDefault("line", 0).intValue(), + objectNode.getNumberMemberOrDefault("column", 0).intValue() ); Builder builder = builder().sourceLocation(location); objectNode.expectStringMember("id", builder::id) - .expectMember("severity", Severity::fromNode, builder::severity) - .expectStringMember("message", builder::message) - .getStringMember("suppressionReason", builder::suppressionReason) - .getStringMember("hint", builder::hint) - .getMember("shapeId", ShapeId::fromNode, builder::shapeId); + .expectMember("severity", Severity::fromNode, builder::severity) + .expectStringMember("message", builder::message) + .getStringMember("suppressionReason", builder::suppressionReason) + .getStringMember("hint", builder::hint) + .getMember("shapeId", ShapeId::fromNode, builder::shapeId); return builder.build(); } @@ -392,7 +392,7 @@ public Builder shapeId(T toShapeId) { */ public Builder shape(Shape encounteredShape) { return sourceLocation(Objects.requireNonNull(encounteredShape).getSourceLocation()) - .shapeId(encounteredShape.getId()); + .shapeId(encounteredShape.getId()); } /** diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidationUtils.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidationUtils.java index 8297a66be98..093fc0f89ec 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidationUtils.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidationUtils.java @@ -44,28 +44,28 @@ public final class ValidationUtils { // Critical validators must emit validation events with names that match their class name (Name in NameValidator). private static final Set> CRITICAL_VALIDATORS = SetUtils.of( - // These validators should run before even any other validators. These validators are considered - // correctness validators that ensure relationships are valid and to shapes that can be found and that - // the model has no cycles. - TargetValidator.class, - ResourceCycleValidator.class, - - // This validator is considered critical because it ensures an enum shape itself is valid. - EnumShapeValidator.class, - - // Ensure that traits are valid, according to the model, before other validators are run. - ExclusiveStructureMemberTraitValidator.class, - TraitTargetValidator.class, - TraitValueValidator.class, - TraitConflictValidator.class, - - // Defaults need to be valid. - DefaultTraitValidator.class, - - // Ensure the semantic model adheres to the requirements of shape IDs and service shape uniqueness. - ShapeIdConflictValidator.class, - SingleOperationBindingValidator.class, - SingleResourceBindingValidator.class + // These validators should run before even any other validators. These validators are considered + // correctness validators that ensure relationships are valid and to shapes that can be found and that + // the model has no cycles. + TargetValidator.class, + ResourceCycleValidator.class, + + // This validator is considered critical because it ensures an enum shape itself is valid. + EnumShapeValidator.class, + + // Ensure that traits are valid, according to the model, before other validators are run. + ExclusiveStructureMemberTraitValidator.class, + TraitTargetValidator.class, + TraitValueValidator.class, + TraitConflictValidator.class, + + // Defaults need to be valid. + DefaultTraitValidator.class, + + // Ensure the semantic model adheres to the requirements of shape IDs and service shape uniqueness. + ShapeIdConflictValidator.class, + SingleOperationBindingValidator.class, + SingleResourceBindingValidator.class ); private static final Pattern CAMEL_WORD_SPLITTER = Pattern.compile("(? Map> findDuplicateShapeNames(Collection shapes) { return shapes.stream() - .map(ToShapeId::toShapeId) - // Exclude IDs with members since these need to be validated separately. - .filter(id -> !id.hasMember()) - // Group by the lowercase name of each shape, and collect the shape IDs as strings. - .collect(groupingBy(id -> id.getName().toLowerCase(Locale.US))) - .entrySet() - .stream() - // Only keep entries that have duplicates. - .filter(entry -> entry.getValue().size() > 1) - // Sort by the member name and collect into an ordered map to preserve sort order. - .sorted(Comparator.comparing(Map.Entry::getKey)) - .collect(toMap(Map.Entry::getKey, entry -> { - // Sort the shape IDs. - entry.getValue().sort(Comparator.comparing(ShapeId::toString)); - return entry.getValue(); - }, (a, b) -> b, LinkedHashMap::new)); + .map(ToShapeId::toShapeId) + // Exclude IDs with members since these need to be validated separately. + .filter(id -> !id.hasMember()) + // Group by the lowercase name of each shape, and collect the shape IDs as strings. + .collect(groupingBy(id -> id.getName().toLowerCase(Locale.US))) + .entrySet() + .stream() + // Only keep entries that have duplicates. + .filter(entry -> entry.getValue().size() > 1) + // Sort by the member name and collect into an ordered map to preserve sort order. + .sorted(Comparator.comparing(Map.Entry::getKey)) + .collect(toMap(Map.Entry::getKey, entry -> { + // Sort the shape IDs. + entry.getValue().sort(Comparator.comparing(ShapeId::toString)); + return entry.getValue(); + }, (a, b) -> b, LinkedHashMap::new)); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidatorFactory.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidatorFactory.java index d6ba432b585..2ac05d18bef 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidatorFactory.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/ValidatorFactory.java @@ -76,9 +76,9 @@ public List loadBuiltinValidators() { @Override public Optional createValidator(String name, ObjectNode configuration) { return serviceList.stream() - .filter(service -> service.getName().equals(name)) - .map(service -> service.createValidator(configuration)) - .findFirst(); + .filter(service -> service.getName().equals(name)) + .map(service -> service.createValidator(configuration)) + .findFirst(); } }; } @@ -98,9 +98,9 @@ public Optional createValidator(String name, ObjectNode configuration * @return Returns the created ValidatorFactory. */ static ValidatorFactory createServiceFactory( - Iterable validators, - Iterable services, - Iterable decorators + Iterable validators, + Iterable services, + Iterable decorators ) { List serviceList = new ArrayList<>(); services.forEach(serviceList::add); @@ -123,9 +123,9 @@ public List loadDecorators() { @Override public Optional createValidator(String name, ObjectNode configuration) { return serviceList.stream() - .filter(service -> service.getName().equals(name)) - .map(service -> service.createValidator(configuration)) - .findFirst(); + .filter(service -> service.getName().equals(name)) + .map(service -> service.createValidator(configuration)) + .findFirst(); } }; } @@ -139,9 +139,9 @@ public Optional createValidator(String name, ObjectNode configuration */ static ValidatorFactory createServiceFactory(ClassLoader classLoader) { return createServiceFactory( - ServiceLoader.load(Validator.class, classLoader), - ServiceLoader.load(ValidatorService.class, classLoader), - ServiceLoader.load(ValidationEventDecorator.class, classLoader) + ServiceLoader.load(Validator.class, classLoader), + ServiceLoader.load(ValidatorService.class, classLoader), + ServiceLoader.load(ValidationEventDecorator.class, classLoader) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/linters/EmitEachSelectorValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/linters/EmitEachSelectorValidator.java index 110cc1c98c6..d2aa9058a96 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/linters/EmitEachSelectorValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/linters/EmitEachSelectorValidator.java @@ -124,10 +124,10 @@ public List validate(Model model) { private List validateWithSimpleMessages(Model model) { return config.getSelector() - .select(model) - .stream() - .flatMap(shape -> OptionalUtils.stream(createSimpleEvent(shape))) - .collect(Collectors.toList()); + .select(model) + .stream() + .flatMap(shape -> OptionalUtils.stream(createSimpleEvent(shape))) + .collect(Collectors.toList()); } private Optional createSimpleEvent(Shape shape) { @@ -144,8 +144,8 @@ private Optional createSimpleEvent(Shape shape) { // set if the shape actually has the trait. private FromSourceLocation determineEventLocation(Shape shape) { return config.bindToTrait == null - ? shape.getSourceLocation() - : shape.findTrait(config.bindToTrait).orElse(null); + ? shape.getSourceLocation() + : shape.findTrait(config.bindToTrait).orElse(null); } // Created events with a message template requires emitting matches @@ -247,8 +247,8 @@ MessageTemplate parse() { @Override public RuntimeException syntax(String message) { return new RuntimeException( - "Syntax error at line " + line() + " column " + column() - + " of EmitEachSelector message template: " + message + "Syntax error at line " + line() + " column " + column() + + " of EmitEachSelector message template: " + message ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/linters/EmitNoneSelectorValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/linters/EmitNoneSelectorValidator.java index d5e7f3c67a4..7202292ce13 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/linters/EmitNoneSelectorValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/linters/EmitNoneSelectorValidator.java @@ -66,18 +66,18 @@ private EmitNoneSelectorValidator(Config config) { public List validate(Model model) { // Filter out prelude types. Set shapes = config.getSelector() - .select(model) - .stream() - .filter(shape -> !Prelude.isPreludeShape(shape.getId())) - .collect(Collectors.toSet()); + .select(model) + .stream() + .filter(shape -> !Prelude.isPreludeShape(shape.getId())) + .collect(Collectors.toSet()); if (shapes.isEmpty()) { return ListUtils.of( - ValidationEvent.builder() - .id(getName()) - .severity(Severity.DANGER) - .message("Expected at least one shape to match selector: " + config.getSelector()) - .build() + ValidationEvent.builder() + .id(getName()) + .severity(Severity.DANGER) + .message("Expected at least one shape to match selector: " + config.getSelector()) + .build() ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/linters/UnreferencedShapeValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/linters/UnreferencedShapeValidator.java index 82e56ceabb4..977fc7a12d8 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/linters/UnreferencedShapeValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/linters/UnreferencedShapeValidator.java @@ -54,14 +54,14 @@ public Provider() { super(UnreferencedShapeValidator.class, configuration -> { Config config = new Config(); ObjectNode node = configuration.expectObjectNode() - .expectNoAdditionalProperties(Collections.singleton("rootShapeSelector")); + .expectNoAdditionalProperties(Collections.singleton("rootShapeSelector")); node.getStringMember("rootShapeSelector").ifPresent(rootShapeNode -> { try { config.setRootShapeSelector(Selector.parse(rootShapeNode.getValue())); } catch (SelectorSyntaxException e) { throw new ExpectationNotMetException( - "Error parsing `rootShapeSelector`: " + e.getMessage(), - rootShapeNode + "Error parsing `rootShapeSelector`: " + e.getMessage(), + rootShapeNode ); } }); @@ -82,11 +82,11 @@ public List validate(Model model) { for (Shape shape : new UnreferencedShapes(config.rootShapeSelector).compute(model)) { events.add( - note( - shape, - "This shape is unreferenced. It has no modeled connections to shapes " - + "that match the following selector: `" + config.rootShapeSelector + "`" - ) + note( + shape, + "This shape is unreferenced. It has no modeled connections to shapes " + + "that match the following selector: `" + config.rootShapeSelector + "`" + ) ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/BlobLengthPlugin.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/BlobLengthPlugin.java index 63e717181f6..d92b89f06f7 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/BlobLengthPlugin.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/BlobLengthPlugin.java @@ -31,11 +31,11 @@ protected void check(Shape shape, LengthTrait trait, StringNode node, Context co trait.getMin().ifPresent(min -> { if (size < min) { emitter.accept( - node, - getSeverity(context), - "Value provided for `" + shape.getId() - + "` must have at least " + min + " bytes, but the provided value only has " + size - + " bytes" + node, + getSeverity(context), + "Value provided for `" + shape.getId() + + "` must have at least " + min + " bytes, but the provided value only has " + size + + " bytes" ); } }); @@ -43,11 +43,11 @@ protected void check(Shape shape, LengthTrait trait, StringNode node, Context co trait.getMax().ifPresent(max -> { if (value.getBytes(StandardCharsets.UTF_8).length > max) { emitter.accept( - node, - getSeverity(context), - "Value provided for `" + shape.getId() - + "` must have no more than " + max + " bytes, but the provided value has " + size - + " bytes" + node, + getSeverity(context), + "Value provided for `" + shape.getId() + + "` must have no more than " + max + " bytes, but the provided value has " + size + + " bytes" ); } }); @@ -55,7 +55,7 @@ protected void check(Shape shape, LengthTrait trait, StringNode node, Context co private Severity getSeverity(Context context) { return context.hasFeature(NodeValidationVisitor.Feature.ALLOW_CONSTRAINT_ERRORS) - ? Severity.WARNING - : Severity.ERROR; + ? Severity.WARNING + : Severity.ERROR; } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/CollectionLengthPlugin.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/CollectionLengthPlugin.java index 423b71c3c22..2c2f9015fee 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/CollectionLengthPlugin.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/CollectionLengthPlugin.java @@ -26,14 +26,14 @@ protected void check(Shape shape, LengthTrait trait, ArrayNode node, Context con trait.getMin().ifPresent(min -> { if (node.size() < min) { emitter.accept( - node, - String.format( - "Value provided for `%s` must have at least %d elements, but the provided value only " - + "has %d elements", - shape.getId(), - min, - node.size() - ) + node, + String.format( + "Value provided for `%s` must have at least %d elements, but the provided value only " + + "has %d elements", + shape.getId(), + min, + node.size() + ) ); } }); @@ -41,14 +41,14 @@ protected void check(Shape shape, LengthTrait trait, ArrayNode node, Context con trait.getMax().ifPresent(max -> { if (node.size() > max) { emitter.accept( - node, - String.format( - "Value provided for `%s` must have no more than %d elements, but the provided value " - + "has %d elements", - shape.getId(), - max, - node.size() - ) + node, + String.format( + "Value provided for `%s` must have no more than %d elements, but the provided value " + + "has %d elements", + shape.getId(), + max, + node.size() + ) ); } }); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/IdRefPlugin.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/IdRefPlugin.java index eedeff80d92..d09e7364d4a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/IdRefPlugin.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/IdRefPlugin.java @@ -35,26 +35,26 @@ protected void check(Shape shape, IdRefTrait trait, StringNode node, Context con if (resolved == null) { if (trait.failWhenMissing()) { failWhenNoMatch( - node, - trait, - emitter, - String.format( - "Shape ID `%s` was not found in the model", - target - ) + node, + trait, + emitter, + String.format( + "Shape ID `%s` was not found in the model", + target + ) ); } } else { if (!matchesSelector(trait, resolved, context)) { failWhenNoMatch( - node, - trait, - emitter, - String.format( - "Shape ID `%s` does not match selector `%s`", - resolved.getId(), - trait.getSelector() - ) + node, + trait, + emitter, + String.format( + "Shape ID `%s` does not match selector `%s`", + resolved.getId(), + trait.getSelector() + ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/IntEnumPlugin.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/IntEnumPlugin.java index f22396ff15f..96339bfc2a6 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/IntEnumPlugin.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/IntEnumPlugin.java @@ -23,13 +23,13 @@ protected void check(IntEnumShape shape, NumberNode node, Context context, Emitt Collection values = shape.getEnumValues().values(); if (!values.contains(node.getValue().intValue())) { emitter.accept( - node, - String.format( - "Integer value provided for `%s` must be one of the following values: %s, but found %s", - shape.getId(), - ValidationUtils.tickedList(values), - node.getValue() - ) + node, + String.format( + "Integer value provided for `%s` must be one of the following values: %s, but found %s", + shape.getId(), + ValidationUtils.tickedList(values), + node.getValue() + ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/MapLengthPlugin.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/MapLengthPlugin.java index 331cad06f2b..041821c147b 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/MapLengthPlugin.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/MapLengthPlugin.java @@ -27,15 +27,15 @@ protected void check(Shape shape, LengthTrait trait, ObjectNode node, Context co trait.getMin().ifPresent(min -> { if (node.size() < min) { emitter.accept( - node, - getSeverity(context), - String.format( - "Value provided for `%s` must have at least %d entries, but the provided value only " - + "has %d entries", - shape.getId(), - min, - node.size() - ) + node, + getSeverity(context), + String.format( + "Value provided for `%s` must have at least %d entries, but the provided value only " + + "has %d entries", + shape.getId(), + min, + node.size() + ) ); } }); @@ -43,15 +43,15 @@ protected void check(Shape shape, LengthTrait trait, ObjectNode node, Context co trait.getMax().ifPresent(max -> { if (node.size() > max) { emitter.accept( - node, - getSeverity(context), - String.format( - "Value provided for `%s` must have no more than %d entries, but the provided value " - + "has %d entries", - shape.getId(), - max, - node.size() - ) + node, + getSeverity(context), + String.format( + "Value provided for `%s` must have no more than %d entries, but the provided value " + + "has %d entries", + shape.getId(), + max, + node.size() + ) ); } }); @@ -59,7 +59,7 @@ protected void check(Shape shape, LengthTrait trait, ObjectNode node, Context co private Severity getSeverity(Context context) { return context.hasFeature(NodeValidationVisitor.Feature.ALLOW_CONSTRAINT_ERRORS) - ? Severity.WARNING - : Severity.ERROR; + ? Severity.WARNING + : Severity.ERROR; } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/MemberAndShapeTraitPlugin.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/MemberAndShapeTraitPlugin.java index a81bab94b5d..72a6cb0924a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/MemberAndShapeTraitPlugin.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/MemberAndShapeTraitPlugin.java @@ -10,7 +10,7 @@ import software.amazon.smithy.model.traits.Trait; abstract class MemberAndShapeTraitPlugin - implements NodeValidatorPlugin { + implements NodeValidatorPlugin { private final Class targetShapeClass; private final Class nodeClass; @@ -26,8 +26,8 @@ abstract class MemberAndShapeTraitPlugin model.getShape(member.getTarget())) - .filter(targetShapeClass::isInstance) - .isPresent(); + .flatMap(member -> model.getShape(member.getTarget())) + .filter(targetShapeClass::isInstance) + .isPresent(); } protected abstract void check(Shape shape, T trait, N value, Context context, Emitter emitter); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/NodeValidatorPlugin.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/NodeValidatorPlugin.java index ac3a87ff452..7a27614a22d 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/NodeValidatorPlugin.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/NodeValidatorPlugin.java @@ -45,17 +45,17 @@ public interface NodeValidatorPlugin { */ static List getBuiltins() { return ListUtils.of( - new NonNumericFloatValuesPlugin(), - new BlobLengthPlugin(), - new CollectionLengthPlugin(), - new IdRefPlugin(), - new MapLengthPlugin(), - new PatternTraitPlugin(), - new RangeTraitPlugin(), - new StringEnumPlugin(), - new IntEnumPlugin(), - new StringLengthPlugin(), - new UniqueItemsPlugin() + new NonNumericFloatValuesPlugin(), + new BlobLengthPlugin(), + new CollectionLengthPlugin(), + new IdRefPlugin(), + new MapLengthPlugin(), + new PatternTraitPlugin(), + new RangeTraitPlugin(), + new StringEnumPlugin(), + new IntEnumPlugin(), + new StringLengthPlugin(), + new UniqueItemsPlugin() ); } @@ -71,9 +71,9 @@ final class Context { // Use an LRU cache to ensure the Selector cache doesn't grow too large // when given bad inputs. private final Map> selectorResults = new LinkedHashMap>( - 50 + 1, - .75F, - true + 50 + 1, + .75F, + true ) { @Override public boolean removeEldestEntry(Map.Entry> eldest) { @@ -133,10 +133,10 @@ public Optional getReferringMember() { @FunctionalInterface interface Emitter { void accept( - FromSourceLocation sourceLocation, - Severity severity, - String message, - String... additionalEventIdParts + FromSourceLocation sourceLocation, + Severity severity, + String message, + String... additionalEventIdParts ); default void accept(FromSourceLocation sourceLocation, String message) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/NonNumericFloatValuesPlugin.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/NonNumericFloatValuesPlugin.java index 1311e9ffca0..4bbb1103454 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/NonNumericFloatValuesPlugin.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/NonNumericFloatValuesPlugin.java @@ -23,13 +23,13 @@ public void apply(Shape shape, Node value, Context context, Emitter emitter) { String nodeValue = value.expectStringNode().getValue(); if (!NON_NUMERIC_FLOAT_VALUES.contains(nodeValue)) { emitter.accept( - value, - String.format( - "Value for `%s` must either be numeric or one of the following strings: [\"%s\"], but was \"%s\"", - shape.getId(), - String.join("\", \"", NON_NUMERIC_FLOAT_VALUES), - nodeValue - ) + value, + String.format( + "Value for `%s` must either be numeric or one of the following strings: [\"%s\"], but was \"%s\"", + shape.getId(), + String.join("\", \"", NON_NUMERIC_FLOAT_VALUES), + nodeValue + ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/PatternTraitPlugin.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/PatternTraitPlugin.java index c3ee8050ce2..4f1d19d2427 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/PatternTraitPlugin.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/PatternTraitPlugin.java @@ -24,20 +24,20 @@ final class PatternTraitPlugin extends MemberAndShapeTraitPlugin { if (value.equals(NonNumericFloat.NAN)) { emitter.accept( - node, - getSeverity(context), - String.format( - "Value provided for `%s` must be a number because the `smithy.api#range` trait is applied, " - + "but found \"%s\"", - shape.getId(), - node.getValue() - ) + node, + getSeverity(context), + String.format( + "Value provided for `%s` must be a number because the `smithy.api#range` trait is applied, " + + "but found \"%s\"", + shape.getId(), + node.getValue() + ) ); } if (trait.getMin().isPresent() && value.equals(NonNumericFloat.NEGATIVE_INFINITY)) { emitter.accept( - node, - getSeverity(context), - String.format( - "Value provided for `%s` must be greater than or equal to %s, but found \"%s\"", - shape.getId(), - trait.getMin().get(), - node.getValue() - ), - shape.isMemberShape() ? MEMBER : TARGET, - INVALID_RANGE + node, + getSeverity(context), + String.format( + "Value provided for `%s` must be greater than or equal to %s, but found \"%s\"", + shape.getId(), + trait.getMin().get(), + node.getValue() + ), + shape.isMemberShape() ? MEMBER : TARGET, + INVALID_RANGE ); } if (trait.getMax().isPresent() && value.equals(NonNumericFloat.POSITIVE_INFINITY)) { emitter.accept( - node, - getSeverity(context), - String.format( - "Value provided for `%s` must be less than or equal to %s, but found \"%s\"", - shape.getId(), - trait.getMax().get(), - node.getValue() - ), - shape.isMemberShape() ? MEMBER : TARGET, - INVALID_RANGE + node, + getSeverity(context), + String.format( + "Value provided for `%s` must be less than or equal to %s, but found \"%s\"", + shape.getId(), + trait.getMax().get(), + node.getValue() + ), + shape.isMemberShape() ? MEMBER : TARGET, + INVALID_RANGE ); } }); @@ -90,16 +90,16 @@ protected void check(Shape shape, Context context, RangeTrait trait, NumberNode node.asBigDecimal().ifPresent(decimal -> { if (decimal.compareTo(min) < 0) { emitter.accept( - node, - getSeverity(node, context), - String.format( - "Value provided for `%s` must be greater than or equal to %s, but found %s", - shape.getId(), - min, - decimal - ), - shape.isMemberShape() ? MEMBER : TARGET, - INVALID_RANGE + node, + getSeverity(node, context), + String.format( + "Value provided for `%s` must be greater than or equal to %s, but found %s", + shape.getId(), + min, + decimal + ), + shape.isMemberShape() ? MEMBER : TARGET, + INVALID_RANGE ); } }); @@ -109,16 +109,16 @@ protected void check(Shape shape, Context context, RangeTrait trait, NumberNode node.asBigDecimal().ifPresent(decimal -> { if (decimal.compareTo(max) > 0) { emitter.accept( - node, - getSeverity(node, context), - String.format( - "Value provided for `%s` must be less than or equal to %s, but found %s", - shape.getId(), - max, - decimal - ), - shape.isMemberShape() ? MEMBER : TARGET, - INVALID_RANGE + node, + getSeverity(node, context), + String.format( + "Value provided for `%s` must be less than or equal to %s, but found %s", + shape.getId(), + max, + decimal + ), + shape.isMemberShape() ? MEMBER : TARGET, + INVALID_RANGE ); } }); @@ -127,14 +127,14 @@ protected void check(Shape shape, Context context, RangeTrait trait, NumberNode private Severity getSeverity(NumberNode node, Context context) { boolean zeroValueWarning = context - .hasFeature(NodeValidationVisitor.Feature.RANGE_TRAIT_ZERO_VALUE_WARNING); + .hasFeature(NodeValidationVisitor.Feature.RANGE_TRAIT_ZERO_VALUE_WARNING); boolean rangeTraitWarning = context.hasFeature(NodeValidationVisitor.Feature.ALLOW_CONSTRAINT_ERRORS); return (zeroValueWarning && node.isZero()) || rangeTraitWarning ? Severity.WARNING : Severity.ERROR; } private Severity getSeverity(Context context) { return context.hasFeature(NodeValidationVisitor.Feature.ALLOW_CONSTRAINT_ERRORS) - ? Severity.WARNING - : Severity.ERROR; + ? Severity.WARNING + : Severity.ERROR; } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/StringEnumPlugin.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/StringEnumPlugin.java index f9334099fef..fd368363cf2 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/StringEnumPlugin.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/StringEnumPlugin.java @@ -25,12 +25,12 @@ protected void check(StringShape shape, StringNode node, Context context, Emitte List values = trait.getEnumDefinitionValues(); if (!values.contains(node.getValue())) { emitter.accept( - node, - String.format( - "String value provided for `%s` must be one of the following values: %s", - shape.getId(), - ValidationUtils.tickedList(values) - ) + node, + String.format( + "String value provided for `%s` must be one of the following values: %s", + shape.getId(), + ValidationUtils.tickedList(values) + ) ); } }); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/StringLengthPlugin.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/StringLengthPlugin.java index 42d50842363..120d171e0ed 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/StringLengthPlugin.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/StringLengthPlugin.java @@ -25,15 +25,15 @@ protected void check(Shape shape, LengthTrait trait, StringNode node, Context co trait.getMin().ifPresent(min -> { if (node.getValue().length() < min) { emitter.accept( - node, - getSeverity(context), - String.format( - "String value provided for `%s` must be >= %d characters, but the provided value is " - + "only %d characters.", - shape.getId(), - min, - node.getValue().length() - ) + node, + getSeverity(context), + String.format( + "String value provided for `%s` must be >= %d characters, but the provided value is " + + "only %d characters.", + shape.getId(), + min, + node.getValue().length() + ) ); } }); @@ -41,15 +41,15 @@ protected void check(Shape shape, LengthTrait trait, StringNode node, Context co trait.getMax().ifPresent(max -> { if (node.getValue().length() > max) { emitter.accept( - node, - getSeverity(context), - String.format( - "String value provided for `%s` must be <= %d characters, but the provided value is " - + "%d characters.", - shape.getId(), - max, - node.getValue().length() - ) + node, + getSeverity(context), + String.format( + "String value provided for `%s` must be <= %d characters, but the provided value is " + + "%d characters.", + shape.getId(), + max, + node.getValue().length() + ) ); } }); @@ -57,7 +57,7 @@ protected void check(Shape shape, LengthTrait trait, StringNode node, Context co private Severity getSeverity(Context context) { return context.hasFeature(NodeValidationVisitor.Feature.ALLOW_CONSTRAINT_ERRORS) - ? Severity.WARNING - : Severity.ERROR; + ? Severity.WARNING + : Severity.ERROR; } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/TimestampFormatPlugin.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/TimestampFormatPlugin.java index 773b5c11091..689887851b5 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/TimestampFormatPlugin.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/TimestampFormatPlugin.java @@ -30,8 +30,8 @@ public void apply(Shape shape, Node value, Context context, Emitter emitter) { if (shape instanceof TimestampShape) { // Don't validate the timestamp target if a referring member had the timestampFormat trait. boolean fromMemberWithTrait = context.getReferringMember() - .filter(member -> member.hasTrait(TimestampFormatTrait.class)) - .isPresent(); + .filter(member -> member.hasTrait(TimestampFormatTrait.class)) + .isPresent(); if (!fromMemberWithTrait) { validate(shape, shape.getTrait(TimestampFormatTrait.class).orElse(null), value, emitter); } @@ -54,13 +54,13 @@ private void validate(Shape shape, TimestampFormatTrait trait, Node value, Emitt // Accepts any number including floats. if (!value.isNumberNode()) { emitter.accept( - value, - Severity.ERROR, - String.format( - "Invalid %s value provided for a timestamp with a `%s` format.", - value.getType(), - trait.getValue() - ) + value, + Severity.ERROR, + String.format( + "Invalid %s value provided for a timestamp with a `%s` format.", + value.getType(), + trait.getValue() + ) ); } break; @@ -82,11 +82,11 @@ private void defaultValidation(Shape shape, Node value, Emitter emitter) { validateDatetime(shape, value, emitter); } else { emitter.accept( - value, - "Invalid " + value.getType() + " value provided for timestamp, `" - + shape.getId() + "`. Expected a number that contains epoch seconds with " - + "optional millisecond precision, or a string that contains an RFC 3339 " - + "formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")" + value, + "Invalid " + value.getType() + " value provided for timestamp, `" + + shape.getId() + "`. Expected a number that contains epoch seconds with " + + "optional millisecond precision, or a string that contains an RFC 3339 " + + "formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")" ); } } @@ -95,9 +95,9 @@ private void defaultValidation(Shape shape, Node value, Emitter emitter) { private void validateDatetime(Shape shape, Node value, Emitter emitter) { if (!value.isStringNode()) { emitter.accept( - value, - "Expected a string value for a date-time timestamp " - + "(e.g., \"1985-04-12T23:20:50.52Z\")" + value, + "Expected a string value for a date-time timestamp " + + "(e.g., \"1985-04-12T23:20:50.52Z\")" ); return; } @@ -108,10 +108,10 @@ private void validateDatetime(Shape shape, Node value, Emitter emitter) { // However, Smithy doesn't allow offsets for timestamp shapes. if (!(timestamp.endsWith("Z") && isValidFormat(timestamp, DATE_TIME_Z))) { emitter.accept( - value, - "Invalid string value, `" + timestamp + "`, provided for timestamp, `" - + shape.getId() + "`. Expected an RFC 3339 formatted timestamp (e.g., " - + "\"1985-04-12T23:20:50.52Z\")" + value, + "Invalid string value, `" + timestamp + "`, provided for timestamp, `" + + shape.getId() + "`. Expected an RFC 3339 formatted timestamp (e.g., " + + "\"1985-04-12T23:20:50.52Z\")" ); } } @@ -129,10 +129,10 @@ private void validateHttpDate(Node value, Emitter emitter) { private String createInvalidHttpDateMessage(String dateValue) { return String.format( - "Invalid value provided for %s formatted timestamp. Expected a string value that " - + "matches the IMF-fixdate production of RFC 9110 section-5.6.7. Found: %s", - TimestampFormatTrait.HTTP_DATE, - dateValue + "Invalid value provided for %s formatted timestamp. Expected a string value that " + + "matches the IMF-fixdate production of RFC 9110 section-5.6.7. Found: %s", + TimestampFormatTrait.HTTP_DATE, + dateValue ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/TimestampValidationStrategy.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/TimestampValidationStrategy.java index 789c7daff93..944c6884406 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/TimestampValidationStrategy.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/TimestampValidationStrategy.java @@ -36,10 +36,10 @@ public void apply(Shape shape, Node value, Context context, Emitter emitter) { public void apply(Shape shape, Node value, Context context, Emitter emitter) { if (isTimestampMember(context.model(), shape) && !value.isNumberNode()) { emitter.accept( - shape, - "Invalid " + value.getType() + " value provided for timestamp, `" - + shape.getId() + "`. Expected a number that contains epoch " - + "seconds with optional millisecond precision" + shape, + "Invalid " + value.getType() + " value provided for timestamp, `" + + shape.getId() + "`. Expected a number that contains epoch " + + "seconds with optional millisecond precision" ); } } @@ -47,9 +47,9 @@ public void apply(Shape shape, Node value, Context context, Emitter emitter) { private static boolean isTimestampMember(Model model, Shape shape) { return shape.asMemberShape() - .map(MemberShape::getTarget) - .flatMap(model::getShape) - .filter(Shape::isTimestampShape) - .isPresent(); + .map(MemberShape::getTarget) + .flatMap(model::getShape) + .filter(Shape::isTimestampShape) + .isPresent(); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/UniqueItemsPlugin.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/UniqueItemsPlugin.java index 6ee4fbdb96e..2d9168da69d 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/UniqueItemsPlugin.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/UniqueItemsPlugin.java @@ -39,13 +39,13 @@ protected void check(Shape shape, UniqueItemsTrait trait, ArrayNode value, Conte duplicateValues.add(duplicateNode.toString()); } emitter.accept( - value, - String.format( - "Value provided for `%s` must have unique items, but the following items had multiple entries: " - + "[`%s`]", - shape.getId(), - String.join("`, `", duplicateValues) - ) + value, + String.format( + "Value provided for `%s` must have unique items, but the following items had multiple entries: " + + "[`%s`]", + shape.getId(), + String.join("`, `", duplicateValues) + ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/suppressions/ModelBasedEventDecorator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/suppressions/ModelBasedEventDecorator.java index 905e8b990e7..3411e0682e0 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/suppressions/ModelBasedEventDecorator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/suppressions/ModelBasedEventDecorator.java @@ -93,9 +93,9 @@ public ValidationEvent decorate(ValidationEvent ev) { } private static void loadMetadataSeverityOverrides( - Model model, - List severityOverrides, - List events + Model model, + List severityOverrides, + List events ) { model.getMetadataProperty(SEVERITY_OVERRIDES).ifPresent(value -> { try { @@ -114,9 +114,9 @@ private static void loadMetadataSeverityOverrides( } private static void loadMetadataSuppressions( - Model model, - List suppressions, - List events + Model model, + List suppressions, + List events ) { model.getMetadataProperty(SUPPRESSIONS).ifPresent(value -> { try { @@ -135,10 +135,10 @@ private static void loadMetadataSuppressions( } private static ValidationEvent modifyEventSeverity( - Model model, - ValidationEvent event, - List suppressions, - List severityOverrides + Model model, + ValidationEvent event, + List suppressions, + List severityOverrides ) { // ERROR and SUPPRESSED events cannot be suppressed. if (!event.getSeverity().canSuppress()) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/testrunner/SmithyTestCase.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/testrunner/SmithyTestCase.java index 67f1f17e7cf..1be713eebe0 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/testrunner/SmithyTestCase.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/testrunner/SmithyTestCase.java @@ -31,7 +31,7 @@ */ public final class SmithyTestCase { private static final Pattern EVENT_PATTERN = Pattern.compile( - "^\\[(?SUPPRESSED|NOTE|WARNING|DANGER|ERROR)] (?[^ ]+): ?(?.*) \\| (?[^)]+)" + "^\\[(?SUPPRESSED|NOTE|WARNING|DANGER|ERROR)] (?[^ ]+): ?(?.*) \\| (?[^)]+)" ); private final List expectedEvents; @@ -102,24 +102,24 @@ public String getModelLocation() { public Result createResult(ValidatedResult validatedResult) { List actualEvents = validatedResult.getValidationEvents(); List unmatchedEvents = getExpectedEvents().stream() - .filter( - expectedEvent -> actualEvents.stream() - .noneMatch(actualEvent -> compareEvents(expectedEvent, actualEvent)) - ) - .collect(Collectors.toList()); + .filter( + expectedEvent -> actualEvents.stream() + .noneMatch(actualEvent -> compareEvents(expectedEvent, actualEvent)) + ) + .collect(Collectors.toList()); List extraEvents = actualEvents.stream() - .filter( - actualEvent -> getExpectedEvents().stream() - .noneMatch(expectedEvent -> compareEvents(expectedEvent, actualEvent)) - ) - // Exclude suppressed events from needing to be defined as acceptable validation - // events. However, these can still be defined as required events. - .filter(event -> event.getSeverity() != Severity.SUPPRESSED) - // Exclude ModelDeprecation events and deprecation warnings about traits - // needing to be defined. Without this exclusion, existing 1.0 test cases will fail. - .filter(event -> !isModelDeprecationEvent(event)) - .collect(Collectors.toList()); + .filter( + actualEvent -> getExpectedEvents().stream() + .noneMatch(expectedEvent -> compareEvents(expectedEvent, actualEvent)) + ) + // Exclude suppressed events from needing to be defined as acceptable validation + // events. However, these can still be defined as required events. + .filter(event -> event.getSeverity() != Severity.SUPPRESSED) + // Exclude ModelDeprecation events and deprecation warnings about traits + // needing to be defined. Without this exclusion, existing 1.0 test cases will fail. + .filter(event -> !isModelDeprecationEvent(event)) + .collect(Collectors.toList()); return new SmithyTestCase.Result(getModelLocation(), unmatchedEvents, extraEvents); } @@ -133,10 +133,10 @@ private static boolean compareEvents(ValidationEvent expected, ValidationEvent a String comparedMessage = normalizeMessage(expected.getMessage()); return expected.getSeverity() == actual.getSeverity() - && actual.containsId(expected.getId()) - && expected.getShapeId().equals(actual.getShapeId()) - // Normalize new lines. - && normalizedActualMessage.startsWith(comparedMessage); + && actual.containsId(expected.getId()) + && expected.getShapeId().equals(actual.getShapeId()) + // Normalize new lines. + && normalizedActualMessage.startsWith(comparedMessage); } // Newlines in persisted validation events are escaped. @@ -146,9 +146,9 @@ private static String normalizeMessage(String message) { private boolean isModelDeprecationEvent(ValidationEvent event) { return event.containsId(Validator.MODEL_DEPRECATION) - // Trait vendors should be free to deprecate a trait without breaking consumers. - || event.containsId("DeprecatedTrait") - || event.containsId("DeprecatedShape"); + // Trait vendors should be free to deprecate a trait without breaking consumers. + || event.containsId("DeprecatedTrait") + || event.containsId("DeprecatedShape"); } private static String inferErrorFileLocation(String modelLocation) { @@ -163,22 +163,22 @@ private static List loadExpectedEvents(String errorsFileLocatio String contents = IoUtils.readUtf8File(errorsFileLocation); String fileName = Objects.requireNonNull(Paths.get(errorsFileLocation).getFileName()).toString(); return Arrays.stream(contents.split(System.lineSeparator())) - .filter(line -> !line.trim().isEmpty()) - .map(line -> parseValidationEvent(line, fileName)) - .collect(Collectors.toList()); + .filter(line -> !line.trim().isEmpty()) + .map(line -> parseValidationEvent(line, fileName)) + .collect(Collectors.toList()); } static ValidationEvent parseValidationEvent(String event, String fileName) { Matcher matcher = EVENT_PATTERN.matcher(event); if (!matcher.find()) { throw new IllegalArgumentException( - format( - "Invalid validation event in file `%s`, the following event did " - + "not match the expected regular expression `%s`: %s", - fileName, - EVENT_PATTERN.pattern(), - event - ) + format( + "Invalid validation event in file `%s`, the following event did " + + "not match the expected regular expression `%s`: %s", + fileName, + EVENT_PATTERN.pattern(), + event + ) ); } @@ -186,10 +186,10 @@ static ValidationEvent parseValidationEvent(String event, String fileName) { SourceLocation location = new SourceLocation("/", 0, 0); ValidationEvent.Builder builder = ValidationEvent.builder() - .severity(Severity.fromString(matcher.group("severity")).get()) - .sourceLocation(location) - .id(matcher.group("id")) - .message(matcher.group("message")); + .severity(Severity.fromString(matcher.group("severity")).get()) + .sourceLocation(location) + .id(matcher.group("id")) + .message(matcher.group("message")); // A shape ID of "-" means no shape. if (!matcher.group("shape").equals("-")) { @@ -208,9 +208,9 @@ public static final class Result { private final Collection extraEvents; Result( - String modelLocation, - Collection unmatchedEvents, - Collection extraEvents + String modelLocation, + Collection unmatchedEvents, + Collection extraEvents ) { this.modelLocation = modelLocation; this.unmatchedEvents = Collections.unmodifiableCollection(new TreeSet<>(unmatchedEvents)); @@ -222,17 +222,17 @@ public String toString() { StringBuilder builder = new StringBuilder(); builder.append( - "=======================\n" - + "Model Validation Result\n" - + "=======================\n" + "=======================\n" + + "Model Validation Result\n" + + "=======================\n" ) - .append(getModelLocation()) - .append('\n'); + .append(getModelLocation()) + .append('\n'); if (!getUnmatchedEvents().isEmpty()) { builder.append( - "\nDid not match the following events\n" - + "----------------------------------\n" + "\nDid not match the following events\n" + + "----------------------------------\n" ); for (ValidationEvent event : getUnmatchedEvents()) { builder.append(event.toString().replace("\n", "\\n")).append('\n'); @@ -242,8 +242,8 @@ public String toString() { if (!getExtraEvents().isEmpty()) { builder.append( - "\nEncountered unexpected events\n" - + "-----------------------------\n" + "\nEncountered unexpected events\n" + + "-----------------------------\n" ); for (ValidationEvent event : getExtraEvents()) { builder.append(event.toString().replace("\n", "\\n")).append("\n"); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/testrunner/SmithyTestSuite.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/testrunner/SmithyTestSuite.java index e8fb7966963..bf80d7d2079 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/testrunner/SmithyTestSuite.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/testrunner/SmithyTestSuite.java @@ -100,9 +100,9 @@ public static Stream defaultParameterizedTestSource(Class contextCl ClassLoader classLoader = contextClass.getClassLoader(); ModelAssembler assembler = Model.assembler(classLoader).discoverModels(classLoader); return SmithyTestSuite.runner() - .setModelAssemblerFactory(assembler::copy) - .addTestCasesFromUrl(contextClass.getResource(DEFAULT_TEST_CASE_LOCATION)) - .parameterizedTestSource(); + .setModelAssemblerFactory(assembler::copy) + .addTestCasesFromUrl(contextClass.getResource(DEFAULT_TEST_CASE_LOCATION)) + .parameterizedTestSource(); } /** @@ -181,13 +181,13 @@ public SmithyTestSuite addTestCase(SmithyTestCase testCase) { public SmithyTestSuite addTestCasesFromDirectory(Path modelDirectory) { try (Stream files = Files.walk(modelDirectory)) { files - .filter(Files::isRegularFile) - .filter(file -> { - String filename = file.toString(); - return filename.endsWith(".json") || filename.endsWith(".smithy"); - }) - .map(file -> SmithyTestCase.fromModelFile(file.toString())) - .forEach(this::addTestCase); + .filter(Files::isRegularFile) + .filter(file -> { + String filename = file.toString(); + return filename.endsWith(".json") || filename.endsWith(".smithy"); + }) + .map(file -> SmithyTestCase.fromModelFile(file.toString())) + .forEach(this::addTestCase); return this; } catch (IOException e) { throw new RuntimeException(e); @@ -276,16 +276,16 @@ private boolean isLegacyValidationRequired(SmithyTestCase testCase) { if (!criticalEvents.isEmpty() && !nonCriticalEvents.isEmpty()) { LOGGER.warning( - String.format( - "Test suite `%s` relies on the emission of non-critical validation events " - + "after critical validation events were emitted. This test case should be " - + "refactored so that critical validation events are tested using separate " - + "test cases from non-critical events. Critical events: %s. Non-critical " - + "events: %s", - testCase.getModelLocation(), - criticalEvents, - nonCriticalEvents - ) + String.format( + "Test suite `%s` relies on the emission of non-critical validation events " + + "after critical validation events were emitted. This test case should be " + + "refactored so that critical validation events are tested using separate " + + "test cases from non-critical events. Critical events: %s. Non-critical " + + "events: %s", + testCase.getModelLocation(), + criticalEvents, + nonCriticalEvents + ) ); return true; } @@ -394,11 +394,11 @@ public List getFailedResults() { @Override public String toString() { StringBuilder builder = new StringBuilder( - String.format( - "Smithy validation test runner encountered %d successful result(s), and %d failed result(s)", - getSuccessCount(), - getFailedResults().size() - ) + String.format( + "Smithy validation test runner encountered %d successful result(s), and %d failed result(s)", + getSuccessCount(), + getFailedResults().size() + ) ); getFailedResults().forEach(failed -> builder.append('\n').append(failed.toString()).append('\n')); return builder.toString(); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/AuthTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/AuthTraitValidator.java index 17414b5c613..7309b2b7146 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/AuthTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/AuthTraitValidator.java @@ -47,10 +47,10 @@ private void validateService(Model model, ServiceShape service, List serviceAuth, - ServiceShape service, - Shape shape, - List events + Set serviceAuth, + ServiceShape service, + Shape shape, + List events ) { if (shape.getTrait(AuthTrait.class).isPresent()) { AuthTrait authTrait = shape.getTrait(AuthTrait.class).get(); @@ -59,15 +59,15 @@ private void validateShape( if (!appliedAuthTraitValue.isEmpty()) { events.add( - danger( - shape, - authTrait, - String.format( - "auth trait applies authentication that is not configured on the service shape, `%s`: %s", - service.getId(), - appliedAuthTraitValue + danger( + shape, + authTrait, + String.format( + "auth trait applies authentication that is not configured on the service shape, `%s`: %s", + service.getId(), + appliedAuthTraitValue + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/DefaultTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/DefaultTraitValidator.java index 078fc89086c..56a6b528471 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/DefaultTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/DefaultTraitValidator.java @@ -52,33 +52,33 @@ public List validate(Model model) { DefaultTrait memberDefault = member.getTrait(DefaultTrait.class).orElse(null); if (memberDefault == null) { events.add( - error( - member, - String.format( - "Member targets %s, which requires that the member defines the same default " - + "of `%s` or `null`", - shape.toShapeId(), - Node.printJson(value) + error( + member, + String.format( + "Member targets %s, which requires that the member defines the same default " + + "of `%s` or `null`", + shape.toShapeId(), + Node.printJson(value) + ) ) - ) ); } else if (!memberDefault.toNode().isNullNode() - && !value.equals(member.expectTrait(DefaultTrait.class).toNode())) { - // The member trait is not set to null nor does it match the target defualt. - events.add( - error( - member, - String.format( - "Member defines a default value that differs from the default value of the " - + "target shape, %s. The member has a default of `%s`, but the target has a " - + "default of `%s`.", - shape.toShapeId(), - member.expectTrait(DefaultTrait.class).toNode(), - Node.printJson(value) - ) - ) - ); - } + && !value.equals(member.expectTrait(DefaultTrait.class).toNode())) { + // The member trait is not set to null nor does it match the target defualt. + events.add( + error( + member, + String.format( + "Member defines a default value that differs from the default value of the " + + "target shape, %s. The member has a default of `%s`, but the target has a " + + "default of `%s`.", + shape.toShapeId(), + member.expectTrait(DefaultTrait.class).toNode(), + Node.printJson(value) + ) + ) + ); + } } } } @@ -88,11 +88,11 @@ public List validate(Model model) { } private NodeValidationVisitor validateShapeValue( - Model model, - Shape shape, - DefaultTrait trait, - NodeValidationVisitor visitor, - List events + Model model, + Shape shape, + DefaultTrait trait, + NodeValidationVisitor visitor, + List events ) { Node value = trait.toNode(); Shape shapeTarget = shape; @@ -141,24 +141,24 @@ private NodeValidationVisitor validateShapeValue( value.asArrayNode().ifPresent(array -> { if (!array.isEmpty()) { events.add( - error( - shape, - trait, - "The @default value of a document cannot be a non-empty " - + "array" - ) + error( + shape, + trait, + "The @default value of a document cannot be a non-empty " + + "array" + ) ); } }); value.asObjectNode().ifPresent(obj -> { if (!obj.isEmpty()) { events.add( - error( - shape, - trait, - "The @default value of a document cannot be a non-empty " - + "object" - ) + error( + shape, + trait, + "The @default value of a document cannot be a non-empty " + + "object" + ) ); } }); @@ -171,23 +171,23 @@ private NodeValidationVisitor validateShapeValue( } private NodeValidationVisitor createOrReuseVisitor( - Model model, - NodeValidationVisitor visitor, - Node value, - Shape shape + Model model, + NodeValidationVisitor visitor, + Node value, + Shape shape ) { if (visitor == null) { return NodeValidationVisitor - .builder() - .model(model) - .eventId(getName()) - .value(value) - .startingContext("Error validating @default trait") - .eventShapeId(shape.getId()) - // Use WARNING for range trait errors so that a Smithy model 1.0 to 2.0 conversion can automatically - // suppress any errors to losslessly handle the conversion. - .addFeature(NodeValidationVisitor.Feature.RANGE_TRAIT_ZERO_VALUE_WARNING) - .build(); + .builder() + .model(model) + .eventId(getName()) + .value(value) + .startingContext("Error validating @default trait") + .eventShapeId(shape.getId()) + // Use WARNING for range trait errors so that a Smithy model 1.0 to 2.0 conversion can automatically + // suppress any errors to losslessly handle the conversion. + .addFeature(NodeValidationVisitor.Feature.RANGE_TRAIT_ZERO_VALUE_WARNING) + .build(); } else { visitor.setValue(value); visitor.setEventShapeId(shape.getId()); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/DefaultValueInUpdateValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/DefaultValueInUpdateValidator.java index c93a985d0ad..17d7b093695 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/DefaultValueInUpdateValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/DefaultValueInUpdateValidator.java @@ -46,13 +46,13 @@ public List validate(Model model) { if (!defaultedMembers.isEmpty()) { events.add( - warning( - operation, - "This update style operation has top-level input members marked with " - + "the @default trait. It will be impossible to tell if the member was " - + "omitted or explicitly provided. Affected members: " - + defaultedMembers - ) + warning( + operation, + "This update style operation has top-level input members marked with " + + "the @default trait. It will be impossible to tell if the member was " + + "omitted or explicitly provided. Affected members: " + + defaultedMembers + ) ); defaultedMembers.clear(); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/DeprecatedTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/DeprecatedTraitValidator.java index e74b0abddcf..30e64720304 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/DeprecatedTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/DeprecatedTraitValidator.java @@ -50,14 +50,14 @@ public List validate(Model model) { // Ignore the use of @box on prelude shapes. if (!Prelude.isPreludeShape(shape)) { events.add( - warning( - shape, - shape.findTrait(trait.getId()).get(), - format( - "This shape applies a trait that is deprecated: %s", - traitMessage + warning( + shape, + shape.findTrait(trait.getId()).get(), + format( + "This shape applies a trait that is deprecated: %s", + traitMessage + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EnumShapeValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EnumShapeValidator.java index 7617fa35bf2..e6d353ae90a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EnumShapeValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EnumShapeValidator.java @@ -55,23 +55,23 @@ private void validateEnumShape(List events, EnumShape shape) { Optional value = trait.getStringValue(); if (!value.isPresent()) { events.add( - error( - member, - member.expectTrait(EnumValueTrait.class), - "enum members can only be assigned string values, but found: " - + Node.printJson(trait.toNode()) - ) + error( + member, + member.expectTrait(EnumValueTrait.class), + "enum members can only be assigned string values, but found: " + + Node.printJson(trait.toNode()) + ) ); } else { if (!values.add(value.get())) { events.add( - error( - member, - String.format( - "Multiple enum members found with duplicate value `%s`", - value.get() + error( + member, + String.format( + "Multiple enum members found with duplicate value `%s`", + value.get() + ) ) - ) ); } if (value.get().equals("")) { @@ -96,10 +96,10 @@ private void validateIntEnumShape(List events, IntEnumShape sha // The EnumValueTrait must point to a number. if (!trait.getIntValue().isPresent()) { ValidationEvent event = error( - member, - trait, - "intEnum members require integer values, but found: " - + Node.printJson(trait.toNode()) + member, + trait, + "intEnum members require integer values, but found: " + + Node.printJson(trait.toNode()) ); events.add(event); continue; @@ -110,12 +110,12 @@ private void validateIntEnumShape(List events, IntEnumShape sha // Validate the it is an integer. if (number.isFloatingPointNumber()) { events.add( - error( - member, - trait, - "intEnum members do not support floating point values: " - + number.getValue() - ) + error( + member, + trait, + "intEnum members do not support floating point values: " + + number.getValue() + ) ); continue; } @@ -123,25 +123,25 @@ private void validateIntEnumShape(List events, IntEnumShape sha long longValue = number.getValue().longValue(); if (longValue > Integer.MAX_VALUE || longValue < Integer.MIN_VALUE) { events.add( - error( - member, - trait, - "intEnum members must fit within an integer, but found: " - + longValue - ) + error( + member, + trait, + "intEnum members must fit within an integer, but found: " + + longValue + ) ); continue; } if (!values.add(number.getValue().intValue())) { events.add( - error( - member, - String.format( - "Multiple intEnum members found with duplicate value `%d`", - number.getValue().intValue() + error( + member, + String.format( + "Multiple intEnum members found with duplicate value `%d`", + number.getValue().intValue() + ) ) - ) ); } @@ -156,14 +156,14 @@ private ValidationEvent missingIntEnumValue(Shape shape, FromSourceLocation sour private void validateEnumMemberName(List events, MemberShape member) { if (!RECOMMENDED_NAME_PATTERN.matcher(member.getMemberName()).find()) { events.add( - warning( - member, - String.format( - "The name `%s` does not match the recommended enum name format of beginning with an " - + "uppercase letter, followed by any number of uppercase letters, numbers, or underscores.", - member.getMemberName() + warning( + member, + String.format( + "The name `%s` does not match the recommended enum name format of beginning with an " + + "uppercase letter, followed by any number of uppercase letters, numbers, or underscores.", + member.getMemberName() + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EnumTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EnumTraitValidator.java index 9da7b1bd1f0..f71812a4b83 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EnumTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EnumTraitValidator.java @@ -46,14 +46,14 @@ private List validateEnumTrait(Shape shape, EnumTrait trait) { for (EnumDefinition definition : trait.getValues()) { if (!values.add(definition.getValue())) { events.add( - error( - shape, - trait, - String.format( - "Duplicate enum trait values found with the same `value` property of '%s'", - definition.getValue() + error( + shape, + trait, + String.format( + "Duplicate enum trait values found with the same `value` property of '%s'", + definition.getValue() + ) ) - ) ); } } @@ -64,29 +64,29 @@ private List validateEnumTrait(Shape shape, EnumTrait trait) { String name = definition.getName().get(); if (!names.add(name)) { events.add( - error( - shape, - trait, - String.format( - "Duplicate enum trait values found with the same `name` property of '%s'", - name + error( + shape, + trait, + String.format( + "Duplicate enum trait values found with the same `name` property of '%s'", + name + ) ) - ) ); } if (!RECOMMENDED_NAME_PATTERN.matcher(name).find()) { events.add( - warning( - shape, - trait, - String.format( - "The name `%s` does not match the recommended enum name format of beginning " - + "with an uppercase letter, followed by any number of uppercase letters, numbers, " - + "or underscores.", - name - ), - name - ) + warning( + shape, + trait, + String.format( + "The name `%s` does not match the recommended enum name format of beginning " + + "with an uppercase letter, followed by any number of uppercase letters, numbers, " + + "or underscores.", + name + ), + name + ) ); } } @@ -97,25 +97,25 @@ private List validateEnumTrait(Shape shape, EnumTrait trait) { for (EnumDefinition definition : trait.getValues()) { if (!definition.getName().isPresent()) { events.add( - error( - shape, - trait, - String.format( - "`%s` enum value body is missing the `name` property; if any enum trait value contains a " - + "`name` property, then all values must contain the `name` property.", - definition.getValue() + error( + shape, + trait, + String.format( + "`%s` enum value body is missing the `name` property; if any enum trait value contains a " + + "`name` property, then all values must contain the `name` property.", + definition.getValue() + ) ) - ) ); } } } else { // Enums SHOULD have names, so warn if there are none. ValidationEvent event = warning( - shape, - trait, - "Enums should define the `name` property to allow rich " - + "types to be generated in code generators." + shape, + trait, + "Enums should define the `name` property to allow rich " + + "types to be generated in code generators." ); // Change the id of the event so that it can be suppressed separately. events.add(event.toBuilder().id("EnumNamesPresent").build()); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EventPayloadTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EventPayloadTraitValidator.java index 7445327675e..6a15ef2f4ba 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EventPayloadTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EventPayloadTraitValidator.java @@ -32,9 +32,9 @@ public List validate(Model model) { List events = new ArrayList<>(); for (MemberShape member : model.getMemberShapesWithTrait(EventPayloadTrait.class)) { model.getShape(member.getContainer()) - .flatMap(Shape::asStructureShape) - .flatMap(structure -> validateEvent(structure, member)) - .ifPresent(events::add); + .flatMap(Shape::asStructureShape) + .flatMap(structure -> validateEvent(structure, member)) + .ifPresent(events::add); } return events; @@ -42,26 +42,26 @@ public List validate(Model model) { private Optional validateEvent(StructureShape shape, MemberShape payload) { List unmarked = shape.getAllMembers() - .values() - .stream() - .filter(FunctionalUtils.not(this::isMarked)) - .map(MemberShape::getMemberName) - .collect(Collectors.toList()); + .values() + .stream() + .filter(FunctionalUtils.not(this::isMarked)) + .map(MemberShape::getMemberName) + .collect(Collectors.toList()); if (unmarked.isEmpty()) { return Optional.empty(); } return Optional.of( - error( - shape, - String.format( - "This event structure contains a member marked with the `eventPayload` trait, so all other members " - + "must be marked with the `eventHeader` trait. However, the following member(s) are not marked " - + "with the eventHeader trait: %s", - ValidationUtils.tickedList(unmarked) + error( + shape, + String.format( + "This event structure contains a member marked with the `eventPayload` trait, so all other members " + + "must be marked with the `eventHeader` trait. However, the following member(s) are not marked " + + "with the eventHeader trait: %s", + ValidationUtils.tickedList(unmarked) + ) ) - ) ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExamplesTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExamplesTraitValidator.java index 68a142f11f5..c33e76ffac8 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExamplesTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExamplesTraitValidator.java @@ -47,14 +47,14 @@ private List validateExamples(Model model, OperationShape shape NodeValidationVisitor validator; if (example.getAllowConstraintErrors() && !isErrorDefined) { events.add( - error( - shape, - trait, - String.format( - "Example: `%s` has allowConstraintErrors enabled, so error must be defined.", - example.getTitle() + error( + shape, + trait, + String.format( + "Example: `%s` has allowConstraintErrors enabled, so error must be defined.", + example.getTitle() + ) ) - ) ); } validator = createVisitor("input", example.getInput(), model, shape, example); @@ -64,23 +64,23 @@ private List validateExamples(Model model, OperationShape shape if (isOutputDefined && isErrorDefined) { events.add( - error( - shape, - trait, - String.format( - "Example: `%s` has both output and error defined, only one should be present.", - example.getTitle() + error( + shape, + trait, + String.format( + "Example: `%s` has both output and error defined, only one should be present.", + example.getTitle() + ) ) - ) ); } else if (isOutputDefined) { model.getShape(shape.getOutputShape()).ifPresent(output -> { NodeValidationVisitor validator = createVisitor( - "output", - example.getOutput().get(), - model, - shape, - example + "output", + example.getOutput().get(), + model, + shape, + example ); events.addAll(output.accept(validator)); }); @@ -90,27 +90,27 @@ private List validateExamples(Model model, OperationShape shape if (errorShape.isPresent() && ( // The error is directly bound to the operation. shape.getErrors().contains(errorExample.getShapeId()) - // The error is bound to all services that contain the operation. - || servicesContainError(model, shape, errorExample.getShapeId()))) { + // The error is bound to all services that contain the operation. + || servicesContainError(model, shape, errorExample.getShapeId()))) { NodeValidationVisitor validator = createVisitor( - "error", - errorExample.getContent(), - model, - shape, - example + "error", + errorExample.getContent(), + model, + shape, + example ); events.addAll(errorShape.get().accept(validator)); } else { events.add( - error( - shape, - trait, - String.format( - "Error parameters provided for operation without the `%s` error: `%s`", - errorExample.getShapeId(), - example.getTitle() + error( + shape, + trait, + String.format( + "Error parameters provided for operation without the `%s` error: `%s`", + errorExample.getShapeId(), + example.getTitle() + ) ) - ) ); } } @@ -144,18 +144,18 @@ private boolean servicesContainError(Model model, OperationShape shape, ShapeId } private NodeValidationVisitor createVisitor( - String name, - ObjectNode value, - Model model, - Shape shape, - ExamplesTrait.Example example + String name, + ObjectNode value, + Model model, + Shape shape, + ExamplesTrait.Example example ) { NodeValidationVisitor.Builder builder = NodeValidationVisitor.builder() - .model(model) - .eventShapeId(shape.getId()) - .value(value) - .startingContext("Example " + name + " of `" + example.getTitle() + "`") - .eventId(getName()); + .model(model) + .eventShapeId(shape.getId()) + .value(value) + .startingContext("Example " + name + " of `" + example.getTitle() + "`") + .eventId(getName()); if (example.getAllowConstraintErrors()) { builder.addFeature(NodeValidationVisitor.Feature.ALLOW_CONSTRAINT_ERRORS); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExclusiveStructureMemberTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExclusiveStructureMemberTraitValidator.java index 34eb8feed4e..92fdcf16ed0 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExclusiveStructureMemberTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExclusiveStructureMemberTraitValidator.java @@ -48,9 +48,9 @@ public List validate(Model model) { } private void validateExclusiveMembers( - Shape shape, - Set exclusiveMemberTraits, - List events + Shape shape, + Set exclusiveMemberTraits, + List events ) { for (ShapeId traitId : exclusiveMemberTraits) { List matches = new ArrayList<>(); @@ -62,25 +62,25 @@ private void validateExclusiveMembers( if (matches.size() > 1) { events.add( - error( - shape, - String.format( - "The `%s` trait can be applied to only a single member of a shape, but it was found on " - + "the following members: %s", - Trait.getIdiomaticTraitName(traitId), - ValidationUtils.tickedList(matches) + error( + shape, + String.format( + "The `%s` trait can be applied to only a single member of a shape, but it was found on " + + "the following members: %s", + Trait.getIdiomaticTraitName(traitId), + ValidationUtils.tickedList(matches) + ) ) - ) ); } } } private void validateExclusiveTargets( - Model model, - Shape shape, - Set exclusiveTargets, - List events + Model model, + Shape shape, + Set exclusiveTargets, + List events ) { // Find all member targets that violate the exclusion rule (e.g., streaming trait). for (ShapeId id : exclusiveTargets) { @@ -93,15 +93,15 @@ private void validateExclusiveTargets( if (matches.size() > 1) { events.add( - error( - shape, - String.format( - "Only a single member of a structure can target a shape marked with the `%s` trait, " - + "but it was found on the following members: %s", - Trait.getIdiomaticTraitName(id), - ValidationUtils.tickedList(matches) + error( + shape, + String.format( + "Only a single member of a structure can target a shape marked with the `%s` trait, " + + "but it was found on the following members: %s", + Trait.getIdiomaticTraitName(id), + ValidationUtils.tickedList(matches) + ) ) - ) ); } } @@ -109,7 +109,7 @@ private void validateExclusiveTargets( private boolean memberTargetHasTrait(Model model, MemberShape member, ShapeId trait) { return model.getShape(member.getTarget()) - .flatMap(target -> target.findTrait(trait)) - .isPresent(); + .flatMap(target -> target.findTrait(trait)) + .isPresent(); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HostLabelTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HostLabelTraitValidator.java index 5d1c59fe2af..8dac689626e 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HostLabelTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HostLabelTraitValidator.java @@ -47,7 +47,7 @@ public final class HostLabelTraitValidator extends AbstractValidator { * Match the expanded template to be a valid RFC 3896 host. */ private static final java.util.regex.Pattern EXPANDED_PATTERN = java.util.regex.Pattern.compile( - "^[a-zA-Z0-9][a-zA-Z0-9-]{0,62}(?>\\.[a-zA-Z0-9-]{1,63})*\\.?$" + "^[a-zA-Z0-9][a-zA-Z0-9-]{0,62}(?>\\.[a-zA-Z0-9-]{1,63})*\\.?$" ); @Override @@ -66,9 +66,9 @@ public List validate(Model model) { } private List validateStructure( - Model model, - OperationShape operation, - EndpointTrait endpoint + Model model, + OperationShape operation, + EndpointTrait endpoint ) { List events = new ArrayList<>(); @@ -81,16 +81,16 @@ private List validateStructure( // Only validate the bindings if the input is a structure. Typing // validation of the input is handled elsewhere. model.getShape(operation.getInputShape()) - .flatMap(Shape::asStructureShape) - .ifPresent(input -> events.addAll(validateBindings(operation, endpoint, input))); + .flatMap(Shape::asStructureShape) + .ifPresent(input -> events.addAll(validateBindings(operation, endpoint, input))); return events; } private List validateBindings( - OperationShape operation, - EndpointTrait endpoint, - StructureShape input + OperationShape operation, + EndpointTrait endpoint, + StructureShape input ) { List events = new ArrayList<>(); SmithyPattern hostPrefix = endpoint.getHostPrefix(); @@ -99,9 +99,9 @@ private List validateBindings( // found. If any labels remain after looking at all members, then // there are unmatched labels. Set labels = hostPrefix.getLabels() - .stream() - .map(SmithyPattern.Segment::getContent) - .collect(Collectors.toSet()); + .stream() + .map(SmithyPattern.Segment::getContent) + .collect(Collectors.toSet()); for (MemberShape member : input.getAllMembers().values()) { if (member.hasTrait(HostLabelTrait.class)) { @@ -109,17 +109,17 @@ private List validateBindings( labels.remove(member.getMemberName()); if (!hostPrefix.getLabel(member.getMemberName()).isPresent()) { events.add( - error( - member, - trait, - format( - "This `%s` structure member is marked with the `hostLabel` trait, but no " - + "corresponding `endpoint` label could be found when used as the input of " - + "the `%s` operation.", - member.getMemberName(), - operation.getId() + error( + member, + trait, + format( + "This `%s` structure member is marked with the `hostLabel` trait, but no " + + "corresponding `endpoint` label could be found when used as the input of " + + "the `%s` operation.", + member.getMemberName(), + operation.getId() + ) ) - ) ); } } @@ -127,15 +127,15 @@ private List validateBindings( if (!labels.isEmpty()) { events.add( - error( - operation, - format( - "This operation uses %s as input, but the following host labels found in the operation's " - + "`endpoint` trait do not have a corresponding member marked with the `hostLabel` trait: %s", - input.getId(), - ValidationUtils.tickedList(labels) + error( + operation, + format( + "This operation uses %s as input, but the following host labels found in the operation's " + + "`endpoint` trait do not have a corresponding member marked with the `hostLabel` trait: %s", + input.getId(), + ValidationUtils.tickedList(labels) + ) ) - ) ); } @@ -143,28 +143,28 @@ private List validateBindings( } private Optional validateExpandedPattern( - OperationShape operation, - EndpointTrait endpoint + OperationShape operation, + EndpointTrait endpoint ) { // Replace all label portions with stubs so the hostPrefix // can be validated. String stubHostPrefix = endpoint.getHostPrefix() - .getSegments() - .stream() - .map(segment -> segment.isLabel() ? "foo" : segment.getContent()) - .collect(Collectors.joining()); + .getSegments() + .stream() + .map(segment -> segment.isLabel() ? "foo" : segment.getContent()) + .collect(Collectors.joining()); if (!EXPANDED_PATTERN.matcher(stubHostPrefix).matches()) { return Optional.of( - error( - operation, - endpoint, - format( - "The `endpoint` trait hostPrefix, %s, could " - + "not expand in to a valid RFC 3986 host: %s", - endpoint.getHostPrefix(), - stubHostPrefix + error( + operation, + endpoint, + format( + "The `endpoint` trait hostPrefix, %s, could " + + "not expand in to a valid RFC 3986 host: %s", + endpoint.getHostPrefix(), + stubHostPrefix + ) ) - ) ); } return Optional.empty(); @@ -174,7 +174,7 @@ private Optional validateTrailingPeriod(OperationShape operatio SmithyPattern hostPrefix = trait.getHostPrefix(); if (!hostPrefix.toString().endsWith(".") && !hostPrefix.getLabels().isEmpty()) { String message = "`endpoint` trait hostPrefix contains host labels and does not end in a period (`.`). " - + "This can result in clients inadvertently sending data to domains you do not control."; + + "This can result in clients inadvertently sending data to domains you do not control."; return Optional.of(danger(operation, trait, message)); } return Optional.empty(); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpApiKeyAuthTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpApiKeyAuthTraitValidator.java index d94dc943c84..c0738178b2a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpApiKeyAuthTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpApiKeyAuthTraitValidator.java @@ -29,15 +29,15 @@ public List validate(Model model) { trait.getScheme().ifPresent(scheme -> { if (trait.getIn() != HttpApiKeyAuthTrait.Location.HEADER) { events.add( - error( - serviceShape, - trait, - String.format( - "The httpApiKeyAuth trait must have an `in` value of `header` when a `scheme`" - + " is provided, found: %s", - trait.getIn() + error( + serviceShape, + trait, + String.format( + "The httpApiKeyAuth trait must have an `in` value of `header` when a `scheme`" + + " is provided, found: %s", + trait.getIn() + ) ) - ) ); } }); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpBindingTraitIgnoredValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpBindingTraitIgnoredValidator.java index 22dc0e7770c..0e2dd89fecf 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpBindingTraitIgnoredValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpBindingTraitIgnoredValidator.java @@ -52,21 +52,21 @@ */ public class HttpBindingTraitIgnoredValidator extends AbstractValidator { private static final List IGNORED_OUTSIDE_INPUT = ListUtils.of( - HttpLabelTrait.ID, - HttpQueryParamsTrait.ID, - HttpQueryTrait.ID + HttpLabelTrait.ID, + HttpQueryParamsTrait.ID, + HttpQueryTrait.ID ); private static final List IGNORED_OUTSIDE_OUTPUT = ListUtils.of( - HttpResponseCodeTrait.ID + HttpResponseCodeTrait.ID ); private static final List HTTP_MEMBER_BINDING_TRAITS = ListUtils.of( - HttpHeaderTrait.ID, - HttpLabelTrait.ID, - HttpPayloadTrait.ID, - HttpPrefixHeadersTrait.ID, - HttpQueryParamsTrait.ID, - HttpQueryTrait.ID, - HttpResponseCodeTrait.ID + HttpHeaderTrait.ID, + HttpLabelTrait.ID, + HttpPayloadTrait.ID, + HttpPrefixHeadersTrait.ID, + HttpQueryParamsTrait.ID, + HttpQueryTrait.ID, + HttpResponseCodeTrait.ID ); @Override @@ -101,10 +101,10 @@ public List validate(Model model) { } private List checkRelationships( - StructureShape containerShape, - MemberShape memberShape, - Map traits, - NeighborProvider reverse + StructureShape containerShape, + MemberShape memberShape, + Map traits, + NeighborProvider reverse ) { // Prepare which traits need relationship tracking for. Set ignoredOutsideInputTraits = new HashSet<>(traits.keySet()); @@ -127,12 +127,12 @@ private List checkRelationships( // Track if we've got a non-input relationship and a trait that's ignored outside input. // Continue so we don't emit a duplicate for non-top-level. if (relationship.getRelationshipType() != RelationshipType.INPUT - && !ignoredOutsideInputTraits.isEmpty() + && !ignoredOutsideInputTraits.isEmpty() ) { ignoredRelationships.merge( - relationship.getRelationshipType(), - ListUtils.of(relationship.getShape().getId()), - this::mergeShapeIdLists + relationship.getRelationshipType(), + ListUtils.of(relationship.getShape().getId()), + this::mergeShapeIdLists ); continue; } @@ -140,25 +140,25 @@ private List checkRelationships( // Track if we've got a non-output relationship and a trait that's ignored outside output. // Continue so we don't emit a duplicate for non-top-level. if (relationship.getRelationshipType() != RelationshipType.OUTPUT - && !ignoredOutsideOutputTraits.isEmpty() + && !ignoredOutsideOutputTraits.isEmpty() ) { ignoredRelationships.merge( - relationship.getRelationshipType(), - ListUtils.of(relationship.getShape().getId()), - this::mergeShapeIdLists + relationship.getRelationshipType(), + ListUtils.of(relationship.getShape().getId()), + this::mergeShapeIdLists ); continue; } // Track if there are non-top-level relationship and any HTTP member binding trait. if (relationship.getRelationshipType() != RelationshipType.INPUT - && relationship.getRelationshipType() != RelationshipType.OUTPUT - && relationship.getRelationshipType() != RelationshipType.ERROR + && relationship.getRelationshipType() != RelationshipType.OUTPUT + && relationship.getRelationshipType() != RelationshipType.ERROR ) { ignoredRelationships.merge( - relationship.getRelationshipType(), - ListUtils.of(relationship.getShape().getId()), - this::mergeShapeIdLists + relationship.getRelationshipType(), + ListUtils.of(relationship.getShape().getId()), + this::mergeShapeIdLists ); } } @@ -192,11 +192,11 @@ private List mergeShapeIdLists(List shapeIds1, List s } private ValidationEvent emit( - String type, - MemberShape memberShape, - Trait trait, - int checkedRelationshipCount, - Map> ignoredRelationships + String type, + MemberShape memberShape, + Trait trait, + int checkedRelationshipCount, + Map> ignoredRelationships ) { String mixedIn = memberShape.getMixins().isEmpty() ? "" : " mixed in"; String message = "The `%s` trait applied to this%s member is "; @@ -212,10 +212,10 @@ private String formatIgnoredRelationships(Map> i List relationshipTypeBindings = new ArrayList<>(); for (Map.Entry> ignoredRelationshipType : ignoredRelationships.entrySet()) { StringBuilder stringBuilder = new StringBuilder( - ignoredRelationshipType.getKey() - .toString() - .toLowerCase(Locale.US) - .replace("_", " ") + ignoredRelationshipType.getKey() + .toString() + .toLowerCase(Locale.US) + .replace("_", " ") ); Set bindings = new TreeSet<>(); for (ShapeId binding : ignoredRelationshipType.getValue()) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpBindingsMissingValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpBindingsMissingValidator.java index b73aa0de7d0..04e636a5121 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpBindingsMissingValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpBindingsMissingValidator.java @@ -35,8 +35,8 @@ public List validate(Model model) { TopDownIndex topDownIndex = TopDownIndex.of(model); return model.shapes(ServiceShape.class) - .flatMap(shape -> validateService(topDownIndex, model, shape).stream()) - .collect(Collectors.toList()); + .flatMap(shape -> validateService(topDownIndex, model, shape).stream()) + .collect(Collectors.toList()); } private List validateService(TopDownIndex topDownIndex, Model model, ServiceShape service) { @@ -59,15 +59,15 @@ private List validateService(TopDownIndex topDownIndex, Model m private ShapeId protocolWithBindings(ServiceShape service, Model model) { return ServiceIndex.of(model) - .getProtocols(service) - .values() - .stream() - .map(t -> model.expectShape(t.toShapeId())) - .map(s -> Pair.of(s.getId(), s.expectTrait(ProtocolDefinitionTrait.class))) - .filter(pair -> pair.getRight().getTraits().contains(HttpTrait.ID)) - .map(Pair::getLeft) - .findFirst() - .orElse(null); + .getProtocols(service) + .values() + .stream() + .map(t -> model.expectShape(t.toShapeId())) + .map(s -> Pair.of(s.getId(), s.expectTrait(ProtocolDefinitionTrait.class))) + .filter(pair -> pair.getRight().getTraits().contains(HttpTrait.ID)) + .map(Pair::getLeft) + .findFirst() + .orElse(null); } private boolean hasBindings(OperationShape op) { @@ -75,26 +75,26 @@ private boolean hasBindings(OperationShape op) { } private List validateOperations( - ServiceShape service, - Set operations, - Severity severity, - String reason + ServiceShape service, + Set operations, + Severity severity, + String reason ) { return operations.stream() - .filter(operation -> !operation.getTrait(HttpTrait.class).isPresent()) - .map( - operation -> createEvent( - severity, - operation, - operation.getSourceLocation(), - String.format( - "%s operations in the `%s` service define the `http` trait, but this " - + "operation is missing the `http` trait.", - reason, - service.getId() - ) + .filter(operation -> !operation.getTrait(HttpTrait.class).isPresent()) + .map( + operation -> createEvent( + severity, + operation, + operation.getSourceLocation(), + String.format( + "%s operations in the `%s` service define the `http` trait, but this " + + "operation is missing the `http` trait.", + reason, + service.getId() + ) + ) ) - ) - .collect(Collectors.toList()); + .collect(Collectors.toList()); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpHeaderTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpHeaderTraitValidator.java index 4ea72f4dfef..4c7acac2d9b 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpHeaderTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpHeaderTraitValidator.java @@ -30,105 +30,105 @@ public final class HttpHeaderTraitValidator extends AbstractValidator { /** Gather the allowed characters for HTTP headers (tchar from RFC 9110 section 5.6.2). **/ private static final Set TCHAR = SetUtils.of( - // "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - '!', - '#', - '$', - '%', - '&', - '\'', - '*', - '+', - '-', - '.', - '^', - '_', - '`', - '|', - '~', - // DIGIT (0-9) - '0', - '1', - '2', - '3', - '4', - '5', - '6', - '7', - '8', - '9', - // ALPHA (A-Z) - 'A', - 'B', - 'C', - 'D', - 'E', - 'F', - 'G', - 'H', - 'I', - 'J', - 'K', - 'L', - 'M', - 'N', - 'O', - 'P', - 'Q', - 'R', - 'S', - 'T', - 'U', - 'V', - 'W', - 'X', - 'Y', - 'Z', - // ALPHA (a-z) - 'a', - 'b', - 'c', - 'd', - 'e', - 'f', - 'g', - 'h', - 'i', - 'j', - 'k', - 'l', - 'm', - 'n', - 'o', - 'p', - 'q', - 'r', - 's', - 't', - 'u', - 'v', - 'w', - 'x', - 'y', - 'z' + // "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + '!', + '#', + '$', + '%', + '&', + '\'', + '*', + '+', + '-', + '.', + '^', + '_', + '`', + '|', + '~', + // DIGIT (0-9) + '0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + // ALPHA (A-Z) + 'A', + 'B', + 'C', + 'D', + 'E', + 'F', + 'G', + 'H', + 'I', + 'J', + 'K', + 'L', + 'M', + 'N', + 'O', + 'P', + 'Q', + 'R', + 'S', + 'T', + 'U', + 'V', + 'W', + 'X', + 'Y', + 'Z', + // ALPHA (a-z) + 'a', + 'b', + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i', + 'j', + 'k', + 'l', + 'm', + 'n', + 'o', + 'p', + 'q', + 'r', + 's', + 't', + 'u', + 'v', + 'w', + 'x', + 'y', + 'z' ); private static final Set BLOCKLIST = SetUtils.of( - "authorization", - "connection", - "content-length", - "expect", - "host", - "max-forwards", - "proxy-authenticate", - "server", - "te", - "trailer", - "transfer-encoding", - "upgrade", - "user-agent", - "www-authenticate", - "x-forwarded-for" + "authorization", + "connection", + "content-length", + "expect", + "host", + "max-forwards", + "proxy-authenticate", + "server", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "user-agent", + "www-authenticate", + "x-forwarded-for" ); @Override @@ -156,28 +156,28 @@ private Optional validateHeader(MemberShape member, HttpHeaderT if (BLOCKLIST.contains(header.toLowerCase(Locale.ENGLISH))) { return Optional.of( - danger( - member, - trait, - String.format( - "`%s` is not an allowed HTTP header binding", - header + danger( + member, + trait, + String.format( + "`%s` is not an allowed HTTP header binding", + header + ) ) - ) ); } for (int i = 0; i < header.length(); i++) { if (!TCHAR.contains(header.charAt(i))) { return Optional.of( - danger( - member, - trait, - String.format( - "`%s` is not a valid HTTP header field name according to section 5.6.2 of RFC 9110", - header + danger( + member, + trait, + String.format( + "`%s` is not a valid HTTP header field name according to section 5.6.2 of RFC 9110", + header + ) ) - ) ); } } @@ -187,29 +187,29 @@ private Optional validateHeader(MemberShape member, HttpHeaderT private List validateStructure(StructureShape structure) { return structure.getAllMembers() - .values() - .stream() - .filter(member -> member.hasTrait(HttpHeaderTrait.class)) - .collect( - groupingBy( - shape -> shape.expectTrait(HttpHeaderTrait.class).getValue().toLowerCase(Locale.US), - mapping(MemberShape::getMemberName, toList()) + .values() + .stream() + .filter(member -> member.hasTrait(HttpHeaderTrait.class)) + .collect( + groupingBy( + shape -> shape.expectTrait(HttpHeaderTrait.class).getValue().toLowerCase(Locale.US), + mapping(MemberShape::getMemberName, toList()) + ) ) - ) - .entrySet() - .stream() - .filter(entry -> entry.getValue().size() > 1) - .map( - entry -> error( - structure, - String.format( - "`httpHeader` field name binding conflicts found for the `%s` header in the " - + "following structure members: %s", - entry.getKey(), - ValidationUtils.tickedList(entry.getValue()) - ) + .entrySet() + .stream() + .filter(entry -> entry.getValue().size() > 1) + .map( + entry -> error( + structure, + String.format( + "`httpHeader` field name binding conflicts found for the `%s` header in the " + + "following structure members: %s", + entry.getKey(), + ValidationUtils.tickedList(entry.getValue()) + ) + ) ) - ) - .collect(toList()); + .collect(toList()); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpLabelTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpLabelTraitValidator.java index 0b268e0930c..98fe3b38c3e 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpLabelTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpLabelTraitValidator.java @@ -52,18 +52,18 @@ public List validate(Model model) { private List validateStructure(Model model, OperationShape operation, HttpTrait http) { return validateBindings( - model, - operation, - http, - model.expectShape(operation.getInputShape(), StructureShape.class) + model, + operation, + http, + model.expectShape(operation.getInputShape(), StructureShape.class) ); } private List validateBindings( - Model model, - OperationShape operation, - HttpTrait http, - StructureShape input + Model model, + OperationShape operation, + HttpTrait http, + StructureShape input ) { List events = new ArrayList<>(); @@ -71,10 +71,10 @@ private List validateBindings( // found. If any labels remain after looking at all members, then // there are unmatched labels. Set labels = http.getUri() - .getLabels() - .stream() - .map(UriPattern.Segment::getContent) - .collect(Collectors.toSet()); + .getLabels() + .stream() + .map(UriPattern.Segment::getContent) + .collect(Collectors.toSet()); for (MemberShape member : input.getAllMembers().values()) { member.getTrait(HttpLabelTrait.class).ifPresent(trait -> { @@ -83,35 +83,35 @@ private List validateBindings( // Emit an error if the member is not a valid label. if (!http.getUri().getLabel(member.getMemberName()).isPresent()) { events.add( - error( - member, - trait, - format( - "This `%s` structure member is marked with the `httpLabel` trait, but no " - + "corresponding `http` URI label could be found when used as the input of " - + "the `%s` operation.", - member.getMemberName(), - operation.getId() + error( + member, + trait, + format( + "This `%s` structure member is marked with the `httpLabel` trait, but no " + + "corresponding `http` URI label could be found when used as the input of " + + "the `%s` operation.", + member.getMemberName(), + operation.getId() + ) ) - ) ); } else if (http.getUri().getLabel(member.getMemberName()).get().isGreedyLabel()) { model.getShape(member.getTarget()).ifPresent(target -> { // Greedy labels must be strings. if (!target.isStringShape()) { events.add( - error( - member, - trait, - format( - "The `%s` structure member corresponds to a greedy label when used as the " - + "input of the `%s` operation. This member targets %s, but greedy labels " - + "must target string shapes.", - member.getMemberName(), - operation.getId(), - target + error( + member, + trait, + format( + "The `%s` structure member corresponds to a greedy label when used as the " + + "input of the `%s` operation. This member targets %s, but greedy labels " + + "must target string shapes.", + member.getMemberName(), + operation.getId(), + target + ) ) - ) ); } }); @@ -121,15 +121,15 @@ private List validateBindings( if (!labels.isEmpty()) { events.add( - error( - operation, - String.format( - "This operation uses `%s` as input, but the following URI labels found in the operation's " - + "`http` trait do not have a corresponding member marked with the `httpLabel` trait: %s", - input.getId(), - ValidationUtils.tickedList(labels) + error( + operation, + String.format( + "This operation uses `%s` as input, but the following URI labels found in the operation's " + + "`http` trait do not have a corresponding member marked with the `httpLabel` trait: %s", + input.getId(), + ValidationUtils.tickedList(labels) + ) ) - ) ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpMethodSemanticsValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpMethodSemanticsValidator.java index b32cfae962b..f8c5a09e25d 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpMethodSemanticsValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpMethodSemanticsValidator.java @@ -42,32 +42,32 @@ public final class HttpMethodSemanticsValidator extends AbstractValidator { * the validator will have no enforced semantic on a specific property. */ private static final Map EXPECTED = MapUtils.of( - "GET", - new HttpMethodSemantics(true, false, false, null), - "HEAD", - new HttpMethodSemantics(true, false, false, null), - "OPTIONS", - new HttpMethodSemantics( - true, - false, - true, - "OPTIONS requests are typically used as part of CORS and should not be modeled explicitly. They " - + "are an implementation detail that should not appear in generated client or server code. " - + "Instead, tooling should use the `cors` trait on a service to automatically configure CORS on " - + "clients and servers. It is the responsibility of service frameworks and API gateways to " - + "automatically manage OPTIONS requests. For example, OPTIONS requests are automatically " - + "created when using Smithy models with Amazon API Gateway." - ), - "TRACE", - new HttpMethodSemantics(true, false, false, null), - "POST", - new HttpMethodSemantics(false, null, true, null), - "DELETE", - new HttpMethodSemantics(false, true, false, null), - "PUT", - new HttpMethodSemantics(false, true, true, null), - "PATCH", - new HttpMethodSemantics(false, null, true, null) + "GET", + new HttpMethodSemantics(true, false, false, null), + "HEAD", + new HttpMethodSemantics(true, false, false, null), + "OPTIONS", + new HttpMethodSemantics( + true, + false, + true, + "OPTIONS requests are typically used as part of CORS and should not be modeled explicitly. They " + + "are an implementation detail that should not appear in generated client or server code. " + + "Instead, tooling should use the `cors` trait on a service to automatically configure CORS on " + + "clients and servers. It is the responsibility of service frameworks and API gateways to " + + "automatically manage OPTIONS requests. For example, OPTIONS requests are automatically " + + "created when using Smithy models with Amazon API Gateway." + ), + "TRACE", + new HttpMethodSemantics(true, false, false, null), + "POST", + new HttpMethodSemantics(false, null, true, null), + "DELETE", + new HttpMethodSemantics(false, true, false, null), + "PUT", + new HttpMethodSemantics(false, true, true, null), + "PATCH", + new HttpMethodSemantics(false, null, true, null) ); private static final String UNEXPECTED_PAYLOAD = "UnexpectedPayload"; @@ -92,9 +92,9 @@ public List validate(Model model) { } private List validateOperation( - HttpBindingIndex bindingIndex, - OperationShape shape, - HttpTrait trait + HttpBindingIndex bindingIndex, + OperationShape shape, + HttpTrait trait ) { String method = trait.getMethod().toUpperCase(Locale.US); @@ -108,15 +108,15 @@ private List validateOperation( // Emit a warning if the method is standard, but doesn't match standard casing. if (!EXPECTED.containsKey(trait.getMethod())) { events.add( - warning( - shape, - trait, - String.format( - "This operation uses the `%s` method in the `http` trait, but expected `%s`.", - trait.getMethod(), - method + warning( + shape, + trait, + String.format( + "This operation uses the `%s` method in the `http` trait, but expected `%s`.", + trait.getMethod(), + method + ) ) - ) ); } @@ -129,32 +129,32 @@ private List validateOperation( boolean isReadonly = shape.getTrait(ReadonlyTrait.class).isPresent(); if (semantics.isReadonly != null && semantics.isReadonly != isReadonly) { events.add( - warning( - shape, - trait, - String.format( - "This operation uses the `%s` method in the `http` trait, but %s marked with the readonly trait", - method, - isReadonly ? "is" : "is not" - ), - isReadonly ? UNNECESSARY_READONLY_TRAIT : MISSING_READONLY_TRAIT - ) + warning( + shape, + trait, + String.format( + "This operation uses the `%s` method in the `http` trait, but %s marked with the readonly trait", + method, + isReadonly ? "is" : "is not" + ), + isReadonly ? UNNECESSARY_READONLY_TRAIT : MISSING_READONLY_TRAIT + ) ); } boolean isIdempotent = shape.getTrait(IdempotentTrait.class).isPresent(); if (semantics.isIdempotent != null && semantics.isIdempotent != isIdempotent) { events.add( - warning( - shape, - trait, - String.format( - "This operation uses the `%s` method in the `http` trait, but %s marked with the idempotent trait", - method, - isIdempotent ? "is" : "is not" - ), - isIdempotent ? UNNECESSARY_IDEMPOTENT_TRAIT : MISSING_IDEMPOTENT_TRAIT - ) + warning( + shape, + trait, + String.format( + "This operation uses the `%s` method in the `http` trait, but %s marked with the idempotent trait", + method, + isIdempotent ? "is" : "is not" + ), + isIdempotent ? UNNECESSARY_IDEMPOTENT_TRAIT : MISSING_IDEMPOTENT_TRAIT + ) ); } @@ -163,40 +163,42 @@ private List validateOperation( if (semantics.allowsRequestPayload != null && !semantics.allowsRequestPayload) { if (!payloadBindings.isEmpty()) { events.add( - danger( - shape, - trait, - String.format( - "This operation uses the `%s` method in the `http` trait, but the `%s` member is sent as the " - + "payload of the request because it is marked with the `httpPayload` trait. Many HTTP " - + "clients do not support payloads with %1$s requests. Consider binding this member to " - + "other parts of the HTTP request such as a query string parameter using the `httpQuery` " - + "trait, a header using the `httpHeader` trait, or a path segment using the `httpLabel` " - + "trait.", - method, - payloadBindings.get(0).getMemberName() - ), - UNEXPECTED_PAYLOAD - ) + danger( + shape, + trait, + String.format( + "This operation uses the `%s` method in the `http` trait, but the `%s` member is sent as the " + + "payload of the request because it is marked with the `httpPayload` trait. Many HTTP " + + "clients do not support payloads with %1$s requests. Consider binding this member to " + + "other parts of the HTTP request such as a query string parameter using the `httpQuery` " + + "trait, a header using the `httpHeader` trait, or a path segment using the `httpLabel` " + + "trait.", + method, + payloadBindings.get(0).getMemberName() + ), + UNEXPECTED_PAYLOAD + ) ); } else if (!documentBindings.isEmpty()) { events.add( - danger( - shape, - trait, - String.format( - "This operation uses the `%s` method in the `http` trait, but the following members " - + "are sent as part of the payload of the request: %s. These members are sent as part " - + "of the payload because they are not explicitly configured to be sent in headers, in the " - + "query string, or in a URI segment. Many HTTP clients do not support payloads with %1$s " - + "requests. Consider binding these members to other parts of the HTTP request such as " - + "query string parameters using the `httpQuery` trait, headers using the `httpHeader` " - + "trait, or URI segments using the `httpLabel` trait.", - method, - ValidationUtils.tickedList(documentBindings.stream().map(HttpBinding::getMemberName)) - ), - UNEXPECTED_PAYLOAD - ) + danger( + shape, + trait, + String.format( + "This operation uses the `%s` method in the `http` trait, but the following members " + + "are sent as part of the payload of the request: %s. These members are sent as part " + + "of the payload because they are not explicitly configured to be sent in headers, in the " + + "query string, or in a URI segment. Many HTTP clients do not support payloads with %1$s " + + "requests. Consider binding these members to other parts of the HTTP request such as " + + "query string parameters using the `httpQuery` trait, headers using the `httpHeader` " + + "trait, or URI segments using the `httpLabel` trait.", + method, + ValidationUtils.tickedList( + documentBindings.stream().map(HttpBinding::getMemberName) + ) + ), + UNEXPECTED_PAYLOAD + ) ); } } @@ -211,10 +213,10 @@ private static final class HttpMethodSemantics { private final String warningWhenModeled; private HttpMethodSemantics( - Boolean isReadonly, - Boolean isIdempotent, - Boolean allowsRequestPayload, - String warningWhenModeled + Boolean isReadonly, + Boolean isIdempotent, + Boolean allowsRequestPayload, + String warningWhenModeled ) { this.isReadonly = isReadonly; this.isIdempotent = isIdempotent; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPayloadValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPayloadValidator.java index afd464c7f47..b4384d5480f 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPayloadValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPayloadValidator.java @@ -54,9 +54,9 @@ public List validate(Model model) { } private List validateOperation( - HttpBindingIndex bindings, - OperationIndex opIndex, - OperationShape shape + HttpBindingIndex bindings, + OperationIndex opIndex, + OperationShape shape ) { List events = new ArrayList<>(); validatePayload(shape.getId(), opIndex.expectInputShape(shape), bindings, true).ifPresent(events::add); @@ -66,35 +66,35 @@ private List validateOperation( private List validateError(StructureShape shape, HttpBindingIndex bindings) { return validatePayload(shape.getId(), shape, bindings, false) - .map(Collections::singletonList) - .orElseGet(Collections::emptyList); + .map(Collections::singletonList) + .orElseGet(Collections::emptyList); } private Optional validatePayload( - ShapeId subject, - StructureShape inputOrError, - HttpBindingIndex bindings, - boolean request + ShapeId subject, + StructureShape inputOrError, + HttpBindingIndex bindings, + boolean request ) { Map resolved = request - ? bindings.getRequestBindings(subject) - : bindings.getResponseBindings(subject); + ? bindings.getRequestBindings(subject) + : bindings.getResponseBindings(subject); Set unbound = resolved.entrySet() - .stream() - .filter(binding -> binding.getValue().getLocation() == HttpBinding.Location.UNBOUND) - .map(Map.Entry::getKey) - .collect(Collectors.toSet()); + .stream() + .filter(binding -> binding.getValue().getLocation() == HttpBinding.Location.UNBOUND) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); if (!unbound.isEmpty()) { return Optional.of( - error( - inputOrError, - String.format( - "A member of this structure is marked with the `httpPayload` trait, but the following " - + "structure members are not explicitly bound to the HTTP message: %s", - ValidationUtils.tickedList(unbound) + error( + inputOrError, + String.format( + "A member of this structure is marked with the `httpPayload` trait, but the following " + + "structure members are not explicitly bound to the HTTP message: %s", + ValidationUtils.tickedList(unbound) + ) ) - ) ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPrefixHeadersTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPrefixHeadersTraitValidator.java index 2ef46c975bf..150ca02a00c 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPrefixHeadersTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPrefixHeadersTraitValidator.java @@ -35,9 +35,9 @@ public List validate(Model model) { } private List validateMember( - StructureShape structure, - MemberShape member, - HttpPrefixHeadersTrait prefixTrait + StructureShape structure, + MemberShape member, + HttpPrefixHeadersTrait prefixTrait ) { List events = new ArrayList<>(); String prefix = prefixTrait.getValue().toLowerCase(Locale.ENGLISH); @@ -48,18 +48,18 @@ private List validateMember( String lowerCaseHeader = httpHeaderTrait.getValue().toLowerCase(Locale.ENGLISH); if (lowerCaseHeader.startsWith(prefix)) { events.add( - error( - otherMember, - httpHeaderTrait, - String.format( - "`httpHeader` binding of `%s` conflicts with the `httpPrefixHeaders` binding of `%s` " - + "to `%s`. `httpHeader` bindings must not case-insensitively start with any " - + "`httpPrefixHeaders` bindings.", - lowerCaseHeader, - member.getId(), - prefix + error( + otherMember, + httpHeaderTrait, + String.format( + "`httpHeader` binding of `%s` conflicts with the `httpPrefixHeaders` binding of `%s` " + + "to `%s`. `httpHeader` bindings must not case-insensitively start with any " + + "`httpPrefixHeaders` bindings.", + lowerCaseHeader, + member.getId(), + prefix + ) ) - ) ); } }); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpQueryParamsTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpQueryParamsTraitValidator.java index 06dfe2bf6f0..1990256eb9d 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpQueryParamsTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpQueryParamsTraitValidator.java @@ -37,14 +37,14 @@ private List validateQueryTraitUsage(Model model) { for (MemberShape member : model.getMemberShapesWithTrait(HttpQueryParamsTrait.class)) { model.getShape(member.getContainer()) - .flatMap(Shape::asStructureShape) - .ifPresent(structure -> { - // Gather the names of member shapes, as strings, that apply HttpQuery traits - List queryShapes = getMembersWithTrait(structure, HttpQueryTrait.class); - if (queryShapes.size() > 0) { - events.add(createNote(structure, member.getMemberName(), queryShapes)); - } - }); + .flatMap(Shape::asStructureShape) + .ifPresent(structure -> { + // Gather the names of member shapes, as strings, that apply HttpQuery traits + List queryShapes = getMembersWithTrait(structure, HttpQueryTrait.class); + if (queryShapes.size() > 0) { + events.add(createNote(structure, member.getMemberName(), queryShapes)); + } + }); } return events; @@ -62,16 +62,16 @@ private List getMembersWithTrait(StructureShape structure, Class queryShapes) { return note( - target, - String.format( - "Structure member `%s` is marked with the `httpQueryParams` trait, and " - + "`httpQuery` traits are applied to the following members: %s. The service will not be able to " - + "disambiguate between query string parameters intended for the `%s` member and those explicitly " - + "bound to the `httpQuery` members.", - queryParamsShape, - ValidationUtils.tickedList(queryShapes), - queryParamsShape - ) + target, + String.format( + "Structure member `%s` is marked with the `httpQueryParams` trait, and " + + "`httpQuery` traits are applied to the following members: %s. The service will not be able to " + + "disambiguate between query string parameters intended for the `%s` member and those explicitly " + + "bound to the `httpQuery` members.", + queryParamsShape, + ValidationUtils.tickedList(queryShapes), + queryParamsShape + ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpQueryTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpQueryTraitValidator.java index 11acfbf470a..9408b696f81 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpQueryTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpQueryTraitValidator.java @@ -48,9 +48,9 @@ private Map>> getQueryBindings(Model mod model.getShape(member.getContainer()).flatMap(Shape::asStructureShape).ifPresent(structure -> { HttpQueryTrait trait = member.expectTrait(HttpQueryTrait.class); queryBindings - .computeIfAbsent(structure, s -> new HashMap<>()) - .computeIfAbsent(trait.getValue(), v -> new HashSet<>()) - .add(member.getMemberName()); + .computeIfAbsent(structure, s -> new HashMap<>()) + .computeIfAbsent(trait.getValue(), v -> new HashSet<>()) + .add(member.getMemberName()); }); } @@ -58,8 +58,8 @@ private Map>> getQueryBindings(Model mod } private List validateBindings( - Map>> queryBindings, - Map> structureToOperations + Map>> queryBindings, + Map> structureToOperations ) { List events = new ArrayList<>(); @@ -68,22 +68,22 @@ private List validateBindings( // Emit if there are bindings on this shape for the same query string parameter. if (paramsToMembers.getValue().size() > 1) { events.add( - error( - entry.getKey(), - String.format( - "`httpQuery` parameter name binding conflicts found for the `%s` parameter in the " - + "following structure members: %s", - paramsToMembers.getKey(), - ValidationUtils.tickedList(paramsToMembers.getValue()) + error( + entry.getKey(), + String.format( + "`httpQuery` parameter name binding conflicts found for the `%s` parameter in the " + + "following structure members: %s", + paramsToMembers.getKey(), + ValidationUtils.tickedList(paramsToMembers.getValue()) + ) ) - ) ); } } List operations = structureToOperations.getOrDefault( - entry.getKey(), - Collections.emptyList() + entry.getKey(), + Collections.emptyList() ); for (OperationShape operation : operations) { UriPattern pattern = operation.expectTrait(HttpTrait.class).getUri(); @@ -91,15 +91,15 @@ private List validateBindings( String literalKey = literalEntry.getKey(); if (entry.getValue().containsKey(literalKey)) { events.add( - error( - entry.getKey(), - String.format( - "`httpQuery` name `%s` conflicts with the `http` trait of the `%s` operation: `%s`", - literalKey, - operation.getId(), - pattern + error( + entry.getKey(), + String.format( + "`httpQuery` name `%s` conflicts with the `http` trait of the `%s` operation: `%s`", + literalKey, + operation.getId(), + pattern + ) ) - ) ); } } @@ -114,11 +114,11 @@ private Map> getStructureToOperations(Model Map> structureToOperations = new HashMap<>(); for (OperationShape operation : model.getOperationShapesWithTrait(HttpTrait.class)) { index.getInput(operation) - .ifPresent( - structure -> structureToOperations - .computeIfAbsent(structure, key -> new ArrayList<>()) - .add(operation) - ); + .ifPresent( + structure -> structureToOperations + .computeIfAbsent(structure, key -> new ArrayList<>()) + .add(operation) + ); } return structureToOperations; } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpResponseCodeSemanticsValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpResponseCodeSemanticsValidator.java index 1f886b8b024..a9cdf7a8d3d 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpResponseCodeSemanticsValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpResponseCodeSemanticsValidator.java @@ -48,14 +48,14 @@ private Optional validateOperationsWithHttpTrait(Model model, O if (trait.getCode() == 204 || trait.getCode() == 205) { if (HttpBindingIndex.of(model).hasResponseBody(operation)) { return Optional.of( - warning( - operation, - String.format( - "The HTTP %d status code does not allow a response body. To use this status code, all output " - + "members need to be bound to @httpHeader, @httpPrefixHeaders, @httpResponseCode, etc.", - trait.getCode() + warning( + operation, + String.format( + "The HTTP %d status code does not allow a response body. To use this status code, all output " + + "members need to be bound to @httpHeader, @httpPrefixHeaders, @httpResponseCode, etc.", + trait.getCode() + ) ) - ) ); } } @@ -83,14 +83,14 @@ private Optional validateError(StructureShape shape, ErrorTrait private ValidationEvent invalidError(Shape shape, Trait trait, int code, String range, String errorValue) { return danger( - shape, - trait, - String.format( - "Expected an `httpError` code in the %s range for a `%s` error, but found %s", - range, - errorValue, - code - ) + shape, + trait, + String.format( + "Expected an `httpError` code in the %s range for a `%s` error, but found %s", + range, + errorValue, + code + ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpUriConflictValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpUriConflictValidator.java index 8ae2d3c7bea..f2bbbfda92b 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpUriConflictValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpUriConflictValidator.java @@ -45,8 +45,8 @@ public List validate(Model model) { } return model.shapes(ServiceShape.class) - .flatMap(shape -> validateService(model, shape).stream()) - .collect(Collectors.toList()); + .flatMap(shape -> validateService(model, shape).stream()) + .collect(Collectors.toList()); } private List validateService(Model model, ServiceShape service) { @@ -66,10 +66,10 @@ private List validateService(Model model, ServiceShape service) } private List checkConflicts( - Model model, - OperationShape operation, - HttpTrait httpTrait, - List operations + Model model, + OperationShape operation, + HttpTrait httpTrait, + List operations ) { String method = httpTrait.getMethod(); UriPattern pattern = httpTrait.getUri(); @@ -82,8 +82,8 @@ private List checkConflicts( if (other != operation && other.hasTrait(HttpTrait.class)) { HttpTrait otherHttpTrait = other.expectTrait(HttpTrait.class); if (otherHttpTrait.getMethod().equals(method) - && otherHttpTrait.getUri().conflictsWith(pattern) - && endpointConflicts(model, operation, other)) { + && otherHttpTrait.getUri().conflictsWith(pattern) + && endpointConflicts(model, operation, other)) { // Now that we know we have a conflict, determine whether it is allowable or not. if (isAllowableConflict(model, operation, other)) { allowableConflicts.add(Pair.of(other.getId(), otherHttpTrait.getUri())); @@ -103,8 +103,8 @@ && endpointConflicts(model, operation, other)) { // Allowable conflicts get turned into DANGERs, which must at least be acknowledged with a suppression. if (!allowableConflicts.isEmpty()) { String message = formatConflicts(pattern, allowableConflicts) - + ". Pattern traits applied to the label members prevent the label value from evaluating to a " - + "conflict, but this is still a poor design. If this is acceptable, this can be suppressed."; + + ". Pattern traits applied to the label members prevent the label value from evaluating to a " + + "conflict, but this is still a poor design. If this is acceptable, this can be suppressed."; events.add(danger(operation, message)); } @@ -127,12 +127,12 @@ private boolean endpointConflicts(Model model, OperationShape operation, Operati SmithyPattern prefix = operation.getTrait(EndpointTrait.class).get().getHostPrefix(); SmithyPattern otherPrefix = otherOperation.getTrait(EndpointTrait.class).get().getHostPrefix(); boolean allowable = !isAllowableConflict( - model, - prefix, - operation, - otherPrefix, - otherOperation, - this::getHostLabelPatterns + model, + prefix, + operation, + otherPrefix, + otherOperation, + this::getHostLabelPatterns ); return allowable; } @@ -141,22 +141,22 @@ private boolean isAllowableConflict(Model model, OperationShape operation, Opera UriPattern uriPattern = operation.getTrait(HttpTrait.class).get().getUri(); UriPattern otherUriPattern = otherOperation.getTrait(HttpTrait.class).get().getUri(); return isAllowableConflict( - model, - uriPattern, - operation, - otherUriPattern, - otherOperation, - this::getHttpLabelPatterns + model, + uriPattern, + operation, + otherUriPattern, + otherOperation, + this::getHttpLabelPatterns ); } private boolean isAllowableConflict( - Model model, - SmithyPattern pattern, - OperationShape operation, - SmithyPattern otherPattern, - OperationShape otherOperation, - BiFunction> getLabelPatterns + Model model, + SmithyPattern pattern, + OperationShape operation, + SmithyPattern otherPattern, + OperationShape otherOperation, + BiFunction> getLabelPatterns ) { Map conflictingLabelSegments = pattern.getConflictingLabelSegmentsMap(otherPattern); @@ -170,47 +170,47 @@ private boolean isAllowableConflict( Map otherLabelPatterns = getLabelPatterns.apply(model, otherOperation); return conflictingLabelSegments.entrySet() - .stream() - // Only allow conflicts in cases where one of the segments is static and the other is a label. - .filter(conflict -> conflict.getKey().isLabel() != conflict.getValue().isLabel()) - // Only allow the uris to conflict if every conflicting segment is allowable. - .allMatch(conflict -> { - Pattern p; - String staticSegment; - - if (conflict.getKey().isLabel()) { - p = labelPatterns.get(conflict.getKey().getContent()); - staticSegment = conflict.getValue().getContent(); - } else { - p = otherLabelPatterns.get(conflict.getValue().getContent()); - staticSegment = conflict.getKey().getContent(); - } + .stream() + // Only allow conflicts in cases where one of the segments is static and the other is a label. + .filter(conflict -> conflict.getKey().isLabel() != conflict.getValue().isLabel()) + // Only allow the uris to conflict if every conflicting segment is allowable. + .allMatch(conflict -> { + Pattern p; + String staticSegment; + + if (conflict.getKey().isLabel()) { + p = labelPatterns.get(conflict.getKey().getContent()); + staticSegment = conflict.getValue().getContent(); + } else { + p = otherLabelPatterns.get(conflict.getValue().getContent()); + staticSegment = conflict.getKey().getContent(); + } - if (p == null) { - return false; - } + if (p == null) { + return false; + } - // If the pattern on the label segment does not match the static segment, then this segment's - // conflict is allowable. - return !p.matcher(staticSegment).find(); - }); + // If the pattern on the label segment does not match the static segment, then this segment's + // conflict is allowable. + return !p.matcher(staticSegment).find(); + }); } private Map getHttpLabelPatterns(Model model, OperationShape operation) { return HttpBindingIndex.of(model) - .getRequestBindings(operation) - .entrySet() - .stream() - .filter(entry -> entry.getValue().getLocation().equals(HttpBinding.Location.LABEL)) - .flatMap( - entry -> OptionalUtils.stream( - entry.getValue() - .getMember() - .getMemberTrait(model, PatternTrait.class) - .map(pattern -> Pair.of(entry.getKey(), pattern.getPattern())) + .getRequestBindings(operation) + .entrySet() + .stream() + .filter(entry -> entry.getValue().getLocation().equals(HttpBinding.Location.LABEL)) + .flatMap( + entry -> OptionalUtils.stream( + entry.getValue() + .getMember() + .getMemberTrait(model, PatternTrait.class) + .map(pattern -> Pair.of(entry.getKey(), pattern.getPattern())) + ) ) - ) - .collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); + .collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); } private Map getHostLabelPatterns(Model model, OperationShape operation) { @@ -225,14 +225,14 @@ private Map getHostLabelPatterns(Model model, OperationShape op private String formatConflicts(UriPattern pattern, List> conflicts) { String conflictString = conflicts.stream() - .map(conflict -> String.format("`%s` (%s)", conflict.getLeft(), conflict.getRight())) - .sorted() - .collect(Collectors.joining(", ")); + .map(conflict -> String.format("`%s` (%s)", conflict.getLeft(), conflict.getRight())) + .sorted() + .collect(Collectors.joining(", ")); return String.format( - "Operation URI, `%s`, conflicts with other operation URIs in the same service: [%s]", - pattern, - conflictString + "Operation URI, `%s`, conflicts with other operation URIs in the same service: [%s]", + pattern, + conflictString ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpUriGreedyLabelValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpUriGreedyLabelValidator.java index 49fbb479d56..fa41e4dbe9b 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpUriGreedyLabelValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpUriGreedyLabelValidator.java @@ -41,22 +41,22 @@ public List validate(Model model) { for (int j = i + 1; j < segments.size(); j++) { if (segments.get(j).isGreedyLabel()) { events.add( - danger( - shape, - trait, - "At most one greedy label segment may exist in a pattern: " + pattern, - MULTIPLE_GREEDY_LABELS - ) + danger( + shape, + trait, + "At most one greedy label segment may exist in a pattern: " + pattern, + MULTIPLE_GREEDY_LABELS + ) ); } if (segments.get(j).isLabel()) { events.add( - danger( - shape, - trait, - "A greedy label must be the last label in its pattern: " + pattern, - GREEDY_LABEL_IS_NOT_LAST_LABEL - ) + danger( + shape, + trait, + "A greedy label must be the last label in its pattern: " + pattern, + GREEDY_LABEL_IS_NOT_LAST_LABEL + ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/IdempotencyTokenIgnoredValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/IdempotencyTokenIgnoredValidator.java index 9239ab3fd16..7ec3f6d2e77 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/IdempotencyTokenIgnoredValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/IdempotencyTokenIgnoredValidator.java @@ -53,11 +53,11 @@ public List validate(Model model) { } private void checkRelationships( - StructureShape containerShape, - MemberShape memberShape, - Trait trait, - NeighborProvider reverse, - List events + StructureShape containerShape, + MemberShape memberShape, + Trait trait, + NeighborProvider reverse, + List events ) { // Store relationships so we can emit one event per ignored binding. @@ -70,7 +70,7 @@ private void checkRelationships( } if (relationship.getRelationshipType() != RelationshipType.INPUT) { ignoredRelationships.computeIfAbsent(relationship.getRelationshipType(), x -> new ArrayList<>()) - .add(relationship.getShape().getId()); + .add(relationship.getShape().getId()); } } @@ -81,13 +81,13 @@ private void checkRelationships( } private ValidationEvent emit( - MemberShape memberShape, - Trait trait, - Map> ignoredRelationships + MemberShape memberShape, + Trait trait, + Map> ignoredRelationships ) { String message = "The `idempotencyToken` trait only has an effect when applied to a top-level operation input member, " - + "but it was applied and ignored in the following contexts: " - + formatIgnoredRelationships(ignoredRelationships); + + "but it was applied and ignored in the following contexts: " + + formatIgnoredRelationships(ignoredRelationships); return warning(memberShape, trait, message); } @@ -95,15 +95,15 @@ private String formatIgnoredRelationships(Map> i List relationshipTypeBindings = new ArrayList<>(); for (Map.Entry> ignoredRelationshipType : ignoredRelationships.entrySet()) { StringBuilder buf = new StringBuilder( - ignoredRelationshipType.getKey() - .toString() - .toLowerCase(Locale.US) - .replace("_", " ") + ignoredRelationshipType.getKey() + .toString() + .toLowerCase(Locale.US) + .replace("_", " ") ); Set bindings = ignoredRelationshipType.getValue() - .stream() - .map(ShapeId::toString) - .collect(Collectors.toCollection(TreeSet::new)); + .stream() + .map(ShapeId::toString) + .collect(Collectors.toCollection(TreeSet::new)); buf.append(": [").append(String.join(", ", bindings)).append("]"); relationshipTypeBindings.add(buf.toString()); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/JsonNameValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/JsonNameValidator.java index 908f80f8641..6535a836f35 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/JsonNameValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/JsonNameValidator.java @@ -41,22 +41,25 @@ private void validateMembersOfContainer(Shape container, List e Map> memberMappings = new TreeMap<>(); for (MemberShape m : container.members()) { String jsonName = m.getTrait(JsonNameTrait.class) - .map(JsonNameTrait::getValue) - .orElseGet(m::getMemberName); + .map(JsonNameTrait::getValue) + .orElseGet(m::getMemberName); memberMappings.computeIfAbsent(jsonName, n -> new TreeSet<>()).add(m); } for (Map.Entry> entry : memberMappings.entrySet()) { if (entry.getValue().size() > 1) { events.add( - error( - container, - String.format( - "This shape contains members with conflicting JSON names that resolve to '%s': %s", - entry.getKey(), - entry.getValue().stream().map(MemberShape::getMemberName).collect(Collectors.joining(", ")) + error( + container, + String.format( + "This shape contains members with conflicting JSON names that resolve to '%s': %s", + entry.getKey(), + entry.getValue() + .stream() + .map(MemberShape::getMemberName) + .collect(Collectors.joining(", ")) + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/LengthTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/LengthTraitValidator.java index 4c291470766..c80633423aa 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/LengthTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/LengthTraitValidator.java @@ -27,27 +27,27 @@ public List validate(Model model) { private List validateLengthTrait(Shape shape, LengthTrait trait) { List events = new ArrayList<>(); trait.getMin() - .filter(min -> min < 0) - .map(min -> error(shape, trait, "A length trait is applied with a negative `min` value.")) - .ifPresent(events::add); + .filter(min -> min < 0) + .map(min -> error(shape, trait, "A length trait is applied with a negative `min` value.")) + .ifPresent(events::add); trait.getMax() - .filter(max -> max < 0) - .map(max -> error(shape, trait, "A length trait is applied with a negative `max` value.")) - .ifPresent(events::add); + .filter(max -> max < 0) + .map(max -> error(shape, trait, "A length trait is applied with a negative `max` value.")) + .ifPresent(events::add); trait.getMin() - .flatMap(min -> trait.getMax().map(max -> Pair.of(min, max))) - .filter(pair -> pair.getLeft() > pair.getRight()) - .map( - pair -> error( - shape, - trait, - "A length trait is applied with a `min` value greater than " - + "its `max` value." + .flatMap(min -> trait.getMax().map(max -> Pair.of(min, max))) + .filter(pair -> pair.getLeft() > pair.getRight()) + .map( + pair -> error( + shape, + trait, + "A length trait is applied with a `min` value greater than " + + "its `max` value." + ) ) - ) - .map(events::add); + .map(events::add); return events; } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/MediaTypeValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/MediaTypeValidator.java index ade2ff4f87f..9bf29d88dc1 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/MediaTypeValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/MediaTypeValidator.java @@ -31,15 +31,15 @@ private Optional validateMediaType(Shape shape, MediaTypeTrait return Optional.empty(); } catch (RuntimeException e) { return Optional.of( - error( - shape, - trait, - String.format( - "Invalid mediaType value, \"%s\": %s", - trait.getValue(), - e.getMessage() + error( + shape, + trait, + String.format( + "Invalid mediaType value, \"%s\": %s", + trait.getValue(), + e.getMessage() + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/MemberShouldReferenceResourceValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/MemberShouldReferenceResourceValidator.java index b03c5e0c184..98db39bd0b4 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/MemberShouldReferenceResourceValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/MemberShouldReferenceResourceValidator.java @@ -53,14 +53,14 @@ public List validate(Model model) { Set potentialReferences = computePotentialReferences(model, member); if (!potentialReferences.isEmpty()) { events.add( - warning( - member, - format( - "This member appears to reference the following resources without " - + "being included in a `@references` trait: [%s]", - ValidationUtils.tickedList(potentialReferences) + warning( + member, + format( + "This member appears to reference the following resources without " + + "being included in a `@references` trait: [%s]", + ValidationUtils.tickedList(potentialReferences) + ) ) - ) ); } } @@ -106,14 +106,14 @@ private Set computePotentialReferences(Model model, MemberShape member) } private void computeResourcesToIgnore( - Model model, - MemberShape member, - ResourceShape resource, - Set resourcesToIgnore + Model model, + MemberShape member, + ResourceShape resource, + Set resourcesToIgnore ) { // Exclude actually bound members via searching with a PathFinder. List resourceMemberPaths = PathFinder.create(model) - .search(resource, ListUtils.of(member)); + .search(resource, ListUtils.of(member)); if (!resourceMemberPaths.isEmpty()) { // This member is already bound to a resource, so we don't need a references trait for it. // In addition, we should not tell users to add a references trait for other resources that @@ -133,7 +133,7 @@ private void computeResourcesToIgnore( private void ignoreReferencedResources(Shape shape, Set resourcesToIgnore) { if (shape.hasTrait(ReferencesTrait.class)) { for (ReferencesTrait.Reference reference : shape.expectTrait(ReferencesTrait.class) - .getReferences()) { + .getReferences()) { resourcesToIgnore.add(reference.getResource()); } } @@ -142,6 +142,6 @@ private void ignoreReferencedResources(Shape shape, Set resourcesToIgno private boolean isIdentifierMatch(ResourceShape resource, MemberShape member) { Map identifiers = resource.getIdentifiers(); return identifiers.containsKey(member.getMemberName()) - && identifiers.get(member.getMemberName()).equals(member.getTarget()); + && identifiers.get(member.getMemberName()).equals(member.getTarget()); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/NoInlineDocumentSupportValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/NoInlineDocumentSupportValidator.java index 3eb144853b6..902c487b94a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/NoInlineDocumentSupportValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/NoInlineDocumentSupportValidator.java @@ -86,14 +86,14 @@ private ValidationEvent createEvent(ServiceShape service, Trait protocol, Set validate(Model model) { } private void validateInputOutput( - Set shapes, - NeighborProvider reverseProvider, - List events, - String descriptor, - String invalid + Set shapes, + NeighborProvider reverseProvider, + List events, + String descriptor, + String invalid ) { for (Shape shape : shapes) { Set operations = new HashSet<>(); @@ -99,62 +99,62 @@ private void validateInputOutput( } private ValidationEvent emitInvalidOperationBinding( - Shape operation, - Shape target, - String property, - String invalid + Shape operation, + Shape target, + String property, + String invalid ) { return ValidationEvent.builder() - .id(OPERATION_INPUT_OUTPUT_MISUSE) - .severity(Severity.ERROR) - .shape(operation) - .message( - String.format( - "Operation `%s` cannot target structures marked with the `@%s` trait: `%s`", - property, - invalid, - target.getId() + .id(OPERATION_INPUT_OUTPUT_MISUSE) + .severity(Severity.ERROR) + .shape(operation) + .message( + String.format( + "Operation `%s` cannot target structures marked with the `@%s` trait: `%s`", + property, + invalid, + target.getId() + ) ) - ) - .build(); + .build(); } private ValidationEvent emitInvalidMemberRef(MemberShape member, String trait) { return ValidationEvent.builder() - .id(OPERATION_INPUT_OUTPUT_MISUSE) - .severity(Severity.ERROR) - .shape(member) - .message("Members cannot target structures marked with the @" + trait + " trait: " + member.getTarget()) - .build(); + .id(OPERATION_INPUT_OUTPUT_MISUSE) + .severity(Severity.ERROR) + .shape(member) + .message("Members cannot target structures marked with the @" + trait + " trait: " + member.getTarget()) + .build(); } private ValidationEvent emitMultipleUses(Shape shape, String descriptor, Set operations) { return ValidationEvent.builder() - .id(OPERATION_INPUT_OUTPUT_MISUSE) - .severity(Severity.ERROR) - .shape(shape) - .message( - "Shapes marked with the @" + descriptor + " trait cannot be used as " + descriptor + " by " - + "multiple operations: " + ValidationUtils.tickedList(operations) - ) - .build(); + .id(OPERATION_INPUT_OUTPUT_MISUSE) + .severity(Severity.ERROR) + .shape(shape) + .message( + "Shapes marked with the @" + descriptor + " trait cannot be used as " + descriptor + " by " + + "multiple operations: " + ValidationUtils.tickedList(operations) + ) + .build(); } private ValidationEvent emitBadInputOutputName(Shape operation, String property, ShapeId target) { return ValidationEvent.builder() - .severity(Severity.WARNING) - .shape(operation) - .id(OPERATION_INPUT_OUTPUT_NAME + "." + property) - .message( - String.format( - "The %s of this operation should target a shape that starts with the operation's name, '%s', " - + "but the targeted shape is `%s`", - property, - operation.getId().getName(), - target + .severity(Severity.WARNING) + .shape(operation) + .id(OPERATION_INPUT_OUTPUT_NAME + "." + property) + .message( + String.format( + "The %s of this operation should target a shape that starts with the operation's name, '%s', " + + "but the targeted shape is `%s`", + property, + operation.getId().getName(), + target + ) ) - ) - .build(); + .build(); } private void validateOperationNameAmbiguity(Model model, OperationShape operation, List events) { @@ -180,26 +180,26 @@ private void validateOperationNameAmbiguity(Model model, OperationShape operatio } private ValidationEvent createAmbiguousEvent( - Shape ambiguousShape, - OperationShape operation, - ShapeId ioShape, - String descriptor + Shape ambiguousShape, + OperationShape operation, + ShapeId ioShape, + String descriptor ) { return ValidationEvent.builder() - .id(OPERATION_NAME_AMBIGUITY) - .shape(ambiguousShape) - .severity(Severity.WARNING) - .message( - String.format( - "The name of this shape implies that it is the %1$s of %2$s, but that operation uses %3$s " - + "for %1$s. This kind of ambiguity can confuse developers calling this operation and can " - + "cause issues in code generators that use similar naming conventions to generate %1$s " - + "types.", - descriptor, - operation.getId(), - ioShape + .id(OPERATION_NAME_AMBIGUITY) + .shape(ambiguousShape) + .severity(Severity.WARNING) + .message( + String.format( + "The name of this shape implies that it is the %1$s of %2$s, but that operation uses %3$s " + + "for %1$s. This kind of ambiguity can confuse developers calling this operation and can " + + "cause issues in code generators that use similar naming conventions to generate %1$s " + + "types.", + descriptor, + operation.getId(), + ioShape + ) ) - ) - .build(); + .build(); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PaginatedTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PaginatedTraitValidator.java index efe154cbed4..eda7b3a39a6 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PaginatedTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PaginatedTraitValidator.java @@ -46,15 +46,15 @@ public final class PaginatedTraitValidator extends AbstractValidator { private static final Set ITEM_SHAPES = SetUtils.of(ShapeType.LIST, ShapeType.MAP); private static final Set PAGE_SHAPES = SetUtils.of( - ShapeType.BYTE, - ShapeType.INTEGER, - ShapeType.LONG, - ShapeType.SHORT + ShapeType.BYTE, + ShapeType.INTEGER, + ShapeType.LONG, + ShapeType.SHORT ); private static final Set DANGER_PAGE_SHAPES = SetUtils.of( - ShapeType.BYTE, - ShapeType.LONG, - ShapeType.SHORT + ShapeType.BYTE, + ShapeType.LONG, + ShapeType.SHORT ); private static final Set TOKEN_SHAPES = SetUtils.of(ShapeType.STRING, ShapeType.MAP); private static final Set DANGER_TOKEN_SHAPES = SetUtils.of(ShapeType.MAP); @@ -78,11 +78,11 @@ public List validate(Model model) { } private List validateOperation( - Model model, - TopDownIndex topDownIndex, - OperationIndex opIndex, - OperationShape operation, - PaginatedTrait trait + Model model, + TopDownIndex topDownIndex, + OperationIndex opIndex, + OperationShape operation, + PaginatedTrait trait ) { List events = new ArrayList<>(); @@ -91,22 +91,22 @@ private List validateOperation( PageSizeValidator pageSizeValidator = new PageSizeValidator(); events.addAll(validateMember(opIndex, model, null, operation, trait, pageSizeValidator)); pageSizeValidator.getMember(model, opIndex, operation, trait) - .filter(MemberShape::isRequired) - .ifPresent( - member -> events.add( - warning( - operation, - trait, - String.format( - "paginated trait `%s` member `%s` should not be required", - pageSizeValidator.propertyName(), - member.getMemberName() - ), - SHOULD_NOT_BE_REQUIRED, - pageSizeValidator.propertyName() - ) - ) - ); + .filter(MemberShape::isRequired) + .ifPresent( + member -> events.add( + warning( + operation, + trait, + String.format( + "paginated trait `%s` member `%s` should not be required", + pageSizeValidator.propertyName(), + member.getMemberName() + ), + SHOULD_NOT_BE_REQUIRED, + pageSizeValidator.propertyName() + ) + ) + ); // Validate output. events.addAll(validateMember(opIndex, model, null, operation, trait, new OutputTokenValidator())); @@ -129,75 +129,75 @@ private List validateOperation( } private List validateMember( - OperationIndex opIndex, - Model model, - ServiceShape service, - OperationShape operation, - PaginatedTrait trait, - PropertyValidator validator + OperationIndex opIndex, + Model model, + ServiceShape service, + OperationShape operation, + PaginatedTrait trait, + PropertyValidator validator ) { String prefix = service != null ? "When bound within the `" + service.getId() + "` service, " : ""; String memberPath = validator.getMemberPath(opIndex, operation, trait).orElse(null); if (memberPath == null) { return service != null && validator.isRequiredToBePresent() - ? Collections.singletonList( - error( - operation, - trait, - String.format( - "%spaginated trait `%s` is not configured", - prefix, - validator.propertyName() - ) + ? Collections.singletonList( + error( + operation, + trait, + String.format( + "%spaginated trait `%s` is not configured", + prefix, + validator.propertyName() + ) + ) ) - ) - : Collections.emptyList(); + : Collections.emptyList(); } if (!validator.pathsAllowed() && memberPath.contains(".")) { return Collections.singletonList( - error( - operation, - trait, - String.format( - "%spaginated trait `%s` does not allow path values", - prefix, - validator.propertyName() + error( + operation, + trait, + String.format( + "%spaginated trait `%s` does not allow path values", + prefix, + validator.propertyName() + ) ) - ) ); } MemberShape member = validator.getMember(model, opIndex, operation, trait).orElse(null); if (member == null) { return Collections.singletonList( - error( - operation, - trait, - String.format( - "%spaginated trait `%s` targets a member `%s` that does not exist", - prefix, - validator.propertyName(), - memberPath + error( + operation, + trait, + String.format( + "%spaginated trait `%s` targets a member `%s` that does not exist", + prefix, + validator.propertyName(), + memberPath + ) ) - ) ); } List events = new ArrayList<>(); if (validator.mustBeOptional() && member.isRequired()) { events.add( - error( - operation, - trait, - String.format( - "%spaginated trait `%s` member `%s` must not be required", - prefix, - validator.propertyName(), - member.getMemberName() + error( + operation, + trait, + String.format( + "%spaginated trait `%s` member `%s` must not be required", + prefix, + validator.propertyName(), + member.getMemberName() + ) ) - ) ); } @@ -205,19 +205,19 @@ private List validateMember( if (target != null) { if (!validator.validTargets().contains(target.getType())) { events.add( - error( - operation, - trait, - String.format( - "%spaginated trait `%s` member `%s` targets a %s shape, but must target one of " - + "the following: [%s]", - prefix, - validator.propertyName(), - member.getId().getMember().get(), - target.getType(), - ValidationUtils.tickedList(validator.validTargets()) + error( + operation, + trait, + String.format( + "%spaginated trait `%s` member `%s` targets a %s shape, but must target one of " + + "the following: [%s]", + prefix, + validator.propertyName(), + member.getId().getMember().get(), + target.getType(), + ValidationUtils.tickedList(validator.validTargets()) + ) ) - ) ); } if (validator.dangerTargets().contains(target.getType())) { @@ -227,39 +227,39 @@ private List validateMember( String memberName = member.getId().getMember().get(); String targetType = target.getType().toString(); events.add( - danger( - operation, - trait, - String.format( - "%spaginated trait `%s` member `%s` targets a %s shape, but this is not recommended. " - + "One of [%s] SHOULD be targeted.", - prefix, - traitName, - memberName, - targetType, - ValidationUtils.tickedList(preferredTargets) - ), - WRONG_SHAPE_TYPE, - traitName - ) + danger( + operation, + trait, + String.format( + "%spaginated trait `%s` member `%s` targets a %s shape, but this is not recommended. " + + "One of [%s] SHOULD be targeted.", + prefix, + traitName, + memberName, + targetType, + ValidationUtils.tickedList(preferredTargets) + ), + WRONG_SHAPE_TYPE, + traitName + ) ); } } if (validator.pathsAllowed() && PATH_PATTERN.split(memberPath).length > 2) { events.add( - warning( - operation, - trait, - String.format( - "%spaginated trait `%s` contains a path with more than two parts, which can make your API " - + "cumbersome to use", - prefix, - validator.propertyName() - ), - DEEPLY_NESTED, - validator.propertyName() - ) + warning( + operation, + trait, + String.format( + "%spaginated trait `%s` contains a path with more than two parts, which can make your API " + + "cumbersome to use", + prefix, + validator.propertyName() + ), + DEEPLY_NESTED, + validator.propertyName() + ) ); } @@ -282,10 +282,10 @@ Set dangerTargets() { abstract Optional getMemberPath(OperationIndex opIndex, OperationShape operation, PaginatedTrait trait); abstract Optional getMember( - Model model, - OperationIndex opIndex, - OperationShape operation, - PaginatedTrait trait + Model model, + OperationIndex opIndex, + OperationShape operation, + PaginatedTrait trait ); boolean pathsAllowed() { @@ -301,20 +301,20 @@ boolean pathsAllowed() { } Optional getMember( - Model model, - OperationIndex opIndex, - OperationShape operation, - PaginatedTrait trait + Model model, + OperationIndex opIndex, + OperationShape operation, + PaginatedTrait trait ) { StructureShape outputShape = opIndex.expectOutputShape(operation); return getMemberPath(opIndex, operation, trait) - .map(path -> PaginatedTrait.resolveFullPath(path, model, outputShape)) - .flatMap(memberShapes -> { - if (memberShapes.size() == 0) { - return Optional.empty(); - } - return Optional.of(memberShapes.get(memberShapes.size() - 1)); - }); + .map(path -> PaginatedTrait.resolveFullPath(path, model, outputShape)) + .flatMap(memberShapes -> { + if (memberShapes.size() == 0) { + return Optional.empty(); + } + return Optional.of(memberShapes.get(memberShapes.size() - 1)); + }); } } @@ -344,10 +344,10 @@ Optional getMemberPath(OperationIndex opIndex, OperationShape operation, } Optional getMember( - Model model, - OperationIndex opIndex, - OperationShape operation, - PaginatedTrait trait + Model model, + OperationIndex opIndex, + OperationShape operation, + PaginatedTrait trait ) { StructureShape input = opIndex.expectInputShape(operation); return getMemberPath(opIndex, operation, trait).flatMap(input::getMember); @@ -406,10 +406,10 @@ Optional getMemberPath(OperationIndex opIndex, OperationShape operation, } Optional getMember( - Model model, - OperationIndex opIndex, - OperationShape operation, - PaginatedTrait trait + Model model, + OperationIndex opIndex, + OperationShape operation, + PaginatedTrait trait ) { StructureShape input = opIndex.expectInputShape(operation); return getMemberPath(opIndex, operation, trait).flatMap(input::getMember); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PatternTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PatternTraitValidator.java index e1e3f08c9a6..174b8083f57 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PatternTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PatternTraitValidator.java @@ -42,17 +42,17 @@ private void validatePatternTrait(List events, Shape shape) { sj.add("trailing '$'"); } events.add( - warning( - shape, - trait, - String.format( - "A pattern trait is applied without a %s, meaning only part of the string must match the regular " - + "expression. Explicitly anchoring regular expressions is preferable because it is more " - + "restrictive by default and does not require modelers to understand that Smithy patterns are " - + "not automatically anchored.", - sj + warning( + shape, + trait, + String.format( + "A pattern trait is applied without a %s, meaning only part of the string must match the regular " + + "expression. Explicitly anchoring regular expressions is preferable because it is more " + + "restrictive by default and does not require modelers to understand that Smithy patterns are " + + "not automatically anchored.", + sj + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PrivateAccessValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PrivateAccessValidator.java index 84a46a3907e..7370159b3e7 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PrivateAccessValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PrivateAccessValidator.java @@ -48,9 +48,9 @@ private void validateNeighbors(Shape shape, List relationships, Li private ValidationEvent getPrivateAccessValidationEvent(Relationship relationship) { ShapeId neighborId = relationship.expectNeighborShape().getId(); String message = String.format( - "This shape has an invalid %s relationship that targets a private shape, `%s`, in another namespace.", - relationship.getRelationshipType().toString().toLowerCase(Locale.US), - neighborId + "This shape has an invalid %s relationship that targets a private shape, `%s`, in another namespace.", + relationship.getRelationshipType().toString().toLowerCase(Locale.US), + neighborId ); // For now, emit a warning for trait relationships instead of an error. This is because private access on trait diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/RangeTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/RangeTraitValidator.java index 2f8aa95ce66..686ca69ffc6 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/RangeTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/RangeTraitValidator.java @@ -36,36 +36,36 @@ public List validate(Model model) { private List validateRangeTrait(Model model, Shape shape, RangeTrait trait) { List events = new ArrayList<>(); trait.getMin() - .flatMap(min -> validateRangeProperty(model, shape, trait, min, "min")) - .ifPresent(events::add); + .flatMap(min -> validateRangeProperty(model, shape, trait, min, "min")) + .ifPresent(events::add); trait.getMax() - .flatMap(max -> validateRangeProperty(model, shape, trait, max, "max")) - .ifPresent(events::add); + .flatMap(max -> validateRangeProperty(model, shape, trait, max, "max")) + .ifPresent(events::add); // Makes sure that `min` is less than `max` trait.getMin() - .flatMap(min -> trait.getMax().map(max -> Pair.of(min, max))) - .filter(pair -> pair.getLeft().compareTo(pair.getRight()) > 0) - .map( - pair -> error( - shape, - trait, - "A range trait is applied with a `min` value greater than " - + "its `max` value." + .flatMap(min -> trait.getMax().map(max -> Pair.of(min, max))) + .filter(pair -> pair.getLeft().compareTo(pair.getRight()) > 0) + .map( + pair -> error( + shape, + trait, + "A range trait is applied with a `min` value greater than " + + "its `max` value." + ) ) - ) - .map(events::add); + .map(events::add); return events; } private Optional validateRangeProperty( - Model model, - Shape shape, - RangeTrait trait, - BigDecimal property, - String name + Model model, + Shape shape, + RangeTrait trait, + BigDecimal property, + String name ) { if (!property.remainder(BigDecimal.ONE).equals(BigDecimal.ZERO)) { if (shape.isMemberShape()) { @@ -73,34 +73,34 @@ private Optional validateRangeProperty( Optional target = model.getShape(member.getTarget()); if (target.isPresent() && !isDecimalShape(target.get())) { return Optional.of( - error( - shape, - trait, - format( - "Member `%s` is marked with the `range` trait, but its `%s` property " - + "is a decimal (%s) when its target (`%s`) does not support decimals.", - shape.getId(), - name, - property, - target.get().getId() + error( + shape, + trait, + format( + "Member `%s` is marked with the `range` trait, but its `%s` property " + + "is a decimal (%s) when its target (`%s`) does not support decimals.", + shape.getId(), + name, + property, + target.get().getId() + ) ) - ) ); } } else if (!isDecimalShape(shape)) { return Optional.of( - error( - shape, - trait, - format( - "Shape `%s` is marked with the `range` trait, but its `%s` property " - + "is a decimal (%s) when its shape (`%s`) does not support decimals.", - shape.getId(), - name, - property, - shape.getType() + error( + shape, + trait, + format( + "Shape `%s` is marked with the `range` trait, but its `%s` property " + + "is a decimal (%s) when its shape (`%s`) does not support decimals.", + shape.getId(), + name, + property, + shape.getType() + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ReferencesTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ReferencesTraitValidator.java index 2ff920cd051..c1fb7efc57a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ReferencesTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ReferencesTraitValidator.java @@ -52,12 +52,12 @@ private List validateShape(Model model, Shape shape, References for (ReferencesTrait.Reference reference : trait.getReferences()) { if (shape.isStringShape() && !reference.getIds().isEmpty()) { events.add( - error( - shape, - trait, - "References applied to string shapes cannot contain 'ids': " - + reference - ) + error( + shape, + trait, + "References applied to string shapes cannot contain 'ids': " + + reference + ) ); } @@ -66,15 +66,15 @@ private List validateShape(Model model, Shape shape, References if (targetedShape.isPresent()) { if (!targetedShape.get().isResourceShape()) { events.add( - error( - shape, - trait, - format( - "`references` trait reference targets a %s shape not a resource: %s", - targetedShape.get().getType(), - reference + error( + shape, + trait, + format( + "`references` trait reference targets a %s shape not a resource: %s", + targetedShape.get().getType(), + reference + ) ) - ) ); } else { ResourceShape resource = targetedShape.get().asResourceShape().get(); @@ -87,11 +87,11 @@ private List validateShape(Model model, Shape shape, References } private List validateSingleReference( - Model model, - ReferencesTrait.Reference reference, - Shape shape, - ReferencesTrait trait, - ResourceShape target + Model model, + ReferencesTrait.Reference reference, + Shape shape, + ReferencesTrait trait, + ResourceShape target ) { if (shape.asStructureShape().isPresent()) { return validateStructureRef(model, reference, shape.asStructureShape().get(), trait, target); @@ -103,26 +103,26 @@ private List validateSingleReference( } private List validateStringShapeRef( - ReferencesTrait.Reference reference, - StringShape shape, - ReferencesTrait trait, - ResourceShape target + ReferencesTrait.Reference reference, + StringShape shape, + ReferencesTrait trait, + ResourceShape target ) { // You can only reference a resource with a single ID on a string shape. if (target.getIdentifiers().size() != 1) { return ListUtils.of( - error( - shape, - trait, - String.format( - "This string shape contains an invalid reference to %s: %s. References on a string shape can " - + "only refer to resource shapes with exactly one entry in its identifiers property, but this " - + "shape has the following identifiers: [%s]", - target.getId(), - reference, - ValidationUtils.tickedList(target.getIdentifiers().keySet()) + error( + shape, + trait, + String.format( + "This string shape contains an invalid reference to %s: %s. References on a string shape can " + + "only refer to resource shapes with exactly one entry in its identifiers property, but this " + + "shape has the following identifiers: [%s]", + target.getId(), + reference, + ValidationUtils.tickedList(target.getIdentifiers().keySet()) + ) ) - ) ); } @@ -136,11 +136,11 @@ private enum ErrorReason { } private List validateStructureRef( - Model model, - ReferencesTrait.Reference reference, - StructureShape shape, - ReferencesTrait trait, - ResourceShape target + Model model, + ReferencesTrait.Reference reference, + StructureShape shape, + ReferencesTrait trait, + ResourceShape target ) { List events = new ArrayList<>(); Map resolvedIds = resolveIds(reference, target); @@ -175,17 +175,17 @@ private List validateStructureRef( private Map resolveIds(ReferencesTrait.Reference reference, ResourceShape target) { return !reference.getIds().isEmpty() - ? reference.getIds() - : target.getIdentifiers().keySet().stream().collect(toMap(identity(), identity())); + ? reference.getIds() + : target.getIdentifiers().keySet().stream().collect(toMap(identity(), identity())); } private void validateExplicitIds( - ReferencesTrait.Reference reference, - StructureShape shape, - ReferencesTrait trait, - ResourceShape target, - Map resolvedIds, - List events + ReferencesTrait.Reference reference, + StructureShape shape, + ReferencesTrait trait, + ResourceShape target, + Map resolvedIds, + List events ) { // References require the exact number of entries as the identifiers of the resource. if (resolvedIds.size() != target.getIdentifiers().size()) { @@ -201,57 +201,57 @@ private void validateExplicitIds( } private ValidationEvent wrongNumberOfIdentifiers( - Shape shape, - ReferencesTrait trait, - ReferencesTrait.Reference reference, - Collection expectedNames + Shape shape, + ReferencesTrait trait, + ReferencesTrait.Reference reference, + Collection expectedNames ) { String prefix = expectedNames.size() < reference.getIds().size() - ? "Too many identifiers" - : "Not enough identifiers"; + ? "Too many identifiers" + : "Not enough identifiers"; return error( - shape, - trait, - String.format( - "%s were provided in the `ids` properties of %s. Expected %d identifiers(s), but " - + "found %d. This resource requires bindings for the following identifiers: [%s].", - prefix, - reference, - expectedNames.size(), - reference.getIds().size(), - ValidationUtils.tickedList(expectedNames) - ) + shape, + trait, + String.format( + "%s were provided in the `ids` properties of %s. Expected %d identifiers(s), but " + + "found %d. This resource requires bindings for the following identifiers: [%s].", + prefix, + reference, + expectedNames.size(), + reference.getIds().size(), + ValidationUtils.tickedList(expectedNames) + ) ); } private ValidationEvent extraneousIdentifiers( - Shape shape, - ReferencesTrait trait, - ReferencesTrait.Reference reference, - ResourceShape resource, - Collection extraneousKeys + Shape shape, + ReferencesTrait trait, + ReferencesTrait.Reference reference, + ResourceShape resource, + Collection extraneousKeys ) { return error( - shape, - trait, - String.format( - "`references` trait %s contains extraneous resource identifier bindings, [%s], that are " - + "not actually identifier names of the resource, `%s`. This resource has the following identifier " - + "names: [%s]", - reference, - ValidationUtils.tickedList(extraneousKeys), - reference.getResource(), - ValidationUtils.tickedList(resource.getIdentifiers().keySet()) - ) + shape, + trait, + String.format( + "`references` trait %s contains extraneous resource identifier bindings, [%s], that are " + + "not actually identifier names of the resource, `%s`. This resource has the following identifier " + + "names: [%s]", + reference, + ValidationUtils.tickedList(extraneousKeys), + reference.getResource(), + ValidationUtils.tickedList(resource.getIdentifiers().keySet()) + ) ); } private Optional validateErrors( - StructureShape shape, - ReferencesTrait trait, - ReferencesTrait.Reference reference, - boolean implicit, - Map errors + StructureShape shape, + ReferencesTrait trait, + ReferencesTrait.Reference reference, + boolean implicit, + Map errors ) { List messages = new ArrayList<>(); errors.forEach((name, reason) -> { @@ -260,11 +260,11 @@ private Optional validateErrors( // Must be found when it's explicit or not a collection rel. if (implicit) { messages.add( - format( - "implicit binding of `%s` is not part of the structure " - + "(set \"rel\" to \"collection\" to create a collection binding)", - name - ) + format( + "implicit binding of `%s` is not part of the structure " + + "(set \"rel\" to \"collection\" to create a collection binding)", + name + ) ); } else { messages.add(format("`%s` refers to a member that is not part of the structure", name)); @@ -284,15 +284,15 @@ private Optional validateErrors( } return Optional.of( - error( - shape, - trait, - format( - "`references` trait %s is invalid for the following reasons: %s", - reference, - messages.stream().sorted().collect(Collectors.joining("; ")) + error( + shape, + trait, + format( + "`references` trait %s is invalid for the following reasons: %s", + reference, + messages.stream().sorted().collect(Collectors.joining("; ")) + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/RequestCompressionTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/RequestCompressionTraitValidator.java index d047e9d05d4..2cad704be7f 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/RequestCompressionTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/RequestCompressionTraitValidator.java @@ -43,11 +43,11 @@ private void validateOperationInput(Model model, OperationShape operationShape, // traits applied if (operationShape.getInputShape().equals(ShapeId.from("smithy.api#Unit"))) { events.add( - error( - operationShape, - "The `requestCompression` trait can only be applied to operations which have an " - + "input shape defined" - ) + error( + operationShape, + "The `requestCompression` trait can only be applied to operations which have an " + + "input shape defined" + ) ); return; } @@ -56,16 +56,16 @@ private void validateOperationInput(Model model, OperationShape operationShape, Shape targetShape = model.expectShape(memberShape.getTarget()); if (targetShape.hasTrait(StreamingTrait.class) && targetShape.hasTrait(RequiresLengthTrait.class)) { events.add( - error( - operationShape, - String.format( - "The `requestCompression` trait can only be applied to operations which do not have " - + "input members that target shapes with both the `streaming` and `requiresLength` " - + "traits applied, but found member `%s` targeting `%s`", - memberShape.getId(), - targetShape.getId() + error( + operationShape, + String.format( + "The `requestCompression` trait can only be applied to operations which do not have " + + "input members that target shapes with both the `streaming` and `requiresLength` " + + "traits applied, but found member `%s` targeting `%s`", + memberShape.getId(), + targetShape.getId() + ) ) - ) ); } } @@ -76,15 +76,15 @@ private void validateEncodings(Model model, OperationShape operationShape, List< RequestCompressionTrait trait = operationShape.expectTrait(RequestCompressionTrait.class); if (trait.getEncodings().isEmpty()) { events.add( - error( - operationShape, - trait, - String.format( - "There must be at least one compression algorithm in `encodings` for the " - + "`requestCompression` trait applied to `%s`", - operationShape.getId() + error( + operationShape, + trait, + String.format( + "There must be at least one compression algorithm in `encodings` for the " + + "`requestCompression` trait applied to `%s`", + operationShape.getId() + ) ) - ) ); return; } @@ -97,16 +97,16 @@ private void validateEncodings(Model model, OperationShape operationShape, List< } if (!invalidEncodings.isEmpty()) { events.add( - error( - operationShape, - trait, - String.format( - "Invalid compression algorithm%s found in `requestCompression` trait applied to `%s`: %s", - invalidEncodings.size() == 1 ? "" : "s", - operationShape.getId(), - ValidationUtils.tickedList(invalidEncodings) + error( + operationShape, + trait, + String.format( + "Invalid compression algorithm%s found in `requestCompression` trait applied to `%s`: %s", + invalidEncodings.size() == 1 ? "" : "s", + operationShape.getId(), + ValidationUtils.tickedList(invalidEncodings) + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceCycleValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceCycleValidator.java index 1949ca28e86..bf80195a61f 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceCycleValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceCycleValidator.java @@ -25,8 +25,8 @@ public final class ResourceCycleValidator extends AbstractValidator { @Override public List validate(Model model) { return model.shapes(ResourceShape.class) - .flatMap(shape -> OptionalUtils.stream(detectCycles(model, shape, new LinkedHashSet<>()))) - .collect(Collectors.toList()); + .flatMap(shape -> OptionalUtils.stream(detectCycles(model, shape, new LinkedHashSet<>()))) + .collect(Collectors.toList()); } private Optional detectCycles(Model model, ResourceShape resource, Set visited) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierBindingValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierBindingValidator.java index 45a6576152b..56407cd8a00 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierBindingValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierBindingValidator.java @@ -64,15 +64,15 @@ private void validateResourceIdentifierTraits(Model model, List Set explicitBindings = entry.getValue(); explicitBindings.remove(entry.getKey()); events.add( - warning( - structure, - String.format( - "Implicit resource identifier for '%s' is overridden by `resourceIdentifier` trait on " - + "members: '%s'", - entry.getKey(), - String.join("', '", explicitBindings) + warning( + structure, + String.format( + "Implicit resource identifier for '%s' is overridden by `resourceIdentifier` trait on " + + "members: '%s'", + entry.getKey(), + String.join("', '", explicitBindings) + ) ) - ) ); } } @@ -94,8 +94,8 @@ private Map> computePotentialStructureBindings(Shape structu // Ensure no two members are bound to the same identifier. for (MemberShape member : structure.members()) { String bindingName = member.getTrait(ResourceIdentifierTrait.class) - .map(ResourceIdentifierTrait::getValue) - .orElseGet(member::getMemberName); + .map(ResourceIdentifierTrait::getValue) + .orElseGet(member::getMemberName); bindings.computeIfAbsent(bindingName, k -> new HashSet<>()).add(member.getMemberName()); } return bindings; @@ -108,8 +108,8 @@ private void validateResourceIdentifierTraitConflicts(Shape structure, List new HashSet<>() + member.expectTrait(ResourceIdentifierTrait.class).getValue(), + k -> new HashSet<>() ).add(member.getMemberName()); } } @@ -117,15 +117,15 @@ private void validateResourceIdentifierTraitConflicts(Shape structure, List> entry : explicitBindings.entrySet()) { if (entry.getValue().size() > 1) { events.add( - error( - structure, - String.format( - "Conflicting resource identifier member bindings found for identifier '%s' between " - + "members: '%s'", - entry.getKey(), - String.join("', '", entry.getValue()) + error( + structure, + String.format( + "Conflicting resource identifier member bindings found for identifier '%s' between " + + "members: '%s'", + entry.getKey(), + String.join("', '", entry.getValue()) + ) ) - ) ); } } @@ -134,62 +134,64 @@ private void validateResourceIdentifierTraitConflicts(Shape structure, List events) { IdentifierBindingIndex bindingIndex = IdentifierBindingIndex.of(model); Stream.of( - model.shapes(ResourceShape.class) - .flatMap(resource -> validateResource(model, resource, bindingIndex)), - model.shapes(ResourceShape.class) - .flatMap(resource -> validateCollectionBindings(model, resource, bindingIndex)), - model.shapes(ResourceShape.class) - .flatMap(resource -> validateInstanceBindings(model, resource, bindingIndex)) + model.shapes(ResourceShape.class) + .flatMap(resource -> validateResource(model, resource, bindingIndex)), + model.shapes(ResourceShape.class) + .flatMap(resource -> validateCollectionBindings(model, resource, bindingIndex)), + model.shapes(ResourceShape.class) + .flatMap(resource -> validateInstanceBindings(model, resource, bindingIndex)) ).flatMap(Function.identity()).forEach(events::add); } private Stream validateResource( - Model model, - ResourceShape parent, - IdentifierBindingIndex bindingIndex + Model model, + ResourceShape parent, + IdentifierBindingIndex bindingIndex ) { return parent.getResources() - .stream() - .flatMap(childId -> OptionalUtils.stream(model.getShape(childId).flatMap(Shape::asResourceShape))) - .flatMap( - child -> child.getAllOperations() - .stream() - .flatMap(id -> OptionalUtils.stream(model.getShape(id).flatMap(Shape::asOperationShape))) - .map(operation -> Pair.of(child, operation)) - ) - .flatMap( - pair -> OptionalUtils.stream( - validateOperation(parent, pair.getLeft(), pair.getRight(), bindingIndex) + .stream() + .flatMap(childId -> OptionalUtils.stream(model.getShape(childId).flatMap(Shape::asResourceShape))) + .flatMap( + child -> child.getAllOperations() + .stream() + .flatMap( + id -> OptionalUtils.stream(model.getShape(id).flatMap(Shape::asOperationShape)) + ) + .map(operation -> Pair.of(child, operation)) ) - ); + .flatMap( + pair -> OptionalUtils.stream( + validateOperation(parent, pair.getLeft(), pair.getRight(), bindingIndex) + ) + ); } private Optional validateOperation( - ResourceShape parent, - ResourceShape child, - OperationShape operation, - IdentifierBindingIndex bindingIndex + ResourceShape parent, + ResourceShape child, + OperationShape operation, + IdentifierBindingIndex bindingIndex ) { if (bindingIndex.getOperationBindingType(child, operation) != IdentifierBindingIndex.BindingType.NONE) { Set bindings = bindingIndex.getOperationInputBindings(child, operation).keySet(); Set missing = parent.getIdentifiers() - .keySet() - .stream() - .filter(FunctionalUtils.not(bindings::contains)) - .collect(Collectors.toSet()); + .keySet() + .stream() + .filter(FunctionalUtils.not(bindings::contains)) + .collect(Collectors.toSet()); if (!missing.isEmpty()) { return Optional.of( - error( - operation, - String.format( - "This operation is bound to the `%s` resource, which is a child of the `%s` resource, and " - + "it is missing the following resource identifier bindings of `%s`: [%s]", - child.getId(), - parent.getId(), - parent.getId(), - ValidationUtils.tickedList(missing) + error( + operation, + String.format( + "This operation is bound to the `%s` resource, which is a child of the `%s` resource, and " + + "it is missing the following resource identifier bindings of `%s`: [%s]", + child.getId(), + parent.getId(), + parent.getId(), + ValidationUtils.tickedList(missing) + ) ) - ) ); } } @@ -198,92 +200,92 @@ private Optional validateOperation( } private Stream validateCollectionBindings( - Model model, - ResourceShape resource, - IdentifierBindingIndex identifierIndex + Model model, + ResourceShape resource, + IdentifierBindingIndex identifierIndex ) { return resource.getAllOperations() - .stream() - // Find all collection operations bound to the resource. - .filter( - operation -> identifierIndex.getOperationBindingType( - resource, - operation - ) == IdentifierBindingIndex.BindingType.COLLECTION - ) - // Get their operation shapes. - .flatMap(id -> OptionalUtils.stream(model.getShape(id).flatMap(Shape::asOperationShape))) - // Find collection operations which improperly bind all the resource identifiers. - .filter(operation -> hasAllIdentifiersBound(resource, operation, identifierIndex)) - .map( - operation -> error( - operation, - format( - "This operation is bound as a collection operation on the `%s` resource, but it improperly " - + "binds all of the identifiers of the resource to members of the operation input.", - resource.getId() - ) + .stream() + // Find all collection operations bound to the resource. + .filter( + operation -> identifierIndex.getOperationBindingType( + resource, + operation + ) == IdentifierBindingIndex.BindingType.COLLECTION ) - ); + // Get their operation shapes. + .flatMap(id -> OptionalUtils.stream(model.getShape(id).flatMap(Shape::asOperationShape))) + // Find collection operations which improperly bind all the resource identifiers. + .filter(operation -> hasAllIdentifiersBound(resource, operation, identifierIndex)) + .map( + operation -> error( + operation, + format( + "This operation is bound as a collection operation on the `%s` resource, but it improperly " + + "binds all of the identifiers of the resource to members of the operation input.", + resource.getId() + ) + ) + ); } private Stream validateInstanceBindings( - Model model, - ResourceShape resource, - IdentifierBindingIndex bindingIndex + Model model, + ResourceShape resource, + IdentifierBindingIndex bindingIndex ) { return resource.getAllOperations() - .stream() - // Find all instance operations bound to the resource. - .filter( - operation -> bindingIndex.getOperationBindingType( - resource, - operation - ) == IdentifierBindingIndex.BindingType.INSTANCE - ) - // Get their operation shapes. - .flatMap(id -> OptionalUtils.stream(model.getShape(id).flatMap(Shape::asOperationShape))) - // Find instance operations which do not bind all of the resource identifiers. - .filter(operation -> !hasAllIdentifiersBound(resource, operation, bindingIndex)) - .map(operation -> { - String expectedIdentifiers = createBindingMessage(resource.getIdentifiers()); - String boundIds = createBindingMessage(bindingIndex.getOperationInputBindings(resource, operation)); - return error( - operation, - format( - "This operation does not form a valid instance operation when bound to resource `%s`. " - + "All of the identifiers of the resource were not implicitly or explicitly bound " - + "to the input of the operation. Expected the following identifier bindings: " - + "[%s]. Found the following identifier bindings: [%s]", - resource.getId(), - expectedIdentifiers, - boundIds - ) - ); - }); + .stream() + // Find all instance operations bound to the resource. + .filter( + operation -> bindingIndex.getOperationBindingType( + resource, + operation + ) == IdentifierBindingIndex.BindingType.INSTANCE + ) + // Get their operation shapes. + .flatMap(id -> OptionalUtils.stream(model.getShape(id).flatMap(Shape::asOperationShape))) + // Find instance operations which do not bind all of the resource identifiers. + .filter(operation -> !hasAllIdentifiersBound(resource, operation, bindingIndex)) + .map(operation -> { + String expectedIdentifiers = createBindingMessage(resource.getIdentifiers()); + String boundIds = createBindingMessage(bindingIndex.getOperationInputBindings(resource, operation)); + return error( + operation, + format( + "This operation does not form a valid instance operation when bound to resource `%s`. " + + "All of the identifiers of the resource were not implicitly or explicitly bound " + + "to the input of the operation. Expected the following identifier bindings: " + + "[%s]. Found the following identifier bindings: [%s]", + resource.getId(), + expectedIdentifiers, + boundIds + ) + ); + }); } private boolean hasAllIdentifiersBound( - ResourceShape resource, - OperationShape operation, - IdentifierBindingIndex bindingIndex + ResourceShape resource, + OperationShape operation, + IdentifierBindingIndex bindingIndex ) { return bindingIndex.getOperationInputBindings(resource, operation) - .keySet() - .containsAll(resource.getIdentifiers().keySet()); + .keySet() + .containsAll(resource.getIdentifiers().keySet()); } private String createBindingMessage(Map bindings) { return bindings.entrySet() - .stream() - .map( - entry -> format( - "required member named `%s` that targets `%s`", - entry.getKey(), - entry.getValue().toString() + .stream() + .map( + entry -> format( + "required member named `%s` that targets `%s`", + entry.getKey(), + entry.getValue().toString() + ) ) - ) - .sorted() - .collect(Collectors.joining(", ")); + .sorted() + .collect(Collectors.joining(", ")); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierValidator.java index 948a013d7cd..81e1a179972 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierValidator.java @@ -44,14 +44,14 @@ private List validatePropertyRedefine(ResourceShape resource, M for (String identifier : resource.getIdentifiers().keySet()) { if (propertyLowerCaseToActual.containsKey(identifier.toLowerCase(Locale.ENGLISH))) { events.add( - error( - resource, - String.format( - "Resource identifier `%s` cannot also be a" - + " resource property", - identifier + error( + resource, + String.format( + "Resource identifier `%s` cannot also be a" + + " resource property", + identifier + ) ) - ) ); } } @@ -72,62 +72,62 @@ private List validateAgainstChildren(ResourceShape resource, Mo private Optional checkForMissing(ResourceShape resource, ResourceShape parent) { // Look for identifiers on the parent that are flat-out missing on the child. String missingKeys = parent.getIdentifiers() - .entrySet() - .stream() - .filter(entry -> resource.getIdentifiers().get(entry.getKey()) == null) - .map(Map.Entry::getKey) - .sorted() - .collect(Collectors.joining(", ")); + .entrySet() + .stream() + .filter(entry -> resource.getIdentifiers().get(entry.getKey()) == null) + .map(Map.Entry::getKey) + .sorted() + .collect(Collectors.joining(", ")); if (missingKeys.isEmpty()) { return Optional.empty(); } return Optional.of( - error( - resource, - String.format( - "This resource is bound as a child of `%s`, but it is invalid because its `identifiers` property " - + "is missing the following identifiers that are defined in `%s`: [%s]", - parent.getId(), - parent.getId(), - missingKeys + error( + resource, + String.format( + "This resource is bound as a child of `%s`, but it is invalid because its `identifiers` property " + + "is missing the following identifiers that are defined in `%s`: [%s]", + parent.getId(), + parent.getId(), + missingKeys + ) ) - ) ); } private Optional checkForMismatches(ResourceShape resource, ResourceShape parent) { // Look for identifiers on the child that have the same key but target different shapes. String mismatchedTargets = parent.getIdentifiers() - .entrySet() - .stream() - .filter(entry -> resource.getIdentifiers().get(entry.getKey()) != null) - .filter(entry -> !resource.getIdentifiers().get(entry.getKey()).equals(entry.getValue())) - .map( - entry -> String.format( - "expected the `%s` member to target `%s`, but found a target of `%s`", - entry.getKey(), - entry.getValue(), - resource.getIdentifiers().get(entry.getKey()) + .entrySet() + .stream() + .filter(entry -> resource.getIdentifiers().get(entry.getKey()) != null) + .filter(entry -> !resource.getIdentifiers().get(entry.getKey()).equals(entry.getValue())) + .map( + entry -> String.format( + "expected the `%s` member to target `%s`, but found a target of `%s`", + entry.getKey(), + entry.getValue(), + resource.getIdentifiers().get(entry.getKey()) + ) ) - ) - .sorted() - .collect(Collectors.joining("; ")); + .sorted() + .collect(Collectors.joining("; ")); if (mismatchedTargets.isEmpty()) { return Optional.empty(); } return Optional.of( - error( - resource, - String.format( - "The `identifiers` property of this resource is incompatible with its binding to `%s`: %s", - parent.getId(), - mismatchedTargets + error( + resource, + String.format( + "The `identifiers` property of this resource is incompatible with its binding to `%s`: %s", + parent.getId(), + mismatchedTargets + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceLifecycleValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceLifecycleValidator.java index 1f2094ead88..80989192a98 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceLifecycleValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceLifecycleValidator.java @@ -27,8 +27,8 @@ public final class ResourceLifecycleValidator extends AbstractValidator { @Override public List validate(Model model) { return model.shapes(ResourceShape.class) - .flatMap(shape -> validateResource(model, shape).stream()) - .collect(Collectors.toList()); + .flatMap(shape -> validateResource(model, shape).stream()) + .collect(Collectors.toList()); } private List validateResource(Model model, ResourceShape resource) { @@ -65,50 +65,50 @@ private List validateResource(Model model, ResourceShape resour } private Optional validateReadonly( - ResourceShape resource, - OperationShape operation, - String lifecycle, - boolean requireReadOnly + ResourceShape resource, + OperationShape operation, + String lifecycle, + boolean requireReadOnly ) { if (requireReadOnly == operation.hasTrait(ReadonlyTrait.class)) { return Optional.empty(); } return Optional.of( - error( - resource, - format( - "The `%s` lifecycle operation of this resource targets an invalid operation, `%s`. The targeted " - + "operation %s be marked with the readonly trait.", - lifecycle, - operation.getId(), - requireReadOnly ? "must" : "must not" + error( + resource, + format( + "The `%s` lifecycle operation of this resource targets an invalid operation, `%s`. The targeted " + + "operation %s be marked with the readonly trait.", + lifecycle, + operation.getId(), + requireReadOnly ? "must" : "must not" + ) ) - ) ); } private Optional validateIdempotent( - ResourceShape resource, - OperationShape operation, - String lifecycle, - String additionalMessage + ResourceShape resource, + OperationShape operation, + String lifecycle, + String additionalMessage ) { if (operation.hasTrait(IdempotentTrait.class)) { return Optional.empty(); } return Optional.of( - error( - resource, - format( - "The `%s` lifecycle operation of this resource targets an invalid operation, `%s`. The targeted " - + "operation must be marked as idempotent.%s", - lifecycle, - operation.getId(), - additionalMessage + error( + resource, + format( + "The `%s` lifecycle operation of this resource targets an invalid operation, `%s`. The targeted " + + "operation must be marked as idempotent.%s", + lifecycle, + operation.getId(), + additionalMessage + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceOperationInputOutputValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceOperationInputOutputValidator.java index 6155cb84e00..fc80e08b2af 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceOperationInputOutputValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceOperationInputOutputValidator.java @@ -47,59 +47,59 @@ private List validateResource(Model model, ResourceShape resour PropertyBindingIndex propertyBindingIndex = PropertyBindingIndex.of(model); processLifecycleOperationProperties( - model, - resource, - "put", - resource.getPut(), - propertyBindingIndex, - propertiesInOperations, - events + model, + resource, + "put", + resource.getPut(), + propertyBindingIndex, + propertiesInOperations, + events ); processLifecycleOperationProperties( - model, - resource, - "create", - resource.getCreate(), - propertyBindingIndex, - propertiesInOperations, - events + model, + resource, + "create", + resource.getCreate(), + propertyBindingIndex, + propertiesInOperations, + events ); processLifecycleOperationProperties( - model, - resource, - "read", - resource.getRead(), - propertyBindingIndex, - propertiesInOperations, - events + model, + resource, + "read", + resource.getRead(), + propertyBindingIndex, + propertiesInOperations, + events ); processLifecycleOperationProperties( - model, - resource, - "update", - resource.getUpdate(), - propertyBindingIndex, - propertiesInOperations, - events + model, + resource, + "update", + resource.getUpdate(), + propertyBindingIndex, + propertiesInOperations, + events ); processLifecycleOperationProperties( - model, - resource, - "delete", - resource.getDelete(), - propertyBindingIndex, - propertiesInOperations, - events - ); - for (ShapeId operationId : resource.getOperations()) { - processLifecycleOperationProperties( model, resource, - operationId.getName(), - Optional.of(operationId), + "delete", + resource.getDelete(), propertyBindingIndex, propertiesInOperations, events + ); + for (ShapeId operationId : resource.getOperations()) { + processLifecycleOperationProperties( + model, + resource, + operationId.getName(), + Optional.of(operationId), + propertyBindingIndex, + propertiesInOperations, + events ); } @@ -107,14 +107,14 @@ private List validateResource(Model model, ResourceShape resour definedProperties.removeAll(propertiesInOperations); for (String propertyNotInLifecycleOp : definedProperties) { events.add( - error( - resource, - String.format( - "Resource property `%s` is not used in the input or output" - + " of create or an instance operation.", - propertyNotInLifecycleOp + error( + resource, + String.format( + "Resource property `%s` is not used in the input or output" + + " of create or an instance operation.", + propertyNotInLifecycleOp + ) ) - ) ); } @@ -122,30 +122,30 @@ private List validateResource(Model model, ResourceShape resour } private void processLifecycleOperationProperties( - Model model, - ResourceShape resource, - String name, - Optional operationShapeId, - PropertyBindingIndex propertyBindingIndex, - Set propertiesInOperations, - List events + Model model, + ResourceShape resource, + String name, + Optional operationShapeId, + PropertyBindingIndex propertyBindingIndex, + Set propertiesInOperations, + List events ) { operationShapeId.flatMap(model::getShape).flatMap(Shape::asOperationShape).ifPresent(operation -> { propertiesInOperations.addAll(getAllOperationProperties(propertyBindingIndex, operation)); validateOperationInputOutput( - model, - propertyBindingIndex, - resource, - operation, - name, - events + model, + propertyBindingIndex, + resource, + operation, + name, + events ); }); } private List getAllOperationProperties( - PropertyBindingIndex propertyBindingIndex, - OperationShape operation + PropertyBindingIndex propertyBindingIndex, + OperationShape operation ) { List properties = new ArrayList<>(); for (MemberShape member : propertyBindingIndex.getInputPropertiesShape(operation).members()) { @@ -162,46 +162,46 @@ private List getAllOperationProperties( } private void validateOperationInputOutput( - Model model, - PropertyBindingIndex propertyBindingIndex, - ResourceShape resource, - OperationShape operation, - String lifecycleOperationName, - List events + Model model, + PropertyBindingIndex propertyBindingIndex, + ResourceShape resource, + OperationShape operation, + String lifecycleOperationName, + List events ) { validateOperationInput(model, propertyBindingIndex, resource, operation, lifecycleOperationName, events); validateOperationOutput(model, propertyBindingIndex, resource, operation, lifecycleOperationName, events); } private void validateOperationOutput( - Model model, - PropertyBindingIndex propertyBindingIndex, - ResourceShape resource, - OperationShape operation, - String lifecycleOperationName, - List events + Model model, + PropertyBindingIndex propertyBindingIndex, + ResourceShape resource, + OperationShape operation, + String lifecycleOperationName, + List events ) { Map properties = resource.getProperties(); Map> propertyToMemberMappings = new TreeMap<>(); IdentifierBindingIndex identifierBindingIndex = IdentifierBindingIndex.of(model); Set identifierMembers = new HashSet<>( - identifierBindingIndex - .getOperationOutputBindings(resource, operation) - .values() + identifierBindingIndex + .getOperationOutputBindings(resource, operation) + .values() ); Shape shape = propertyBindingIndex.getOutputPropertiesShape(operation); for (MemberShape member : shape.members()) { if (propertyBindingIndex.isMemberShapeProperty(member)) { validateMember( - events, - lifecycleOperationName, - propertyBindingIndex, - resource, - member, - identifierMembers, - properties, - propertyToMemberMappings + events, + lifecycleOperationName, + propertyBindingIndex, + resource, + member, + identifierMembers, + properties, + propertyToMemberMappings ); } } @@ -209,34 +209,34 @@ private void validateOperationOutput( } private void validateOperationInput( - Model model, - PropertyBindingIndex propertyBindingIndex, - ResourceShape resource, - OperationShape operation, - String lifecycleOperationName, - List events + Model model, + PropertyBindingIndex propertyBindingIndex, + ResourceShape resource, + OperationShape operation, + String lifecycleOperationName, + List events ) { Map properties = resource.getProperties(); Map> propertyToMemberMappings = new TreeMap<>(); IdentifierBindingIndex identifierBindingIndex = IdentifierBindingIndex.of(model); Set identifierMembers = new HashSet<>( - identifierBindingIndex - .getOperationOutputBindings(resource, operation) - .values() + identifierBindingIndex + .getOperationOutputBindings(resource, operation) + .values() ); Shape shape = propertyBindingIndex.getInputPropertiesShape(operation); for (MemberShape member : shape.members()) { if (propertyBindingIndex.isMemberShapeProperty(member)) { validateMember( - events, - lifecycleOperationName, - propertyBindingIndex, - resource, - member, - identifierMembers, - properties, - propertyToMemberMappings + events, + lifecycleOperationName, + propertyBindingIndex, + resource, + member, + identifierMembers, + properties, + propertyToMemberMappings ); } } @@ -244,38 +244,38 @@ private void validateOperationInput( } private void validateConflictingProperties( - List events, - Shape shape, - Map> propertyToMemberMappings + List events, + Shape shape, + Map> propertyToMemberMappings ) { for (Map.Entry> entry : propertyToMemberMappings.entrySet()) { if (entry.getValue().size() > 1) { events.add( - error( - shape, - String.format( - "This shape contains members with conflicting resource property names that resolve to '%s': %s", - entry.getKey(), - entry.getValue() - .stream() - .map(MemberShape::getMemberName) - .collect(Collectors.joining(", ")) + error( + shape, + String.format( + "This shape contains members with conflicting resource property names that resolve to '%s': %s", + entry.getKey(), + entry.getValue() + .stream() + .map(MemberShape::getMemberName) + .collect(Collectors.joining(", ")) + ) ) - ) ); } } } private void validateMember( - List events, - String lifecycleOperationName, - PropertyBindingIndex propertyBindingIndex, - ResourceShape resource, - MemberShape member, - Set identifierMembers, - Map properties, - Map> propertyToMemberMappings + List events, + String lifecycleOperationName, + PropertyBindingIndex propertyBindingIndex, + ResourceShape resource, + MemberShape member, + Set identifierMembers, + Map properties, + Map> propertyToMemberMappings ) { String propertyName = propertyBindingIndex.getPropertyName(member.getId()).get(); propertyToMemberMappings.computeIfAbsent(propertyName, m -> new TreeSet<>()).add(member); @@ -283,30 +283,30 @@ private void validateMember( if (!properties.get(propertyName).equals(member.getTarget())) { ShapeId expectedTarget = properties.get(propertyName); events.add( - error( - member, - String.format( - "This member must target `%s`. This member is used as part of the `%s` operation of the `%s` " - + "resource and conflicts with its `%s` resource property.", - expectedTarget, - lifecycleOperationName, - resource.getId(), - propertyName + error( + member, + String.format( + "This member must target `%s`. This member is used as part of the `%s` operation of the `%s` " + + "resource and conflicts with its `%s` resource property.", + expectedTarget, + lifecycleOperationName, + resource.getId(), + propertyName + ) ) - ) ); } } else if (!identifierMembers.contains(member.getMemberName())) { events.add( - error( - member, - String.format( - "Member `%s` does not target a property or identifier" - + " for resource `%s`", - member.getMemberName(), - resource.getId().toString() + error( + member, + String.format( + "Member `%s` does not target a property or identifier" + + " for resource `%s`", + member.getMemberName(), + resource.getId().toString() + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceAuthDefinitionsValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceAuthDefinitionsValidator.java index 53a3a5547c5..f69ebfb3e8c 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceAuthDefinitionsValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceAuthDefinitionsValidator.java @@ -25,21 +25,21 @@ public List validate(Model model) { ServiceIndex index = ServiceIndex.of(model); List services = model.getServiceShapes() - .stream() - .filter(serviceShape -> !serviceShape.hasTrait(AuthTrait.ID)) - .filter(serviceShape -> index.getAuthSchemes(serviceShape).size() > 1) - .collect(Collectors.toList()); + .stream() + .filter(serviceShape -> !serviceShape.hasTrait(AuthTrait.ID)) + .filter(serviceShape -> index.getAuthSchemes(serviceShape).size() > 1) + .collect(Collectors.toList()); for (ServiceShape service : services) { events.add( - warning( - service, - "This service uses multiple authentication schemes but does not have " - + "the `@auth` trait applied. The `@auth` trait defines a priority ordering " - + "of auth schemes for a client to use. Without it, the ordering of auth " - + "schemes is alphabetical based on the absolute shape ID of the auth " - + "schemes." - ) + warning( + service, + "This service uses multiple authentication schemes but does not have " + + "the `@auth` trait applied. The `@auth` trait defines a priority ordering " + + "of auth schemes for a client to use. Without it, the ordering of auth " + + "schemes is alphabetical based on the absolute shape ID of the auth " + + "schemes." + ) ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceBoundResourceOperationValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceBoundResourceOperationValidator.java index 6fb50c6de8c..c02c022c763 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceBoundResourceOperationValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceBoundResourceOperationValidator.java @@ -48,13 +48,13 @@ public List validate(Model model) { for (MemberShape member : operationIndex.getInputMembers(operation).values()) { if (isImplicitIdentifierBinding(member, resource)) { potentiallyBetterBindings.computeIfAbsent(operation, k -> new HashSet<>()) - .add(resource.getId()); + .add(resource.getId()); } } for (MemberShape member : operationIndex.getOutputMembers(operation).values()) { if (isImplicitIdentifierBinding(member, resource)) { potentiallyBetterBindings.computeIfAbsent(operation, k -> new HashSet<>()) - .add(resource.getId()); + .add(resource.getId()); } } } @@ -63,20 +63,20 @@ public List validate(Model model) { // Emit events per service that's present with a potentially bad binding. for (Map.Entry> entry : potentiallyBetterBindings.entrySet()) { events.add( - warning( - entry.getKey(), - service, - format( - "The `%s` operation is bound to the `%s` service but has members that match identifiers " - + "of the following resource shapes: [%s]. It may be more accurately bound to one " - + "of them than directly to the service.", - entry.getKey().getId(), - service.getId(), - ValidationUtils.tickedList(entry.getValue()) - ), - service.getId().toString(), - entry.getKey().getId().getName() - ) + warning( + entry.getKey(), + service, + format( + "The `%s` operation is bound to the `%s` service but has members that match identifiers " + + "of the following resource shapes: [%s]. It may be more accurately bound to one " + + "of them than directly to the service.", + entry.getKey().getId(), + service.getId(), + ValidationUtils.tickedList(entry.getValue()) + ), + service.getId().toString(), + entry.getKey().getId().getName() + ) ); } } @@ -86,7 +86,7 @@ public List validate(Model model) { private boolean isImplicitIdentifierBinding(MemberShape member, ResourceShape resource) { return resource.getIdentifiers().containsKey(member.getMemberName()) - && member.getTrait(RequiredTrait.class).isPresent() - && member.getTarget().equals(resource.getIdentifiers().get(member.getMemberName())); + && member.getTrait(RequiredTrait.class).isPresent() + && member.getTarget().equals(resource.getIdentifiers().get(member.getMemberName())); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceValidator.java index 8892e684c03..c252f5d1147 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceValidator.java @@ -68,8 +68,8 @@ private void validateService(Model model, ServiceShape service, List new TreeSet<>()) - .add(id); + .computeIfAbsent(possiblyRename.toLowerCase(Locale.ENGLISH), name -> new TreeSet<>()) + .add(id); } } @@ -118,25 +118,25 @@ private List validateRenames(ServiceShape service, Map validateRenames(ServiceShape service, Map { events.add( - error( - service, - String.format( - "Service attempts to rename a %s shape from `%s` to \"%s\"; %s", - closure.get(from).getType(), - from, - to, - reason + error( + service, + String.format( + "Service attempts to rename a %s shape from `%s` to \"%s\"; %s", + closure.get(from).getType(), + from, + to, + reason + ) ) - ) ); }); } @@ -177,8 +177,8 @@ private ValidationEvent conflictingNames(Severity severity, ServiceShape service if (service.getRename().get(subject.getId()) != null) { message.append("Renamed shape name \"") - .append(service.getRename().get(subject.getId())) - .append('"'); + .append(service.getRename().get(subject.getId())) + .append('"'); } else { message.append("Shape name `").append(subject.getId()).append('`'); } @@ -187,24 +187,24 @@ private ValidationEvent conflictingNames(Severity severity, ServiceShape service if (service.getRename().get(other.getId()) != null) { message.append("(renamed to \"") - .append(service.getRename().get(other.getId())) - .append("\") "); + .append(service.getRename().get(other.getId())) + .append("\") "); } message.append("in the `") - .append(service.getId()) - .append("` service closure. ") - .append("Shapes in the closure of a service ") - .append(severity.ordinal() >= Severity.DANGER.ordinal() ? "must " : "should ") - .append("have case-insensitively unique names regardless of their namespaces. ") - .append("Use the `rename` property of the service to disambiguate shape names."); + .append(service.getId()) + .append("` service closure. ") + .append("Shapes in the closure of a service ") + .append(severity.ordinal() >= Severity.DANGER.ordinal() ? "must " : "should ") + .append("have case-insensitively unique names regardless of their namespaces. ") + .append("Use the `rename` property of the service to disambiguate shape names."); return ValidationEvent.builder() - .id(getName()) - .severity(severity) - .shape(subject) - .message(message.toString()) - .build(); + .id(getName()) + .severity(severity) + .shape(subject) + .message(message.toString()) + .build(); } private static final class ConflictDetector { @@ -226,8 +226,8 @@ Severity detect(Shape a, Shape b) { // Create a normalized cache key since the comparison of a to b // and b to a is the same result. Pair cacheKey = a.getId().compareTo(b.getId()) < 0 - ? Pair.of(a.getId(), b.getId()) - : Pair.of(b.getId(), a.getId()); + ? Pair.of(a.getId(), b.getId()) + : Pair.of(b.getId(), a.getId()); // Don't use computeIfAbsent here since we don't want to lock the HashMap. // Computing if there is a conflict for aggregate shapes requires that @@ -246,9 +246,9 @@ private Severity detectConflicts(Shape a, Shape b) { // 2. Conflicting shapes must have the same types. // 3. Conflicting shapes must have the same traits. if (isShapeTypeConflictForbidden(a) - || isShapeTypeConflictForbidden(b) - || a.getType() != b.getType() - || !equivalentTraits(a.getAllTraits(), b.getAllTraits())) { + || isShapeTypeConflictForbidden(b) + || a.getType() != b.getType() + || !equivalentTraits(a.getAllTraits(), b.getAllTraits())) { return Severity.ERROR; } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SetValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SetValidator.java index 2bd11ea0e84..39494992992 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SetValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SetValidator.java @@ -20,14 +20,14 @@ public List validate(Model model) { List events = new ArrayList<>(); for (SetShape set : model.getSetShapes()) { ValidationEvent event = ValidationEvent.builder() - .id(AbstractValidator.MODEL_DEPRECATION) - .severity(Severity.WARNING) - .shape(set) - .message( - "Set shapes are deprecated and have been removed in Smithy IDL v2. " - + "Use a list shape with the @uniqueItems trait instead." - ) - .build(); + .id(AbstractValidator.MODEL_DEPRECATION) + .severity(Severity.WARNING) + .shape(set) + .message( + "Set shapes are deprecated and have been removed in Smithy IDL v2. " + + "Use a list shape with the @uniqueItems trait instead." + ) + .build(); events.add(event); } return events; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeIdConflictValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeIdConflictValidator.java index b4eff76a1fa..5fea5eb925a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeIdConflictValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeIdConflictValidator.java @@ -37,20 +37,20 @@ public List validate(Model model) { if (entry.getValue().size() > 1) { for (ShapeId value : entry.getValue()) { String collideString = entry.getValue() - .stream() - .filter(id -> !id.equals(value)) - .sorted() - .map(id -> "`" + id + "`") - .collect(Collectors.joining(", ")); + .stream() + .filter(id -> !id.equals(value)) + .sorted() + .map(id -> "`" + id + "`") + .collect(Collectors.joining(", ")); events.add( - error( - model.expectShape(value), - String.format( - "Shape ID `%s` conflicts with other shape IDs in the model: [%s]", - value, - collideString + error( + model.expectShape(value), + String.format( + "Shape ID `%s` conflicts with other shape IDs in the model: [%s]", + value, + collideString + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeRecursionValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeRecursionValidator.java index 00e9e09be3b..63be0890321 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeRecursionValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeRecursionValidator.java @@ -69,14 +69,14 @@ private void validateListMapSetShapes(PathFinder finder, Model model, List events) { for (PathFinder.Path path : finder.search(shape, Collections.singletonList(shape))) { events.add( - error( - shape, - String.format( - "Found invalid shape recursion: %s. A recursive list, set, or map shape is only " - + "valid if an intermediate reference is through a union or structure.", - formatPath(path) + error( + shape, + String.format( + "Found invalid shape recursion: %s. A recursive list, set, or map shape is only " + + "valid if an intermediate reference is through a union or structure.", + formatPath(path) + ) ) - ) ); } } @@ -93,14 +93,14 @@ private void validateStructurePaths(PathFinder finder, Model model, List validate(Model model) { TopDownIndex topDownIndex = TopDownIndex.of(model); return model.shapes(ServiceShape.class) - .flatMap(shape -> validateService(topDownIndex, shape).stream()) - .collect(Collectors.toList()); + .flatMap(shape -> validateService(topDownIndex, shape).stream()) + .collect(Collectors.toList()); } private List validateService(TopDownIndex topDownIndex, ServiceShape service) { @@ -51,15 +51,18 @@ private List validateService(TopDownIndex topDownIndex, Service if (containers.size() > 1) { events.add( - error( - operation, - String.format( - "An operation can appear only once in an entire service closure. This operation is " - + "illegally bound into the `%s` service closure from multiple shapes: %s", - service.getId(), - containers.stream().map(Object::toString).sorted().collect(Collectors.joining(", ")) + error( + operation, + String.format( + "An operation can appear only once in an entire service closure. This operation is " + + "illegally bound into the `%s` service closure from multiple shapes: %s", + service.getId(), + containers.stream() + .map(Object::toString) + .sorted() + .collect(Collectors.joining(", ")) + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SingleResourceBindingValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SingleResourceBindingValidator.java index b7bec471d53..8231d47f4d3 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SingleResourceBindingValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SingleResourceBindingValidator.java @@ -28,8 +28,8 @@ public final class SingleResourceBindingValidator extends AbstractValidator { public List validate(Model model) { TopDownIndex topDownIndex = TopDownIndex.of(model); return model.shapes(ServiceShape.class) - .flatMap(shape -> validateService(topDownIndex, shape).stream()) - .collect(Collectors.toList()); + .flatMap(shape -> validateService(topDownIndex, shape).stream()) + .collect(Collectors.toList()); } private List validateService(TopDownIndex topDownIndex, ServiceShape service) { @@ -48,15 +48,15 @@ private List validateService(TopDownIndex topDownIndex, Service if (containers.size() > 1) { events.add( - error( - resource, - String.format( - "A resource can appear only once in an entire service closure. This resource is " - + "illegally bound into the `%s` service closure from multiple shapes: [%s]", - service.getId(), - ValidationUtils.tickedList(containers) + error( + resource, + String.format( + "A resource can appear only once in an entire service closure. This resource is " + + "illegally bound into the `%s` service closure from multiple shapes: [%s]", + service.getId(), + ValidationUtils.tickedList(containers) + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/StreamingTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/StreamingTraitValidator.java index 1c4e27f0949..c49e563b519 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/StreamingTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/StreamingTraitValidator.java @@ -62,13 +62,13 @@ private void validateBlobTargetsAreNonOptional(Model model, List e Shape target = model.expectShape(member.getTarget()); if (target.hasTrait(StreamingTrait.class)) { events.add( - error( - member, - String.format( - "Member `%s` referencing @streaming shape `%s` must have the @httpPayload trait, " - + "as service `%s` has a protocol that supports @httpPayload.", - member.toShapeId(), - member.getTarget(), - service.toShapeId() + error( + member, + String.format( + "Member `%s` referencing @streaming shape `%s` must have the @httpPayload trait, " + + "as service `%s` has a protocol that supports @httpPayload.", + member.toShapeId(), + member.getTarget(), + service.toShapeId() + ) ) - ) ); } } @@ -113,9 +113,9 @@ private void validateBlobTargetsArePayloads(Model model, List e private boolean protocolTraitSupportsHttpPayload(Model model, ShapeId protocolTrait) { return model.expectShape(protocolTrait) - .expectTrait(ProtocolDefinitionTrait.class) - .getTraits() - .contains(HttpPayloadTrait.ID); + .expectTrait(ProtocolDefinitionTrait.class) + .getTraits() + .contains(HttpPayloadTrait.ID); } private void validateStreamingTargets(Model model, List events) { @@ -143,41 +143,41 @@ private void validateRef(Model model, MemberShape member, NeighborProvider rever case OUTPUT: if (target.hasTrait(RequiresLengthTrait.class)) { events.add( - error( - rel.getNeighborShape().get(), - String.format( - "Structures that contain a reference to a stream marked with the " - + "@requiresLength trait can only be used as operation inputs, but this " - + "structure is referenced from `%s` as %s", - rel.getShape().getId(), - rel.getRelationshipType().toString().toLowerCase(Locale.ENGLISH) + error( + rel.getNeighborShape().get(), + String.format( + "Structures that contain a reference to a stream marked with the " + + "@requiresLength trait can only be used as operation inputs, but this " + + "structure is referenced from `%s` as %s", + rel.getShape().getId(), + rel.getRelationshipType().toString().toLowerCase(Locale.ENGLISH) + ) ) - ) ); } break; case MEMBER_TARGET: events.add( - error( - rel.getShape(), - String.format( - "Members cannot target structures that contain a stream, but this member targets %s", - container.getId() + error( + rel.getShape(), + String.format( + "Members cannot target structures that contain a stream, but this member targets %s", + container.getId() + ) ) - ) ); break; default: events.add( - error( - rel.getShape(), - String.format( - "This shape has an invalid `%s` relationship to a structure, `%s`, that contains " - + "a stream", - rel.getRelationshipType(), - container.getId() + error( + rel.getShape(), + String.format( + "This shape has an invalid `%s` relationship to a structure, `%s`, that contains " + + "a stream", + rel.getRelationshipType(), + container.getId() + ) ) - ) ); } } @@ -199,14 +199,14 @@ private void validateAllEventStreamMembersTargetStructures(Model model, List INVALID_MEMBER_TARGETS = SetUtils.of( - ShapeType.SERVICE, - ShapeType.RESOURCE, - ShapeType.OPERATION, - ShapeType.MEMBER + ShapeType.SERVICE, + ShapeType.RESOURCE, + ShapeType.OPERATION, + ShapeType.MEMBER ); private static final String UNRESOLVED_SHAPE_PART = "UnresolvedShape"; // Relationship types listed here are checked to see if a shape refers to a deprecated shape. private static final Map RELATIONSHIP_TYPE_DEPRECATION_MAPPINGS = MapUtils.of( - RelationshipType.MEMBER_TARGET, - "Member targets a deprecated shape", - RelationshipType.RESOURCE, - "Binds a deprecated resource", - RelationshipType.OPERATION, - "Binds a deprecated operation", - RelationshipType.IDENTIFIER, - "Resource identifier targets a deprecated shape", - RelationshipType.PROPERTY, - "Resource property targets a deprecated shape", - RelationshipType.INPUT, - "Operation input targets a deprecated shape", - RelationshipType.OUTPUT, - "Operation output targets a deprecated shape", - RelationshipType.ERROR, - "Operation error targets a deprecated shape", - RelationshipType.MIXIN, - "Applies a deprecated mixin" + RelationshipType.MEMBER_TARGET, + "Member targets a deprecated shape", + RelationshipType.RESOURCE, + "Binds a deprecated resource", + RelationshipType.OPERATION, + "Binds a deprecated operation", + RelationshipType.IDENTIFIER, + "Resource identifier targets a deprecated shape", + RelationshipType.PROPERTY, + "Resource property targets a deprecated shape", + RelationshipType.INPUT, + "Operation input targets a deprecated shape", + RelationshipType.OUTPUT, + "Operation output targets a deprecated shape", + RelationshipType.ERROR, + "Operation error targets a deprecated shape", + RelationshipType.MIXIN, + "Applies a deprecated mixin" ); @Override @@ -81,10 +81,10 @@ public List validate(Model model) { } private void validateShape( - Model model, - Shape shape, - List relationships, - List mutableEvents + Model model, + Shape shape, + List relationships, + List mutableEvents ) { for (Relationship relationship : relationships) { if (relationship.getNeighborShape().isPresent()) { @@ -96,27 +96,27 @@ private void validateShape( } private void validateTarget( - Model model, - Shape shape, - Shape target, - Relationship rel, - List events + Model model, + Shape shape, + Shape target, + Relationship rel, + List events ) { RelationshipType relType = rel.getRelationshipType(); if (relType != RelationshipType.MIXIN && relType.getDirection() == RelationshipDirection.DIRECTED) { if (target.hasTrait(TraitDefinition.class)) { events.add( - error( - shape, - format( - "Found a %s reference to trait definition `%s`. Trait definitions cannot be targeted by " - + "members or referenced by shapes in any other context other than applying them as " - + "traits.", - relType, - rel.getNeighborShapeId() + error( + shape, + format( + "Found a %s reference to trait definition `%s`. Trait definitions cannot be targeted by " + + "members or referenced by shapes in any other context other than applying them as " + + "traits.", + relType, + rel.getNeighborShapeId() + ) ) - ) ); return; } @@ -124,15 +124,15 @@ private void validateTarget( // Ignoring members with the mixin trait, forbid shapes to reference mixins except as mixins. if (!target.isMemberShape() && target.hasTrait(MixinTrait.class)) { events.add( - error( - shape, - format( - "Illegal %s reference to mixin `%s`; shapes marked with the mixin trait can only be " - + "referenced to apply them as a mixin.", - relType, - rel.getNeighborShapeId() + error( + shape, + format( + "Illegal %s reference to mixin `%s`; shapes marked with the mixin trait can only be " + + "referenced to apply them as a mixin.", + relType, + rel.getNeighborShapeId() + ) ) - ) ); return; } @@ -146,14 +146,14 @@ private void validateTarget( // Members and property cannot target other members, service, operation, or resource shapes. if (INVALID_MEMBER_TARGETS.contains(target.getType())) { events.add( - error( - shape, - format( - "Members cannot target %s shapes, but found %s", - target.getType(), - target + error( + shape, + format( + "Members cannot target %s shapes, but found %s", + target.getType(), + target + ) ) - ) ); } break; @@ -197,27 +197,27 @@ private void validateTarget( case LIST: if (target.getType() != ShapeType.OPERATION) { events.add( - error( - shape, - format( - "Resource %s lifecycle operation must target an operation, but found %s", - relType.toString().toLowerCase(Locale.US), - target + error( + shape, + format( + "Resource %s lifecycle operation must target an operation, but found %s", + relType.toString().toLowerCase(Locale.US), + target + ) ) - ) ); } break; case MIXIN: if (!target.hasTrait(MixinTrait.class)) { events.add( - error( - shape, - format( - "Attempted to use %s as a mixin, but it is not marked with the mixin trait", - target.getId() + error( + shape, + format( + "Attempted to use %s as a mixin, but it is not marked with the mixin trait", + target.getId() + ) ) - ) ); } break; @@ -227,10 +227,10 @@ private void validateTarget( } private void validateDeprecatedTargets( - Shape shape, - Shape target, - RelationshipType relType, - List events + Shape shape, + Shape target, + RelationshipType relType, + List events ) { if (!target.hasTrait(DeprecatedTrait.class)) { return; @@ -246,12 +246,12 @@ private void validateDeprecatedTargets( deprecatedTrait.getMessage().ifPresent(message -> builder.append(". ").append(message)); deprecatedTrait.getSince().ifPresent(since -> builder.append(" (since ").append(since).append(')')); events.add( - ValidationEvent.builder() - .id("DeprecatedShape." + target.getId()) - .severity(Severity.WARNING) - .shape(shape) - .message(builder.toString()) - .build() + ValidationEvent.builder() + .id("DeprecatedShape." + target.getId()) + .severity(Severity.WARNING) + .shape(shape) + .message(builder.toString()) + .build() ); } @@ -274,36 +274,36 @@ private ValidationEvent unresolvedTarget(Model model, Shape shape, Relationship // positives than are useful. Collection suggestions = computeTargetSuggestions(model, rel.getNeighborShapeId()); String suggestionText = !suggestions.isEmpty() - ? ". Did you mean " + String.join(", ", suggestions) + "?" - : ""; + ? ". Did you mean " + String.join(", ", suggestions) + "?" + : ""; if (rel.getRelationshipType() == RelationshipType.MEMBER_TARGET) { // Don't show the relationship type for invalid member targets. return error( - shape, - String.format( - "member shape targets an unresolved shape `%s`%s", - rel.getNeighborShapeId(), - suggestionText - ), - UNRESOLVED_SHAPE_PART + shape, + String.format( + "member shape targets an unresolved shape `%s`%s", + rel.getNeighborShapeId(), + suggestionText + ), + UNRESOLVED_SHAPE_PART ); } else { // Use "a" or "an" depending on if the relationship starts with a vowel. String indefiniteArticle = isUppercaseVowel(rel.getRelationshipType().toString().charAt(0)) - ? "an" - : "a"; + ? "an" + : "a"; return error( - shape, - String.format( - "%s shape has %s `%s` relationship to an unresolved shape `%s`%s", - shape.getType(), - indefiniteArticle, - rel.getRelationshipType().toString().toLowerCase(Locale.US), - rel.getNeighborShapeId(), - suggestionText - ), - UNRESOLVED_SHAPE_PART + shape, + String.format( + "%s shape has %s `%s` relationship to an unresolved shape `%s`%s", + shape.getType(), + indefiniteArticle, + rel.getRelationshipType().toString().toLowerCase(Locale.US), + rel.getNeighborShapeId(), + suggestionText + ), + UNRESOLVED_SHAPE_PART ); } } @@ -338,36 +338,36 @@ private static boolean isUppercaseVowel(char c) { private ValidationEvent badType(Shape shape, Shape target, RelationshipType rel, ShapeType valid) { return error( - shape, - format( - "%s shape `%s` relationships must target a %s shape, but found %s", - shape.getType(), - rel.toString().toLowerCase(Locale.US), - valid, - target - ) + shape, + format( + "%s shape `%s` relationships must target a %s shape, but found %s", + shape.getType(), + rel.toString().toLowerCase(Locale.US), + valid, + target + ) ); } private ValidationEvent inputOutputWithErrorTrait(Shape shape, Shape target, RelationshipType rel) { String descriptor = rel == RelationshipType.INPUT ? "input" : "output"; return error( - shape, - format( - "Operation %s targets an invalid structure `%s` that is marked with the `error` trait.", - descriptor, - target.getId() - ) + shape, + format( + "Operation %s targets an invalid structure `%s` that is marked with the `error` trait.", + descriptor, + target.getId() + ) ); } private ValidationEvent errorNoTrait(Shape shape, ShapeId target) { return error( - shape, - format( - "`%s` cannot be bound as an error because it is not marked with the `error` trait.", - target - ) + shape, + format( + "`%s` cannot be bound as an error because it is not marked with the `error` trait.", + target + ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitBreakingChangesValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitBreakingChangesValidator.java index 384da4b653c..74de0922293 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitBreakingChangesValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitBreakingChangesValidator.java @@ -40,8 +40,8 @@ private void validateTrait(Model model, Shape shape, List event for (String part : pointer.getParts()) { Shape previous = current; current = current.getMember(part) - .flatMap(member -> model.getShape(member.getTarget())) - .orElse(null); + .flatMap(member -> model.getShape(member.getTarget())) + .orElse(null); if (current == null) { events.add(emit(shape, i, segment, previous)); break; @@ -56,18 +56,18 @@ private ValidationEvent emit(Shape shape, int element, int segment, Shape evalua TraitDefinition definition = shape.expectTrait(TraitDefinition.class); NodePointer path = definition.getBreakingChanges().get(element).getDefaultedPath(); return error( - shape, - definition, - String.format( - "Invalid trait breakingChanges element %d, '%s', at segment '%s': " - + "Evaluated shape `%s`, a %s, has no member named `%s`", - element, - path, - path.getParts().get(segment), - evaluated.getId(), - evaluated.getType(), - path.getParts().get(segment) - ) + shape, + definition, + String.format( + "Invalid trait breakingChanges element %d, '%s', at segment '%s': " + + "Evaluated shape `%s`, a %s, has no member named `%s`", + element, + path, + path.getParts().get(segment), + evaluated.getId(), + evaluated.getType(), + path.getParts().get(segment) + ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitConflictValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitConflictValidator.java index 4277f4533bb..f0f2c6f67d9 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitConflictValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitConflictValidator.java @@ -50,18 +50,18 @@ public List validate(Model model) { // Find shapes that use this trait and also apply conflicting traits. private void findAndCollectConflicts( - Model model, - ShapeId trait, - List conflicts, - Map>> shapeToTraitConflicts + Model model, + ShapeId trait, + List conflicts, + Map>> shapeToTraitConflicts ) { for (Shape shape : model.getShapesWithTrait(trait)) { for (ShapeId conflict : conflicts) { if (shape.hasTrait(conflict)) { shapeToTraitConflicts - .computeIfAbsent(shape, id -> new HashMap<>()) - .computeIfAbsent(trait, id -> new ArrayList<>()) - .add(conflict); + .computeIfAbsent(shape, id -> new HashMap<>()) + .computeIfAbsent(trait, id -> new ArrayList<>()) + .add(conflict); } } } @@ -69,13 +69,13 @@ private void findAndCollectConflicts( private ValidationEvent emitForConflicts(Shape shape, Map> conflicts) { return error( - shape, - "Found conflicting traits on " + shape.getType() + " shape: " - + conflicts.entrySet() - .stream() - .flatMap(this::lines) - .sorted() - .collect(Collectors.joining(", ")) + shape, + "Found conflicting traits on " + shape.getType() + " shape: " + + conflicts.entrySet() + .stream() + .flatMap(this::lines) + .sorted() + .collect(Collectors.joining(", ")) ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitTargetValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitTargetValidator.java index beae9dce3e7..19fa56402b0 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitTargetValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitTargetValidator.java @@ -51,8 +51,8 @@ public List validate(Model model) { // Short circuit for traits that match everything. if (!definition.getSelector().toString().equals("*")) { selectorsToTraits - .computeIfAbsent(definition.getSelector(), selector -> new ArrayList<>()) - .add(traitId); + .computeIfAbsent(definition.getSelector(), selector -> new ArrayList<>()) + .add(traitId); } }); }); @@ -69,24 +69,24 @@ private void validateMixinsUsedAsTraits(Shape traitShape, Set appliedTo, if (traitShape.hasTrait(MixinTrait.class)) { for (Shape shape : appliedTo) { events.add( - error( - shape, - String.format( - "Trait `%s` is a mixin and cannot be applied to `%s`.", - Trait.getIdiomaticTraitName(traitShape.getId()), - shape.getId() + error( + shape, + String.format( + "Trait `%s` is a mixin and cannot be applied to `%s`.", + Trait.getIdiomaticTraitName(traitShape.getId()), + shape.getId() + ) ) - ) ); } } } private void validateTraitTargets( - Model model, - List events, - Selector selector, - List traits + Model model, + List events, + Selector selector, + List traits ) { Set matches = selector.select(model); @@ -98,17 +98,17 @@ private void validateTraitTargets( // Strip out newlines with successive spaces. String sanitized = SANITIZE.matcher(selector.toString()).replaceAll(" "); events.add( - error( - shape, - shape.findTrait(traitId).get(), - String.format( - "Trait `%s` cannot be applied to `%s`. This trait may only be applied " - + "to shapes that match the following selector: %s", - Trait.getIdiomaticTraitName(traitId), - shape.getId(), - sanitized + error( + shape, + shape.findTrait(traitId).get(), + String.format( + "Trait `%s` cannot be applied to `%s`. This trait may only be applied " + + "to shapes that match the following selector: %s", + Trait.getIdiomaticTraitName(traitId), + shape.getId(), + sanitized + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitValidatorsValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitValidatorsValidator.java index 938a4e1e6c7..a8e151a08d6 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitValidatorsValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitValidatorsValidator.java @@ -43,12 +43,12 @@ private boolean isValid(Shape shape, List events) { for (String key : trait.getValidators().keySet()) { if (!ShapeId.isValidNamespace(key)) { events.add( - error( - shape, - trait, - "`" + TraitValidatorsTrait.ID + "` key is not a valid event ID: `" - + key + '`' - ) + error( + shape, + trait, + "`" + TraitValidatorsTrait.ID + "` key is not a valid event ID: `" + + key + '`' + ) ); isValid = false; } @@ -57,10 +57,10 @@ private boolean isValid(Shape shape, List events) { } private void emitIncompatibleShapes( - Model model, - Shape traitWithValidators, - Shape appliedShape, - List events + Model model, + Shape traitWithValidators, + Shape appliedShape, + List events ) { Selector.StartingContext startingEnv = new Selector.StartingContext(Collections.singleton(appliedShape)); TraitValidatorsTrait trait = traitWithValidators.expectTrait(TraitValidatorsTrait.class); @@ -71,34 +71,34 @@ private void emitIncompatibleShapes( for (Shape shape : definition.getSelector().select(model, startingEnv)) { String suffix = definition.getMessage().orElse(null); events.add( - createEvent( - traitWithValidators, - appliedShape, - id, - shape, - definition.getSeverity(), - suffix - ) + createEvent( + traitWithValidators, + appliedShape, + id, + shape, + definition.getSeverity(), + suffix + ) ); } } } private ValidationEvent createEvent( - Shape traitWithValidators, - Shape appliedShape, - String eventId, - Shape shape, - Severity severity, - String suffix + Shape traitWithValidators, + Shape appliedShape, + String eventId, + Shape shape, + Severity severity, + String suffix ) { String suffixMessage = suffix == null ? "" : ": " + suffix; String message = String.format( - "Found an incompatible shape when validating the constraints of the `%s` trait " - + "attached to `%s`%s", - traitWithValidators.getId(), - appliedShape.getId(), - suffixMessage + "Found an incompatible shape when validating the constraints of the `%s` trait " + + "attached to `%s`%s", + traitWithValidators.getId(), + appliedShape.getId(), + suffixMessage ); return ValidationEvent.builder().id(eventId).shape(shape).message(message).severity(severity).build(); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitValueValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitValueValidator.java index 1567067f6fa..8f74d6f127a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitValueValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitValueValidator.java @@ -30,10 +30,10 @@ public List validate(Model model) { // Create a reusable validation visitor so that the // selector cache is shared for each trait. NodeValidationVisitor validator = NodeValidationVisitor.builder() - .eventId(NAME) - .model(model) - .value(Node.nullNode()) - .build(); + .eventId(NAME) + .model(model) + .value(Node.nullNode()) + .build(); List events = new ArrayList<>(); boolean validatePrelude = model.getMetadataProperty(VALIDATE_PRELUDE).isPresent(); @@ -47,11 +47,11 @@ public List validate(Model model) { } private List validateTrait( - Model model, - NodeValidationVisitor validator, - Shape targetShape, - Trait trait, - boolean validatePrelude + Model model, + NodeValidationVisitor validator, + Shape targetShape, + Trait trait, + boolean validatePrelude ) { ShapeId shape = trait.toShapeId(); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnionValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnionValidator.java index cd5fa40f9ae..c8e3d4a26f3 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnionValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnionValidator.java @@ -39,17 +39,17 @@ public List validate(Model model) { private void validateUnionMemberTarget(MemberShape member, Shape target, List events) { if (target.hasTrait(DefaultTrait.class)) { events.add( - note( - member, - String.format( - "This union member targets `%s`, a shape with a default value of `%s`. Note that " - + "default values are only applicable to structures and ignored in tagged unions. It " - + "is a best practice for union members to target shapes with no default value (for example, " - + "instead of targeting PrimitiveInteger, target Integer).", - target.getId(), - Node.printJson(target.expectTrait(DefaultTrait.class).toNode()) + note( + member, + String.format( + "This union member targets `%s`, a shape with a default value of `%s`. Note that " + + "default values are only applicable to structures and ignored in tagged unions. It " + + "is a best practice for union members to target shapes with no default value (for example, " + + "instead of targeting PrimitiveInteger, target Integer).", + target.getId(), + Node.printJson(target.expectTrait(DefaultTrait.class).toNode()) + ) ) - ) ); } } @@ -57,12 +57,12 @@ private void validateUnionMemberTarget(MemberShape member, Shape target, List events) { if (member.hasTrait(BoxTrait.class)) { events.add( - warning( - member, - member.expectTrait(BoxTrait.class), - "Invalid box trait found on a union member. The box trait on union members " - + "has no effect because union members are implicitly nullable." - ) + warning( + member, + member.expectTrait(BoxTrait.class), + "Invalid box trait found on a union member. The box trait on union members " + + "has no effect because union members are implicitly nullable." + ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnitTypeValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnitTypeValidator.java index 0f318c02823..08acd36fb6f 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnitTypeValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnitTypeValidator.java @@ -40,32 +40,32 @@ public List validate(Model model) { break; case MEMBER_TARGET: relationship.getShape() - .asMemberShape() - .map(MemberShape::getContainer) - .flatMap(model::getShape) - .filter( - shape -> !(shape.getType() == ShapeType.UNION - || shape.getType() == ShapeType.ENUM - || shape.getType() == ShapeType.INT_ENUM) - ) - .ifPresent(container -> { - events.add( - error( - relationship.getShape(), - "Only members of a union, enum, or intEnum can reference smithy.api#Unit" - ) - ); - }); + .asMemberShape() + .map(MemberShape::getContainer) + .flatMap(model::getShape) + .filter( + shape -> !(shape.getType() == ShapeType.UNION + || shape.getType() == ShapeType.ENUM + || shape.getType() == ShapeType.INT_ENUM) + ) + .ifPresent(container -> { + events.add( + error( + relationship.getShape(), + "Only members of a union, enum, or intEnum can reference smithy.api#Unit" + ) + ); + }); break; default: events.add( - error( - relationship.getShape(), - String.format( - "This shape has an invalid %s reference to smithy.api#Unit", - relationship.getRelationshipType() + error( + relationship.getShape(), + String.format( + "This shape has an invalid %s reference to smithy.api#Unit", + relationship.getRelationshipType() + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnreferencedShapeValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnreferencedShapeValidator.java index 809c3e61cc8..c295c92e1d0 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnreferencedShapeValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnreferencedShapeValidator.java @@ -32,13 +32,13 @@ public List validate(Model model) { List events = new ArrayList<>(); for (Shape shape : new UnreferencedShapes().compute(model)) { events.add( - note( - shape, - String.format( - "The %s shape is not connected to from any service shape.", - shape.getType() + note( + shape, + String.format( + "The %s shape is not connected to from any service shape.", + shape.getType() + ) ) - ) ); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnstableTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnstableTraitValidator.java index 37d793fad91..0ad1d743a16 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnstableTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnstableTraitValidator.java @@ -25,12 +25,12 @@ public List validate(Model model) { for (Shape trait : model.getShapesWithTrait(UnstableTrait.class)) { for (Shape appliedTo : model.getShapesWithTrait(trait)) { events.add( - warning( - appliedTo, - appliedTo.findTrait(trait.getId()).get(), // point to the applied trait which for sure exists. - format("This shape applies a trait that is unstable: %s", trait.toShapeId()), - trait.toShapeId().toString() - ) + warning( + appliedTo, + appliedTo.findTrait(trait.getId()).get(), // point to the applied trait which for sure exists. + format("This shape applies a trait that is unstable: %s", trait.toShapeId()), + trait.toShapeId().toString() + ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/XmlFlattenedTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/XmlFlattenedTraitValidator.java index 46abaecf537..09bc121ef10 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/XmlFlattenedTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/XmlFlattenedTraitValidator.java @@ -43,17 +43,17 @@ private void validateMemberTargetingList(MemberShape member, ListShape targetLis XmlNameTrait xmlName = targetList.getMember().expectTrait(XmlNameTrait.class); if (!member.getMemberName().equals(xmlName.getValue())) { events.add( - warning( - member, - String.format( - "Member is `@xmlFlattened`, so `@xmlName` of target's member (`%s`) has no effect." - + " The flattened list elements will have the name of this member - `%s`. If this" - + " is unintended, you can add `@xmlName(\"%s\")` to this member.", - targetList.getMember().getId(), - member.getMemberName(), - xmlName.getValue() + warning( + member, + String.format( + "Member is `@xmlFlattened`, so `@xmlName` of target's member (`%s`) has no effect." + + " The flattened list elements will have the name of this member - `%s`. If this" + + " is unintended, you can add `@xmlName(\"%s\")` to this member.", + targetList.getMember().getId(), + member.getMemberName(), + xmlName.getValue() + ) ) - ) ); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/XmlNamespaceTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/XmlNamespaceTraitValidator.java index 27f8b262459..2244417ff4f 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/XmlNamespaceTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/XmlNamespaceTraitValidator.java @@ -40,14 +40,14 @@ private Optional validateTrait(Shape shape, XmlNamespaceTrait x new java.net.URI(xmlNamespace.getUri()); } catch (java.net.URISyntaxException uriSyntaxException) { return Optional.of( - error( - shape, - format( - "An `xmlNamespace` trait is applied to the %s shape with an invalid uri: %s", - shape, - xmlNamespace.getUri() + error( + shape, + format( + "An `xmlNamespace` trait is applied to the %s shape with an invalid uri: %s", + shape, + xmlNamespace.getUri() + ) ) - ) ); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/ModelTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/ModelTest.java index 0cbddb93139..ba4aa747829 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/ModelTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/ModelTest.java @@ -40,14 +40,14 @@ public class ModelTest { @Test public void buildsModel() { Model model = Model.builder() - .putMetadataProperty("name.name", Node.objectNode()) - .addShape( - StringShape.builder() - .id("smithy.example#String") - .addTrait(TraitDefinition.builder().build()) - .build() - ) - .build(); + .putMetadataProperty("name.name", Node.objectNode()) + .addShape( + StringShape.builder() + .id("smithy.example#String") + .addTrait(TraitDefinition.builder().build()) + .build() + ) + .build(); assertTrue(model.getMetadataProperty("name.name").isPresent()); assertThat(model.getShapesWithTrait(TraitDefinition.class), hasSize(1)); @@ -56,12 +56,12 @@ public void buildsModel() { @Test public void modelEquality() { Model modelA = Model.builder() - .putMetadataProperty("foo", Node.from("baz")) - .addShape(StringShape.builder().id("ns.foo#baz").build()) - .build(); + .putMetadataProperty("foo", Node.from("baz")) + .addShape(StringShape.builder().id("ns.foo#baz").build()) + .build(); Model modelB = Model.builder() - .putMetadataProperty("foo", Node.from("baz")) - .build(); + .putMetadataProperty("foo", Node.from("baz")) + .build(); assertThat(modelA, equalTo(modelA)); assertThat(modelA, not(equalTo(modelB))); @@ -71,28 +71,28 @@ public void modelEquality() { @Test public void modelEqualityExamples() { StructureShape opInput = StructureShape.builder() - .id(ShapeId.fromParts("foo", "FooInput")) - .addMember("test", ShapeId.from("smithy.api#String")) - .build(); + .id(ShapeId.fromParts("foo", "FooInput")) + .addMember("test", ShapeId.from("smithy.api#String")) + .build(); Supplier op = () -> { ExamplesTrait.Example example = ExamplesTrait.Example.builder() - .title("anything") - .input(ObjectNode.builder().withMember("test", StringNode.from("something")).build()) - .build(); + .title("anything") + .input(ObjectNode.builder().withMember("test", StringNode.from("something")).build()) + .build(); ExamplesTrait examples = ExamplesTrait.builder().addExample(example).build(); return OperationShape.builder() - .id(ShapeId.fromParts("foo", "Foo")) - .input(opInput) - .addTrait(examples) - .build(); + .id(ShapeId.fromParts("foo", "Foo")) + .input(opInput) + .addTrait(examples) + .build(); }; Model modelA = Model.builder() - .addShape(op.get()) - .build(); + .addShape(op.get()) + .build(); Model modelB = Model.builder() - .addShape(op.get()) - .build(); + .addShape(op.get()) + .build(); assertThat(modelA, equalTo(modelA)); assertThat(modelA, equalTo(modelB)); @@ -131,10 +131,10 @@ public void getsShapesAsType() { StringShape b = StringShape.builder().id("ns.foo#b").build(); TimestampShape c = TimestampShape.builder().id("ns.foo#c").build(); Model model = Model.builder() - .addShape(a) - .addShape(b) - .addShape(c) - .build(); + .addShape(a) + .addShape(b) + .addShape(c) + .build(); List shapes = model.shapes(StringShape.class).collect(Collectors.toList()); assertThat(shapes, hasSize(2)); @@ -161,9 +161,9 @@ public void canRemoveShapeById() { StringShape a = StringShape.builder().id("ns.foo#a").build(); StringShape b = StringShape.builder().id("ns.foo#b").build(); Model model = Model.builder() - .addShapes(Arrays.asList(a, b)) - .removeShape(ShapeId.from("ns.foo#a")) - .build(); + .addShapes(Arrays.asList(a, b)) + .removeShape(ShapeId.from("ns.foo#a")) + .build(); List shapes = model.shapes().collect(Collectors.toList()); assertThat(shapes, hasSize(1)); @@ -239,9 +239,9 @@ public void toSetWithTypeRespectsSubclassing() { public void addsMembersAutomatically() { StringShape string = StringShape.builder().id("ns.foo#a").build(); ListShape list = ListShape.builder() - .id("ns.foo#list") - .member(ShapeId.from("ns.foo#a")) - .build(); + .id("ns.foo#list") + .member(ShapeId.from("ns.foo#a")) + .build(); Model model = Model.builder().addShapes(string, list).build(); Set shapes = model.toSet(); @@ -253,13 +253,13 @@ public void addsMembersAutomatically() { public void removesMembersAutomatically() { StringShape string = StringShape.builder().id("ns.foo#a").build(); ListShape list = ListShape.builder() - .id("ns.foo#list") - .member(ShapeId.from("ns.foo#a")) - .build(); + .id("ns.foo#list") + .member(ShapeId.from("ns.foo#a")) + .build(); Model model = Model.builder() - .addShapes(string, list) - .removeShape(list.getId()) - .build(); + .addShapes(string, list) + .removeShape(list.getId()) + .build(); Set shapes = model.toSet(); assertThat(shapes, hasSize(1)); @@ -270,12 +270,12 @@ public void removesMembersAutomatically() { public void syntheticTraitsCanBeQueriedLikeNormalTraits() { ShapeId originalId = ShapeId.from("com.foo.nested#Str"); StringShape stringShape = StringShape.builder() - .id("com.foo#Str") - .addTrait(new OriginalShapeIdTrait(originalId)) - .build(); + .id("com.foo#Str") + .addTrait(new OriginalShapeIdTrait(originalId)) + .build(); Model model = Model.builder() - .addShape(stringShape) - .build(); + .addShape(stringShape) + .build(); assertThat(model.getShapesWithTrait(OriginalShapeIdTrait.class), contains(stringShape)); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/ShapeMatcher.java b/smithy-model/src/test/java/software/amazon/smithy/model/ShapeMatcher.java index 7ea538303fe..588100353e9 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/ShapeMatcher.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/ShapeMatcher.java @@ -35,10 +35,10 @@ public final class ShapeMatcher extends TypeSafeMatcher shapeType, - ValidatedResult result, - String description, - List, Function>> assertions + Class shapeType, + ValidatedResult result, + String description, + List, Function>> assertions ) { this.shapeType = shapeType; this.result = result; @@ -69,10 +69,10 @@ public static Builder builderFor(Class shapeType, Valida * @return Returns the created matcher. */ public static ShapeMatcher hasEvent( - ValidatedResult result, - String eventId, - Severity severity, - String messageContains + ValidatedResult result, + String eventId, + Severity severity, + String messageContains ) { return builderFor(Shape.class, result).addEventAssertion(eventId, severity, messageContains).build(); } @@ -85,32 +85,32 @@ public static ShapeMatcher hasEvent( */ public static ShapeMatcher memberIsNullable(ValidatedResult result) { return ShapeMatcher.builderFor(MemberShape.class, result) - .description("Member is marked with @required or @default trait") - .addAssertion( - member -> !member.hasTrait(RequiredTrait.class), - member -> "Member is marked with the @required trait" - ) - .addAssertion(member -> { - DefaultTrait trait = member.getTrait(DefaultTrait.class).orElse(null); - return trait == null || trait.toNode().isNullNode(); - }, - member -> "Member is marked with the @default trait" - ) - .build(); + .description("Member is marked with @required or @default trait") + .addAssertion( + member -> !member.hasTrait(RequiredTrait.class), + member -> "Member is marked with the @required trait" + ) + .addAssertion(member -> { + DefaultTrait trait = member.getTrait(DefaultTrait.class).orElse(null); + return trait == null || trait.toNode().isNullNode(); + }, + member -> "Member is marked with the @default trait" + ) + .build(); } private static boolean findEvent( - ValidatedResult result, - String eventId, - ToShapeId id, - Severity severity, - String contains + ValidatedResult result, + String eventId, + ToShapeId id, + Severity severity, + String contains ) { for (ValidationEvent event : result.getValidationEvents()) { if (event.getShapeId().filter(sid -> sid.equals(id.toShapeId())).isPresent() - && event.getSeverity() == severity - && event.containsId(eventId) - && event.getMessage().contains(contains)) { + && event.getSeverity() == severity + && event.containsId(eventId) + && event.getMessage().contains(contains)) { return true; } } @@ -124,18 +124,18 @@ protected final boolean matchesSafely(ShapeId id) { } return result.getResult() - .flatMap(model -> model.getShape(id)) - .filter(shapeType::isInstance) - .map(shapeType::cast) - .filter(s -> { - for (Pair, Function> pair : assertions) { - if (!pair.left.test(s)) { - return false; + .flatMap(model -> model.getShape(id)) + .filter(shapeType::isInstance) + .map(shapeType::cast) + .filter(s -> { + for (Pair, Function> pair : assertions) { + if (!pair.left.test(s)) { + return false; + } } - } - return true; - }) - .isPresent(); + return true; + }) + .isPresent(); } @Override @@ -229,11 +229,11 @@ public Builder addAssertion(Predicate test, Function errorSuppl */ public Builder addEventAssertion(String eventId, Severity severity, String messageContains) { return addAssertion( - shape -> findEvent(result, eventId, shape.getId(), severity, messageContains), - shape -> "No event matched ID " + eventId + " on shape " + shape.getId() - + " with severity " + severity + " containing a message of '" - + messageContains + "'. Found the following events: " - + result.getValidationEvents() + shape -> findEvent(result, eventId, shape.getId(), severity, messageContains), + shape -> "No event matched ID " + eventId + " on shape " + shape.getId() + + " with severity " + severity + " containing a message of '" + + messageContains + "'. Found the following events: " + + result.getValidationEvents() ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/SourceLocationTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/SourceLocationTest.java index 341a1fb6fb8..18d98d20610 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/SourceLocationTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/SourceLocationTest.java @@ -17,35 +17,35 @@ public class SourceLocationTest { @Test public void sortsSourceLocations() { Model model = Model.builder() - .addShape( - StringShape.builder() - .id("smithy.example#First") - .source(new SourceLocation("a.smithy", 1, 1)) - .build() - ) - .addShape( - StringShape.builder() - .id("smithy.example#Second") - .source(new SourceLocation("a.smithy", 1, 2)) - .build() - ) - .addShape( - StringShape.builder() - .id("smithy.example#Third") - .source(new SourceLocation("a.smithy", 2, 1)) - .build() - ) - .addShape( - StringShape.builder() - .id("smithy.example#Fourth") - .source(new SourceLocation("b.smithy", 1, 1)) - .build() - ) - .build(); + .addShape( + StringShape.builder() + .id("smithy.example#First") + .source(new SourceLocation("a.smithy", 1, 1)) + .build() + ) + .addShape( + StringShape.builder() + .id("smithy.example#Second") + .source(new SourceLocation("a.smithy", 1, 2)) + .build() + ) + .addShape( + StringShape.builder() + .id("smithy.example#Third") + .source(new SourceLocation("a.smithy", 2, 1)) + .build() + ) + .addShape( + StringShape.builder() + .id("smithy.example#Fourth") + .source(new SourceLocation("b.smithy", 1, 1)) + .build() + ) + .build(); List shapes = model.shapes() - .sorted(Comparator.comparing(Shape::getSourceLocation)) - .collect(Collectors.toList()); + .sorted(Comparator.comparing(Shape::getSourceLocation)) + .collect(Collectors.toList()); assertEquals("First", shapes.get(0).getId().getName()); assertEquals("Second", shapes.get(1).getId().getName()); assertEquals("Third", shapes.get(2).getId().getName()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/BottomUpIndexTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/BottomUpIndexTest.java index 95665f64b4c..250eb0f5e48 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/BottomUpIndexTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/BottomUpIndexTest.java @@ -25,9 +25,9 @@ public class BottomUpIndexTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(OperationIndexTest.class.getResource("bottom-up.smithy")) - .assemble() - .unwrap(); + .addImport(OperationIndexTest.class.getResource("bottom-up.smithy")) + .assemble() + .unwrap(); } @AfterAll @@ -41,53 +41,54 @@ public void findsEntityBinding() { assertThat(index.getEntityBinding(serviceId, serviceId), equalTo(Optional.empty())); assertThat( - index.getEntityBinding(serviceId, ShapeId.from("smithy.example#ServiceOperation")).map(EntityShape::getId), - equalTo(Optional.of(serviceId)) + index.getEntityBinding(serviceId, ShapeId.from("smithy.example#ServiceOperation")) + .map(EntityShape::getId), + equalTo(Optional.of(serviceId)) ); assertThat( - index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1")).map(EntityShape::getId), - equalTo(Optional.of(serviceId)) + index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1")).map(EntityShape::getId), + equalTo(Optional.of(serviceId)) ); assertThat( - index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1Operation")) - .map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1"))) + index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1Operation")) + .map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1"))) ); assertThat( - index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_1")).map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1"))) + index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_1")).map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1"))) ); assertThat( - index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_2")).map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1"))) + index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_2")).map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1"))) ); assertThat( - index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_Operation")) - .map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) + index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_Operation")) + .map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) ); assertThat( - index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_1")).map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) + index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_1")).map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) ); assertThat( - index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_2")).map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) + index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_2")).map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) ); assertThat( - index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_Operation")) - .map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) + index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_Operation")) + .map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) ); assertThat( - index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_1_Operation")) - .map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1_1"))) + index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_1_Operation")) + .map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1_1"))) ); assertThat( - index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_2_Operation")) - .map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1_2"))) + index.getEntityBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_2_Operation")) + .map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1_2"))) ); } @@ -97,54 +98,56 @@ public void findsResourceBinding() { assertThat(index.getResourceBinding(serviceId, serviceId), equalTo(Optional.empty())); assertThat( - index.getResourceBinding(serviceId, ShapeId.from("smithy.example#ServiceOperation")) - .map(EntityShape::getId), - equalTo(Optional.empty()) + index.getResourceBinding(serviceId, ShapeId.from("smithy.example#ServiceOperation")) + .map(EntityShape::getId), + equalTo(Optional.empty()) ); assertThat( - index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1")).map(EntityShape::getId), - equalTo(Optional.empty()) + index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1")).map(EntityShape::getId), + equalTo(Optional.empty()) ); assertThat( - index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1Operation")) - .map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1"))) + index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1Operation")) + .map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1"))) ); assertThat( - index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_1")).map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1"))) + index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_1")).map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1"))) ); assertThat( - index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_2")).map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1"))) + index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_2")).map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1"))) ); assertThat( - index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_Operation")) - .map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) + index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_Operation")) + .map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) ); assertThat( - index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_1")).map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) + index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_1")) + .map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) ); assertThat( - index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_2")).map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) + index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_2")) + .map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) ); assertThat( - index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_Operation")) - .map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) + index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_Operation")) + .map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1"))) ); assertThat( - index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_1_Operation")) - .map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1_1"))) + index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_1_Operation")) + .map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1_1"))) ); assertThat( - index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_2_Operation")) - .map(EntityShape::getId), - equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1_2"))) + index.getResourceBinding(serviceId, ShapeId.from("smithy.example#Resource1_1_2_Operation")) + .map(EntityShape::getId), + equalTo(Optional.of(ShapeId.from("smithy.example#Resource1_1_2"))) ); } @@ -152,22 +155,22 @@ public void findsResourceBinding() { public void findsPathToLeafOperation() { BottomUpIndex index = BottomUpIndex.of(model); List entities = index.getAllParents( - serviceId, - ShapeId.from("smithy.example#Resource1_1_2_Operation") + serviceId, + ShapeId.from("smithy.example#Resource1_1_2_Operation") ); List ids = entities.stream() - .map(EntityShape::getId) - .map(ShapeId::toString) - .collect(Collectors.toList()); + .map(EntityShape::getId) + .map(ShapeId::toString) + .collect(Collectors.toList()); assertThat( - ids, - contains( - "smithy.example#Resource1_1_2", - "smithy.example#Resource1_1", - "smithy.example#Resource1", - "smithy.example#Example" - ) + ids, + contains( + "smithy.example#Resource1_1_2", + "smithy.example#Resource1_1", + "smithy.example#Resource1", + "smithy.example#Example" + ) ); } @@ -175,13 +178,13 @@ public void findsPathToLeafOperation() { public void findsPathToLeafResource() { BottomUpIndex index = BottomUpIndex.of(model); List entities = index.getAllParents( - serviceId, - ShapeId.from("smithy.example#Resource1_1_2") + serviceId, + ShapeId.from("smithy.example#Resource1_1_2") ); List ids = entities.stream() - .map(EntityShape::getId) - .map(ShapeId::toString) - .collect(Collectors.toList()); + .map(EntityShape::getId) + .map(ShapeId::toString) + .collect(Collectors.toList()); assertThat(ids, contains("smithy.example#Resource1_1", "smithy.example#Resource1", "smithy.example#Example")); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/EventStreamIndexTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/EventStreamIndexTest.java index a61b0fbfb32..760835e19c7 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/EventStreamIndexTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/EventStreamIndexTest.java @@ -22,9 +22,9 @@ public class EventStreamIndexTest { @BeforeAll public static void beforeAll() { model = Model.assembler() - .addImport(EventStreamIndexTest.class.getResource("event-stream-index.json")) - .assemble() - .unwrap(); + .addImport(EventStreamIndexTest.class.getResource("event-stream-index.json")) + .assemble() + .unwrap(); } @Test @@ -46,8 +46,8 @@ public void providesEmptyOptionalWhenNoInput() { EventStreamIndex index = EventStreamIndex.of(model); assertThat( - index.getInputInfo(ShapeId.from("example.smithy#EmptyOperation")), - equalTo(Optional.empty()) + index.getInputInfo(ShapeId.from("example.smithy#EmptyOperation")), + equalTo(Optional.empty()) ); } @@ -56,8 +56,8 @@ public void providesEmptyOptionalWhenNoOutput() { EventStreamIndex index = EventStreamIndex.of(model); assertThat( - index.getOutputInfo(ShapeId.from("example.smithy#EmptyOperation")), - equalTo(Optional.empty()) + index.getOutputInfo(ShapeId.from("example.smithy#EmptyOperation")), + equalTo(Optional.empty()) ); } @@ -66,8 +66,8 @@ public void providesEmptyOptionalWhenNoEventStreamTarget() { EventStreamIndex index = EventStreamIndex.of(model); assertThat( - index.getOutputInfo(ShapeId.from("example.smithy#NotEventStreamOperation")), - equalTo(Optional.empty()) + index.getOutputInfo(ShapeId.from("example.smithy#NotEventStreamOperation")), + equalTo(Optional.empty()) ); } @@ -76,8 +76,8 @@ public void returnsEventStreamInputInformation() { EventStreamIndex index = EventStreamIndex.of(model); assertThat( - index.getOutputInfo(ShapeId.from("example.smithy#NotEventStreamOperation")), - equalTo(Optional.empty()) + index.getOutputInfo(ShapeId.from("example.smithy#NotEventStreamOperation")), + equalTo(Optional.empty()) ); } @@ -88,17 +88,17 @@ public void returnsEventStreamOutputInformation() { assertTrue(index.getInputInfo(ShapeId.from("example.smithy#EventStreamOperation")).isPresent()); assertTrue(index.getOutputInfo(ShapeId.from("example.smithy#EventStreamOperation")).isPresent()); EventStreamInfo input = index.getInputInfo( - ShapeId.from("example.smithy#EventStreamOperation") + ShapeId.from("example.smithy#EventStreamOperation") ).get(); EventStreamInfo output = index.getOutputInfo( - ShapeId.from("example.smithy#EventStreamOperation") + ShapeId.from("example.smithy#EventStreamOperation") ).get(); assertThat(input.getOperation().getId(), equalTo(ShapeId.from("example.smithy#EventStreamOperation"))); assertThat(input.getStructure().getId(), equalTo(ShapeId.from("example.smithy#EventStreamOperationInput"))); assertThat( - input.getEventStreamMember().getId(), - equalTo(ShapeId.from("example.smithy#EventStreamOperationInput$c")) + input.getEventStreamMember().getId(), + equalTo(ShapeId.from("example.smithy#EventStreamOperationInput$c")) ); assertThat(input.getEventStreamTarget().getId(), equalTo(ShapeId.from("example.smithy#InputEventStream"))); assertThat(input.getInitialMessageMembers(), hasKey("a")); @@ -110,8 +110,8 @@ public void returnsEventStreamOutputInformation() { assertThat(output.getOperation().getId(), equalTo(ShapeId.from("example.smithy#EventStreamOperation"))); assertThat(output.getStructure().getId(), equalTo(ShapeId.from("example.smithy#EventStreamOperationOutput"))); assertThat( - output.getEventStreamMember().getId(), - equalTo(ShapeId.from("example.smithy#EventStreamOperationOutput$c")) + output.getEventStreamMember().getId(), + equalTo(ShapeId.from("example.smithy#EventStreamOperationOutput$c")) ); assertThat(output.getEventStreamTarget().getId(), equalTo(ShapeId.from("example.smithy#OutputEventStream"))); assertThat(output.getInitialMessageMembers(), hasKey("a")); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/HttpBindingIndexTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/HttpBindingIndexTest.java index 3f01f31e6fb..546117d670f 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/HttpBindingIndexTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/HttpBindingIndexTest.java @@ -45,9 +45,9 @@ public class HttpBindingIndexTest { @BeforeAll private static void readModel() { model = Model.assembler() - .addImport(HttpBindingIndex.class.getResource("http-index.json")) - .assemble() - .unwrap(); + .addImport(HttpBindingIndex.class.getResource("http-index.json")) + .assemble() + .unwrap(); } @Test @@ -60,10 +60,10 @@ public void providesResponseCode() { @Test public void determinesErrorCodeFromHttpErrorTrait() { StructureShape structure = StructureShape.builder() - .id("ns.foo#Error") - .addTrait(new ErrorTrait("client", SourceLocation.NONE)) - .addTrait(new HttpErrorTrait(400, SourceLocation.NONE)) - .build(); + .id("ns.foo#Error") + .addTrait(new ErrorTrait("client", SourceLocation.NONE)) + .addTrait(new HttpErrorTrait(400, SourceLocation.NONE)) + .build(); Model model = Model.assembler().addShape(structure).assemble().unwrap(); HttpBindingIndex index = HttpBindingIndex.of(model); @@ -73,9 +73,9 @@ public void determinesErrorCodeFromHttpErrorTrait() { @Test public void determinesErrorCodeFromErrorTrait() { StructureShape structure = StructureShape.builder() - .id("ns.foo#Error") - .addTrait(new ErrorTrait("client", SourceLocation.NONE)) - .build(); + .id("ns.foo#Error") + .addTrait(new ErrorTrait("client", SourceLocation.NONE)) + .build(); Model model = Model.assembler().addShape(structure).assemble().unwrap(); HttpBindingIndex index = HttpBindingIndex.of(model); @@ -98,59 +98,59 @@ public void returnsResponseMemberBindingsWithDefaults() { assertThat(responseBindings.size(), is(5)); assertThat( - responseBindings.get("foo"), - equalTo( - new HttpBinding( - expectMember(model, "ns.foo#ServiceOperationExplicitMembersOutput$foo"), - HttpBinding.Location.HEADER, - "X-Foo", - new HttpHeaderTrait("X-Foo", SourceLocation.NONE) + responseBindings.get("foo"), + equalTo( + new HttpBinding( + expectMember(model, "ns.foo#ServiceOperationExplicitMembersOutput$foo"), + HttpBinding.Location.HEADER, + "X-Foo", + new HttpHeaderTrait("X-Foo", SourceLocation.NONE) + ) ) - ) ); assertThat( - responseBindings.get("qux"), - equalTo( - new HttpBinding( - expectMember(model, "ns.foo#ServiceOperationExplicitMembersOutput$qux"), - HttpBinding.Location.PREFIX_HEADERS, - "X-Prefix-", - new HttpPrefixHeadersTrait("X-Prefix-", SourceLocation.NONE) + responseBindings.get("qux"), + equalTo( + new HttpBinding( + expectMember(model, "ns.foo#ServiceOperationExplicitMembersOutput$qux"), + HttpBinding.Location.PREFIX_HEADERS, + "X-Prefix-", + new HttpPrefixHeadersTrait("X-Prefix-", SourceLocation.NONE) + ) ) - ) ); assertThat( - responseBindings.get("baz"), - equalTo( - new HttpBinding( - expectMember(model, "ns.foo#ServiceOperationExplicitMembersOutput$baz"), - HttpBinding.Location.DOCUMENT, - "baz", - null + responseBindings.get("baz"), + equalTo( + new HttpBinding( + expectMember(model, "ns.foo#ServiceOperationExplicitMembersOutput$baz"), + HttpBinding.Location.DOCUMENT, + "baz", + null + ) ) - ) ); assertThat( - responseBindings.get("bar"), - equalTo( - new HttpBinding( - expectMember(model, "ns.foo#ServiceOperationExplicitMembersOutput$bar"), - HttpBinding.Location.DOCUMENT, - "bar", - null + responseBindings.get("bar"), + equalTo( + new HttpBinding( + expectMember(model, "ns.foo#ServiceOperationExplicitMembersOutput$bar"), + HttpBinding.Location.DOCUMENT, + "bar", + null + ) ) - ) ); assertThat( - responseBindings.get("bam"), - equalTo( - new HttpBinding( - expectMember(model, "ns.foo#ServiceOperationExplicitMembersOutput$bam"), - HttpBinding.Location.DOCUMENT, - "bam", - null + responseBindings.get("bam"), + equalTo( + new HttpBinding( + expectMember(model, "ns.foo#ServiceOperationExplicitMembersOutput$bam"), + HttpBinding.Location.DOCUMENT, + "bam", + null + ) ) - ) ); } @@ -162,37 +162,37 @@ public void returnsResponseMemberBindingsWithExplicitBody() { assertThat(responseBindings.entrySet(), hasSize(3)); assertThat( - responseBindings.get("foo"), - equalTo( - new HttpBinding( - expectMember(model, "ns.foo#ServiceOperationExplicitBodyOutput$foo"), - HttpBinding.Location.HEADER, - "X-Foo", - new HttpHeaderTrait("X-Foo", SourceLocation.NONE) + responseBindings.get("foo"), + equalTo( + new HttpBinding( + expectMember(model, "ns.foo#ServiceOperationExplicitBodyOutput$foo"), + HttpBinding.Location.HEADER, + "X-Foo", + new HttpHeaderTrait("X-Foo", SourceLocation.NONE) + ) ) - ) ); assertThat( - responseBindings.get("qux"), - equalTo( - new HttpBinding( - expectMember(model, "ns.foo#ServiceOperationExplicitBodyOutput$qux"), - HttpBinding.Location.PREFIX_HEADERS, - "X-Prefix-", - new HttpPrefixHeadersTrait("X-Prefix-", SourceLocation.NONE) + responseBindings.get("qux"), + equalTo( + new HttpBinding( + expectMember(model, "ns.foo#ServiceOperationExplicitBodyOutput$qux"), + HttpBinding.Location.PREFIX_HEADERS, + "X-Prefix-", + new HttpPrefixHeadersTrait("X-Prefix-", SourceLocation.NONE) + ) ) - ) ); assertThat( - responseBindings.get("baz"), - equalTo( - new HttpBinding( - expectMember(model, "ns.foo#ServiceOperationExplicitBodyOutput$baz"), - HttpBinding.Location.PAYLOAD, - "baz", - new HttpPayloadTrait() + responseBindings.get("baz"), + equalTo( + new HttpBinding( + expectMember(model, "ns.foo#ServiceOperationExplicitBodyOutput$baz"), + HttpBinding.Location.PAYLOAD, + "baz", + new HttpPayloadTrait() + ) ) - ) ); } @@ -204,15 +204,15 @@ public void returnsResponseCodeBinding() { assertThat(responseBindings.size(), is(1)); assertThat( - responseBindings.get("Status"), - equalTo( - new HttpBinding( - expectMember(model, "ns.foo#StructureWithBoundResponseCode$Status"), - HttpBinding.Location.RESPONSE_CODE, - "Status", - new HttpResponseCodeTrait() + responseBindings.get("Status"), + equalTo( + new HttpBinding( + expectMember(model, "ns.foo#StructureWithBoundResponseCode$Status"), + HttpBinding.Location.RESPONSE_CODE, + "Status", + new HttpResponseCodeTrait() + ) ) - ) ); } @@ -232,15 +232,15 @@ public void findsLabelBindings() { assertThat(bindings.entrySet(), hasSize(1)); assertThat( - bindings.get("baz"), - equalTo( - new HttpBinding( - expectMember(model, "ns.foo#WithLabelsInput$baz"), - HttpBinding.Location.LABEL, - "baz", - null + bindings.get("baz"), + equalTo( + new HttpBinding( + expectMember(model, "ns.foo#WithLabelsInput$baz"), + HttpBinding.Location.LABEL, + "baz", + null + ) ) - ) ); } @@ -251,26 +251,26 @@ public void findsQueryBindings() { Map bindings = index.getRequestBindings(id); assertThat( - bindings.get("baz"), - equalTo( - new HttpBinding( - expectMember(model, "ns.foo#ServiceOperationExplicitMembersInput$baz"), - HttpBinding.Location.QUERY, - "baz", - new HttpQueryTrait("baz") + bindings.get("baz"), + equalTo( + new HttpBinding( + expectMember(model, "ns.foo#ServiceOperationExplicitMembersInput$baz"), + HttpBinding.Location.QUERY, + "baz", + new HttpQueryTrait("baz") + ) ) - ) ); assertThat( - bindings.get("bar"), - equalTo( - new HttpBinding( - expectMember(model, "ns.foo#ServiceOperationExplicitMembersInput$bar"), - HttpBinding.Location.QUERY, - "bar", - new HttpQueryTrait("bar") + bindings.get("bar"), + equalTo( + new HttpBinding( + expectMember(model, "ns.foo#ServiceOperationExplicitMembersInput$bar"), + HttpBinding.Location.QUERY, + "bar", + new HttpQueryTrait("bar") + ) ) - ) ); } @@ -281,50 +281,50 @@ public void findsQueryParamsBindings() { Map bindings = index.getRequestBindings(id); assertThat( - bindings.get("corge"), - equalTo( - new HttpBinding( - expectMember(model, "ns.foo#ServiceOperationExplicitMembersInput$corge"), - HttpBinding.Location.QUERY_PARAMS, - "corge", - new HttpQueryParamsTrait() + bindings.get("corge"), + equalTo( + new HttpBinding( + expectMember(model, "ns.foo#ServiceOperationExplicitMembersInput$corge"), + HttpBinding.Location.QUERY_PARAMS, + "corge", + new HttpQueryParamsTrait() + ) ) - ) ); } @Test public void findsUnboundMembers() { ServiceShape service = ServiceShape.builder() - .id("ns.foo#Service") - .version("1") - .addOperation("ns.foo#Operation") - .build(); + .id("ns.foo#Service") + .version("1") + .addOperation("ns.foo#Operation") + .build(); OperationShape operation = OperationShape.builder() - .id("ns.foo#Operation") - .input(ShapeId.from("ns.foo#Input")) - .addTrait(HttpTrait.builder().uri(UriPattern.parse("/")).method("GET").build()) - .build(); + .id("ns.foo#Operation") + .input(ShapeId.from("ns.foo#Input")) + .addTrait(HttpTrait.builder().uri(UriPattern.parse("/")).method("GET").build()) + .build(); StructureShape structure = StructureShape.builder() - .id("ns.foo#Input") - .addMember( - MemberShape.builder() - .id("ns.foo#Input$bar") - .target("ns.foo#String") - .addTrait(new HttpPayloadTrait()) - .build() - ) - .addMember(MemberShape.builder().id("ns.foo#Input$baz").target("ns.foo#String").build()) - .build(); + .id("ns.foo#Input") + .addMember( + MemberShape.builder() + .id("ns.foo#Input$bar") + .target("ns.foo#String") + .addTrait(new HttpPayloadTrait()) + .build() + ) + .addMember(MemberShape.builder().id("ns.foo#Input$baz").target("ns.foo#String").build()) + .build(); StringShape string = StringShape.builder().id("ns.foo#String").build(); Model model = Model.assembler() - .addShape(structure) - .addShape(string) - .addShape(operation) - .addShape(service) - .assemble() - .getResult() - .get(); + .addShape(structure) + .addShape(string) + .addShape(operation) + .addShape(service) + .assemble() + .getResult() + .get(); HttpBindingIndex index = HttpBindingIndex.of(model); Map requestBindings = index.getRequestBindings(operation.getId()); @@ -335,10 +335,10 @@ public void findsUnboundMembers() { @Test public void checksForHttpRequestAndResponseBindings() { Shape shape = MemberShape.builder() - .target("smithy.api#Timestamp") - .id("smithy.example#Baz$bar") - .addTrait(new HttpLabelTrait()) - .build(); + .target("smithy.api#Timestamp") + .id("smithy.example#Baz$bar") + .addTrait(new HttpLabelTrait()) + .build(); assertThat(HttpBindingIndex.hasHttpRequestBindings(shape), is(true)); assertThat(HttpBindingIndex.hasHttpResponseBindings(shape), is(false)); @@ -347,10 +347,10 @@ public void checksForHttpRequestAndResponseBindings() { @Test public void checksForHttpResponseBindings() { Shape shape = MemberShape.builder() - .target("smithy.api#Timestamp") - .id("smithy.example#Baz$bar") - .addTrait(new HttpHeaderTrait("hello", SourceLocation.NONE)) - .build(); + .target("smithy.api#Timestamp") + .id("smithy.example#Baz$bar") + .addTrait(new HttpHeaderTrait("hello", SourceLocation.NONE)) + .build(); assertThat(HttpBindingIndex.hasHttpRequestBindings(shape), is(true)); assertThat(HttpBindingIndex.hasHttpResponseBindings(shape), is(true)); @@ -359,10 +359,10 @@ public void checksForHttpResponseBindings() { @Test public void checksForHttpResponseCodeBindings() { Shape shape = MemberShape.builder() - .target("smithy.api#Integer") - .id("smithy.example#Baz$bar") - .addTrait(new HttpResponseCodeTrait()) - .build(); + .target("smithy.api#Integer") + .id("smithy.example#Baz$bar") + .addTrait(new HttpResponseCodeTrait()) + .build(); assertThat(HttpBindingIndex.hasHttpRequestBindings(shape), is(false)); assertThat(HttpBindingIndex.hasHttpResponseBindings(shape), is(true)); @@ -371,10 +371,10 @@ public void checksForHttpResponseCodeBindings() { @Test public void checksForRequestQueryBindings() { Shape queryShape = MemberShape.builder() - .target("smithy.api#Timestamp") - .id("smithy.example#Baz$bar") - .addTrait(new HttpQueryTrait("foo")) - .build(); + .target("smithy.api#Timestamp") + .id("smithy.example#Baz$bar") + .addTrait(new HttpQueryTrait("foo")) + .build(); assertThat(HttpBindingIndex.hasHttpRequestBindings(queryShape), is(true)); assertThat(HttpBindingIndex.hasHttpResponseBindings(queryShape), is(false)); @@ -383,10 +383,10 @@ public void checksForRequestQueryBindings() { @Test public void checksForRequestQueryParamsBindings() { Shape queryParamsShape = MemberShape.builder() - .target("smithy.api#Timestamp") - .id("smithy.example#Baz$bar") - .addTrait(new HttpQueryParamsTrait()) - .build(); + .target("smithy.api#Timestamp") + .id("smithy.example#Baz$bar") + .addTrait(new HttpQueryParamsTrait()) + .build(); assertThat(HttpBindingIndex.hasHttpRequestBindings(queryParamsShape), is(true)); assertThat(HttpBindingIndex.hasHttpResponseBindings(queryParamsShape), is(false)); @@ -455,20 +455,20 @@ private static MemberShape expectMember(Model model, String id) { @Test public void usesTimestampFormatMemberTraitToDetermineFormat() { MemberShape member = MemberShape.builder() - .id("foo.bar#Baz$member") - .target("smithy.api#Timestamp") - .addTrait(new TimestampFormatTrait(TimestampFormatTrait.EPOCH_SECONDS)) - .build(); + .id("foo.bar#Baz$member") + .target("smithy.api#Timestamp") + .addTrait(new TimestampFormatTrait(TimestampFormatTrait.EPOCH_SECONDS)) + .build(); Model model = Model.assembler() - .addShape(member) - .addShape(ListShape.builder().member(member).id("foo.bar#Baz").build()) - .assemble() - .unwrap(); + .addShape(member) + .addShape(ListShape.builder().member(member).id("foo.bar#Baz").build()) + .assemble() + .unwrap(); HttpBindingIndex index = HttpBindingIndex.of(model); TimestampFormatTrait.Format format = index.determineTimestampFormat( - member, - HttpBinding.Location.HEADER, - TimestampFormatTrait.Format.DATE_TIME + member, + HttpBinding.Location.HEADER, + TimestampFormatTrait.Format.DATE_TIME ); assertThat(format, equalTo(TimestampFormatTrait.Format.EPOCH_SECONDS)); @@ -477,104 +477,104 @@ public void usesTimestampFormatMemberTraitToDetermineFormat() { @Test public void headerLocationUsesHttpDateTimestampFormat() { MemberShape member = MemberShape.builder() - .id("foo.bar#Baz$member") - .target("smithy.api#Timestamp") - .build(); + .id("foo.bar#Baz$member") + .target("smithy.api#Timestamp") + .build(); Model model = Model.assembler() - .addShape(member) - .addShape(ListShape.builder().member(member).id("foo.bar#Baz").build()) - .assemble() - .unwrap(); + .addShape(member) + .addShape(ListShape.builder().member(member).id("foo.bar#Baz").build()) + .assemble() + .unwrap(); HttpBindingIndex index = HttpBindingIndex.of(model); assertThat( - index.determineTimestampFormat( - member, - HttpBinding.Location.HEADER, - TimestampFormatTrait.Format.EPOCH_SECONDS - ), - equalTo(TimestampFormatTrait.Format.HTTP_DATE) + index.determineTimestampFormat( + member, + HttpBinding.Location.HEADER, + TimestampFormatTrait.Format.EPOCH_SECONDS + ), + equalTo(TimestampFormatTrait.Format.HTTP_DATE) ); } @Test public void prefixHeadersLocationUsesHttpDateTimestampFormat() { MemberShape key = MemberShape.builder() - .id("foo.bar#Baz$key") - .target("smithy.api#String") - .build(); + .id("foo.bar#Baz$key") + .target("smithy.api#String") + .build(); MemberShape value = MemberShape.builder() - .id("foo.bar#Baz$value") - .target("smithy.api#Timestamp") - .build(); + .id("foo.bar#Baz$value") + .target("smithy.api#Timestamp") + .build(); Model model = Model.assembler() - .addShape(value) - .addShape(MapShape.builder().addMember(key).addMember(value).id("foo.bar#Baz").build()) - .assemble() - .unwrap(); + .addShape(value) + .addShape(MapShape.builder().addMember(key).addMember(value).id("foo.bar#Baz").build()) + .assemble() + .unwrap(); HttpBindingIndex index = HttpBindingIndex.of(model); assertThat( - index.determineTimestampFormat( - value, - HttpBinding.Location.PREFIX_HEADERS, - TimestampFormatTrait.Format.EPOCH_SECONDS - ), - equalTo(TimestampFormatTrait.Format.HTTP_DATE) + index.determineTimestampFormat( + value, + HttpBinding.Location.PREFIX_HEADERS, + TimestampFormatTrait.Format.EPOCH_SECONDS + ), + equalTo(TimestampFormatTrait.Format.HTTP_DATE) ); } @Test public void queryAndLabelLocationUsesDateTimeTimestampFormat() { MemberShape member = MemberShape.builder() - .id("foo.bar#Baz$member") - .target("smithy.api#Timestamp") - .build(); + .id("foo.bar#Baz$member") + .target("smithy.api#Timestamp") + .build(); Model model = Model.assembler() - .addShape(member) - .addShape(ListShape.builder().member(member).id("foo.bar#Baz").build()) - .assemble() - .unwrap(); + .addShape(member) + .addShape(ListShape.builder().member(member).id("foo.bar#Baz").build()) + .assemble() + .unwrap(); HttpBindingIndex index = HttpBindingIndex.of(model); assertThat( - index.determineTimestampFormat( - member, - HttpBinding.Location.QUERY, - TimestampFormatTrait.Format.EPOCH_SECONDS - ), - equalTo(TimestampFormatTrait.Format.DATE_TIME) + index.determineTimestampFormat( + member, + HttpBinding.Location.QUERY, + TimestampFormatTrait.Format.EPOCH_SECONDS + ), + equalTo(TimestampFormatTrait.Format.DATE_TIME) ); assertThat( - index.determineTimestampFormat( - member, - HttpBinding.Location.LABEL, - TimestampFormatTrait.Format.EPOCH_SECONDS - ), - equalTo(TimestampFormatTrait.Format.DATE_TIME) + index.determineTimestampFormat( + member, + HttpBinding.Location.LABEL, + TimestampFormatTrait.Format.EPOCH_SECONDS + ), + equalTo(TimestampFormatTrait.Format.DATE_TIME) ); } @Test public void otherLocationsUseDefaultTimestampFormat() { MemberShape member = MemberShape.builder() - .id("foo.bar#Baz$member") - .target("smithy.api#Timestamp") - .build(); + .id("foo.bar#Baz$member") + .target("smithy.api#Timestamp") + .build(); Model model = Model.assembler() - .addShape(member) - .addShape(ListShape.builder().member(member).id("foo.bar#Baz").build()) - .assemble() - .unwrap(); + .addShape(member) + .addShape(ListShape.builder().member(member).id("foo.bar#Baz").build()) + .assemble() + .unwrap(); HttpBindingIndex index = HttpBindingIndex.of(model); assertThat( - index.determineTimestampFormat( - member, - HttpBinding.Location.DOCUMENT, - TimestampFormatTrait.Format.EPOCH_SECONDS - ), - equalTo(TimestampFormatTrait.Format.EPOCH_SECONDS) + index.determineTimestampFormat( + member, + HttpBinding.Location.DOCUMENT, + TimestampFormatTrait.Format.EPOCH_SECONDS + ), + equalTo(TimestampFormatTrait.Format.EPOCH_SECONDS) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/IdentifierBindingIndexTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/IdentifierBindingIndexTest.java index 4a88c0f9175..643fa18d1e0 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/IdentifierBindingIndexTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/IdentifierBindingIndexTest.java @@ -32,12 +32,12 @@ public void returnsEmptyMapForUnknownBindings() { IdentifierBindingIndex index = IdentifierBindingIndex.of(model); assertThat( - index.getOperationBindingType(ShapeId.from("ns.foo#A"), ShapeId.from("ns.foo#B")), - equalTo(IdentifierBindingIndex.BindingType.NONE) + index.getOperationBindingType(ShapeId.from("ns.foo#A"), ShapeId.from("ns.foo#B")), + equalTo(IdentifierBindingIndex.BindingType.NONE) ); assertThat( - index.getOperationInputBindings(ShapeId.from("ns.foo#A"), ShapeId.from("ns.foo#B")), - equalTo(Collections.emptyMap()) + index.getOperationInputBindings(ShapeId.from("ns.foo#A"), ShapeId.from("ns.foo#B")), + equalTo(Collections.emptyMap()) ); } @@ -45,27 +45,27 @@ public void returnsEmptyMapForUnknownBindings() { public void findsImplicitInstanceBindings() { StringShape id = StringShape.builder().id("ns.foo#Id").build(); StructureShape input = StructureShape.builder() - .id("ns.foo#Input") - .addMember( - MemberShape.builder() - .id("ns.foo#Input$abc") - .addTrait(new RequiredTrait()) - .target("ns.foo#Id") - .build() - ) - .build(); + .id("ns.foo#Input") + .addMember( + MemberShape.builder() + .id("ns.foo#Input$abc") + .addTrait(new RequiredTrait()) + .target("ns.foo#Id") + .build() + ) + .build(); OperationShape operation = OperationShape.builder().id("ns.foo#Operation").input(input.getId()).build(); ResourceShape resource = ResourceShape.builder() - .id("ns.foo#Resource") - .addIdentifier("abc", "ns.foo#Id") - .addOperation(operation.getId()) - .build(); + .id("ns.foo#Resource") + .addIdentifier("abc", "ns.foo#Id") + .addOperation(operation.getId()) + .build(); Model model = Model.assembler().addShapes(id, resource, operation, input).assemble().unwrap(); IdentifierBindingIndex index = IdentifierBindingIndex.of(model); assertThat( - index.getOperationBindingType(resource.getId(), operation.getId()), - equalTo(IdentifierBindingIndex.BindingType.INSTANCE) + index.getOperationBindingType(resource.getId(), operation.getId()), + equalTo(IdentifierBindingIndex.BindingType.INSTANCE) ); Map expectedBindings = new HashMap<>(); @@ -78,60 +78,60 @@ public void findsCollectionBindings() { StringShape id = StringShape.builder().id("ns.foo#Id").build(); StructureShape input = StructureShape.builder().id("ns.foo#Input").build(); OperationShape operation = OperationShape.builder() - .id("ns.foo#Operation") - .input(input.getId()) - .build(); + .id("ns.foo#Operation") + .input(input.getId()) + .build(); OperationShape listOperation = OperationShape.builder() - .id("ns.foo#ListResources") - .addTrait(new ReadonlyTrait()) - .input(input.getId()) - .build(); + .id("ns.foo#ListResources") + .addTrait(new ReadonlyTrait()) + .input(input.getId()) + .build(); OperationShape createOperation = OperationShape.builder() - .id("ns.foo#CreateResource") - .input(input.getId()) - .build(); + .id("ns.foo#CreateResource") + .input(input.getId()) + .build(); ResourceShape resource = ResourceShape.builder() - .id("ns.foo#Resource") - .addIdentifier("abc", "ns.foo#Id") - .create(createOperation.getId()) - .list(listOperation.getId()) - .addCollectionOperation(operation.getId()) - .build(); + .id("ns.foo#Resource") + .addIdentifier("abc", "ns.foo#Id") + .create(createOperation.getId()) + .list(listOperation.getId()) + .addCollectionOperation(operation.getId()) + .build(); Model model = Model.assembler() - .addShapes(id, resource, operation, input, listOperation, createOperation) - .assemble() - .unwrap(); + .addShapes(id, resource, operation, input, listOperation, createOperation) + .assemble() + .unwrap(); IdentifierBindingIndex index = IdentifierBindingIndex.of(model); assertThat( - index.getOperationBindingType(resource.getId(), operation.getId()), - equalTo(IdentifierBindingIndex.BindingType.COLLECTION) + index.getOperationBindingType(resource.getId(), operation.getId()), + equalTo(IdentifierBindingIndex.BindingType.COLLECTION) ); assertThat( - index.getOperationInputBindings(resource.getId(), operation.getId()), - equalTo(Collections.emptyMap()) + index.getOperationInputBindings(resource.getId(), operation.getId()), + equalTo(Collections.emptyMap()) ); assertThat( - index.getOperationBindingType(resource.getId(), listOperation.getId()), - equalTo(IdentifierBindingIndex.BindingType.COLLECTION) + index.getOperationBindingType(resource.getId(), listOperation.getId()), + equalTo(IdentifierBindingIndex.BindingType.COLLECTION) ); assertThat( - index.getOperationInputBindings( - resource.getId(), - listOperation.getId() - ), - equalTo(Collections.emptyMap()) + index.getOperationInputBindings( + resource.getId(), + listOperation.getId() + ), + equalTo(Collections.emptyMap()) ); assertThat( - index.getOperationBindingType(resource.getId(), createOperation.getId()), - equalTo(IdentifierBindingIndex.BindingType.COLLECTION) + index.getOperationBindingType(resource.getId(), createOperation.getId()), + equalTo(IdentifierBindingIndex.BindingType.COLLECTION) ); assertThat( - index.getOperationInputBindings( - resource.getId(), - createOperation.getId() - ), - equalTo(Collections.emptyMap()) + index.getOperationInputBindings( + resource.getId(), + createOperation.getId() + ), + equalTo(Collections.emptyMap()) ); } @@ -140,28 +140,28 @@ public void findsExplicitBindings() { Map expectedBindings = new HashMap<>(); expectedBindings.put("abc", "def"); StructureShape input = StructureShape.builder() - .id("ns.foo#Input") - .addMember( - MemberShape.builder() - .id("ns.foo#Input$def") - .addTrait(new RequiredTrait()) - .addTrait(new ResourceIdentifierTrait("abc", SourceLocation.NONE)) - .target("smithy.api#String") - .build() - ) - .build(); + .id("ns.foo#Input") + .addMember( + MemberShape.builder() + .id("ns.foo#Input$def") + .addTrait(new RequiredTrait()) + .addTrait(new ResourceIdentifierTrait("abc", SourceLocation.NONE)) + .target("smithy.api#String") + .build() + ) + .build(); OperationShape operation = OperationShape.builder().id("ns.foo#Operation").input(input.getId()).build(); ResourceShape resource = ResourceShape.builder() - .id("ns.foo#Resource") - .addIdentifier("abc", "smithy.api#String") - .addOperation(operation.getId()) - .build(); + .id("ns.foo#Resource") + .addIdentifier("abc", "smithy.api#String") + .addOperation(operation.getId()) + .build(); Model model = Model.assembler().addShapes(resource, operation, input).assemble().unwrap(); IdentifierBindingIndex index = IdentifierBindingIndex.of(model); assertThat( - index.getOperationBindingType(resource.getId(), operation.getId()), - equalTo(IdentifierBindingIndex.BindingType.INSTANCE) + index.getOperationBindingType(resource.getId(), operation.getId()), + equalTo(IdentifierBindingIndex.BindingType.INSTANCE) ); assertThat(index.getOperationInputBindings(resource.getId(), operation.getId()), equalTo(expectedBindings)); } @@ -171,18 +171,18 @@ public void explicitBindingsPreferred() { // Ensure that this does not fail to load. This previously failed when using Collectors.toMap due to // a collision in the keys used to map an identifier to multiple members. Model model = Model.assembler() - .addImport(getClass().getResource("colliding-resource-identifiers.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("colliding-resource-identifiers.smithy")) + .assemble() + .unwrap(); IdentifierBindingIndex index = IdentifierBindingIndex.of(model); // Ensure that the explicit trait bindings are preferred over implicit bindings. assertThat( - index.getOperationInputBindings( - ShapeId.from("smithy.example#Foo"), - ShapeId.from("smithy.example#GetFoo") - ), - equalTo(MapUtils.of("bar", "bam")) + index.getOperationInputBindings( + ShapeId.from("smithy.example#Foo"), + ShapeId.from("smithy.example#GetFoo") + ), + equalTo(MapUtils.of("bar", "bam")) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/NullableIndexTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/NullableIndexTest.java index 20cbdec5465..145d667dad0 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/NullableIndexTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/NullableIndexTest.java @@ -66,147 +66,147 @@ public void checksIfBoxed(Model model, String shapeId, boolean isBoxed) { public static Collection data() { ListShape denseList = ListShape.builder() - .id("smithy.test#DenseList") - .member(ShapeId.from("smithy.api#Boolean")) - .build(); + .id("smithy.test#DenseList") + .member(ShapeId.from("smithy.api#Boolean")) + .build(); ListShape sparseList = ListShape.builder() - .id("smithy.test#SparseList") - .member(ShapeId.from("smithy.api#Boolean")) - .addTrait(new SparseTrait()) - .build(); + .id("smithy.test#SparseList") + .member(ShapeId.from("smithy.api#Boolean")) + .addTrait(new SparseTrait()) + .build(); MapShape denseMap = MapShape.builder() - .id("smithy.test#DenseMap") - .key(ShapeId.from("smithy.api#String")) - .value(ShapeId.from("smithy.api#String")) - .build(); + .id("smithy.test#DenseMap") + .key(ShapeId.from("smithy.api#String")) + .value(ShapeId.from("smithy.api#String")) + .build(); MapShape sparseMap = MapShape.builder() - .id("smithy.test#SparseMap") - .key(ShapeId.from("smithy.api#String")) - .value(ShapeId.from("smithy.api#String")) - .addTrait(new SparseTrait()) - .build(); + .id("smithy.test#SparseMap") + .key(ShapeId.from("smithy.api#String")) + .value(ShapeId.from("smithy.api#String")) + .addTrait(new SparseTrait()) + .build(); SetShape denseSet = SetShape.builder() - .id("smithy.test#DenseSet") - .member(ShapeId.from("smithy.api#String")) - .build(); + .id("smithy.test#DenseSet") + .member(ShapeId.from("smithy.api#String")) + .build(); UnionShape union = UnionShape.builder() - .id("smithy.test#Union") - .addMember("a", ShapeId.from("smithy.api#String")) - .build(); + .id("smithy.test#Union") + .addMember("a", ShapeId.from("smithy.api#String")) + .build(); StructureShape structure = StructureShape.builder() - .id("smithy.test#Struct") - // Nullable - .addMember("a", ShapeId.from("smithy.api#String")) - // Nullable because the target is boxed - .addMember("b", ShapeId.from("smithy.api#Boolean")) - // Nullable because the member is boxed - .addMember( - "c", - ShapeId.from("smithy.api#PrimitiveBoolean"), - b -> b.addTrait(new DefaultTrait(Node.nullNode())) - ) - // Non-nullable due to the default trait with a zero value. - .addMember( - "d", - ShapeId.from("smithy.api#PrimitiveBoolean"), - b -> b.addTrait(new DefaultTrait(Node.from(false))) - ) - .addMember("e", ShapeId.from("smithy.api#Document")) - .build(); + .id("smithy.test#Struct") + // Nullable + .addMember("a", ShapeId.from("smithy.api#String")) + // Nullable because the target is boxed + .addMember("b", ShapeId.from("smithy.api#Boolean")) + // Nullable because the member is boxed + .addMember( + "c", + ShapeId.from("smithy.api#PrimitiveBoolean"), + b -> b.addTrait(new DefaultTrait(Node.nullNode())) + ) + // Non-nullable due to the default trait with a zero value. + .addMember( + "d", + ShapeId.from("smithy.api#PrimitiveBoolean"), + b -> b.addTrait(new DefaultTrait(Node.from(false))) + ) + .addMember("e", ShapeId.from("smithy.api#Document")) + .build(); Model model = Model.assembler() - .addShapes(denseList, sparseList) - .addShapes(denseMap, sparseMap) - .addShapes(denseSet, union, structure) - .assemble() - .unwrap(); + .addShapes(denseList, sparseList) + .addShapes(denseMap, sparseMap) + .addShapes(denseSet, union, structure) + .assemble() + .unwrap(); return Arrays.asList( - new Object[][]{ - {model, "smithy.api#String", true}, - {model, "smithy.api#Blob", true}, - {model, "smithy.api#Boolean", true}, - {model, "smithy.api#Timestamp", true}, - {model, "smithy.api#Byte", true}, - {model, "smithy.api#Short", true}, - {model, "smithy.api#Integer", true}, - {model, "smithy.api#Long", true}, - {model, "smithy.api#Float", true}, - {model, "smithy.api#Double", true}, - {model, "smithy.api#BigInteger", true}, - {model, "smithy.api#BigDecimal", true}, - - // Dense lists are nullable but their members are not. - {model, denseList.getId().toString(), true}, - {model, denseList.getMember().getId().toString(), false}, - - // Sparse lists are nullable and so are their members. - {model, sparseList.getId().toString(), true}, - {model, sparseList.getMember().getId().toString(), true}, - - // Dense maps are nullable but their value members are not. - {model, denseMap.getId().toString(), true}, - {model, denseMap.getValue().getId().toString(), false}, - {model, denseMap.getKey().getId().toString(), false}, - - // Sparse maps are nullable and so are their value members. - {model, sparseMap.getId().toString(), true}, - {model, sparseMap.getValue().getId().toString(), true}, - {model, sparseMap.getKey().getId().toString(), false}, - - // Unions are nullable, but their members never are. - {model, union.getId().toString(), true}, - {model, union.getMember("a").get().getId().toString(), false}, - - // Structures are nullable, but their members are conditionally nullable. - {model, structure.getId().toString(), true}, - {model, structure.getMember("a").get().getId().toString(), true}, - {model, structure.getMember("b").get().getId().toString(), true}, - {model, structure.getMember("c").get().getId().toString(), true}, - {model, structure.getMember("d").get().getId().toString(), false}, - // documents are nullable as structure members - {model, structure.getMember("e").get().getId().toString(), true}, - } + new Object[][]{ + {model, "smithy.api#String", true}, + {model, "smithy.api#Blob", true}, + {model, "smithy.api#Boolean", true}, + {model, "smithy.api#Timestamp", true}, + {model, "smithy.api#Byte", true}, + {model, "smithy.api#Short", true}, + {model, "smithy.api#Integer", true}, + {model, "smithy.api#Long", true}, + {model, "smithy.api#Float", true}, + {model, "smithy.api#Double", true}, + {model, "smithy.api#BigInteger", true}, + {model, "smithy.api#BigDecimal", true}, + + // Dense lists are nullable but their members are not. + {model, denseList.getId().toString(), true}, + {model, denseList.getMember().getId().toString(), false}, + + // Sparse lists are nullable and so are their members. + {model, sparseList.getId().toString(), true}, + {model, sparseList.getMember().getId().toString(), true}, + + // Dense maps are nullable but their value members are not. + {model, denseMap.getId().toString(), true}, + {model, denseMap.getValue().getId().toString(), false}, + {model, denseMap.getKey().getId().toString(), false}, + + // Sparse maps are nullable and so are their value members. + {model, sparseMap.getId().toString(), true}, + {model, sparseMap.getValue().getId().toString(), true}, + {model, sparseMap.getKey().getId().toString(), false}, + + // Unions are nullable, but their members never are. + {model, union.getId().toString(), true}, + {model, union.getMember("a").get().getId().toString(), false}, + + // Structures are nullable, but their members are conditionally nullable. + {model, structure.getId().toString(), true}, + {model, structure.getMember("a").get().getId().toString(), true}, + {model, structure.getMember("b").get().getId().toString(), true}, + {model, structure.getMember("c").get().getId().toString(), true}, + {model, structure.getMember("d").get().getId().toString(), false}, + // documents are nullable as structure members + {model, structure.getMember("e").get().getId().toString(), true}, + } ); } @ParameterizedTest @MethodSource("nullableTraitTests") public void takesNullableIntoAccount( - NullableIndex.CheckMode mode, - boolean foo, - boolean bar, - boolean baz, - boolean bam, - boolean boo + NullableIndex.CheckMode mode, + boolean foo, + boolean bar, + boolean baz, + boolean bam, + boolean boo ) { StringShape str = StringShape.builder().id("smithy.example#Str").build(); StructureShape struct = StructureShape.builder() - .id("smithy.example#Struct") - // This member is technically invalid, but clientOptional takes precedent here - // over the default trait. - .addMember( - "foo", - str.getId(), - b -> b.addTrait(new ClientOptionalTrait()) - .addTrait(new DefaultTrait(Node.from("a"))) - .build() - ) - .addMember( - "bar", - str.getId(), - b -> b.addTrait(new ClientOptionalTrait()) - .addTrait(new RequiredTrait()) - .build() - ) - .addMember("baz", str.getId(), b -> b.addTrait(new ClientOptionalTrait()).build()) - .addMember("bam", str.getId(), b -> b.addTrait(new RequiredTrait()).build()) - .addMember("boo", str.getId(), b -> b.addTrait(new DefaultTrait(Node.from("boo"))).build()) - .build(); + .id("smithy.example#Struct") + // This member is technically invalid, but clientOptional takes precedent here + // over the default trait. + .addMember( + "foo", + str.getId(), + b -> b.addTrait(new ClientOptionalTrait()) + .addTrait(new DefaultTrait(Node.from("a"))) + .build() + ) + .addMember( + "bar", + str.getId(), + b -> b.addTrait(new ClientOptionalTrait()) + .addTrait(new RequiredTrait()) + .build() + ) + .addMember("baz", str.getId(), b -> b.addTrait(new ClientOptionalTrait()).build()) + .addMember("bam", str.getId(), b -> b.addTrait(new RequiredTrait()).build()) + .addMember("boo", str.getId(), b -> b.addTrait(new DefaultTrait(Node.from("boo"))).build()) + .build(); Model model = Model.builder().addShapes(str, struct).build(); NullableIndex nullableIndex = NullableIndex.of(model); @@ -220,8 +220,8 @@ public void takesNullableIntoAccount( public static Stream nullableTraitTests() { return Stream.of( - Arguments.of(NullableIndex.CheckMode.CLIENT, true, true, true, false, false), - Arguments.of(NullableIndex.CheckMode.SERVER, false, false, true, false, false) + Arguments.of(NullableIndex.CheckMode.CLIENT, true, true, true, false, false), + Arguments.of(NullableIndex.CheckMode.SERVER, false, false, true, false, false) ); } @@ -230,12 +230,12 @@ public static Stream nullableTraitTests() { public void takesInputTraitIntoAccount(NullableIndex.CheckMode mode, boolean foo, boolean bar, boolean baz) { StringShape str = StringShape.builder().id("smithy.example#Str").build(); StructureShape struct = StructureShape.builder() - .id("smithy.example#Struct") - .addTrait(new InputTrait()) - .addMember("foo", str.getId(), b -> b.addTrait(new DefaultTrait(Node.from("foo"))).build()) - .addMember("bar", str.getId(), b -> b.addTrait(new RequiredTrait()).build()) - .addMember("baz", str.getId()) - .build(); + .id("smithy.example#Struct") + .addTrait(new InputTrait()) + .addMember("foo", str.getId(), b -> b.addTrait(new DefaultTrait(Node.from("foo"))).build()) + .addMember("bar", str.getId(), b -> b.addTrait(new RequiredTrait()).build()) + .addMember("baz", str.getId()) + .build(); Model model = Model.builder().addShapes(str, struct).build(); NullableIndex nullableIndex = NullableIndex.of(model); @@ -247,8 +247,8 @@ public void takesInputTraitIntoAccount(NullableIndex.CheckMode mode, boolean foo public static Stream inputTraitTests() { return Stream.of( - Arguments.of(NullableIndex.CheckMode.CLIENT, true, true, true), - Arguments.of(NullableIndex.CheckMode.SERVER, false, false, true) + Arguments.of(NullableIndex.CheckMode.CLIENT, true, true, true), + Arguments.of(NullableIndex.CheckMode.SERVER, false, false, true) ); } @@ -257,12 +257,12 @@ public void worksWithV2NullabilityRulesForInteger() { // 2.0 nullability rules are assumed. Using a model assembler with a 1.0 model will ensure that 1.0 // semantics are used in the NullableIndex. IntegerShape integer = IntegerShape.builder() - .id("smithy.example#Integer") - .build(); + .id("smithy.example#Integer") + .build(); StructureShape struct = StructureShape.builder() - .id("smithy.example#Struct") - .addMember("foo", integer.getId()) - .build(); + .id("smithy.example#Struct") + .addMember("foo", integer.getId()) + .build(); Model model = Model.builder().addShapes(integer, struct).build(); NullableIndex index = NullableIndex.of(model); @@ -272,12 +272,12 @@ public void worksWithV2NullabilityRulesForInteger() { @Test public void settingDefaultIsNoticedByNullableIndexToo() { IntegerShape integer = IntegerShape.builder() - .id("smithy.example#Integer") - .build(); + .id("smithy.example#Integer") + .build(); StructureShape struct = StructureShape.builder() - .id("smithy.example#Struct") - .addMember("foo", integer.getId(), b -> b.addTrait(new DefaultTrait(Node.from(0)))) - .build(); + .id("smithy.example#Struct") + .addMember("foo", integer.getId(), b -> b.addTrait(new DefaultTrait(Node.from(0)))) + .build(); Model model = Model.builder().addShapes(integer, struct).build(); NullableIndex index = NullableIndex.of(model); @@ -287,12 +287,12 @@ public void settingDefaultIsNoticedByNullableIndexToo() { @Test public void worksWithV1NullabilityRulesForString() { StringShape string = StringShape.builder() - .id("smithy.example#String") - .build(); + .id("smithy.example#String") + .build(); StructureShape struct = StructureShape.builder() - .id("smithy.example#Struct") - .addMember("foo", string.getId()) - .build(); + .id("smithy.example#Struct") + .addMember("foo", string.getId()) + .build(); Model model = Model.builder().addShapes(string, struct).build(); NullableIndex index = NullableIndex.of(model); @@ -303,12 +303,12 @@ public void worksWithV1NullabilityRulesForString() { @SuppressWarnings("deprecation") public void worksWithV1NullabilityRulesForBoxedMember() { IntegerShape integer = IntegerShape.builder() - .id("smithy.example#Integer") - .build(); + .id("smithy.example#Integer") + .build(); StructureShape struct = StructureShape.builder() - .id("smithy.example#Struct") - .addMember("foo", integer.getId(), b -> b.addTrait(new BoxTrait())) - .build(); + .id("smithy.example#Struct") + .addMember("foo", integer.getId(), b -> b.addTrait(new BoxTrait())) + .build(); Model model = Model.builder().addShapes(integer, struct).build(); NullableIndex index = NullableIndex.of(model); @@ -319,13 +319,13 @@ public void worksWithV1NullabilityRulesForBoxedMember() { @SuppressWarnings("deprecation") public void worksWithV1NullabilityRulesForBoxedTarget() { IntegerShape integer = IntegerShape.builder() - .id("smithy.example#Integer") - .addTrait(new BoxTrait()) - .build(); + .id("smithy.example#Integer") + .addTrait(new BoxTrait()) + .build(); StructureShape struct = StructureShape.builder() - .id("smithy.example#Struct") - .addMember("foo", integer.getId()) - .build(); + .id("smithy.example#Struct") + .addMember("foo", integer.getId()) + .build(); Model model = Model.builder().addShapes(integer, struct).build(); NullableIndex index = NullableIndex.of(model); @@ -336,14 +336,14 @@ public void worksWithV1NullabilityRulesForBoxedTarget() { @SuppressWarnings("deprecation") public void worksWithV1NullabilityRulesIgnoringRequired() { IntegerShape integer = IntegerShape.builder() - .id("smithy.example#Integer") - .addTrait(new BoxTrait()) - .build(); + .id("smithy.example#Integer") + .addTrait(new BoxTrait()) + .build(); StructureShape struct = StructureShape.builder() - .id("smithy.example#Struct") - // The required trait isn't used in v1 to determine nullability. - .addMember("foo", integer.getId(), b -> b.addTrait(new RequiredTrait())) - .build(); + .id("smithy.example#Struct") + // The required trait isn't used in v1 to determine nullability. + .addMember("foo", integer.getId(), b -> b.addTrait(new RequiredTrait())) + .build(); Model model = Model.builder().addShapes(integer, struct).build(); NullableIndex index = NullableIndex.of(model); @@ -354,10 +354,10 @@ public void worksWithV1NullabilityRulesIgnoringRequired() { @SuppressWarnings("deprecation") public void worksWithV1NullabilityRulesForDenseMaps() { MapShape map = MapShape.builder() - .id("smithy.example#Map") - .key(ShapeId.from("smithy.api#String")) - .value(ShapeId.from("smithy.api#String")) - .build(); + .id("smithy.example#Map") + .key(ShapeId.from("smithy.api#String")) + .value(ShapeId.from("smithy.api#String")) + .build(); Model model = Model.assembler().addShapes(map).assemble().unwrap(); NullableIndex index = NullableIndex.of(model); @@ -370,11 +370,11 @@ public void worksWithV1NullabilityRulesForDenseMaps() { @SuppressWarnings("deprecation") public void worksWithV1NullabilityRulesForSparseMaps() { MapShape map = MapShape.builder() - .id("smithy.example#Map") - .key(ShapeId.from("smithy.api#String")) - .value(ShapeId.from("smithy.api#String")) - .addTrait(new SparseTrait()) - .build(); + .id("smithy.example#Map") + .key(ShapeId.from("smithy.api#String")) + .value(ShapeId.from("smithy.api#String")) + .addTrait(new SparseTrait()) + .build(); Model model = Model.assembler().addShapes(map).assemble().unwrap(); NullableIndex index = NullableIndex.of(model); @@ -387,9 +387,9 @@ public void worksWithV1NullabilityRulesForSparseMaps() { @SuppressWarnings("deprecation") public void worksWithV1NullabilityRulesForDenseLists() { ListShape list = ListShape.builder() - .id("smithy.example#Map") - .member(ShapeId.from("smithy.api#String")) - .build(); + .id("smithy.example#Map") + .member(ShapeId.from("smithy.api#String")) + .build(); Model model = Model.assembler().addShapes(list).assemble().unwrap(); NullableIndex index = NullableIndex.of(model); @@ -401,10 +401,10 @@ public void worksWithV1NullabilityRulesForDenseLists() { @SuppressWarnings("deprecation") public void worksWithV1NullabilityRulesForSparseLists() { ListShape list = ListShape.builder() - .id("smithy.example#Map") - .member(ShapeId.from("smithy.api#String")) - .addTrait(new SparseTrait()) - .build(); + .id("smithy.example#Map") + .member(ShapeId.from("smithy.api#String")) + .addTrait(new SparseTrait()) + .build(); Model model = Model.assembler().addShapes(list).assemble().unwrap(); NullableIndex index = NullableIndex.of(model); @@ -415,42 +415,42 @@ public void worksWithV1NullabilityRulesForSparseLists() { @Test public void carefulModeTreatsStructureAndUnionAsOptional() { StructureShape struct = StructureShape.builder() - .id("smithy.example#Struct") - .build(); + .id("smithy.example#Struct") + .build(); UnionShape union = UnionShape.builder() - .id("smithy.example#Union") - .addMember("a", ShapeId.from("smithy.api#String")) - .build(); + .id("smithy.example#Union") + .addMember("a", ShapeId.from("smithy.api#String")) + .build(); StructureShape outer = StructureShape.builder() - .id("smithy.example#Outer") - .addMember("a", struct.getId(), m -> m.addTrait(new RequiredTrait())) - .addMember("b", union.getId(), m -> m.addTrait(new RequiredTrait())) - .build(); + .id("smithy.example#Outer") + .addMember("a", struct.getId(), m -> m.addTrait(new RequiredTrait())) + .addMember("b", union.getId(), m -> m.addTrait(new RequiredTrait())) + .build(); Model model = Model.assembler().addShapes(struct, union, outer).assemble().unwrap(); NullableIndex index = NullableIndex.of(model); assertThat( - index.isMemberNullable(outer.getMember("a").get(), NullableIndex.CheckMode.CLIENT_CAREFUL), - is(true) + index.isMemberNullable(outer.getMember("a").get(), NullableIndex.CheckMode.CLIENT_CAREFUL), + is(true) ); assertThat( - index.isMemberNullable(outer.getMember("b").get(), NullableIndex.CheckMode.CLIENT_CAREFUL), - is(true) + index.isMemberNullable(outer.getMember("b").get(), NullableIndex.CheckMode.CLIENT_CAREFUL), + is(true) ); } @Test public void correctlyDeterminesNullabilityOfUpgradedV1Models() { Model model = Model.assembler() - .addImport(getClass().getResource("nullable-index-v1.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("nullable-index-v1.smithy")) + .assemble() + .unwrap(); // Re-serialize to test with a 2.0 model. Model model2 = Model.assembler() - .addDocumentNode(ModelSerializer.builder().build().serialize(model)) - .assemble() - .unwrap(); + .addDocumentNode(ModelSerializer.builder().build().serialize(model)) + .assemble() + .unwrap(); correctlyDeterminesNullabilityOfUpgradedV1ModelsAssertions(model); correctlyDeterminesNullabilityOfUpgradedV1ModelsAssertions(model2); @@ -475,15 +475,15 @@ private void correctlyDeterminesNullabilityOfUpgradedV1ModelsAssertions(Model mo @Test public void requiresIsNotInherentlyNonNullIn1_0() { Model model = Model.assembler() - .addImport(getClass().getResource("nullable-index-v1.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("nullable-index-v1.smithy")) + .assemble() + .unwrap(); // Re-serialize to test with a 2.0 model. Model model2 = Model.assembler() - .addDocumentNode(ModelSerializer.builder().build().serialize(model)) - .assemble() - .unwrap(); + .addDocumentNode(ModelSerializer.builder().build().serialize(model)) + .assemble() + .unwrap(); requiresIsNotInherentlyNonNullIn1_0_Assertions(model); requiresIsNotInherentlyNonNullIn1_0_Assertions(model2); @@ -497,27 +497,27 @@ private void requiresIsNotInherentlyNonNullIn1_0_Assertions(Model model) { assertThat(index.isNullable(ShapeId.from("smithy.example#Baz$bam")), is(false)); assertThat( - index.isMemberNullable(model.expectShape(ShapeId.from("smithy.example#Baz$bar"), MemberShape.class)), - is(false) + index.isMemberNullable(model.expectShape(ShapeId.from("smithy.example#Baz$bar"), MemberShape.class)), + is(false) ); assertThat( - index.isMemberNullable(model.expectShape(ShapeId.from("smithy.example#Baz$bam"), MemberShape.class)), - is(false) + index.isMemberNullable(model.expectShape(ShapeId.from("smithy.example#Baz$bam"), MemberShape.class)), + is(false) ); } @Test public void addedDefaultMakesMemberNullableInV1NotV2() { Model model = Model.assembler() - .addImport(getClass().getResource("nullable-index-added-default.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("nullable-index-added-default.smithy")) + .assemble() + .unwrap(); // Re-serialize to test with a 2.0 model. Model model2 = Model.assembler() - .addDocumentNode(ModelSerializer.builder().build().serialize(model)) - .assemble() - .unwrap(); + .addDocumentNode(ModelSerializer.builder().build().serialize(model)) + .assemble() + .unwrap(); addedDefaultMakesMemberNullableInV1NotV2Assertions(model); addedDefaultMakesMemberNullableInV1NotV2Assertions(model2); @@ -534,8 +534,8 @@ private void addedDefaultMakesMemberNullableInV1NotV2Assertions(Model model) { // In v2 based semantics and tools, the addedDefault trait is ignored. assertThat( - index.isMemberNullable(model.expectShape(ShapeId.from("smithy.example#Foo$baz"), MemberShape.class)), - is(false) + index.isMemberNullable(model.expectShape(ShapeId.from("smithy.example#Foo$baz"), MemberShape.class)), + is(false) ); } @@ -545,21 +545,21 @@ private void addedDefaultMakesMemberNullableInV1NotV2Assertions(Model model) { @Test public void requiredMembersAreNonNullableEvenIfDefaultNullTraitIsPresent() { String modelText = "$version: \"2.0\"\n" - + "namespace smithy.example\n" - + "structure Foo {\n" - + " @required\n" - + " baz: Integer = null\n" - + "}\n"; + + "namespace smithy.example\n" + + "structure Foo {\n" + + " @required\n" + + " baz: Integer = null\n" + + "}\n"; Model model = Model.assembler() - .addUnparsedModel("foo.smithy", modelText) - .assemble() - .unwrap(); + .addUnparsedModel("foo.smithy", modelText) + .assemble() + .unwrap(); NullableIndex index = NullableIndex.of(model); assertThat( - index.isMemberNullable(model.expectShape(ShapeId.from("smithy.example#Foo$baz"), MemberShape.class)), - is(false) + index.isMemberNullable(model.expectShape(ShapeId.from("smithy.example#Foo$baz"), MemberShape.class)), + is(false) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/OperationIndexTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/OperationIndexTest.java index 82147f52873..1d1419536be 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/OperationIndexTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/OperationIndexTest.java @@ -32,9 +32,9 @@ public class OperationIndexTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(OperationIndexTest.class.getResource("operation-index-test.smithy")) - .assemble() - .unwrap(); + .addImport(OperationIndexTest.class.getResource("operation-index-test.smithy")) + .assemble() + .unwrap(); } @AfterAll @@ -48,14 +48,14 @@ public void indexesUnitOperations() { assertThat(opIndex.getInput(ShapeId.from("ns.foo#A")), is(Optional.empty())); assertThat( - opIndex.getInputShape(ShapeId.from("ns.foo#A")).map(Shape::getId), - equalTo(Optional.of(UnitTypeTrait.UNIT)) + opIndex.getInputShape(ShapeId.from("ns.foo#A")).map(Shape::getId), + equalTo(Optional.of(UnitTypeTrait.UNIT)) ); assertThat(opIndex.expectInputShape(ShapeId.from("ns.foo#A")).getId(), equalTo(UnitTypeTrait.UNIT)); assertThat(opIndex.getOutput(ShapeId.from("ns.foo#A")), is(Optional.empty())); assertThat( - opIndex.getOutputShape(ShapeId.from("ns.foo#A")).map(Shape::getId), - equalTo(Optional.of(UnitTypeTrait.UNIT)) + opIndex.getOutputShape(ShapeId.from("ns.foo#A")).map(Shape::getId), + equalTo(Optional.of(UnitTypeTrait.UNIT)) ); assertThat(opIndex.expectOutputShape(ShapeId.from("ns.foo#A")).getId(), equalTo(UnitTypeTrait.UNIT)); assertThat(opIndex.getErrors(ShapeId.from("ns.foo#A")), empty()); @@ -104,8 +104,8 @@ public void getsInputBindings() { OperationIndex index = OperationIndex.of(model); Set actual = index.getInputBindings(ShapeId.from("ns.foo#Input")); Set expected = SetUtils.of( - model.expectShape(ShapeId.from("ns.foo#B"), OperationShape.class), - model.expectShape(ShapeId.from("ns.foo#C"), OperationShape.class) + model.expectShape(ShapeId.from("ns.foo#B"), OperationShape.class), + model.expectShape(ShapeId.from("ns.foo#C"), OperationShape.class) ); assertThat(actual, equalTo(expected)); assertThat(index.getInputBindings(ShapeId.from("ns.foo#Output")), empty()); @@ -126,8 +126,8 @@ public void getsOutputBindings() { OperationIndex index = OperationIndex.of(model); Set actual = index.getOutputBindings(ShapeId.from("ns.foo#Output")); Set expected = SetUtils.of( - model.expectShape(ShapeId.from("ns.foo#B"), OperationShape.class), - model.expectShape(ShapeId.from("ns.foo#C"), OperationShape.class) + model.expectShape(ShapeId.from("ns.foo#B"), OperationShape.class), + model.expectShape(ShapeId.from("ns.foo#C"), OperationShape.class) ); assertThat(actual, equalTo(expected)); assertThat(index.getOutputBindings(ShapeId.from("ns.foo#Input")), empty()); @@ -156,8 +156,8 @@ public void getsErrorBindings() { OperationIndex index = OperationIndex.of(model); Set actual = index.getErrorBindings(ShapeId.from("ns.foo#CommonError1")); Set expected = SetUtils.of( - model.expectShape(ShapeId.from("ns.foo#MyService"), ServiceShape.class), - model.expectShape(ShapeId.from("ns.foo#C"), OperationShape.class) + model.expectShape(ShapeId.from("ns.foo#MyService"), ServiceShape.class), + model.expectShape(ShapeId.from("ns.foo#C"), OperationShape.class) ); assertThat(actual, equalTo(expected)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/PaginatedIndexTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/PaginatedIndexTest.java index c24881314a3..116f1d9fc2a 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/PaginatedIndexTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/PaginatedIndexTest.java @@ -21,12 +21,12 @@ public class PaginatedIndexTest { @Test public void findDirectChildren() { ValidatedResult result = Model.assembler() - .addImport( - getClass().getResource( - "/software/amazon/smithy/model/errorfiles/validators/paginated/paginated-valid.json" + .addImport( + getClass().getResource( + "/software/amazon/smithy/model/errorfiles/validators/paginated/paginated-valid.json" + ) ) - ) - .assemble(); + .assemble(); Model model = result.getResult().get(); PaginatedIndex index = PaginatedIndex.of(model); ShapeId service = ShapeId.from("ns.foo#Service"); @@ -40,34 +40,34 @@ public void findDirectChildren() { assertThat(info.getOutputTokenMember().getMemberName(), equalTo("nextToken")); assertThat(info.getOutputTokenMemberPath().isEmpty(), is(false)); assertThat( - info.getOutputTokenMemberPath() - .stream() - .map(MemberShape::getMemberName) - .collect(Collectors.toList()), - equalTo(ListUtils.of("nextToken")) + info.getOutputTokenMemberPath() + .stream() + .map(MemberShape::getMemberName) + .collect(Collectors.toList()), + equalTo(ListUtils.of("nextToken")) ); assertThat(info.getPageSizeMember().isPresent(), is(true)); assertThat(info.getPageSizeMember().get().getMemberName(), equalTo("pageSize")); assertThat(info.getItemsMember().get().getMemberName(), equalTo("items")); assertThat(info.getItemsMemberPath().isEmpty(), is(false)); assertThat( - info.getItemsMemberPath() - .stream() - .map(MemberShape::getMemberName) - .collect(Collectors.toList()), - equalTo(ListUtils.of("items")) + info.getItemsMemberPath() + .stream() + .map(MemberShape::getMemberName) + .collect(Collectors.toList()), + equalTo(ListUtils.of("items")) ); } @Test public void findIndirectChildren() { ValidatedResult result = Model.assembler() - .addImport( - getClass().getResource( - "/software/amazon/smithy/model/errorfiles/validators/paginated/paginated-valid.json" + .addImport( + getClass().getResource( + "/software/amazon/smithy/model/errorfiles/validators/paginated/paginated-valid.json" + ) ) - ) - .assemble(); + .assemble(); Model model = result.getResult().get(); PaginatedIndex index = PaginatedIndex.of(model); @@ -80,21 +80,21 @@ public void findIndirectChildren() { assertThat(info.getOutputTokenMember().getMemberName(), equalTo("nextToken")); assertThat(info.getOutputTokenMemberPath().isEmpty(), is(false)); assertThat( - info.getOutputTokenMemberPath() - .stream() - .map(MemberShape::getMemberName) - .collect(Collectors.toList()), - equalTo(ListUtils.of("result", "nextToken")) + info.getOutputTokenMemberPath() + .stream() + .map(MemberShape::getMemberName) + .collect(Collectors.toList()), + equalTo(ListUtils.of("result", "nextToken")) ); assertThat(info.getItemsMember().isPresent(), is(true)); assertThat(info.getItemsMember().get().getMemberName(), equalTo("items")); assertThat(info.getItemsMemberPath().isEmpty(), is(false)); assertThat( - info.getItemsMemberPath() - .stream() - .map(MemberShape::getMemberName) - .collect(Collectors.toList()), - equalTo(ListUtils.of("result", "items")) + info.getItemsMemberPath() + .stream() + .map(MemberShape::getMemberName) + .collect(Collectors.toList()), + equalTo(ListUtils.of("result", "items")) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/PropertyBindingIndexTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/PropertyBindingIndexTest.java index ddd557e587d..7617ceb7527 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/PropertyBindingIndexTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/PropertyBindingIndexTest.java @@ -22,67 +22,67 @@ public class PropertyBindingIndexTest { @Test public void testIndex() { ValidatedResult vrmodel = Model.assembler() - .addImport(OperationIndexTest.class.getResource("member-property-index.smithy")) - .assemble(); + .addImport(OperationIndexTest.class.getResource("member-property-index.smithy")) + .assemble(); Model model = vrmodel.getResult().get(); PropertyBindingIndex index = PropertyBindingIndex.of(model); assertFalse( - index.doesMemberShapeRequireProperty( - model.expectShape( - ShapeId.from("com.example#ResourceStructure_1$token"), - MemberShape.class + index.doesMemberShapeRequireProperty( + model.expectShape( + ShapeId.from("com.example#ResourceStructure_1$token"), + MemberShape.class + ) ) - ) ); assertFalse( - index.doesMemberShapeRequireProperty( - model.expectShape( - ShapeId.from("com.example#ResourceStructure_1$id"), - MemberShape.class + index.doesMemberShapeRequireProperty( + model.expectShape( + ShapeId.from("com.example#ResourceStructure_1$id"), + MemberShape.class + ) ) - ) ); assertFalse( - index.doesMemberShapeRequireProperty( - model.expectShape( - ShapeId.from("com.example#ResourceStructure_1$spurious"), - MemberShape.class + index.doesMemberShapeRequireProperty( + model.expectShape( + ShapeId.from("com.example#ResourceStructure_1$spurious"), + MemberShape.class + ) ) - ) ); assertFalse( - index.doesMemberShapeRequireProperty( - model.expectShape( - ShapeId.from("com.example#ResourceStructure_2$nested"), - MemberShape.class + index.doesMemberShapeRequireProperty( + model.expectShape( + ShapeId.from("com.example#ResourceStructure_2$nested"), + MemberShape.class + ) ) - ) ); assertTrue( - index.doesMemberShapeRequireProperty( - model.expectShape( - ShapeId.from("com.example#ResourceStructure_1$property"), - MemberShape.class + index.doesMemberShapeRequireProperty( + model.expectShape( + ShapeId.from("com.example#ResourceStructure_1$property"), + MemberShape.class + ) ) - ) ); assertTrue( - index.isMemberShapeProperty( - model.expectShape( - ShapeId.from("com.example#ResourceStructure_1$property"), - MemberShape.class + index.isMemberShapeProperty( + model.expectShape( + ShapeId.from("com.example#ResourceStructure_1$property"), + MemberShape.class + ) ) - ) ); assertFalse( - index.isMemberShapeProperty( - model.expectShape( - ShapeId.from("com.example#ResourceStructure_1$spurious"), - MemberShape.class + index.isMemberShapeProperty( + model.expectShape( + ShapeId.from("com.example#ResourceStructure_1$spurious"), + MemberShape.class + ) ) - ) ); assertTrue(index.getPropertyName(ShapeId.from("com.example#ResourceStructure_1$property")).isPresent()); @@ -98,12 +98,12 @@ public void testIndex() { assertEquals(ShapeId.from("com.example#ResourceDescription"), index.getOutputPropertiesShape(update).getId()); assertTrue( - index.doesMemberShapeRequireProperty( - model.expectShape( - ShapeId.from("com.example#ChangeResourceOutput$id"), - MemberShape.class + index.doesMemberShapeRequireProperty( + model.expectShape( + ShapeId.from("com.example#ChangeResourceOutput$id"), + MemberShape.class + ) ) - ) ); Assertions.assertThrows(ValidatedResultException.class, () -> vrmodel.unwrap()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/ServiceIndexTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/ServiceIndexTest.java index 98d1e945f5d..2e3a0b05ebf 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/ServiceIndexTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/ServiceIndexTest.java @@ -34,9 +34,9 @@ public class ServiceIndexTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(ServiceIndexTest.class.getResource("service-index-finds-auth-schemes.smithy")) - .assemble() - .unwrap(); + .addImport(ServiceIndexTest.class.getResource("service-index-finds-auth-schemes.smithy")) + .assemble() + .unwrap(); } @AfterAll @@ -47,9 +47,9 @@ public static void after() { @Test public void protocolsOfService() { Model model = Model.assembler() - .addImport(getClass().getResource("service-index-loads-protocols.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("service-index-loads-protocols.smithy")) + .assemble() + .unwrap(); ServiceIndex serviceIndex = ServiceIndex.of(model); Map protocols = serviceIndex.getProtocols(ShapeId.from("smithy.example#TestService")); @@ -62,7 +62,7 @@ public void protocolsOfService() { public void authSchemesOfService() { ServiceIndex serviceIndex = ServiceIndex.of(model); Map auth = serviceIndex.getAuthSchemes( - ShapeId.from("smithy.example#ServiceWithoutAuthTrait") + ShapeId.from("smithy.example#ServiceWithoutAuthTrait") ); assertAuthSchemes(auth, HttpBasicAuthTrait.ID, HttpBearerAuthTrait.ID, HttpDigestAuthTrait.ID, CUSTOM_AUTH_ID); } @@ -158,8 +158,8 @@ public void authSchemesOfOperationWithoutAuthTraitAndServiceWithEmptyAuthTrait() public void authSchemesOfOperationWithAuthTrait() { ServiceIndex serviceIndex = ServiceIndex.of(model); Map auth = serviceIndex.getEffectiveAuthSchemes( - ShapeId.from("smithy.example#ServiceWithAuthTrait"), - ShapeId.from("smithy.example#OperationWithAuthTrait") + ShapeId.from("smithy.example#ServiceWithAuthTrait"), + ShapeId.from("smithy.example#OperationWithAuthTrait") ); assertAuthSchemes(auth, HttpDigestAuthTrait.ID); } @@ -204,12 +204,12 @@ public void authSchemesOfOperationWithOptionalAuthTraitAndServiceWithoutAuthTrai auth = serviceIndex.getEffectiveAuthSchemes(service, operation, NO_AUTH_AWARE); assertAuthSchemes( - auth, - HttpBasicAuthTrait.ID, - HttpBearerAuthTrait.ID, - HttpDigestAuthTrait.ID, - CUSTOM_AUTH_ID, - NoAuthTrait.ID + auth, + HttpBasicAuthTrait.ID, + HttpBearerAuthTrait.ID, + HttpDigestAuthTrait.ID, + CUSTOM_AUTH_ID, + NoAuthTrait.ID ); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/TextIndexTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/TextIndexTest.java index 0364177821a..80ab150e62b 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/TextIndexTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/TextIndexTest.java @@ -15,9 +15,9 @@ public class TextIndexTest { @Test public void handlesSyntheticTraits() { Model model = Model.assembler() - .addImport(OperationIndexTest.class.getResource("text-index.smithy")) - .assemble() - .unwrap(); + .addImport(OperationIndexTest.class.getResource("text-index.smithy")) + .assemble() + .unwrap(); TextIndex index = TextIndex.of(model); assertThat(index.getTextInstances(), hasSize(5)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/TopDownIndexTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/TopDownIndexTest.java index 901d131a33c..ef1d9eac97d 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/TopDownIndexTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/TopDownIndexTest.java @@ -20,10 +20,10 @@ public class TopDownIndexTest { @Test public void findDirectChildren() { ServiceShape service = ServiceShape.builder() - .id("ns.foo#Service") - .version("1") - .addResource("ns.foo#Resource") - .build(); + .id("ns.foo#Service") + .version("1") + .addResource("ns.foo#Resource") + .build(); ResourceShape resource = ResourceShape.builder().id("ns.foo#Resource").build(); Model model = Model.builder().addShapes(service, resource).build(); TopDownIndex childIndex = TopDownIndex.of(model); @@ -37,15 +37,15 @@ public void findDirectChildren() { @Test public void findsAllChildren() { ServiceShape service = ServiceShape.builder() - .id("ns.foo#Service") - .version("1") - .addResource("ns.foo#A") - .build(); + .id("ns.foo#Service") + .version("1") + .addResource("ns.foo#A") + .build(); ResourceShape resourceA = ResourceShape.builder() - .id("ns.foo#A") - .list(ShapeId.from("ns.foo#List")) - .addResource("ns.foo#B") - .build(); + .id("ns.foo#A") + .list(ShapeId.from("ns.foo#List")) + .addResource("ns.foo#B") + .build(); ResourceShape resourceB = ResourceShape.builder().id("ns.foo#B").addOperation("ns.foo#Operation").build(); OperationShape operation = OperationShape.builder().id("ns.foo#Operation").build(); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/AstModelLoaderTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/AstModelLoaderTest.java index 0d3609c23f7..c772f3995e5 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/AstModelLoaderTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/AstModelLoaderTest.java @@ -16,14 +16,14 @@ public class AstModelLoaderTest { @Test public void failsToLoadPropertiesFromV1() { ValidatedResult model = Model.assembler() - .addImport(getClass().getResource("invalid/version/properties-v2-only.json")) - .assemble(); + .addImport(getClass().getResource("invalid/version/properties-v2-only.json")) + .assemble(); assertEquals(1, model.getValidationEvents(Severity.ERROR).size()); assertTrue( - model.getValidationEvents(Severity.ERROR) - .get(0) - .getMessage() - .contains("Resource properties can only be used with Smithy version 2 or later.") + model.getValidationEvents(Severity.ERROR) + .get(0) + .getMessage() + .contains("Resource properties can only be used with Smithy version 2 or later.") ); } @@ -31,17 +31,17 @@ public void failsToLoadPropertiesFromV1() { public void doesNotFailOnEmptyApply() { // Empty apply statements are pointless but shouldn't break the loader. Model.assembler() - .addImport(getClass().getResource("ast-empty-apply-1.json")) - .addImport(getClass().getResource("ast-empty-apply-2.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("ast-empty-apply-1.json")) + .addImport(getClass().getResource("ast-empty-apply-2.json")) + .assemble() + .unwrap(); } @Test public void allowsMixinsOnOperationsWithoutWarningOrError() { ValidatedResult model = Model.assembler() - .addImport(getClass().getResource("mixins/operation-mixins.json")) - .assemble(); + .addImport(getClass().getResource("mixins/operation-mixins.json")) + .assemble(); assertEquals(0, model.getValidationEvents(Severity.WARNING).size()); assertEquals(0, model.getValidationEvents(Severity.ERROR).size()); } @@ -49,8 +49,8 @@ public void allowsMixinsOnOperationsWithoutWarningOrError() { @Test public void allowsMixinsOnResourcesWithoutWarningOrError() { ValidatedResult model = Model.assembler() - .addImport(getClass().getResource("mixins/resource-mixins.json")) - .assemble(); + .addImport(getClass().getResource("mixins/resource-mixins.json")) + .assemble(); assertEquals(0, model.getValidationEvents(Severity.WARNING).size()); assertEquals(0, model.getValidationEvents(Severity.ERROR).size()); } @@ -58,8 +58,8 @@ public void allowsMixinsOnResourcesWithoutWarningOrError() { @Test public void allowsMixinsOnServiceWithoutWarningOrError() { ValidatedResult model = Model.assembler() - .addImport(getClass().getResource("mixins/service-mixins.json")) - .assemble(); + .addImport(getClass().getResource("mixins/service-mixins.json")) + .assemble(); assertEquals(0, model.getValidationEvents(Severity.WARNING).size()); assertEquals(0, model.getValidationEvents(Severity.ERROR).size()); } @@ -67,8 +67,8 @@ public void allowsMixinsOnServiceWithoutWarningOrError() { @Test public void allowsMixinsOnStructuresWithoutWarningOrError() { ValidatedResult model = Model.assembler() - .addImport(getClass().getResource("mixins/structure-mixins.json")) - .assemble(); + .addImport(getClass().getResource("mixins/structure-mixins.json")) + .assemble(); assertEquals(0, model.getValidationEvents(Severity.WARNING).size()); assertEquals(0, model.getValidationEvents(Severity.ERROR).size()); } @@ -76,8 +76,8 @@ public void allowsMixinsOnStructuresWithoutWarningOrError() { @Test public void allowsMixinsOnUnionsWithoutWarningOrError() { ValidatedResult model = Model.assembler() - .addImport(getClass().getResource("mixins/union-mixins.json")) - .assemble(); + .addImport(getClass().getResource("mixins/union-mixins.json")) + .assemble(); assertEquals(0, model.getValidationEvents(Severity.WARNING).size()); assertEquals(0, model.getValidationEvents(Severity.ERROR).size()); } @@ -85,8 +85,8 @@ public void allowsMixinsOnUnionsWithoutWarningOrError() { @Test public void allowsMixinsOnSimpleShapesWithoutWarningOrError() { ValidatedResult model = Model.assembler() - .addImport(getClass().getResource("mixins/simple-shape-mixins.json")) - .assemble(); + .addImport(getClass().getResource("mixins/simple-shape-mixins.json")) + .assemble(); assertEquals(0, model.getValidationEvents(Severity.WARNING).size()); assertEquals(0, model.getValidationEvents(Severity.ERROR).size()); } @@ -94,8 +94,8 @@ public void allowsMixinsOnSimpleShapesWithoutWarningOrError() { @Test public void allowsMixinsOnCollectionShapesWithoutWarningOrError() { ValidatedResult model = Model.assembler() - .addImport(getClass().getResource("mixins/collection-mixins.json")) - .assemble(); + .addImport(getClass().getResource("mixins/collection-mixins.json")) + .assemble(); assertEquals(0, model.getValidationEvents(Severity.WARNING).size()); assertEquals(0, model.getValidationEvents(Severity.ERROR).size()); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/IdlInternalTokenizerTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/IdlInternalTokenizerTest.java index 3bd19397770..165558e822f 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/IdlInternalTokenizerTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/IdlInternalTokenizerTest.java @@ -47,11 +47,11 @@ public void failsWhenExpectedSpacesNotThere() { ModelSyntaxException e = Assertions.assertThrows(ModelSyntaxException.class, tokenizer::expectAndSkipSpaces); assertThat( - e.getMessage(), - startsWith( - "Syntax error at line 1, column 1: Expected SPACE(' ') but found " - + "IDENTIFIER('abc')" - ) + e.getMessage(), + startsWith( + "Syntax error at line 1, column 1: Expected SPACE(' ') but found " + + "IDENTIFIER('abc')" + ) ); } @@ -82,24 +82,24 @@ public void throwsWhenExpectedWhitespaceNotFound() { IdlInternalTokenizer tokenizer = new IdlInternalTokenizer("a.smithy", "hi"); ModelSyntaxException e = Assertions.assertThrows( - ModelSyntaxException.class, - tokenizer::expectAndSkipWhitespace + ModelSyntaxException.class, + tokenizer::expectAndSkipWhitespace ); assertThat( - e.getMessage(), - startsWith( - "Syntax error at line 1, column 1: Expected one or more whitespace " - + "characters, but found IDENTIFIER('hi')" - ) + e.getMessage(), + startsWith( + "Syntax error at line 1, column 1: Expected one or more whitespace " + + "characters, but found IDENTIFIER('hi')" + ) ); } @Test public void skipDocsAndWhitespace() { IdlInternalTokenizer tokenizer = new IdlInternalTokenizer( - "a.smithy", - " \n\n /// Docs\n/// Docs\n\n hi" + "a.smithy", + " \n\n /// Docs\n/// Docs\n\n hi" ); tokenizer.skipWsAndDocs(); @@ -125,16 +125,16 @@ public void throwsWhenBrNotFound() { IdlInternalTokenizer tokenizer = new IdlInternalTokenizer("a.smithy", "Hi"); ModelSyntaxException e = Assertions.assertThrows( - ModelSyntaxException.class, - tokenizer::expectAndSkipBr + ModelSyntaxException.class, + tokenizer::expectAndSkipBr ); assertThat( - e.getMessage(), - startsWith( - "Syntax error at line 1, column 1: Expected a line break, but " - + "found IDENTIFIER('Hi')" - ) + e.getMessage(), + startsWith( + "Syntax error at line 1, column 1: Expected a line break, but " + + "found IDENTIFIER('Hi')" + ) ); } @@ -157,16 +157,16 @@ public void failsForSingleExpectedToken() { IdlInternalTokenizer tokenizer = new IdlInternalTokenizer("a.smithy", "Hi"); ModelSyntaxException e = Assertions.assertThrows( - ModelSyntaxException.class, - () -> tokenizer.expect(IdlToken.NUMBER) + ModelSyntaxException.class, + () -> tokenizer.expect(IdlToken.NUMBER) ); assertThat( - e.getMessage(), - startsWith( - "Syntax error at line 1, column 1: Expected NUMBER but " - + "found IDENTIFIER('Hi')" - ) + e.getMessage(), + startsWith( + "Syntax error at line 1, column 1: Expected NUMBER but " + + "found IDENTIFIER('Hi')" + ) ); } @@ -182,25 +182,25 @@ public void failsForMultipleExpectedTokens() { IdlInternalTokenizer tokenizer = new IdlInternalTokenizer("a.smithy", "Hi"); ModelSyntaxException e = Assertions.assertThrows( - ModelSyntaxException.class, - () -> tokenizer.expect(IdlToken.NUMBER, IdlToken.LBRACE) + ModelSyntaxException.class, + () -> tokenizer.expect(IdlToken.NUMBER, IdlToken.LBRACE) ); assertThat( - e.getMessage(), - startsWith( - "Syntax error at line 1, column 1: Expected one of NUMBER, LBRACE('{'); " - + "but found IDENTIFIER('Hi')" - ) + e.getMessage(), + startsWith( + "Syntax error at line 1, column 1: Expected one of NUMBER, LBRACE('{'); " + + "but found IDENTIFIER('Hi')" + ) ); } @Test public void returnsCapturedDocsInRange() { String model = "/// Hi\n" - + "/// There\n" - + "/// 123\n" - + "/// 456\n"; + + "/// There\n" + + "/// 123\n" + + "/// 456\n"; IdlInternalTokenizer tokenizer = new IdlInternalTokenizer("a.smithy", model); tokenizer.skipWsAndDocs(); @@ -212,69 +212,69 @@ public void returnsCapturedDocsInRange() { public static Stream textBlockTests() { return Stream.of( - Arguments.of( - "\"\"\"\n" - + " Hello\n" - + " - Indented\"\"\"\n", - "Hello\n - Indented" - ), - Arguments.of( - "\"\"\"\n" - + " Hello\n" - + " - Indented\n" - + " \"\"\"\n", - "Hello\n - Indented\n" - ), - Arguments.of( - "\"\"\"\n" - + " Hello\n" - + " - Indented\n" - + "\"\"\"\n", - " Hello\n - Indented\n" - ), - Arguments.of( - "\"\"\"\n" - + " Hello\"\"\"\n", - "Hello" - ), - Arguments.of( - "\"\"\"\n" - + " Hello\n" - + "\n" - + " - Indented\n" - + "\"\"\"\n", - " Hello\n\n - Indented\n" - ), - Arguments.of( - "\"\"\"\n" - + " \n" // only WS doesn't influence line length calculations. - + " Hello\n" - + " \n" // only WS doesn't influence line length calculations. - + " \"\"\"", - "\nHello\n\n" - ), - Arguments.of( - "\"\"\"\n" - + "\n" // empty lines are incidental whitespace. - + " Hello\n" - + " \n" // only WS doesn't influence line length calculations. - + " \"\"\"", - "\nHello\n\n" - ), - Arguments.of( - "\"\"\"\n" - + "\n" // empty lines are incidental whitespace. - + "Hello\n" - + "\n" - + "\n" - + "\"\"\"", - "\nHello\n\n\n" - ), - Arguments.of( - "\"\"\"\n" - + "\"\"\"", - "" - ) + Arguments.of( + "\"\"\"\n" + + " Hello\n" + + " - Indented\"\"\"\n", + "Hello\n - Indented" + ), + Arguments.of( + "\"\"\"\n" + + " Hello\n" + + " - Indented\n" + + " \"\"\"\n", + "Hello\n - Indented\n" + ), + Arguments.of( + "\"\"\"\n" + + " Hello\n" + + " - Indented\n" + + "\"\"\"\n", + " Hello\n - Indented\n" + ), + Arguments.of( + "\"\"\"\n" + + " Hello\"\"\"\n", + "Hello" + ), + Arguments.of( + "\"\"\"\n" + + " Hello\n" + + "\n" + + " - Indented\n" + + "\"\"\"\n", + " Hello\n\n - Indented\n" + ), + Arguments.of( + "\"\"\"\n" + + " \n" // only WS doesn't influence line length calculations. + + " Hello\n" + + " \n" // only WS doesn't influence line length calculations. + + " \"\"\"", + "\nHello\n\n" + ), + Arguments.of( + "\"\"\"\n" + + "\n" // empty lines are incidental whitespace. + + " Hello\n" + + " \n" // only WS doesn't influence line length calculations. + + " \"\"\"", + "\nHello\n\n" + ), + Arguments.of( + "\"\"\"\n" + + "\n" // empty lines are incidental whitespace. + + "Hello\n" + + "\n" + + "\n" + + "\"\"\"", + "\nHello\n\n\n" + ), + Arguments.of( + "\"\"\"\n" + + "\"\"\"", + "" + ) ); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/IdlModelLoaderTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/IdlModelLoaderTest.java index 937bf461514..818d27e6749 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/IdlModelLoaderTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/IdlModelLoaderTest.java @@ -52,9 +52,9 @@ public class IdlModelLoaderTest { @Test public void loadsAppropriateSourceLocations() { Model model = Model.assembler() - .addImport(getClass().getResource("valid/main-test.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("valid/main-test.smithy")) + .assemble() + .unwrap(); model.shapes().forEach(shape -> { if (!Prelude.isPreludeShape(shape.getId())) { @@ -73,9 +73,9 @@ public void loadsAppropriateSourceLocations() { @Test public void loadsAppropriateTraitSourceLocations() { Model model = Model.assembler() - .addImport(getClass().getResource("valid/trait-locations.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("valid/trait-locations.smithy")) + .assemble() + .unwrap(); Shape shape = model.expectShape(ShapeId.from("com.example#TraitBearer")); @@ -93,19 +93,19 @@ public void loadsAppropriateTraitSourceLocations() { @Test public void fallsBackToPublicPreludeShapes() { Model model = Model.assembler() - .addImport(getClass().getResource("valid/forward-reference-resolver.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("valid/forward-reference-resolver.smithy")) + .assemble() + .unwrap(); MemberShape baz = model.expectShape(ShapeId.from("smithy.example#Foo$baz")) - .asMemberShape() - .get(); + .asMemberShape() + .get(); MemberShape bar = model.expectShape(ShapeId.from("smithy.example#Foo$bar")) - .asMemberShape() - .get(); + .asMemberShape() + .get(); ResourceShape resource = model.expectShape(ShapeId.from("smithy.example#MyResource")) - .asResourceShape() - .get(); + .asResourceShape() + .get(); assertThat(baz.getTarget().toString(), equalTo("smithy.api#String")); assertThat(bar.getTarget().toString(), equalTo("smithy.example#Integer")); @@ -117,20 +117,20 @@ public void fallsBackToPublicPreludeShapes() { @Test public void canLoadAndAliasShapesAndTraits() { Model model = Model.assembler() - .addImport(getClass().getResource("first-namespace.smithy")) - .addImport(getClass().getResource("second-namespace.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("first-namespace.smithy")) + .addImport(getClass().getResource("second-namespace.smithy")) + .assemble() + .unwrap(); } @Test public void defersApplyTargetAndTrait() { Model model = Model.assembler() - .addImport(getClass().getResource("apply-use-1.smithy")) - .addImport(getClass().getResource("apply-use-2.smithy")) - .addImport(getClass().getResource("apply-use-3.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("apply-use-1.smithy")) + .addImport(getClass().getResource("apply-use-2.smithy")) + .addImport(getClass().getResource("apply-use-3.smithy")) + .assemble() + .unwrap(); Shape shape = model.expectShape(ShapeId.from("smithy.example#Foo")); @@ -160,15 +160,15 @@ public void limitsRecursion() { @Test public void handlesMultilineDocComments() { Model model = Model.assembler() - .addImport(getClass().getResource("multiline-comments.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("multiline-comments.smithy")) + .assemble() + .unwrap(); Shape shape = model.expectShape(ShapeId.from("smithy.example#MyStruct$myMember")); String docs = shape.getTrait(DocumentationTrait.class) - .map(StringTrait::getValue) - .orElse("") - .replace("\r\n", "\n"); + .map(StringTrait::getValue) + .orElse("") + .replace("\r\n", "\n"); assertThat(docs, equalTo("This is the first line.\nThis is the second line.")); } @@ -176,50 +176,50 @@ public void handlesMultilineDocComments() { @Test public void warnsWhenInvalidSyntacticShapeIdIsFound() { ValidatedResult result = Model.assembler() - .addUnparsedModel( - "foo.smithy", - "$version: \"2.0\"\n" - + "namespace smithy.example\n" - + "@tags([nonono])\n" - + "string Foo\n" - ) - .assemble(); + .addUnparsedModel( + "foo.smithy", + "$version: \"2.0\"\n" + + "namespace smithy.example\n" + + "@tags([nonono])\n" + + "string Foo\n" + ) + .assemble(); assertThat(result.isBroken(), is(true)); List events = result.getValidationEvents(Severity.DANGER); assertThat(events.stream().filter(e -> e.getId().equals("SyntacticShapeIdTarget")).count(), equalTo(1L)); assertThat( - events.stream() - .filter(e -> e.getId().equals("SyntacticShapeIdTarget")) - .filter(e -> e.getMessage().contains("`nonono`")) - .count(), - equalTo(1L) + events.stream() + .filter(e -> e.getId().equals("SyntacticShapeIdTarget")) + .filter(e -> e.getMessage().contains("`nonono`")) + .count(), + equalTo(1L) ); } @Test public void properlyLoadsOperationsWithUseStatements() { Model model = Model.assembler() - .addImport(getClass().getResource("use-operations/service.smithy")) - .addImport(getClass().getResource("use-operations/nested.smithy")) - .addImport(getClass().getResource("use-operations/other.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("use-operations/service.smithy")) + .addImport(getClass().getResource("use-operations/nested.smithy")) + .addImport(getClass().getResource("use-operations/other.smithy")) + .assemble() + .unwrap(); // Spot check for a specific "use" shape. assertThat( - model.expectShape(ShapeId.from("smithy.example#Local"), OperationShape.class).getInput(), - equalTo(Optional.of(ShapeId.from("smithy.example.nested#A"))) + model.expectShape(ShapeId.from("smithy.example#Local"), OperationShape.class).getInput(), + equalTo(Optional.of(ShapeId.from("smithy.example.nested#A"))) ); assertThat( - model.expectShape(ShapeId.from("smithy.example#Local"), OperationShape.class).getErrors(), - equalTo(ListUtils.of(ShapeId.from("smithy.example.nested#C"))) + model.expectShape(ShapeId.from("smithy.example#Local"), OperationShape.class).getErrors(), + equalTo(ListUtils.of(ShapeId.from("smithy.example.nested#C"))) ); Map identifiers = model.expectShape( - ShapeId.from("smithy.example.nested#Resource"), - ResourceShape.class + ShapeId.from("smithy.example.nested#Resource"), + ResourceShape.class ).getIdentifiers(); assertThat(identifiers.get("s"), equalTo(ShapeId.from("smithy.api#String"))); @@ -246,10 +246,10 @@ public void addressesConfusingEdgeCaseForUnknownTraits() { }; List events = Model.assembler() - .traitFactory(factory) - .addUnparsedModel("foo.smithy", "namespace smithy.example\n@foo\nstring MyString\n") - .assemble() - .getValidationEvents(); + .traitFactory(factory) + .addUnparsedModel("foo.smithy", "namespace smithy.example\n@foo\nstring MyString\n") + .assemble() + .getValidationEvents(); // Ensure that there is also an event that the @foo trait couldn't be found. // This is a bit overkill, but ensures that it works end-to-end. @@ -268,25 +268,25 @@ public void addressesConfusingEdgeCaseForUnknownTraits() { @Test public void loadsServiceRenames() { Model model = Model.assembler() - .addImport(getClass().getResource("valid/__shared.json")) - .addImport(getClass().getResource("valid/service-with-rename.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("valid/__shared.json")) + .addImport(getClass().getResource("valid/service-with-rename.smithy")) + .assemble() + .unwrap(); // Spot check for a specific "use" shape. assertThat( - model.expectShape(ShapeId.from("smithy.example#MyService"), ServiceShape.class).getRename(), - equalTo(MapUtils.of(ShapeId.from("foo.example#Widget"), "FooWidget")) + model.expectShape(ShapeId.from("smithy.example#MyService"), ServiceShape.class).getRename(), + equalTo(MapUtils.of(ShapeId.from("foo.example#Widget"), "FooWidget")) ); } @Test public void loadsServicesWithNonconflictingUnitTypes() { Model model = Model.assembler() - .addImport(getClass().getResource("valid/__shared.json")) - .addImport(getClass().getResource("valid/service-with-nonconflicting-unit.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("valid/__shared.json")) + .addImport(getClass().getResource("valid/service-with-nonconflicting-unit.smithy")) + .assemble() + .unwrap(); // Make sure we can find our Unit type assertThat(model.expectShape(ShapeId.from("smithy.example#Unit")), Matchers.notNullValue()); @@ -305,9 +305,9 @@ public void emitsVersionWhenNotSet() { @Test public void defaultValueSugaringDoesNotEatSubsequentDocumentation() { Model model = Model.assembler() - .addImport(getClass().getResource("default-subsequent-trait.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("default-subsequent-trait.smithy")) + .assemble() + .unwrap(); StructureShape testShape = model.expectShape(ShapeId.from("smithy.example#TestShape"), StructureShape.class); MemberShape barMember = testShape.getMember("bar").orElseThrow(AssertionFailedError::new); @@ -327,14 +327,14 @@ public void defaultValueSugaringDoesNotEatSubsequentDocumentation() { @Test public void setsCorrectLocationForEnum() { Model model = Model.assembler() - .addImport(getClass().getResource("valid/enums/enums.smithy")) - .addImport(getClass().getResource("valid/enums/enum-docs.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("valid/enums/enums.smithy")) + .addImport(getClass().getResource("valid/enums/enum-docs.smithy")) + .assemble() + .unwrap(); EnumShape enumWithoutValueTraits = model.expectShape( - ShapeId.from("smithy.example#EnumWithoutValueTraits"), - EnumShape.class + ShapeId.from("smithy.example#EnumWithoutValueTraits"), + EnumShape.class ); MemberShape barMember = enumWithoutValueTraits.getMember("BAR").orElseThrow(AssertionFailedError::new); @@ -355,8 +355,8 @@ public void setsCorrectLocationForEnum() { @Test public void doesBasicErrorRecoveryToTrait() { ValidatedResult result = Model.assembler() - .addImport(getClass().getResource("error-recovery/to-trait.smithy")) - .assemble(); + .addImport(getClass().getResource("error-recovery/to-trait.smithy")) + .assemble(); assertThat(result.isBroken(), is(true)); assertThat(result.getResult().isPresent(), is(true)); @@ -372,9 +372,9 @@ public void doesBasicErrorRecoveryToTrait() { boolean foundTrait = false; for (ValidationEvent e : result.getValidationEvents()) { if (e.getSeverity() == Severity.ERROR && e.getMessage() - .contains( - "Syntax error at line 9, column 9: Expected COLON(':') but found IDENTIFIER('MyInteger')" - )) { + .contains( + "Syntax error at line 9, column 9: Expected COLON(':') but found IDENTIFIER('MyInteger')" + )) { foundSyntax = true; } if (e.getSeverity() == Severity.ERROR && e.getMessage().contains("Unable to resolve trait")) { @@ -389,8 +389,8 @@ public void doesBasicErrorRecoveryToTrait() { @Test public void doesBasicErrorRecoveryToDocs() { ValidatedResult result = Model.assembler() - .addImport(getClass().getResource("error-recovery/to-docs.smithy")) - .assemble(); + .addImport(getClass().getResource("error-recovery/to-docs.smithy")) + .assemble(); assertThat(result.isBroken(), is(true)); assertThat(result.getResult().isPresent(), is(true)); @@ -420,8 +420,8 @@ public void doesBasicErrorRecoveryToDocs() { @Test public void doesBasicErrorRecoveryToIdentifier() { ValidatedResult result = Model.assembler() - .addImport(getClass().getResource("error-recovery/to-identifier.smithy")) - .assemble(); + .addImport(getClass().getResource("error-recovery/to-identifier.smithy")) + .assemble(); assertThat(result.isBroken(), is(true)); assertThat(result.getResult().isPresent(), is(true)); @@ -433,11 +433,11 @@ public void doesBasicErrorRecoveryToIdentifier() { assertThat(model.expectShape(myString).hasTrait(ExternalDocumentationTrait.class), is(false)); boolean foundSyntax = result.getValidationEvents() - .stream() - .anyMatch( - e -> e.getSeverity() == Severity.ERROR - && e.getMessage().contains("Syntax error at line 6, column 28") - ); + .stream() + .anyMatch( + e -> e.getSeverity() == Severity.ERROR + && e.getMessage().contains("Syntax error at line 6, column 28") + ); assertThat(foundSyntax, is(true)); } @@ -445,8 +445,8 @@ public void doesBasicErrorRecoveryToIdentifier() { @Test public void doesBasicErrorRecoveryToControl() { ValidatedResult result = Model.assembler() - .addImport(getClass().getResource("error-recovery/to-dollar.smithy")) - .assemble(); + .addImport(getClass().getResource("error-recovery/to-dollar.smithy")) + .assemble(); assertThat(result.isBroken(), is(true)); assertThat(result.getResult().isPresent(), is(true)); @@ -456,11 +456,11 @@ public void doesBasicErrorRecoveryToControl() { assertThat(model.getShape(ShapeId.from("smithy.example#MyInteger")).isPresent(), is(true)); boolean foundSyntax = result.getValidationEvents() - .stream() - .anyMatch( - e -> e.getSeverity() == Severity.ERROR - && e.getMessage().contains("Syntax error at line 1, column 5") - ); + .stream() + .anyMatch( + e -> e.getSeverity() == Severity.ERROR + && e.getMessage().contains("Syntax error at line 1, column 5") + ); assertThat(foundSyntax, is(true)); } @@ -468,8 +468,8 @@ public void doesBasicErrorRecoveryToControl() { @Test public void doesBasicErrorRecoveryInMetadata() { ValidatedResult result = Model.assembler() - .addImport(getClass().getResource("error-recovery/in-metadata.smithy")) - .assemble(); + .addImport(getClass().getResource("error-recovery/in-metadata.smithy")) + .assemble(); assertThat(result.isBroken(), is(true)); assertThat(result.getResult().isPresent(), is(true)); @@ -485,9 +485,9 @@ public void doesBasicErrorRecoveryInMetadata() { // Find all four invalid metadata keys. long foundSyntax = result.getValidationEvents() - .stream() - .filter(e -> e.getSeverity() == Severity.ERROR && e.getMessage().contains("Syntax error")) - .count(); + .stream() + .filter(e -> e.getSeverity() == Severity.ERROR && e.getMessage().contains("Syntax error")) + .count(); assertThat(foundSyntax, equalTo(4L)); } @@ -503,15 +503,15 @@ public void throwsWhenTooNested() { ModelSyntaxException e = Assertions.assertThrows(ModelSyntaxException.class, loader::increaseNestingLevel); assertThat( - e.getMessage(), - startsWith("Syntax error at line 1, column 1: Parser exceeded maximum allowed depth of 64") + e.getMessage(), + startsWith("Syntax error at line 1, column 1: Parser exceeded maximum allowed depth of 64") ); } @Test public void handlesMultipleMemberInheritance() { ValidatedResult result = Model.assembler() - .addImport(getClass().getResource("error-recovery/to-dollar.smithy")) - .assemble(); + .addImport(getClass().getResource("error-recovery/to-dollar.smithy")) + .assemble(); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/InvalidSmithyModelLoaderRunnerTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/InvalidSmithyModelLoaderRunnerTest.java index a7173a31804..7ab5d46e1e9 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/InvalidSmithyModelLoaderRunnerTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/InvalidSmithyModelLoaderRunnerTest.java @@ -33,22 +33,22 @@ public void testParserRunner(String file) { try { Model.assembler() - .addImport(file) - .assemble() - .unwrap(); + .addImport(file) + .assemble() + .unwrap(); throw new IllegalStateException("Expected a parse error for " + file); } catch (RuntimeException e) { String actualMessage = cleanErrorMessage(e.getMessage()); String expectedMessage = cleanErrorMessage(expectedError); if (!actualMessage.contains(expectedMessage)) { throw new IllegalStateException( - String.format( - "Expected a different parse error for %s.\nExpected (%s)\nFound (%s)", - file, - expectedMessage, - actualMessage - ), - e + String.format( + "Expected a different parse error for %s.\nExpected (%s)\nFound (%s)", + file, + expectedMessage, + actualMessage + ), + e ); } } @@ -56,29 +56,29 @@ public void testParserRunner(String file) { private String cleanErrorMessage(String errorMessage) { return errorMessage - // We'll never see EOF on Windows since we only get 2 context characters and those - // will be taken up by the line separator characters. - .replace("[EOF]", "") - // Make sure the line separators and representations of them are consistent across - // operating systems. - .replace("\r\n", "\\n") - .replace("\r", "\\n") - .replace("\n", "\\n"); + // We'll never see EOF on Windows since we only get 2 context characters and those + // will be taken up by the line separator characters. + .replace("[EOF]", "") + // Make sure the line separators and representations of them are consistent across + // operating systems. + .replace("\r\n", "\\n") + .replace("\r", "\\n") + .replace("\n", "\\n"); } public static Collection data() throws Exception { try ( - Stream paths = Files.walk( - Paths.get( - ValidSmithyModelLoaderRunnerTest.class.getResource("invalid").toURI() + Stream paths = Files.walk( + Paths.get( + ValidSmithyModelLoaderRunnerTest.class.getResource("invalid").toURI() + ) ) - ) ) { return paths - .filter(Files::isRegularFile) - .filter(file -> file.toString().endsWith(".smithy")) - .map(Object::toString) - .collect(Collectors.toList()); + .filter(Files::isRegularFile) + .filter(file -> file.toString().endsWith(".smithy")) + .map(Object::toString) + .collect(Collectors.toList()); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelAssemblerTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelAssemblerTest.java index 3cb0f621201..03658411e87 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelAssemblerTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelAssemblerTest.java @@ -100,8 +100,8 @@ public void after() throws IOException { public void addsExplicitShapes() { StringShape shape = StringShape.builder().id("ns.foo#Bar").build(); ValidatedResult result = new ModelAssembler() - .addShape(shape) - .assemble(); + .addShape(shape) + .assemble(); assertThat(result.getValidationEvents(), empty()); assertThat(result.unwrap().getShape(ShapeId.from("ns.foo#Bar")), is(Optional.of(shape))); @@ -112,9 +112,9 @@ public void addsExplicitTraits() { StringShape shape = StringShape.builder().id("ns.foo#Bar").build(); SuppressTrait trait = SuppressTrait.builder().build(); ValidatedResult result = new ModelAssembler() - .addShape(shape) - .addTrait(shape.toShapeId(), trait) - .assemble(); + .addShape(shape) + .addTrait(shape.toShapeId(), trait) + .assemble(); assertThat(result.getValidationEvents(), empty()); Shape resultShape = result.unwrap().getShape(ShapeId.from("ns.foo#Bar")).get(); @@ -127,9 +127,9 @@ public void addsExplicitTraitsToBuiltModel() { StringShape shape = StringShape.builder().id("ns.foo#Bar").build(); SuppressTrait trait = SuppressTrait.builder().build(); ValidatedResult result = new ModelAssembler() - .addModel(Model.assembler().addShape(shape).assemble().unwrap()) - .addTrait(shape.toShapeId(), trait) - .assemble(); + .addModel(Model.assembler().addShape(shape).assemble().unwrap()) + .addTrait(shape.toShapeId(), trait) + .assemble(); assertThat(result.getValidationEvents(), empty()); Shape resultShape = result.unwrap().getShape(ShapeId.from("ns.foo#Bar")).get(); @@ -140,12 +140,12 @@ public void addsExplicitTraitsToBuiltModel() { @Test public void addsExplicitTraitsToUnparsedModel() { String unparsed = "{\"smithy\": \"" + Model.MODEL_VERSION - + "\", \"shapes\": { \"ns.foo#Bar\": { \"type\": \"string\"}}}"; + + "\", \"shapes\": { \"ns.foo#Bar\": { \"type\": \"string\"}}}"; SuppressTrait trait = SuppressTrait.builder().build(); ValidatedResult result = new ModelAssembler() - .addUnparsedModel(SourceLocation.NONE.getFilename(), unparsed) - .addTrait(ShapeId.from("ns.foo#Bar"), trait) - .assemble(); + .addUnparsedModel(SourceLocation.NONE.getFilename(), unparsed) + .addTrait(ShapeId.from("ns.foo#Bar"), trait) + .assemble(); assertThat(result.getValidationEvents(), empty()); Shape resultShape = result.unwrap().getShape(ShapeId.from("ns.foo#Bar")).get(); @@ -156,12 +156,12 @@ public void addsExplicitTraitsToUnparsedModel() { @Test public void addsExplicitTraitsToParsedDocumentNode() { String unparsed = "{\"smithy\": \"" + Model.MODEL_VERSION - + "\", \"shapes\": { \"ns.foo#Bar\": { \"type\": \"string\"}}}"; + + "\", \"shapes\": { \"ns.foo#Bar\": { \"type\": \"string\"}}}"; SuppressTrait trait = SuppressTrait.builder().build(); ValidatedResult result = new ModelAssembler() - .addDocumentNode(Node.parse(unparsed, SourceLocation.NONE.getFilename())) - .addTrait(ShapeId.from("ns.foo#Bar"), trait) - .assemble(); + .addDocumentNode(Node.parse(unparsed, SourceLocation.NONE.getFilename())) + .addTrait(ShapeId.from("ns.foo#Bar"), trait) + .assemble(); assertThat(result.getValidationEvents(), empty()); Shape resultShape = result.unwrap().getShape(ShapeId.from("ns.foo#Bar")).get(); @@ -172,16 +172,16 @@ public void addsExplicitTraitsToParsedDocumentNode() { @Test public void addsExplicitDocumentNode_1_0_0() { ObjectNode node = Node.objectNode() - .withMember("smithy", "1.0") - .withMember( - "shapes", - Node.objectNode() - .withMember( - "ns.foo#String", + .withMember("smithy", "1.0") + .withMember( + "shapes", Node.objectNode() - .withMember("type", Node.from("string")) - ) - ); + .withMember( + "ns.foo#String", + Node.objectNode() + .withMember("type", Node.from("string")) + ) + ); ValidatedResult result = new ModelAssembler().addDocumentNode(node).assemble(); assertTrue(result.unwrap().getShape(ShapeId.from("ns.foo#String")).isPresent()); @@ -190,10 +190,10 @@ public void addsExplicitDocumentNode_1_0_0() { @Test public void addsExplicitUnparsedDocumentNode() { String document = "{\"smithy\": \"" + Model.MODEL_VERSION - + "\", \"shapes\": { \"ns.foo#String\": { \"type\": \"string\"}}}"; + + "\", \"shapes\": { \"ns.foo#String\": { \"type\": \"string\"}}}"; ValidatedResult result = new ModelAssembler() - .addUnparsedModel(SourceLocation.NONE.getFilename(), document) - .assemble(); + .addUnparsedModel(SourceLocation.NONE.getFilename(), document) + .assemble(); assertThat(result.getValidationEvents(), empty()); assertTrue(result.unwrap().getShape(ShapeId.from("ns.foo#String")).isPresent()); @@ -202,15 +202,15 @@ public void addsExplicitUnparsedDocumentNode() { @Test public void addsExplicitValidators() { ValidationEvent event = ValidationEvent.builder() - .severity(Severity.ERROR) - .id("Foo") - .message("bar") - .build(); + .severity(Severity.ERROR) + .id("Foo") + .message("bar") + .build(); String document = "{\"smithy\": \"" + Model.MODEL_VERSION + "\"}"; ValidatedResult result = new ModelAssembler() - .addUnparsedModel(SourceLocation.NONE.getFilename(), document) - .addValidator(index -> Collections.singletonList(event)) - .assemble(); + .addUnparsedModel(SourceLocation.NONE.getFilename(), document) + .addValidator(index -> Collections.singletonList(event)) + .assemble(); assertThat(result.getValidationEvents(), contains(event)); } @@ -218,17 +218,17 @@ public void addsExplicitValidators() { @Test public void detectsTraitsOnUnknownShape() { String document = "{\"smithy\": \"" + Model.MODEL_VERSION - + "\", \"shapes\": {\"ns.foo#Unknown\": {\"type\": \"apply\", \"traits\": {\"smithy.api#documentation\": \"foo\"}}}}"; + + "\", \"shapes\": {\"ns.foo#Unknown\": {\"type\": \"apply\", \"traits\": {\"smithy.api#documentation\": \"foo\"}}}}"; ValidatedResult result = new ModelAssembler() - .addUnparsedModel(SourceLocation.NONE.getFilename(), document) - .assemble(); + .addUnparsedModel(SourceLocation.NONE.getFilename(), document) + .assemble(); assertThat(result.getValidationEvents(), hasSize(1)); assertThat( - result.getValidationEvents().get(0).getMessage(), - containsString( - "Trait `documentation` applied to unknown shape `ns.foo#Unknown`" - ) + result.getValidationEvents().get(0).getMessage(), + containsString( + "Trait `documentation` applied to unknown shape `ns.foo#Unknown`" + ) ); assertThat(result.getValidationEvents().get(0).getSeverity(), is(Severity.ERROR)); } @@ -236,17 +236,17 @@ public void detectsTraitsOnUnknownShape() { @Test public void detectsInvalidShapeTypes() { ValidatedResult result = new ModelAssembler() - .addImport(getClass().getResource("invalid-shape-types.json")) - .assemble(); + .addImport(getClass().getResource("invalid-shape-types.json")) + .assemble(); assertThat(result.getValidationEvents(), hasSize(1)); assertThat(result.getValidationEvents().get(0).getMessage(), containsString("Invalid shape `type`: foobaz")); assertThat(result.getValidationEvents().get(0).getSeverity(), is(Severity.ERROR)); assertTrue( - result.getResult() - .get() - .getShape(ShapeId.from("example.namespace#String")) - .isPresent() + result.getResult() + .get() + .getShape(ShapeId.from("example.namespace#String")) + .isPresent() ); } @@ -258,94 +258,94 @@ public void detectsUnresolvedImports() { @Test public void importsSymlinksDirectoryWithAllShapes() throws Exception { ValidatedResult result = new ModelAssembler() - .addImport(getClass().getResource("main.json")) - .addImport(createSymbolicLink(Paths.get(getClass().getResource("nested").toURI()), "symlink-nested")) - .assemble(); + .addImport(getClass().getResource("main.json")) + .addImport(createSymbolicLink(Paths.get(getClass().getResource("nested").toURI()), "symlink-nested")) + .assemble(); Model model = result.unwrap(); assertTrue(model.getShape(ShapeId.from("example.namespace#String")).isPresent()); assertThat( - model.getShape(ShapeId.from("example.namespace#String")).get().getType(), - is(ShapeType.STRING) + model.getShape(ShapeId.from("example.namespace#String")).get().getType(), + is(ShapeType.STRING) ); assertThat( - model.getShape(ShapeId.from("example.namespace#String2")).get().getType(), - is(ShapeType.STRING) + model.getShape(ShapeId.from("example.namespace#String2")).get().getType(), + is(ShapeType.STRING) ); assertThat( - model.getShape(ShapeId.from("example.namespace#String3")).get().getType(), - is(ShapeType.STRING) + model.getShape(ShapeId.from("example.namespace#String3")).get().getType(), + is(ShapeType.STRING) ); assertThat( - model.getShape(ShapeId.from("example.namespace#String")).get().getType(), - is(ShapeType.STRING) + model.getShape(ShapeId.from("example.namespace#String")).get().getType(), + is(ShapeType.STRING) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Integer")).get().getType(), - is(ShapeType.INTEGER) + model.getShape(ShapeId.from("example.namespace#Integer")).get().getType(), + is(ShapeType.INTEGER) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Long")).get().getType(), - is(ShapeType.LONG) + model.getShape(ShapeId.from("example.namespace#Long")).get().getType(), + is(ShapeType.LONG) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Float")).get().getType(), - is(ShapeType.FLOAT) + model.getShape(ShapeId.from("example.namespace#Float")).get().getType(), + is(ShapeType.FLOAT) ); assertThat( - model.getShape(ShapeId.from("example.namespace#BigDecimal")).get().getType(), - is(ShapeType.BIG_DECIMAL) + model.getShape(ShapeId.from("example.namespace#BigDecimal")).get().getType(), + is(ShapeType.BIG_DECIMAL) ); assertThat( - model.getShape(ShapeId.from("example.namespace#BigInteger")).get().getType(), - is(ShapeType.BIG_INTEGER) + model.getShape(ShapeId.from("example.namespace#BigInteger")).get().getType(), + is(ShapeType.BIG_INTEGER) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Blob")).get().getType(), - is(ShapeType.BLOB) + model.getShape(ShapeId.from("example.namespace#Blob")).get().getType(), + is(ShapeType.BLOB) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Boolean")).get().getType(), - is(ShapeType.BOOLEAN) + model.getShape(ShapeId.from("example.namespace#Boolean")).get().getType(), + is(ShapeType.BOOLEAN) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Timestamp")).get().getType(), - is(ShapeType.TIMESTAMP) + model.getShape(ShapeId.from("example.namespace#Timestamp")).get().getType(), + is(ShapeType.TIMESTAMP) ); assertThat( - model.getShape(ShapeId.from("example.namespace#List")).get().getType(), - is(ShapeType.LIST) + model.getShape(ShapeId.from("example.namespace#List")).get().getType(), + is(ShapeType.LIST) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Map")).get().getType(), - is(ShapeType.MAP) + model.getShape(ShapeId.from("example.namespace#Map")).get().getType(), + is(ShapeType.MAP) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Structure")).get().getType(), - is(ShapeType.STRUCTURE) + model.getShape(ShapeId.from("example.namespace#Structure")).get().getType(), + is(ShapeType.STRUCTURE) ); assertThat( - model.getShape(ShapeId.from("example.namespace#TaggedUnion")).get().getType(), - is(ShapeType.UNION) + model.getShape(ShapeId.from("example.namespace#TaggedUnion")).get().getType(), + is(ShapeType.UNION) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Resource")).get().getType(), - is(ShapeType.RESOURCE) + model.getShape(ShapeId.from("example.namespace#Resource")).get().getType(), + is(ShapeType.RESOURCE) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Operation")).get().getType(), - is(ShapeType.OPERATION) + model.getShape(ShapeId.from("example.namespace#Operation")).get().getType(), + is(ShapeType.OPERATION) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Service")).get().getType(), - is(ShapeType.SERVICE) + model.getShape(ShapeId.from("example.namespace#Service")).get().getType(), + is(ShapeType.SERVICE) ); ShapeId stringId = ShapeId.from("example.namespace#String"); Optional sensitiveTrait = model - .getShape(stringId) - .get() - .getTrait(SensitiveTrait.class); + .getShape(stringId) + .get() + .getTrait(SensitiveTrait.class); assertTrue(sensitiveTrait.isPresent()); assertThat(model.getMetadata(), hasKey("foo")); @@ -356,36 +356,36 @@ public void importsSymlinksDirectoryWithAllShapes() throws Exception { assertThat(model.getMetadata().get("lorem"), equalTo(Node.from("ipsum"))); assertThat(model.getMetadata(), hasKey("list")); assertThat( - model.getMetadata().get("list").expectArrayNode().getElementsAs(StringNode::getValue), - containsInAnyOrder("a", "b", "c") + model.getMetadata().get("list").expectArrayNode().getElementsAs(StringNode::getValue), + containsInAnyOrder("a", "b", "c") ); // The String shape should have a documentation trait applied. assertTrue( - model.getShape(ShapeId.from("example.namespace#String")) - .flatMap(shape -> shape.getTrait(DocumentationTrait.class)) - .isPresent() + model.getShape(ShapeId.from("example.namespace#String")) + .flatMap(shape -> shape.getTrait(DocumentationTrait.class)) + .isPresent() ); } @Test public void importsSymlinkFileWithAllShapes() throws Exception { ValidatedResult result = new ModelAssembler() - .addImport(getClass().getResource("main.json")) - .addImport( - createSymbolicLink( - Paths.get(getClass().getResource("nested/merges-2.json").toURI()), - "symlink-merges-2.json" + .addImport(getClass().getResource("main.json")) + .addImport( + createSymbolicLink( + Paths.get(getClass().getResource("nested/merges-2.json").toURI()), + "symlink-merges-2.json" + ) ) - ) - .assemble(); + .assemble(); assertThat(result.getValidationEvents(), empty()); Model model = result.unwrap(); // The String shape should have a documentation trait applied. assertTrue( - model.getShape(ShapeId.from("example.namespace#String")) - .flatMap(shape -> shape.getTrait(DocumentationTrait.class)) - .isPresent() + model.getShape(ShapeId.from("example.namespace#String")) + .flatMap(shape -> shape.getTrait(DocumentationTrait.class)) + .isPresent() ); } @@ -407,94 +407,94 @@ public Path createSymbolicLink(Path target, String linkName) throws IOException @Test public void importsFilesWithAllShapes() throws Exception { ValidatedResult result = new ModelAssembler() - .addImport(getClass().getResource("main.json")) - .addImport(Paths.get(getClass().getResource("nested").toURI())) - .assemble(); + .addImport(getClass().getResource("main.json")) + .addImport(Paths.get(getClass().getResource("nested").toURI())) + .assemble(); Model model = result.unwrap(); assertTrue(model.getShape(ShapeId.from("example.namespace#String")).isPresent()); assertThat( - model.getShape(ShapeId.from("example.namespace#String")).get().getType(), - is(ShapeType.STRING) + model.getShape(ShapeId.from("example.namespace#String")).get().getType(), + is(ShapeType.STRING) ); assertThat( - model.getShape(ShapeId.from("example.namespace#String2")).get().getType(), - is(ShapeType.STRING) + model.getShape(ShapeId.from("example.namespace#String2")).get().getType(), + is(ShapeType.STRING) ); assertThat( - model.getShape(ShapeId.from("example.namespace#String3")).get().getType(), - is(ShapeType.STRING) + model.getShape(ShapeId.from("example.namespace#String3")).get().getType(), + is(ShapeType.STRING) ); assertThat( - model.getShape(ShapeId.from("example.namespace#String")).get().getType(), - is(ShapeType.STRING) + model.getShape(ShapeId.from("example.namespace#String")).get().getType(), + is(ShapeType.STRING) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Integer")).get().getType(), - is(ShapeType.INTEGER) + model.getShape(ShapeId.from("example.namespace#Integer")).get().getType(), + is(ShapeType.INTEGER) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Long")).get().getType(), - is(ShapeType.LONG) + model.getShape(ShapeId.from("example.namespace#Long")).get().getType(), + is(ShapeType.LONG) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Float")).get().getType(), - is(ShapeType.FLOAT) + model.getShape(ShapeId.from("example.namespace#Float")).get().getType(), + is(ShapeType.FLOAT) ); assertThat( - model.getShape(ShapeId.from("example.namespace#BigDecimal")).get().getType(), - is(ShapeType.BIG_DECIMAL) + model.getShape(ShapeId.from("example.namespace#BigDecimal")).get().getType(), + is(ShapeType.BIG_DECIMAL) ); assertThat( - model.getShape(ShapeId.from("example.namespace#BigInteger")).get().getType(), - is(ShapeType.BIG_INTEGER) + model.getShape(ShapeId.from("example.namespace#BigInteger")).get().getType(), + is(ShapeType.BIG_INTEGER) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Blob")).get().getType(), - is(ShapeType.BLOB) + model.getShape(ShapeId.from("example.namespace#Blob")).get().getType(), + is(ShapeType.BLOB) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Boolean")).get().getType(), - is(ShapeType.BOOLEAN) + model.getShape(ShapeId.from("example.namespace#Boolean")).get().getType(), + is(ShapeType.BOOLEAN) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Timestamp")).get().getType(), - is(ShapeType.TIMESTAMP) + model.getShape(ShapeId.from("example.namespace#Timestamp")).get().getType(), + is(ShapeType.TIMESTAMP) ); assertThat( - model.getShape(ShapeId.from("example.namespace#List")).get().getType(), - is(ShapeType.LIST) + model.getShape(ShapeId.from("example.namespace#List")).get().getType(), + is(ShapeType.LIST) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Map")).get().getType(), - is(ShapeType.MAP) + model.getShape(ShapeId.from("example.namespace#Map")).get().getType(), + is(ShapeType.MAP) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Structure")).get().getType(), - is(ShapeType.STRUCTURE) + model.getShape(ShapeId.from("example.namespace#Structure")).get().getType(), + is(ShapeType.STRUCTURE) ); assertThat( - model.getShape(ShapeId.from("example.namespace#TaggedUnion")).get().getType(), - is(ShapeType.UNION) + model.getShape(ShapeId.from("example.namespace#TaggedUnion")).get().getType(), + is(ShapeType.UNION) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Resource")).get().getType(), - is(ShapeType.RESOURCE) + model.getShape(ShapeId.from("example.namespace#Resource")).get().getType(), + is(ShapeType.RESOURCE) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Operation")).get().getType(), - is(ShapeType.OPERATION) + model.getShape(ShapeId.from("example.namespace#Operation")).get().getType(), + is(ShapeType.OPERATION) ); assertThat( - model.getShape(ShapeId.from("example.namespace#Service")).get().getType(), - is(ShapeType.SERVICE) + model.getShape(ShapeId.from("example.namespace#Service")).get().getType(), + is(ShapeType.SERVICE) ); ShapeId stringId = ShapeId.from("example.namespace#String"); Optional sensitiveTrait = model - .getShape(stringId) - .get() - .getTrait(SensitiveTrait.class); + .getShape(stringId) + .get() + .getTrait(SensitiveTrait.class); assertTrue(sensitiveTrait.isPresent()); assertThat(model.getMetadata(), hasKey("foo")); @@ -505,90 +505,90 @@ public void importsFilesWithAllShapes() throws Exception { assertThat(model.getMetadata().get("lorem"), equalTo(Node.from("ipsum"))); assertThat(model.getMetadata(), hasKey("list")); assertThat( - model.getMetadata().get("list").expectArrayNode().getElementsAs(StringNode::getValue), - containsInAnyOrder("a", "b", "c") + model.getMetadata().get("list").expectArrayNode().getElementsAs(StringNode::getValue), + containsInAnyOrder("a", "b", "c") ); // The String shape should have a documentation trait applied. assertTrue( - model.getShape(ShapeId.from("example.namespace#String")) - .flatMap(shape -> shape.getTrait(DocumentationTrait.class)) - .isPresent() + model.getShape(ShapeId.from("example.namespace#String")) + .flatMap(shape -> shape.getTrait(DocumentationTrait.class)) + .isPresent() ); } @Test public void reportsSourceLocationOfShapesImportedFromFiles() throws Exception { Model model = new ModelAssembler() - .addImport(getClass().getResource("main.json")) - .addImport(Paths.get(getClass().getResource("nested").toURI())) - .assemble() - .unwrap(); + .addImport(getClass().getResource("main.json")) + .addImport(Paths.get(getClass().getResource("nested").toURI())) + .assemble() + .unwrap(); String expectedPath = Paths.get(getClass().getResource("main.json").toURI()).toString(); assertThat( - model.getShape(ShapeId.from("example.namespace#String")).get().getSourceLocation(), - is(new SourceLocation(expectedPath, 4, 37)) + model.getShape(ShapeId.from("example.namespace#String")).get().getSourceLocation(), + is(new SourceLocation(expectedPath, 4, 37)) ); assertThat( - model.getShape(ShapeId.from("example.namespace#TaggedUnion$foo")).get().getSourceLocation(), - is(new SourceLocation(expectedPath, 69, 24)) + model.getShape(ShapeId.from("example.namespace#TaggedUnion$foo")).get().getSourceLocation(), + is(new SourceLocation(expectedPath, 69, 24)) ); } @Test public void detectsMetadataConflicts() { ValidatedResult result = new ModelAssembler() - .addImport(getClass().getResource("metadata-conflicts.json")) - .addImport(getClass().getResource("metadata-conflicts-2.json")) - .assemble(); + .addImport(getClass().getResource("metadata-conflicts.json")) + .addImport(getClass().getResource("metadata-conflicts-2.json")) + .assemble(); assertThat(result.getValidationEvents(), hasSize(1)); assertThat( - result.getValidationEvents().get(0).getMessage(), - containsString("Metadata conflict for key `foo`") + result.getValidationEvents().get(0).getMessage(), + containsString("Metadata conflict for key `foo`") ); } @Test public void metadataIsNotAffectedByTheSourceName() { Model model1 = new ModelAssembler() - .addUnparsedModel("a1.smithy", "metadata items = [1]") - .addUnparsedModel("a2.smithy", "metadata items = [2]") - .addUnparsedModel("a3.smithy", "metadata items = [3]") - .assemble() - .unwrap(); + .addUnparsedModel("a1.smithy", "metadata items = [1]") + .addUnparsedModel("a2.smithy", "metadata items = [2]") + .addUnparsedModel("a3.smithy", "metadata items = [3]") + .assemble() + .unwrap(); Model model2 = new ModelAssembler() - .addUnparsedModel("b1.smithy", "metadata items = [1]") - .addUnparsedModel("b2.smithy", "metadata items = [2]") - .addUnparsedModel("b3.smithy", "metadata items = [3]") - .assemble() - .unwrap(); + .addUnparsedModel("b1.smithy", "metadata items = [1]") + .addUnparsedModel("b2.smithy", "metadata items = [2]") + .addUnparsedModel("b3.smithy", "metadata items = [3]") + .assemble() + .unwrap(); List metadata1 = model1.getMetadata() - .get("items") - .expectArrayNode() - .getElements() - .stream() - .map(s -> s.expectNumberNode().getValue()) - .collect(Collectors.toList()); + .get("items") + .expectArrayNode() + .getElements() + .stream() + .map(s -> s.expectNumberNode().getValue()) + .collect(Collectors.toList()); List metadata2 = model2.getMetadata() - .get("items") - .expectArrayNode() - .getElements() - .stream() - .map(s -> s.expectNumberNode().getValue()) - .collect(Collectors.toList()); + .get("items") + .expectArrayNode() + .getElements() + .stream() + .map(s -> s.expectNumberNode().getValue()) + .collect(Collectors.toList()); assertThat(metadata1, is(metadata2)); } @Test public void mergesMultipleModels() { Model model = new ModelAssembler() - .addImport(getClass().getResource("merges-1.json")) - .addImport(getClass().getResource("nested/merges-2.json")) - .addImport(getClass().getResource("nested/merges-3.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("merges-1.json")) + .addImport(getClass().getResource("nested/merges-2.json")) + .addImport(getClass().getResource("nested/merges-3.json")) + .assemble() + .unwrap(); assertImportPathsWereLoaded(model); } @@ -596,24 +596,24 @@ public void mergesMultipleModels() { @Test public void mergesDirectories() throws Exception { Model model = new ModelAssembler() - .addImport(getClass().getResource("merges-1.json")) - .addImport(Paths.get(getClass().getResource("nested").toURI())) - .assemble() - .unwrap(); + .addImport(getClass().getResource("merges-1.json")) + .addImport(Paths.get(getClass().getResource("nested").toURI())) + .assemble() + .unwrap(); assertImportPathsWereLoaded(model); } private void assertImportPathsWereLoaded(Model model) { assertTrue( - model.getShape(ShapeId.from("example.namespace#String")) - .flatMap(shape -> shape.getTrait(DocumentationTrait.class)) - .isPresent() + model.getShape(ShapeId.from("example.namespace#String")) + .flatMap(shape -> shape.getTrait(DocumentationTrait.class)) + .isPresent() ); assertTrue( - model.getShape(ShapeId.from("example.namespace#String")) - .flatMap(shape -> shape.getTrait(MediaTypeTrait.class)) - .isPresent() + model.getShape(ShapeId.from("example.namespace#String")) + .flatMap(shape -> shape.getTrait(MediaTypeTrait.class)) + .isPresent() ); } @@ -621,21 +621,21 @@ private void assertImportPathsWereLoaded(Model model) { public void canAddEntireModelsToAssembler() { Model model = new ModelAssembler().addImport(getClass().getResource("main.json")).assemble().unwrap(); Model model2 = Model.assembler() - .addModel(model) - .addUnparsedModel( - "N/A", - "{\"smithy\": \"" + Model.MODEL_VERSION - + "\", \"shapes\": {\"example.namespace#String\": {\"type\": \"apply\", \"traits\": {\"smithy.api#documentation\": \"hi\"}}}}" - ) - .assemble() - .unwrap(); + .addModel(model) + .addUnparsedModel( + "N/A", + "{\"smithy\": \"" + Model.MODEL_VERSION + + "\", \"shapes\": {\"example.namespace#String\": {\"type\": \"apply\", \"traits\": {\"smithy.api#documentation\": \"hi\"}}}}" + ) + .assemble() + .unwrap(); assertEquals( - "hi", - model2.expectShape(ShapeId.from("example.namespace#String")) - .getTrait(DocumentationTrait.class) - .get() - .getValue() + "hi", + model2.expectShape(ShapeId.from("example.namespace#String")) + .getTrait(DocumentationTrait.class) + .get() + .getValue() ); } @@ -663,10 +663,10 @@ public Optional createValidator(String name, ObjectNode configuration }; new ModelAssembler() - .addImport(getClass().getResource("loads-validators.smithy")) - .validatorFactory(factory) - .assemble() - .unwrap(); + .addImport(getClass().getResource("loads-validators.smithy")) + .validatorFactory(factory) + .assemble() + .unwrap(); assertThat(loaded, hasKey("MyValidator")); assertThat(loaded.get("MyValidator"), equalTo(Node.parse("{\"foo\":\"baz\"}"))); @@ -689,10 +689,10 @@ public Optional createValidator(String name, ObjectNode configuration }; List collectedEvents = Collections.synchronizedList(new ArrayList<>()); ValidatedResult result = new ModelAssembler() - .addImport(getClass().getResource("core-events.smithy")) - .validatorFactory(factory) - .validationEventListener(collectedEvents::add) - .assemble(); + .addImport(getClass().getResource("core-events.smithy")) + .validatorFactory(factory) + .validationEventListener(collectedEvents::add) + .assemble(); for (ValidationEvent event : result.getValidationEvents()) { assertEquals(event.getSeverity(), Severity.SUPPRESSED); } @@ -704,13 +704,13 @@ public Optional createValidator(String name, ObjectNode configuration @Test public void canIgnoreUnknownTraits() { String document = "{\"smithy\": \"" + Model.MODEL_VERSION + "\", " - + "\"shapes\": { " - + "\"ns.foo#String\": {" - + "\"type\": \"string\", \"traits\": {\"com.foo#invalidTrait\": true}}}}"; + + "\"shapes\": { " + + "\"ns.foo#String\": {" + + "\"type\": \"string\", \"traits\": {\"com.foo#invalidTrait\": true}}}}"; ValidatedResult result = new ModelAssembler() - .addUnparsedModel(SourceLocation.NONE.getFilename(), document) - .putProperty(ModelAssembler.ALLOW_UNKNOWN_TRAITS, true) - .assemble(); + .addUnparsedModel(SourceLocation.NONE.getFilename(), document) + .putProperty(ModelAssembler.ALLOW_UNKNOWN_TRAITS, true) + .assemble(); assertThat(result.getValidationEvents(), not(empty())); assertFalse(result.isBroken()); @@ -719,16 +719,16 @@ public void canIgnoreUnknownTraits() { @Test public void canLoadModelsFromJar() { Model model = Model.assembler() - .addImport(getClass().getResource("jar-import.jar")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("jar-import.jar")) + .assemble() + .unwrap(); for (String id : ListUtils.of("foo.baz#A", "foo.baz#B", "foo.baz#C")) { ShapeId shapeId = ShapeId.from(id); assertTrue(model.getShape(shapeId).isPresent()); assertThat( - model.getShape(shapeId).get().getSourceLocation().getFilename(), - startsWith("jar:file:") + model.getShape(shapeId).get().getSourceLocation().getFilename(), + startsWith("jar:file:") ); } } @@ -741,10 +741,10 @@ public void canLoadTraitFromJarMultipleTimes() { Supplier modelSupplier = () -> { URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{jar}); return Model.assembler(urlClassLoader) - .discoverModels(urlClassLoader) - .addImport(file) - .assemble() - .unwrap(); + .discoverModels(urlClassLoader) + .addImport(file) + .assemble() + .unwrap(); }; Model model = modelSupplier.get(); @@ -757,12 +757,12 @@ public void canLoadTraitFromJarMultipleTimes() { @Test public void canDisableValidation() { String document = "namespace foo.baz\n" - + "@idempotent\n" // < this is invalid - + "string MyString\n"; + + "@idempotent\n" // < this is invalid + + "string MyString\n"; ValidatedResult result = new ModelAssembler() - .addUnparsedModel("foo.smithy", document) - .disableValidation() - .assemble(); + .addUnparsedModel("foo.smithy", document) + .disableValidation() + .assemble(); assertFalse(result.isBroken()); } @@ -770,12 +770,12 @@ public void canDisableValidation() { @Test public void canHandleBadSuppressions() { String document = "namespace foo.baz\n" - + "@idempotent\n" // < this is invalid - + "string MyString\n"; + + "@idempotent\n" // < this is invalid + + "string MyString\n"; ValidatedResult result = new ModelAssembler() - .addUnparsedModel("foo.smithy", document) - .putMetadata("suppressions", Node.parse("[{}]")) - .assemble(); + .addUnparsedModel("foo.smithy", document) + .putMetadata("suppressions", Node.parse("[{}]")) + .assemble(); assertTrue(result.isBroken()); } @@ -786,19 +786,19 @@ public void detectsDuplicateTraitsWithDifferentTypes() { // regression test to ensure that trait specific stuff like coercion // is handled correctly. String document1 = "namespace foo.baz\n" - + "@trait\n" - + "structure myTrait {}\n"; + + "@trait\n" + + "structure myTrait {}\n"; String document2 = "namespace foo.baz\n" - + "@trait\n" - + "integer myTrait\n"; + + "@trait\n" + + "integer myTrait\n"; String document3 = "namespace foo.baz\n" - + "@myTrait(10)\n" - + "string MyShape\n"; + + "@myTrait(10)\n" + + "string MyShape\n"; ValidatedResult result = new ModelAssembler() - .addUnparsedModel("1.smithy", document1) - .addUnparsedModel("2.smithy", document2) - .addUnparsedModel("3.smithy", document3) - .assemble(); + .addUnparsedModel("1.smithy", document1) + .addUnparsedModel("2.smithy", document2) + .addUnparsedModel("3.smithy", document3) + .assemble(); assertTrue(result.isBroken()); } @@ -808,19 +808,19 @@ public void allowsConflictingShapesThatAreEqual() { // While these two shapes have different traits, the traits merge. // Since they are equivalent the conflicts are allowed. String document1 = "namespace foo.baz\n" - + "@deprecated\n" - + "structure Foo {\n" - + " foo: String," - + "}\n"; + + "@deprecated\n" + + "structure Foo {\n" + + " foo: String," + + "}\n"; String document2 = "namespace foo.baz\n" - + "structure Foo {\n" - + " @internal\n" - + " foo: String,\n" - + "}\n"; + + "structure Foo {\n" + + " @internal\n" + + " foo: String,\n" + + "}\n"; ValidatedResult result = new ModelAssembler() - .addUnparsedModel("1.smithy", document1) - .addUnparsedModel("2.smithy", document2) - .assemble(); + .addUnparsedModel("1.smithy", document1) + .addUnparsedModel("2.smithy", document2) + .assemble(); assertFalse(result.isBroken()); @@ -835,15 +835,15 @@ public void allowsConflictingShapesThatAreEqual() { public void detectsConflictingDuplicateAggregates() { // Aggregate shapes have to have the same exact members. String document1 = "namespace foo.baz\n" - + "structure Foo {\n" - + " foo: String," - + "}\n"; + + "structure Foo {\n" + + " foo: String," + + "}\n"; String document2 = "namespace foo.baz\n" - + "structure Foo {}\n"; + + "structure Foo {}\n"; ValidatedResult result = new ModelAssembler() - .addUnparsedModel("1.smithy", document1) - .addUnparsedModel("2.smithy", document2) - .assemble(); + .addUnparsedModel("1.smithy", document1) + .addUnparsedModel("2.smithy", document2) + .assemble(); assertTrue(result.isBroken()); } @@ -852,9 +852,9 @@ public void detectsConflictingDuplicateAggregates() { public void allowsDuplicateEquivalentMetadata() { String document = "metadata foo = 10\n"; ValidatedResult result = new ModelAssembler() - .addUnparsedModel("1.smithy", document) - .addUnparsedModel("2.smithy", document) - .assemble(); + .addUnparsedModel("1.smithy", document) + .addUnparsedModel("2.smithy", document) + .assemble(); assertFalse(result.isBroken()); assertThat(result.unwrap().getMetadata().get("foo"), equalTo(Node.from(10))); @@ -864,9 +864,9 @@ public void allowsDuplicateEquivalentMetadata() { public void mergesConflictingMetadataArrays() { String document = "metadata foo = [\"a\"]\n"; ValidatedResult result = new ModelAssembler() - .addUnparsedModel("1.smithy", document) - .addUnparsedModel("2.smithy", document) - .assemble(); + .addUnparsedModel("1.smithy", document) + .addUnparsedModel("2.smithy", document) + .assemble(); assertFalse(result.isBroken()); assertThat(result.unwrap().getMetadata().get("foo"), equalTo(Node.fromStrings("a", "a"))); @@ -877,19 +877,19 @@ public void createsDynamicTraitWhenTraitFactoryReturnsEmpty() { ShapeId id = ShapeId.from("ns.foo#Test"); ShapeId traitId = ShapeId.from("smithy.foo#baz"); String document = "{\n" - + "\"smithy\": \"" + Model.MODEL_VERSION + "\",\n" - + " \"shapes\": {\n" - + " \"" + id + "\": {\n" - + " \"type\": \"string\",\n" - + " \"traits\": {\"" + traitId + "\": true}\n" - + " }\n" - + " }\n" - + "}"; + + "\"smithy\": \"" + Model.MODEL_VERSION + "\",\n" + + " \"shapes\": {\n" + + " \"" + id + "\": {\n" + + " \"type\": \"string\",\n" + + " \"traits\": {\"" + traitId + "\": true}\n" + + " }\n" + + " }\n" + + "}"; Model model = new ModelAssembler() - .addUnparsedModel(SourceLocation.NONE.getFilename(), document) - .putProperty(ModelAssembler.ALLOW_UNKNOWN_TRAITS, true) - .assemble() - .unwrap(); + .addUnparsedModel(SourceLocation.NONE.getFilename(), document) + .putProperty(ModelAssembler.ALLOW_UNKNOWN_TRAITS, true) + .assemble() + .unwrap(); assertTrue(model.expectShape(id).findTrait(traitId).isPresent()); assertThat(model.expectShape(id).findTrait(traitId).get(), instanceOf(DynamicTrait.class)); @@ -898,14 +898,14 @@ public void createsDynamicTraitWhenTraitFactoryReturnsEmpty() { @Test public void dedupesExactSameTraitsAndMetadataFromSameLocation() { Model model = Model.assembler() - .addImport(getClass().getResource("dedupe-models.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("dedupe-models.smithy")) + .assemble() + .unwrap(); Model model2 = Model.assembler() - .addModel(model) - .addImport(getClass().getResource("dedupe-models.smithy")) - .assemble() - .unwrap(); + .addModel(model) + .addImport(getClass().getResource("dedupe-models.smithy")) + .assemble() + .unwrap(); assertThat(model, equalTo(model2)); } @@ -919,10 +919,10 @@ public void canListenToEvents() { List collectedEvents = Collections.synchronizedList(new ArrayList<>()); Model.assembler() - .addValidator(model -> toEmit) - .validationEventListener(collectedEvents::add) - .assemble() - .unwrap(); + .addValidator(model -> toEmit) + .validationEventListener(collectedEvents::add) + .assemble() + .unwrap(); assertThat(collectedEvents, equalTo(toEmit)); } @@ -939,17 +939,17 @@ public void canListenToEvents() { public void transientTraitsAreNotValidated() { ShapeId originalId = ShapeId.from("com.foo.nested#Str"); StringShape stringShape = StringShape.builder() - .id("com.foo#Str") - .addTrait(new OriginalShapeIdTrait(originalId)) - .build(); + .id("com.foo#Str") + .addTrait(new OriginalShapeIdTrait(originalId)) + .build(); Model model = Model.assembler() - .addShape(stringShape) - .assemble() - .unwrap(); + .addShape(stringShape) + .assemble() + .unwrap(); assertThat( - model.expectShape(stringShape.getId()).expectTrait(OriginalShapeIdTrait.class).getOriginalId(), - equalTo(originalId) + model.expectShape(stringShape.getId()).expectTrait(OriginalShapeIdTrait.class).getOriginalId(), + equalTo(originalId) ); } @@ -960,15 +960,15 @@ public void transientTraitsAreNotValidated() { @Test public void doesNotReParsesSyntheticTraits() { Model model = Model.assembler() - .addImport(getClass().getResource("does-not-reparses-synthetic-traits.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("does-not-reparses-synthetic-traits.smithy")) + .assemble() + .unwrap(); Model.assembler() - .addModel(model) - .addUnparsedModel("foo.smithy", "namespace smithy.example\napply Foo @sensitive\n") - .assemble() - .unwrap(); + .addModel(model) + .addUnparsedModel("foo.smithy", "namespace smithy.example\napply Foo @sensitive\n") + .assemble() + .unwrap(); } @Test @@ -996,9 +996,9 @@ public void reset() { public void loadsMixinMembersInCorrectOrderAndWithTraits() { Model model = Model.assembler() - .addImport(getClass().getResource("mixins/mixins-can-override-traits.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("mixins/mixins-can-override-traits.smithy")) + .assemble() + .unwrap(); StructureShape f = model.expectShape(ShapeId.from("smithy.example#F"), StructureShape.class); @@ -1011,10 +1011,10 @@ public void loadsMixinMembersInCorrectOrderAndWithTraits() { @Test public void ignoresAcceptableMixinConflicts() { Model model = Model.assembler() - .addImport(getClass().getResource("mixins/mixin-conflict-acceptable-1.smithy")) - .addImport(getClass().getResource("mixins/mixin-conflict-acceptable-2.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("mixins/mixin-conflict-acceptable-1.smithy")) + .addImport(getClass().getResource("mixins/mixin-conflict-acceptable-2.smithy")) + .assemble() + .unwrap(); StructureShape a = model.expectShape(ShapeId.from("smithy.example#A"), StructureShape.class); @@ -1025,10 +1025,10 @@ public void ignoresAcceptableMixinConflicts() { public void failsWhenMixinsConflictAndAreNotEquivalent() { ValidatedResultException e = Assertions.assertThrows(ValidatedResultException.class, () -> { Model.assembler() - .addImport(getClass().getResource("mixins/mixin-conflict-acceptable-1.smithy")) - .addImport(getClass().getResource("mixins/mixin-conflict-error.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("mixins/mixin-conflict-acceptable-1.smithy")) + .addImport(getClass().getResource("mixins/mixin-conflict-error.smithy")) + .assemble() + .unwrap(); }); assertThat(e.getMessage(), containsString("Conflicting shape definition for `smithy.example#A`")); @@ -1037,13 +1037,13 @@ public void failsWhenMixinsConflictAndAreNotEquivalent() { @Test public void canLoadSetsUsingBuiltModel() { SetShape set = SetShape.builder() - .id("smithy.example#Set") - .member(ShapeId.from("smithy.api#String")) - .build(); + .id("smithy.example#Set") + .member(ShapeId.from("smithy.api#String")) + .build(); Model model = Model.assembler() - .addShape(set) - .assemble() - .unwrap(); + .addShape(set) + .assemble() + .unwrap(); Model.assembler().addModel(model).assemble().unwrap(); } @@ -1051,17 +1051,17 @@ public void canLoadSetsUsingBuiltModel() { @Test public void canIgnoreTraitConflictsWithBuiltShapes() { StringShape string1 = StringShape.builder() - .id("smithy.example#String1") - .addTrait(new DocumentationTrait("hi")) - .build(); + .id("smithy.example#String1") + .addTrait(new DocumentationTrait("hi")) + .build(); ModelAssembler assembler = Model.assembler(); assembler.addShape(string1); assembler.addUnparsedModel( - "foo.smithy", - "$version: \"2.0\"\n" - + "namespace smithy.example\n\n" - + "@documentation(\"hi\")\n" - + "string String1\n" + "foo.smithy", + "$version: \"2.0\"\n" + + "namespace smithy.example\n\n" + + "@documentation(\"hi\")\n" + + "string String1\n" ); Model result = assembler.assemble().unwrap(); @@ -1071,17 +1071,17 @@ public void canIgnoreTraitConflictsWithBuiltShapes() { @Test public void canMergeTraitConflictsWithBuiltShapes() { StringShape string1 = StringShape.builder() - .id("smithy.example#String1") - .addTrait(TagsTrait.builder().addValue("a").build()) - .build(); + .id("smithy.example#String1") + .addTrait(TagsTrait.builder().addValue("a").build()) + .build(); ModelAssembler assembler = Model.assembler(); assembler.addShape(string1); assembler.addUnparsedModel( - "foo.smithy", - "$version: \"2.0\"\n" - + "namespace smithy.example\n\n" - + "@tags([\"b\"])\n" - + "string String1\n" + "foo.smithy", + "$version: \"2.0\"\n" + + "namespace smithy.example\n\n" + + "@tags([\"b\"])\n" + + "string String1\n" ); Model result = assembler.assemble().unwrap(); @@ -1091,16 +1091,16 @@ public void canMergeTraitConflictsWithBuiltShapes() { @Test public void providesDiffWhenConflictsAreFound() { String a = "$version: \"2\"\n" - + "namespace foo.baz\n" - + "integer Foo\n"; + + "namespace foo.baz\n" + + "integer Foo\n"; String b = "$version: \"2\"\n" - + "namespace foo.baz\n" - + "@default(0)\n" - + "long Foo\n"; + + "namespace foo.baz\n" + + "@default(0)\n" + + "long Foo\n"; ValidatedResult result = new ModelAssembler() - .addUnparsedModel("1.smithy", a) - .addUnparsedModel("2.smithy", b) - .assemble(); + .addUnparsedModel("1.smithy", a) + .addUnparsedModel("2.smithy", b) + .assemble(); assertTrue(result.isBroken()); assertThat(result.getValidationEvents().get(0).getMessage(), containsString("Left is long, right is integer")); @@ -1109,14 +1109,14 @@ public void providesDiffWhenConflictsAreFound() { @Test public void canRoundTripShapesWithMixinsThroughAssembler() { StructureShape mixin = StructureShape.builder() - .id("smithy.example#Mixin") - .addTrait(MixinTrait.builder().build()) - .build(); + .id("smithy.example#Mixin") + .addTrait(MixinTrait.builder().build()) + .build(); StructureShape struct = StructureShape.builder() - .id("smithy.example#Foo") - .addMixin(mixin) - .addMember("foo", ShapeId.from("smithy.api#String")) - .build(); + .id("smithy.example#Foo") + .addMixin(mixin) + .addMember("foo", ShapeId.from("smithy.api#String")) + .build(); Model model = Model.assembler().addShapes(mixin, struct).assemble().unwrap(); assertThat(model.expectShape(struct.getId()), equalTo(struct)); @@ -1126,19 +1126,19 @@ public void canRoundTripShapesWithMixinsThroughAssembler() { @Test public void mixinShapesNoticeDependencyChanges() { StructureShape mixin = StructureShape.builder() - .id("smithy.example#Mixin") - .addTrait(MixinTrait.builder().build()) - .build(); + .id("smithy.example#Mixin") + .addTrait(MixinTrait.builder().build()) + .build(); StructureShape struct = StructureShape.builder() - .id("smithy.example#Foo") - .addMixin(mixin) - .addMember("foo", ShapeId.from("smithy.api#String")) - .build(); + .id("smithy.example#Foo") + .addMixin(mixin) + .addMember("foo", ShapeId.from("smithy.api#String")) + .build(); Model model = Model.assembler() - .addShapes(mixin, struct) - .addTrait(mixin.getId(), new SensitiveTrait()) - .assemble() - .unwrap(); + .addShapes(mixin, struct) + .addTrait(mixin.getId(), new SensitiveTrait()) + .assemble() + .unwrap(); assertThat(model.expectShape(mixin.getId()).getAllTraits(), hasKey(SensitiveTrait.ID)); assertThat(model.expectShape(mixin.getId()).getIntroducedTraits(), hasKey(SensitiveTrait.ID)); @@ -1149,21 +1149,21 @@ public void mixinShapesNoticeDependencyChanges() { @Test public void nodeModelsDoNotInterfereWithManuallyAddedModels() { StructureShape struct = StructureShape.builder() - .id("smithy.example#Foo") - .addMember("foo", ShapeId.from("smithy.api#Integer")) - .build(); + .id("smithy.example#Foo") + .addMember("foo", ShapeId.from("smithy.api#Integer")) + .build(); // Create an object node with a source location of none. ObjectNode node = Node.objectNodeBuilder() - .withMember(new StringNode("smithy", SourceLocation.NONE), new StringNode("1.0", SourceLocation.NONE)) - .build(); + .withMember(new StringNode("smithy", SourceLocation.NONE), new StringNode("1.0", SourceLocation.NONE)) + .build(); Model model = Model.assembler() - .addShape(struct) - // Add a Node with a 1.0 version and a SourceLocation.none() value. - // This source location is the same as the manually given shape, but it should not - // cause the manually given shape to also think it's a 1.0 shape. - .addDocumentNode(node) - .assemble() - .unwrap(); + .addShape(struct) + // Add a Node with a 1.0 version and a SourceLocation.none() value. + // This source location is the same as the manually given shape, but it should not + // cause the manually given shape to also think it's a 1.0 shape. + .addDocumentNode(node) + .assemble() + .unwrap(); // Ensure that the upgrade process did not add a Box trait to the manually created shape // because it is not assumed to be a 1.0 shape. @@ -1176,14 +1176,14 @@ public void nodeModelsDoNotInterfereWithManuallyAddedModels() { @Test public void canResolveTargetsWithoutPrelude() { ValidatedResult model = Model.assembler() - .disablePrelude() - .addUnparsedModel( - "foo.smithy", - "$version: \"2.0\"\n" - + "namespace smithy.example\n" - + "list Foo { member: String }\n" - ) - .assemble(); + .disablePrelude() + .addUnparsedModel( + "foo.smithy", + "$version: \"2.0\"\n" + + "namespace smithy.example\n" + + "list Foo { member: String }\n" + ) + .assemble(); assertThat(model.getValidationEvents(), hasSize(1)); assertThat(model.getValidationEvents().get(0).getMessage(), containsString("unresolved shape")); @@ -1205,21 +1205,21 @@ public void findsBoxTraitOnPreludeShapes() { @Test public void forwardReferencesAreOrdered() { Model model = Model.assembler() - .addImport(getClass().getResource("forward-references-are-ordered.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("forward-references-are-ordered.smithy")) + .assemble() + .unwrap(); ShapeId service = ShapeId.from("smithy.example#Example"); assertThat( - model.expectShape(service, ServiceShape.class).getErrors(), - contains( - ShapeId.from("smithy.example#Error1"), - ShapeId.from("smithy.example#Error2"), - ShapeId.from("smithy.example#Error3"), - ShapeId.from("smithy.example#Error4"), - ShapeId.from("smithy.example#Error5"), - ShapeId.from("smithy.example#Error6") - ) + model.expectShape(service, ServiceShape.class).getErrors(), + contains( + ShapeId.from("smithy.example#Error1"), + ShapeId.from("smithy.example#Error2"), + ShapeId.from("smithy.example#Error3"), + ShapeId.from("smithy.example#Error4"), + ShapeId.from("smithy.example#Error5"), + ShapeId.from("smithy.example#Error6") + ) ); } @@ -1227,39 +1227,39 @@ public void forwardReferencesAreOrdered() { public void upgrades1_0_documentNodesToo() { // Loads fine through import. Model model1 = Model.assembler() - .addImport(getClass().getResource("needs-upgrade-document-node.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("needs-upgrade-document-node.json")) + .assemble() + .unwrap(); assertionChecksFor_upgradesAndDowngrades(model1); // And through unparsed. String contents = IoUtils.readUtf8Resource(getClass(), "needs-upgrade-document-node.json"); Model model2 = Model.assembler() - .addUnparsedModel("foo.json", contents) - .assemble() - .unwrap(); + .addUnparsedModel("foo.json", contents) + .assemble() + .unwrap(); assertionChecksFor_upgradesAndDowngrades(model2); // And through document node. Node node = Node.parse(contents); Model model3 = Model.assembler() - .addDocumentNode(node) - .assemble() - .unwrap(); + .addDocumentNode(node) + .assemble() + .unwrap(); assertionChecksFor_upgradesAndDowngrades(model3); // Pathological case. Model model4 = Model.assembler() - .addModel(model1) - .addModel(model2) - .addModel(model3) - .addDocumentNode(node) - .addUnparsedModel("foo.json", contents) - .assemble() - .unwrap(); + .addModel(model1) + .addModel(model2) + .addModel(model3) + .addDocumentNode(node) + .addUnparsedModel("foo.json", contents) + .assemble() + .unwrap(); assertionChecksFor_upgradesAndDowngrades(model4); @@ -1287,39 +1287,39 @@ private void assertionChecksFor_upgradesAndDowngrades(Model model) { public void patches2_0_documentNodesToo() { // Loads fine through import. Model model1 = Model.assembler() - .addImport(getClass().getResource("needs-downgrade-document-node.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("needs-downgrade-document-node.json")) + .assemble() + .unwrap(); assertionChecksFor_upgradesAndDowngrades(model1); // And through unparsed. String contents = IoUtils.readUtf8Resource(getClass(), "needs-downgrade-document-node.json"); Model model2 = Model.assembler() - .addUnparsedModel("foo.json", contents) - .assemble() - .unwrap(); + .addUnparsedModel("foo.json", contents) + .assemble() + .unwrap(); assertionChecksFor_upgradesAndDowngrades(model2); // And through document node. Node node = Node.parse(contents); Model model3 = Model.assembler() - .addDocumentNode(node) - .assemble() - .unwrap(); + .addDocumentNode(node) + .assemble() + .unwrap(); assertionChecksFor_upgradesAndDowngrades(model3); // Pathological case. Model model4 = Model.assembler() - .addModel(model1) - .addModel(model2) - .addModel(model3) - .addDocumentNode(node) - .addUnparsedModel("foo.json", contents) - .assemble() - .unwrap(); + .addModel(model1) + .addModel(model2) + .addModel(model3) + .addDocumentNode(node) + .addUnparsedModel("foo.json", contents) + .assemble() + .unwrap(); assertionChecksFor_upgradesAndDowngrades(model4); @@ -1331,22 +1331,22 @@ public void patches2_0_documentNodesToo() { @Test public void syntheticBoxingResultsInSameModelBetween1and2() { Model model1 = Model.assembler() - .addImport(getClass().getResource("synthetic-boxing-1.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("synthetic-boxing-1.smithy")) + .assemble() + .unwrap(); Model model2 = Model.assembler() - .addImport(getClass().getResource("synthetic-boxing-2.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("synthetic-boxing-2.smithy")) + .assemble() + .unwrap(); Model model3 = Model.assembler() - .addImport(getClass().getResource("synthetic-boxing-1.smithy")) - .addImport(getClass().getResource("synthetic-boxing-2.smithy")) - .addModel(model1) - .addModel(model2) - .assemble() - .unwrap(); + .addImport(getClass().getResource("synthetic-boxing-1.smithy")) + .addImport(getClass().getResource("synthetic-boxing-2.smithy")) + .addModel(model1) + .addModel(model2) + .assemble() + .unwrap(); assertThat(model1, equalTo(model2)); assertThat(model1, equalTo(model3)); @@ -1355,9 +1355,9 @@ public void syntheticBoxingResultsInSameModelBetween1and2() { @Test public void appliesBoxTraitsToMixinsToo() { Model model1 = Model.assembler() - .addImport(getClass().getResource("synthetic-boxing-mixins.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("synthetic-boxing-mixins.smithy")) + .assemble() + .unwrap(); // MixedInteger and MixinInteger have synthetic box traits. assertThat(model1.expectShape(ShapeId.from("smithy.example#MixinInteger")).hasTrait(BoxTrait.class), is(true)); @@ -1365,12 +1365,12 @@ public void appliesBoxTraitsToMixinsToo() { // MixinStruct$bar and MixedStruct$bar have synthetic box traits. StructureShape mixinStruct = model1.expectShape( - ShapeId.from("smithy.example#MixinStruct"), - StructureShape.class + ShapeId.from("smithy.example#MixinStruct"), + StructureShape.class ); StructureShape mixedStruct = model1.expectShape( - ShapeId.from("smithy.example#MixedStruct"), - StructureShape.class + ShapeId.from("smithy.example#MixedStruct"), + StructureShape.class ); assertThat(mixinStruct.getAllMembers().get("bar").hasTrait(BoxTrait.class), is(true)); assertThat(mixinStruct.getAllMembers().get("bar").hasTrait(DefaultTrait.class), is(true)); @@ -1387,8 +1387,8 @@ public void appliesBoxTraitsToMixinsToo() { @Test public void versionTransformsAreAlwaysApplied() { ValidatedResult result = Model.assembler() - .addImport(getClass().getResource("invalid-1.0-model-upgraded.smithy")) - .assemble(); + .addImport(getClass().getResource("invalid-1.0-model-upgraded.smithy")) + .assemble(); // Ensure that the invalid trait caused the model to have errors. assertThat(result.getValidationEvents(Severity.ERROR), not(empty())); @@ -1415,8 +1415,8 @@ public void versionTransformsAreAlwaysApplied() { @Test public void ignoresUnrecognizedFileExtensions() throws URISyntaxException { ValidatedResult result = Model.assembler() - .addImport(Paths.get(getClass().getResource("assembler-ignore-unrecognized-files").toURI())) - .assemble(); + .addImport(Paths.get(getClass().getResource("assembler-ignore-unrecognized-files").toURI())) + .assemble(); assertThat(result.getValidationEvents(Severity.DANGER), empty()); assertThat(result.getValidationEvents(Severity.ERROR), empty()); @@ -1427,8 +1427,8 @@ public void ignoresUnrecognizedFileExtensions() throws URISyntaxException { @Test public void ignoresUnrecognizedJsonFiles() throws URISyntaxException { ValidatedResult result = Model.assembler() - .addImport(Paths.get(getClass().getResource("assembler-ignore-unrecognized-json").toURI())) - .assemble(); + .addImport(Paths.get(getClass().getResource("assembler-ignore-unrecognized-json").toURI())) + .assemble(); assertThat(result.getValidationEvents(Severity.DANGER), empty()); assertThat(result.getValidationEvents(Severity.ERROR), empty()); @@ -1450,8 +1450,8 @@ public void failsOnInvalidJarJsonFile() throws URISyntaxException, IOException { @Test public void doesNotThrowOnInvalidSuppression() { ObjectNode node = Node.objectNode() - .withMember("smithy", "1.0") - .withMember("metadata", Node.objectNode().withMember("suppressions", "hi!")); + .withMember("smithy", "1.0") + .withMember("metadata", Node.objectNode().withMember("suppressions", "hi!")); ValidatedResult result = new ModelAssembler().addDocumentNode(node).assemble(); @@ -1464,9 +1464,9 @@ public void modelLoadingErrorsAreEmittedToListener() { List events = new ArrayList<>(); ValidatedResult result = new ModelAssembler() - .addDocumentNode(node) - .validationEventListener(events::add) - .assemble(); + .addDocumentNode(node) + .validationEventListener(events::add) + .assemble(); assertThat(result.getValidationEvents(Severity.ERROR), hasSize(1)); assertThat(events, equalTo(result.getValidationEvents())); @@ -1475,81 +1475,81 @@ public void modelLoadingErrorsAreEmittedToListener() { @Test public void exceptionsThrownWhenCreatingTraitsDontCrashSmithy() { String document = "{\n" - + "\"smithy\": \"" + Model.MODEL_VERSION + "\",\n" - + " \"shapes\": {\n" - + " \"ns.foo#Test\": {\n" - + " \"type\": \"string\",\n" - + " \"traits\": {\"smithy.foo#baz\": true}\n" - + " }\n" - + " }\n" - + "}"; + + "\"smithy\": \"" + Model.MODEL_VERSION + "\",\n" + + " \"shapes\": {\n" + + " \"ns.foo#Test\": {\n" + + " \"type\": \"string\",\n" + + " \"traits\": {\"smithy.foo#baz\": true}\n" + + " }\n" + + " }\n" + + "}"; ValidatedResult result = new ModelAssembler() - .addUnparsedModel(SourceLocation.NONE.getFilename(), document) - .putProperty(ModelAssembler.ALLOW_UNKNOWN_TRAITS, true) - .traitFactory((traitId, target, value) -> { - throw new RuntimeException("Oops!"); - }) - .assemble(); + .addUnparsedModel(SourceLocation.NONE.getFilename(), document) + .putProperty(ModelAssembler.ALLOW_UNKNOWN_TRAITS, true) + .traitFactory((traitId, target, value) -> { + throw new RuntimeException("Oops!"); + }) + .assemble(); assertThat(result.getValidationEvents(Severity.ERROR), not(empty())); assertThat( - result.getValidationEvents(Severity.ERROR).get(0).getMessage(), - equalTo("Error creating trait `smithy.foo#baz`: Oops!") + result.getValidationEvents(Severity.ERROR).get(0).getMessage(), + equalTo("Error creating trait `smithy.foo#baz`: Oops!") ); } @Test public void resolvesDuplicateTraitApplicationsToDuplicateMixedInMembers() throws Exception { String model = IoUtils.readUtf8File( - Paths.get(getClass().getResource("mixins/apply-to-mixed-member.json").toURI()) + Paths.get(getClass().getResource("mixins/apply-to-mixed-member.json").toURI()) ); // Should be able to de-conflict the apply statements when the same model is loaded multiple times. // See https://github.com/smithy-lang/smithy/issues/2004 Model.assembler() - .addUnparsedModel("test.json", model) - .addUnparsedModel("test2.json", model) - .addUnparsedModel("test3.json", model) - .assemble() - .unwrap(); + .addUnparsedModel("test.json", model) + .addUnparsedModel("test2.json", model) + .addUnparsedModel("test3.json", model) + .assemble() + .unwrap(); } @Test public void resolvesDuplicateTraitApplicationsToSameMixedInMember() throws Exception { String modelToApplyTo = IoUtils.readUtf8File( - Paths.get(getClass().getResource("mixins/mixed-member.smithy").toURI()) + Paths.get(getClass().getResource("mixins/mixed-member.smithy").toURI()) ); String modelWithApply = IoUtils.readUtf8File( - Paths.get(getClass().getResource("mixins/member-apply-other-namespace.smithy").toURI()) + Paths.get(getClass().getResource("mixins/member-apply-other-namespace.smithy").toURI()) ); // Should be able to load when you have multiple identical apply statements to the same mixed in member. // See https://github.com/smithy-lang/smithy/issues/2004 Model.assembler() - .addUnparsedModel("mixed-member.smithy", modelToApplyTo) - .addUnparsedModel("member-apply-1.smithy", modelWithApply) - .addUnparsedModel("member-apply-2.smithy", modelWithApply) - .assemble() - .unwrap(); + .addUnparsedModel("mixed-member.smithy", modelToApplyTo) + .addUnparsedModel("member-apply-1.smithy", modelWithApply) + .addUnparsedModel("member-apply-2.smithy", modelWithApply) + .assemble() + .unwrap(); } @Test public void handlesMultipleInheritanceForMixinMembers() { Model model = Model.assembler() - .addImport(getClass().getResource("mixins/multiple-inheritance-with-introduction.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("mixins/multiple-inheritance-with-introduction.smithy")) + .assemble() + .unwrap(); MemberShape shape = model.expectShape(ShapeId.from("com.example#FinalStructure$member"), MemberShape.class); assertThat( - shape.getMixins(), - contains( - ShapeId.from("com.example#MixinA$member"), - ShapeId.from("com.example#MixinB$member") - ) + shape.getMixins(), + contains( + ShapeId.from("com.example#MixinA$member"), + ShapeId.from("com.example#MixinB$member") + ) ); assertThat( - shape.getAllTraits().keySet(), - containsInAnyOrder(PatternTrait.ID, RequiredTrait.ID, InternalTrait.ID) + shape.getAllTraits().keySet(), + containsInAnyOrder(PatternTrait.ID, RequiredTrait.ID, InternalTrait.ID) ); String actualPattern = shape.expectTrait(PatternTrait.class).getValue(); assertThat(actualPattern, equalTo("baz")); @@ -1558,30 +1558,30 @@ public void handlesMultipleInheritanceForMixinMembers() { @Test public void loadsShapesWhenThereAreUnresolvedMixins() { String modelText = "$version: \"2\"\n" - + "namespace com.foo\n" - + "\n" - + "string Foo\n" - + "@mixin\n" - + "structure Bar {}\n" - + "structure Baz with [Unknown] {}\n"; + + "namespace com.foo\n" + + "\n" + + "string Foo\n" + + "@mixin\n" + + "structure Bar {}\n" + + "structure Baz with [Unknown] {}\n"; ValidatedResult result = Model.assembler() - .addUnparsedModel("foo.smithy", modelText) - .assemble(); + .addUnparsedModel("foo.smithy", modelText) + .assemble(); assertThat(result.isBroken(), is(true)); assertThat(result.getResult().isPresent(), is(true)); Set fooShapes = result.getResult() - .get() - .getShapeIds() - .stream() - .filter(id -> id.getNamespace().equals("com.foo")) - .collect(Collectors.toSet()); + .get() + .getShapeIds() + .stream() + .filter(id -> id.getNamespace().equals("com.foo")) + .collect(Collectors.toSet()); assertThat( - fooShapes, - containsInAnyOrder( - ShapeId.from("com.foo#Foo"), - ShapeId.from("com.foo#Bar") - ) + fooShapes, + containsInAnyOrder( + ShapeId.from("com.foo#Foo"), + ShapeId.from("com.foo#Bar") + ) ); } @@ -1589,18 +1589,18 @@ public void loadsShapesWhenThereAreUnresolvedMixins() { public void handlesSameModelWhenBuiltAndImported() throws Exception { Path modelUri = Paths.get(getClass().getResource("mixin-and-apply-model.smithy").toURI()); Model sourceModel = Model.assembler() - .addImport(modelUri) - .assemble() - .unwrap(); + .addImport(modelUri) + .assemble() + .unwrap(); Model combinedModel = Model.assembler() - .addModel(sourceModel) - .addImport(modelUri) - .assemble() - .unwrap(); + .addModel(sourceModel) + .addImport(modelUri) + .assemble() + .unwrap(); assertTrue( - combinedModel.expectShape(ShapeId.from("smithy.example#MachineData$machineId"), MemberShape.class) - .hasTrait(RequiredTrait.ID) + combinedModel.expectShape(ShapeId.from("smithy.example#MachineData$machineId"), MemberShape.class) + .hasTrait(RequiredTrait.ID) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelDiscoveryTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelDiscoveryTest.java index a1176b1a44d..71a97f8075d 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelDiscoveryTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelDiscoveryTest.java @@ -26,13 +26,13 @@ public void discoversModelsInManifests() throws MalformedURLException { List models = ModelDiscovery.findModels(manifest); assertThat( - models, - contains( - new URL(prefix + "foo.smithy"), - new URL(prefix + "baz/bar/example.json"), - new URL(prefix + "test"), - new URL(prefix + "test2") - ) + models, + contains( + new URL(prefix + "foo.smithy"), + new URL(prefix + "baz/bar/example.json"), + new URL(prefix + "test"), + new URL(prefix + "test2") + ) ); } @@ -42,8 +42,8 @@ public void discoversModelsFromClasspath() { URLClassLoader classLoader = new URLClassLoader(urls); List models = ModelDiscovery.findModels(classLoader); List names = models.stream() - .map(ModelDiscovery::getSmithyModelPathFromJarUrl) - .collect(Collectors.toList()); + .map(ModelDiscovery::getSmithyModelPathFromJarUrl) + .collect(Collectors.toList()); assertThat(names, contains("a.smithy", "b/b.smithy", "b/c/c.json")); } @@ -63,13 +63,13 @@ public void skipsCommentLines() throws IOException { List models = ModelDiscovery.findModels(manifest); assertThat( - models, - contains( - new URL(prefix + "foo.smithy"), - new URL(prefix + "baz/bar/example.json"), - new URL(prefix + "test"), - new URL(prefix + "test2") - ) + models, + contains( + new URL(prefix + "foo.smithy"), + new URL(prefix + "baz/bar/example.json"), + new URL(prefix + "test"), + new URL(prefix + "test2") + ) ); } @@ -124,12 +124,12 @@ public void prohibitsSpecialCharacters() { @Test public void extractsOutModelNameFromJarURL() throws IOException { assertThat( - ModelDiscovery.getSmithyModelPathFromJarUrl(new URL("jar:file:/a.jar!/META-INF/smithy/a/b.json")), - equalTo("a/b.json") + ModelDiscovery.getSmithyModelPathFromJarUrl(new URL("jar:file:/a.jar!/META-INF/smithy/a/b.json")), + equalTo("a/b.json") ); assertThat( - ModelDiscovery.getSmithyModelPathFromJarUrl(new URL("jar:file:/a.jar!/META-INF/smithy/b.json")), - equalTo("b.json") + ModelDiscovery.getSmithyModelPathFromJarUrl(new URL("jar:file:/a.jar!/META-INF/smithy/b.json")), + equalTo("b.json") ); } @@ -143,24 +143,24 @@ public void requiresModelNameToBeValidWhenParsing() throws IOException { @Test public void createSmithyManifestUrlFromPath() throws IOException { assertThat( - ModelDiscovery.createSmithyJarManifestUrl("/foo.jar"), - equalTo(new URL("jar:file:/foo.jar!/META-INF/smithy/manifest")) + ModelDiscovery.createSmithyJarManifestUrl("/foo.jar"), + equalTo(new URL("jar:file:/foo.jar!/META-INF/smithy/manifest")) ); } @Test public void createSmithyManifestUrlFromFileUrl() throws IOException { assertThat( - ModelDiscovery.createSmithyJarManifestUrl("file:/foo.jar"), - equalTo(new URL("jar:file:/foo.jar!/META-INF/smithy/manifest")) + ModelDiscovery.createSmithyJarManifestUrl("file:/foo.jar"), + equalTo(new URL("jar:file:/foo.jar!/META-INF/smithy/manifest")) ); } @Test public void createSmithyManifestUrlFromJarUrl() throws IOException { assertThat( - ModelDiscovery.createSmithyJarManifestUrl("jar:file:/foo.jar"), - equalTo(new URL("jar:file:/foo.jar!/META-INF/smithy/manifest")) + ModelDiscovery.createSmithyJarManifestUrl("jar:file:/foo.jar"), + equalTo(new URL("jar:file:/foo.jar!/META-INF/smithy/manifest")) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelInteropTransformerTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelInteropTransformerTest.java index 6bd628b3f05..59bf1416a36 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelInteropTransformerTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelInteropTransformerTest.java @@ -140,18 +140,18 @@ private static UpgradeTestCase createAndValidate(String directory) { private static ObjectNode serializeNormalizedModel(Model model, ModelSerializer serializer) { Model normalized = Model.assembler() - .addDocumentNode(serializer.serialize(model)) - .assemble() - .getResult() - .get(); + .addDocumentNode(serializer.serialize(model)) + .assemble() + .getResult() + .get(); return serializer.serialize(normalized); } private static UpgradeTestCase createFromDirectory(String directory) { try ( - Stream paths = Files.walk( - Paths.get(ModelInteropTransformerTest.class.getResource(directory).toURI()) - ) + Stream paths = Files.walk( + Paths.get(ModelInteropTransformerTest.class.getResource(directory).toURI()) + ) ) { UpgradeTestCase testCase = new UpgradeTestCase(); paths.filter(Files::isRegularFile).forEach(file -> { @@ -173,34 +173,34 @@ private static UpgradeTestCase createFromDirectory(String directory) { private static Matcher targetsShape(ValidatedResult result, String shapeName) { return ShapeMatcher.builderFor(MemberShape.class, result) - .description("Targets " + shapeName) - .addAssertion( - member -> member.getTarget() - .equals(ShapeId.fromOptionalNamespace(Prelude.NAMESPACE, shapeName)), - member -> "targeted " + member.getTarget() - ) - .build(); + .description("Targets " + shapeName) + .addAssertion( + member -> member.getTarget() + .equals(ShapeId.fromOptionalNamespace(Prelude.NAMESPACE, shapeName)), + member -> "targeted " + member.getTarget() + ) + .build(); } private static Matcher addedDefaultTrait(ValidatedResult result) { return ShapeMatcher.builderFor(MemberShape.class, result) - .description("member to have a default trait") - .addAssertion( - member -> member.hasTrait(DefaultTrait.class), - member -> "no @default trait" - ) - .build(); + .description("member to have a default trait") + .addAssertion( + member -> member.hasTrait(DefaultTrait.class), + member -> "no @default trait" + ) + .build(); } private static Matcher v2ShapeUsesBoxTrait(ValidatedResult result) { return ShapeMatcher.builderFor(MemberShape.class, result) - .description("v2 shape uses box trait") - .addEventAssertion( - Validator.MODEL_ERROR, - Severity.ERROR, - "@box is not supported in Smithy IDL 2.0" - ) - .build(); + .description("v2 shape uses box trait") + .addEventAssertion( + Validator.MODEL_ERROR, + Severity.ERROR, + "@box is not supported in Smithy IDL 2.0" + ) + .build(); } // This test ensures that the upgrader properly upgrades 1.0 models to 2.0 models, back patches 2.0 models with @@ -210,26 +210,26 @@ private static Matcher v2ShapeUsesBoxTrait(ValidatedResult resul public void ensuresConsistentNullabilityAcrossVersions() { Pattern splitPattern = Pattern.compile("\r\n|\r|\n"); List> cases = ListUtils.of( - Pair.of("1-to-2", "nullableBooleanBoxedTarget"), - Pair.of("1-to-2", "nullableBooleanBoxedNonPreludeTarget"), - Pair.of("1-to-2", "nullableBooleanInV1BoxedTargetRequired"), - Pair.of("1-to-2", "nonNullableBooleanUnboxedTarget"), - Pair.of("1-to-2", "nullableBooleanBoxedMember"), - Pair.of("1-to-2", "nonNullableBooleanUnboxedCustomTarget"), - Pair.of("1-to-2", "nullableIntegerBoxedTarget"), - Pair.of("1-to-2", "nullableIntegerBoxedNonPreludeTarget"), - Pair.of("1-to-2", "nullableIntegerInV1BoxedTargetRequired"), - Pair.of("1-to-2", "nonNullableIntegerUnboxedTarget"), - Pair.of("1-to-2", "nullableIntegerBoxedMember"), - Pair.of("1-to-2", "nonNullableIntegerUnboxedCustomTarget"), - - Pair.of("2-to-1", "booleanDefaultZeroValueToNonNullable"), - Pair.of("2-to-1", "booleanDefaultNonZeroValueToNullable"), - Pair.of("2-to-1", "booleanRequiredToNullable"), - Pair.of("2-to-1", "booleanDefaultWithAddedTraitToNullable"), - Pair.of("2-to-1", "booleanDefaultWithClientOptionalTraitToNullable"), - Pair.of("2-to-1", "intEnumSetToZeroValueToNonNullable"), - Pair.of("2-to-1", "booleanDefaultZeroValueToNonNullablePrelude") + Pair.of("1-to-2", "nullableBooleanBoxedTarget"), + Pair.of("1-to-2", "nullableBooleanBoxedNonPreludeTarget"), + Pair.of("1-to-2", "nullableBooleanInV1BoxedTargetRequired"), + Pair.of("1-to-2", "nonNullableBooleanUnboxedTarget"), + Pair.of("1-to-2", "nullableBooleanBoxedMember"), + Pair.of("1-to-2", "nonNullableBooleanUnboxedCustomTarget"), + Pair.of("1-to-2", "nullableIntegerBoxedTarget"), + Pair.of("1-to-2", "nullableIntegerBoxedNonPreludeTarget"), + Pair.of("1-to-2", "nullableIntegerInV1BoxedTargetRequired"), + Pair.of("1-to-2", "nonNullableIntegerUnboxedTarget"), + Pair.of("1-to-2", "nullableIntegerBoxedMember"), + Pair.of("1-to-2", "nonNullableIntegerUnboxedCustomTarget"), + + Pair.of("2-to-1", "booleanDefaultZeroValueToNonNullable"), + Pair.of("2-to-1", "booleanDefaultNonZeroValueToNullable"), + Pair.of("2-to-1", "booleanRequiredToNullable"), + Pair.of("2-to-1", "booleanDefaultWithAddedTraitToNullable"), + Pair.of("2-to-1", "booleanDefaultWithClientOptionalTraitToNullable"), + Pair.of("2-to-1", "intEnumSetToZeroValueToNonNullable"), + Pair.of("2-to-1", "booleanDefaultZeroValueToNonNullablePrelude") ); cases.forEach(pair -> { @@ -246,9 +246,9 @@ public void ensuresConsistentNullabilityAcrossVersions() { expectedNode.getStringMap().forEach((k, v) -> nullability.put(k, v.expectBooleanNode().getValue())); Model original = Model.assembler() - .addUnparsedModel(name + ".smithy", contents) - .assemble() - .unwrap(); + .addUnparsedModel(name + ".smithy", contents) + .assemble() + .unwrap(); upgradeAssertions(name, original, nullability, 0); @@ -258,9 +258,9 @@ public void ensuresConsistentNullabilityAcrossVersions() { for (int tripCount = 1; tripCount <= 2; tripCount++) { Node serialized = ModelSerializer.builder().build().serialize(updatedModel); updatedModel = Model.assembler() - .addDocumentNode(serialized) - .assemble() - .unwrap(); + .addDocumentNode(serialized) + .assemble() + .unwrap(); upgradeAssertions(name, updatedModel, nullability, tripCount); } }); @@ -275,13 +275,13 @@ private void upgradeAssertions(String name, Model model, Map ex boolean isBoxed = member.getMemberTrait(model, BoxTrait.class).isPresent(); result.put("v1-box", isBoxed); result.put( - "v1-client-zero-value", - index.isMemberNullable(member, NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1) + "v1-client-zero-value", + index.isMemberNullable(member, NullableIndex.CheckMode.CLIENT_ZERO_VALUE_V1) ); result.put("v2", index.isMemberNullable(model.expectShape(shape, MemberShape.class))); String reason = "Expected " + name + " to have nullability of " + expected + " but found " - + result + " (round trip #" + roundTrip + ')'; + + result + " (round trip #" + roundTrip + ')'; assertThat(reason, expected, equalTo(result)); @@ -289,7 +289,7 @@ private void upgradeAssertions(String name, Model model, Map ex boolean isDeprecatedIndexWorking = index.isNullable(member); if (!isDeprecatedIndexWorking == result.get("v1-client-zero-value")) { String reasonBox = "Expected deprecated index checks to be " + result.get("v1") + " for " + name - + "; traits: " + member.getAllTraits() + "; round trip " + roundTrip; + + "; traits: " + member.getAllTraits() + "; round trip " + roundTrip; Assertions.fail(reasonBox); } } @@ -300,23 +300,23 @@ private void upgradeAssertions(String name, Model model, Map ex @Test public void boxTraitOnRootShapeIsNotLossyWhenRoundTripped() { Model model = Model.assembler() - .addUnparsedModel( - "foo.smithy", - "$version: \"1.0\"\n" - + "namespace smithy.example\n" - + "@box\n" - + "integer MyInteger\n" - + "\n" - + "integer PrimitiveInteger\n" - + "\n" - + "structure Foo {\n" - + " @box\n" - + " baz: MyInteger\n" - + " bam: PrimitiveInteger\n" - + "}\n" - ) - .assemble() - .unwrap(); + .addUnparsedModel( + "foo.smithy", + "$version: \"1.0\"\n" + + "namespace smithy.example\n" + + "@box\n" + + "integer MyInteger\n" + + "\n" + + "integer PrimitiveInteger\n" + + "\n" + + "structure Foo {\n" + + " @box\n" + + " baz: MyInteger\n" + + " bam: PrimitiveInteger\n" + + "}\n" + ) + .assemble() + .unwrap(); Node roundTripNode = ModelSerializer.builder().build().serialize(model); Model roundTripModel = Model.assembler().addDocumentNode(roundTripNode).assemble().unwrap(); @@ -341,9 +341,9 @@ private void boxTraitRootAssertionsV1(Model model, int roundTrip) { Node serialized = ModelSerializer.builder().build().serialize(model); String raw = Node.prettyPrintJson(serialized); Model model2 = Model.assembler() - .addUnparsedModel("foo.json", raw) - .assemble() - .unwrap(); + .addUnparsedModel("foo.json", raw) + .assemble() + .unwrap(); assertThat(model2.expectShape(myInteger).hasTrait(BoxTrait.class), is(true)); assertThat(model2.expectShape(myInteger).hasTrait(DefaultTrait.class), is(false)); @@ -366,48 +366,48 @@ private void boxTraitRootAssertionsV1(Model model, int roundTrip) { @Test public void boxTraitOnlyAddedToRootWhenNotSetToZeroValueDefault() { Model model = Model.assembler() - .addUnparsedModel( - "foo.smithy", - "$version: \"2.0\"\n" - + "namespace smithy.example\n" - + "\n" - + "@default(\"\")\n" - + "string DefaultString\n" - + "\n" - + "integer BoxedInteger\n" - + "\n" - + "@default(1)\n" - + "integer BoxedIntegerWithDefault\n" - + "\n" - + "@default(0)\n" - + "integer PrimitiveInteger\n" - + "\n" - + "intEnum BoxedIntEnum {\n" - + " ONE = 1\n" - + "}\n" - + "\n" - + "@default(1)\n" - + "intEnum BoxedIntEnumWithDefault {\n" - + " ONE = 1\n" - + "}\n" - + "\n" - + "@default(0)\n" - + "intEnum PrimitiveIntEnum {\n" - + " ZERO = 0\n" - + "}\n" - + "\n" - + "structure Foo {\n" - + " DefaultString: DefaultString = \"\"\n" - + " BoxedInteger: BoxedInteger\n" - + " PrimitiveInteger: PrimitiveInteger = 0\n" - + " BoxedIntegerWithDefault: BoxedIntegerWithDefault = 1\n" - + " BoxedIntEnum: BoxedIntEnum\n" - + " BoxedIntEnumWithDefault: BoxedIntEnumWithDefault = 1\n" - + " PrimitiveIntEnum: PrimitiveIntEnum = 0\n" - + "}\n" - ) - .assemble() - .unwrap(); + .addUnparsedModel( + "foo.smithy", + "$version: \"2.0\"\n" + + "namespace smithy.example\n" + + "\n" + + "@default(\"\")\n" + + "string DefaultString\n" + + "\n" + + "integer BoxedInteger\n" + + "\n" + + "@default(1)\n" + + "integer BoxedIntegerWithDefault\n" + + "\n" + + "@default(0)\n" + + "integer PrimitiveInteger\n" + + "\n" + + "intEnum BoxedIntEnum {\n" + + " ONE = 1\n" + + "}\n" + + "\n" + + "@default(1)\n" + + "intEnum BoxedIntEnumWithDefault {\n" + + " ONE = 1\n" + + "}\n" + + "\n" + + "@default(0)\n" + + "intEnum PrimitiveIntEnum {\n" + + " ZERO = 0\n" + + "}\n" + + "\n" + + "structure Foo {\n" + + " DefaultString: DefaultString = \"\"\n" + + " BoxedInteger: BoxedInteger\n" + + " PrimitiveInteger: PrimitiveInteger = 0\n" + + " BoxedIntegerWithDefault: BoxedIntegerWithDefault = 1\n" + + " BoxedIntEnum: BoxedIntEnum\n" + + " BoxedIntEnumWithDefault: BoxedIntEnumWithDefault = 1\n" + + " PrimitiveIntEnum: PrimitiveIntEnum = 0\n" + + "}\n" + ) + .assemble() + .unwrap(); Node roundTripNode = ModelSerializer.builder().build().serialize(model); Model roundTripModel = Model.assembler().addDocumentNode(roundTripNode).assemble().unwrap(); @@ -485,8 +485,8 @@ private void boxTraitRootAssertionsV2(Model model, int roundTrip) { @Test public void doesNotFailWhenUpgradingWhenZeroValueIncompatibleWithRangeTrait() { ValidatedResult result = Model.assembler() - .addImport(getClass().getResource("range-upgrade-1.0.smithy")) - .assemble(); + .addImport(getClass().getResource("range-upgrade-1.0.smithy")) + .assemble(); assertThat(result.isBroken(), is(false)); @@ -498,10 +498,10 @@ public void doesNotFailWhenUpgradingWhenZeroValueIncompatibleWithRangeTrait() { // Make sure the range trait wasn't modified. assertThat(shape1.expectTrait(RangeTrait.class).getMin().get().toString(), equalTo("1")); assertThat( - result.getValidationEvents() - .stream() - .anyMatch(event -> event.getMessage().contains("must be greater than or equal to 1")), - is(true) + result.getValidationEvents() + .stream() + .anyMatch(event -> event.getMessage().contains("must be greater than or equal to 1")), + is(true) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelValidatorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelValidatorTest.java index 9a3b914b6e3..ff2f81ed6ec 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelValidatorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelValidatorTest.java @@ -24,15 +24,15 @@ public class ModelValidatorTest { @Test public void addsExplicitValidators() { ValidationEvent event = ValidationEvent.builder() - .severity(Severity.ERROR) - .id("Foo") - .message("bar") - .build(); + .severity(Severity.ERROR) + .id("Foo") + .message("bar") + .build(); String document = "{\"smithy\": \"1.0\"}"; ValidatedResult result = new ModelAssembler() - .addUnparsedModel("[N/A]", document) - .addValidator(index -> Collections.singletonList(event)) - .assemble(); + .addUnparsedModel("[N/A]", document) + .addValidator(index -> Collections.singletonList(event)) + .assemble(); assertThat(result.getValidationEvents(), contains(event)); } @@ -40,8 +40,8 @@ public void addsExplicitValidators() { @Test public void registersTraitValidators() { ValidatedResult result = new ModelAssembler() - .addImport(getClass().getResource("errors.json")) - .assemble(); + .addImport(getClass().getResource("errors.json")) + .assemble(); assertThat(result.getValidationEvents(), hasSize(2)); assertThat(result.getValidationEvents().get(0).getMessage(), containsString("client")); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/PreludeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/PreludeTest.java index 41766c12152..77349177a5b 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/PreludeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/PreludeTest.java @@ -46,9 +46,9 @@ public void checkIfPrivateShapesAreReferenced() { ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.scrubTraitDefinitions(model); Set unreferencedPrivateShapes = result.shapes() - .filter(shape -> shape.hasTrait(PrivateTrait.class)) - .map(Shape::getId) - .collect(Collectors.toSet()); + .filter(shape -> shape.hasTrait(PrivateTrait.class)) + .map(Shape::getId) + .collect(Collectors.toSet()); assertThat(unreferencedPrivateShapes, emptyCollectionOf(ShapeId.class)); } @@ -66,10 +66,10 @@ public void checkIfPrivateShapesAreReferenced() { @Test public void ensurePreludeIsValid() { Model.assembler() - .putMetadata(TraitValueValidator.VALIDATE_PRELUDE, Node.from(true)) - .assemble() - // If the prelude is invalid, then this will throw an exception. - .unwrap(); + .putMetadata(TraitValueValidator.VALIDATE_PRELUDE, Node.from(true)) + .assemble() + // If the prelude is invalid, then this will throw an exception. + .unwrap(); } @Test diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/TopologicalShapeSortTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/TopologicalShapeSortTest.java index b508795dae3..b42d4ae1e58 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/TopologicalShapeSortTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/TopologicalShapeSortTest.java @@ -62,8 +62,8 @@ public void detectsCycles() { throw new IllegalArgumentException("should have detected a cycle"); } catch (TopologicalShapeSort.CycleException e) { assertThat( - e.getUnresolved(), - containsInAnyOrder(from("test#A"), from("test#B"), from("test#C"), from("test#E")) + e.getUnresolved(), + containsInAnyOrder(from("test#A"), from("test#B"), from("test#C"), from("test#E")) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidSmithyModelLoaderRunnerTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidSmithyModelLoaderRunnerTest.java index 64f785abcd0..d3c87225f49 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidSmithyModelLoaderRunnerTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidSmithyModelLoaderRunnerTest.java @@ -34,9 +34,9 @@ public class ValidSmithyModelLoaderRunnerTest { @BeforeAll public static void before() { shared = Model.assembler() - .addImport(ValidSmithyModelLoaderRunnerTest.class.getResource("valid/__shared.json")) - .assemble() - .unwrap(); + .addImport(ValidSmithyModelLoaderRunnerTest.class.getResource("valid/__shared.json")) + .assemble() + .unwrap(); } @ParameterizedTest @@ -44,24 +44,24 @@ public static void before() { public void parserRunnerTest(String file) { Path smithyFilename = Paths.get(file.replace(".json", ".smithy")); Model expected = Model.assembler() - .addImport(file) - // Always include the __shared.json file. This is used for - // cross-model loading testing. - .addModel(shared) - .assemble() - .unwrap(); + .addImport(file) + // Always include the __shared.json file. This is used for + // cross-model loading testing. + .addModel(shared) + .assemble() + .unwrap(); Model result; try { result = Model.assembler() - .addImport(smithyFilename) - .addModel(shared) - .assemble() - .unwrap(); + .addImport(smithyFilename) + .addModel(shared) + .assemble() + .unwrap(); } catch (Exception e) { throw new IllegalStateException( - String.format("Error parsing: %s\n\n%s", smithyFilename, e.getMessage()), - e + String.format("Error parsing: %s\n\n%s", smithyFilename, e.getMessage()), + e ); } @@ -72,37 +72,37 @@ private void validateMatch(Model result, Model expected, String file) { if (!result.equals(expected)) { ModelSerializer serializer = ModelSerializer.builder().build(); throw new IllegalStateException( - String.format( - "Result did not match the expected model for %s.\nResult:\n\n%s\n\nExpected:\n\n%s\r\nDiff: %s", - file, - formatModel(result), - formatModel(expected), - Node.diff(serializer.serialize(result), serializer.serialize(expected)) - ) + String.format( + "Result did not match the expected model for %s.\nResult:\n\n%s\n\nExpected:\n\n%s\r\nDiff: %s", + file, + formatModel(result), + formatModel(expected), + Node.diff(serializer.serialize(result), serializer.serialize(expected)) + ) ); } } private static String formatModel(Model model) { ModelSerializer serializer = ModelSerializer.builder() - .shapeFilter(shape -> !shape.getSourceLocation().getFilename().contains("__shared.json")) - .build(); + .shapeFilter(shape -> !shape.getSourceLocation().getFilename().contains("__shared.json")) + .build(); return Node.prettyPrintJson(serializer.serialize(model)); } public static Collection data() throws Exception { try { Stream paths = Files.walk( - Paths.get( - ValidSmithyModelLoaderRunnerTest.class.getResource("valid").toURI() - ) + Paths.get( + ValidSmithyModelLoaderRunnerTest.class.getResource("valid").toURI() + ) ); return paths - .filter(Files::isRegularFile) - .filter(file -> file.toString().endsWith(".json")) - .filter(file -> !file.toString().contains("__shared.json")) - .map(Object::toString) - .collect(Collectors.toList()); + .filter(Files::isRegularFile) + .filter(file -> file.toString().endsWith(".json")) + .filter(file -> !file.toString().contains("__shared.json")) + .map(Object::toString) + .collect(Collectors.toList()); } catch (IOException e) { throw new RuntimeException(e); } @@ -111,15 +111,15 @@ public static Collection data() throws Exception { @Test public void canAddTraitsToForwardReferenceMembersWithUseStatements() { Model result = Model.assembler() - .addImport(ValidSmithyModelLoaderRunnerTest.class.getResource("forwardrefs/use/use.smithy")) - .addModel(shared) - .assemble() - .unwrap(); + .addImport(ValidSmithyModelLoaderRunnerTest.class.getResource("forwardrefs/use/use.smithy")) + .addModel(shared) + .assemble() + .unwrap(); Model expected = Model.assembler() - .addImport(ValidSmithyModelLoaderRunnerTest.class.getResource("forwardrefs/use/result.json")) - .addModel(shared) - .assemble() - .unwrap(); + .addImport(ValidSmithyModelLoaderRunnerTest.class.getResource("forwardrefs/use/result.json")) + .addModel(shared) + .assemble() + .unwrap(); validateMatch(result, expected, "forwardrefs/use-shapes.smithy"); } @@ -127,18 +127,18 @@ public void canAddTraitsToForwardReferenceMembersWithUseStatements() { @Test public void canAddTraitsToForwardReferenceMembersWithNoUseStatements() { Model result = Model.assembler() - .addImport(ValidSmithyModelLoaderRunnerTest.class.getResource("forwardrefs/use/no-use.smithy")) - .addModel(shared) - .assemble() - .unwrap(); + .addImport(ValidSmithyModelLoaderRunnerTest.class.getResource("forwardrefs/use/no-use.smithy")) + .addModel(shared) + .assemble() + .unwrap(); Model expected = Model.assembler() - .addImport( - ValidSmithyModelLoaderRunnerTest.class - .getResource("forwardrefs/use/result.json") - ) - .addModel(shared) - .assemble() - .unwrap(); + .addImport( + ValidSmithyModelLoaderRunnerTest.class + .getResource("forwardrefs/use/result.json") + ) + .addModel(shared) + .assemble() + .unwrap(); validateMatch(result, expected, "forwardrefs/user/no-use.smithy"); } @@ -146,27 +146,27 @@ public void canAddTraitsToForwardReferenceMembersWithNoUseStatements() { @Test public void canHandleForwardRefsInResourceProperties() { Model modelA = Model.assembler() - .addImport( - ValidSmithyModelLoaderRunnerTest.class - .getResource("forwardrefs/resource/operation.smithy") - ) - .assemble() - .unwrap(); + .addImport( + ValidSmithyModelLoaderRunnerTest.class + .getResource("forwardrefs/resource/operation.smithy") + ) + .assemble() + .unwrap(); Model result = Model.assembler() - .addModel(modelA) - .addImport( - ValidSmithyModelLoaderRunnerTest.class - .getResource("forwardrefs/resource/resource.smithy") - ) - .assemble() - .unwrap(); + .addModel(modelA) + .addImport( + ValidSmithyModelLoaderRunnerTest.class + .getResource("forwardrefs/resource/resource.smithy") + ) + .assemble() + .unwrap(); Model expected = Model.assembler() - .addImport( - ValidSmithyModelLoaderRunnerTest.class - .getResource("forwardrefs/resource/result.json") - ) - .assemble() - .unwrap(); + .addImport( + ValidSmithyModelLoaderRunnerTest.class + .getResource("forwardrefs/resource/result.json") + ) + .assemble() + .unwrap(); validateMatch(result, expected, "forwardrefs/resource/operation.smithy"); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidationEventDecoratorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidationEventDecoratorTest.java index 0112f2fa960..577d16946d1 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidationEventDecoratorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidationEventDecoratorTest.java @@ -32,9 +32,9 @@ public class ValidationEventDecoratorTest { @Test public void canDecorateValidationEvents() { ValidatedResult result = Model.assembler() - .addImport(getClass().getResource("validation-event-decorator-test.smithy")) - .validatorFactory(testFactory(new TestValidationEventDecorator())) - .assemble(); + .addImport(getClass().getResource("validation-event-decorator-test.smithy")) + .validatorFactory(testFactory(new TestValidationEventDecorator())) + .assemble(); for (ValidationEvent event : result.getValidationEvents()) { ShapeId eventShapeId = event.getShapeId().orElse(null); if (MATCHING_SHAPE_IDS.contains(eventShapeId)) { @@ -50,9 +50,9 @@ public void canDecorateValidationEvents() { public void exceptionsAreNotCaughtWhenDecoratorsThrow() { assertThrows(RuntimeException.class, () -> { Model.assembler() - .addImport(getClass().getResource("validation-event-decorator-test.smithy")) - .validatorFactory(testFactory(new ThrowingValidationEventDecorator())) - .assemble(); + .addImport(getClass().getResource("validation-event-decorator-test.smithy")) + .validatorFactory(testFactory(new ThrowingValidationEventDecorator())) + .assemble(); }); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidatorDefinitionTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidatorDefinitionTest.java index 84e87ce15ad..be7d8a8342f 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidatorDefinitionTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidatorDefinitionTest.java @@ -26,33 +26,33 @@ public class ValidatorDefinitionTest { @Test public void mapsAndFiltersOverShapes() { List events = Model.assembler() - .addImport(getClass().getResource("validator-filtering-and-mapping.smithy")) - .validatorFactory(new ValidatorFactory() { - @Override - public List loadBuiltinValidators() { - return Collections.emptyList(); - } + .addImport(getClass().getResource("validator-filtering-and-mapping.smithy")) + .validatorFactory(new ValidatorFactory() { + @Override + public List loadBuiltinValidators() { + return Collections.emptyList(); + } - @Override - public Optional createValidator(String name, ObjectNode configuration) { - return name.equals("hello") - ? Optional.of( - model -> model.shapes() - .map( - shape -> ValidationEvent.builder() - .id("hello.subpart") - .shape(shape) - .severity(Severity.WARNING) - .message("Hello!") - .build() + @Override + public Optional createValidator(String name, ObjectNode configuration) { + return name.equals("hello") + ? Optional.of( + model -> model.shapes() + .map( + shape -> ValidationEvent.builder() + .id("hello.subpart") + .shape(shape) + .severity(Severity.WARNING) + .message("Hello!") + .build() + ) + .collect(Collectors.toList()) ) - .collect(Collectors.toList()) - ) - : Optional.empty(); - } - }) - .assemble() - .getValidationEvents(); + : Optional.empty(); + } + }) + .assemble() + .getValidationEvents(); assertThat(events, not(empty())); Assertions.assertEquals(2, events.stream().filter(e -> e.getId().equals("hello.subpart")).count()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidatorLoaderTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidatorLoaderTest.java index 245df8be0f8..b969264596a 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidatorLoaderTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidatorLoaderTest.java @@ -18,9 +18,9 @@ public class ValidatorLoaderTest { @Test public void loadsAppropriateSourceLocations() { List events = Model.assembler() - .addImport(getClass().getResource("invalid-validation-selector.json")) - .assemble() - .getValidationEvents(); + .addImport(getClass().getResource("invalid-validation-selector.json")) + .assemble() + .getValidationEvents(); assertThat(events, not(empty())); Assertions.assertTrue(events.stream().anyMatch(e -> e.getMessage().contains("Syntax error"))); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/sourcecontext/DefaultSourceLoaderTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/sourcecontext/DefaultSourceLoaderTest.java index 1adc439e521..1871f4abc88 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/sourcecontext/DefaultSourceLoaderTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/sourcecontext/DefaultSourceLoaderTest.java @@ -47,12 +47,12 @@ public void ignoresInvalidSourceLocations() { String file = getClass().getResource("context.smithy").getFile(); assertThat( - SourceContextLoader.createLineBasedLoader(4).loadContext(new SourceLocation(file, -1, -1)), - empty() + SourceContextLoader.createLineBasedLoader(4).loadContext(new SourceLocation(file, -1, -1)), + empty() ); assertThat( - SourceContextLoader.createLineBasedLoader(4).loadContext(new SourceLocation(file, 9999, -1)), - empty() + SourceContextLoader.createLineBasedLoader(4).loadContext(new SourceLocation(file, 9999, -1)), + empty() ); } @@ -115,11 +115,11 @@ public void modelLoadsLeadingLinesUpToShape() { SourceContextLoader loader = SourceContextLoader.createModelAwareLoader(model, 4); Shape shape = model.expectShape(ShapeId.from("example.smithy#Baz")); ValidationEvent event = ValidationEvent.builder() - .severity(Severity.ERROR) - .id("Foo") - .shape(shape) - .message("Test") - .build(); + .severity(Severity.ERROR) + .id("Foo") + .shape(shape) + .message("Test") + .build(); Collection context = loader.loadContext(event); Iterator iter = context.iterator(); @@ -135,11 +135,11 @@ public void showsContainerAndMember() { SourceContextLoader loader = SourceContextLoader.createModelAwareLoader(model, 4); Shape shape = model.expectShape(ShapeId.from("example.smithy#Baz$bam")); ValidationEvent event = ValidationEvent.builder() - .severity(Severity.ERROR) - .id("Foo") - .shape(shape) - .message("Test") - .build(); + .severity(Severity.ERROR) + .id("Foo") + .shape(shape) + .message("Test") + .build(); Collection context = loader.loadContext(event); Iterator iter = context.iterator(); @@ -154,17 +154,17 @@ public void ignoresInvalidMembersThatAreAboveContainers() { MemberShape member = model.expectShape(ShapeId.from("example.smithy#Baz$bam"), MemberShape.class); // Create a modified member that is incorrectly above the container shape. MemberShape modified = member.toBuilder() - .addTrait(new SensitiveTrait()) // change it so the change takes effect - .source(new SourceLocation(member.getSourceLocation().getFilename(), 1, 1)) - .build(); + .addTrait(new SensitiveTrait()) // change it so the change takes effect + .source(new SourceLocation(member.getSourceLocation().getFilename(), 1, 1)) + .build(); Model updated = ModelTransformer.create().replaceShapes(model, Collections.singleton(modified)); SourceContextLoader loader = SourceContextLoader.createModelAwareLoader(updated, 4); ValidationEvent event = ValidationEvent.builder() - .severity(Severity.ERROR) - .id("Foo") - .shape(modified) - .message("Test") - .build(); + .severity(Severity.ERROR) + .id("Foo") + .shape(modified) + .message("Test") + .build(); Collection context = loader.loadContext(event); assertThat(context, empty()); @@ -176,12 +176,12 @@ public void showsMemberAfterTrait() { SourceContextLoader loader = SourceContextLoader.createModelAwareLoader(model, 4); Shape shape = model.expectShape(ShapeId.from("example.smithy#Baz$bam")); ValidationEvent event = ValidationEvent.builder() - .severity(Severity.ERROR) - .id("Foo") - .shape(shape) - .sourceLocation(shape.expectTrait(DocumentationTrait.class)) - .message("Test") - .build(); + .severity(Severity.ERROR) + .id("Foo") + .shape(shape) + .sourceLocation(shape.expectTrait(DocumentationTrait.class)) + .message("Test") + .build(); Collection context = loader.loadContext(event); Iterator iter = context.iterator(); @@ -196,12 +196,12 @@ public void applyStatementsJustShowTheStatement() { SourceContextLoader loader = SourceContextLoader.createModelAwareLoader(model, 4); Shape shape = model.expectShape(ShapeId.from("example.smithy#Foo")); ValidationEvent event = ValidationEvent.builder() - .severity(Severity.ERROR) - .id("Foo") - .shape(shape) - .sourceLocation(shape.expectTrait(DocumentationTrait.class)) - .message("Test") - .build(); + .severity(Severity.ERROR) + .id("Foo") + .shape(shape) + .sourceLocation(shape.expectTrait(DocumentationTrait.class)) + .message("Test") + .build(); Collection context = loader.loadContext(event); Iterator iter = context.iterator(); @@ -215,12 +215,12 @@ public void showsJsonModelTraits() { SourceContextLoader loader = SourceContextLoader.createModelAwareLoader(model, 4); Shape shape = model.expectShape(ShapeId.from("example.smithy#Foo")); ValidationEvent event = ValidationEvent.builder() - .severity(Severity.ERROR) - .id("Foo") - .shape(shape) - .sourceLocation(shape.expectTrait(SensitiveTrait.class)) - .message("Test") - .build(); + .severity(Severity.ERROR) + .id("Foo") + .shape(shape) + .sourceLocation(shape.expectTrait(SensitiveTrait.class)) + .message("Test") + .build(); Collection context = loader.loadContext(event); Iterator iter = context.iterator(); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/BottomUpNeighborVisitorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/BottomUpNeighborVisitorTest.java index 82259f5ec97..7ac52068bae 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/BottomUpNeighborVisitorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/BottomUpNeighborVisitorTest.java @@ -31,47 +31,47 @@ public class BottomUpNeighborVisitorTest { public void dataShape() { Shape shape = BlobShape.builder().id("ns.foo#name").build(); MemberShape listMemberShape = MemberShape.builder() - .target(shape.getId()) - .id("ns.foo#list$member") - .build(); + .target(shape.getId()) + .id("ns.foo#list$member") + .build(); ListShape listShape = ListShape.builder().id("ns.foo#list").member(listMemberShape).build(); MemberShape mapKeyShape = MemberShape.builder() - .target(shape.getId()) - .id("ns.foo#map$key") - .build(); + .target(shape.getId()) + .id("ns.foo#map$key") + .build(); MemberShape mapValueShape = MemberShape.builder() - .target(shape.getId()) - .id("ns.foo#map$value") - .build(); + .target(shape.getId()) + .id("ns.foo#map$value") + .build(); MapShape mapShape = MapShape.builder() - .id(mapKeyShape.getId().withoutMember()) - .key(mapKeyShape) - .value(mapValueShape) - .build(); + .id(mapKeyShape.getId().withoutMember()) + .key(mapKeyShape) + .value(mapValueShape) + .build(); MemberShape structureMemberShape = MemberShape.builder() - .target(shape.getId()) - .id("ns.foo#structure$aMember") - .build(); + .target(shape.getId()) + .id("ns.foo#structure$aMember") + .build(); StructureShape structureShape = StructureShape.builder() - .id(structureMemberShape.getId().withoutMember()) - .addMember(structureMemberShape) - .build(); + .id(structureMemberShape.getId().withoutMember()) + .addMember(structureMemberShape) + .build(); Model model = Model.builder() - .addShapes(shape, listShape, mapShape, structureShape) - .build(); + .addShapes(shape, listShape, mapShape, structureShape) + .build(); NeighborProvider neighborVisitor = NeighborProvider.reverse(model); assertThat( - neighborVisitor.getNeighbors(shape), - containsInAnyOrder( - Relationship.create(listMemberShape, RelationshipType.MEMBER_TARGET, shape), - Relationship.create(mapKeyShape, RelationshipType.MEMBER_TARGET, shape), - Relationship.create(mapValueShape, RelationshipType.MEMBER_TARGET, shape), - Relationship.create(structureMemberShape, RelationshipType.MEMBER_TARGET, shape) - ) + neighborVisitor.getNeighbors(shape), + containsInAnyOrder( + Relationship.create(listMemberShape, RelationshipType.MEMBER_TARGET, shape), + Relationship.create(mapKeyShape, RelationshipType.MEMBER_TARGET, shape), + Relationship.create(mapValueShape, RelationshipType.MEMBER_TARGET, shape), + Relationship.create(structureMemberShape, RelationshipType.MEMBER_TARGET, shape) + ) ); } @@ -79,76 +79,76 @@ public void dataShape() { public void memberShape() { Shape shape = BlobShape.builder().id("ns.foo#name").build(); MemberShape listMemberShape = MemberShape.builder() - .target(shape.getId()) - .id("ns.foo#list$member") - .build(); + .target(shape.getId()) + .id("ns.foo#list$member") + .build(); Shape listShape = ListShape.builder().member(listMemberShape).id("ns.foo#list").build(); MemberShape mapKeyShape = MemberShape.builder() - .target(shape.getId()) - .id("ns.foo#map$key") - .build(); + .target(shape.getId()) + .id("ns.foo#map$key") + .build(); MemberShape mapValueShape = MemberShape.builder() - .target(shape.getId()) - .id("ns.foo#map$value") - .build(); + .target(shape.getId()) + .id("ns.foo#map$value") + .build(); Shape mapShape = MapShape.builder() - .key(mapKeyShape) - .value(mapValueShape) - .id("ns.foo#map") - .build(); + .key(mapKeyShape) + .value(mapValueShape) + .id("ns.foo#map") + .build(); MemberShape structureMemberShape = MemberShape.builder() - .target(shape.getId()) - .id("ns.foo#structure$aMember") - .build(); + .target(shape.getId()) + .id("ns.foo#structure$aMember") + .build(); Shape structureShape = StructureShape.builder().addMember(structureMemberShape).id("ns.foo#structure").build(); MemberShape tuMemberShape = MemberShape.builder() - .target(shape.getId()) - .id("ns.foo#union$aMember") - .build(); + .target(shape.getId()) + .id("ns.foo#union$aMember") + .build(); Shape unionShape = UnionShape.builder().addMember(tuMemberShape).id("ns.foo#union").build(); Model model = Model.builder() - .addShape(shape) - .addShape(listMemberShape) - .addShape(listShape) - .addShape(mapKeyShape) - .addShape(mapValueShape) - .addShape(mapShape) - .addShape(structureMemberShape) - .addShape(structureShape) - .addShape(tuMemberShape) - .addShape(unionShape) - .build(); + .addShape(shape) + .addShape(listMemberShape) + .addShape(listShape) + .addShape(mapKeyShape) + .addShape(mapValueShape) + .addShape(mapShape) + .addShape(structureMemberShape) + .addShape(structureShape) + .addShape(tuMemberShape) + .addShape(unionShape) + .build(); NeighborProvider neighborVisitor = NeighborProvider.reverse(model); assertThat( - neighborVisitor.getNeighbors(listMemberShape), - containsInAnyOrder( - Relationship.create(listShape, RelationshipType.LIST_MEMBER, listMemberShape) - ) + neighborVisitor.getNeighbors(listMemberShape), + containsInAnyOrder( + Relationship.create(listShape, RelationshipType.LIST_MEMBER, listMemberShape) + ) ); assertThat( - neighborVisitor.getNeighbors(mapKeyShape), - containsInAnyOrder( - Relationship.create(mapShape, RelationshipType.MAP_KEY, mapKeyShape) - ) + neighborVisitor.getNeighbors(mapKeyShape), + containsInAnyOrder( + Relationship.create(mapShape, RelationshipType.MAP_KEY, mapKeyShape) + ) ); assertThat( - neighborVisitor.getNeighbors(mapValueShape), - containsInAnyOrder( - Relationship.create(mapShape, RelationshipType.MAP_VALUE, mapValueShape) - ) + neighborVisitor.getNeighbors(mapValueShape), + containsInAnyOrder( + Relationship.create(mapShape, RelationshipType.MAP_VALUE, mapValueShape) + ) ); assertThat( - neighborVisitor.getNeighbors(structureMemberShape), - containsInAnyOrder( - Relationship.create(structureShape, RelationshipType.STRUCTURE_MEMBER, structureMemberShape) - ) + neighborVisitor.getNeighbors(structureMemberShape), + containsInAnyOrder( + Relationship.create(structureShape, RelationshipType.STRUCTURE_MEMBER, structureMemberShape) + ) ); assertThat( - neighborVisitor.getNeighbors(tuMemberShape), - containsInAnyOrder( - Relationship.create(unionShape, RelationshipType.UNION_MEMBER, tuMemberShape) - ) + neighborVisitor.getNeighbors(tuMemberShape), + containsInAnyOrder( + Relationship.create(unionShape, RelationshipType.UNION_MEMBER, tuMemberShape) + ) ); } @@ -158,56 +158,56 @@ public void structureShape() { StructureShape input = StructureShape.builder().id("ns.foo#Input").build(); StructureShape output = StructureShape.builder().id("ns.foo#Output").build(); OperationShape fooOperation = OperationShape.builder() - .id("ns.foo#Foo") - .input(input.getId()) - .output(output.getId()) - .addError(error.getId()) - .build(); + .id("ns.foo#Foo") + .input(input.getId()) + .output(output.getId()) + .addError(error.getId()) + .build(); OperationShape barOperation = OperationShape.builder() - .id("ns.foo#Bar") - .input(output.getId()) - .output(input.getId()) - .addError(error.getId()) - .build(); + .id("ns.foo#Bar") + .input(output.getId()) + .output(input.getId()) + .addError(error.getId()) + .build(); Model model = Model.builder().addShapes(fooOperation, barOperation, input, output, error).build(); NeighborProvider neighborVisitor = NeighborProvider.reverse(model); assertThat( - neighborVisitor.getNeighbors(input), - containsInAnyOrder( - Relationship.create(fooOperation, RelationshipType.INPUT, input), - Relationship.create(barOperation, RelationshipType.OUTPUT, input) - ) + neighborVisitor.getNeighbors(input), + containsInAnyOrder( + Relationship.create(fooOperation, RelationshipType.INPUT, input), + Relationship.create(barOperation, RelationshipType.OUTPUT, input) + ) ); assertThat( - neighborVisitor.getNeighbors(output), - containsInAnyOrder( - Relationship.create(fooOperation, RelationshipType.OUTPUT, output), - Relationship.create(barOperation, RelationshipType.INPUT, output) - ) + neighborVisitor.getNeighbors(output), + containsInAnyOrder( + Relationship.create(fooOperation, RelationshipType.OUTPUT, output), + Relationship.create(barOperation, RelationshipType.INPUT, output) + ) ); assertThat( - neighborVisitor.getNeighbors(error), - containsInAnyOrder( - Relationship.create(fooOperation, RelationshipType.ERROR, error), - Relationship.create(barOperation, RelationshipType.ERROR, error) - ) + neighborVisitor.getNeighbors(error), + containsInAnyOrder( + Relationship.create(fooOperation, RelationshipType.ERROR, error), + Relationship.create(barOperation, RelationshipType.ERROR, error) + ) ); } @Test public void serviceShape() { ServiceShape service = ServiceShape.builder() - .id("ns.foo#Svc") - .version("2017-01-17") - .addOperation("ns.foo#Operation") - .addResource("ns.foo#Resource") - .build(); + .id("ns.foo#Svc") + .version("2017-01-17") + .addOperation("ns.foo#Operation") + .addResource("ns.foo#Resource") + .build(); OperationShape operationShape = OperationShape.builder().id("ns.foo#Operation").build(); ResourceShape resourceShape = ResourceShape.builder().id("ns.foo#Resource").build(); Model model = Model.builder() - .addShapes(service, resourceShape, operationShape) - .build(); + .addShapes(service, resourceShape, operationShape) + .build(); NeighborProvider neighborVisitor = NeighborProvider.reverse(model); assertThat(neighborVisitor.getNeighbors(service), empty()); @@ -216,168 +216,168 @@ public void serviceShape() { @Test public void resourceShape() { ServiceShape parent = ServiceShape.builder() - .id("ns.foo#Svc") - .version("2017-01-17") - .addResource("ns.foo#Resource") - .build(); + .id("ns.foo#Svc") + .version("2017-01-17") + .addResource("ns.foo#Resource") + .build(); ServiceShape otherService = ServiceShape.builder() - .id("ns.foo#OtherSvc") - .version("2017-01-17") - .addResource("ns.foo#Child1") - .build(); + .id("ns.foo#OtherSvc") + .version("2017-01-17") + .addResource("ns.foo#Child1") + .build(); ResourceShape resource = ResourceShape.builder() - .id("ns.foo#Resource") - .addIdentifier("id", "smithy.api#String") - .addResource("ns.foo#Child1") - .build(); + .id("ns.foo#Resource") + .addIdentifier("id", "smithy.api#String") + .addResource("ns.foo#Child1") + .build(); ResourceShape child1 = ResourceShape.builder().id("ns.foo#Child1").addResource("ns.foo#Child2").build(); ResourceShape child2 = ResourceShape.builder().id("ns.foo#Child2").build(); Model model = Model.builder() - .addShapes(parent, resource, child1, child2) - .addShape(otherService) - .build(); + .addShapes(parent, resource, child1, child2) + .addShape(otherService) + .build(); NeighborProvider neighborVisitor = NeighborProvider.reverse(model); assertThat( - neighborVisitor.getNeighbors(child2), - containsInAnyOrder( - Relationship.create(child1, RelationshipType.RESOURCE, child2) - ) + neighborVisitor.getNeighbors(child2), + containsInAnyOrder( + Relationship.create(child1, RelationshipType.RESOURCE, child2) + ) ); assertThat( - neighborVisitor.getNeighbors(child1), - containsInAnyOrder( - Relationship.create(resource, RelationshipType.RESOURCE, child1), - Relationship.create(otherService, RelationshipType.RESOURCE, child1) - ) + neighborVisitor.getNeighbors(child1), + containsInAnyOrder( + Relationship.create(resource, RelationshipType.RESOURCE, child1), + Relationship.create(otherService, RelationshipType.RESOURCE, child1) + ) ); assertThat( - neighborVisitor.getNeighbors(resource), - containsInAnyOrder( - Relationship.create(parent, RelationshipType.RESOURCE, resource) - ) + neighborVisitor.getNeighbors(resource), + containsInAnyOrder( + Relationship.create(parent, RelationshipType.RESOURCE, resource) + ) ); assertThat( - neighborVisitor.getNeighbors(child2), - containsInAnyOrder( - Relationship.create(child1, RelationshipType.RESOURCE, child2) - ) + neighborVisitor.getNeighbors(child2), + containsInAnyOrder( + Relationship.create(child1, RelationshipType.RESOURCE, child2) + ) ); } @Test public void operationShape() { ServiceShape parent = ServiceShape.builder() - .id("ns.foo#Svc") - .version("2017-01-17") - .addResource("ns.foo#Resource") - .build(); + .id("ns.foo#Svc") + .version("2017-01-17") + .addResource("ns.foo#Resource") + .build(); ServiceShape otherService = ServiceShape.builder() - .id("ns.foo#OtherSvc") - .version("2017-01-17") - .addOperation("ns.foo#Named") - .build(); + .id("ns.foo#OtherSvc") + .version("2017-01-17") + .addOperation("ns.foo#Named") + .build(); ResourceShape resource = ResourceShape.builder() - .id("ns.foo#Resource") - .addIdentifier("id", "smithy.api#String") - .put(ShapeId.from("ns.foo#Put")) - .create(ShapeId.from("ns.foo#Create")) - .read(ShapeId.from("ns.foo#Get")) - .update(ShapeId.from("ns.foo#Update")) - .delete(ShapeId.from("ns.foo#Delete")) - .list(ShapeId.from("ns.foo#List")) - .addOperation("ns.foo#Named") - .addCollectionOperation("ns.foo#GenericCollection") - .build(); + .id("ns.foo#Resource") + .addIdentifier("id", "smithy.api#String") + .put(ShapeId.from("ns.foo#Put")) + .create(ShapeId.from("ns.foo#Create")) + .read(ShapeId.from("ns.foo#Get")) + .update(ShapeId.from("ns.foo#Update")) + .delete(ShapeId.from("ns.foo#Delete")) + .list(ShapeId.from("ns.foo#List")) + .addOperation("ns.foo#Named") + .addCollectionOperation("ns.foo#GenericCollection") + .build(); OperationShape createOperation = OperationShape.builder().id("ns.foo#Create").build(); OperationShape getOperation = OperationShape.builder() - .id("ns.foo#Get") - .addTrait(new ReadonlyTrait()) - .build(); + .id("ns.foo#Get") + .addTrait(new ReadonlyTrait()) + .build(); OperationShape updateOperation = OperationShape.builder().id("ns.foo#Update").build(); OperationShape deleteOperation = OperationShape.builder() - .id("ns.foo#Delete") - .addTrait(new IdempotentTrait()) - .build(); + .id("ns.foo#Delete") + .addTrait(new IdempotentTrait()) + .build(); OperationShape listOperation = OperationShape.builder() - .id("ns.foo#List") - .addTrait(new ReadonlyTrait()) - .build(); + .id("ns.foo#List") + .addTrait(new ReadonlyTrait()) + .build(); OperationShape namedOperation = OperationShape.builder() - .id("ns.foo#Named") - .build(); + .id("ns.foo#Named") + .build(); OperationShape collectionOperation = OperationShape.builder() - .id("ns.foo#GenericCollection") - .build(); + .id("ns.foo#GenericCollection") + .build(); OperationShape putOperation = OperationShape.builder() - .id("ns.foo#Put") - .build(); + .id("ns.foo#Put") + .build(); Model model = Model.builder() - .addShape(parent) - .addShapes(resource, createOperation, getOperation, updateOperation, deleteOperation, listOperation) - .addShapes(otherService, namedOperation, collectionOperation, putOperation) - .build(); + .addShape(parent) + .addShapes(resource, createOperation, getOperation, updateOperation, deleteOperation, listOperation) + .addShapes(otherService, namedOperation, collectionOperation, putOperation) + .build(); NeighborProvider neighborVisitor = NeighborProvider.reverse(model); assertThat( - neighborVisitor.getNeighbors(namedOperation), - containsInAnyOrder( - Relationship.create(resource, RelationshipType.OPERATION, namedOperation), - Relationship.create(otherService, RelationshipType.OPERATION, namedOperation) - ) + neighborVisitor.getNeighbors(namedOperation), + containsInAnyOrder( + Relationship.create(resource, RelationshipType.OPERATION, namedOperation), + Relationship.create(otherService, RelationshipType.OPERATION, namedOperation) + ) ); assertThat( - neighborVisitor.getNeighbors(createOperation), - containsInAnyOrder( - Relationship.create(resource, RelationshipType.CREATE, createOperation) - ) + neighborVisitor.getNeighbors(createOperation), + containsInAnyOrder( + Relationship.create(resource, RelationshipType.CREATE, createOperation) + ) ); assertThat( - neighborVisitor.getNeighbors(getOperation), - containsInAnyOrder( - Relationship.create(resource, RelationshipType.READ, getOperation) - ) + neighborVisitor.getNeighbors(getOperation), + containsInAnyOrder( + Relationship.create(resource, RelationshipType.READ, getOperation) + ) ); assertThat( - neighborVisitor.getNeighbors(updateOperation), - containsInAnyOrder( - Relationship.create(resource, RelationshipType.UPDATE, updateOperation) - ) + neighborVisitor.getNeighbors(updateOperation), + containsInAnyOrder( + Relationship.create(resource, RelationshipType.UPDATE, updateOperation) + ) ); assertThat( - neighborVisitor.getNeighbors(deleteOperation), - containsInAnyOrder( - Relationship.create(resource, RelationshipType.DELETE, deleteOperation) - ) + neighborVisitor.getNeighbors(deleteOperation), + containsInAnyOrder( + Relationship.create(resource, RelationshipType.DELETE, deleteOperation) + ) ); assertThat( - neighborVisitor.getNeighbors(listOperation), - containsInAnyOrder( - Relationship.create(resource, RelationshipType.LIST, listOperation) - ) + neighborVisitor.getNeighbors(listOperation), + containsInAnyOrder( + Relationship.create(resource, RelationshipType.LIST, listOperation) + ) ); assertThat( - neighborVisitor.getNeighbors(putOperation), - containsInAnyOrder( - Relationship.create(resource, RelationshipType.PUT, putOperation) - ) + neighborVisitor.getNeighbors(putOperation), + containsInAnyOrder( + Relationship.create(resource, RelationshipType.PUT, putOperation) + ) ); assertThat( - neighborVisitor.getNeighbors(collectionOperation), - containsInAnyOrder( - Relationship.create(resource, RelationshipType.COLLECTION_OPERATION, collectionOperation) - ) + neighborVisitor.getNeighbors(collectionOperation), + containsInAnyOrder( + Relationship.create(resource, RelationshipType.COLLECTION_OPERATION, collectionOperation) + ) ); } @Test public void returnsEmptyOnUnreferencedShape() { StringShape target = StringShape.builder() - .id("ns.foo#String") - .build(); + .id("ns.foo#String") + .build(); Model model = Model.builder() - .addShape(target) - .build(); + .addShape(target) + .build(); NeighborProvider neighborVisitor = NeighborProvider.reverse(model); assertThat(neighborVisitor.getNeighbors(target), empty()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NeighborProviderTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NeighborProviderTest.java index a0f3fb26da9..d68de85cec4 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NeighborProviderTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NeighborProviderTest.java @@ -25,9 +25,9 @@ public class NeighborProviderTest { @Test public void canGetTraitRelationshipsFromStrings() { StringShape stringShape = StringShape.builder() - .id(ShapeId.from("smithy.example#Foo")) - .addTrait(new SensitiveTrait()) - .build(); + .id(ShapeId.from("smithy.example#Foo")) + .addTrait(new SensitiveTrait()) + .build(); Model model = Model.assembler().addShape(stringShape).assemble().unwrap(); NeighborProvider provider = NeighborProvider.of(model); @@ -41,8 +41,8 @@ public void canGetTraitRelationshipsFromStrings() { @Test public void canGetTraitRelationshipsFromShapeWithNoTraits() { StringShape stringShape = StringShape.builder() - .id(ShapeId.from("smithy.example#Foo")) - .build(); + .id(ShapeId.from("smithy.example#Foo")) + .build(); Model model = Model.assembler().addShape(stringShape).assemble().unwrap(); NeighborProvider provider = NeighborProvider.of(model); @@ -55,66 +55,66 @@ public void canGetTraitRelationshipsFromShapeWithNoTraits() { @ParameterizedTest @CsvSource( { - "One,Ref1", - "Two,Ref2", - "Three,Ref3", - "Four,Ref4", - "Five,Ref5", - "Six,Ref6", - "Seven,Ref7", - "Eight,Ref8", - "Nine,Ref9", - "Ten,Ref10", - "Eleven,Ref11", - "Twelve,Ref12", - "Thirteen,Ref13", - "Fourteen,Ref14" + "One,Ref1", + "Two,Ref2", + "Three,Ref3", + "Four,Ref4", + "Five,Ref5", + "Six,Ref6", + "Seven,Ref7", + "Eight,Ref8", + "Nine,Ref9", + "Ten,Ref10", + "Eleven,Ref11", + "Twelve,Ref12", + "Thirteen,Ref13", + "Fourteen,Ref14" } ) public void canGetIdRefRelationships(String shapeName, String referencedShapeName) { Model model = Model.assembler() - .addImport(getClass().getResource("idref-neighbors.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("idref-neighbors.smithy")) + .assemble() + .unwrap(); NeighborProvider provider = NeighborProvider.of(model); provider = NeighborProvider.withIdRefRelationships(model, provider); Shape shape = model.expectShape(ShapeId.fromParts("com.foo", shapeName)); Shape ref = model.expectShape(ShapeId.fromParts("com.foo", referencedShapeName)); List relationships = provider.getNeighbors(shape) - .stream() - .filter(relationship -> relationship.getRelationshipType().equals(RelationshipType.ID_REF)) - .collect(Collectors.toList()); + .stream() + .filter(relationship -> relationship.getRelationshipType().equals(RelationshipType.ID_REF)) + .collect(Collectors.toList()); assertThat( - relationships, - containsInAnyOrder( - equalTo(Relationship.create(shape, RelationshipType.ID_REF, ref)) - ) + relationships, + containsInAnyOrder( + equalTo(Relationship.create(shape, RelationshipType.ID_REF, ref)) + ) ); } @Test public void canGetIdRefRelationshipsThroughTraitDefs() { Model model = Model.assembler() - .addImport(getClass().getResource("idref-neighbors-in-trait-def.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("idref-neighbors-in-trait-def.smithy")) + .assemble() + .unwrap(); NeighborProvider provider = NeighborProvider.of(model); provider = NeighborProvider.withIdRefRelationships(model, provider); Shape shape = model.expectShape(ShapeId.from("com.foo#WithRefStructTrait")); Shape ref = model.expectShape(ShapeId.from("com.foo#OtherReferenced")); List relationships = provider.getNeighbors(shape) - .stream() - .filter(relationship -> relationship.getRelationshipType().equals(RelationshipType.ID_REF)) - .collect(Collectors.toList()); + .stream() + .filter(relationship -> relationship.getRelationshipType().equals(RelationshipType.ID_REF)) + .collect(Collectors.toList()); Shape shape1 = model.expectShape(ShapeId.from("com.foo#refStruct$other")); Shape ref1 = model.expectShape(ShapeId.from("com.foo#ReferencedInTraitDef")); List relationships1 = provider.getNeighbors(shape1) - .stream() - .filter(relationship -> relationship.getRelationshipType().equals(RelationshipType.ID_REF)) - .collect(Collectors.toList()); + .stream() + .filter(relationship -> relationship.getRelationshipType().equals(RelationshipType.ID_REF)) + .collect(Collectors.toList()); assertThat(relationships, containsInAnyOrder(Relationship.create(shape, RelationshipType.ID_REF, ref))); assertThat(relationships1, containsInAnyOrder(Relationship.create(shape1, RelationshipType.ID_REF, ref1))); @@ -123,24 +123,24 @@ public void canGetIdRefRelationshipsThroughTraitDefs() { @Test public void canGetIdRefRelationshipsThroughMultipleLevelsOfIdRef() { Model model = Model.assembler() - .addImport(getClass().getResource("idref-neighbors-multiple-levels.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("idref-neighbors-multiple-levels.smithy")) + .assemble() + .unwrap(); NeighborProvider provider = NeighborProvider.of(model); provider = NeighborProvider.withIdRefRelationships(model, provider); Shape shape = model.expectShape(ShapeId.from("com.foo#WithIdRef")); Shape ref = model.expectShape(ShapeId.from("com.foo#Referenced")); List relationships = provider.getNeighbors(shape) - .stream() - .filter(relationship -> relationship.getRelationshipType().equals(RelationshipType.ID_REF)) - .collect(Collectors.toList()); + .stream() + .filter(relationship -> relationship.getRelationshipType().equals(RelationshipType.ID_REF)) + .collect(Collectors.toList()); Shape shape1 = model.expectShape(ShapeId.from("com.foo#ConnectedThroughReferenced")); Shape ref1 = model.expectShape(ShapeId.from("com.foo#AnotherReferenced")); List relationships1 = provider.getNeighbors(shape1) - .stream() - .filter(relationship -> relationship.getRelationshipType().equals(RelationshipType.ID_REF)) - .collect(Collectors.toList()); + .stream() + .filter(relationship -> relationship.getRelationshipType().equals(RelationshipType.ID_REF)) + .collect(Collectors.toList()); assertThat(relationships, containsInAnyOrder(Relationship.create(shape, RelationshipType.ID_REF, ref))); assertThat(relationships1, containsInAnyOrder(Relationship.create(shape1, RelationshipType.ID_REF, ref1))); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NeighborVisitorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NeighborVisitorTest.java index a4fd1f52918..675b9213830 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NeighborVisitorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NeighborVisitorTest.java @@ -55,20 +55,20 @@ public void blobShape() { @Test public void findsMixinsOnThingsOtherThanStructAndUnion() { Shape blobMixin = BlobShape.builder() - .id("smithy.example#BlobMixin") - .addTrait(MixinTrait.builder().build()) - .build(); + .id("smithy.example#BlobMixin") + .addTrait(MixinTrait.builder().build()) + .build(); Shape shape = BlobShape.builder() - .id("ns.foo#name") - .addMixin(blobMixin) - .build(); + .id("ns.foo#name") + .addMixin(blobMixin) + .build(); Model model = Model.builder().addShapes(shape, blobMixin).build(); NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = shape.accept(neighborVisitor); List types = relationships.stream() - .map(Relationship::getRelationshipType) - .collect(Collectors.toList()); + .map(Relationship::getRelationshipType) + .collect(Collectors.toList()); assertThat(types, contains(RelationshipType.MIXIN)); } @@ -97,9 +97,9 @@ public void stringShape() { public void enumShape() { EnumShape.Builder builder = (EnumShape.Builder) EnumShape.builder().id("ns.foo#name"); EnumShape shape = builder - .addMember("foo", "bar") - .addMember("baz", "bam") - .build(); + .addMember("foo", "bar") + .addMember("baz", "bam") + .build(); MemberShape member1Target = shape.getMember("foo").get(); MemberShape member2Target = shape.getMember("baz").get(); Model model = Model.builder().addShape(shape).build(); @@ -107,11 +107,11 @@ public void enumShape() { List relationships = shape.accept(neighborVisitor); assertThat( - relationships, - containsInAnyOrder( - Relationship.create(shape, RelationshipType.ENUM_MEMBER, member1Target), - Relationship.create(shape, RelationshipType.ENUM_MEMBER, member2Target) - ) + relationships, + containsInAnyOrder( + Relationship.create(shape, RelationshipType.ENUM_MEMBER, member1Target), + Relationship.create(shape, RelationshipType.ENUM_MEMBER, member2Target) + ) ); } @@ -119,9 +119,9 @@ public void enumShape() { public void intEnumShape() { IntEnumShape.Builder builder = (IntEnumShape.Builder) IntEnumShape.builder().id("ns.foo#name"); IntEnumShape shape = builder - .addMember("foo", 1) - .addMember("baz", 2) - .build(); + .addMember("foo", 1) + .addMember("baz", 2) + .build(); MemberShape member1Target = shape.getMember("foo").get(); MemberShape member2Target = shape.getMember("baz").get(); Model model = Model.builder().addShape(shape).build(); @@ -129,11 +129,11 @@ public void intEnumShape() { List relationships = shape.accept(neighborVisitor); assertThat( - relationships, - containsInAnyOrder( - Relationship.create(shape, RelationshipType.INT_ENUM_MEMBER, member1Target), - Relationship.create(shape, RelationshipType.INT_ENUM_MEMBER, member2Target) - ) + relationships, + containsInAnyOrder( + Relationship.create(shape, RelationshipType.INT_ENUM_MEMBER, member1Target), + Relationship.create(shape, RelationshipType.INT_ENUM_MEMBER, member2Target) + ) ); } @@ -151,9 +151,9 @@ public void timestampShape() { public void listShape() { Shape string = StringShape.builder().id("ns.foo#String").build(); ListShape list = ListShape.builder() - .id("ns.foo#name") - .member(string.getId()) - .build(); + .id("ns.foo#name") + .member(string.getId()) + .build(); Model model = Model.builder().addShape(list).addShape(string).build(); NeighborVisitor neighborVisitor = new NeighborVisitor(model); MemberShape memberTarget = list.getMember(); @@ -167,20 +167,20 @@ public void mapShape() { Shape key = StringShape.builder().id("ns.foo#KeyString").build(); Shape value = StringShape.builder().id("ns.foo#ValueString").build(); MapShape map = MapShape.builder() - .id("ns.foo#name") - .key( - MemberShape.builder() - .id("ns.foo#name$key") - .target(key.getId()) - .build() - ) - .value( - MemberShape.builder() - .id("ns.foo#name$value") - .target(value.getId()) - .build() - ) - .build(); + .id("ns.foo#name") + .key( + MemberShape.builder() + .id("ns.foo#name$key") + .target(key.getId()) + .build() + ) + .value( + MemberShape.builder() + .id("ns.foo#name$value") + .target(value.getId()) + .build() + ) + .build(); MemberShape keyTarget = map.getKey(); MemberShape valueTarget = map.getValue(); Model model = Model.builder().addShape(map).addShape(key).addShape(value).build(); @@ -188,11 +188,11 @@ public void mapShape() { List relationships = map.accept(neighborVisitor); assertThat( - relationships, - containsInAnyOrder( - Relationship.create(map, RelationshipType.MAP_KEY, keyTarget), - Relationship.create(map, RelationshipType.MAP_VALUE, valueTarget) - ) + relationships, + containsInAnyOrder( + Relationship.create(map, RelationshipType.MAP_KEY, keyTarget), + Relationship.create(map, RelationshipType.MAP_VALUE, valueTarget) + ) ); } @@ -201,38 +201,38 @@ public void structureShape() { Shape memberShape1 = StringShape.builder().id("ns.foo#M1String").build(); Shape memberShape2 = StringShape.builder().id("ns.foo#M2String").build(); StructureShape struct = StructureShape.builder() - .id("ns.foo#name") - .addMember( - MemberShape.builder() - .id("ns.foo#name$m1") - .target(memberShape1.getId()) - .build() - ) - .addMember( - MemberShape.builder() - .id("ns.foo#name$m2") - .target(memberShape2.getId()) - .build() - ) - .build(); + .id("ns.foo#name") + .addMember( + MemberShape.builder() + .id("ns.foo#name$m1") + .target(memberShape1.getId()) + .build() + ) + .addMember( + MemberShape.builder() + .id("ns.foo#name$m2") + .target(memberShape2.getId()) + .build() + ) + .build(); MemberShape member1Target = struct.getMember("m1").get(); MemberShape member2Target = struct.getMember("m2").get(); Model model = Model.builder() - .addShape(struct) - .addShape(memberShape1) - .addShape(memberShape2) - .addShape(member1Target) - .addShape(member2Target) - .build(); + .addShape(struct) + .addShape(memberShape1) + .addShape(memberShape2) + .addShape(member1Target) + .addShape(member2Target) + .build(); NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = struct.accept(neighborVisitor); assertThat( - relationships, - containsInAnyOrder( - Relationship.create(struct, RelationshipType.STRUCTURE_MEMBER, member1Target), - Relationship.create(struct, RelationshipType.STRUCTURE_MEMBER, member2Target) - ) + relationships, + containsInAnyOrder( + Relationship.create(struct, RelationshipType.STRUCTURE_MEMBER, member1Target), + Relationship.create(struct, RelationshipType.STRUCTURE_MEMBER, member2Target) + ) ); } @@ -240,31 +240,31 @@ public void structureShape() { public void structureShapeWithMixins() { StringShape string = StringShape.builder().id("smithy.example#String").build(); StructureShape mixin1 = StructureShape.builder() - .id("smithy.example#TestMixin1") - .addTrait(MixinTrait.builder().build()) - .addTrait(DeprecatedTrait.builder().build()) - .addMember("a", string.getId(), builder -> builder.addTrait(new SensitiveTrait())) - .addMember("b", string.getId()) - .build(); + .id("smithy.example#TestMixin1") + .addTrait(MixinTrait.builder().build()) + .addTrait(DeprecatedTrait.builder().build()) + .addMember("a", string.getId(), builder -> builder.addTrait(new SensitiveTrait())) + .addMember("b", string.getId()) + .build(); StructureShape concrete = StructureShape.builder() - .id("smithy.example#Concrete") - .addTrait(new SensitiveTrait()) - .addMixin(mixin1) - .addMember("b", string.getId(), builder -> builder.addTrait(DeprecatedTrait.builder().build())) - .addMember("c", string.getId()) - .build(); + .id("smithy.example#Concrete") + .addTrait(new SensitiveTrait()) + .addMixin(mixin1) + .addMember("b", string.getId(), builder -> builder.addTrait(DeprecatedTrait.builder().build())) + .addMember("c", string.getId()) + .build(); Model model = Model.builder().addShapes(mixin1, concrete, string).build(); NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = concrete.accept(neighborVisitor); assertThat( - relationships, - containsInAnyOrder( - Relationship.create(concrete, RelationshipType.STRUCTURE_MEMBER, concrete.getMember("a").get()), - Relationship.create(concrete, RelationshipType.STRUCTURE_MEMBER, concrete.getMember("b").get()), - Relationship.create(concrete, RelationshipType.STRUCTURE_MEMBER, concrete.getMember("c").get()), - Relationship.create(concrete, RelationshipType.MIXIN, mixin1) - ) + relationships, + containsInAnyOrder( + Relationship.create(concrete, RelationshipType.STRUCTURE_MEMBER, concrete.getMember("a").get()), + Relationship.create(concrete, RelationshipType.STRUCTURE_MEMBER, concrete.getMember("b").get()), + Relationship.create(concrete, RelationshipType.STRUCTURE_MEMBER, concrete.getMember("c").get()), + Relationship.create(concrete, RelationshipType.MIXIN, mixin1) + ) ); } @@ -273,160 +273,160 @@ public void unionShape() { Shape variant1Shape = StringShape.builder().id("ns.foo#V1String").build(); Shape variant2Shape = StringShape.builder().id("ns.foo#V2String").build(); UnionShape union = UnionShape.builder() - .id("ns.foo#name") - .addMember( - MemberShape.builder() - .id("ns.foo#name$tag1") - .target(variant1Shape.getId()) - .build() - ) - .addMember( - MemberShape.builder() - .id("ns.foo#name$tag2") - .target(variant2Shape.getId()) - .build() - ) - .build(); + .id("ns.foo#name") + .addMember( + MemberShape.builder() + .id("ns.foo#name$tag1") + .target(variant1Shape.getId()) + .build() + ) + .addMember( + MemberShape.builder() + .id("ns.foo#name$tag2") + .target(variant2Shape.getId()) + .build() + ) + .build(); MemberShape v1Target = union.getMember("tag1").get(); MemberShape v2Target = union.getMember("tag2").get(); Model model = Model.builder() - .addShape(union) - .addShape(variant1Shape) - .addShape(variant2Shape) - .addShape(v1Target) - .addShape(v2Target) - .build(); + .addShape(union) + .addShape(variant1Shape) + .addShape(variant2Shape) + .addShape(v1Target) + .addShape(v2Target) + .build(); NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = union.accept(neighborVisitor); assertThat( - relationships, - containsInAnyOrder( - Relationship.create(union, RelationshipType.UNION_MEMBER, v1Target), - Relationship.create(union, RelationshipType.UNION_MEMBER, v2Target) - ) + relationships, + containsInAnyOrder( + Relationship.create(union, RelationshipType.UNION_MEMBER, v1Target), + Relationship.create(union, RelationshipType.UNION_MEMBER, v2Target) + ) ); } @Test public void serviceShape() { ServiceShape service = ServiceShape.builder() - .id("ns.foo#Svc") - .version("2017-01-17") - .addOperation("ns.foo#Operation") - .addResource("ns.foo#Resource") - .build(); + .id("ns.foo#Svc") + .version("2017-01-17") + .addOperation("ns.foo#Operation") + .addResource("ns.foo#Resource") + .build(); OperationShape operationShape = OperationShape.builder().id("ns.foo#Operation").build(); ResourceShape resourceShape = ResourceShape.builder().id("ns.foo#Resource").build(); Model model = Model.builder() - .addShapes(service, resourceShape, operationShape) - .build(); + .addShapes(service, resourceShape, operationShape) + .build(); NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = service.accept(neighborVisitor); assertThat( - relationships, - containsInAnyOrder( - Relationship.create(service, RelationshipType.RESOURCE, resourceShape), - Relationship.create(service, RelationshipType.OPERATION, operationShape) - ) + relationships, + containsInAnyOrder( + Relationship.create(service, RelationshipType.RESOURCE, resourceShape), + Relationship.create(service, RelationshipType.OPERATION, operationShape) + ) ); } @Test public void serviceErrors() { ServiceShape service = ServiceShape.builder() - .id("ns.foo#Svc") - .version("2017-01-17") - .addError("ns.foo#Common1") - .build(); + .id("ns.foo#Svc") + .version("2017-01-17") + .addError("ns.foo#Common1") + .build(); StructureShape errorShape = StructureShape.builder() - .id("ns.foo#Common1") - .addTrait(new ErrorTrait("client")) - .build(); + .id("ns.foo#Common1") + .addTrait(new ErrorTrait("client")) + .build(); Model model = Model.builder().addShapes(service, errorShape).build(); NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = service.accept(neighborVisitor); assertThat( - relationships, - contains( - Relationship.create(service, RelationshipType.ERROR, errorShape) - ) + relationships, + contains( + Relationship.create(service, RelationshipType.ERROR, errorShape) + ) ); } @Test public void resourceShape() { ServiceShape parent = ServiceShape.builder() - .id("ns.foo#Svc") - .version("2017-01-17") - .addResource("ns.foo#Resource") - .build(); + .id("ns.foo#Svc") + .version("2017-01-17") + .addResource("ns.foo#Resource") + .build(); ResourceShape resource = ResourceShape.builder() - .id("ns.foo#Resource") - .addIdentifier("id", "ns.foo#ResourceIdentifier") - .addProperty("fooProperty", "ns.foo#ResourceProperty") - .put(ShapeId.from("ns.foo#Put")) - .create(ShapeId.from("ns.foo#Create")) - .read(ShapeId.from("ns.foo#Get")) - .update(ShapeId.from("ns.foo#Update")) - .delete(ShapeId.from("ns.foo#Delete")) - .list(ShapeId.from("ns.foo#List")) - .addOperation("ns.foo#Named") - .addCollectionOperation("ns.foo#GenericCollection") - .addResource("ns.foo#Child1") - .build(); + .id("ns.foo#Resource") + .addIdentifier("id", "ns.foo#ResourceIdentifier") + .addProperty("fooProperty", "ns.foo#ResourceProperty") + .put(ShapeId.from("ns.foo#Put")) + .create(ShapeId.from("ns.foo#Create")) + .read(ShapeId.from("ns.foo#Get")) + .update(ShapeId.from("ns.foo#Update")) + .delete(ShapeId.from("ns.foo#Delete")) + .list(ShapeId.from("ns.foo#List")) + .addOperation("ns.foo#Named") + .addCollectionOperation("ns.foo#GenericCollection") + .addResource("ns.foo#Child1") + .build(); StringShape identifier = StringShape.builder().id("ns.foo#ResourceIdentifier").build(); StringShape property = StringShape.builder().id("ns.foo#ResourceProperty").build(); OperationShape createOperation = OperationShape.builder().id("ns.foo#Create").build(); OperationShape getOperation = OperationShape.builder() - .id("ns.foo#Get") - .addTrait(new ReadonlyTrait()) - .build(); + .id("ns.foo#Get") + .addTrait(new ReadonlyTrait()) + .build(); OperationShape updateOperation = OperationShape.builder().id("ns.foo#Update").build(); OperationShape deleteOperation = OperationShape.builder() - .id("ns.foo#Delete") - .addTrait(new IdempotentTrait()) - .build(); + .id("ns.foo#Delete") + .addTrait(new IdempotentTrait()) + .build(); OperationShape listOperation = OperationShape.builder() - .id("ns.foo#List") - .addTrait(new ReadonlyTrait()) - .build(); + .id("ns.foo#List") + .addTrait(new ReadonlyTrait()) + .build(); OperationShape namedOperation = OperationShape.builder() - .id("ns.foo#Named") - .build(); + .id("ns.foo#Named") + .build(); OperationShape collectionOperation = OperationShape.builder() - .id("ns.foo#GenericCollection") - .build(); + .id("ns.foo#GenericCollection") + .build(); OperationShape putOperation = OperationShape.builder() - .id("ns.foo#Put") - .build(); + .id("ns.foo#Put") + .build(); ResourceShape child1 = ResourceShape.builder().id("ns.foo#Child1").addResource("ns.foo#Child2").build(); ResourceShape child2 = ResourceShape.builder().id("ns.foo#Child2").build(); Model model = Model.builder() - .addShapes(parent, resource, identifier, property, child1, child2) - .addShapes(createOperation, getOperation, updateOperation, deleteOperation, listOperation) - .addShapes(namedOperation, collectionOperation, putOperation) - .build(); + .addShapes(parent, resource, identifier, property, child1, child2) + .addShapes(createOperation, getOperation, updateOperation, deleteOperation, listOperation) + .addShapes(namedOperation, collectionOperation, putOperation) + .build(); NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = resource.accept(neighborVisitor); assertThat( - relationships, - containsInAnyOrder( - Relationship.create(resource, RelationshipType.IDENTIFIER, identifier), - Relationship.create(resource, RelationshipType.PROPERTY, property), - Relationship.create(resource, RelationshipType.CREATE, createOperation), - Relationship.create(resource, RelationshipType.READ, getOperation), - Relationship.create(resource, RelationshipType.UPDATE, updateOperation), - Relationship.create(resource, RelationshipType.DELETE, deleteOperation), - Relationship.create(resource, RelationshipType.LIST, listOperation), - Relationship.create(resource, RelationshipType.PUT, putOperation), - Relationship.create(resource, RelationshipType.COLLECTION_OPERATION, collectionOperation), - Relationship.create(resource, RelationshipType.OPERATION, namedOperation), - Relationship.create(resource, RelationshipType.RESOURCE, child1) - ) + relationships, + containsInAnyOrder( + Relationship.create(resource, RelationshipType.IDENTIFIER, identifier), + Relationship.create(resource, RelationshipType.PROPERTY, property), + Relationship.create(resource, RelationshipType.CREATE, createOperation), + Relationship.create(resource, RelationshipType.READ, getOperation), + Relationship.create(resource, RelationshipType.UPDATE, updateOperation), + Relationship.create(resource, RelationshipType.DELETE, deleteOperation), + Relationship.create(resource, RelationshipType.LIST, listOperation), + Relationship.create(resource, RelationshipType.PUT, putOperation), + Relationship.create(resource, RelationshipType.COLLECTION_OPERATION, collectionOperation), + Relationship.create(resource, RelationshipType.OPERATION, namedOperation), + Relationship.create(resource, RelationshipType.RESOURCE, child1) + ) ); } @@ -436,22 +436,22 @@ public void operationShape() { StructureShape input = StructureShape.builder().id("ns.foo#Input").build(); StructureShape output = StructureShape.builder().id("ns.foo#Output").build(); OperationShape method = OperationShape.builder() - .id("ns.foo#Foo") - .input(input.getId()) - .output(output.getId()) - .addError(error.getId()) - .build(); + .id("ns.foo#Foo") + .input(input.getId()) + .output(output.getId()) + .addError(error.getId()) + .build(); Model model = Model.builder().addShapes(method, input, output, error).build(); NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = method.accept(neighborVisitor); assertThat( - relationships, - containsInAnyOrder( - Relationship.create(method, RelationshipType.INPUT, input), - Relationship.create(method, RelationshipType.OUTPUT, output), - Relationship.create(method, RelationshipType.ERROR, error) - ) + relationships, + containsInAnyOrder( + Relationship.create(method, RelationshipType.INPUT, input), + Relationship.create(method, RelationshipType.OUTPUT, output), + Relationship.create(method, RelationshipType.ERROR, error) + ) ); } @@ -468,14 +468,14 @@ public void operationShapeDoesNotEmitUnitRelationships() { @Test public void unitTypeRelsNotEmittedFromEnums() { MemberShape member = MemberShape.builder() - .id("smithy.api#Example$foo") - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("hi").build()) - .build(); + .id("smithy.api#Example$foo") + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("hi").build()) + .build(); EnumShape enumShape = EnumShape.builder() - .id("smithy.api#Example") - .addMember(member) - .build(); + .id("smithy.api#Example") + .addMember(member) + .build(); Model model = Model.builder().addShapes(enumShape).build(); NeighborVisitor neighborVisitor = new NeighborVisitor(model); @@ -485,65 +485,73 @@ public void unitTypeRelsNotEmittedFromEnums() { assertThat(enumRelationships, hasSize(1)); assertThat( - enumRelationships.get(0), - equalTo(Relationship.create(enumShape, RelationshipType.ENUM_MEMBER, member)) + enumRelationships.get(0), + equalTo(Relationship.create(enumShape, RelationshipType.ENUM_MEMBER, member)) ); assertThat(enumMemberRelationships, hasSize(1)); assertThat( - enumMemberRelationships.get(0), - equalTo(Relationship.create(member, RelationshipType.MEMBER_CONTAINER, enumShape)) + enumMemberRelationships.get(0), + equalTo(Relationship.create(member, RelationshipType.MEMBER_CONTAINER, enumShape)) ); } @Test public void memberShape() { StringShape string = StringShape.builder() - .id("ns.foo#String") - .build(); + .id("ns.foo#String") + .build(); MemberShape target = MemberShape.builder() - .id("ns.foo#List$member") - .target(string.getId()) - .build(); + .id("ns.foo#List$member") + .target(string.getId()) + .build(); ListShape list = ListShape.builder() - .id("ns.foo#List") - .member(target) - .build(); + .id("ns.foo#List") + .member(target) + .build(); Model model = Model.builder() - .addShape(target) - .addShape(string) - .addShape(list) - .build(); + .addShape(target) + .addShape(string) + .addShape(list) + .build(); NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = target.accept(neighborVisitor); assertThat( - relationships, - containsInAnyOrder( - Relationship.create(target, RelationshipType.MEMBER_CONTAINER, list), - Relationship.create(target, RelationshipType.MEMBER_TARGET, string) - ) + relationships, + containsInAnyOrder( + Relationship.create(target, RelationshipType.MEMBER_CONTAINER, list), + Relationship.create(target, RelationshipType.MEMBER_TARGET, string) + ) ); } @Test public void returnsEmptyOnMissingShape() { MemberShape target = MemberShape.builder() - .id("ns.foo#List$member") - .target("ns.foo#String") - .build(); + .id("ns.foo#List$member") + .target("ns.foo#String") + .build(); Model model = Model.builder() - .addShape(target) - .build(); + .addShape(target) + .build(); NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = target.accept(neighborVisitor); assertThat( - relationships, - containsInAnyOrder( - Relationship.createInvalid(target, RelationshipType.MEMBER_CONTAINER, ShapeId.from("ns.foo#List")), - Relationship.createInvalid(target, RelationshipType.MEMBER_TARGET, ShapeId.from("ns.foo#String")) - ) + relationships, + containsInAnyOrder( + Relationship.createInvalid( + target, + RelationshipType.MEMBER_CONTAINER, + ShapeId.from("ns.foo#List") + ), + Relationship.createInvalid( + target, + RelationshipType.MEMBER_TARGET, + ShapeId.from("ns.foo#String") + ) + ) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NodeQueryTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NodeQueryTest.java index 79c440899f0..34b594286c6 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NodeQueryTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NodeQueryTest.java @@ -164,32 +164,32 @@ public void eachQueryExecuteOnResultOfPreviousQuery() { Node element2 = Node.from("{}"); Node element3 = Node.from("element3"); Node obj = Node.objectNode() - .withMember( - "foo", - Node.objectNode() - .withMember("arr1", Node.arrayNode(element1)) - .withMember("arr2", Node.arrayNode(element2)) - .withMember("arr3", Node.arrayNode(element3)) - ); + .withMember( + "foo", + Node.objectNode() + .withMember("arr1", Node.arrayNode(element1)) + .withMember("arr2", Node.arrayNode(element2)) + .withMember("arr3", Node.arrayNode(element3)) + ); Node node = Node.arrayNode(obj, obj); Collection result = new NodeQuery() - .anyElement() - .member("foo") - .anyMember() - .anyElement() - .execute(node); + .anyElement() + .member("foo") + .anyMember() + .anyElement() + .execute(node); assertThat( - result, - containsInAnyOrder( - element1, - element2, - element3, - element1, - element2, - element3 - ) + result, + containsInAnyOrder( + element1, + element2, + element3, + element1, + element2, + element3 + ) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/UnreferencedShapesTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/UnreferencedShapesTest.java index bcb56528b68..aaefb0a7f81 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/UnreferencedShapesTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/UnreferencedShapesTest.java @@ -27,9 +27,9 @@ public class UnreferencedShapesTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(UnreferencedShapesTest.class.getResource("unreferenced-test.json")) - .assemble() - .unwrap(); + .addImport(UnreferencedShapesTest.class.getResource("unreferenced-test.json")) + .assemble() + .unwrap(); } @AfterAll @@ -49,11 +49,11 @@ public void doesNotCheckShapesThatAreTraitShapes() { UnreferencedShapes unref = new UnreferencedShapes(); assertThat( - unref.compute(model).stream().map(Shape::getId).collect(Collectors.toSet()), - containsInAnyOrder( - ShapeId.from("ns.foo#Exclude1"), - ShapeId.from("ns.foo#Exclude2") - ) + unref.compute(model).stream().map(Shape::getId).collect(Collectors.toSet()), + containsInAnyOrder( + ShapeId.from("ns.foo#Exclude1"), + ShapeId.from("ns.foo#Exclude2") + ) ); } @@ -69,17 +69,17 @@ public void doesNotIgnorePrivateShapes() { private Model createPrivateShapeModel(ShapeId id) { return Model.assembler() - .addShape(StringShape.builder().id(id).addTrait(new PrivateTrait()).build()) - .assemble() - .unwrap(); + .addShape(StringShape.builder().id(id).addTrait(new PrivateTrait()).build()) + .assemble() + .unwrap(); } @Test public void checksShapeReferencesThroughIdRef() { Model m = Model.assembler() - .addImport(getClass().getResource("idref-neighbors.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("idref-neighbors.smithy")) + .assemble() + .unwrap(); Set shapes = new UnreferencedShapes().compute(m); @@ -89,19 +89,19 @@ public void checksShapeReferencesThroughIdRef() { @Test public void doesNotCheckShapeReferencesThroughIdRefOnUnconnectedShapes() { Model m = Model.assembler() - .addImport(getClass().getResource("idref-neighbors-unconnected.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("idref-neighbors-unconnected.smithy")) + .assemble() + .unwrap(); Set ids = new UnreferencedShapes().compute(m).stream().map(Shape::getId).collect(Collectors.toSet()); assertThat( - ids, - containsInAnyOrder( - ShapeId.from("com.foo#WithTrait"), - ShapeId.from("com.foo#Referenced"), - ShapeId.from("com.foo#Unconnected") - ) + ids, + containsInAnyOrder( + ShapeId.from("com.foo#WithTrait"), + ShapeId.from("com.foo#Referenced"), + ShapeId.from("com.foo#Unconnected") + ) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitionsTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitionsTest.java index 244d5deee64..b0a2483a73c 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitionsTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitionsTest.java @@ -15,14 +15,14 @@ public class UnreferencedTraitDefinitionsTest { @Test public void shouldReportDefinitionsForTraitsThatAreNotUsed() { Model model = Model.assembler() - .addImport(UnreferencedTraitDefinitionsTest.class.getResource("unreferenced-test.json")) - .assemble() - .unwrap(); + .addImport(UnreferencedTraitDefinitionsTest.class.getResource("unreferenced-test.json")) + .assemble() + .unwrap(); UnreferencedTraitDefinitions unreferencedTraitDefinitions = new UnreferencedTraitDefinitions(); assertThat( - unreferencedTraitDefinitions.compute(model), - contains(model.expectShape(ShapeId.from("ns.foo#quux"))) + unreferencedTraitDefinitions.compute(model), + contains(model.expectShape(ShapeId.from("ns.foo#quux"))) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/WalkerTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/WalkerTest.java index c821edd5929..7e9f09aaaac 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/WalkerTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/WalkerTest.java @@ -26,38 +26,38 @@ public class WalkerTest { public void getASetOfConnectedShapes() { // list-of-map-of-string-to-string StringShape string = StringShape.builder() - .id("ns.foo#String") - .build(); + .id("ns.foo#String") + .build(); MemberShape key = MemberShape.builder() - .id("ns.foo#Map$key") - .target(string.getId()) - .build(); + .id("ns.foo#Map$key") + .target(string.getId()) + .build(); MemberShape value = MemberShape.builder() - .id("ns.foo#Map$value") - .target(string.getId()) - .build(); + .id("ns.foo#Map$value") + .target(string.getId()) + .build(); MapShape map = MapShape.builder() - .id("ns.foo#Map") - .key(key) - .value(value) - .build(); + .id("ns.foo#Map") + .key(key) + .value(value) + .build(); MemberShape listMember = MemberShape.builder() - .id("ns.foo#List$member") - .target(map.getId()) - .build(); + .id("ns.foo#List$member") + .target(map.getId()) + .build(); ListShape list = ListShape.builder() - .id("ns.foo#List") - .member(listMember) - .build(); + .id("ns.foo#List") + .member(listMember) + .build(); Walker walker = new Walker( - Model.builder() - .addShape(list) - .addShape(listMember) - .addShape(map) - .addShape(key) - .addShape(value) - .addShape(string) - .build() + Model.builder() + .addShape(list) + .addShape(listMember) + .addShape(map) + .addShape(key) + .addShape(value) + .addShape(string) + .build() ); Set connected = walker.walkShapes(listMember); @@ -68,38 +68,38 @@ public void getASetOfConnectedShapes() { public void supportsCycles() { // list-of-map-of-string-to-list-of-... StringShape string = StringShape.builder() - .id("ns.foo#String") - .build(); + .id("ns.foo#String") + .build(); MemberShape key = MemberShape.builder() - .id("ns.foo#Map$key") - .target(string.getId()) - .build(); + .id("ns.foo#Map$key") + .target(string.getId()) + .build(); MemberShape value = MemberShape.builder() - .id("ns.foo#Map$value") - .target("ns.foo#List") // cycles here - .build(); + .id("ns.foo#Map$value") + .target("ns.foo#List") // cycles here + .build(); MapShape map = MapShape.builder() - .id("ns.foo#Map") - .key(key) - .value(value) - .build(); + .id("ns.foo#Map") + .key(key) + .value(value) + .build(); MemberShape listMember = MemberShape.builder() - .id("ns.foo#List$member") - .target(map.getId()) - .build(); + .id("ns.foo#List$member") + .target(map.getId()) + .build(); ListShape list = ListShape.builder() - .id("ns.foo#List") - .member(listMember) - .build(); + .id("ns.foo#List") + .member(listMember) + .build(); Walker walker = new Walker( - Model.builder() - .addShape(list) - .addShape(listMember) - .addShape(map) - .addShape(key) - .addShape(value) - .addShape(string) - .build() + Model.builder() + .addShape(list) + .addShape(listMember) + .addShape(map) + .addShape(key) + .addShape(value) + .addShape(string) + .build() ); Set connected = walker.walkShapes(listMember); @@ -109,12 +109,12 @@ public void supportsCycles() { @Test public void yieldsUniqueShapes() { OperationShape readOperation = OperationShape.builder() - .id("smithy.example#Read") - .build(); + .id("smithy.example#Read") + .build(); ResourceShape resource = ResourceShape.builder() - .id("smithy.example#Resource") - .read(readOperation.getId()) - .build(); + .id("smithy.example#Resource") + .read(readOperation.getId()) + .build(); Model model = Model.builder().addShapes(readOperation, resource).build(); Walker walker = new Walker(model); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/node/ArrayNodeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/node/ArrayNodeTest.java index 428c95df253..f87999af66e 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/node/ArrayNodeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/node/ArrayNodeTest.java @@ -77,8 +77,8 @@ public void withValue() { StringNode strNode1 = Node.from("abc"); StringNode strNode2 = Node.from("abc"); ArrayNode node = Node.arrayNode() - .withValue(strNode1) - .withValue(strNode2); + .withValue(strNode1) + .withValue(strNode2); assertThat(node.size(), is(2)); assertSame(strNode1, node.get(0).get()); @@ -144,12 +144,12 @@ public void mergesNodes() { assertThat(result.getSourceLocation(), equalTo(sloc)); assertThat( - result.getElements() - .stream() - .map(Node::expectStringNode) - .map(StringNode::getValue) - .collect(Collectors.toList()), - contains("a", "b", "c", "d") + result.getElements() + .stream() + .map(Node::expectStringNode) + .map(StringNode::getValue) + .collect(Collectors.toList()), + contains("a", "b", "c", "d") ); } @@ -175,12 +175,12 @@ public void getsValuesUsingMapper() { List list = array.getElementsAs(StringNode::getValue); assertThat( - array.getElements() - .stream() - .map(Node::expectStringNode) - .map(StringNode::getValue) - .collect(Collectors.toList()), - equalTo(list) + array.getElements() + .stream() + .map(Node::expectStringNode) + .map(StringNode::getValue) + .collect(Collectors.toList()), + equalTo(list) ); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/node/DefaultNodeWriterTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/node/DefaultNodeWriterTest.java index d0910308346..0ed2e72b4d1 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/node/DefaultNodeWriterTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/node/DefaultNodeWriterTest.java @@ -23,79 +23,79 @@ public void testWriter(Node node, String expected) { public static Collection data() { return Arrays.asList( - new Object[][]{ - {Node.from(true), "true"}, - {Node.from("foo"), "\"foo\""}, - {Node.from(10), "10"}, - {Node.from(10.0), "10.0"}, - {Node.parse("10.2"), "10.2"}, - {new NullNode(SourceLocation.none()), "null"}, - { - new ArrayNode( - Arrays.asList(Node.from(1), Node.from(2)), - SourceLocation.none() - ), - String.format("[%n 1,%n 2%n]")}, - { - Node.objectNode() - .withMember("foo", Node.from("foo")) - .withMember("baz", Node.from(1)) - .withMember( - "bar", - Node.objectNode() - .withMember( - "qux", - Node.arrayNode() - .withValue(Node.from("ipsum")) + new Object[][]{ + {Node.from(true), "true"}, + {Node.from("foo"), "\"foo\""}, + {Node.from(10), "10"}, + {Node.from(10.0), "10.0"}, + {Node.parse("10.2"), "10.2"}, + {new NullNode(SourceLocation.none()), "null"}, + { + new ArrayNode( + Arrays.asList(Node.from(1), Node.from(2)), + SourceLocation.none() + ), + String.format("[%n 1,%n 2%n]")}, + { + Node.objectNode() + .withMember("foo", Node.from("foo")) + .withMember("baz", Node.from(1)) + .withMember( + "bar", + Node.objectNode() + .withMember( + "qux", + Node.arrayNode() + .withValue(Node.from("ipsum")) + ) + ), + String.format( + "{%n" + + " \"foo\": \"foo\",%n" + + " \"baz\": 1,%n" + + " \"bar\": {%n" + + " \"qux\": [%n" + + " \"ipsum\"%n" + + " ]%n" + + " }%n" + + "}" ) - ), - String.format( - "{%n" - + " \"foo\": \"foo\",%n" - + " \"baz\": 1,%n" - + " \"bar\": {%n" - + " \"qux\": [%n" - + " \"ipsum\"%n" - + " ]%n" - + " }%n" - + "}" - ) - }, - { - Node.objectNode() - .withMember( - "foo", - Node.objectNode() - .withMember( - "bar", - Node.arrayNode() - .withValue(Node.from("baz")) + }, + { + Node.objectNode() + .withMember( + "foo", + Node.objectNode() + .withMember( + "bar", + Node.arrayNode() + .withValue(Node.from("baz")) + ) + ) + .withMember( + "bam", + Node.arrayNode() + .withValue( + Node.objectNode() + .withMember("abc", Node.from(123)) + ) + ), + String.format( + "{%n" + + " \"foo\": {%n" + + " \"bar\": [%n" + + " \"baz\"%n" + + " ]%n" + + " },%n" + + " \"bam\": [%n" + + " {%n" + + " \"abc\": 123%n" + + " }%n" + + " ]%n" + + "}" ) - ) - .withMember( - "bam", - Node.arrayNode() - .withValue( - Node.objectNode() - .withMember("abc", Node.from(123)) - ) - ), - String.format( - "{%n" - + " \"foo\": {%n" - + " \"bar\": [%n" - + " \"baz\"%n" - + " ]%n" - + " },%n" - + " \"bam\": [%n" - + " {%n" - + " \"abc\": 123%n" - + " }%n" - + " ]%n" - + "}" - ) + } } - } ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeDiffTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeDiffTest.java index e7a1575ace9..be22f3ef435 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeDiffTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeDiffTest.java @@ -14,12 +14,12 @@ public class NodeDiffTest { @Test public void detectsNodeTypeDifference() { assertThat( - NodeDiff.diff(Node.nullNode(), Node.from(true)), - contains( - String.format( - "[]: Expected node of type `boolean` but found node of type `null`.%n%nExpected: true%n%n Found: null" + NodeDiff.diff(Node.nullNode(), Node.from(true)), + contains( + String.format( + "[]: Expected node of type `boolean` but found node of type `null`.%n%nExpected: true%n%n Found: null" + ) ) - ) ); } @@ -27,8 +27,8 @@ public void detectsNodeTypeDifference() { public void comparesBooleans() { assertThat(NodeDiff.diff(Node.from(true), Node.from(true)), empty()); assertThat( - NodeDiff.diff(Node.from(true), Node.from(false)), - contains("[]: Expected `false` but found `true`") + NodeDiff.diff(Node.from(true), Node.from(false)), + contains("[]: Expected `false` but found `true`") ); } @@ -36,8 +36,8 @@ public void comparesBooleans() { public void comparesNumbers() { assertThat(NodeDiff.diff(Node.from(10), Node.from(10)), empty()); assertThat( - NodeDiff.diff(Node.from(2), Node.from(1)), - contains("[]: Expected `1` but found `2`") + NodeDiff.diff(Node.from(2), Node.from(1)), + contains("[]: Expected `1` but found `2`") ); } @@ -45,8 +45,8 @@ public void comparesNumbers() { public void comparesStrings() { assertThat(NodeDiff.diff(Node.from("pop"), Node.from("pop")), empty()); assertThat( - NodeDiff.diff(Node.from("foo"), Node.from("bar")), - contains("[]: Expected `\"bar\"` but found `\"foo\"`") + NodeDiff.diff(Node.from("foo"), Node.from("bar")), + contains("[]: Expected `\"bar\"` but found `\"foo\"`") ); } @@ -61,8 +61,8 @@ public void detectsExtraListElements() { Node expected = Node.fromStrings("snap", "crackle"); assertThat( - NodeDiff.diff(actual, expected), - contains("[]: Extra element encountered in list at position 2: \"pop\"") + NodeDiff.diff(actual, expected), + contains("[]: Extra element encountered in list at position 2: \"pop\"") ); } @@ -72,8 +72,8 @@ public void detectsMissingListElements() { Node expected = Node.fromStrings("snap", "crackle", "pop"); assertThat( - NodeDiff.diff(actual, expected), - contains("[]: Expected element (position 2) not encountered in list: \"pop\"") + NodeDiff.diff(actual, expected), + contains("[]: Expected element (position 2) not encountered in list: \"pop\"") ); } @@ -83,11 +83,11 @@ public void detectsDifferentListElements() { Node expected = Node.fromStrings("snap", "crackle", "pop"); assertThat( - NodeDiff.diff(actual, expected), - contains( - "[[0]]: Expected `\"snap\"` but found `\"fizz\"`", - "[[1]]: Expected `\"crackle\"` but found `\"buzz\"`" - ) + NodeDiff.diff(actual, expected), + contains( + "[[0]]: Expected `\"snap\"` but found `\"fizz\"`", + "[[1]]: Expected `\"crackle\"` but found `\"buzz\"`" + ) ); } @@ -97,12 +97,12 @@ public void reportsMultipleDifferenceTypesOnLists() { Node expected = Node.fromStrings("snap", "crackle", "pop"); assertThat( - NodeDiff.diff(actual, expected), - contains( - "[[0]]: Expected `\"snap\"` but found `\"fizz\"`", - "[[1]]: Expected `\"crackle\"` but found `\"buzz\"`", - "[]: Expected element (position 2) not encountered in list: \"pop\"" - ) + NodeDiff.diff(actual, expected), + contains( + "[[0]]: Expected `\"snap\"` but found `\"fizz\"`", + "[[1]]: Expected `\"crackle\"` but found `\"buzz\"`", + "[]: Expected element (position 2) not encountered in list: \"pop\"" + ) ); } @@ -112,8 +112,8 @@ public void detectsExtraObjectKeys() { Node expected = Node.objectNode().withMember("foo", Node.from("bar")); assertThat( - NodeDiff.diff(actual, expected), - contains("[]: Extra key `fizz` encountered with content: \"buzz\"") + NodeDiff.diff(actual, expected), + contains("[]: Extra key `fizz` encountered with content: \"buzz\"") ); } @@ -123,8 +123,8 @@ public void detectsMissingObjectKeys() { Node expected = Node.objectNode().withMember("foo", Node.from("bar")).withMember("fizz", Node.from("buzz")); assertThat( - NodeDiff.diff(actual, expected), - contains("[]: Expected key `fizz` not present.") + NodeDiff.diff(actual, expected), + contains("[]: Expected key `fizz` not present.") ); } @@ -134,8 +134,8 @@ public void detectsDifferentObjectKeys() { Node expected = Node.objectNode().withMember("foo", Node.from("baz")); assertThat( - NodeDiff.diff(actual, expected), - contains("[/foo]: Expected `\"baz\"` but found `\"bar\"`") + NodeDiff.diff(actual, expected), + contains("[/foo]: Expected `\"baz\"` but found `\"bar\"`") ); } @@ -145,59 +145,62 @@ public void reportsMultipleDifferenceTypesOnObjects() { Node expected = Node.objectNode().withMember("foo", Node.from("baz")).withMember("fizz", Node.from("buzz")); assertThat( - NodeDiff.diff(actual, expected), - contains( - "[/foo]: Expected `\"baz\"` but found `\"bar\"`", - "[]: Expected key `fizz` not present.", - "[]: Extra key `snap` encountered with content: \"crackle\"" - ) + NodeDiff.diff(actual, expected), + contains( + "[/foo]: Expected `\"baz\"` but found `\"bar\"`", + "[]: Expected key `fizz` not present.", + "[]: Extra key `snap` encountered with content: \"crackle\"" + ) ); } @Test public void detectsDeeplyNestedDifferences() { Node expected = Node.objectNode() - .withMember( - "foo", - Node.arrayNode() - .withValue(Node.from("bar")) - .withValue( - Node.objectNode() - .withMember( - "baz", - Node.arrayNode() - .withValue(Node.from("snap")) - .withValue( + .withMember( + "foo", + Node.arrayNode() + .withValue(Node.from("bar")) + .withValue( Node.objectNode() - .withMember("crackle", Node.from("pop")) - ) - ) - ) - ); + .withMember( + "baz", + Node.arrayNode() + .withValue(Node.from("snap")) + .withValue( + Node.objectNode() + .withMember("crackle", Node.from("pop")) + ) + ) + ) + ); Node actual = Node.objectNode() - .withMember( - "foo", - Node.arrayNode() - .withValue(Node.from("bar")) - .withValue( - Node.objectNode() - .withMember( - "baz", - Node.arrayNode() - .withValue(Node.from("snap")) - .withValue( + .withMember( + "foo", + Node.arrayNode() + .withValue(Node.from("bar")) + .withValue( Node.objectNode() - .withMember("crackle", Node.from("quux")) - ) - ) - ) - ); + .withMember( + "baz", + Node.arrayNode() + .withValue(Node.from("snap")) + .withValue( + Node.objectNode() + .withMember( + "crackle", + Node.from("quux") + ) + ) + ) + ) + ); assertThat( - NodeDiff.diff(actual, expected), - contains( - "[/foo[1]/baz[1]/crackle]: Expected `\"pop\"` but found `\"quux\"`" - ) + NodeDiff.diff(actual, expected), + contains( + "[/foo[1]/baz[1]/crackle]: Expected `\"pop\"` but found `\"quux\"`" + ) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeMapperTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeMapperTest.java index 9969aecd130..84647e5d5fc 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeMapperTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeMapperTest.java @@ -147,48 +147,48 @@ public void serializesKitchenSink() { Node result = mapper.serialize(new KitchenSink()); Node.assertEquals( - result, - Node.parse( - "{\n" - + " \"long\": 4,\n" - + " \"float\": 5.0,\n" - + " \"string\": \"string\",\n" - + " \"shapeId\": \"foo.baz#Bar\",\n" - + " \"double\": 6.0,\n" - + " \"boolean\": true,\n" - + " \"enum\": \"array\",\n" - + " \"int\": 3,\n" - + " \"presentString\": \"present\",\n" - + " \"short\": 2,\n" - + " \"boolean2\": true,\n" - + " \"byte\": 1,\n" - + " \"map\": {\n" - + " \"b\": [\n" - + " \"2\",\n" - + " \"3\"\n" - + " ],\n" - + " \"a\": [\n" - + " \"1\",\n" - + " \"2\"\n" - + " ]\n" - + " },\n" - + " \"complexList\": [\n" - + " [\n" - + " \"a\",\n" - + " \"b\"\n" - + " ],\n" - + " [\n" - + " \"c\",\n" - + " \"d\"\n" - + " ]\n" - + " ],\n" - + " \"falseBoolean\": false,\n" - + " \"stringIterable\": [\n" - + " \"foo\",\n" - + " \"baz\"\n" - + " ]\n" - + "}" - ) + result, + Node.parse( + "{\n" + + " \"long\": 4,\n" + + " \"float\": 5.0,\n" + + " \"string\": \"string\",\n" + + " \"shapeId\": \"foo.baz#Bar\",\n" + + " \"double\": 6.0,\n" + + " \"boolean\": true,\n" + + " \"enum\": \"array\",\n" + + " \"int\": 3,\n" + + " \"presentString\": \"present\",\n" + + " \"short\": 2,\n" + + " \"boolean2\": true,\n" + + " \"byte\": 1,\n" + + " \"map\": {\n" + + " \"b\": [\n" + + " \"2\",\n" + + " \"3\"\n" + + " ],\n" + + " \"a\": [\n" + + " \"1\",\n" + + " \"2\"\n" + + " ]\n" + + " },\n" + + " \"complexList\": [\n" + + " [\n" + + " \"a\",\n" + + " \"b\"\n" + + " ],\n" + + " [\n" + + " \"c\",\n" + + " \"d\"\n" + + " ]\n" + + " ],\n" + + " \"falseBoolean\": false,\n" + + " \"stringIterable\": [\n" + + " \"foo\",\n" + + " \"baz\"\n" + + " ]\n" + + "}" + ) ); } @@ -375,16 +375,16 @@ public void catchesAndShowsErrorsWhenSerializing() { NodeMapper mapper = new NodeMapper(); NodeSerializationException e = Assertions.assertThrows( - NodeSerializationException.class, - () -> mapper.serialize(tc) + NodeSerializationException.class, + () -> mapper.serialize(tc) ); assertThat( - e.getMessage(), - equalTo( - "Error serializing `throws` field of software.amazon.smithy.model.node.NodeMapperTest$ThrowingClass " - + "using getThrows(): Nope!" - ) + e.getMessage(), + equalTo( + "Error serializing `throws` field of software.amazon.smithy.model.node.NodeMapperTest$ThrowingClass " + + "using getThrows(): Nope!" + ) ); } @@ -471,10 +471,10 @@ public void deserializesWithFromNodeFactoryAndUnknownPropertiesWithWarning() { Baz result = new NodeMapper().deserialize(baz, Baz.class); assertThat( - result.toString(), - equalTo( - "Baz{foo='hi', baz=10, inner=Baz{foo='null', baz=0, inner=Baz{foo='null', baz=0, inner=null}}}" - ) + result.toString(), + equalTo( + "Baz{foo='hi', baz=10, inner=Baz{foo='null', baz=0, inner=Baz{foo='null', baz=0, inner=null}}}" + ) ); } @@ -485,16 +485,16 @@ public void deserializesWithFromNodeFactoryAndUnknownPropertiesWithFailure() { mapper.setWhenMissingSetter(NodeMapper.WhenMissing.FAIL); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserialize(baz, Baz.class) + NodeDeserializationException.class, + () -> mapper.deserialize(baz, Baz.class) ); assertThat( - e.getMessage(), - equalTo( - "Deserialization error at (/inner/inner) [1, 59]: unable to find setter method for `noSetter!` on " - + "software.amazon.smithy.model.node.NodeMapperTest$Baz" - ) + e.getMessage(), + equalTo( + "Deserialization error at (/inner/inner) [1, 59]: unable to find setter method for `noSetter!` on " + + "software.amazon.smithy.model.node.NodeMapperTest$Baz" + ) ); } @@ -515,16 +515,16 @@ public void detectsWhenFromNodeFails() { NodeMapper mapper = new NodeMapper(); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserialize(Node.objectNode(), FailingFromNode.class) + NodeDeserializationException.class, + () -> mapper.deserialize(Node.objectNode(), FailingFromNode.class) ); assertThat( - e.getMessage(), - equalTo( - "Deserialization error at (/): unable to create software.amazon.smithy.model.node.NodeMapperTest$FailingFromNode " - + "from {}: Unable to deserialize Node using fromNode method: nope" - ) + e.getMessage(), + equalTo( + "Deserialization error at (/): unable to create software.amazon.smithy.model.node.NodeMapperTest$FailingFromNode " + + "from {}: Unable to deserialize Node using fromNode method: nope" + ) ); } @@ -541,16 +541,16 @@ public void ignoresFromNodeThatDoNotReturnSameType() { mapper.setWhenMissingSetter(NodeMapper.WhenMissing.FAIL); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserialize(value, BadTypeFromNode.class) + NodeDeserializationException.class, + () -> mapper.deserialize(value, BadTypeFromNode.class) ); assertThat( - e.getMessage(), - equalTo( - "Deserialization error at (/): unable to find setter method for `foo` on " - + "software.amazon.smithy.model.node.NodeMapperTest$BadTypeFromNode" - ) + e.getMessage(), + equalTo( + "Deserialization error at (/): unable to find setter method for `foo` on " + + "software.amazon.smithy.model.node.NodeMapperTest$BadTypeFromNode" + ) ); } @@ -567,16 +567,16 @@ public void ignoresFromNodeThatIsNotStatic() { mapper.setWhenMissingSetter(NodeMapper.WhenMissing.FAIL); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserialize(value, NonStaticFromNode.class) + NodeDeserializationException.class, + () -> mapper.deserialize(value, NonStaticFromNode.class) ); assertThat( - e.getMessage(), - equalTo( - "Deserialization error at (/): unable to find setter method for `foo` on " - + "software.amazon.smithy.model.node.NodeMapperTest$NonStaticFromNode" - ) + e.getMessage(), + equalTo( + "Deserialization error at (/): unable to find setter method for `foo` on " + + "software.amazon.smithy.model.node.NodeMapperTest$NonStaticFromNode" + ) ); } @@ -593,16 +593,16 @@ public void ignoresFromNodeThatDoesNotAcceptNode() { mapper.setWhenMissingSetter(NodeMapper.WhenMissing.FAIL); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserialize(value, NonNodeFromNode.class) + NodeDeserializationException.class, + () -> mapper.deserialize(value, NonNodeFromNode.class) ); assertThat( - e.getMessage(), - equalTo( - "Deserialization error at (/): unable to find setter method for `foo` on " - + "software.amazon.smithy.model.node.NodeMapperTest$NonNodeFromNode" - ) + e.getMessage(), + equalTo( + "Deserialization error at (/): unable to find setter method for `foo` on " + + "software.amazon.smithy.model.node.NodeMapperTest$NonNodeFromNode" + ) ); } @@ -619,16 +619,16 @@ public void ignoresFromNodeThatAcceptsMultipleArgs() { mapper.setWhenMissingSetter(NodeMapper.WhenMissing.FAIL); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserialize(value, MultiArgFromNode.class) + NodeDeserializationException.class, + () -> mapper.deserialize(value, MultiArgFromNode.class) ); assertThat( - e.getMessage(), - equalTo( - "Deserialization error at (/): unable to find setter method for `foo` on " - + "software.amazon.smithy.model.node.NodeMapperTest$MultiArgFromNode" - ) + e.getMessage(), + equalTo( + "Deserialization error at (/): unable to find setter method for `foo` on " + + "software.amazon.smithy.model.node.NodeMapperTest$MultiArgFromNode" + ) ); } @@ -661,17 +661,17 @@ public void deserializesWithBuilderCatchesErrorCreatingBuilder() { NodeMapper mapper = new NodeMapper(); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserialize(value, ClassThrowingBuilderMethod.class) + NodeDeserializationException.class, + () -> mapper.deserialize(value, ClassThrowingBuilderMethod.class) ); assertThat( - e.getMessage(), - startsWith( - "Deserialization error at (/): unable to create " - + "software.amazon.smithy.model.node.NodeMapperTest$ClassThrowingBuilderMethod from " - + "{\"foo\":\"foo\"}: Unable to deserialize Node using a builder: nope" - ) + e.getMessage(), + startsWith( + "Deserialization error at (/): unable to create " + + "software.amazon.smithy.model.node.NodeMapperTest$ClassThrowingBuilderMethod from " + + "{\"foo\":\"foo\"}: Unable to deserialize Node using a builder: nope" + ) ); } @@ -695,16 +695,16 @@ public void ignoresNonStaticBuilderMethod() { mapper.setWhenMissingSetter(NodeMapper.WhenMissing.FAIL); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserialize(value, NonStaticBuilderMethod.class) + NodeDeserializationException.class, + () -> mapper.deserialize(value, NonStaticBuilderMethod.class) ); assertThat( - e.getMessage(), - equalTo( - "Deserialization error at (/) [1, 9]: unable to find setter method for `foo` on " - + "software.amazon.smithy.model.node.NodeMapperTest$NonStaticBuilderMethod" - ) + e.getMessage(), + equalTo( + "Deserialization error at (/) [1, 9]: unable to find setter method for `foo` on " + + "software.amazon.smithy.model.node.NodeMapperTest$NonStaticBuilderMethod" + ) ); } @@ -728,16 +728,16 @@ public void ignoresBuilderThatReturnsDifferentType() { mapper.setWhenMissingSetter(NodeMapper.WhenMissing.FAIL); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserialize(value, BuilderBadReturnType.class) + NodeDeserializationException.class, + () -> mapper.deserialize(value, BuilderBadReturnType.class) ); assertThat( - e.getMessage(), - equalTo( - "Deserialization error at (/) [1, 9]: unable to find setter method for `foo` on " - + "software.amazon.smithy.model.node.NodeMapperTest$BuilderBadReturnType" - ) + e.getMessage(), + equalTo( + "Deserialization error at (/) [1, 9]: unable to find setter method for `foo` on " + + "software.amazon.smithy.model.node.NodeMapperTest$BuilderBadReturnType" + ) ); } @@ -839,8 +839,8 @@ public void deserializesListWithSpecificMember() { Node value = Node.parse("[true, false, true]"); assertThat( - new NodeMapper().deserializeCollection(value, List.class, Boolean.class), - contains(true, false, true) + new NodeMapper().deserializeCollection(value, List.class, Boolean.class), + contains(true, false, true) ); } @@ -944,11 +944,11 @@ public void cannotDeserializeNonCollectionArrays() { }); assertThat( - e.getMessage(), - equalTo( - "Deserialization error at (/): unable to create " - + "software.amazon.smithy.model.node.NodeMapperTest$PojoWithCollection from [\"a\",\"b\"]" - ) + e.getMessage(), + equalTo( + "Deserialization error at (/): unable to create " + + "software.amazon.smithy.model.node.NodeMapperTest$PojoWithCollection from [\"a\",\"b\"]" + ) ); } @@ -961,12 +961,12 @@ public void detectsWhenUnableToAddToCollection() { }); assertThat( - e.getMessage(), - equalTo( - "Deserialization error at (/): unable to create " - + "software.amazon.smithy.model.node.NodeMapperTest$ThrowingCollectionOnAdd from [\"a\",\"b\"]: " - + "Cannot add a" - ) + e.getMessage(), + equalTo( + "Deserialization error at (/): unable to create " + + "software.amazon.smithy.model.node.NodeMapperTest$ThrowingCollectionOnAdd from [\"a\",\"b\"]: " + + "Cannot add a" + ) ); } @@ -986,12 +986,12 @@ public void detectsWhenUnableToCreateCollection() { }); assertThat( - e.getMessage(), - equalTo( - "Deserialization error at (/): unable to create " - + "software.amazon.smithy.model.node.NodeMapperTest$ThrowingCollectionOnCreate from [\"a\",\"b\"]: " - + "Unable to deserialize array into Collection: nope" - ) + e.getMessage(), + equalTo( + "Deserialization error at (/): unable to create " + + "software.amazon.smithy.model.node.NodeMapperTest$ThrowingCollectionOnCreate from [\"a\",\"b\"]: " + + "Unable to deserialize array into Collection: nope" + ) ); } @@ -1010,11 +1010,11 @@ public void detectsWhenUnableToFindCollectionConstructorAndContinues() { }); assertThat( - e.getMessage(), - equalTo( - "Unable to find a zero-arg constructor for Collection " - + "software.amazon.smithy.model.node.NodeMapperTest$NonZeroArgConstructorCollection" - ) + e.getMessage(), + equalTo( + "Unable to find a zero-arg constructor for Collection " + + "software.amazon.smithy.model.node.NodeMapperTest$NonZeroArgConstructorCollection" + ) ); } @@ -1135,16 +1135,16 @@ public void throwsWhenMapDoesNotHaveZeroArgConstructor() { NodeMapper mapper = new NodeMapper(); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserialize(object, NoZeroArgCtorMap.class) + NodeDeserializationException.class, + () -> mapper.deserialize(object, NoZeroArgCtorMap.class) ); assertThat( - e.getMessage(), - equalTo( - "Unable to find a zero-arg constructor for Map " - + "software.amazon.smithy.model.node.NodeMapperTest$NoZeroArgCtorMap" - ) + e.getMessage(), + equalTo( + "Unable to find a zero-arg constructor for Map " + + "software.amazon.smithy.model.node.NodeMapperTest$NoZeroArgCtorMap" + ) ); } @@ -1158,16 +1158,16 @@ public void throwsWhenMapCtorThrows() { NodeMapper mapper = new NodeMapper(); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserialize(object, BadMapCtor.class) + NodeDeserializationException.class, + () -> mapper.deserialize(object, BadMapCtor.class) ); assertThat( - e.getMessage(), - equalTo( - "Deserialization error at (/): unable to create software.amazon.smithy.model.node.NodeMapperTest$BadMapCtor " - + "from {}: Unable to deserialize object into Map: nope" - ) + e.getMessage(), + equalTo( + "Deserialization error at (/): unable to create software.amazon.smithy.model.node.NodeMapperTest$BadMapCtor " + + "from {}: Unable to deserialize object into Map: nope" + ) ); } @@ -1183,15 +1183,15 @@ public void dealsWithInvalidMapTypes() { NodeMapper mapper = new NodeMapper(); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserializeMap(object, Map.class, String.class) + NodeDeserializationException.class, + () -> mapper.deserializeMap(object, Map.class, String.class) ); assertThat( - e.getMessage(), - equalTo( - "Deserialization error at (/foo): unable to create java.lang.String from 10" - ) + e.getMessage(), + equalTo( + "Deserialization error at (/foo): unable to create java.lang.String from 10" + ) ); } @@ -1298,10 +1298,10 @@ public void setInner(Baz inner) { @Override public String toString() { return "Baz{" + - "foo='" + foo + '\'' + - ", baz=" + baz + - ", inner=" + inner + - '}'; + "foo='" + foo + '\'' + + ", baz=" + baz + + ", inner=" + inner + + '}'; } } @@ -1310,16 +1310,16 @@ public void detectsWhenBeanCtorFails() { NodeMapper mapper = new NodeMapper(); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserialize(Node.objectNode(), FailingCtor.class) + NodeDeserializationException.class, + () -> mapper.deserialize(Node.objectNode(), FailingCtor.class) ); assertThat( - e.getMessage(), - equalTo( - "Deserialization error at (/): unable to create software.amazon.smithy.model.node.NodeMapperTest$FailingCtor " - + "from {}: Unable to deserialize a Node when invoking target constructor: nope" - ) + e.getMessage(), + equalTo( + "Deserialization error at (/): unable to create software.amazon.smithy.model.node.NodeMapperTest$FailingCtor " + + "from {}: Unable to deserialize a Node when invoking target constructor: nope" + ) ); } @@ -1346,15 +1346,15 @@ public void deserializesIntoValueAndCatchesErrors() { Baz baz = new Baz(); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserializeInto(node, baz) + NodeDeserializationException.class, + () -> mapper.deserializeInto(node, baz) ); assertThat( - e.getMessage(), - startsWith( - "Deserialization error at (/foo): unable to create java.lang.String from true" - ) + e.getMessage(), + startsWith( + "Deserialization error at (/foo): unable to create java.lang.String from true" + ) ); } @@ -1402,9 +1402,9 @@ public void serializesSourceLocationFromValue() { public void serializesSourceLocationFromTrait() { SourceLocation sourceLocation = new SourceLocation("/foo/baz"); SourceLocationBearerTrait trait = SourceLocationBearerTrait.builder() - .sourceLocation(sourceLocation) - .foo("foo") - .build(); + .sourceLocation(sourceLocation) + .foo("foo") + .build(); Node result = trait.createNode(); assertThat(result.expectObjectNode().getStringMap(), hasKey("foo")); @@ -1436,7 +1436,7 @@ public String getFoo() { } private static class SourceLocationBearerTrait extends AbstractTrait implements - ToSmithyBuilder { + ToSmithyBuilder { public static final ShapeId ID = ShapeId.from("smithy.test#sourceLocationBearer"); private final String foo; @@ -1494,16 +1494,16 @@ public void throwsWhenUnableToDeserializeEnums() { NodeMapper mapper = new NodeMapper(); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserialize(Node.from("invalid"), FooEnum.class) + NodeDeserializationException.class, + () -> mapper.deserialize(Node.from("invalid"), FooEnum.class) ); assertThat( - e.getMessage(), - equalTo( - "Deserialization error at (/): unable to create software.amazon.smithy.model.node.NodeMapperTest$FooEnum " - + "from \"invalid\": Expected one of the following enum strings: [foo, Baz, BAR]" - ) + e.getMessage(), + equalTo( + "Deserialization error at (/): unable to create software.amazon.smithy.model.node.NodeMapperTest$FooEnum " + + "from \"invalid\": Expected one of the following enum strings: [foo, Baz, BAR]" + ) ); } @@ -1539,8 +1539,8 @@ public void failsWhenUnableToParsePattern() { Node input = Node.from("["); Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserialize(input, Pattern.class) + NodeDeserializationException.class, + () -> mapper.deserialize(input, Pattern.class) ); // Shy away from a specific message assertion in case the message ever changes between JDK versions. } @@ -1610,8 +1610,8 @@ public void doesNotSupportNonStaticInnerClasses() { NodeMapper mapper = new NodeMapper(); NodeDeserializationException e = Assertions.assertThrows( - NodeDeserializationException.class, - () -> mapper.deserialize(Node.objectNode(), NonStatic.class) + NodeDeserializationException.class, + () -> mapper.deserialize(Node.objectNode(), NonStatic.class) ); assertThat(e.getMessage(), containsString("Cannot create non-static inner class")); @@ -1623,9 +1623,9 @@ public final class NonStatic {} public void deserializesWithCamelCase() { NodeMapper mapper = new NodeMapper(); Node input = Node.objectNode() - .withMember("set.me.here", "hi1") - .withMember("set.Me.Here.too", "hi2") - .withMember("ignore..me", "hi3"); + .withMember("set.me.here", "hi1") + .withMember("set.Me.Here.too", "hi2") + .withMember("ignore..me", "hi3"); CamelCase result = mapper.deserialize(input, CamelCase.class); assertThat(result.getSetMeHere(), equalTo("hi1")); @@ -1667,12 +1667,12 @@ public void setIgnoreMe(String ignoreMe) { public void deserializesMapOfShapeIdToShapeType() { NodeMapper mapper = new NodeMapper(); Node input = Node.objectNode() - .withMember( - "shapeTypes", - Node.objectNode() - .withMember("smithy.example#A", "union") - .withMember("smithy.example#B", "string") - ); + .withMember( + "shapeTypes", + Node.objectNode() + .withMember("smithy.example#A", "union") + .withMember("smithy.example#B", "string") + ); ShapeIdMap result = mapper.deserialize(input, ShapeIdMap.class); assertThat(result.getShapeTypes().keySet().iterator().next(), instanceOf(ShapeId.class)); @@ -1700,27 +1700,27 @@ public Map getShapeTypes() { public void deserializesNestedGenericTypes() { NodeMapper mapper = new NodeMapper(); Node input = Node.objectNode() - .withMember( - "shapeTypes", - Node.objectNode() - .withMember( - "smithy.example#A", - Node.arrayNode( - Node.objectNode() - .withMember("smithy.example#B", "string") - ) - ) - ); + .withMember( + "shapeTypes", + Node.objectNode() + .withMember( + "smithy.example#A", + Node.arrayNode( + Node.objectNode() + .withMember("smithy.example#B", "string") + ) + ) + ); ComplicatedShapeIdMap result = mapper.deserialize(input, ComplicatedShapeIdMap.class); assertThat(result.getShapeTypes(), hasKey(ShapeId.from("smithy.example#A"))); assertThat( - result.getShapeTypes(), - hasValue( - ListUtils.of( - MapUtils.of(ShapeId.from("smithy.example#B"), ShapeType.STRING) + result.getShapeTypes(), + hasValue( + ListUtils.of( + MapUtils.of(ShapeId.from("smithy.example#B"), ShapeType.STRING) + ) ) - ) ); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeParserTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeParserTest.java index 6e6b2b06709..ccd07ad6fa7 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeParserTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeParserTest.java @@ -155,38 +155,38 @@ public void parsesObjectWithNestedObjects() { assertThat(result.getSourceLocation().getColumn(), is(1)); assertThat( - result.expectObjectNode() - .expectMember("foo") - .expectObjectNode() - .expectMember("bar") - .getSourceLocation() - .getLine(), - is(1) + result.expectObjectNode() + .expectMember("foo") + .expectObjectNode() + .expectMember("bar") + .getSourceLocation() + .getLine(), + is(1) ); assertThat( - result.expectObjectNode() - .expectMember("foo") - .expectObjectNode() - .expectMember("bar") - .getSourceLocation() - .getColumn(), - is(17) + result.expectObjectNode() + .expectMember("foo") + .expectObjectNode() + .expectMember("bar") + .getSourceLocation() + .getColumn(), + is(17) ); } @Test public void parsesJsonWithComments() { ObjectNode result = Node.parseJsonWithComments( - "// Skip leading comments...\n" - + " { // Hello!\n" - + "// Foo\n" - + "\"foo\"// baz bar //\n" - + ": // bam\n" - + "true // hi\n" - + "} // there\n" - + "// some more?\n" - + " // even more\n", - "/path/to/file.json" + "// Skip leading comments...\n" + + " { // Hello!\n" + + "// Foo\n" + + "\"foo\"// baz bar //\n" + + ": // bam\n" + + "true // hi\n" + + "} // there\n" + + "// some more?\n" + + " // even more\n", + "/path/to/file.json" ).expectObjectNode(); assertThat(Node.printJson(result), equalTo("{\"foo\":true}")); @@ -204,8 +204,8 @@ public void parsesJsonWithComments() { @Test public void parsesCommentsToEof() { Node result = Node.parseJsonWithComments( - "{\"foo\": true}\n" - + "// EOF" + "{\"foo\": true}\n" + + "// EOF" ); assertThat(Node.printJson(result), equalTo("{\"foo\":true}")); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeSerializerTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeSerializerTest.java index 20e814156df..cb95daf7d63 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeSerializerTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeSerializerTest.java @@ -16,82 +16,82 @@ public void serializesNodes() { assertThat(Node.printJson(node), equalTo("{\"foo\":\"bar\",\"baz\":true,\"bam\":false,\"boo\":10}")); assertThat( - Node.prettyPrintJson(node), - equalTo( - String.format( - "{%n" - + " \"foo\": \"bar\",%n" - + " \"baz\": true,%n" - + " \"bam\": false,%n" - + " \"boo\": 10%n" - + "}" + Node.prettyPrintJson(node), + equalTo( + String.format( + "{%n" + + " \"foo\": \"bar\",%n" + + " \"baz\": true,%n" + + " \"bam\": false,%n" + + " \"boo\": 10%n" + + "}" + ) ) - ) ); assertThat( - Node.prettyPrintJson(node, "\t"), - equalTo( - String.format( - "{%n" - + "\t\"foo\": \"bar\",%n" - + "\t\"baz\": true,%n" - + "\t\"bam\": false,%n" - + "\t\"boo\": 10%n" - + "}" + Node.prettyPrintJson(node, "\t"), + equalTo( + String.format( + "{%n" + + "\t\"foo\": \"bar\",%n" + + "\t\"baz\": true,%n" + + "\t\"bam\": false,%n" + + "\t\"boo\": 10%n" + + "}" + ) ) - ) ); } @Test public void serializesComplexNodes() { Node node = Node.parse( - "[\n" - + "{\"foo\": \"\uD83D\uDCA9\", \"baz\": true, \"bam\": false, \"boo\": 10},\n" - + "10,\n" - + "true,\n" - + "false,\n" - + "{},\n" - + "[],\n" - + "\"\",\n" - + "\" \",\n" - + "null,\n" - + "-1,\n" - + "-1.0\n" - + "]" + "[\n" + + "{\"foo\": \"\uD83D\uDCA9\", \"baz\": true, \"bam\": false, \"boo\": 10},\n" + + "10,\n" + + "true,\n" + + "false,\n" + + "{},\n" + + "[],\n" + + "\"\",\n" + + "\" \",\n" + + "null,\n" + + "-1,\n" + + "-1.0\n" + + "]" ); assertThat( - Node.printJson(node), - equalTo( - "[{\"foo\":\"\uD83D\uDCA9\",\"baz\":true,\"bam\":false," - + "\"boo\":10},10,true,false,{},[],\"\",\" \",null,-1,-1.0]" - ) + Node.printJson(node), + equalTo( + "[{\"foo\":\"\uD83D\uDCA9\",\"baz\":true,\"bam\":false," + + "\"boo\":10},10,true,false,{},[],\"\",\" \",null,-1,-1.0]" + ) ); assertThat( - Node.prettyPrintJson(node), - equalTo( - String.format( - "[%n" - + " {%n" - + " \"foo\": \"\uD83D\uDCA9\",%n" - + " \"baz\": true,%n" - + " \"bam\": false,%n" - + " \"boo\": 10%n" - + " },%n" - + " 10,%n" - + " true,%n" - + " false,%n" - + " {},%n" // optimized empty object - + " [],%n" // optimized empty array - + " \"\",%n" - + " \" \",%n" - + " null,%n" - + " -1,%n" - + " -1.0%n" - + "]" + Node.prettyPrintJson(node), + equalTo( + String.format( + "[%n" + + " {%n" + + " \"foo\": \"\uD83D\uDCA9\",%n" + + " \"baz\": true,%n" + + " \"bam\": false,%n" + + " \"boo\": 10%n" + + " },%n" + + " 10,%n" + + " true,%n" + + " false,%n" + + " {},%n" // optimized empty object + + " [],%n" // optimized empty array + + " \"\",%n" + + " \" \",%n" + + " null,%n" + + " -1,%n" + + " -1.0%n" + + "]" + ) ) - ) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeTest.java index 3d8cd828fa3..fac31948b35 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/node/NodeTest.java @@ -142,15 +142,15 @@ public void returnsEmptyOptionalWhenConverting() { @Test public void deepSortsNodes() { ObjectNode node = Node.parse("{\"foo\": [1, {\"baz\": 1, \"a\": 2}, true], \"bar\": false}") - .withDeepSortedKeys() - .expectObjectNode(); + .withDeepSortedKeys() + .expectObjectNode(); assertThat(node.getMembers().keySet(), contains(Node.from("bar"), Node.from("foo"))); assertThat(node.getMember("bar").get(), instanceOf(BooleanNode.class)); assertThat(node.getMember("foo").get().expectArrayNode().get(0).get(), instanceOf(NumberNode.class)); assertThat( - node.getMember("foo").get().expectArrayNode().get(1).get().expectObjectNode().getMembers().keySet(), - contains(Node.from("a"), Node.from("baz")) + node.getMember("foo").get().expectArrayNode().get(1).get().expectObjectNode().getMembers().keySet(), + contains(Node.from("a"), Node.from("baz")) ); assertThat(node.getMember("foo").get().expectArrayNode().get(2).get(), instanceOf(BooleanNode.class)); } @@ -158,21 +158,21 @@ public void deepSortsNodes() { @Test public void deepSortsNodesWithComparator() { ObjectNode node = Node.parse("{\"foo\": [1, {\"baz\": 1, \"a\": 2}, true], \"bar\": false}") - .withDeepSortedKeys(Comparator.comparing(StringNode::getValue).reversed()) - .expectObjectNode(); + .withDeepSortedKeys(Comparator.comparing(StringNode::getValue).reversed()) + .expectObjectNode(); assertThat(node.getMembers().keySet(), contains(Node.from("foo"), Node.from("bar"))); assertThat( - node.getMember("foo").get().expectArrayNode().get(1).get().expectObjectNode().getMembers().keySet(), - contains(Node.from("baz"), Node.from("a")) + node.getMember("foo").get().expectArrayNode().get(1).get().expectObjectNode().getMembers().keySet(), + contains(Node.from("baz"), Node.from("a")) ); } @Test public void prettyPrintsJson() { assertThat( - Node.prettyPrintJson(Node.parse("{\"foo\": true}")), - equalTo(String.format("{%n \"foo\": true%n}")) + Node.prettyPrintJson(Node.parse("{\"foo\": true}")), + equalTo(String.format("{%n \"foo\": true%n}")) ); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/node/ObjectNodeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/node/ObjectNodeTest.java index 4709f3d950c..126c7647365 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/node/ObjectNodeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/node/ObjectNodeTest.java @@ -32,13 +32,13 @@ public class ObjectNodeTest { private static final ObjectNode EXPECTATION_NODE = Node.objectNodeBuilder() - .withMember("array", Node.arrayNode()) - .withMember("boolean", Node.from(true)) - .withMember("number", Node.from(10)) - .withMember("null", Node.nullNode()) - .withMember("string", Node.from("hi")) - .withMember("object", Node.objectNode()) - .build(); + .withMember("array", Node.arrayNode()) + .withMember("boolean", Node.from(true)) + .withMember("number", Node.from(10)) + .withMember("null", Node.nullNode()) + .withMember("string", Node.from("hi")) + .withMember("object", Node.objectNode()) + .build(); @Test public void emptyNodeIsEmpty() { @@ -81,10 +81,10 @@ public void getMember() { @Test public void containsMember() { ObjectNode node = ObjectNode.objectNodeBuilder() - .withMember("foo", "bar") - .withMember("baz", true) - .withMember("bam", false) - .build(); + .withMember("foo", "bar") + .withMember("baz", true) + .withMember("bam", false) + .build(); assertTrue(node.containsMember("foo")); assertTrue(node.containsMember("baz")); @@ -94,14 +94,14 @@ public void containsMember() { @Test public void membersAreOrdered() { ObjectNode node = ObjectNode.objectNodeBuilder() - .withMember("foo", "bar") - .withMember("baz", true) - .withMember("bam", false) - .build(); + .withMember("foo", "bar") + .withMember("baz", true) + .withMember("bam", false) + .build(); assertThat( - node.getMembers().values(), - contains(node.expectMember("foo"), node.expectMember("baz"), node.expectBooleanMember("bam")) + node.getMembers().values(), + contains(node.expectMember("foo"), node.expectMember("baz"), node.expectBooleanMember("bam")) ); assertThat(node.getStringMap().keySet(), contains("foo", "baz", "bam")); } @@ -109,10 +109,10 @@ public void membersAreOrdered() { @Test public void getMemberByType() { ObjectNode node = ObjectNode.objectNodeBuilder() - .withMember("string", "bar") - .withMember("boolean", true) - .withMember("number", 10) - .build(); + .withMember("string", "bar") + .withMember("boolean", true) + .withMember("number", 10) + .build(); assertThat(node.getStringMemberOrDefault("string", "hi"), equalTo("bar")); assertThat(node.getStringMemberOrDefault("not-there", "hi"), equalTo("hi")); @@ -129,10 +129,10 @@ public void getMemberByType() { @Test public void getMembersByPrefix() { ObjectNode node = ObjectNode.objectNodeBuilder() - .withMember("a.1", 1) - .withMember("a.2", 2) - .withMember("bee", 3) - .build(); + .withMember("a.1", 1) + .withMember("a.2", 2) + .withMember("bee", 3) + .build(); assertThat(node.getMembersByPrefix("a.").keySet(), containsInAnyOrder("a.1", "a.2")); assertThat(node.getMembersByPrefix("b").keySet(), containsInAnyOrder("bee")); @@ -187,9 +187,9 @@ public void withoutMemberRemovesMember() { SourceLocation sourceLocation = new SourceLocation("filename", 0, 1); ObjectNode node = new ObjectNode(new HashMap<>(), sourceLocation); node = node - .withMember(Node.from("key-1"), Node.from("value-1")) - .withMember(Node.from("key-2"), Node.from("value-2")) - .withoutMember("key-1"); + .withMember(Node.from("key-1"), Node.from("value-1")) + .withMember(Node.from("key-2"), Node.from("value-2")) + .withoutMember("key-1"); assertEquals(1, node.size()); assertFalse(node.getMember("key-1").isPresent()); @@ -247,8 +247,8 @@ public void getSourceLocation() { public void checksIfAdditionalPropertiesArePresent() { ObjectNode node = new ObjectNode(new HashMap<>(), SourceLocation.none()); node.withMember(Node.from("a"), Node.from("value-1")) - .withMember(Node.from("b"), Node.from("value-2")) - .expectNoAdditionalProperties(Arrays.asList("a", "b", "c")); + .withMember(Node.from("b"), Node.from("value-2")) + .expectNoAdditionalProperties(Arrays.asList("a", "b", "c")); } @Test @@ -256,16 +256,16 @@ public void throwsWhenAdditionalPropertiesAreFound() { Throwable thrown = Assertions.assertThrows(ExpectationNotMetException.class, () -> { ObjectNode node = new ObjectNode(new HashMap<>(), SourceLocation.none()); node.withMember(Node.from("a"), Node.from("value-1")) - .withMember(Node.from("b"), Node.from("value-2")) - .expectNoAdditionalProperties(Arrays.asList("foo", "baz")); + .withMember(Node.from("b"), Node.from("value-2")) + .expectNoAdditionalProperties(Arrays.asList("foo", "baz")); }); assertThat( - thrown.getMessage(), - containsString( - "Expected an object with possible properties of `baz`, `foo`, but found " - + "additional properties: `a`, `b`" - ) + thrown.getMessage(), + containsString( + "Expected an object with possible properties of `baz`, `foo`, but found " + + "additional properties: `a`, `b`" + ) ); } @@ -273,8 +273,8 @@ public void throwsWhenAdditionalPropertiesAreFound() { public void doesNotThrowForAdditionalPropertiesWarning() { ObjectNode node = new ObjectNode(new HashMap<>(), SourceLocation.none()); node.withMember(Node.from("a"), Node.from("value-1")) - .withMember(Node.from("b"), Node.from("value-2")) - .warnIfAdditionalProperties(Arrays.asList("foo", "baz")); + .withMember(Node.from("b"), Node.from("value-2")) + .warnIfAdditionalProperties(Arrays.asList("foo", "baz")); } @Test @@ -447,38 +447,38 @@ public void failsWhenExpectedListOfString() { @Test public void successfullyConsumesTypes() { ObjectNode value = Node.objectNodeBuilder() - .withMember("number1", Node.from(1)) - .withMember("number2", Node.from(2)) - .withMember("string1", Node.from("a")) - .withMember("string2", Node.from("b")) - .withMember("boolean1", Node.from(true)) - .withMember("boolean2", Node.from(false)) - .withMember("array1", Node.fromNodes(Node.from("a"))) - .withMember("array2", Node.fromNodes(Node.from("b"))) - .withMember("null1", Node.nullNode()) - .withMember("object1", Node.objectNode()) - .withMember("object2", Node.objectNode()) - .withMember("mapper", Node.objectNode().withMember("a", Node.from("hello"))) - .build(); + .withMember("number1", Node.from(1)) + .withMember("number2", Node.from(2)) + .withMember("string1", Node.from("a")) + .withMember("string2", Node.from("b")) + .withMember("boolean1", Node.from(true)) + .withMember("boolean2", Node.from(false)) + .withMember("array1", Node.fromNodes(Node.from("a"))) + .withMember("array2", Node.fromNodes(Node.from("b"))) + .withMember("null1", Node.nullNode()) + .withMember("object1", Node.objectNode()) + .withMember("object2", Node.objectNode()) + .withMember("mapper", Node.objectNode().withMember("a", Node.from("hello"))) + .build(); Map result = new HashMap<>(); value.expectObjectNode() - .getNumberMember("number1", v -> result.put("number1", v)) - .expectNumberMember("number2", v -> result.put("number2", v)) - .getNumberMember("number3", v -> result.put("number3", v)) - .getStringMember("string1", v -> result.put("string1", v)) - .expectStringMember("string2", v -> result.put("string2", v)) - .getStringMember("string3", v -> result.put("string3", v)) - .getBooleanMember("boolean1", v -> result.put("boolean1", v)) - .expectBooleanMember("boolean2", v -> result.put("boolean2", v)) - .getBooleanMember("boolean3", v -> result.put("boolean3", v)) - .getArrayMember("array1", StringNode::getValue, v -> result.put("array1", v)) - .expectArrayMember("array2", StringNode::getValue, v -> result.put("array2", v)) - .getArrayMember("array3", StringNode::getValue, v -> result.put("array3", v)) - .getMember("null1", Node::expectNullNode, v -> result.put("null1", null)) - .getObjectMember("object1", v -> result.put("object1", v)) - .expectObjectMember("object2", v -> result.put("object2", v)) - .expectMember("mapper", Mapper::fromNode, v -> result.put("mapper", v)); + .getNumberMember("number1", v -> result.put("number1", v)) + .expectNumberMember("number2", v -> result.put("number2", v)) + .getNumberMember("number3", v -> result.put("number3", v)) + .getStringMember("string1", v -> result.put("string1", v)) + .expectStringMember("string2", v -> result.put("string2", v)) + .getStringMember("string3", v -> result.put("string3", v)) + .getBooleanMember("boolean1", v -> result.put("boolean1", v)) + .expectBooleanMember("boolean2", v -> result.put("boolean2", v)) + .getBooleanMember("boolean3", v -> result.put("boolean3", v)) + .getArrayMember("array1", StringNode::getValue, v -> result.put("array1", v)) + .expectArrayMember("array2", StringNode::getValue, v -> result.put("array2", v)) + .getArrayMember("array3", StringNode::getValue, v -> result.put("array3", v)) + .getMember("null1", Node::expectNullNode, v -> result.put("null1", null)) + .getObjectMember("object1", v -> result.put("object1", v)) + .expectObjectMember("object2", v -> result.put("object2", v)) + .expectMember("mapper", Mapper::fromNode, v -> result.put("mapper", v)); assertThat(result.keySet(), Matchers.equalTo(value.getStringMap().keySet())); assertThat(result.get("number1"), Matchers.equalTo(1)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/pattern/SmithyPatternTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/pattern/SmithyPatternTest.java index 71795512e01..807646dda7a 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/pattern/SmithyPatternTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/pattern/SmithyPatternTest.java @@ -35,18 +35,18 @@ private static List parser(String target) { public void parsesGreedyLabels() { String target = "/foo/baz/{bar+}"; SmithyPattern pattern = SmithyPattern.builder() - .segments(parser(target)) - .pattern(target) - .build(); + .segments(parser(target)) + .pattern(target) + .build(); assertThat(pattern.toString(), equalTo(target)); assertThat( - pattern.getGreedyLabel(), - equalTo( - Optional.of( - new Segment("bar", Segment.Type.GREEDY_LABEL) + pattern.getGreedyLabel(), + equalTo( + Optional.of( + new Segment("bar", Segment.Type.GREEDY_LABEL) + ) ) - ) ); } @@ -54,14 +54,14 @@ public void parsesGreedyLabels() { public void computesHashAndEquals() { String target1 = "/foo"; SmithyPattern pattern1 = SmithyPattern.builder() - .segments(parser(target1)) - .pattern(target1) - .build(); + .segments(parser(target1)) + .pattern(target1) + .build(); String target2 = "/foo/{baz+}/"; SmithyPattern pattern2 = SmithyPattern.builder() - .segments(parser(target2)) - .pattern(target2) - .build(); + .segments(parser(target2)) + .pattern(target2) + .build(); assertThat(pattern1, equalTo(pattern1)); assertThat(pattern1, not(equalTo(pattern2))); @@ -75,9 +75,9 @@ public void computesHashAndEquals() { public void labelsAreCaseInsensitive() { String target = "/foo/{baz}"; SmithyPattern pattern = SmithyPattern.builder() - .segments(parser(target)) - .pattern(target) - .build(); + .segments(parser(target)) + .pattern(target) + .build(); Segment segment = new Segment("baz", Segment.Type.LABEL); assertThat(pattern.getLabel("baz"), is(Optional.of(segment))); @@ -89,9 +89,9 @@ public void labelsMustNotIncludeEmptySegments() { Throwable thrown = Assertions.assertThrows(InvalidPatternException.class, () -> { String target = "//baz"; SmithyPattern.builder() - .segments(parser(target)) - .pattern(target) - .build(); + .segments(parser(target)) + .pattern(target) + .build(); }); assertThat(thrown.getMessage(), containsString("Segments must not be empty at index 1")); @@ -102,9 +102,9 @@ public void labelsMustNotBeRepeated() { Throwable thrown = Assertions.assertThrows(InvalidPatternException.class, () -> { String target = "/{foo}/{Foo}"; SmithyPattern.builder() - .segments(parser(target)) - .pattern(target) - .build(); + .segments(parser(target)) + .pattern(target) + .build(); }); assertThat(thrown.getMessage(), containsString("Label `Foo` is defined more than once")); @@ -115,10 +115,10 @@ public void restrictsGreedyLabels() { Throwable thrown = Assertions.assertThrows(InvalidPatternException.class, () -> { String target = "/foo/{baz+}"; SmithyPattern.builder() - .allowsGreedyLabels(false) - .segments(parser(target)) - .pattern(target) - .build(); + .allowsGreedyLabels(false) + .segments(parser(target)) + .pattern(target) + .build(); }); assertThat(thrown.getMessage(), containsString("Pattern must not contain a greedy label")); @@ -129,9 +129,9 @@ public void noEmptyLabels() { Throwable thrown = Assertions.assertThrows(InvalidPatternException.class, () -> { String target = "/a/{}"; SmithyPattern.builder() - .segments(parser(target)) - .pattern(target) - .build(); + .segments(parser(target)) + .pattern(target) + .build(); }); assertThat(thrown.getMessage(), containsString("Empty label declaration in pattern at index 2")); @@ -142,9 +142,9 @@ public void labelsMustMatchRegex() { Throwable thrown = Assertions.assertThrows(InvalidPatternException.class, () -> { String target = "/{!}"; SmithyPattern.builder() - .segments(parser(target)) - .pattern(target) - .build(); + .segments(parser(target)) + .pattern(target) + .build(); }); assertThat(thrown.getMessage(), containsString("Invalid label name")); @@ -156,9 +156,9 @@ public void labelsMustSpanEntireSegment() { Throwable thrown = Assertions.assertThrows(InvalidPatternException.class, () -> { String target = "/{foo}baz"; SmithyPattern.builder() - .segments(parser(target)) - .pattern(target) - .build(); + .segments(parser(target)) + .pattern(target) + .build(); }); assertThat(thrown.getMessage(), containsString("Literal segments must not contain")); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/pattern/UriPatternTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/pattern/UriPatternTest.java index f30067f1925..683d4bb9ab5 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/pattern/UriPatternTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/pattern/UriPatternTest.java @@ -72,8 +72,8 @@ public void labelsMustNotEndWithQuestionMark() { @Test public void patternsMustNotContainFragments() { Throwable thrown = Assertions.assertThrows( - InvalidUriPatternException.class, - () -> UriPattern.parse("/foo#bam") + InvalidUriPatternException.class, + () -> UriPattern.parse("/foo#bam") ); assertThat(thrown.getMessage(), containsString("URI pattern must not contain a fragment")); @@ -113,36 +113,36 @@ public void patternConflictTest(String patternA, String patternB, boolean isConf public static Collection data() { return Arrays.asList( - new Object[][]{ - {"/a/{x}", "/{y}/a", false}, - {"/{x}/a", "/a/{y}", false}, - {"/a/{x}", "/b/{y}", false}, - {"/{x+}", "/a", false}, - {"/a", "/{x+}", false}, - {"/a/{x}/b/{y}", "/a/{x+}", false}, - {"/a/{x+}", "/a/{y}", false}, - {"/a/{x}", "/a/{y+}", false}, - {"/a/{x+}", "/b/{y+}", false}, - {"/a/b/c/d", "/a/{b}/c/{d}", false}, - {"/foo?a=b", "/foo?a=c", false}, - {"/a/{x}/b", "/a/{y}/b/{z}", false}, - {"/a/{x}/b", "/a/{y}/b/{z}/c", false}, - {"/a=b", "/a", false}, - {"/a=b", "/a=", false}, - {"/foo?a", "/foo?b", false}, - // Conflicts can be resolved using query literals - {"/a/{x}/b", "/a/{y}/b?x", false}, - {"/a/{x}/b?x", "/a/{y}/b?y", false}, - {"/a/{x}/b?x=y", "/a/{y}/b?x=z", false}, - // Only equivalent patterns are consider conflicts. - {"/a/{x}/b", "/a/{y}/b", true}, - {"/a/{x}/b?x", "/a/{y}/b?x", true}, - {"/a/{x}", "/a/{y}", true}, - {"/a/{x+}", "/a/{y+}", true}, - {"/foo?a", "/foo?a", true}, - {"/foo?a=b", "/foo?a=b", true}, - {"/foo?a", "/foo?a=", true}, - } + new Object[][]{ + {"/a/{x}", "/{y}/a", false}, + {"/{x}/a", "/a/{y}", false}, + {"/a/{x}", "/b/{y}", false}, + {"/{x+}", "/a", false}, + {"/a", "/{x+}", false}, + {"/a/{x}/b/{y}", "/a/{x+}", false}, + {"/a/{x+}", "/a/{y}", false}, + {"/a/{x}", "/a/{y+}", false}, + {"/a/{x+}", "/b/{y+}", false}, + {"/a/b/c/d", "/a/{b}/c/{d}", false}, + {"/foo?a=b", "/foo?a=c", false}, + {"/a/{x}/b", "/a/{y}/b/{z}", false}, + {"/a/{x}/b", "/a/{y}/b/{z}/c", false}, + {"/a=b", "/a", false}, + {"/a=b", "/a=", false}, + {"/foo?a", "/foo?b", false}, + // Conflicts can be resolved using query literals + {"/a/{x}/b", "/a/{y}/b?x", false}, + {"/a/{x}/b?x", "/a/{y}/b?y", false}, + {"/a/{x}/b?x=y", "/a/{y}/b?x=z", false}, + // Only equivalent patterns are consider conflicts. + {"/a/{x}/b", "/a/{y}/b", true}, + {"/a/{x}/b?x", "/a/{y}/b?x", true}, + {"/a/{x}", "/a/{y}", true}, + {"/a/{x+}", "/a/{y+}", true}, + {"/foo?a", "/foo?a", true}, + {"/foo?a=b", "/foo?a=b", true}, + {"/foo?a", "/foo?a=", true}, + } ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/AttributeValueTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/AttributeValueTest.java index c5acc4fdfcb..da688a42c5c 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/AttributeValueTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/AttributeValueTest.java @@ -202,9 +202,9 @@ public void projectionReturnsResultOfEachContainedValue() { @Test public void createsServiceValue() { ServiceShape serviceShape = ServiceShape.builder() - .id("foo.baz#Service") - .version("XYZ") - .build(); + .id("foo.baz#Service") + .version("XYZ") + .build(); AttributeValue service = AttributeValue.service(serviceShape); assertThat(service.toString(), equalTo(serviceShape.getId().toString())); @@ -239,41 +239,41 @@ public void createsIdValueWithMember() { @Test public void createsShapeValue() { ServiceShape serviceShape = ServiceShape.builder() - .id("foo.baz#Service") - .version("XYZ") - .addTrait(new DocumentationTrait("hi")) - .build(); + .id("foo.baz#Service") + .version("XYZ") + .addTrait(new DocumentationTrait("hi")) + .build(); AttributeValue service = AttributeValue.shape(serviceShape, MapUtils.of()); assertThat(service.toString(), equalTo(serviceShape.getId().toString())); assertThat( - service.getPath( - ListUtils.of("id", "name") - ).toString(), - equalTo(serviceShape.getId().getName()) + service.getPath( + ListUtils.of("id", "name") + ).toString(), + equalTo(serviceShape.getId().getName()) ); assertThat( - service.getPath( - ListUtils.of("trait", "documentation") - ).toString(), - equalTo("hi") + service.getPath( + ListUtils.of("trait", "documentation") + ).toString(), + equalTo("hi") ); assertThat( - service.getPath( - ListUtils.of("service", "version") - ).toString(), - equalTo("XYZ") + service.getPath( + ListUtils.of("service", "version") + ).toString(), + equalTo("XYZ") ); } @Test public void createsTraitValue() { ServiceShape serviceShape = ServiceShape.builder() - .id("foo.baz#Service") - .version("XYZ") - .addTrait(new DocumentationTrait("hi")) - .addTrait(TagsTrait.builder().addValue("hi").build()) - .build(); + .id("foo.baz#Service") + .version("XYZ") + .addTrait(new DocumentationTrait("hi")) + .addTrait(TagsTrait.builder().addValue("hi").build()) + .build(); AttributeValue service = AttributeValue.shape(serviceShape, MapUtils.of()).getProperty("trait"); assertThat(service.toString(), equalTo("")); @@ -316,8 +316,8 @@ public void shapeProvidesVarAccess() { assertThat(attr.getProperty("var").toString(), equalTo("")); assertThat(attr.getProperty("var").toMessageString(), equalTo("")); assertThat( - attr.getPath(ListUtils.of("var", "a")).getProperty("id").toMessageString(), - equalTo("[foo.baz#Foo2, foo.baz#Foo3]") + attr.getPath(ListUtils.of("var", "a")).getProperty("id").toMessageString(), + equalTo("[foo.baz#Foo2, foo.baz#Foo3]") ); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/ForwardNeighborSelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/ForwardNeighborSelectorTest.java index 6ab4e510dd7..977f83cbd1a 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/ForwardNeighborSelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/ForwardNeighborSelectorTest.java @@ -24,9 +24,9 @@ public class ForwardNeighborSelectorTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(ForwardNeighborSelectorTest.class.getResource("neighbor-test.smithy")) - .assemble() - .unwrap(); + .addImport(ForwardNeighborSelectorTest.class.getResource("neighbor-test.smithy")) + .assemble() + .unwrap(); } @AfterAll @@ -36,11 +36,11 @@ public static void after() { private Set selectIds(String expression) { return Selector.parse(expression) - .select(model) - .stream() - .map(Shape::getId) - .map(ShapeId::toString) - .collect(Collectors.toSet()); + .select(model) + .stream() + .map(Shape::getId) + .map(ShapeId::toString) + .collect(Collectors.toSet()); } @Test @@ -48,12 +48,12 @@ public void undirectedEdgeTraversal() { Set result = selectIds("operation > *"); assertThat( - result, - containsInAnyOrder( - "smithy.example#Input", - "smithy.example#Output", - "smithy.example#Error" - ) + result, + containsInAnyOrder( + "smithy.example#Input", + "smithy.example#Output", + "smithy.example#Error" + ) ); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/IdentitySelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/IdentitySelectorTest.java index afe5c5b5dee..b04ee6646bd 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/IdentitySelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/IdentitySelectorTest.java @@ -28,9 +28,9 @@ public void createdFromSelectorParse() { public void returnsAllShapes() { Selector s = Selector.parse("*"); Model model = Model.builder() - .addShape(StringShape.builder().id("com.foo#A").build()) - .addShape(StringShape.builder().id("com.foo#B").build()) - .build(); + .addShape(StringShape.builder().id("com.foo#A").build()) + .addShape(StringShape.builder().id("com.foo#B").build()) + .build(); assertThat(s.select(model), equalTo(model.toSet())); } @@ -39,9 +39,9 @@ public void returnsAllShapes() { public void returnsAllShapesInStream() { Selector s = Selector.parse("*"); Model model = Model.builder() - .addShape(StringShape.builder().id("com.foo#A").build()) - .addShape(StringShape.builder().id("com.foo#B").build()) - .build(); + .addShape(StringShape.builder().id("com.foo#A").build()) + .addShape(StringShape.builder().id("com.foo#B").build()) + .build(); assertThat(s.shapes(model).collect(Collectors.toSet()), equalTo(model.toSet())); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/NeighborSelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/NeighborSelectorTest.java index a4d8918006c..c6e4f736a96 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/NeighborSelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/NeighborSelectorTest.java @@ -16,9 +16,9 @@ public class NeighborSelectorTest { private static final Model MODEL = Model.assembler() - .addImport(NeighborSelectorTest.class.getResource("neighbor-test.smithy")) - .assemble() - .unwrap(); + .addImport(NeighborSelectorTest.class.getResource("neighbor-test.smithy")) + .assemble() + .unwrap(); @Test public void specialCasesDeprecatedBoundSelectorFromResource() { @@ -39,11 +39,11 @@ public void specialCasesDeprecatedInstanceOperation() { Selector selector = Selector.parse("-[instanceOperation]->"); assertThat( - selector.select(MODEL), - containsInAnyOrder( - MODEL.expectShape(ShapeId.from("smithy.example#DeleteMyResource")), - MODEL.expectShape(ShapeId.from("smithy.example#GetMyResource")) - ) + selector.select(MODEL), + containsInAnyOrder( + MODEL.expectShape(ShapeId.from("smithy.example#DeleteMyResource")), + MODEL.expectShape(ShapeId.from("smithy.example#GetMyResource")) + ) ); } @@ -52,13 +52,13 @@ public void canUseDeprecatedRelsWithRealRels() { Selector selector = Selector.parse("-[bound, instanceOperation, resource]->"); assertThat( - selector.select(MODEL), - containsInAnyOrder( - MODEL.expectShape(ShapeId.from("smithy.example#MyService2")), - MODEL.expectShape(ShapeId.from("smithy.example#MyResource")), - MODEL.expectShape(ShapeId.from("smithy.example#DeleteMyResource")), - MODEL.expectShape(ShapeId.from("smithy.example#GetMyResource")) - ) + selector.select(MODEL), + containsInAnyOrder( + MODEL.expectShape(ShapeId.from("smithy.example#MyService2")), + MODEL.expectShape(ShapeId.from("smithy.example#MyResource")), + MODEL.expectShape(ShapeId.from("smithy.example#DeleteMyResource")), + MODEL.expectShape(ShapeId.from("smithy.example#GetMyResource")) + ) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/NotSelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/NotSelectorTest.java index f9df9993ca4..4d162989a17 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/NotSelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/NotSelectorTest.java @@ -22,9 +22,9 @@ public class NotSelectorTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(SelectorTest.class.getResource("not-test.smithy")) - .assemble() - .unwrap(); + .addImport(SelectorTest.class.getResource("not-test.smithy")) + .assemble() + .unwrap(); } @Test @@ -47,8 +47,8 @@ public void notStringOrFloat() { @Test public void allowsSingleSelector() { SelectorSyntaxException e = Assertions.assertThrows( - SelectorSyntaxException.class, - () -> Selector.parse(":not(string, float)") + SelectorSyntaxException.class, + () -> Selector.parse(":not(string, float)") ); assertThat(e.getMessage(), containsString("The :not function requires a single selector argument")); @@ -69,10 +69,10 @@ public void filtersOutEvenMoreComplexResultsFromLeftToRight() { // match structure members that don't have a length trait and they // target string shapes that don't have a length trait. Set ids = SelectorTest.ids( - model, - "structure > member" - + ":not([trait|length])" - + ":test(> string :not([trait|length]))" + model, + "structure > member" + + ":not([trait|length])" + + ":test(> string :not([trait|length]))" ); assertThat(ids, hasItem("smithy.example#StructA$noLengthOnEither")); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/PathFinderTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/PathFinderTest.java index fdfd914fdcc..f3a49c85cbf 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/PathFinderTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/PathFinderTest.java @@ -34,29 +34,29 @@ public void findsPathsFromAtoB() { MemberShape structMemberFoo = MemberShape.builder().id("a.b#Struct$foo").target(list).build(); MemberShape structMemberBaz = MemberShape.builder().id("a.b#Struct$baz").target(string).build(); StructureShape struct = StructureShape.builder() - .id("a.b#Struct") - .addMember(structMemberFoo) - .addMember(structMemberBaz) - .build(); + .id("a.b#Struct") + .addMember(structMemberFoo) + .addMember(structMemberBaz) + .build(); Model model = Model.builder() - .addShapes(struct, structMemberFoo, structMemberBaz, list, listMember, string, structMemberBaz) - .build(); + .addShapes(struct, structMemberFoo, structMemberBaz, list, listMember, string, structMemberBaz) + .build(); List result1 = formatPaths(PathFinder.create(model).search(struct, "string")); assertThat( - result1, - containsInAnyOrder( - "[id|a.b#Struct] -[member]-> [id|a.b#Struct$baz] > [id|a.b#String]", - "[id|a.b#Struct] -[member]-> [id|a.b#Struct$foo] > [id|a.b#List] -[member]-> [id|a.b#List$member] > [id|a.b#String]" - ) + result1, + containsInAnyOrder( + "[id|a.b#Struct] -[member]-> [id|a.b#Struct$baz] > [id|a.b#String]", + "[id|a.b#Struct] -[member]-> [id|a.b#Struct$foo] > [id|a.b#List] -[member]-> [id|a.b#List$member] > [id|a.b#String]" + ) ); List result2 = formatPaths(PathFinder.create(model).search(structMemberFoo, "string")); assertThat( - result2, - contains( - "[id|a.b#Struct$foo] > [id|a.b#List] -[member]-> [id|a.b#List$member] > [id|a.b#String]" - ) + result2, + contains( + "[id|a.b#Struct$foo] > [id|a.b#List] -[member]-> [id|a.b#List$member] > [id|a.b#String]" + ) ); } @@ -72,31 +72,31 @@ public void doesNotFailOnRecursion() { MemberShape structMemberFoo = MemberShape.builder().id("a.b#Struct$foo").target(list).build(); MemberShape structMemberBaz = MemberShape.builder().id("a.b#Struct$baz").target(string).build(); StructureShape struct = StructureShape.builder() - .id("a.b#Struct") - .addTrait(new SensitiveTrait()) - .addMember(structMemberFoo) - .addMember(structMemberBaz) - .build(); + .id("a.b#Struct") + .addTrait(new SensitiveTrait()) + .addMember(structMemberFoo) + .addMember(structMemberBaz) + .build(); Model model = Model.builder() - .addShapes(struct, structMemberFoo, structMemberBaz, list, listMember, string, structMemberBaz) - .build(); + .addShapes(struct, structMemberFoo, structMemberBaz, list, listMember, string, structMemberBaz) + .build(); List result = formatPaths(PathFinder.create(model).search(struct, "[trait|sensitive]")); assertThat( - result, - containsInAnyOrder( - "[id|a.b#Struct] -[member]-> [id|a.b#Struct$foo] > [id|a.b#List] -[member]-> [id|a.b#List$member] > [id|a.b#Struct]", - "[id|a.b#Struct] -[member]-> [id|a.b#Struct$baz] > [id|a.b#String]" - ) + result, + containsInAnyOrder( + "[id|a.b#Struct] -[member]-> [id|a.b#Struct$foo] > [id|a.b#List] -[member]-> [id|a.b#List$member] > [id|a.b#Struct]", + "[id|a.b#Struct] -[member]-> [id|a.b#Struct$baz] > [id|a.b#String]" + ) ); } @Test public void doesNotFailOnMoreComplexRecursion() { Model model = Model.assembler() - .addImport(getClass().getResource("path-finder-recursion.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("path-finder-recursion.json")) + .assemble() + .unwrap(); PathFinder finder = PathFinder.create(model); ShapeId operation = ShapeId.from("smithy.example#Operation"); @@ -104,19 +104,19 @@ public void doesNotFailOnMoreComplexRecursion() { List resultStrings = result.stream().map(PathFinder.Path::toString).collect(Collectors.toList()); assertThat( - resultStrings, - containsInAnyOrder( - "[id|smithy.example#Operation] -[input]-> [id|smithy.example#OperationInput] -[member]-> [id|smithy.example#OperationInput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$structureMap] > [id|smithy.example#MapOfStructures] -[member]-> [id|smithy.example#MapOfStructures$value]", - "[id|smithy.example#Operation] -[input]-> [id|smithy.example#OperationInput] -[member]-> [id|smithy.example#OperationInput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$structureMap] > [id|smithy.example#MapOfStructures] -[member]-> [id|smithy.example#MapOfStructures$value] > [id|smithy.example#SimpleStructure] -[member]-> [id|smithy.example#SimpleStructure$crackle]", - "[id|smithy.example#Operation] -[input]-> [id|smithy.example#OperationInput] -[member]-> [id|smithy.example#OperationInput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$structureList] > [id|smithy.example#ListOfStructures] -[member]-> [id|smithy.example#ListOfStructures$member] > [id|smithy.example#SimpleStructure] -[member]-> [id|smithy.example#SimpleStructure$crackle]", - "[id|smithy.example#Operation] -[input]-> [id|smithy.example#OperationInput] -[member]-> [id|smithy.example#OperationInput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$nestedStructure] > [id|smithy.example#SimpleStructure] -[member]-> [id|smithy.example#SimpleStructure$crackle]", - "[id|smithy.example#Operation] -[input]-> [id|smithy.example#OperationInput] -[member]-> [id|smithy.example#OperationInput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$recursiveStructure] > [id|smithy.example#RecursiveStructure] -[member]-> [id|smithy.example#RecursiveStructure$bar]", - "[id|smithy.example#Operation] -[output]-> [id|smithy.example#OperationOutput] -[member]-> [id|smithy.example#OperationOutput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$structureMap] > [id|smithy.example#MapOfStructures] -[member]-> [id|smithy.example#MapOfStructures$value] > [id|smithy.example#SimpleStructure] -[member]-> [id|smithy.example#SimpleStructure$crackle]", - "[id|smithy.example#Operation] -[output]-> [id|smithy.example#OperationOutput] -[member]-> [id|smithy.example#OperationOutput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$structureMap] > [id|smithy.example#MapOfStructures] -[member]-> [id|smithy.example#MapOfStructures$value]", - "[id|smithy.example#Operation] -[output]-> [id|smithy.example#OperationOutput] -[member]-> [id|smithy.example#OperationOutput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$structureList] > [id|smithy.example#ListOfStructures] -[member]-> [id|smithy.example#ListOfStructures$member] > [id|smithy.example#SimpleStructure] -[member]-> [id|smithy.example#SimpleStructure$crackle]", - "[id|smithy.example#Operation] -[output]-> [id|smithy.example#OperationOutput] -[member]-> [id|smithy.example#OperationOutput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$nestedStructure] > [id|smithy.example#SimpleStructure] -[member]-> [id|smithy.example#SimpleStructure$crackle]", - "[id|smithy.example#Operation] -[output]-> [id|smithy.example#OperationOutput] -[member]-> [id|smithy.example#OperationOutput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$recursiveStructure] > [id|smithy.example#RecursiveStructure] -[member]-> [id|smithy.example#RecursiveStructure$bar]" - ) + resultStrings, + containsInAnyOrder( + "[id|smithy.example#Operation] -[input]-> [id|smithy.example#OperationInput] -[member]-> [id|smithy.example#OperationInput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$structureMap] > [id|smithy.example#MapOfStructures] -[member]-> [id|smithy.example#MapOfStructures$value]", + "[id|smithy.example#Operation] -[input]-> [id|smithy.example#OperationInput] -[member]-> [id|smithy.example#OperationInput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$structureMap] > [id|smithy.example#MapOfStructures] -[member]-> [id|smithy.example#MapOfStructures$value] > [id|smithy.example#SimpleStructure] -[member]-> [id|smithy.example#SimpleStructure$crackle]", + "[id|smithy.example#Operation] -[input]-> [id|smithy.example#OperationInput] -[member]-> [id|smithy.example#OperationInput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$structureList] > [id|smithy.example#ListOfStructures] -[member]-> [id|smithy.example#ListOfStructures$member] > [id|smithy.example#SimpleStructure] -[member]-> [id|smithy.example#SimpleStructure$crackle]", + "[id|smithy.example#Operation] -[input]-> [id|smithy.example#OperationInput] -[member]-> [id|smithy.example#OperationInput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$nestedStructure] > [id|smithy.example#SimpleStructure] -[member]-> [id|smithy.example#SimpleStructure$crackle]", + "[id|smithy.example#Operation] -[input]-> [id|smithy.example#OperationInput] -[member]-> [id|smithy.example#OperationInput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$recursiveStructure] > [id|smithy.example#RecursiveStructure] -[member]-> [id|smithy.example#RecursiveStructure$bar]", + "[id|smithy.example#Operation] -[output]-> [id|smithy.example#OperationOutput] -[member]-> [id|smithy.example#OperationOutput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$structureMap] > [id|smithy.example#MapOfStructures] -[member]-> [id|smithy.example#MapOfStructures$value] > [id|smithy.example#SimpleStructure] -[member]-> [id|smithy.example#SimpleStructure$crackle]", + "[id|smithy.example#Operation] -[output]-> [id|smithy.example#OperationOutput] -[member]-> [id|smithy.example#OperationOutput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$structureMap] > [id|smithy.example#MapOfStructures] -[member]-> [id|smithy.example#MapOfStructures$value]", + "[id|smithy.example#Operation] -[output]-> [id|smithy.example#OperationOutput] -[member]-> [id|smithy.example#OperationOutput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$structureList] > [id|smithy.example#ListOfStructures] -[member]-> [id|smithy.example#ListOfStructures$member] > [id|smithy.example#SimpleStructure] -[member]-> [id|smithy.example#SimpleStructure$crackle]", + "[id|smithy.example#Operation] -[output]-> [id|smithy.example#OperationOutput] -[member]-> [id|smithy.example#OperationOutput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$nestedStructure] > [id|smithy.example#SimpleStructure] -[member]-> [id|smithy.example#SimpleStructure$crackle]", + "[id|smithy.example#Operation] -[output]-> [id|smithy.example#OperationOutput] -[member]-> [id|smithy.example#OperationOutput$payload] > [id|smithy.example#ComplexStructure] -[member]-> [id|smithy.example#ComplexStructure$recursiveStructure] > [id|smithy.example#RecursiveStructure] -[member]-> [id|smithy.example#RecursiveStructure$bar]" + ) ); } @@ -145,10 +145,10 @@ public void doesNotAddItselfToResultAsFirstMatch() { List result = formatPaths(PathFinder.create(model).search(list, "list")); assertThat( - result, - contains( - "[id|a.b#List] -[member]-> [id|a.b#List$member] > [id|a.b#List]" - ) + result, + contains( + "[id|a.b#List] -[member]-> [id|a.b#List$member] > [id|a.b#List]" + ) ); } @@ -168,28 +168,28 @@ public void providesStartAndEndShapes() { @Test public void createsPathToInputAndOutputMember() { Model model = Model.assembler() - .addImport(getClass().getResource("path-to-member.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("path-to-member.smithy")) + .assemble() + .unwrap(); PathFinder finder = PathFinder.create(model); ShapeId operation = ShapeId.from("smithy.example#Operation"); Optional input = finder.createPathToInputMember(operation, "foo"); assertThat(input.isPresent(), is(true)); assertThat( - input.get().toString(), - equalTo( - "[id|smithy.example#Operation] -[input]-> [id|smithy.example#Input] -[member]-> [id|smithy.example#Input$foo] > [id|smithy.api#String]" - ) + input.get().toString(), + equalTo( + "[id|smithy.example#Operation] -[input]-> [id|smithy.example#Input] -[member]-> [id|smithy.example#Input$foo] > [id|smithy.api#String]" + ) ); Optional output = finder.createPathToOutputMember(operation, "foo"); assertThat(output.isPresent(), is(true)); assertThat( - output.get().toString(), - equalTo( - "[id|smithy.example#Operation] -[output]-> [id|smithy.example#Output] -[member]-> [id|smithy.example#Output$foo] > [id|smithy.api#String]" - ) + output.get().toString(), + equalTo( + "[id|smithy.example#Operation] -[output]-> [id|smithy.example#Output] -[member]-> [id|smithy.example#Output$foo] > [id|smithy.api#String]" + ) ); } @@ -197,9 +197,9 @@ public void createsPathToInputAndOutputMember() { public void createsPathToOtherShape() { MemberShape recursiveMember = MemberShape.builder().id("a.b#Struct$a").target("a.b#Struct").build(); StructureShape struct = StructureShape.builder() - .id("a.b#Struct") - .addMember(recursiveMember) - .build(); + .id("a.b#Struct") + .addMember(recursiveMember) + .build(); Model model = Model.builder().addShapes(struct).build(); PathFinder finder = PathFinder.create(model); List paths = finder.search(struct.getId(), Collections.singleton(struct)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/RecursiveNeighborSelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/RecursiveNeighborSelectorTest.java index 2eb3fbc8550..f3c904ed70a 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/RecursiveNeighborSelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/RecursiveNeighborSelectorTest.java @@ -24,9 +24,9 @@ public class RecursiveNeighborSelectorTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(ForwardNeighborSelectorTest.class.getResource("neighbor-test.smithy")) - .assemble() - .unwrap(); + .addImport(ForwardNeighborSelectorTest.class.getResource("neighbor-test.smithy")) + .assemble() + .unwrap(); } @AfterAll @@ -36,11 +36,11 @@ public static void after() { private Set selectIds(String expression) { return Selector.parse(expression) - .select(model) - .stream() - .map(Shape::getId) - .map(ShapeId::toString) - .collect(Collectors.toSet()); + .select(model) + .stream() + .map(Shape::getId) + .map(ShapeId::toString) + .collect(Collectors.toSet()); } @Test @@ -48,20 +48,20 @@ public void findsClosure() { Set result = selectIds("service[id=smithy.example#MyService2] ~> *"); assertThat( - result, - containsInAnyOrder( - "smithy.example#MyResource", - "smithy.example#GetMyResource", - "smithy.example#DeleteMyResource", - "smithy.example#Input", - "smithy.example#Output$foo", - "smithy.example#Error$foo", - "smithy.example#Operation", - "smithy.example#Error", - "smithy.api#String", - "smithy.example#Input$foo", - "smithy.example#Output" - ) + result, + containsInAnyOrder( + "smithy.example#MyResource", + "smithy.example#GetMyResource", + "smithy.example#DeleteMyResource", + "smithy.example#Input", + "smithy.example#Output$foo", + "smithy.example#Error$foo", + "smithy.example#Operation", + "smithy.example#Error", + "smithy.api#String", + "smithy.example#Input$foo", + "smithy.example#Output" + ) ); } @@ -75,17 +75,17 @@ public void findsEmptyClosure() { @Test public void stopsSendingShapesWhenGetsStopSignal() { Model model = Model.assembler() - .addImport(getClass().getResource("http-model.smithy")) - .assemble() - .getResult() // ignore built-in errors - .get(); + .addImport(getClass().getResource("http-model.smithy")) + .assemble() + .getResult() // ignore built-in errors + .get(); // This is a slightly less efficient variation of a similar // test in SelectorTest because it doesn't use a temporary // variable to store the recursive neighbors. Set ids = SelectorTest.exampleIds( - model, - "service :test(~> operation[trait|http]) ~> operation :not([trait|http])" + model, + "service :test(~> operation[trait|http]) ~> operation :not([trait|http])" ); assertThat(ids, contains("smithy.example#NoHttp")); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/ReverseNeighborSelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/ReverseNeighborSelectorTest.java index e6401cb38bf..069adf3827a 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/ReverseNeighborSelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/ReverseNeighborSelectorTest.java @@ -22,20 +22,20 @@ public class ReverseNeighborSelectorTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(SelectorTest.class.getResource("reverse-neighbor.smithy")) - .assemble() - .unwrap(); + .addImport(SelectorTest.class.getResource("reverse-neighbor.smithy")) + .assemble() + .unwrap(); } @Test public void parsesValidReverseNeighbors() { List exprs = ListUtils.of( - "string < member < list", - "structure <-[input]-", - "structure <-[input]- operation", - "structure <-[input, output]- operation", - "structure <-[input, output, error]- operation", - "structure <-[ input , output,error ]-operation" + "string < member < list", + "structure <-[input]-", + "structure <-[input]- operation", + "structure <-[input, output]- operation", + "structure <-[input, output, error]- operation", + "structure <-[ input , output,error ]-operation" ); for (String expr : exprs) { @@ -46,16 +46,16 @@ public void parsesValidReverseNeighbors() { @Test public void detectsInvalidReverseNeighbors() { List exprs = ListUtils.of( - "structure <-", - "structure <-[", - "structure <-[input", - "structure <-[input,", - "structure <-[input, output", - "structure <-[input, output]", - "structure <-[input, output]--", - "structure < - [input, output]-", // no spaces between '-' and '[' - "structure <-[input, output] -", // no spaces between ']' and '-' - "structure <-[]-" + "structure <-", + "structure <-[", + "structure <-[input", + "structure <-[input,", + "structure <-[input, output", + "structure <-[input, output]", + "structure <-[input, output]--", + "structure < - [input, output]-", // no spaces between '-' and '[' + "structure <-[input, output] -", // no spaces between ']' and '-' + "structure <-[]-" ); for (String expr : exprs) { @@ -101,8 +101,8 @@ public void traversesDirectedReverseOperationInputOutputAndErrors() { @Test public void traversesDirectedReverseOperationDeepInputOutput() { Set result = SelectorTest.exampleIds( - model, - "string :test(< member < list < member < structure <-[output]- operation)" + model, + "string :test(< member < list < member < structure <-[output]- operation)" ); assertThat(result, containsInAnyOrder("smithy.example#MyString1")); @@ -120,20 +120,20 @@ public void traversesUndirectedReverseOperationInputOutputAndErrors() { Set result = SelectorTest.exampleIds(model, ":test(structure <-[input, output, error]- operation)"); assertThat( - result, - containsInAnyOrder( - "smithy.example#OperationInput", - "smithy.example#OperationOutput", - "smithy.example#Error" - ) + result, + containsInAnyOrder( + "smithy.example#OperationInput", + "smithy.example#OperationOutput", + "smithy.example#Error" + ) ); } @Test public void traversesUndirectedReverseOperationDeepInputOutput() { Set result = SelectorTest.exampleIds( - model, - ":test(string < member < list < member < structure <-[input, output]- operation)" + model, + ":test(string < member < list < member < structure <-[input, output]- operation)" ); assertThat(result, containsInAnyOrder("smithy.example#MyString1")); @@ -144,11 +144,11 @@ public void findsShapesNotConnectedToOtherShapes() { Set result = SelectorTest.exampleIds(model, ":not([trait|trait]) :not(< *)"); assertThat( - result, - containsInAnyOrder( - "smithy.example#Operation", - "smithy.example#MyString2" - ) + result, + containsInAnyOrder( + "smithy.example#Operation", + "smithy.example#MyString2" + ) ); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/SelectorRunnerTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/SelectorRunnerTest.java index a0c7a31ee90..5e58bcfbb29 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/SelectorRunnerTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/SelectorRunnerTest.java @@ -36,23 +36,23 @@ public void selectorTest(Path filename) { boolean skipPrelude = test.getBooleanMemberOrDefault("skipPreludeShapes", false); Set expectedMatches = test.expectArrayMember("matches") - .getElementsAs(n -> n.expectStringNode("Each element of matches must be an ID").expectShapeId()) - .stream() - .filter(shapeId -> { - String namespace = shapeId.getNamespace(); - return !namespace.contains(Prelude.NAMESPACE) - || (!skipPrelude && namespace.contains(Prelude.NAMESPACE)); - }) - .collect(Collectors.toSet()); + .getElementsAs(n -> n.expectStringNode("Each element of matches must be an ID").expectShapeId()) + .stream() + .filter(shapeId -> { + String namespace = shapeId.getNamespace(); + return !namespace.contains(Prelude.NAMESPACE) + || (!skipPrelude && namespace.contains(Prelude.NAMESPACE)); + }) + .collect(Collectors.toSet()); Set actualMatches = selector.shapes(model) - .map(Shape::getId) - .filter(shapeId -> { - String namespace = shapeId.getNamespace(); - return !namespace.contains(Prelude.NAMESPACE) - || (!skipPrelude && namespace.contains(Prelude.NAMESPACE)); - }) - .collect(Collectors.toSet()); + .map(Shape::getId) + .filter(shapeId -> { + String namespace = shapeId.getNamespace(); + return !namespace.contains(Prelude.NAMESPACE) + || (!skipPrelude && namespace.contains(Prelude.NAMESPACE)); + }) + .collect(Collectors.toSet()); if (!expectedMatches.equals(actualMatches)) { failTest(filename, test, expectedMatches, actualMatches); @@ -62,9 +62,9 @@ public void selectorTest(Path filename) { private List findTestCases(Model model) { return model.getMetadataProperty("selectorTests") - .orElseThrow(() -> new IllegalArgumentException("Missing selectorTests metadata key")) - .expectArrayNode("selectorTests must be an array") - .getElementsAs(ObjectNode.class); + .orElseThrow(() -> new IllegalArgumentException("Missing selectorTests metadata key")) + .expectArrayNode("selectorTests must be an array") + .getElementsAs(ObjectNode.class); } private void failTest(Path filename, ObjectNode test, Set expectedMatches, Set actualMatches) { @@ -76,8 +76,8 @@ private void failTest(Path filename, ObjectNode test, Set expectedMatch extra.removeAll(expectedMatches); StringBuilder error = new StringBuilder("Selector ") - .append(selector) - .append(" test case failed.\n"); + .append(selector) + .append(" test case failed.\n"); if (!missing.isEmpty()) { error.append("The following shapes were not matched: ").append(missing).append(".\n"); @@ -88,7 +88,7 @@ private void failTest(Path filename, ObjectNode test, Set expectedMatch } test.getStringMember("documentation") - .ifPresent(docs -> error.append('(').append(docs.getValue()).append(")")); + .ifPresent(docs -> error.append('(').append(docs.getValue()).append(")")); Assertions.fail(error.toString()); } @@ -97,12 +97,12 @@ public static List source() throws Exception { List paths = new ArrayList<>(); try (Stream files = Files.walk(Paths.get(SelectorRunnerTest.class.getResource("cases").toURI()))) { files - .filter(Files::isRegularFile) - .filter(file -> { - String filename = file.toString(); - return filename.endsWith(".smithy") || filename.endsWith(".json"); - }) - .forEach(paths::add); + .filter(Files::isRegularFile) + .filter(file -> { + String filename = file.toString(); + return filename.endsWith(".smithy") || filename.endsWith(".json"); + }) + .forEach(paths::add); } catch (IOException e) { throw new RuntimeException("Error loading models for selector runner", e); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/SelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/SelectorTest.java index bcdfaaee1c3..8596aefa2d0 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/SelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/SelectorTest.java @@ -49,10 +49,10 @@ public class SelectorTest { private static final String OPERATIONS_MISSING_BINDINGS = "service\n" - + "$operations(~> operation)\n" - + ":test(${operations}[trait|http])\n" - + "${operations}\n" - + ":not([trait|http])"; + + "$operations(~> operation)\n" + + ":test(${operations}[trait|http])\n" + + "${operations}\n" + + ":not([trait|http])"; private static Model modelJson; private static Model traitModel; @@ -62,23 +62,23 @@ public class SelectorTest { @BeforeAll public static void before() { modelJson = Model.assembler() - .addImport(SelectorTest.class.getResource("model.json")) - .disablePrelude() - .assemble() - .unwrap(); + .addImport(SelectorTest.class.getResource("model.json")) + .disablePrelude() + .assemble() + .unwrap(); traitModel = Model.assembler() - .addImport(SelectorTest.class.getResource("nested-traits.smithy")) - .assemble() - .unwrap(); + .addImport(SelectorTest.class.getResource("nested-traits.smithy")) + .assemble() + .unwrap(); httpModel = Model.assembler() - .addImport(SelectorTest.class.getResource("http-model.smithy")) - .assemble() - .getResult() // ignore built-in errors - .get(); + .addImport(SelectorTest.class.getResource("http-model.smithy")) + .assemble() + .getResult() // ignore built-in errors + .get(); resourceModel = Model.assembler() - .addImport(SelectorTest.class.getResource("resource.smithy")) - .assemble() - .unwrap(); + .addImport(SelectorTest.class.getResource("resource.smithy")) + .assemble() + .unwrap(); } @Test @@ -119,21 +119,21 @@ public void supportsDeprecatedEachFunction() { static Set ids(Model model, String expression) { return Selector.parse(expression) - .select(model) - .stream() - .map(Shape::getId) - .map(ShapeId::toString) - .collect(Collectors.toSet()); + .select(model) + .stream() + .map(Shape::getId) + .map(ShapeId::toString) + .collect(Collectors.toSet()); } static Set exampleIds(Model model, String expression) { return Selector.parse(expression) - .select(model) - .stream() - .map(Shape::getId) - .filter(id -> id.getNamespace().equals("smithy.example")) - .map(ShapeId::toString) - .collect(Collectors.toSet()); + .select(model) + .stream() + .map(Shape::getId) + .filter(id -> id.getNamespace().equals("smithy.example")) + .map(ShapeId::toString) + .collect(Collectors.toSet()); } @Test @@ -182,8 +182,8 @@ public void canSelectOnTraitObjectKeys() { @Test public void canSelectOnTraitObjectValues() { Set result = ids( - traitModel, - "[trait|externalDocumentation|(values)='https://www.anotherexample.com/']" + traitModel, + "[trait|externalDocumentation|(values)='https://www.anotherexample.com/']" ); assertThat(result, hasItem("smithy.example#DocumentedString2")); @@ -237,42 +237,42 @@ public void selectsCollections() { Set result = Selector.parse("collection").select(modelJson); assertThat( - result, - containsInAnyOrder( - ListShape.builder() - .id("ns.foo#List") - .member(MemberShape.builder().id("ns.foo#List$member").target("ns.foo#String").build()) - .build() - ) + result, + containsInAnyOrder( + ListShape.builder() + .id("ns.foo#List") + .member(MemberShape.builder().id("ns.foo#List$member").target("ns.foo#String").build()) + .build() + ) ); } @Test public void selectsCustomTraits() { Model model = Model.assembler() - .addImport(getClass().getResource("model-custom-trait.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("model-custom-trait.json")) + .assemble() + .unwrap(); Set result = Selector.parse("*[trait|'com.example#beta']").select(model); Trait betaTrait = new DynamicTrait(ShapeId.from("com.example#beta"), Node.objectNode()); Trait requiredTrait = new RequiredTrait(); assertThat( - result, - containsInAnyOrder( - MemberShape.builder() - .id("com.example#AnotherStructureShape$bar") - .target("com.example#MyShape") - .addTrait(betaTrait) - .addTrait(requiredTrait) - .build(), - MemberShape.builder() - .id("com.example#MyShape$foo") - .target("com.example#StringShape") - .addTrait(betaTrait) - .addTrait(requiredTrait) - .build() - ) + result, + containsInAnyOrder( + MemberShape.builder() + .id("com.example#AnotherStructureShape$bar") + .target("com.example#MyShape") + .addTrait(betaTrait) + .addTrait(requiredTrait) + .build(), + MemberShape.builder() + .id("com.example#MyShape$foo") + .target("com.example#StringShape") + .addTrait(betaTrait) + .addTrait(requiredTrait) + .build() + ) ); } @@ -340,8 +340,8 @@ public void toleratesUnknownSelectorAttributes() { @Test public void throwsOnInvalidShapeType() { SelectorSyntaxException e = Assertions.assertThrows( - SelectorSyntaxException.class, - () -> Selector.parse("foo") + SelectorSyntaxException.class, + () -> Selector.parse("foo") ); assertThat(e.getMessage(), containsString("Unknown shape type")); @@ -361,8 +361,8 @@ public void parsesNestedTraitEndsWith() { @Test public void throwsOnInvalidComparator() { SelectorSyntaxException e = Assertions.assertThrows( - SelectorSyntaxException.class, - () -> Selector.parse("[id%=100]") + SelectorSyntaxException.class, + () -> Selector.parse("[id%=100]") ); assertThat(e.getMessage(), containsString("Found '%', but expected one of the following tokens")); @@ -376,20 +376,20 @@ public void parsesCaseInsensitiveAttributes() { @Test public void detectsInvalidShapeIds() { List exprs = ListUtils.of( - "[id=#]", - "[id=com#]", - "[id=com.foo#]", - "[id=com.foo#$]", - "[id=com.foo#baz$]", - "[id=com.foo#.baz$]", - "[id=com..foo#baz]", - "[id=com#baz$.]", - "[id=com#baz$bar$]", - "[id=com#baz$bar#]", - "[id=com#baz$bar.bam]", - "[id=com.baz#foo$bar]", // Members are not permitted and must be quoted. - "[id=Com.Baz#Foo$Bar123]", - "[id=Com._Baz_#_Foo_$_Bar_123__]" + "[id=#]", + "[id=com#]", + "[id=com.foo#]", + "[id=com.foo#$]", + "[id=com.foo#baz$]", + "[id=com.foo#.baz$]", + "[id=com..foo#baz]", + "[id=com#baz$.]", + "[id=com#baz$bar$]", + "[id=com#baz$bar#]", + "[id=com#baz$bar.bam]", + "[id=com.baz#foo$bar]", // Members are not permitted and must be quoted. + "[id=Com.Baz#Foo$Bar123]", + "[id=Com._Baz_#_Foo_$_Bar_123__]" ); for (String expr : exprs) { @@ -400,10 +400,10 @@ public void detectsInvalidShapeIds() { @Test public void parsesValidShapeIds() { List exprs = ListUtils.of( - "[id=com#foo]", - "[id=com.baz#foo]", - "[id=com.baz.bar#foo]", - "[id=Foo]" + "[id=com#foo]", + "[id=com.baz#foo]", + "[id=com.baz.bar#foo]", + "[id=Foo]" ); for (String expr : exprs) { @@ -414,16 +414,16 @@ public void parsesValidShapeIds() { @Test public void detectsInvalidNumbers() { List exprs = ListUtils.of( - "[id=1-]", - "[id=-]", - "[id=1.]", - "[id=1..1]", - "[id=1.0e]", - "[id=1.0e+]", - "[id=1e+]", - "[id=1e++]", - "[id=1+]", - "[id=+1]" + "[id=1-]", + "[id=-]", + "[id=1.]", + "[id=1..1]", + "[id=1.0e]", + "[id=1.0e+]", + "[id=1e+]", + "[id=1e++]", + "[id=1+]", + "[id=+1]" ); for (String expr : exprs) { @@ -434,20 +434,20 @@ public void detectsInvalidNumbers() { @Test public void parsesValidNumbers() { List exprs = ListUtils.of( - "[id=1]", - "[id=123]", - "[id=0]", - "[id=-1]", - "[id=-10]", - "[id=123456789]", - "[id=1.5]", - "[id=1.123456789]", - "[id=1.1e+1]", - "[id=1.1e-1]", - "[id=1.1e-0]", - "[id=1.1e-123456789]", - "[id=1e+123456789]", - "[id=1e-123456789]" + "[id=1]", + "[id=123]", + "[id=0]", + "[id=-1]", + "[id=-10]", + "[id=123456789]", + "[id=1.5]", + "[id=1.123456789]", + "[id=1.1e+1]", + "[id=1.1e-1]", + "[id=1.1e-0]", + "[id=1.1e-123456789]", + "[id=1e+123456789]", + "[id=1e-123456789]" ); for (String expr : exprs) { @@ -458,12 +458,12 @@ public void parsesValidNumbers() { @Test public void parsesValidQuotedAttributes() { List exprs = ListUtils.of( - "[id='1']", - "[id=\"1\"]", - "[id='aaaaa']", - "[id=\"aaaaaa\"]", - "[trait|'foo'=\"aaaaaa\"]", - "[trait|\"foo\"=\"aaaaaa\"]" + "[id='1']", + "[id=\"1\"]", + "[id='aaaaa']", + "[id=\"aaaaaa\"]", + "[trait|'foo'=\"aaaaaa\"]", + "[trait|\"foo\"=\"aaaaaa\"]" ); for (String expr : exprs) { @@ -474,9 +474,9 @@ public void parsesValidQuotedAttributes() { @Test public void toleratesInvalidKnownAttributePaths() { List exprs = ListUtils.of( - "[service]", - "[service|version|foo]", - "[trait]" + "[service]", + "[service|version|foo]", + "[trait]" ); for (String expr : exprs) { @@ -487,15 +487,15 @@ public void toleratesInvalidKnownAttributePaths() { @Test public void parsesValidAttributePathsAndToleratesUnknownPaths() { List exprs = ListUtils.of( - "[id=abc]", - "[id|name=abc]", - "[id|member=abc]", - "[id|namespace=abc]", - "[id|namespace|(foo)=abc]", // invalid, tolerated - "[id|blurb=abc]", // invalid, tolerated - "[service|version=abc]", - "[service|blurb=abc]", // invalid, tolerated - "[trait|foo=abc]" + "[id=abc]", + "[id|name=abc]", + "[id|member=abc]", + "[id|namespace=abc]", + "[id|namespace|(foo)=abc]", // invalid, tolerated + "[id|blurb=abc]", // invalid, tolerated + "[service|version=abc]", + "[service|blurb=abc]", // invalid, tolerated + "[trait|foo=abc]" ); for (String expr : exprs) { @@ -549,12 +549,12 @@ public void canMatchUsingCommaSeparatedAttributeValues() { Set matches3 = ids(traitModel, "[trait|enum|(values)|value = 'm256.mega' , nope ]"); assertThat( - matches1, - containsInAnyOrder( - "smithy.example#DocumentedString1", - "smithy.example#DocumentedString2", - "smithy.example#EnumString" - ) + matches1, + containsInAnyOrder( + "smithy.example#DocumentedString1", + "smithy.example#DocumentedString2", + "smithy.example#EnumString" + ) ); assertThat(matches1, equalTo(matches2)); assertThat(matches1, equalTo(matches3)); @@ -563,26 +563,26 @@ public void canMatchUsingCommaSeparatedAttributeValues() { @Test public void detectsInvalidAttributeCsv() { Assertions.assertThrows( - SelectorSyntaxException.class, - () -> Selector.parse("[trait|enum|(values)|value='m256.mega',]") + SelectorSyntaxException.class, + () -> Selector.parse("[trait|enum|(values)|value='m256.mega',]") ); } @Test public void parsedRelativeComparators() { List exprs = ListUtils.of( - "[trait|httpError > 500]", - "[trait|httpError >= 500]", - "[trait|httpError < 500]", - "[trait|httpError <= 500]", - "[trait|httpError>500]", - "[trait|httpError>=500]", - "[trait|httpError<500]", - "[trait|httpError<=500]", - "[trait|httpError > 500, 400]", // silly, but supported - "[trait|httpError >= 500, 400]", // silly, but supported - "[trait|httpError < 500, 400]", // silly, but supported - "[trait|httpError <= 500, 400]" + "[trait|httpError > 500]", + "[trait|httpError >= 500]", + "[trait|httpError < 500]", + "[trait|httpError <= 500]", + "[trait|httpError>500]", + "[trait|httpError>=500]", + "[trait|httpError<500]", + "[trait|httpError<=500]", + "[trait|httpError > 500, 400]", // silly, but supported + "[trait|httpError >= 500, 400]", // silly, but supported + "[trait|httpError < 500, 400]", // silly, but supported + "[trait|httpError <= 500, 400]" ); // silly, but supported for (String expr : exprs) { @@ -683,22 +683,22 @@ public void projectsTraitValuesAsNodes() { @Test public void parsesValidScopedAttributes() { List exprs = ListUtils.of( - "[@trait: 10=10]", - "[@trait: @{foo}=10]", - "[@trait: @{foo}=@{foo}]", - "[@trait: @{foo}=@{foo} && bar=bar]", - "[@trait: @{foo}=@{foo} && bar=10]", - "[@trait: @{foo}=@{foo} && bar=@{baz}]", - "[@trait: @{foo}=@{foo} && bar=@{baz} && bam='abc']", - "[@trait: @{foo}=@{foo} i && bar=@{baz} i && bam='abc' i ]", - "[@ trait : @{foo}=@{foo} i &&bar=@{baz} i&&bam='abc'i\n]", - "[@\r\n\t trait\r\n\t : @{foo}=@{foo}]\r\n\t ", - "[@trait: @{foo|baz|bam|(boo)}=@{foo|bar|(boo)|baz}]", - "[@trait: @{foo|baz|bam|(boo)}=@{foo|bar|(boo)|baz}, @{foo|bam}]", - // Comma separated values are or'd together. - "[@trait: @{foo|baz|bam|(boo)}=@{foo|bar|(boo)|baz}, @{foo|bam} i && 10=10 i]", - "[@: foo=bar]", - "[@ : foo = bam ]" + "[@trait: 10=10]", + "[@trait: @{foo}=10]", + "[@trait: @{foo}=@{foo}]", + "[@trait: @{foo}=@{foo} && bar=bar]", + "[@trait: @{foo}=@{foo} && bar=10]", + "[@trait: @{foo}=@{foo} && bar=@{baz}]", + "[@trait: @{foo}=@{foo} && bar=@{baz} && bam='abc']", + "[@trait: @{foo}=@{foo} i && bar=@{baz} i && bam='abc' i ]", + "[@ trait : @{foo}=@{foo} i &&bar=@{baz} i&&bam='abc'i\n]", + "[@\r\n\t trait\r\n\t : @{foo}=@{foo}]\r\n\t ", + "[@trait: @{foo|baz|bam|(boo)}=@{foo|bar|(boo)|baz}]", + "[@trait: @{foo|baz|bam|(boo)}=@{foo|bar|(boo)|baz}, @{foo|bam}]", + // Comma separated values are or'd together. + "[@trait: @{foo|baz|bam|(boo)}=@{foo|bar|(boo)|baz}, @{foo|bam} i && 10=10 i]", + "[@: foo=bar]", + "[@ : foo = bam ]" ); for (String expr : exprs) { @@ -709,35 +709,35 @@ public void parsesValidScopedAttributes() { @Test public void detectsInvalidScopedAttributes() { List exprs = ListUtils.of( - "[@", - "[@foo", - "[@foo:", - "[@foo: bar", - "[@foo: bar=", - "[@foo: bar=bam", - "[@foo: bar=bam i", - "[@foo: bar+bam]", // Invalid comparator - "[@foo: @", - "[@foo: @{", - "[@foo: @{abc", - "[@foo: @{abc}", - "[@foo: @{abc}]", - "[@foo: @{abc}=", - "[@foo: @{abc}=10", - "[@foo: @{abc}=10 &&", - "[@foo: @{abc}=10 && abc", - "[@foo: @{abc}=10 && abc=", - "[@foo: @{abc}=10 && abc=def", - "[@foo: @{abc}=10 && abc=def i", - "[@foo: @{abc{}}=10]", - "[@foo: @{abc|}=10]", - "[@foo: @{abc|def(baz)}=10]", // not a valid segment - "[@foo: @{abc|()}=10]", // missing contents of () - "[@foo: @{abc|(.)}=10]", // invalid contents of ()); - "[@:", - "[@: bar", - "[@: bar]", - "[@: bar=bam" + "[@", + "[@foo", + "[@foo:", + "[@foo: bar", + "[@foo: bar=", + "[@foo: bar=bam", + "[@foo: bar=bam i", + "[@foo: bar+bam]", // Invalid comparator + "[@foo: @", + "[@foo: @{", + "[@foo: @{abc", + "[@foo: @{abc}", + "[@foo: @{abc}]", + "[@foo: @{abc}=", + "[@foo: @{abc}=10", + "[@foo: @{abc}=10 &&", + "[@foo: @{abc}=10 && abc", + "[@foo: @{abc}=10 && abc=", + "[@foo: @{abc}=10 && abc=def", + "[@foo: @{abc}=10 && abc=def i", + "[@foo: @{abc{}}=10]", + "[@foo: @{abc|}=10]", + "[@foo: @{abc|def(baz)}=10]", // not a valid segment + "[@foo: @{abc|()}=10]", // missing contents of () + "[@foo: @{abc|(.)}=10]", // invalid contents of ()); + "[@:", + "[@: bar", + "[@: bar]", + "[@: bar=bam" ); for (String expr : exprs) { @@ -759,20 +759,20 @@ public void evaluatesScopedAttributes() { @Test public void evaluatesScopedAttributesWithOr() { final Model enumModel = Model.assembler() - .addImport(SelectorTest.class.getResource("enums.smithy")) - .assemble() - .unwrap(); + .addImport(SelectorTest.class.getResource("enums.smithy")) + .assemble() + .unwrap(); Set shapes = ids( - enumModel, - "[@trait|enum|(values): @{name} ^= DIA, CLU]" + enumModel, + "[@trait|enum|(values): @{name} ^= DIA, CLU]" ); assertThat(shapes, containsInAnyOrder("smithy.example#Suit")); shapes = ids( - enumModel, - "[@trait|enum|(values): @{name} ^= DIA, BLA]" + enumModel, + "[@trait|enum|(values): @{name} ^= DIA, BLA]" ); assertThat(shapes, containsInAnyOrder("smithy.example#Color", "smithy.example#Suit")); @@ -799,16 +799,16 @@ public void projectionsCanMatchThemselvesThroughIntersection() { @Test public void nestedProjectionsAreFlattened() { Set shapes1 = ids( - traitModel, - "[@trait|smithy.example#listyTrait|(values)|(values)|(values): @{foo}=a]" + traitModel, + "[@trait|smithy.example#listyTrait|(values)|(values)|(values): @{foo}=a]" ); Set shapes2 = ids( - traitModel, - "[@trait|smithy.example#listyTrait|(values)|(values)|(values): @{foo}=b]" + traitModel, + "[@trait|smithy.example#listyTrait|(values)|(values)|(values): @{foo}=b]" ); Set shapes3 = ids( - traitModel, - "[@trait|smithy.example#listyTrait|(values)|(values)|(values): @{foo}=c]" + traitModel, + "[@trait|smithy.example#listyTrait|(values)|(values)|(values): @{foo}=c]" ); assertThat(shapes1, contains("smithy.example#MyService")); @@ -850,8 +850,8 @@ public void getsTheLengthOfTraitString() { @Test public void getsTheLengthOfTraitArray() { Set shapes = ids( - traitModel, - "[id=smithy.example#MyService][trait|smithy.example#listyTrait|(length) = 2]" + traitModel, + "[id=smithy.example#MyService][trait|smithy.example#listyTrait|(length) = 2]" ); assertThat(shapes, contains("smithy.example#MyService")); @@ -860,8 +860,8 @@ public void getsTheLengthOfTraitArray() { @Test public void getsTheLengthOfTraitObject() { Set shapes = ids( - traitModel, - "[id=smithy.example#DocumentedString2][trait|externalDocumentation|(length) = 1]" + traitModel, + "[id=smithy.example#DocumentedString2][trait|externalDocumentation|(length) = 1]" ); assertThat(shapes, contains("smithy.example#DocumentedString2")); @@ -872,8 +872,8 @@ public void projectionLengthUsesSetLogic() { // Find shapes with the enum trait where there are more than 1 tags on any // enum definition. Set shapes = exampleIds( - traitModel, - "[trait|enum|(values)|tags|(length) > 1]" + traitModel, + "[trait|enum|(values)|tags|(length) > 1]" ); assertThat(shapes, contains("smithy.example#DocumentedString1")); @@ -882,12 +882,12 @@ public void projectionLengthUsesSetLogic() { @Test public void canBindShapeAsContext() { assertThat( - ids(traitModel, "[trait|trait][@: @{trait|(keys)} = @{id}]"), - hasItems( - "smithy.example#recursiveTrait", - "smithy.api#trait", - "smithy.api#documentation" - ) + ids(traitModel, "[trait|trait][@: @{trait|(keys)} = @{id}]"), + hasItems( + "smithy.example#recursiveTrait", + "smithy.api#trait", + "smithy.api#documentation" + ) ); } @@ -899,11 +899,11 @@ public void parsesSubsetOperator() { @Test public void parsesValidProjectionComparators() { List exprs = ListUtils.of( - "[@: @{trait|tags|(values)} {<<} @{trait|tags|(values)}]", - "[@: @{trait|tags|(values)} {<} @{trait|tags|(values)}]", - "[@: @{trait|tags|(values)} {!=} @{trait|tags|(values)}]", - "[@: @{trait|tags|(values)} {=} @{trait|tags|(values)}]", - "[@: @{trait|tags|(values)} {=} @{trait|tags|(values)}]" + "[@: @{trait|tags|(values)} {<<} @{trait|tags|(values)}]", + "[@: @{trait|tags|(values)} {<} @{trait|tags|(values)}]", + "[@: @{trait|tags|(values)} {!=} @{trait|tags|(values)}]", + "[@: @{trait|tags|(values)} {=} @{trait|tags|(values)}]", + "[@: @{trait|tags|(values)} {=} @{trait|tags|(values)}]" ); for (String expr : exprs) { @@ -914,10 +914,10 @@ public void parsesValidProjectionComparators() { @Test public void detectsInvalidProjectionComparators() { List exprs = ListUtils.of( - "[@: @{trait|tags|(values)} {} @{trait|tags|(values)}]", - "[@: @{trait|tags|(values)} {<<", - "[@: @{trait|tags|(values)} {<", - "[@: @{trait|tags|(values)} {" + "[@: @{trait|tags|(values)} {} @{trait|tags|(values)}]", + "[@: @{trait|tags|(values)} {<<", + "[@: @{trait|tags|(values)} {<", + "[@: @{trait|tags|(values)} {" ); for (String expr : exprs) { @@ -928,21 +928,21 @@ public void detectsInvalidProjectionComparators() { @Test public void canQueryVariablesAtPointTheyWereMatched() { Model result = Model.assembler() - .addImport(SelectorTest.class.getResource("service-with-bad-auth.smithy")) - .assemble() - .getResult() - .get(); + .addImport(SelectorTest.class.getResource("service-with-bad-auth.smithy")) + .assemble() + .getResult() + .get(); // Find all operation shapes that are in the closure of a service that use // auth traits that don't match the auth traits associated with the service. Selector selector = Selector.parse( - "service\n" - + "$service(*)\n" - + "$authTraits(-[trait]-> [trait|authDefinition])\n" - + "~>\n" - + "operation\n" - + "[trait|auth]" - + ":not([@: @{trait|auth|(values)} {<} @{var|authTraits|id}]))" + "service\n" + + "$service(*)\n" + + "$authTraits(-[trait]-> [trait|authDefinition])\n" + + "~>\n" + + "operation\n" + + "[trait|auth]" + + ":not([@: @{trait|auth|(values)} {<} @{var|authTraits|id}]))" ); List>>> results = new ArrayList<>(); @@ -957,34 +957,34 @@ public void canQueryVariablesAtPointTheyWereMatched() { // as it passes through the selector. These test that each select saw different, // expected variables. checkMatches( - results, - "Expected smithy.example#HasDigestAuth with a service of smithy.example#MyService1", - (s, v) -> s.getId().equals(ShapeId.from("smithy.example#HasDigestAuth")) - && v.containsKey("service") - && v.get("service").equals(SetUtils.of(service1)) + results, + "Expected smithy.example#HasDigestAuth with a service of smithy.example#MyService1", + (s, v) -> s.getId().equals(ShapeId.from("smithy.example#HasDigestAuth")) + && v.containsKey("service") + && v.get("service").equals(SetUtils.of(service1)) ); checkMatches( - results, - "Expected smithy.example#HasDigestAuth with a service of smithy.example#MyService2", - (s, v) -> s.getId().equals(ShapeId.from("smithy.example#HasDigestAuth")) - && v.containsKey("service") - && v.get("service").equals(SetUtils.of(service2)) + results, + "Expected smithy.example#HasDigestAuth with a service of smithy.example#MyService2", + (s, v) -> s.getId().equals(ShapeId.from("smithy.example#HasDigestAuth")) + && v.containsKey("service") + && v.get("service").equals(SetUtils.of(service2)) ); checkMatches( - results, - "Expected smithy.example#HasBasicAuth with a service of smithy.example#MyService2", - (s, v) -> s.getId().equals(ShapeId.from("smithy.example#HasBasicAuth")) - && v.containsKey("service") - && v.get("service").equals(SetUtils.of(service2)) + results, + "Expected smithy.example#HasBasicAuth with a service of smithy.example#MyService2", + (s, v) -> s.getId().equals(ShapeId.from("smithy.example#HasBasicAuth")) + && v.containsKey("service") + && v.get("service").equals(SetUtils.of(service2)) ); } private void checkMatches( - Iterable>>> matches, - String message, - BiPredicate>> test + Iterable>>> matches, + String message, + BiPredicate>> test ) { for (Pair>> match : matches) { if (test.test(match.left, match.right)) { @@ -998,20 +998,20 @@ private void checkMatches( @Test public void canPushAndRetrieveVariables() { Model result = Model.assembler() - .addImport(SelectorTest.class.getResource("service-with-bad-auth.smithy")) - .assemble() - .getResult() - .get(); + .addImport(SelectorTest.class.getResource("service-with-bad-auth.smithy")) + .assemble() + .getResult() + .get(); // Find all operation shapes that are in the closure of a service that uses // http bindings on other operations, but the operation does not use http bindings. Selector selector = Selector.parse( - "$service(service)\n" - + "${service}\n" - + "$operations(~> operation)\n" - + "$httpOperations(${operations}[trait|http])\n" - + "${operations}\n" - + ":not([trait|http])" + "$service(service)\n" + + "${service}\n" + + "$operations(~> operation)\n" + + "$httpOperations(${operations}[trait|http])\n" + + "${operations}\n" + + ":not([trait|http])" ); List>>> results = new ArrayList<>(); @@ -1027,15 +1027,15 @@ public void canPushAndRetrieveVariables() { for (Shape service : ListUtils.of(service1, service2)) { checkMatches( - results, - "Expected smithy.example#HasBasicAuth with a service of smithy.example#MyService1", - (s, v) -> s.getId().equals(ShapeId.from("smithy.example#HasBasicAuth")) - && v.containsKey("service") - && v.containsKey("operations") - && v.containsKey("httpOperations") - && v.get("service").equals(SetUtils.of(service)) - && v.get("operations").equals(SetUtils.of(digestAuth, noAuth, basicAuth)) - && v.get("httpOperations").equals(SetUtils.of(digestAuth, noAuth)) + results, + "Expected smithy.example#HasBasicAuth with a service of smithy.example#MyService1", + (s, v) -> s.getId().equals(ShapeId.from("smithy.example#HasBasicAuth")) + && v.containsKey("service") + && v.containsKey("operations") + && v.containsKey("httpOperations") + && v.get("service").equals(SetUtils.of(service)) + && v.get("operations").equals(SetUtils.of(digestAuth, noAuth, basicAuth)) + && v.get("httpOperations").equals(SetUtils.of(digestAuth, noAuth)) ); } } @@ -1043,13 +1043,13 @@ public void canPushAndRetrieveVariables() { @Test public void parsesValidVariableAccess() { List exprs = ListUtils.of( - "${foo}", - "${ foo }", - "${\nfoo\n}\n", - "${a}", - "${a_b_c}", - "${_a}", - "${__a}" + "${foo}", + "${ foo }", + "${\nfoo\n}\n", + "${a}", + "${a_b_c}", + "${_a}", + "${__a}" ); for (String expr : exprs) { @@ -1060,14 +1060,14 @@ public void parsesValidVariableAccess() { @Test public void detectsInvalidVariableAccess() { List exprs = ListUtils.of( - "$", - "${", - "${}", - "$}", - "${a", - "${*}", - "${_}", - "${__}" + "$", + "${", + "${}", + "$}", + "${a", + "${*}", + "${_}", + "${__}" ); for (String expr : exprs) { @@ -1086,8 +1086,8 @@ public void findsOperationsMissingHttpBindings() { public void returnsStreamOfShapes() { Selector selector = Selector.parse(":test(string, map)"); Set shapes = selector - .shapes(modelJson) - .collect(Collectors.toSet()); + .shapes(modelJson) + .collect(Collectors.toSet()); assertThat(shapes, equalTo(selector.select(modelJson))); } @@ -1096,8 +1096,8 @@ public void returnsStreamOfShapes() { public void returnsStreamOfMatches() { Selector selector = Selector.parse(OPERATIONS_MISSING_BINDINGS); Set matches = selector - .matches(httpModel) - .collect(Collectors.toSet()); + .matches(httpModel) + .collect(Collectors.toSet()); Set matches2 = new HashSet<>(); selector.consumeMatches(httpModel, matches2::add); @@ -1108,14 +1108,14 @@ public void returnsStreamOfMatches() { @Test public void canPathToErrorsOfStructure() { ServiceShape service = ServiceShape.builder() - .id("ns.foo#Svc") - .version("2017-01-17") - .addError("ns.foo#Common1") - .build(); + .id("ns.foo#Svc") + .version("2017-01-17") + .addError("ns.foo#Common1") + .build(); StructureShape errorShape = StructureShape.builder() - .id("ns.foo#Common1") - .addTrait(new ErrorTrait("client")) - .build(); + .id("ns.foo#Common1") + .addTrait(new ErrorTrait("client")) + .build(); Model model = Model.builder().addShapes(service, errorShape).build(); Selector selector = Selector.parse("service -[error]-> structure"); @@ -1127,36 +1127,36 @@ public void canPathToErrorsOfStructure() { @Test public void selectsStructuresWithMixins() { Model model = Model.assembler() - .addImport(getClass().getResource("structure-with-mixins.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("structure-with-mixins.smithy")) + .assemble() + .unwrap(); Selector hasMixins = Selector.parse("structure :test(-[mixin]->)"); Selector isUsedMixin = Selector.parse("structure -[mixin]->"); Selector noMixins = Selector.parse("structure[id|namespace='smithy.example'] :not(-[mixin]->)"); Selector unusedMixin = Selector.parse("[trait|mixin][id|namespace='smithy.example'] :not(<-[mixin]-)"); assertThat( - hasMixins.select(model).stream().map(Shape::toShapeId).collect(Collectors.toSet()), - containsInAnyOrder(ShapeId.from("smithy.example#Mixin2"), ShapeId.from("smithy.example#Concrete")) + hasMixins.select(model).stream().map(Shape::toShapeId).collect(Collectors.toSet()), + containsInAnyOrder(ShapeId.from("smithy.example#Mixin2"), ShapeId.from("smithy.example#Concrete")) ); assertThat( - isUsedMixin.select(model).stream().map(Shape::toShapeId).collect(Collectors.toSet()), - containsInAnyOrder(ShapeId.from("smithy.example#Mixin1"), ShapeId.from("smithy.example#Mixin2")) + isUsedMixin.select(model).stream().map(Shape::toShapeId).collect(Collectors.toSet()), + containsInAnyOrder(ShapeId.from("smithy.example#Mixin1"), ShapeId.from("smithy.example#Mixin2")) ); assertThat( - noMixins.select(model).stream().map(Shape::toShapeId).collect(Collectors.toSet()), - containsInAnyOrder( - ShapeId.from("smithy.example#Mixin1"), - ShapeId.from("smithy.example#NoMixins"), - ShapeId.from("smithy.example#UnusedMixin") - ) + noMixins.select(model).stream().map(Shape::toShapeId).collect(Collectors.toSet()), + containsInAnyOrder( + ShapeId.from("smithy.example#Mixin1"), + ShapeId.from("smithy.example#NoMixins"), + ShapeId.from("smithy.example#UnusedMixin") + ) ); assertThat( - unusedMixin.select(model).stream().map(Shape::toShapeId).collect(Collectors.toSet()), - contains(ShapeId.from("smithy.example#UnusedMixin")) + unusedMixin.select(model).stream().map(Shape::toShapeId).collect(Collectors.toSet()), + contains(ShapeId.from("smithy.example#UnusedMixin")) ); } @@ -1164,35 +1164,35 @@ public void selectsStructuresWithMixins() { public void supportsResourceProperties() { Set resourcesWithProperties = Selector.parse("resource :test(-[property]->)").select(resourceModel); ResourceShape forecastResource = resourceModel.expectShape( - ShapeId.from("example.weather#Forecast"), - ResourceShape.class + ShapeId.from("example.weather#Forecast"), + ResourceShape.class ); ResourceShape cityResource = resourceModel.expectShape( - ShapeId.from("example.weather#City"), - ResourceShape.class + ShapeId.from("example.weather#City"), + ResourceShape.class ); assertThat(resourcesWithProperties.size(), equalTo(2)); assertThat(resourcesWithProperties, containsInAnyOrder(forecastResource, cityResource)); Set shapesTargettedByAnyProperty = Selector.parse("resource -[property]-> *").select(resourceModel); StructureShape coordinatesShape = resourceModel.expectShape( - ShapeId.from("example.weather#CityCoordinates"), - StructureShape.class + ShapeId.from("example.weather#CityCoordinates"), + StructureShape.class ); FloatShape floatShape = resourceModel.expectShape(ShapeId.from("smithy.api#Float"), FloatShape.class); StringShape stringShape = resourceModel.expectShape(ShapeId.from("smithy.api#String"), StringShape.class); assertThat(shapesTargettedByAnyProperty.size(), equalTo(3)); assertThat( - shapesTargettedByAnyProperty, - containsInAnyOrder( - coordinatesShape, - floatShape, - stringShape - ) + shapesTargettedByAnyProperty, + containsInAnyOrder( + coordinatesShape, + floatShape, + stringShape + ) ); Set shapesTargettedByCityOnly = Selector.parse("resource [id|name=City] -[property]-> *") - .select(resourceModel); + .select(resourceModel); assertThat(shapesTargettedByCityOnly.size(), equalTo(2)); assertThat(shapesTargettedByCityOnly, containsInAnyOrder(coordinatesShape, stringShape)); } @@ -1200,9 +1200,9 @@ public void supportsResourceProperties() { @Test public void rootFunctionReturnsAllShapes() { Selector selector = Selector.parse( - "string" - + ":in(:root(-[input]-> ~> *))" - + ":not(:in(:root(-[output]-> ~> *)))" + "string" + + ":in(:root(-[input]-> ~> *))" + + ":not(:in(:root(-[output]-> ~> *)))" ); Set result = selector.select(resourceModel); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeCategorySelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeCategorySelectorTest.java index fd727b7f6fa..8eb9e6d83ff 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeCategorySelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeCategorySelectorTest.java @@ -19,9 +19,9 @@ public class ShapeTypeCategorySelectorTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(SelectorTest.class.getResource("shape-type-test.smithy")) - .assemble() - .unwrap(); + .addImport(SelectorTest.class.getResource("shape-type-test.smithy")) + .assemble() + .unwrap(); } @Test diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeSelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeSelectorTest.java index bf0b24efdfa..483fa86be0e 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeSelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeSelectorTest.java @@ -19,9 +19,9 @@ public class ShapeTypeSelectorTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(SelectorTest.class.getResource("shape-type-test.smithy")) - .assemble() - .unwrap(); + .addImport(SelectorTest.class.getResource("shape-type-test.smithy")) + .assemble() + .unwrap(); } @Test diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/SpecIntegTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/SpecIntegTest.java index 7fb7cf6f412..a3eb7428ea0 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/SpecIntegTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/SpecIntegTest.java @@ -30,36 +30,36 @@ public class SpecIntegTest { @BeforeAll public static void before() { attributeExistenceModel = Model.assembler() - .addImport(SelectorTest.class.getResource("attribute-existence.smithy")) - .assemble() - .unwrap(); + .addImport(SelectorTest.class.getResource("attribute-existence.smithy")) + .assemble() + .unwrap(); allowedTagsModel = Model.assembler() - .addImport(SelectorTest.class.getResource("allowed-tags-example.smithy")) - .assemble() - .unwrap(); + .addImport(SelectorTest.class.getResource("allowed-tags-example.smithy")) + .assemble() + .unwrap(); } @Test public void attributeExistence_MatchesShapesWithTrait() { // Simple existence check. assertThat( - SelectorTest.exampleIds(attributeExistenceModel, "[trait|deprecated]"), - containsInAnyOrder("smithy.example#DeprecatedString") + SelectorTest.exampleIds(attributeExistenceModel, "[trait|deprecated]"), + containsInAnyOrder("smithy.example#DeprecatedString") ); // Empty tags traits still exist. assertThat( - SelectorTest.exampleIds(attributeExistenceModel, "[trait|tags]"), - containsInAnyOrder("smithy.example#MyString2") + SelectorTest.exampleIds(attributeExistenceModel, "[trait|tags]"), + containsInAnyOrder("smithy.example#MyString2") ); assertThat( - SelectorTest.exampleIds(attributeExistenceModel, "[trait|enum]"), - containsInAnyOrder( - "smithy.example#MyString3", - "smithy.example#MyString4", - "smithy.example#MyString5" - ) + SelectorTest.exampleIds(attributeExistenceModel, "[trait|enum]"), + containsInAnyOrder( + "smithy.example#MyString3", + "smithy.example#MyString4", + "smithy.example#MyString5" + ) ); } @@ -70,36 +70,36 @@ public void attributeExistence_MatchesShapesWithProjection() { // An empty projection does not exist. assertThat( - SelectorTest.exampleIds(attributeExistenceModel, "[trait|enum|(values)]"), - containsInAnyOrder( - "smithy.example#MyString3", - "smithy.example#MyString4", - "smithy.example#MyString5" - ) + SelectorTest.exampleIds(attributeExistenceModel, "[trait|enum|(values)]"), + containsInAnyOrder( + "smithy.example#MyString3", + "smithy.example#MyString4", + "smithy.example#MyString5" + ) ); assertThat( - SelectorTest.exampleIds(attributeExistenceModel, "[trait|enum|(values)|tags]"), - containsInAnyOrder("smithy.example#MyString5") + SelectorTest.exampleIds(attributeExistenceModel, "[trait|enum|(values)|tags]"), + containsInAnyOrder("smithy.example#MyString5") ); // An empty projection does not exist. assertThat( - SelectorTest.exampleIds(attributeExistenceModel, "[trait|enum|(values)|tags|(values)]"), - containsInAnyOrder("smithy.example#MyString5") + SelectorTest.exampleIds(attributeExistenceModel, "[trait|enum|(values)|tags|(values)]"), + containsInAnyOrder("smithy.example#MyString5") ); } @Test public void allowedTags_MatchesShapesThatViolateExample() { Set ids = SelectorTest.ids( - allowedTagsModel, - "service\n" - + "[trait|smithy.example#allowedTags]\n" - + "$service(*)\n" - + "~>\n" - + "[trait|tags]\n" - + ":not([@: @{trait|tags|(values)} = @{var|service|trait|smithy.example#allowedTags|(values)}])" + allowedTagsModel, + "service\n" + + "[trait|smithy.example#allowedTags]\n" + + "$service(*)\n" + + "~>\n" + + "[trait|tags]\n" + + ":not([@: @{trait|tags|(values)} = @{var|service|trait|smithy.example#allowedTags|(values)}])" ); assertThat(ids, contains("smithy.example#OperationD")); @@ -108,25 +108,25 @@ public void allowedTags_MatchesShapesThatViolateExample() { @Test public void allowedTags_illustratesWhyProjectionComparatorsExist() { Set noneMatch = SelectorTest.ids( - allowedTagsModel, - "service\n" - + "[trait|smithy.example#allowedTags]\n" - + "$service(*)\n" - + "~>\n" - + "[trait|enum]\n" - + ":not([@: @{trait|enum|(values)|tags|(values)}" - + " = @{var|service|trait|smithy.example#allowedTags|(values)}])" + allowedTagsModel, + "service\n" + + "[trait|smithy.example#allowedTags]\n" + + "$service(*)\n" + + "~>\n" + + "[trait|enum]\n" + + ":not([@: @{trait|enum|(values)|tags|(values)}" + + " = @{var|service|trait|smithy.example#allowedTags|(values)}])" ); Set notWhatWeWanted = SelectorTest.ids( - allowedTagsModel, - "service\n" - + "[trait|smithy.example#allowedTags]\n" - + "$service(*)\n" - + "~>\n" - + "[trait|enum]\n" - + "[@: @{trait|enum|(values)|tags|(values)}" - + " != @{var|service|trait|smithy.example#allowedTags|(values)}]" + allowedTagsModel, + "service\n" + + "[trait|smithy.example#allowedTags]\n" + + "$service(*)\n" + + "~>\n" + + "[trait|enum]\n" + + "[@: @{trait|enum|(values)|tags|(values)}" + + " != @{var|service|trait|smithy.example#allowedTags|(values)}]" ); assertThat(noneMatch, empty()); @@ -136,14 +136,14 @@ public void allowedTags_illustratesWhyProjectionComparatorsExist() { @Test public void allowedTags_matchesEnumsUsingSubset() { Set ids = SelectorTest.ids( - allowedTagsModel, - "service\n" - + "[trait|smithy.example#allowedTags]\n" - + "$service(*)\n" - + "~>\n" - + "[trait|enum]\n" - + ":not([@: @{trait|enum|(values)|tags|(values)}" - + " {<} @{var|service|trait|smithy.example#allowedTags|(values)}])" + allowedTagsModel, + "service\n" + + "[trait|smithy.example#allowedTags]\n" + + "$service(*)\n" + + "~>\n" + + "[trait|enum]\n" + + ":not([@: @{trait|enum|(values)|tags|(values)}" + + " {<} @{var|service|trait|smithy.example#allowedTags|(values)}])" ); assertThat(ids, contains("smithy.example#BadEnum")); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/TopDownSelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/TopDownSelectorTest.java index 978eaed7ddf..dd1846d4b83 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/TopDownSelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/TopDownSelectorTest.java @@ -26,14 +26,14 @@ public class TopDownSelectorTest { @BeforeAll public static void before() { model1 = Model.assembler() - .addImport(SelectorTest.class.getResource("topdown-auth.smithy")) - .assemble() - .unwrap(); + .addImport(SelectorTest.class.getResource("topdown-auth.smithy")) + .assemble() + .unwrap(); model2 = Model.assembler() - .addImport(SelectorTest.class.getResource("topdown-exclusive-traits.smithy")) - .assemble() - .unwrap(); + .addImport(SelectorTest.class.getResource("topdown-exclusive-traits.smithy")) + .assemble() + .unwrap(); } @Test @@ -49,32 +49,32 @@ public void doesNotAllowMoreThanTwoSelectors() { @Test public void findsByAuthScheme() { Set basic = SelectorTest.ids( - model1, - ":topdown([trait|auth|(values)='smithy.api#httpBasicAuth'],\n" - + " [trait|auth]:not([trait|auth|(values)='smithy.api#httpBasicAuth']))" + model1, + ":topdown([trait|auth|(values)='smithy.api#httpBasicAuth'],\n" + + " [trait|auth]:not([trait|auth|(values)='smithy.api#httpBasicAuth']))" ); Set digest = SelectorTest.ids( - model1, - ":topdown([trait|auth|(values)='smithy.api#httpDigestAuth'],\n" - + " [trait|auth]:not([trait|auth|(values)='smithy.api#httpDigestAuth']))" + model1, + ":topdown([trait|auth|(values)='smithy.api#httpDigestAuth'],\n" + + " [trait|auth]:not([trait|auth|(values)='smithy.api#httpDigestAuth']))" ); assertThat( - basic, - containsInAnyOrder( - "smithy.example#RA", - "smithy.example#ServiceWithAuthTrait", - "smithy.example#OperationWithNoAuthTrait" - ) + basic, + containsInAnyOrder( + "smithy.example#RA", + "smithy.example#ServiceWithAuthTrait", + "smithy.example#OperationWithNoAuthTrait" + ) ); assertThat( - digest, - containsInAnyOrder( - "smithy.example#ServiceWithAuthTrait", - "smithy.example#OperationWithNoAuthTrait", - "smithy.example#RA", - "smithy.example#OperationWithAuthTrait" - ) + digest, + containsInAnyOrder( + "smithy.example#ServiceWithAuthTrait", + "smithy.example#OperationWithNoAuthTrait", + "smithy.example#RA", + "smithy.example#OperationWithAuthTrait" + ) ); } @@ -85,13 +85,13 @@ public void findsExclusiveTraits() { assertThat(a, containsInAnyOrder("smithy.example#Service1", "smithy.example#R1", "smithy.example#O2")); assertThat( - b, - containsInAnyOrder( - "smithy.example#R2", - "smithy.example#O1", - "smithy.example#O3", - "smithy.example#O4" - ) + b, + containsInAnyOrder( + "smithy.example#R2", + "smithy.example#O1", + "smithy.example#O3", + "smithy.example#O4" + ) ); } @@ -100,16 +100,16 @@ public void topDownWithNoDisqualifiers() { Set a = SelectorTest.ids(model2, ":topdown([trait|smithy.example#a])"); assertThat( - a, - containsInAnyOrder( - "smithy.example#Service1", - "smithy.example#R1", - "smithy.example#O1", - "smithy.example#O2", - "smithy.example#R2", - "smithy.example#O3", - "smithy.example#O4" - ) + a, + containsInAnyOrder( + "smithy.example#Service1", + "smithy.example#R1", + "smithy.example#O1", + "smithy.example#O2", + "smithy.example#R2", + "smithy.example#O3", + "smithy.example#O4" + ) ); } @@ -117,9 +117,9 @@ public void topDownWithNoDisqualifiers() { public void topDownWithNoDisqualifiersWithServiceVariableFollowedByFilter() { Map matches = new HashMap<>(); Selector.parse("service $service(*) :topdown([trait|smithy.example#a]) resource") - .consumeMatches(model2, match -> { - matches.put(match.getShape().getId(), match.get("service").iterator().next().getId()); - }); + .consumeMatches(model2, match -> { + matches.put(match.getShape().getId(), match.get("service").iterator().next().getId()); + }); assertThat(matches, hasKey(ShapeId.from("smithy.example#R1"))); assertThat(matches.get(ShapeId.from("smithy.example#R1")), equalTo(ShapeId.from("smithy.example#Service1"))); @@ -130,10 +130,10 @@ public void topDownWithNoDisqualifiersWithServiceVariableFollowedByFilter() { @Test public void doesNotOverflowOnBrokenResourceCycles() { Model recursiveModel = Model.assembler() - .addImport(getClass().getResource("recursive-resources.smithy")) - .assemble() - .getResult() - .get(); // we know it's invalid. + .addImport(getClass().getResource("recursive-resources.smithy")) + .assemble() + .getResult() + .get(); // we know it's invalid. // The result isn't really important here. We just don't want it to // cause a stack overflow. diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/EntityShapeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/EntityShapeTest.java index 08a2e71ed81..5f709c15058 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/EntityShapeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/EntityShapeTest.java @@ -16,8 +16,8 @@ public class EntityShapeTest { @Test public void operationsAreOrdered() { ServiceShape.Builder builder = ServiceShape.builder() - .id("com.foo#Bar") - .version("1"); + .id("com.foo#Bar") + .version("1"); List operations = new ArrayList<>(20); for (int i = 0; i < 20; i++) { @@ -34,8 +34,8 @@ public void operationsAreOrdered() { @Test public void resourcesAreOrdered() { ServiceShape.Builder builder = ServiceShape.builder() - .id("com.foo#Bar") - .version("1"); + .id("com.foo#Bar") + .version("1"); List resources = new ArrayList<>(20); for (int i = 0; i < 20; i++) { diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/EnumShapeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/EnumShapeTest.java index ef70baec682..fb3a1249652 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/EnumShapeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/EnumShapeTest.java @@ -51,23 +51,23 @@ public void addMember() { EnumShape.Builder builder = (EnumShape.Builder) EnumShape.builder().id("ns.foo#bar"); EnumShape shape = builder.addMember("foo", "bar").build(); assertEquals( - shape.getMember("foo").get(), - MemberShape.builder() - .id(shape.getId().withMember("foo")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bar").build()) - .build() + shape.getMember("foo").get(), + MemberShape.builder() + .id(shape.getId().withMember("foo")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bar").build()) + .build() ); assertTrue(shape.hasTrait(EnumTrait.class)); assertEquals( - shape.expectTrait(EnumTrait.class).getValues(), - ListUtils.of( - EnumDefinition.builder() - .name("foo") - .value("bar") - .build() - ) + shape.expectTrait(EnumTrait.class).getValues(), + ListUtils.of( + EnumDefinition.builder() + .name("foo") + .value("bar") + .build() + ) ); } @@ -75,22 +75,22 @@ public void addMember() { public void addMemberShape() { EnumShape.Builder builder = (EnumShape.Builder) EnumShape.builder().id("ns.foo#bar"); MemberShape member = MemberShape.builder() - .id("ns.foo#bar$foo") - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bar").build()) - .build(); + .id("ns.foo#bar$foo") + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bar").build()) + .build(); EnumShape shape = builder.addMember(member).build(); assertEquals(shape.getMember("foo").get(), member); assertTrue(shape.hasTrait(EnumTrait.class)); assertEquals( - shape.expectTrait(EnumTrait.class).getValues(), - ListUtils.of( - EnumDefinition.builder() - .name("foo") - .value("bar") - .build() - ) + shape.expectTrait(EnumTrait.class).getValues(), + ListUtils.of( + EnumDefinition.builder() + .name("foo") + .value("bar") + .build() + ) ); } @@ -98,25 +98,25 @@ public void addMemberShape() { public void memberValueIsAppliedIfNotPresent() { EnumShape.Builder builder = (EnumShape.Builder) EnumShape.builder().id("ns.foo#bar"); MemberShape member = MemberShape.builder() - .id("ns.foo#bar$foo") - .target(UnitTypeTrait.UNIT) - .build(); + .id("ns.foo#bar$foo") + .target(UnitTypeTrait.UNIT) + .build(); EnumShape shape = builder.addMember(member).build(); MemberShape expected = member.toBuilder() - .addTrait(EnumValueTrait.builder().stringValue("foo").build()) - .build(); + .addTrait(EnumValueTrait.builder().stringValue("foo").build()) + .build(); assertEquals(shape.getMember("foo").get(), expected); assertTrue(shape.hasTrait(EnumTrait.class)); assertEquals( - shape.expectTrait(EnumTrait.class).getValues(), - ListUtils.of( - EnumDefinition.builder() - .name("foo") - .value("foo") - .build() - ) + shape.expectTrait(EnumTrait.class).getValues(), + ListUtils.of( + EnumDefinition.builder() + .name("foo") + .value("foo") + .build() + ) ); } @@ -124,21 +124,21 @@ public void memberValueIsAppliedIfNotPresent() { public void addMemberFromEnumTrait() { EnumShape.Builder builder = (EnumShape.Builder) EnumShape.builder().id("ns.foo#bar"); EnumDefinition enumDefinition = EnumDefinition.builder() - .name("foo") - .value("bar") - .tags(ListUtils.of("internal")) - .build(); + .name("foo") + .value("bar") + .tags(ListUtils.of("internal")) + .build(); EnumShape shape = builder.setMembersFromEnumTrait(EnumTrait.builder().addEnum(enumDefinition).build()).build(); assertEquals( - shape.getMember("foo").get(), - MemberShape.builder() - .id(shape.getId().withMember("foo")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bar").build()) - .addTrait(new InternalTrait()) - .addTrait(TagsTrait.builder().addValue("internal").build()) - .build() + shape.getMember("foo").get(), + MemberShape.builder() + .id(shape.getId().withMember("foo")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bar").build()) + .addTrait(new InternalTrait()) + .addTrait(TagsTrait.builder().addValue("internal").build()) + .build() ); assertTrue(shape.hasTrait(EnumTrait.class)); @@ -150,20 +150,20 @@ public void convertsDocsFromEnumTrait() { EnumShape.Builder builder = (EnumShape.Builder) EnumShape.builder().id("ns.foo#bar"); String docs = "docs"; EnumDefinition enumDefinition = EnumDefinition.builder() - .name("foo") - .value("bar") - .documentation(docs) - .build(); + .name("foo") + .value("bar") + .documentation(docs) + .build(); EnumShape shape = builder.setMembersFromEnumTrait(EnumTrait.builder().addEnum(enumDefinition).build()).build(); assertEquals( - shape.getMember("foo").get(), - MemberShape.builder() - .id(shape.getId().withMember("foo")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bar").build()) - .addTrait(new DocumentationTrait(docs)) - .build() + shape.getMember("foo").get(), + MemberShape.builder() + .id(shape.getId().withMember("foo")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bar").build()) + .addTrait(new DocumentationTrait(docs)) + .build() ); assertTrue(shape.hasTrait(EnumTrait.class)); @@ -175,20 +175,20 @@ public void convertsTagsFromEnumTrait() { EnumShape.Builder builder = (EnumShape.Builder) EnumShape.builder().id("ns.foo#bar"); String tag = "tag"; EnumDefinition enumDefinition = EnumDefinition.builder() - .name("foo") - .value("bar") - .addTag(tag) - .build(); + .name("foo") + .value("bar") + .addTag(tag) + .build(); EnumShape shape = builder.setMembersFromEnumTrait(EnumTrait.builder().addEnum(enumDefinition).build()).build(); assertEquals( - shape.getMember("foo").get(), - MemberShape.builder() - .id(shape.getId().withMember("foo")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bar").build()) - .addTrait(TagsTrait.builder().addValue(tag).build()) - .build() + shape.getMember("foo").get(), + MemberShape.builder() + .id(shape.getId().withMember("foo")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bar").build()) + .addTrait(TagsTrait.builder().addValue(tag).build()) + .build() ); assertTrue(shape.hasTrait(EnumTrait.class)); @@ -199,20 +199,20 @@ public void convertsTagsFromEnumTrait() { public void convertsDeprecatedFromEnumTrait() { EnumShape.Builder builder = (EnumShape.Builder) EnumShape.builder().id("ns.foo#bar"); EnumDefinition enumDefinition = EnumDefinition.builder() - .name("foo") - .value("bar") - .deprecated(true) - .build(); + .name("foo") + .value("bar") + .deprecated(true) + .build(); EnumShape shape = builder.setMembersFromEnumTrait(EnumTrait.builder().addEnum(enumDefinition).build()).build(); assertEquals( - shape.getMember("foo").get(), - MemberShape.builder() - .id(shape.getId().withMember("foo")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bar").build()) - .addTrait(DeprecatedTrait.builder().build()) - .build() + shape.getMember("foo").get(), + MemberShape.builder() + .id(shape.getId().withMember("foo")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bar").build()) + .addTrait(DeprecatedTrait.builder().build()) + .build() ); assertTrue(shape.hasTrait(EnumTrait.class)); @@ -231,12 +231,12 @@ public void convertsEnumUnchanged() { public void givenEnumTraitMustUseNames() { EnumShape.Builder builder = (EnumShape.Builder) EnumShape.builder().id("ns.foo#bar"); EnumTrait trait = EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .value("bar") - .build() - ) - .build(); + .addEnum( + EnumDefinition.builder() + .value("bar") + .build() + ) + .build(); Assertions.assertThrows(IllegalStateException.class, () -> { builder.setMembersFromEnumTrait(trait); @@ -247,29 +247,29 @@ public void givenEnumTraitMustUseNames() { public void givenEnumTraitMaySynthesizeNames() { EnumShape.Builder builder = (EnumShape.Builder) EnumShape.builder().id("ns.foo#bar"); EnumTrait trait = EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .value("foo:bar") - .build() - ) - .build(); + .addEnum( + EnumDefinition.builder() + .value("foo:bar") + .build() + ) + .build(); EnumShape shape = builder.setMembersFromEnumTrait(trait, true).build(); assertEquals( - shape.getMember("foo_bar").get(), - MemberShape.builder() - .id(shape.getId().withMember("foo_bar")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("foo:bar").build()) - .build() + shape.getMember("foo_bar").get(), + MemberShape.builder() + .id(shape.getId().withMember("foo_bar")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("foo:bar").build()) + .build() ); assertTrue(shape.hasTrait(EnumTrait.class)); EnumDefinition expectedDefinition = EnumDefinition.builder() - .name("foo_bar") - .value("foo:bar") - .build(); + .name("foo_bar") + .value("foo:bar") + .build(); assertEquals(shape.expectTrait(EnumTrait.class).getValues(), ListUtils.of(expectedDefinition)); } @@ -277,12 +277,12 @@ public void givenEnumTraitMaySynthesizeNames() { public void givenEnumTraitMayOnlySynthesizeNamesFromValidValues() { EnumShape.Builder builder = (EnumShape.Builder) EnumShape.builder().id("ns.foo#bar"); EnumTrait trait = EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .value("foo&bar") - .build() - ) - .build(); + .addEnum( + EnumDefinition.builder() + .value("foo&bar") + .build() + ) + .build(); Assertions.assertThrows(IllegalStateException.class, () -> { builder.setMembersFromEnumTrait(trait, true); @@ -294,51 +294,51 @@ public void addMultipleMembers() { EnumShape.Builder builder = (EnumShape.Builder) EnumShape.builder().id("ns.foo#bar"); EnumShape shape = builder.members( - ListUtils.of( - MemberShape.builder() - .id("ns.foo#bar$foo") - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bar").build()) - .build(), - MemberShape.builder() - .id("ns.foo#bar$baz") - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bam").build()) - .build() - ) + ListUtils.of( + MemberShape.builder() + .id("ns.foo#bar$foo") + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bar").build()) + .build(), + MemberShape.builder() + .id("ns.foo#bar$baz") + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bam").build()) + .build() + ) ).build(); assertEquals( - shape.getMember("foo").get(), - MemberShape.builder() - .id(shape.getId().withMember("foo")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bar").build()) - .build() + shape.getMember("foo").get(), + MemberShape.builder() + .id(shape.getId().withMember("foo")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bar").build()) + .build() ); assertEquals( - shape.getMember("baz").get(), - MemberShape.builder() - .id(shape.getId().withMember("baz")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bam").build()) - .build() + shape.getMember("baz").get(), + MemberShape.builder() + .id(shape.getId().withMember("baz")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bam").build()) + .build() ); assertTrue(shape.hasTrait(EnumTrait.class)); assertEquals( - shape.expectTrait(EnumTrait.class).getValues(), - ListUtils.of( - EnumDefinition.builder() - .name("foo") - .value("bar") - .build(), - EnumDefinition.builder() - .name("baz") - .value("bam") - .build() - ) + shape.expectTrait(EnumTrait.class).getValues(), + ListUtils.of( + EnumDefinition.builder() + .name("foo") + .value("bar") + .build(), + EnumDefinition.builder() + .name("baz") + .value("bam") + .build() + ) ); } @@ -347,18 +347,18 @@ public void removeMember() { EnumShape.Builder builder = (EnumShape.Builder) EnumShape.builder().id("ns.foo#bar"); builder.members( - ListUtils.of( - MemberShape.builder() - .id("ns.foo#bar$foo") - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bar").build()) - .build(), - MemberShape.builder() - .id("ns.foo#bar$baz") - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bam").build()) - .build() - ) + ListUtils.of( + MemberShape.builder() + .id("ns.foo#bar$foo") + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bar").build()) + .build(), + MemberShape.builder() + .id("ns.foo#bar$baz") + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bam").build()) + .build() + ) ); EnumShape shape = builder.removeMember("foo").build(); @@ -366,23 +366,23 @@ public void removeMember() { assertFalse(shape.getMember("foo").isPresent()); assertEquals( - shape.getMember("baz").get(), - MemberShape.builder() - .id(shape.getId().withMember("baz")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bam").build()) - .build() + shape.getMember("baz").get(), + MemberShape.builder() + .id(shape.getId().withMember("baz")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bam").build()) + .build() ); assertTrue(shape.hasTrait(EnumTrait.class)); assertEquals( - shape.expectTrait(EnumTrait.class).getValues(), - ListUtils.of( - EnumDefinition.builder() - .name("baz") - .value("bam") - .build() - ) + shape.expectTrait(EnumTrait.class).getValues(), + ListUtils.of( + EnumDefinition.builder() + .name("baz") + .value("bam") + .build() + ) ); } @@ -391,30 +391,30 @@ public void clearMembers() { EnumShape.Builder builder = (EnumShape.Builder) EnumShape.builder().id("ns.foo#bar"); EnumShape shape = builder.addMember("foo", "bar") - .clearMembers() - .addMember("baz", "bam") - .build(); + .clearMembers() + .addMember("baz", "bam") + .build(); assertEquals(1, shape.members().size()); assertEquals( - shape.getMember("baz").get(), - MemberShape.builder() - .id(shape.getId().withMember("baz")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bam").build()) - .build() + shape.getMember("baz").get(), + MemberShape.builder() + .id(shape.getId().withMember("baz")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bam").build()) + .build() ); assertTrue(shape.hasTrait(EnumTrait.class)); assertEquals( - shape.expectTrait(EnumTrait.class).getValues(), - ListUtils.of( - EnumDefinition.builder() - .name("baz") - .value("bam") - .build() - ) + shape.expectTrait(EnumTrait.class).getValues(), + ListUtils.of( + EnumDefinition.builder() + .name("baz") + .value("bam") + .build() + ) ); } @@ -422,10 +422,10 @@ public void clearMembers() { public void membersMustTargetUnit() { EnumShape.Builder builder = (EnumShape.Builder) EnumShape.builder().id("ns.foo#bar"); MemberShape member = MemberShape.builder() - .id("ns.foo#bar$foo") - .target("smithy.api#String") - .addTrait(EnumValueTrait.builder().stringValue("bar").build()) - .build(); + .id("ns.foo#bar$foo") + .target("smithy.api#String") + .addTrait(EnumValueTrait.builder().stringValue("bar").build()) + .build(); Assertions.assertThrows(SourceException.class, () -> { builder.addMember(member); }); @@ -434,18 +434,18 @@ public void membersMustTargetUnit() { @Test public void canConvertBaseString() { EnumTrait trait = EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("foo") - .value("bar") - .build() - ) - .build(); + .addEnum( + EnumDefinition.builder() + .name("foo") + .value("bar") + .build() + ) + .build(); StringShape string = StringShape.builder() - .id("ns.foo#bar") - .addTrait(trait) - .source("bar.smithy", 1, 1) - .build(); + .id("ns.foo#bar") + .addTrait(trait) + .source("bar.smithy", 1, 1) + .build(); Optional optionalEnum = EnumShape.fromStringShape(string); assertTrue(optionalEnum.isPresent()); SyntheticEnumTrait syntheticEnumTrait = optionalEnum.get().expectTrait(SyntheticEnumTrait.class); @@ -453,20 +453,20 @@ public void canConvertBaseString() { assertNotNull(syntheticEnumTrait.getSourceLocation()); assertEquals( - optionalEnum.get().getMember("foo").get(), - MemberShape.builder() - .id(optionalEnum.get().getId().withMember("foo")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bar").build()) - .build() + optionalEnum.get().getMember("foo").get(), + MemberShape.builder() + .id(optionalEnum.get().getId().withMember("foo")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bar").build()) + .build() ); } @Test public void cantConvertBaseStringWithoutEnumTrait() { StringShape string = StringShape.builder() - .id("ns.foo#bar") - .build(); + .id("ns.foo#bar") + .build(); Optional optionalEnum = EnumShape.fromStringShape(string); assertFalse(optionalEnum.isPresent()); } @@ -474,16 +474,16 @@ public void cantConvertBaseStringWithoutEnumTrait() { @Test public void cantConvertBaseStringWithNamelessEnumTrait() { EnumTrait trait = EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .value("bar") - .build() - ) - .build(); + .addEnum( + EnumDefinition.builder() + .value("bar") + .build() + ) + .build(); StringShape string = StringShape.builder() - .id("ns.foo#bar") - .addTrait(trait) - .build(); + .id("ns.foo#bar") + .addTrait(trait) + .build(); Optional optionalEnum = EnumShape.fromStringShape(string); assertFalse(optionalEnum.isPresent()); } @@ -500,17 +500,17 @@ public void getEnumValues() { @Test public void canConvertToEnumWithNamedEnumTrait() { EnumTrait trait = EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .value("foo&bar") // even if this value has invalid characters for a synthesized name - .name("BAR") - .build() - ) - .build(); + .addEnum( + EnumDefinition.builder() + .value("foo&bar") // even if this value has invalid characters for a synthesized name + .name("BAR") + .build() + ) + .build(); StringShape string = StringShape.builder() - .id("ns.foo#bar") - .addTrait(trait) - .build(); + .id("ns.foo#bar") + .addTrait(trait) + .build(); assertTrue(EnumShape.canConvertToEnum(string, false)); assertTrue(EnumShape.canConvertToEnum(string, true)); } @@ -518,16 +518,16 @@ public void canConvertToEnumWithNamedEnumTrait() { @Test public void canConvertToEnumWithNamelessEnumTrait() { EnumTrait trait = EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .value("bar") - .build() - ) - .build(); + .addEnum( + EnumDefinition.builder() + .value("bar") + .build() + ) + .build(); StringShape string = StringShape.builder() - .id("ns.foo#bar") - .addTrait(trait) - .build(); + .id("ns.foo#bar") + .addTrait(trait) + .build(); assertFalse(EnumShape.canConvertToEnum(string, false)); assertTrue(EnumShape.canConvertToEnum(string, true)); } @@ -535,16 +535,16 @@ public void canConvertToEnumWithNamelessEnumTrait() { @Test public void canConvertToEnumWithNonConvertableNamelessEnumTrait() { EnumTrait trait = EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .value("foo&bar") - .build() - ) - .build(); + .addEnum( + EnumDefinition.builder() + .value("foo&bar") + .build() + ) + .build(); StringShape string = StringShape.builder() - .id("ns.foo#bar") - .addTrait(trait) - .build(); + .id("ns.foo#bar") + .addTrait(trait) + .build(); assertFalse(EnumShape.canConvertToEnum(string, false)); assertFalse(EnumShape.canConvertToEnum(string, true)); } @@ -552,11 +552,11 @@ public void canConvertToEnumWithNonConvertableNamelessEnumTrait() { @Test public void syntheticEnumSupportsDocumentation() { EnumShape shape = EnumShape.builder() - .id("com.example#DocumentedEnum") - .addMember("documented", "foo", builder -> { - builder.addTrait(new DocumentationTrait("bar")); - }) - .build(); + .id("com.example#DocumentedEnum") + .addMember("documented", "foo", builder -> { + builder.addTrait(new DocumentationTrait("bar")); + }) + .build(); SyntheticEnumTrait trait = shape.expectTrait(SyntheticEnumTrait.class); assertEquals("bar", trait.getValues().get(0).getDocumentation().get()); @@ -565,11 +565,11 @@ public void syntheticEnumSupportsDocumentation() { @Test public void syntheticEnumSupportsDeprecated() { EnumShape shape = EnumShape.builder() - .id("com.example#DeprecatedEnum") - .addMember("deprecated", "foo", builder -> { - builder.addTrait(DeprecatedTrait.builder().build()); - }) - .build(); + .id("com.example#DeprecatedEnum") + .addMember("deprecated", "foo", builder -> { + builder.addTrait(DeprecatedTrait.builder().build()); + }) + .build(); SyntheticEnumTrait trait = shape.expectTrait(SyntheticEnumTrait.class); assertTrue(trait.getValues().get(0).isDeprecated()); @@ -578,11 +578,11 @@ public void syntheticEnumSupportsDeprecated() { @Test public void syntheticEnumSupportsTags() { EnumShape shape = EnumShape.builder() - .id("com.example#TaggedEnum") - .addMember("tagged", "foo", builder -> { - builder.addTrait(TagsTrait.builder().addValue("bar").build()); - }) - .build(); + .id("com.example#TaggedEnum") + .addMember("tagged", "foo", builder -> { + builder.addTrait(TagsTrait.builder().addValue("bar").build()); + }) + .build(); SyntheticEnumTrait trait = shape.expectTrait(SyntheticEnumTrait.class); assertEquals(ListUtils.of("bar"), trait.getValues().get(0).getTags()); @@ -591,15 +591,15 @@ public void syntheticEnumSupportsTags() { @Test public void syntheticEnumSupportsInternal() { EnumShape shape = EnumShape.builder() - .id("com.example#InternalEnum") - .addMember("withoutTag", "foo", builder -> { - builder.addTrait(new InternalTrait()); - }) - .addMember("withTag", "bar", builder -> { - builder.addTrait(new InternalTrait()); - builder.addTrait(TagsTrait.builder().addValue("internal").build()); - }) - .build(); + .id("com.example#InternalEnum") + .addMember("withoutTag", "foo", builder -> { + builder.addTrait(new InternalTrait()); + }) + .addMember("withTag", "bar", builder -> { + builder.addTrait(new InternalTrait()); + builder.addTrait(TagsTrait.builder().addValue("internal").build()); + }) + .build(); SyntheticEnumTrait trait = shape.expectTrait(SyntheticEnumTrait.class); for (EnumDefinition definition : trait.getValues()) { diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/IntEnumShapeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/IntEnumShapeTest.java index d9aefa400f4..11f808375e3 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/IntEnumShapeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/IntEnumShapeTest.java @@ -41,12 +41,12 @@ public void addMember() { IntEnumShape.Builder builder = (IntEnumShape.Builder) IntEnumShape.builder().id("ns.foo#bar"); IntEnumShape shape = builder.addMember("foo", 1).build(); assertEquals( - shape.getMember("foo").get(), - MemberShape.builder() - .id(shape.getId().withMember("foo")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().intValue(1).build()) - .build() + shape.getMember("foo").get(), + MemberShape.builder() + .id(shape.getId().withMember("foo")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().intValue(1).build()) + .build() ); } @@ -54,10 +54,10 @@ public void addMember() { public void addMemberShape() { IntEnumShape.Builder builder = (IntEnumShape.Builder) IntEnumShape.builder().id("ns.foo#bar"); MemberShape member = MemberShape.builder() - .id("ns.foo#bar$foo") - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().intValue(1).build()) - .build(); + .id("ns.foo#bar$foo") + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().intValue(1).build()) + .build(); IntEnumShape shape = builder.addMember(member).build(); assertEquals(shape.getMember("foo").get(), member); } @@ -66,24 +66,24 @@ public void addMemberShape() { public void addMultipleMembers() { IntEnumShape.Builder builder = (IntEnumShape.Builder) IntEnumShape.builder().id("ns.foo#bar"); IntEnumShape shape = builder - .addMember("foo", 1) - .addMember("bar", 2) - .build(); + .addMember("foo", 1) + .addMember("bar", 2) + .build(); assertEquals( - shape.getMember("foo").get(), - MemberShape.builder() - .id(shape.getId().withMember("foo")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().intValue(1).build()) - .build() + shape.getMember("foo").get(), + MemberShape.builder() + .id(shape.getId().withMember("foo")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().intValue(1).build()) + .build() ); assertEquals( - shape.getMember("bar").get(), - MemberShape.builder() - .id(shape.getId().withMember("bar")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().intValue(2).build()) - .build() + shape.getMember("bar").get(), + MemberShape.builder() + .id(shape.getId().withMember("bar")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().intValue(2).build()) + .build() ); } @@ -91,18 +91,18 @@ public void addMultipleMembers() { public void removeMember() { IntEnumShape.Builder builder = (IntEnumShape.Builder) IntEnumShape.builder().id("ns.foo#bar"); IntEnumShape shape = builder - .addMember("foo", 1) - .removeMember("foo") - .addMember("bar", 2) - .build(); + .addMember("foo", 1) + .removeMember("foo") + .addMember("bar", 2) + .build(); assertFalse(shape.getMember("foo").isPresent()); assertEquals( - shape.getMember("bar").get(), - MemberShape.builder() - .id(shape.getId().withMember("bar")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().intValue(2).build()) - .build() + shape.getMember("bar").get(), + MemberShape.builder() + .id(shape.getId().withMember("bar")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().intValue(2).build()) + .build() ); } @@ -110,18 +110,18 @@ public void removeMember() { public void clearMembers() { IntEnumShape.Builder builder = (IntEnumShape.Builder) IntEnumShape.builder().id("ns.foo#bar"); IntEnumShape shape = builder - .addMember("foo", 1) - .clearMembers() - .addMember("bar", 2) - .build(); + .addMember("foo", 1) + .clearMembers() + .addMember("bar", 2) + .build(); assertFalse(shape.getMember("foo").isPresent()); assertEquals( - shape.getMember("bar").get(), - MemberShape.builder() - .id(shape.getId().withMember("bar")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().intValue(2).build()) - .build() + shape.getMember("bar").get(), + MemberShape.builder() + .id(shape.getId().withMember("bar")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().intValue(2).build()) + .build() ); } @@ -136,10 +136,10 @@ public void idMustBeSetFirst() { public void membersMustTargetUnit() { IntEnumShape.Builder builder = (IntEnumShape.Builder) IntEnumShape.builder().id("ns.foo#bar"); MemberShape member = MemberShape.builder() - .id("ns.foo#bar$foo") - .target("smithy.api#Integer") - .addTrait(EnumValueTrait.builder().intValue(1).build()) - .build(); + .id("ns.foo#bar$foo") + .target("smithy.api#Integer") + .addTrait(EnumValueTrait.builder().intValue(1).build()) + .build(); Assertions.assertThrows(SourceException.class, () -> { builder.addMember(member); }); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ListShapeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ListShapeTest.java index 22b9fc4ca56..76748e0cde3 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ListShapeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ListShapeTest.java @@ -19,9 +19,9 @@ public class ListShapeTest { @Test public void returnsAppropriateType() { ListShape shape = ListShape.builder() - .id("ns.foo#bar") - .member(MemberShape.builder().id("ns.foo#bar$member").target("ns.foo#bam").build()) - .build(); + .id("ns.foo#bar") + .member(MemberShape.builder().id("ns.foo#bar$member").target("ns.foo#bam").build()) + .build(); assertEquals(shape.getType(), ShapeType.LIST); } @@ -30,9 +30,9 @@ public void returnsAppropriateType() { public void mustNotContainMembersInShapeId() { Assertions.assertThrows(SourceException.class, () -> { ListShape.builder() - .id("ns.foo#bar$baz") - .member(MemberShape.builder().id("ns.foo#bar$member").target("ns.foo#bam").build()) - .build(); + .id("ns.foo#bar$baz") + .member(MemberShape.builder().id("ns.foo#bar$member").target("ns.foo#bam").build()) + .build(); }); } @@ -47,9 +47,9 @@ public void requiresMember() { public void hasMember() { MemberShape member = MemberShape.builder().id("ns.foo#bar$member").target("ns.foo#bam").build(); ListShape shape = ListShape.builder() - .id("ns.foo#bar") - .member(member) - .build(); + .id("ns.foo#bar") + .member(member) + .build(); assertEquals(member, shape.getMember()); } @@ -104,30 +104,30 @@ public void differentMemberAreNotEqual() { @Test public void addMemberWithTarget() { ListShape shape = ListShape.builder() - .id("ns.foo#bar") - .member(ShapeId.from("ns.foo#bam")) - .build(); + .id("ns.foo#bar") + .member(ShapeId.from("ns.foo#bam")) + .build(); assertEquals( - shape.getMember(), - MemberShape.builder().id(shape.getId().withMember("member")).target("ns.foo#bam").build() + shape.getMember(), + MemberShape.builder().id(shape.getId().withMember("member")).target("ns.foo#bam").build() ); } @Test public void addMemberWithConsumer() { ListShape shape = ListShape.builder() - .id("ns.foo#bar") - .member(ShapeId.from("ns.foo#bam"), builder -> builder.addTrait(new SensitiveTrait())) - .build(); + .id("ns.foo#bar") + .member(ShapeId.from("ns.foo#bam"), builder -> builder.addTrait(new SensitiveTrait())) + .build(); assertEquals( - shape.getMember(), - MemberShape.builder() - .id(shape.getId().withMember("member")) - .target("ns.foo#bam") - .addTrait(new SensitiveTrait()) - .build() + shape.getMember(), + MemberShape.builder() + .id(shape.getId().withMember("member")) + .target("ns.foo#bam") + .addTrait(new SensitiveTrait()) + .build() ); } @@ -141,10 +141,10 @@ public void returnsMembers() { @Test public void builderUpdatesMemberId() { ListShape shape = ListShape.builder() - .id("ns.foo#bar") - .member(ShapeId.from("ns.foo#bam")) - .id("ns.bar#bar") - .build(); + .id("ns.foo#bar") + .member(ShapeId.from("ns.foo#bam")) + .id("ns.bar#bar") + .build(); assertThat(shape.getMember().getId(), equalTo(ShapeId.from("ns.bar#bar$member"))); assertThat(shape.getMember().getTarget(), equalTo(ShapeId.from("ns.foo#bam"))); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/MapShapeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/MapShapeTest.java index 8e0f0e598d9..2f4a509bee7 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/MapShapeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/MapShapeTest.java @@ -18,10 +18,10 @@ public class MapShapeTest { @Test public void returnsAppropriateType() { MapShape shape = MapShape.builder() - .id("ns.foo#bar") - .key(MemberShape.builder().id("ns.foo#bar$key").target("ns.foo#bam").build()) - .value(MemberShape.builder().id("ns.foo#bar$value").target("ns.foo#bam").build()) - .build(); + .id("ns.foo#bar") + .key(MemberShape.builder().id("ns.foo#bar$key").target("ns.foo#bam").build()) + .value(MemberShape.builder().id("ns.foo#bar$value").target("ns.foo#bam").build()) + .build(); assertEquals(shape.getType(), ShapeType.MAP); } @@ -30,64 +30,64 @@ public void returnsAppropriateType() { public void mustNotContainMembersInShapeId() { Assertions.assertThrows(SourceException.class, () -> { MapShape.builder() - .id("ns.foo#bar$baz") - .key(MemberShape.builder().id("ns.foo#bar$key").target("ns.foo#bam").build()) - .value(MemberShape.builder().id("ns.foo#bar$value").target("ns.foo#bam").build()) - .build(); + .id("ns.foo#bar$baz") + .key(MemberShape.builder().id("ns.foo#bar$key").target("ns.foo#bam").build()) + .value(MemberShape.builder().id("ns.foo#bar$value").target("ns.foo#bam").build()) + .build(); }); } @Test public void addMemberWithTarget() { MapShape shape = MapShape.builder() - .id("ns.foo#bar") - .key(ShapeId.from("ns.foo#bam")) - .value(ShapeId.from("ns.foo#bam")) - .build(); + .id("ns.foo#bar") + .key(ShapeId.from("ns.foo#bam")) + .value(ShapeId.from("ns.foo#bam")) + .build(); assertEquals( - shape.getKey(), - MemberShape.builder().id(shape.getId().withMember("key")).target("ns.foo#bam").build() + shape.getKey(), + MemberShape.builder().id(shape.getId().withMember("key")).target("ns.foo#bam").build() ); assertEquals( - shape.getValue(), - MemberShape.builder().id(shape.getId().withMember("value")).target("ns.foo#bam").build() + shape.getValue(), + MemberShape.builder().id(shape.getId().withMember("value")).target("ns.foo#bam").build() ); } @Test public void addMemberWithConsumer() { MapShape shape = MapShape.builder() - .id("ns.foo#bar") - .key(ShapeId.from("ns.foo#bam"), builder -> builder.addTrait(new SensitiveTrait())) - .value(ShapeId.from("ns.foo#bam"), builder -> builder.addTrait(new SensitiveTrait())) - .build(); + .id("ns.foo#bar") + .key(ShapeId.from("ns.foo#bam"), builder -> builder.addTrait(new SensitiveTrait())) + .value(ShapeId.from("ns.foo#bam"), builder -> builder.addTrait(new SensitiveTrait())) + .build(); assertEquals( - shape.getKey(), - MemberShape.builder() - .id(shape.getId().withMember("key")) - .target("ns.foo#bam") - .addTrait(new SensitiveTrait()) - .build() + shape.getKey(), + MemberShape.builder() + .id(shape.getId().withMember("key")) + .target("ns.foo#bam") + .addTrait(new SensitiveTrait()) + .build() ); assertEquals( - shape.getValue(), - MemberShape.builder() - .id(shape.getId().withMember("value")) - .target("ns.foo#bam") - .addTrait(new SensitiveTrait()) - .build() + shape.getValue(), + MemberShape.builder() + .id(shape.getId().withMember("value")) + .target("ns.foo#bam") + .addTrait(new SensitiveTrait()) + .build() ); } @Test public void returnsMembers() { MapShape shape = MapShape.builder() - .id("ns.foo#bar") - .key(ShapeId.from("ns.foo#bam")) - .value(ShapeId.from("ns.foo#bam")) - .build(); + .id("ns.foo#bar") + .key(ShapeId.from("ns.foo#bam")) + .value(ShapeId.from("ns.foo#bam")) + .build(); assertThat(shape.members(), hasSize(2)); } @@ -95,11 +95,11 @@ public void returnsMembers() { @Test public void builderUpdatesMembers() { MapShape shape = MapShape.builder() - .id("ns.foo#bar") - .key(ShapeId.from("ns.foo#bam")) - .value(ShapeId.from("ns.foo#bam")) - .id("ns.bar#bar") - .build(); + .id("ns.foo#bar") + .key(ShapeId.from("ns.foo#bam")) + .value(ShapeId.from("ns.foo#bam")) + .id("ns.bar#bar") + .build(); assertThat(shape.getKey().getId(), equalTo(ShapeId.from("ns.bar#bar$key"))); assertThat(shape.getKey().getTarget(), equalTo(ShapeId.from("ns.foo#bam"))); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/MemberShapeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/MemberShapeTest.java index 311f0e9e011..f867c989fbb 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/MemberShapeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/MemberShapeTest.java @@ -34,18 +34,18 @@ public void mustContainMembersInShapeId() { @Test public void returnsType() { MemberShape shape = MemberShape.builder() - .id(ShapeId.from("ns.foo#bar$baz")) - .target("ns.foo#baz") - .build(); + .id(ShapeId.from("ns.foo#bar$baz")) + .target("ns.foo#baz") + .build(); assertEquals(ShapeType.MEMBER, shape.getType()); } @Test public void checksForEquality() { MemberShape a = MemberShape.builder() - .id(ShapeId.from("ns.foo#bar$baz")) - .target("ns.foo#baz") - .build(); + .id(ShapeId.from("ns.foo#bar$baz")) + .target("ns.foo#baz") + .build(); // Same exact shape. assertEquals(a, a); // Same semantic shape. @@ -59,9 +59,9 @@ public void checksForEquality() { @Test public void equality() { MemberShape a = MemberShape.builder() - .id(ShapeId.from("ns.foo#bar$baz")) - .target("ns.foo#baz") - .build(); + .id(ShapeId.from("ns.foo#bar$baz")) + .target("ns.foo#baz") + .build(); assertEquals(a.hashCode(), a.toBuilder().build().hashCode()); } @@ -75,32 +75,32 @@ public void requiresShapeTargetId() { @Test public void getsMemberTraits() { Shape target = StringShape.builder() - .id("foo.baz#Bar") - .addTrait(new DocumentationTrait("hi")) - .addTrait(ExternalDocumentationTrait.builder().addUrl("Ref", "http://example.com").build()) - .build(); + .id("foo.baz#Bar") + .addTrait(new DocumentationTrait("hi")) + .addTrait(ExternalDocumentationTrait.builder().addUrl("Ref", "http://example.com").build()) + .build(); MemberShape member = MemberShape.builder() - .id("foo.baz#Bar$member") - .target(target) - .addTrait(new DocumentationTrait("override")) - .build(); + .id("foo.baz#Bar$member") + .target(target) + .addTrait(new DocumentationTrait("override")) + .build(); Model model = Model.builder().addShapes(member, target).build(); assertThat( - member.getMemberTrait(model, DocumentationTrait.class).get().getValue(), - equalTo("override") + member.getMemberTrait(model, DocumentationTrait.class).get().getValue(), + equalTo("override") ); assertThat( - member.getMemberTrait(model, ExternalDocumentationTrait.class).get().getUrls().get("Ref"), - equalTo("http://example.com") + member.getMemberTrait(model, ExternalDocumentationTrait.class).get().getUrls().get("Ref"), + equalTo("http://example.com") ); assertThat( - member.findMemberTrait(model, "documentation"), - equalTo(member.findTrait("documentation")) + member.findMemberTrait(model, "documentation"), + equalTo(member.findTrait("documentation")) ); assertThat( - member.findMemberTrait(model, "externalDocumentation"), - equalTo(target.findTrait("externalDocumentation")) + member.findMemberTrait(model, "externalDocumentation"), + equalTo(target.findTrait("externalDocumentation")) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ModelSerializerTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ModelSerializerTest.java index a2fe7ef6d0e..89221db032d 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ModelSerializerTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ModelSerializerTest.java @@ -40,12 +40,12 @@ public class ModelSerializerTest { @TestFactory public Stream generateV2RoundTripTests() throws IOException, URISyntaxException { return Files.list( - Paths.get( - SmithyIdlModelSerializer.class.getResource("ast-serialization/cases/v2").toURI() - ) + Paths.get( + SmithyIdlModelSerializer.class.getResource("ast-serialization/cases/v2").toURI() + ) ) - .filter(path -> !path.toString().endsWith(".1.0.json")) - .map(path -> DynamicTest.dynamicTest(path.getFileName().toString(), () -> testRoundTripV2(path))); + .filter(path -> !path.toString().endsWith(".1.0.json")) + .map(path -> DynamicTest.dynamicTest(path.getFileName().toString(), () -> testRoundTripV2(path))); } private void testRoundTripV2(Path path) { @@ -56,12 +56,12 @@ private void testRoundTripV2(Path path) { @TestFactory public Stream generateV1RoundTripTests() throws IOException, URISyntaxException { return Files.list( - Paths.get( - SmithyIdlModelSerializer.class.getResource("ast-serialization/cases/v1").toURI() - ) + Paths.get( + SmithyIdlModelSerializer.class.getResource("ast-serialization/cases/v1").toURI() + ) ) - .filter(path -> !path.toString().endsWith(".2.0.json")) - .map(path -> DynamicTest.dynamicTest(path.getFileName().toString(), () -> testRoundTripV1(path))); + .filter(path -> !path.toString().endsWith(".2.0.json")) + .map(path -> DynamicTest.dynamicTest(path.getFileName().toString(), () -> testRoundTripV1(path))); } private void testRoundTripV1(Path path) { @@ -90,17 +90,17 @@ private void testV1DowngradeSerialization(Path path, Path expectedV1Path) { @Test public void serializesModels() { Model model = Model.assembler() - .addImport(getClass().getResource("test-model.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("test-model.json")) + .assemble() + .unwrap(); ModelSerializer serializer = ModelSerializer.builder().build(); ObjectNode serialized = serializer.serialize(model); String serializedString = Node.prettyPrintJson(serialized); Model other = Model.assembler() - .addUnparsedModel("N/A", serializedString) - .assemble() - .unwrap(); + .addUnparsedModel("N/A", serializedString) + .assemble() + .unwrap(); String serializedString2 = Node.prettyPrintJson(serializer.serialize(other)); assertThat(serialized.expectMember("smithy").expectStringNode(), equalTo(Node.from(Model.MODEL_VERSION))); @@ -111,18 +111,18 @@ public void serializesModels() { @Test public void filtersMetadata() { ModelSerializer serializer = ModelSerializer.builder() - .metadataFilter(k -> k.equals("foo")) - .build(); + .metadataFilter(k -> k.equals("foo")) + .build(); Model model = Model.builder() - .putMetadataProperty("foo", Node.from("baz")) - .putMetadataProperty("bar", Node.from("qux")) - .build(); + .putMetadataProperty("foo", Node.from("baz")) + .putMetadataProperty("bar", Node.from("qux")) + .build(); ObjectNode result = serializer.serialize(model); assertThat(result.getMember("metadata"), not(Optional.empty())); assertThat( - result.getMember("metadata").get().expectObjectNode().getMember("foo"), - equalTo(Optional.of(Node.from("baz"))) + result.getMember("metadata").get().expectObjectNode().getMember("foo"), + equalTo(Optional.of(Node.from("baz"))) ); assertThat(result.getMember("metadata").get().expectObjectNode().getMember("bar"), is(Optional.empty())); } @@ -130,12 +130,12 @@ public void filtersMetadata() { @Test public void filtersShapes() { ModelSerializer serializer = ModelSerializer.builder() - .shapeFilter(shape -> shape.getId().getName().equals("foo")) - .build(); + .shapeFilter(shape -> shape.getId().getName().equals("foo")) + .build(); Model model = Model.builder() - .addShape(StringShape.builder().id("ns.foo#foo").build()) - .addShape(StringShape.builder().id("ns.foo#baz").build()) - .build(); + .addShape(StringShape.builder().id("ns.foo#foo").build()) + .addShape(StringShape.builder().id("ns.foo#baz").build()) + .build(); ObjectNode result = serializer.serialize(model); ObjectNode shapes = result.expectObjectMember("shapes"); @@ -147,18 +147,18 @@ public void filtersShapes() { @Test public void canFilterTraits() { Shape shape = StringShape.builder() - .id("ns.foo#baz") - .addTrait(new SensitiveTrait()) - .addTrait(new DocumentationTrait("docs", SourceLocation.NONE)) - .build(); + .id("ns.foo#baz") + .addTrait(new SensitiveTrait()) + .addTrait(new DocumentationTrait("docs", SourceLocation.NONE)) + .build(); Model model = Model.assembler().addShape(shape).assemble().unwrap(); ModelSerializer serializer = ModelSerializer.builder() - .traitFilter(trait -> trait.toShapeId().toString().equals("smithy.api#documentation")) - .build(); + .traitFilter(trait -> trait.toShapeId().toString().equals("smithy.api#documentation")) + .build(); ObjectNode obj = serializer.serialize(model) - .expectObjectMember("shapes") - .expectObjectMember("ns.foo#baz"); + .expectObjectMember("shapes") + .expectObjectMember("ns.foo#baz"); obj.expectStringMember("type"); ObjectNode traits = obj.expectObjectMember("traits"); assertThat(traits.expectStringMember("smithy.api#documentation"), equalTo(Node.from("docs"))); @@ -168,18 +168,18 @@ public void canFilterTraits() { @Test public void serializesAliasedPreludeTraitsUsingFullyQualifiedFormWhenNecessary() { Model model = Model.assembler() - .addImport(getClass().getResource("prelude-trait-alias.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("prelude-trait-alias.smithy")) + .assemble() + .unwrap(); ModelSerializer serializer = ModelSerializer.builder().build(); ObjectNode serialized = serializer.serialize(model); String result = Node.prettyPrintJson(serialized); // Make sure that we can serialize and deserialize the original model. Model roundTrip = Model.assembler() - .addUnparsedModel("foo.json", result) - .assemble() - .unwrap(); + .addUnparsedModel("foo.json", result) + .assemble() + .unwrap(); assertThat(model, equalTo(roundTrip)); assertThat(result, containsString("\"ns.foo#sensitive\"")); @@ -190,9 +190,9 @@ public void serializesAliasedPreludeTraitsUsingFullyQualifiedFormWhenNecessary() @Test public void doesNotSerializePreludeTraitsOrShapes() { Model model = Model.assembler() - .addImport(getClass().getResource("test-model.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("test-model.json")) + .assemble() + .unwrap(); ModelSerializer serializer = ModelSerializer.builder().build(); ObjectNode serialized = serializer.serialize(model); @@ -218,18 +218,18 @@ public void allowsDisablingPreludeFilter() { @Test public void doesNotSerializeEmptyServiceVersions() { ServiceShape service = ServiceShape.builder() - .id("com.foo#Example") - .build(); + .id("com.foo#Example") + .build(); Model model = Model.builder().addShape(service).build(); ModelSerializer serializer = ModelSerializer.builder().build(); ObjectNode result = serializer.serialize(model); assertThat( - NodePointer.parse("/shapes/com.foo#Example") - .getValue(result) - .expectObjectNode() - .getStringMap(), - not(hasKey("version")) + NodePointer.parse("/shapes/com.foo#Example") + .getValue(result) + .expectObjectNode() + .getStringMap(), + not(hasKey("version")) ); } @@ -237,12 +237,12 @@ public void doesNotSerializeEmptyServiceVersions() { public void transientTraitsAreNotSerialized() { ShapeId originalId = ShapeId.from("com.foo.nested#Str"); StringShape stringShape = StringShape.builder() - .id("com.foo#Str") - .addTrait(new OriginalShapeIdTrait(originalId)) - .build(); + .id("com.foo#Str") + .addTrait(new OriginalShapeIdTrait(originalId)) + .build(); Model model = Model.builder() - .addShape(stringShape) - .build(); + .addShape(stringShape) + .build(); ModelSerializer serializer = ModelSerializer.builder().build(); ObjectNode result = serializer.serialize(model); @@ -253,24 +253,24 @@ public void transientTraitsAreNotSerialized() { @Test public void serializesSetsAsListsWithUniqueItems() { SetShape set = SetShape.builder() - .id("smithy.example#Set") - .member(ShapeId.from("smithy.example#String")) - .build(); + .id("smithy.example#Set") + .member(ShapeId.from("smithy.example#String")) + .build(); Model model = Model.builder().addShape(set).build(); Node node = ModelSerializer.builder().build().serialize(model); assertThat( - NodePointer.parse("/shapes/smithy.example#Set/type") - .getValue(node) - .expectStringNode() - .getValue(), - equalTo("list") + NodePointer.parse("/shapes/smithy.example#Set/type") + .getValue(node) + .expectStringNode() + .getValue(), + equalTo("list") ); assertThat( - NodePointer.parse("/shapes/smithy.example#Set/traits/smithy.api#uniqueItems") - .getValue(node) - .isNullNode(), - equalTo(false) + NodePointer.parse("/shapes/smithy.example#Set/traits/smithy.api#uniqueItems") + .getValue(node) + .isNullNode(), + equalTo(false) ); } @@ -279,14 +279,14 @@ public void serializesResourceProperties() { Map properties = new TreeMap<>(); properties.put("fooProperty", ShapeId.from("ns.foo#Shape")); ResourceShape shape = ResourceShape.builder() - .id("ns.foo#Bar") - .properties(properties) - .build(); + .id("ns.foo#Bar") + .properties(properties) + .build(); Model model = Model.builder().addShape(shape).build(); Node node = ModelSerializer.builder().build().serialize(model); Node expectedNode = Node.parse( - "{\"smithy\":\"2.0\",\"shapes\":{\"ns.foo#Bar\":" + - "{\"type\":\"resource\",\"properties\":{\"fooProperty\":{\"target\":\"ns.foo#Shape\"}}}}}" + "{\"smithy\":\"2.0\",\"shapes\":{\"ns.foo#Bar\":" + + "{\"type\":\"resource\",\"properties\":{\"fooProperty\":{\"target\":\"ns.foo#Shape\"}}}}}" ); Node.assertEquals(node, expectedNode); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/OperationShapeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/OperationShapeTest.java index 8f896b636f5..041e0151d34 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/OperationShapeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/OperationShapeTest.java @@ -14,26 +14,26 @@ public class OperationShapeTest { @Test public void combinesErrorsWithServiceErrors() { ServiceShape service = ServiceShape.builder() - .id("com.foo#Example") - .version("x") - .addError("com.foo#Common1") - .addError(ShapeId.from("com.foo#Common2")) - .build(); + .id("com.foo#Example") + .version("x") + .addError("com.foo#Common1") + .addError(ShapeId.from("com.foo#Common2")) + .build(); OperationShape operation = OperationShape.builder() - .id("com.foo#Operation") - .addError("com.foo#OperationError") - .build(); + .id("com.foo#Operation") + .addError("com.foo#OperationError") + .build(); List allErrors = operation.getErrors(service); assertThat( - allErrors, - contains( - ShapeId.from("com.foo#Common1"), - ShapeId.from("com.foo#Common2"), - ShapeId.from("com.foo#OperationError") - ) + allErrors, + contains( + ShapeId.from("com.foo#Common1"), + ShapeId.from("com.foo#Common2"), + ShapeId.from("com.foo#OperationError") + ) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ResourceShapeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ResourceShapeTest.java index d2d3b625cba..94d5c90a28b 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ResourceShapeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ResourceShapeTest.java @@ -32,9 +32,9 @@ public void maintainsIdentifiers() { Map identifiers = new TreeMap<>(); identifiers.put("arn", ShapeId.from("ns.foo#ARN")); ResourceShape shape = ResourceShape.builder() - .id("ns.foo#Bar") - .identifiers(identifiers) - .build(); + .id("ns.foo#Bar") + .identifiers(identifiers) + .build(); assertEquals(shape.getIdentifiers(), identifiers); } @@ -44,8 +44,8 @@ public void maintainsProperties() { properties.put("fooProperty", ShapeId.from("ns.foo#Shape")); ResourceShape.Builder builder = ResourceShape.builder(); ResourceShape shape = builder.id("ns.foo#Bar") - .properties(properties) - .build(); + .properties(properties) + .build(); assertEquals(shape.getProperties(), properties); // Verify that toBuilder() works as well. assertEquals(properties, shape.toBuilder().build().getProperties()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ServiceShapeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ServiceShapeTest.java index 8a0a2bbe306..543b308b792 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ServiceShapeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ServiceShapeTest.java @@ -31,9 +31,9 @@ public void mustNotContainMembersInShapeId() { @Test public void convertsToBuilder() { ServiceShape service = ServiceShape.builder() - .id("ns.foo#Bar") - .version("2017-01-17") - .build(); + .id("ns.foo#Bar") + .version("2017-01-17") + .build(); assertEquals(service, service.toBuilder().build()); } @@ -41,10 +41,10 @@ public void convertsToBuilder() { public void providesContextualShapeName() { ShapeId id = ShapeId.from("foo.bar#Name"); ServiceShape serviceShape = ServiceShape.builder() - .id("smithy.example#Service") - .version("1") - .putRename(id, "FooName") - .build(); + .id("smithy.example#Service") + .version("1") + .putRename(id, "FooName") + .build(); assertThat(serviceShape.getContextualName(id), equalTo("FooName")); } @@ -52,8 +52,8 @@ public void providesContextualShapeName() { @Test public void versionDefaultsToEmptyString() { ServiceShape shape = ServiceShape.builder() - .id("com.foo#Example") - .build(); + .id("com.foo#Example") + .build(); assertThat(shape.getVersion(), equalTo("")); } @@ -61,18 +61,18 @@ public void versionDefaultsToEmptyString() { @Test public void hasErrors() { ServiceShape shape = ServiceShape.builder() - .id("com.foo#Example") - .version("x") - .addError("com.foo#Common1") - .addError(ShapeId.from("com.foo#Common2")) - .build(); + .id("com.foo#Example") + .version("x") + .addError("com.foo#Common1") + .addError(ShapeId.from("com.foo#Common2")) + .build(); assertThat(shape, equalTo(shape)); assertThat(shape, equalTo(shape.toBuilder().build())); ServiceShape shape2 = shape.toBuilder() - .errors(Arrays.asList(ShapeId.from("com.foo#Common1"), ShapeId.from("com.foo#Common2"))) - .build(); + .errors(Arrays.asList(ShapeId.from("com.foo#Common1"), ShapeId.from("com.foo#Common2"))) + .build(); assertThat(shape, equalTo(shape2)); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/SetShapeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/SetShapeTest.java index ba96b6b96e6..ff575344438 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/SetShapeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/SetShapeTest.java @@ -14,10 +14,10 @@ public class SetShapeTest { @Test public void builderUpdatesMemberId() { SetShape shape = SetShape.builder() - .id("ns.foo#bar") - .member(ShapeId.from("ns.foo#bam")) - .id("ns.bar#bar") - .build(); + .id("ns.foo#bar") + .member(ShapeId.from("ns.foo#bam")) + .id("ns.bar#bar") + .build(); assertThat(shape.getMember().getId(), equalTo(ShapeId.from("ns.bar#bar$member"))); assertThat(shape.getMember().getTarget(), equalTo(ShapeId.from("ns.foo#bam"))); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeIdTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeIdTest.java index 874af5b2725..d6d7d846001 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeIdTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeIdTest.java @@ -193,84 +193,84 @@ public void ShapeIdValidationsTest(String shapeId, boolean isInvalid) { public static Collection shapeIdData() { return Arrays.asList( - new Object[][]{ - - // valid namespaces - {"n.s#name", false}, - {"name.space#name", false}, - {"name1.space2#name", false}, - {"na.me.spa.ce#name", false}, - {"na.me.spa.ce_#name", false}, - {"na.me.spa.ce__#name", false}, - {"na.me.spa.ce__2#name", false}, - {"na.me.spa.ce__2_#name", false}, - {"namespace#name", false}, - {"mixed.Case#name", false}, - {"NAMESPACE#name", false}, - {"nameSpace#name", false}, - {"Mixed.case#name", false}, - {"_foo.baz#name", false}, - {"__foo.baz#name", false}, - - // invalid namespaces - {"#name", true}, - {"name.space.#name", true}, - {"name..space#name", true}, - {".name.space#name", true}, - {"name-space#name", true}, - {"1namespace.foo#name", true}, - {"a._.b#name", true}, - {"a.____.b#name", true}, - - // valid shape names - {"ns.foo#shapename", false}, - {"ns.foo#shapeName", false}, - {"ns.foo#ShapeName", false}, - {"ns.foo#SHAPENAME", false}, - {"ns.foo#name1", false}, - {"ns.foo#Shape_Name", false}, - {"ns.foo#shape_name_num1", false}, - {"ns.foo#shape_1name", false}, - {"ns.foo#_Shape_Name", false}, - {"ns.foo#__shape_name_num1", false}, - - // invalid shape names - {"ns.foo#", true}, - {"ns.foo#1name", true}, - {"ns.foo#1", true}, - {"ns.foo#shape.name", true}, - - // valid segments - {"ns.foo#name$abc", false}, - {"ns.foo#name$Abc", false}, - {"ns.foo#name$ABC", false}, - {"ns.foo#name$abcMno", false}, - {"ns.foo#name$AbcMno", false}, - {"ns.foo#name$AbcMno1", false}, - {"ns.foo#name$abc_mno", false}, - {"ns.foo#name$Abc_Mno", false}, - {"ns.foo#name$abc_", false}, - {"ns.foo#name$abc__mno", false}, - {"ns.foo#name$_abc", false}, - {"ns.foo#name$_abc_", false}, - - // invalid segments - {"ns.foo#name$", true}, - {"ns.foo#name$abc-mno", true}, - {"ns.foo#name$1abc", true}, - {"ns.foo#name$abc.mno", true}, - {"ns.foo#name$abc.", true}, - } + new Object[][]{ + + // valid namespaces + {"n.s#name", false}, + {"name.space#name", false}, + {"name1.space2#name", false}, + {"na.me.spa.ce#name", false}, + {"na.me.spa.ce_#name", false}, + {"na.me.spa.ce__#name", false}, + {"na.me.spa.ce__2#name", false}, + {"na.me.spa.ce__2_#name", false}, + {"namespace#name", false}, + {"mixed.Case#name", false}, + {"NAMESPACE#name", false}, + {"nameSpace#name", false}, + {"Mixed.case#name", false}, + {"_foo.baz#name", false}, + {"__foo.baz#name", false}, + + // invalid namespaces + {"#name", true}, + {"name.space.#name", true}, + {"name..space#name", true}, + {".name.space#name", true}, + {"name-space#name", true}, + {"1namespace.foo#name", true}, + {"a._.b#name", true}, + {"a.____.b#name", true}, + + // valid shape names + {"ns.foo#shapename", false}, + {"ns.foo#shapeName", false}, + {"ns.foo#ShapeName", false}, + {"ns.foo#SHAPENAME", false}, + {"ns.foo#name1", false}, + {"ns.foo#Shape_Name", false}, + {"ns.foo#shape_name_num1", false}, + {"ns.foo#shape_1name", false}, + {"ns.foo#_Shape_Name", false}, + {"ns.foo#__shape_name_num1", false}, + + // invalid shape names + {"ns.foo#", true}, + {"ns.foo#1name", true}, + {"ns.foo#1", true}, + {"ns.foo#shape.name", true}, + + // valid segments + {"ns.foo#name$abc", false}, + {"ns.foo#name$Abc", false}, + {"ns.foo#name$ABC", false}, + {"ns.foo#name$abcMno", false}, + {"ns.foo#name$AbcMno", false}, + {"ns.foo#name$AbcMno1", false}, + {"ns.foo#name$abc_mno", false}, + {"ns.foo#name$Abc_Mno", false}, + {"ns.foo#name$abc_", false}, + {"ns.foo#name$abc__mno", false}, + {"ns.foo#name$_abc", false}, + {"ns.foo#name$_abc_", false}, + + // invalid segments + {"ns.foo#name$", true}, + {"ns.foo#name$abc-mno", true}, + {"ns.foo#name$1abc", true}, + {"ns.foo#name$abc.mno", true}, + {"ns.foo#name$abc.", true}, + } ); } @ParameterizedTest @MethodSource("toStringData") public void toStringTest( - final String namespace, - final String name, - final String member, - final String expectedResult + final String namespace, + final String name, + final String member, + final String expectedResult ) { ShapeId shapeId = ShapeId.fromParts(namespace, name, member); @@ -279,36 +279,36 @@ public void toStringTest( public static Collection toStringData() { return Arrays.asList( - new Object[][]{ - {"name.space", "Name", null, "name.space#Name"}, - {"name.space", "Name", "member", "name.space#Name$member"}, - } + new Object[][]{ + {"name.space", "Name", null, "name.space#Name"}, + {"name.space", "Name", "member", "name.space#Name$member"}, + } ); } @Test public void compareToTest() { List given = Arrays.asList( - ShapeId.fromParts("ns.foo", "foo"), - ShapeId.fromParts("ns.foo", "Foo"), - ShapeId.fromParts("ns.foo", "bar"), - ShapeId.fromParts("ns.foo", "bar", "member"), - ShapeId.fromParts("ns.foo", "bar", "Member"), - ShapeId.fromParts("ns.foo", "bar", "AMember"), - ShapeId.fromParts("ns.Foo", "foo"), - ShapeId.fromParts("ns.baz", "foo") + ShapeId.fromParts("ns.foo", "foo"), + ShapeId.fromParts("ns.foo", "Foo"), + ShapeId.fromParts("ns.foo", "bar"), + ShapeId.fromParts("ns.foo", "bar", "member"), + ShapeId.fromParts("ns.foo", "bar", "Member"), + ShapeId.fromParts("ns.foo", "bar", "AMember"), + ShapeId.fromParts("ns.Foo", "foo"), + ShapeId.fromParts("ns.baz", "foo") ); given.sort(ShapeId::compareTo); List expected = Arrays.asList( - ShapeId.fromParts("ns.baz", "foo"), - ShapeId.fromParts("ns.foo", "bar"), - ShapeId.fromParts("ns.foo", "bar", "AMember"), - ShapeId.fromParts("ns.foo", "bar", "Member"), - ShapeId.fromParts("ns.foo", "bar", "member"), - ShapeId.fromParts("ns.Foo", "foo"), - ShapeId.fromParts("ns.foo", "Foo"), - ShapeId.fromParts("ns.foo", "foo") + ShapeId.fromParts("ns.baz", "foo"), + ShapeId.fromParts("ns.foo", "bar"), + ShapeId.fromParts("ns.foo", "bar", "AMember"), + ShapeId.fromParts("ns.foo", "bar", "Member"), + ShapeId.fromParts("ns.foo", "bar", "member"), + ShapeId.fromParts("ns.Foo", "foo"), + ShapeId.fromParts("ns.foo", "Foo"), + ShapeId.fromParts("ns.foo", "foo") ); assertEquals(expected, given); @@ -324,15 +324,15 @@ public static Collection equalsData() { ShapeId obj = ShapeId.fromParts("ns.foo", "name"); return Arrays.asList( - new Object[][]{ - {obj, obj, true}, - {ShapeId.fromParts("ns.foo", "name"), "other-object", false}, - {ShapeId.fromParts("ns.foo", "name"), ShapeId.fromParts("ns.foo", "name"), true}, - {ShapeId.fromParts("ns.foo", "name1"), ShapeId.fromParts("ns.foo", "name2"), false}, - {ShapeId.fromParts("ns.foo1", "name1"), ShapeId.fromParts("ns.foo2", "name2"), false}, - {ShapeId.fromParts("ns.foo", "n", "a"), ShapeId.fromParts("ns.foo", "n", "a"), true}, - {ShapeId.fromParts("ns.foo", "n", "a"), ShapeId.fromParts("ns.foo", "n", "c"), false}, - } + new Object[][]{ + {obj, obj, true}, + {ShapeId.fromParts("ns.foo", "name"), "other-object", false}, + {ShapeId.fromParts("ns.foo", "name"), ShapeId.fromParts("ns.foo", "name"), true}, + {ShapeId.fromParts("ns.foo", "name1"), ShapeId.fromParts("ns.foo", "name2"), false}, + {ShapeId.fromParts("ns.foo1", "name1"), ShapeId.fromParts("ns.foo2", "name2"), false}, + {ShapeId.fromParts("ns.foo", "n", "a"), ShapeId.fromParts("ns.foo", "n", "a"), true}, + {ShapeId.fromParts("ns.foo", "n", "a"), ShapeId.fromParts("ns.foo", "n", "c"), false}, + } ); } @@ -353,10 +353,10 @@ public void validatesNamespacesWhenReplaced() { public void providesContextualServiceName() { ShapeId id = ShapeId.from("foo.bar#Name"); ServiceShape serviceShape = ServiceShape.builder() - .id("smithy.example#Service") - .version("1") - .putRename(id, "FooName") - .build(); + .id("smithy.example#Service") + .version("1") + .putRename(id, "FooName") + .build(); assertThat(id.getName(serviceShape), equalTo("FooName")); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeTest.java index 4693d48bd9c..1f4ae715973 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeTest.java @@ -107,14 +107,14 @@ public void hasTraits() { ShapeId id = ShapeId.from("ns.foo#baz"); DocumentationTrait documentationTrait = new DocumentationTrait("docs", SourceLocation.NONE); Shape shape = StringShape.builder() - .id(id) - .addTrait(trait) - .addTrait(otherTrait) - .addTrait(documentationTrait) - .build(); + .id(id) + .addTrait(trait) + .addTrait(otherTrait) + .addTrait(documentationTrait) + .build(); Model model = Model.builder() - .addShapes(shape) - .build(); + .addShapes(shape) + .build(); assertTrue(shape.getTrait(MyTrait.class).isPresent()); assertTrue(shape.getMemberTrait(model, MyTrait.class).isPresent()); @@ -155,11 +155,11 @@ public void removesTraits() { MyTrait trait = new MyTrait(ShapeId.from("foo.baz#foo"), null); MyTrait otherTrait = new OtherTrait(ShapeId.from("foo.baz#other"), null); Shape shape = StringShape.builder() - .id("ns.foo#baz") - .addTrait(trait) - .addTrait(otherTrait) - .removeTrait("foo.baz#other") - .build(); + .id("ns.foo#baz") + .addTrait(trait) + .addTrait(otherTrait) + .removeTrait("foo.baz#other") + .build(); assertThat(shape.getAllTraits(), hasKey(ShapeId.from("foo.baz#foo"))); assertThat(shape.getAllTraits(), not(hasKey(ShapeId.from("foo.baz#other")))); @@ -236,9 +236,9 @@ public void samesTraitsIsEqual() { public void validatesMemberShapeIds() { Assertions.assertThrows(SourceException.class, () -> { StructureShape.builder() - .id("ns.foo#bar") - .addMember(MemberShape.builder().id("ns.baz#Bar$boo").target(ShapeId.from("ns.foo#String")).build()) - .build(); + .id("ns.foo#bar") + .addMember(MemberShape.builder().id("ns.baz#Bar$boo").target(ShapeId.from("ns.foo#String")).build()) + .build(); }); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeVisitorDefaultTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeVisitorDefaultTest.java index 9b92bf955b3..132f5c1cb85 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeVisitorDefaultTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeVisitorDefaultTest.java @@ -27,63 +27,63 @@ private void testCases(ShapeVisitor visitor) { assertEquals(value, BlobShape.builder().id("ns.foo#Bar").build().accept(visitor)); assertEquals(value, BooleanShape.builder().id("ns.foo#Bar").build().accept(visitor)); assertEquals( - value, - ListShape.builder() - .id("ns.foo#Bar") - .member(MemberShape.builder().id("ns.foo#Bar$member").target("ns.foo#Baz").build()) - .build() - .accept(visitor) + value, + ListShape.builder() + .id("ns.foo#Bar") + .member(MemberShape.builder().id("ns.foo#Bar$member").target("ns.foo#Baz").build()) + .build() + .accept(visitor) ); assertEquals( - value, - SetShape.builder() - .id("ns.foo#Bar") - .member(MemberShape.builder().id("ns.foo#Bar$member").target("ns.foo#Baz").build()) - .build() - .accept(visitor) + value, + SetShape.builder() + .id("ns.foo#Bar") + .member(MemberShape.builder().id("ns.foo#Bar$member").target("ns.foo#Baz").build()) + .build() + .accept(visitor) ); assertEquals( - value, - MapShape.builder() - .id("ns.foo#Bar") - .key(MemberShape.builder().id("ns.foo#Bar$key").target("ns.foo#Baz").build()) - .value(MemberShape.builder().id("ns.foo#Bar$value").target("ns.foo#Baz").build()) - .build() - .accept(visitor) + value, + MapShape.builder() + .id("ns.foo#Bar") + .key(MemberShape.builder().id("ns.foo#Bar$key").target("ns.foo#Baz").build()) + .value(MemberShape.builder().id("ns.foo#Bar$value").target("ns.foo#Baz").build()) + .build() + .accept(visitor) ); assertEquals( - value, - OperationShape.builder() - .id("ns.foo#Bar") - .build() - .accept(visitor) + value, + OperationShape.builder() + .id("ns.foo#Bar") + .build() + .accept(visitor) ); assertEquals(value, ResourceShape.builder().id("ns.foo#Bar").build().accept(visitor)); assertEquals( - value, - ServiceShape.builder() - .id("ns.foo#Bar") - .version("2017-01-17") - .build() - .accept(visitor) + value, + ServiceShape.builder() + .id("ns.foo#Bar") + .version("2017-01-17") + .build() + .accept(visitor) ); assertEquals(value, StringShape.builder().id("ns.foo#Bar").build().accept(visitor)); assertEquals(value, StructureShape.builder().id("ns.foo#Bar").build().accept(visitor)); assertEquals( - value, - UnionShape.builder() - .id("ns.foo#Bar") - .addMember(MemberShape.builder().id("ns.foo#Bar$baz").target("ns.foo#Abc").build()) - .build() - .accept(visitor) + value, + UnionShape.builder() + .id("ns.foo#Bar") + .addMember(MemberShape.builder().id("ns.foo#Bar$baz").target("ns.foo#Abc").build()) + .build() + .accept(visitor) ); assertEquals( - value, - MemberShape.builder() - .id("ns.foo#Bar$member") - .target("ns.foo#Bam") - .build() - .accept(visitor) + value, + MemberShape.builder() + .id("ns.foo#Bar$member") + .target("ns.foo#Bam") + .build() + .accept(visitor) ); assertEquals(value, TimestampShape.builder().id("ns.foo#Bar").build().accept(visitor)); assertEquals(value, ByteShape.builder().id("ns.foo#Bar").build().accept(visitor)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/SmithyIdlModelSerializerTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/SmithyIdlModelSerializerTest.java index c1fff506c74..f68bb655063 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/SmithyIdlModelSerializerTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/SmithyIdlModelSerializerTest.java @@ -39,13 +39,13 @@ public class SmithyIdlModelSerializerTest { private static final URL TEST_FILE_URL = Objects.requireNonNull( - SmithyIdlModelSerializer.class.getResource("idl-serialization/cases") + SmithyIdlModelSerializer.class.getResource("idl-serialization/cases") ); @TestFactory public Stream generateTests() throws IOException, URISyntaxException { return Files.list(Paths.get(TEST_FILE_URL.toURI())) - .map(path -> DynamicTest.dynamicTest(path.getFileName().toString(), () -> testConversion(path))); + .map(path -> DynamicTest.dynamicTest(path.getFileName().toString(), () -> testConversion(path))); } public void testConversion(Path path) { @@ -64,43 +64,43 @@ public void testConversion(Path path) { @Test public void multipleNamespacesGenerateMultipleFiles() throws Exception { Model model = Model.assembler() - .addImport(getClass().getResource("idl-serialization/multiple-namespaces/input.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("idl-serialization/multiple-namespaces/input.json")) + .assemble() + .unwrap(); Path outputDir = Paths.get(getClass().getResource("idl-serialization/multiple-namespaces/output").toURI()); SmithyIdlModelSerializer serializer = SmithyIdlModelSerializer.builder() - .basePath(outputDir) - .build(); + .basePath(outputDir) + .build(); Map serialized = serializer.serialize(model); serialized.forEach( - (path, generated) -> assertThat( - generated, - equalTo(IoUtils.readUtf8File(path).replaceAll("\\R", "\n")) - ) + (path, generated) -> assertThat( + generated, + equalTo(IoUtils.readUtf8File(path).replaceAll("\\R", "\n")) + ) ); } @Test public void filtersShapes() { Model model = Model.assembler() - .addImport(getClass().getResource("idl-serialization/test-model.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("idl-serialization/test-model.json")) + .assemble() + .unwrap(); SmithyIdlModelSerializer serializer = SmithyIdlModelSerializer.builder() - .shapeFilter(shape -> shape.getId().getNamespace().equals("ns.structures")) - .build(); + .shapeFilter(shape -> shape.getId().getNamespace().equals("ns.structures")) + .build(); Map serialized = serializer.serialize(model); assertThat(serialized, aMapWithSize(2)); assertThat(serialized, hasKey(Paths.get("ns.structures.smithy"))); assertThat( - serialized.get(Paths.get("ns.structures.smithy")), - containsString("namespace ns.structures") + serialized.get(Paths.get("ns.structures.smithy")), + containsString("namespace ns.structures") ); assertThat(serialized, hasKey(Paths.get("metadata.smithy"))); assertThat( - serialized.get(Paths.get("metadata.smithy")), - containsString("metadata shared = true") + serialized.get(Paths.get("metadata.smithy")), + containsString("metadata shared = true") ); assertThat(serialized, not(hasKey(Paths.get("smithy.api.smithy")))); } @@ -108,12 +108,12 @@ public void filtersShapes() { @Test public void filtersMetadata() { Model model = Model.assembler() - .addImport(getClass().getResource("idl-serialization/test-model.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("idl-serialization/test-model.json")) + .assemble() + .unwrap(); SmithyIdlModelSerializer serializer = SmithyIdlModelSerializer.builder() - .metadataFilter(key -> false) - .build(); + .metadataFilter(key -> false) + .build(); Map serialized = serializer.serialize(model); for (String output : serialized.values()) { assertThat(output, not(containsString("metadata"))); @@ -123,12 +123,12 @@ public void filtersMetadata() { @Test public void filtersTraits() { Model model = Model.assembler() - .addImport(getClass().getResource("idl-serialization/test-model.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("idl-serialization/test-model.json")) + .assemble() + .unwrap(); SmithyIdlModelSerializer serializer = SmithyIdlModelSerializer.builder() - .traitFilter(trait -> !(trait instanceof RequiredTrait)) - .build(); + .traitFilter(trait -> !(trait instanceof RequiredTrait)) + .build(); Map serialized = serializer.serialize(model); for (String output : serialized.values()) { assertThat(output, not(containsString("@required"))); @@ -138,12 +138,12 @@ public void filtersTraits() { @Test public void filtersDocumentationTrait() { Model model = Model.assembler() - .addImport(getClass().getResource("idl-serialization/test-model.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("idl-serialization/test-model.json")) + .assemble() + .unwrap(); SmithyIdlModelSerializer serializer = SmithyIdlModelSerializer.builder() - .traitFilter(trait -> !(trait instanceof DocumentationTrait)) - .build(); + .traitFilter(trait -> !(trait instanceof DocumentationTrait)) + .build(); Map serialized = serializer.serialize(model); for (String output : serialized.values()) { assertThat(output, not(containsString("/// "))); @@ -154,12 +154,12 @@ public void filtersDocumentationTrait() { public void basePathAppliesToMetadataOnlyModel() { Path basePath = Paths.get("/tmp/smithytest"); Model model = Model.assembler() - .putMetadata("foo", StringNode.from("bar")) - .assemble() - .unwrap(); + .putMetadata("foo", StringNode.from("bar")) + .assemble() + .unwrap(); SmithyIdlModelSerializer serializer = SmithyIdlModelSerializer.builder() - .basePath(basePath) - .build(); + .basePath(basePath) + .build(); Map serialized = serializer.serialize(model); assertThat(serialized.keySet(), contains(basePath.resolve("metadata.smithy"))); } @@ -167,8 +167,8 @@ public void basePathAppliesToMetadataOnlyModel() { @Test public void emptyServiceVersionNotSerialized() { ServiceShape service = ServiceShape.builder() - .id("com.foo#Example") - .build(); + .id("com.foo#Example") + .build(); Model model = Model.builder().addShape(service).build(); SmithyIdlModelSerializer serializer = SmithyIdlModelSerializer.builder().build(); Map serialized = serializer.serialize(model); @@ -180,31 +180,31 @@ public void emptyServiceVersionNotSerialized() { public void transientTraitsAreNotSerialized() { ShapeId originalId = ShapeId.from("com.foo.nested#Str"); StringShape stringShape = StringShape.builder() - .id("com.foo#Str") - .addTrait(new OriginalShapeIdTrait(originalId)) - .build(); + .id("com.foo#Str") + .addTrait(new OriginalShapeIdTrait(originalId)) + .build(); Model model = Model.builder() - .addShape(stringShape) - .build(); + .addShape(stringShape) + .build(); SmithyIdlModelSerializer serializer = SmithyIdlModelSerializer.builder().build(); Map results = serializer.serialize(model); assertThat( - results.get(Paths.get("com.foo.smithy")), - not(containsString(OriginalShapeIdTrait.ID.toString())) + results.get(Paths.get("com.foo.smithy")), + not(containsString(OriginalShapeIdTrait.ID.toString())) ); } @Test public void canEnableSerializingPrelude() { Model model = Model.assembler() - .addImport(getClass().getResource("idl-serialization/test-model.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("idl-serialization/test-model.json")) + .assemble() + .unwrap(); SmithyIdlModelSerializer serializer = SmithyIdlModelSerializer.builder() - .serializePrelude() - .build(); + .serializePrelude() + .build(); Map serialized = serializer.serialize(model); assertThat(serialized.get(Paths.get("smithy.api.smithy")), containsString("namespace smithy.api")); } @@ -212,9 +212,9 @@ public void canEnableSerializingPrelude() { @Test public void serializesSetsAsListsWithUniqueItems() { SetShape set = SetShape.builder() - .id("smithy.example#Set") - .member(ShapeId.from("smithy.api#String")) - .build(); + .id("smithy.example#Set") + .member(ShapeId.from("smithy.api#String")) + .build(); Model model = Model.assembler().addShape(set).assemble().unwrap(); SmithyIdlModelSerializer serializer = SmithyIdlModelSerializer.builder().build(); Map models = serializer.serialize(model); @@ -227,21 +227,21 @@ public void serializesSetsAsListsWithUniqueItems() { @Test public void serializesRootLevelDefaults() { String stringModel = "$version: \"2.0\"\n" - + "namespace smithy.example\n" - + "@default(false)\n" - + "boolean PrimitiveBool\n"; + + "namespace smithy.example\n" + + "@default(false)\n" + + "boolean PrimitiveBool\n"; Model model = Model.assembler().addUnparsedModel("test.smithy", stringModel).assemble().unwrap(); Map reserialized = SmithyIdlModelSerializer.builder().build().serialize(model); String modelResult = reserialized.get(Paths.get("smithy.example.smithy")); Model model2 = Model.assembler().addUnparsedModel("test.smithy", modelResult).assemble().unwrap(); assertThat( - model.expectShape(ShapeId.from("smithy.example#PrimitiveBool")).hasTrait(DefaultTrait.ID), - is(true) + model.expectShape(ShapeId.from("smithy.example#PrimitiveBool")).hasTrait(DefaultTrait.ID), + is(true) ); assertThat( - model2.expectShape(ShapeId.from("smithy.example#PrimitiveBool")).hasTrait(DefaultTrait.ID), - is(true) + model2.expectShape(ShapeId.from("smithy.example#PrimitiveBool")).hasTrait(DefaultTrait.ID), + is(true) ); assertThat(model2, equalTo(model2)); } @@ -251,9 +251,9 @@ public void usesOriginalSourceLocation() { URL resource = getClass().getResource("idl-serialization/out-of-order.smithy"); Model model = Model.assembler().addImport(resource).assemble().unwrap(); Map reserialized = SmithyIdlModelSerializer.builder() - .componentOrder(SmithyIdlComponentOrder.SOURCE_LOCATION) - .build() - .serialize(model); + .componentOrder(SmithyIdlComponentOrder.SOURCE_LOCATION) + .build() + .serialize(model); String modelResult = reserialized.values().iterator().next().replace("\r\n", "\n"); assertThat(modelResult, equalTo(IoUtils.readUtf8Url(resource).replace("\r\n", "\n"))); @@ -267,9 +267,9 @@ public void sortsAlphabetically() { Model model = Model.assembler().addImport(before).assemble().unwrap(); Map reserialized = SmithyIdlModelSerializer.builder() - .componentOrder(SmithyIdlComponentOrder.ALPHA_NUMERIC) - .build() - .serialize(model); + .componentOrder(SmithyIdlComponentOrder.ALPHA_NUMERIC) + .build() + .serialize(model); String modelResult = reserialized.get(Paths.get("com.example.smithy")).replace("\r\n", "\n"); String metadataResult = reserialized.get(Paths.get("metadata.smithy")).replace("\r\n", "\n"); @@ -289,7 +289,7 @@ public void handlesEnumMixins() { } String expectedOutput = IoUtils.readUtf8Resource(getClass(), "idl-serialization/enum-mixin-output.smithy") - .replaceAll("\\R", "\n"); + .replaceAll("\\R", "\n"); String serializedString = serialized.entrySet().iterator().next().getValue(); assertEquals(expectedOutput, serializedString); } @@ -303,10 +303,10 @@ public void handlesCustomInlineSuffixes() { Assertions.assertTrue(model.getShape(ShapeId.from("com.example#InlineOperationResponse")).isPresent()); Map reserialized = SmithyIdlModelSerializer.builder() - .inlineInputSuffix("Request") - .inlineOutputSuffix("Response") - .build() - .serialize(model); + .inlineInputSuffix("Request") + .inlineOutputSuffix("Response") + .build() + .serialize(model); String modelResult = reserialized.values().iterator().next().replace("\r\n", "\n"); assertThat(modelResult, equalTo(IoUtils.readUtf8Url(resource).replace("\r\n", "\n"))); @@ -315,24 +315,24 @@ public void handlesCustomInlineSuffixes() { @Test public void canInferInlineSuffixes() { Map resources = MapUtils.of( - Paths.get("default.smithy"), - getClass().getResource("idl-serialization/inferred-io/default.smithy"), - Paths.get("main.smithy"), - getClass().getResource("idl-serialization/inferred-io/main.smithy"), - Paths.get("mixed.smithy"), - getClass().getResource("idl-serialization/inferred-io/mixed.smithy"), - Paths.get("shared.smithy"), - getClass().getResource("idl-serialization/inferred-io/shared.smithy") + Paths.get("default.smithy"), + getClass().getResource("idl-serialization/inferred-io/default.smithy"), + Paths.get("main.smithy"), + getClass().getResource("idl-serialization/inferred-io/main.smithy"), + Paths.get("mixed.smithy"), + getClass().getResource("idl-serialization/inferred-io/mixed.smithy"), + Paths.get("shared.smithy"), + getClass().getResource("idl-serialization/inferred-io/shared.smithy") ); ModelAssembler assembler = Model.assembler(); resources.values().forEach(assembler::addImport); Model model = assembler.assemble().unwrap(); Map reserialized = SmithyIdlModelSerializer.builder() - .shapePlacer(s -> Paths.get(s.getSourceLocation().getFilename()).getFileName()) - .inferInlineIoSuffixes(true) - .build() - .serialize(model); + .shapePlacer(s -> Paths.get(s.getSourceLocation().getFilename()).getFileName()) + .inferInlineIoSuffixes(true) + .build() + .serialize(model); assertThat(reserialized.size(), equalTo(resources.size())); for (Map.Entry entry : reserialized.entrySet()) { @@ -346,18 +346,18 @@ public void canInferInlineSuffixes() { @Test public void coercesInlineIO() { Model before = Model.assembler() - .addImport(getClass().getResource("idl-serialization/coerced-io/before.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("idl-serialization/coerced-io/before.smithy")) + .assemble() + .unwrap(); Map reserialized = SmithyIdlModelSerializer.builder() - .coerceInlineIo(true) - .build() - .serialize(before); + .coerceInlineIo(true) + .build() + .serialize(before); String modelResult = reserialized.values().iterator().next().replace("\r\n", "\n"); String expected = IoUtils.readUtf8Url(getClass().getResource("idl-serialization/coerced-io/after.smithy")) - .replace("\r\n", "\n"); + .replace("\r\n", "\n"); assertEquals(expected, modelResult); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/StructureShapeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/StructureShapeTest.java index 745f2c1e7fe..ad8126e3e54 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/StructureShapeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/StructureShapeTest.java @@ -39,40 +39,40 @@ public void mustNotContainMembersInShapeId() { @Test public void addMemberWithTarget() { StructureShape shape = StructureShape.builder() - .id("ns.foo#bar") - .addMember("foo", ShapeId.from("ns.foo#bam")) - .build(); + .id("ns.foo#bar") + .addMember("foo", ShapeId.from("ns.foo#bam")) + .build(); assertEquals( - shape.getMember("foo").get(), - MemberShape.builder().id(shape.getId().withMember("foo")).target("ns.foo#bam").build() + shape.getMember("foo").get(), + MemberShape.builder().id(shape.getId().withMember("foo")).target("ns.foo#bam").build() ); } @Test public void addMemberWithConsumer() { StructureShape shape = StructureShape.builder() - .id("ns.foo#bar") - .addMember("foo", ShapeId.from("ns.foo#bam"), builder -> builder.addTrait(new SensitiveTrait())) - .build(); + .id("ns.foo#bar") + .addMember("foo", ShapeId.from("ns.foo#bam"), builder -> builder.addTrait(new SensitiveTrait())) + .build(); assertEquals( - shape.getMember("foo").get(), - MemberShape.builder() - .id(shape.getId().withMember("foo")) - .target("ns.foo#bam") - .addTrait(new SensitiveTrait()) - .build() + shape.getMember("foo").get(), + MemberShape.builder() + .id(shape.getId().withMember("foo")) + .target("ns.foo#bam") + .addTrait(new SensitiveTrait()) + .build() ); } @Test public void returnsMembers() { StructureShape shape = StructureShape.builder() - .id("ns.foo#bar") - .addMember("foo", ShapeId.from("ns.foo#bam")) - .addMember("baz", ShapeId.from("ns.foo#bam")) - .build(); + .id("ns.foo#bar") + .addMember("foo", ShapeId.from("ns.foo#bam")) + .addMember("baz", ShapeId.from("ns.foo#bam")) + .build(); assertThat(shape.members(), hasSize(2)); // Members are ordered. @@ -83,16 +83,16 @@ public void returnsMembers() { @Test public void memberOrderMattersForEqualComparison() { StructureShape a = StructureShape.builder() - .id("ns.foo#bar") - .addMember("foo", ShapeId.from("ns.foo#bam")) - .addMember("baz", ShapeId.from("ns.foo#bam")) - .build(); + .id("ns.foo#bar") + .addMember("foo", ShapeId.from("ns.foo#bam")) + .addMember("baz", ShapeId.from("ns.foo#bam")) + .build(); StructureShape b = StructureShape.builder() - .id("ns.foo#bar") - .addMember("baz", ShapeId.from("ns.foo#bam")) - .addMember("foo", ShapeId.from("ns.foo#bam")) - .build(); + .id("ns.foo#bar") + .addMember("baz", ShapeId.from("ns.foo#bam")) + .addMember("foo", ShapeId.from("ns.foo#bam")) + .build(); assertThat(a, not(equalTo(b))); } @@ -100,18 +100,18 @@ public void memberOrderMattersForEqualComparison() { @Test public void builderUpdatesMemberIds() { StructureShape original = StructureShape.builder() - .id("ns.foo#bar") - .addMember("foo", ShapeId.from("ns.foo#bam")) - .addMember("baz", ShapeId.from("ns.foo#bam")) - .build(); + .id("ns.foo#bar") + .addMember("foo", ShapeId.from("ns.foo#bam")) + .addMember("baz", ShapeId.from("ns.foo#bam")) + .build(); StructureShape actual = original.toBuilder().id(ShapeId.from("ns.bar#bar")).build(); StructureShape expected = StructureShape.builder() - .id("ns.bar#bar") - .addMember("foo", ShapeId.from("ns.foo#bam")) - .addMember("baz", ShapeId.from("ns.foo#bam")) - .build(); + .id("ns.bar#bar") + .addMember("foo", ShapeId.from("ns.foo#bam")) + .addMember("baz", ShapeId.from("ns.foo#bam")) + .build(); assertThat(actual, equalTo(expected)); } @@ -119,23 +119,23 @@ public void builderUpdatesMemberIds() { @Test public void supportsMixinTraits() { StructureShape mixin1 = StructureShape.builder() - .id("smithy.example#Mixin1") - .addTrait(new SensitiveTrait()) - .build(); + .id("smithy.example#Mixin1") + .addTrait(new SensitiveTrait()) + .build(); StructureShape mixin2 = StructureShape.builder() - .id("smithy.example#Mixin2") - .addTrait(DeprecatedTrait.builder().build()) - .build(); + .id("smithy.example#Mixin2") + .addTrait(DeprecatedTrait.builder().build()) + .build(); StructureShape mixin3 = StructureShape.builder() - .id("smithy.example#Mixin3") - .addMixin(mixin2) - .build(); + .id("smithy.example#Mixin3") + .addMixin(mixin2) + .build(); StructureShape concrete = StructureShape.builder() - .id("smithy.example#Concrete") - .addMixin(mixin1) - .addMixin(mixin3) - .addTrait(new DocumentationTrait("hi")) - .build(); + .id("smithy.example#Concrete") + .addMixin(mixin1) + .addMixin(mixin3) + .addTrait(new DocumentationTrait("hi")) + .build(); assertTrue(concrete.hasTrait(SensitiveTrait.class)); assertTrue(concrete.hasTrait(DeprecatedTrait.class)); @@ -146,29 +146,29 @@ public void supportsMixinTraits() { public void reordersMixinMembersAutomatically() { StringShape string = StringShape.builder().id("smithy.example#String").build(); StructureShape mixin1 = StructureShape.builder() - .id("smithy.example#Mixin1") - .addTrait(MixinTrait.builder().build()) - .addMember("a", string.getId()) - .build(); + .id("smithy.example#Mixin1") + .addTrait(MixinTrait.builder().build()) + .addMember("a", string.getId()) + .build(); StructureShape mixin2 = StructureShape.builder() - .id("smithy.example#Mixin2") - .addTrait(MixinTrait.builder().build()) - .addMember("b", string.getId()) - .build(); + .id("smithy.example#Mixin2") + .addTrait(MixinTrait.builder().build()) + .addMember("b", string.getId()) + .build(); StructureShape mixin3 = StructureShape.builder() - .id("smithy.example#Mixin3") - .addTrait(MixinTrait.builder().build()) - .addMember("c", string.getId()) - .addMixin(mixin2) - .build(); + .id("smithy.example#Mixin3") + .addTrait(MixinTrait.builder().build()) + .addMember("c", string.getId()) + .addMixin(mixin2) + .build(); StructureShape concrete = StructureShape.builder() - .id("smithy.example#Concrete") - // Note that d is added before mixins, but the builder tracks this - // and handles ordering appropriately when building the shape. - .addMember("d", string.getId()) - .addMixin(mixin1) - .addMixin(mixin3) - .build(); + .id("smithy.example#Concrete") + // Note that d is added before mixins, but the builder tracks this + // and handles ordering appropriately when building the shape. + .addMember("d", string.getId()) + .addMixin(mixin1) + .addMixin(mixin3) + .build(); assertThat(concrete.getMemberNames(), contains("a", "b", "c", "d")); } @@ -177,24 +177,24 @@ public void reordersMixinMembersAutomatically() { public void mixinMembersCanBeModifiedJustLikeNormalMembers() { StringShape string = StringShape.builder().id("smithy.example#String").build(); StructureShape mixin1 = StructureShape.builder() - .id("smithy.example#Mixin1") - .addTrait(MixinTrait.builder().build()) - .addMember("a", string.getId()) - .build(); + .id("smithy.example#Mixin1") + .addTrait(MixinTrait.builder().build()) + .addMember("a", string.getId()) + .build(); StructureShape concrete = StructureShape.builder() - .id("smithy.example#Concrete") - .addMixin(mixin1) - .build(); + .id("smithy.example#Concrete") + .addMixin(mixin1) + .build(); // Just like you'd do with a normal member, you first get the member, // then convert it to a builder to update it, then build it. Then the // member is added to a new container shape and rebuilt. The workflow // is exactly the same as a normal structure with no mixin members. MemberShape updatedA = concrete.getMember("a") - .get() - .toBuilder() - .addTrait(new SensitiveTrait()) - .build(); + .get() + .toBuilder() + .addTrait(new SensitiveTrait()) + .build(); StructureShape updated = concrete.toBuilder().addMember(updatedA).build(); assertThat(updated.getMemberNames(), contains("a")); @@ -206,21 +206,21 @@ public void mixinMembersCanBeModifiedJustLikeNormalMembers() { public void structuresAccountForMissingMixinsOnLocalMembers() { StringShape string = StringShape.builder().id("smithy.example#String").build(); StructureShape mixin1 = StructureShape.builder() - .id("smithy.example#TestMixin1") - .addTrait(MixinTrait.builder().build()) - .addMember("a", string.getId(), builder -> builder.addTrait(new SensitiveTrait())) - .addMember("b", string.getId()) - .build(); + .id("smithy.example#TestMixin1") + .addTrait(MixinTrait.builder().build()) + .addMember("a", string.getId(), builder -> builder.addTrait(new SensitiveTrait())) + .addMember("b", string.getId()) + .build(); StructureShape concrete = StructureShape.builder() - .id("smithy.example#Concrete") - // The missing mixin is automatically added to the computed members because the mixin - // is added after the member is added. If the member is added after the mixin, then - // this safeguard doesn't work. - .addMember(MemberShape.builder().id("smithy.example#Concrete$a").target(string).build()) - // Note that b becomes a local member because it introduces a new trait. - .addMember("b", string.getId(), builder -> builder.addTrait(new SensitiveTrait())) - .addMixin(mixin1) - .build(); + .id("smithy.example#Concrete") + // The missing mixin is automatically added to the computed members because the mixin + // is added after the member is added. If the member is added after the mixin, then + // this safeguard doesn't work. + .addMember(MemberShape.builder().id("smithy.example#Concrete$a").target(string).build()) + // Note that b becomes a local member because it introduces a new trait. + .addMember("b", string.getId(), builder -> builder.addTrait(new SensitiveTrait())) + .addMixin(mixin1) + .build(); assertTrue(concrete.getMember("a").get().hasTrait(SensitiveTrait.class)); assertThat(concrete.getMember("a").get().getMixins(), contains(mixin1.getMember("a").get().getId())); @@ -233,30 +233,30 @@ public void structuresAccountForMissingMixinsOnLocalMembers() { public void flattensMixins() { StringShape string = StringShape.builder().id("smithy.example#String").build(); StructureShape mixin1 = StructureShape.builder() - .id("smithy.example#TestMixin1") - .addTrait(MixinTrait.builder().addLocalTrait(InternalTrait.ID).build()) - .addTrait(DeprecatedTrait.builder().build()) - .addTrait(new InternalTrait()) // local and not copied. - .addMember("a", string.getId(), builder -> builder.addTrait(new SensitiveTrait())) - .addMember("b", string.getId()) - .build(); + .id("smithy.example#TestMixin1") + .addTrait(MixinTrait.builder().addLocalTrait(InternalTrait.ID).build()) + .addTrait(DeprecatedTrait.builder().build()) + .addTrait(new InternalTrait()) // local and not copied. + .addMember("a", string.getId(), builder -> builder.addTrait(new SensitiveTrait())) + .addMember("b", string.getId()) + .build(); StructureShape concrete = StructureShape.builder() - .id("smithy.example#Concrete") - .addTrait(new SensitiveTrait()) - .addMixin(mixin1) - .addMember("b", string.getId(), builder -> builder.addTrait(DeprecatedTrait.builder().build())) - .addMember("c", string.getId()) - .build(); + .id("smithy.example#Concrete") + .addTrait(new SensitiveTrait()) + .addMixin(mixin1) + .addMember("b", string.getId(), builder -> builder.addTrait(DeprecatedTrait.builder().build())) + .addMember("c", string.getId()) + .build(); StructureShape flattened = concrete.toBuilder().flattenMixins().build(); StructureShape expected = StructureShape.builder() - .id("smithy.example#Concrete") - .addTrait(new SensitiveTrait()) - .addTrait(DeprecatedTrait.builder().build()) - .addMember("a", string.getId(), builder -> builder.addTrait(new SensitiveTrait())) - .addMember("b", string.getId(), builder -> builder.addTrait(DeprecatedTrait.builder().build())) - .addMember("c", string.getId()) - .build(); + .id("smithy.example#Concrete") + .addTrait(new SensitiveTrait()) + .addTrait(DeprecatedTrait.builder().build()) + .addMember("a", string.getId(), builder -> builder.addTrait(new SensitiveTrait())) + .addMember("b", string.getId(), builder -> builder.addTrait(DeprecatedTrait.builder().build())) + .addMember("c", string.getId()) + .build(); assertThat(flattened, equalTo(expected)); assertThat(flattened.getMemberNames(), contains("a", "b", "c")); @@ -273,35 +273,35 @@ public void flatteningStructureWithNoMixinsDoesNothing() { public void redefiningMembersPreservesOrder() { StringShape string = StringShape.builder().id("smithy.example#String").build(); StructureShape mixin1 = StructureShape.builder() - .id("smithy.example#Mixin1") - .addTrait(MixinTrait.builder().build()) - .addMember("a", string.getId()) - .addMember("b", string.getId()) - .addMember("c", string.getId()) - .build(); + .id("smithy.example#Mixin1") + .addTrait(MixinTrait.builder().build()) + .addMember("a", string.getId()) + .addMember("b", string.getId()) + .addMember("c", string.getId()) + .build(); StructureShape mixin2 = StructureShape.builder() - .id("smithy.example#Mixin2") - .addTrait(MixinTrait.builder().build()) - .addMember("c", string.getId()) - .addMember("b", string.getId()) - .addMember("a", string.getId()) - .build(); + .id("smithy.example#Mixin2") + .addTrait(MixinTrait.builder().build()) + .addMember("c", string.getId()) + .addMember("b", string.getId()) + .addMember("a", string.getId()) + .build(); StructureShape mixin3 = StructureShape.builder() - .id("smithy.example#Mixin3") - .addTrait(MixinTrait.builder().build()) - .addMember("b", string.getId()) - .addMember("c", string.getId()) - .addMember("a", string.getId()) - .addMixin(mixin2) - .build(); + .id("smithy.example#Mixin3") + .addTrait(MixinTrait.builder().build()) + .addMember("b", string.getId()) + .addMember("c", string.getId()) + .addMember("a", string.getId()) + .addMixin(mixin2) + .build(); StructureShape concrete = StructureShape.builder() - .id("smithy.example#Concrete") - // Note that d is added before mixins, but the builder tracks this - // and handles ordering appropriately when building the shape. - .addMember("d", string.getId()) - .addMixin(mixin1) - .addMixin(mixin3) - .build(); + .id("smithy.example#Concrete") + // Note that d is added before mixins, but the builder tracks this + // and handles ordering appropriately when building the shape. + .addMember("d", string.getId()) + .addMixin(mixin1) + .addMixin(mixin3) + .build(); assertThat(concrete.getMemberNames(), contains("a", "b", "c", "d")); } @@ -310,28 +310,28 @@ public void redefiningMembersPreservesOrder() { public void fixesMissingMemberMixins() { StringShape string = StringShape.builder().id("smithy.example#String").build(); StructureShape mixin1 = StructureShape.builder() - .id("smithy.example#Mixin1") - .addTrait(MixinTrait.builder().build()) - .addMember("a", string.getId()) - .build(); + .id("smithy.example#Mixin1") + .addTrait(MixinTrait.builder().build()) + .addMember("a", string.getId()) + .build(); StructureShape mixin2 = StructureShape.builder() - .id("smithy.example#Mixin2") - .addTrait(MixinTrait.builder().build()) - .addMember("a", string.getId()) - .build(); + .id("smithy.example#Mixin2") + .addTrait(MixinTrait.builder().build()) + .addMember("a", string.getId()) + .build(); StructureShape concrete = StructureShape.builder() - .id("smithy.example#Concrete") - .addMember("a", string.getId()) - .addMixin(mixin1) - .addMixin(mixin2) - .build(); + .id("smithy.example#Concrete") + .addMember("a", string.getId()) + .addMixin(mixin1) + .addMixin(mixin2) + .build(); assertThat( - concrete.getMember("a").get().getMixins(), - contains( - ShapeId.from("smithy.example#Mixin1$a"), - ShapeId.from("smithy.example#Mixin2$a") - ) + concrete.getMember("a").get().getMixins(), + contains( + ShapeId.from("smithy.example#Mixin1$a"), + ShapeId.from("smithy.example#Mixin2$a") + ) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/UnionShapeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/UnionShapeTest.java index a8c5da2f5d8..c65f8031e64 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/UnionShapeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/UnionShapeTest.java @@ -16,14 +16,14 @@ public class UnionShapeTest { @Test public void returnsAppropriateType() { UnionShape shape = UnionShape.builder() - .id("ns.foo#bar") - .addMember( - MemberShape.builder() - .id("ns.foo#bar$baz") - .target("ns.foo#bam") - .build() - ) - .build(); + .id("ns.foo#bar") + .addMember( + MemberShape.builder() + .id("ns.foo#bar$baz") + .target("ns.foo#bam") + .build() + ) + .build(); assertEquals(shape.getType(), ShapeType.UNION); } @@ -38,18 +38,18 @@ public void mustNotContainMembersInShapeId() { @Test public void builderUpdatesMemberIds() { UnionShape original = UnionShape.builder() - .id("ns.foo#bar") - .addMember("foo", ShapeId.from("ns.foo#bam")) - .addMember("baz", ShapeId.from("ns.foo#bam")) - .build(); + .id("ns.foo#bar") + .addMember("foo", ShapeId.from("ns.foo#bam")) + .addMember("baz", ShapeId.from("ns.foo#bam")) + .build(); UnionShape actual = original.toBuilder().id(ShapeId.from("ns.bar#bar")).build(); UnionShape expected = UnionShape.builder() - .id("ns.bar#bar") - .addMember("foo", ShapeId.from("ns.foo#bam")) - .addMember("baz", ShapeId.from("ns.foo#bam")) - .build(); + .id("ns.bar#bar") + .addMember("foo", ShapeId.from("ns.foo#bam")) + .addMember("baz", ShapeId.from("ns.foo#bam")) + .build(); assertThat(actual, equalTo(expected)); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/AnnotationTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/AnnotationTraitTest.java index 60bdc5f97b2..5372ff1901f 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/AnnotationTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/AnnotationTraitTest.java @@ -41,8 +41,8 @@ public void validatesAnnotationTraits() { @Test public void annotationTraitsAreNotLossy() { ObjectNode objectNode = new ObjectNode( - MapUtils.of(Node.from("hi"), Node.from("bye")), - SourceLocation.NONE + MapUtils.of(Node.from("hi"), Node.from("bye")), + SourceLocation.NONE ); SensitiveTrait trait = new SensitiveTrait.Provider().createTrait(ShapeId.from("foo#bar"), objectNode); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/AuthDefinitionTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/AuthDefinitionTraitTest.java index 654c0dea987..ad29d0ed84c 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/AuthDefinitionTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/AuthDefinitionTraitTest.java @@ -21,25 +21,25 @@ public class AuthDefinitionTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); ArrayNode values = Node.fromStrings( - JsonNameTrait.ID.toString(), - XmlNameTrait.ID.toString() + JsonNameTrait.ID.toString(), + XmlNameTrait.ID.toString() ); Node node = Node.objectNode().withMember("traits", values); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#authDefinition"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#authDefinition"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(AuthDefinitionTrait.class)); AuthDefinitionTrait authDefinitionTrait = (AuthDefinitionTrait) trait.get(); assertThat( - authDefinitionTrait.getTraits(), - containsInAnyOrder( - JsonNameTrait.ID, - XmlNameTrait.ID - ) + authDefinitionTrait.getTraits(), + containsInAnyOrder( + JsonNameTrait.ID, + XmlNameTrait.ID + ) ); assertThat(authDefinitionTrait.toNode(), equalTo(node)); assertThat(authDefinitionTrait.toBuilder().build(), equalTo(authDefinitionTrait)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/ClientOptionalTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/ClientOptionalTraitTest.java index 618f484ecc7..edc82a57ebf 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/ClientOptionalTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/ClientOptionalTraitTest.java @@ -20,9 +20,9 @@ public class ClientOptionalTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#clientOptional"), - ShapeId.from("ns.qux#foo"), - Node.objectNode() + ShapeId.from("smithy.api#clientOptional"), + ShapeId.from("ns.qux#foo"), + Node.objectNode() ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/CorsTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/CorsTraitTest.java index e9b23b58c93..91570029942 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/CorsTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/CorsTraitTest.java @@ -24,10 +24,10 @@ public class CorsTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); ObjectNode node = Node.objectNode() - .withMember("origin", Node.from("https://www.amazon.com")) - .withMember("maxAge", Node.from(86400)) - .withMember("additionalAllowedHeaders", Node.fromStrings("foo", "bar")) - .withMember("additionalExposedHeaders", Node.fromStrings("fizz", "buzz")); + .withMember("origin", Node.from("https://www.amazon.com")) + .withMember("maxAge", Node.from(86400)) + .withMember("additionalAllowedHeaders", Node.fromStrings("foo", "bar")) + .withMember("additionalExposedHeaders", Node.fromStrings("fizz", "buzz")); Optional trait = provider.createTrait(ShapeId.from("smithy.api#cors"), ShapeId.from("ns.qux#foo"), node); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(CorsTrait.class)); @@ -43,9 +43,9 @@ public void loadsTrait() { public void injectsDefaults() { TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#cors"), - ShapeId.from("ns.qux#foo"), - Node.objectNode() + ShapeId.from("smithy.api#cors"), + ShapeId.from("ns.qux#foo"), + Node.objectNode() ); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(CorsTrait.class)); @@ -61,10 +61,10 @@ public void injectsDefaults() { public void omitsDefaultsFromSerializedNode() { TraitFactory provider = TraitFactory.createServiceFactory(); ObjectNode node = Node.objectNode() - .withMember("origin", Node.from("*")) - .withMember("maxAge", Node.from(600)) - .withMember("additionalAllowedHeaders", Node.fromStrings()) - .withMember("additionalExposedHeaders", Node.fromStrings()); + .withMember("origin", Node.from("*")) + .withMember("maxAge", Node.from(600)) + .withMember("additionalAllowedHeaders", Node.fromStrings()) + .withMember("additionalExposedHeaders", Node.fromStrings()); Optional trait = provider.createTrait(ShapeId.from("smithy.api#cors"), ShapeId.from("ns.qux#foo"), node); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(CorsTrait.class)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/DeprecatedTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/DeprecatedTraitTest.java index 5c97f6714ac..84c692b3167 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/DeprecatedTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/DeprecatedTraitTest.java @@ -23,9 +23,9 @@ public void loadsTraitWithString() { Node node = Node.objectNode(); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#deprecated"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#deprecated"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); @@ -46,8 +46,8 @@ public void validatesInput() { public void returnDefaultDescription() { DeprecatedTrait deprecatedTrait = DeprecatedTrait.builder().build(); assertThat( - deprecatedTrait.getDeprecatedDescription(ShapeType.OPERATION), - equalTo("This operation is deprecated.") + deprecatedTrait.getDeprecatedDescription(ShapeType.OPERATION), + equalTo("This operation is deprecated.") ); assertThat(deprecatedTrait.getDeprecatedDescription(ShapeType.STRING), equalTo("This shape is deprecated.")); } @@ -56,8 +56,8 @@ public void returnDefaultDescription() { public void returnDescriptionWhenMessageSet() { DeprecatedTrait deprecatedTrait = DeprecatedTrait.builder().message("Use X shape instead.").build(); assertThat( - deprecatedTrait.getDeprecatedDescription(ShapeType.STRING), - equalTo("This shape is deprecated: Use X shape instead.") + deprecatedTrait.getDeprecatedDescription(ShapeType.STRING), + equalTo("This shape is deprecated: Use X shape instead.") ); } @@ -65,20 +65,20 @@ public void returnDescriptionWhenMessageSet() { public void returnDescriptionWhenSinceSet() { DeprecatedTrait deprecatedTrait = DeprecatedTrait.builder().since("2020-01-01").build(); assertThat( - deprecatedTrait.getDeprecatedDescription(ShapeType.STRING), - equalTo("This shape is deprecated since 2020-01-01.") + deprecatedTrait.getDeprecatedDescription(ShapeType.STRING), + equalTo("This shape is deprecated since 2020-01-01.") ); } @Test public void returnDescriptionWhenBothSinceAndMessageSet() { DeprecatedTrait deprecatedTrait = DeprecatedTrait.builder() - .since("2020-01-01") - .message("Use X shape instead.") - .build(); + .since("2020-01-01") + .message("Use X shape instead.") + .build(); assertThat( - deprecatedTrait.getDeprecatedDescription(ShapeType.STRING), - equalTo("This shape is deprecated since 2020-01-01: Use X shape instead.") + deprecatedTrait.getDeprecatedDescription(ShapeType.STRING), + equalTo("This shape is deprecated since 2020-01-01: Use X shape instead.") ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/DocumentationTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/DocumentationTraitTest.java index adf4c0bd175..1589122af7b 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/DocumentationTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/DocumentationTraitTest.java @@ -20,9 +20,9 @@ public void loadsTraitWithString() { Node node = Node.from("Text"); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#documentation"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#documentation"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/EffectiveTraitQueryTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/EffectiveTraitQueryTest.java index cf7bcb8311d..96abacb1b55 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/EffectiveTraitQueryTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/EffectiveTraitQueryTest.java @@ -18,16 +18,16 @@ public class EffectiveTraitQueryTest { @Test public void detectsTraitOnShape() { Shape stringShape = StringShape.builder() - .id("foo.bar#Baz") - .addTrait(new SensitiveTrait()) - .build(); + .id("foo.bar#Baz") + .addTrait(new SensitiveTrait()) + .build(); Model model = Model.builder() - .addShapes(stringShape) - .build(); + .addShapes(stringShape) + .build(); EffectiveTraitQuery query = EffectiveTraitQuery.builder() - .model(model) - .traitClass(SensitiveTrait.class) - .build(); + .model(model) + .traitClass(SensitiveTrait.class) + .build(); assertTrue(query.isTraitApplied(stringShape)); } @@ -35,17 +35,17 @@ public void detectsTraitOnShape() { @Test public void detectsTraitOnMemberTarget() { Shape stringShape = StringShape.builder() - .id("foo.bar#Baz") - .addTrait(new SensitiveTrait()) - .build(); + .id("foo.bar#Baz") + .addTrait(new SensitiveTrait()) + .build(); ListShape list = ListShape.builder().id("foo.bar#List").member(stringShape.getId()).build(); Model model = Model.builder() - .addShapes(stringShape, list) - .build(); + .addShapes(stringShape, list) + .build(); EffectiveTraitQuery query = EffectiveTraitQuery.builder() - .model(model) - .traitClass(SensitiveTrait.class) - .build(); + .model(model) + .traitClass(SensitiveTrait.class) + .build(); assertTrue(query.isTraitApplied(list.getMember())); } @@ -54,21 +54,21 @@ public void detectsTraitOnMemberTarget() { public void ignoresTraitOnMemberContainerByDefault() { Shape stringShape = StringShape.builder().id("foo.bar#Baz").build(); MemberShape member = MemberShape.builder() - .id("foo.baz#Container$member") - .target(stringShape) - .build(); + .id("foo.baz#Container$member") + .target(stringShape) + .build(); ListShape list = ListShape.builder() - .id("foo.baz#Container") - .member(member) - .addTrait(new SensitiveTrait()) - .build(); + .id("foo.baz#Container") + .member(member) + .addTrait(new SensitiveTrait()) + .build(); Model model = Model.builder() - .addShapes(stringShape, member, list) - .build(); + .addShapes(stringShape, member, list) + .build(); EffectiveTraitQuery query = EffectiveTraitQuery.builder() - .model(model) - .traitClass(SensitiveTrait.class) - .build(); + .model(model) + .traitClass(SensitiveTrait.class) + .build(); assertFalse(query.isTraitApplied(member)); } @@ -77,22 +77,22 @@ public void ignoresTraitOnMemberContainerByDefault() { public void detectsTraitOnMemberContainer() { Shape stringShape = StringShape.builder().id("foo.bar#Baz").build(); MemberShape member = MemberShape.builder() - .id("foo.baz#Container$member") - .target(stringShape) - .build(); + .id("foo.baz#Container$member") + .target(stringShape) + .build(); ListShape list = ListShape.builder() - .id("foo.baz#Container") - .member(member) - .addTrait(new SensitiveTrait()) - .build(); + .id("foo.baz#Container") + .member(member) + .addTrait(new SensitiveTrait()) + .build(); Model model = Model.builder() - .addShapes(stringShape, member, list) - .build(); + .addShapes(stringShape, member, list) + .build(); EffectiveTraitQuery query = EffectiveTraitQuery.builder() - .model(model) - .traitClass(SensitiveTrait.class) - .inheritFromContainer(true) - .build(); + .model(model) + .traitClass(SensitiveTrait.class) + .inheritFromContainer(true) + .build(); assertTrue(query.isTraitApplied(member)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/EndpointTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/EndpointTraitTest.java index 933afb62665..6fce97e2965 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/EndpointTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/EndpointTraitTest.java @@ -23,11 +23,11 @@ public class EndpointTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); ObjectNode node = Node.objectNode() - .withMember("hostPrefix", Node.from("foo.baz-")); + .withMember("hostPrefix", Node.from("foo.baz-")); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#endpoint"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#endpoint"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(EndpointTrait.class)); @@ -42,8 +42,8 @@ public void loadsTrait() { public void literalsMustNotContainAdjacentLabels() { Throwable thrown = Assertions.assertThrows(InvalidPatternException.class, () -> { EndpointTrait.builder() - .hostPrefix("foo-{baz}{bar}") - .build(); + .hostPrefix("foo-{baz}{bar}") + .build(); }); assertThat(thrown.getMessage(), containsString("Host labels must not be adjacent")); @@ -53,8 +53,8 @@ public void literalsMustNotContainAdjacentLabels() { public void literalsMustNotContainOpenBrace() { Throwable thrown = Assertions.assertThrows(InvalidPatternException.class, () -> { EndpointTrait.builder() - .hostPrefix("foo-{baz") - .build(); + .hostPrefix("foo-{baz") + .build(); }); assertThat(thrown.getMessage(), containsString("Unclosed label found in pattern")); @@ -64,8 +64,8 @@ public void literalsMustNotContainOpenBrace() { public void literalsMustNotContainTrailingOpenBrace() { Throwable thrown = Assertions.assertThrows(InvalidPatternException.class, () -> { EndpointTrait.builder() - .hostPrefix("foo-{") - .build(); + .hostPrefix("foo-{") + .build(); }); assertThat(thrown.getMessage(), containsString("Unclosed label found in pattern")); @@ -75,8 +75,8 @@ public void literalsMustNotContainTrailingOpenBrace() { public void literalsMustNotContainCloseBrace() { Throwable thrown = Assertions.assertThrows(InvalidPatternException.class, () -> { EndpointTrait.builder() - .hostPrefix("foo-}baz") - .build(); + .hostPrefix("foo-}baz") + .build(); }); assertThat(thrown.getMessage(), containsString("Literal segments must not contain `}`")); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/EnumTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/EnumTraitTest.java index 62facdb6d9e..7631bec9f83 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/EnumTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/EnumTraitTest.java @@ -19,9 +19,9 @@ public class EnumTraitTest { @Test public void loadsTrait() { Node node = Node.parse( - "[{\"value\": \"foo\"}, " - + "{\"value\": \"bam\"}, " - + "{\"value\": \"boozled\"}]" + "[{\"value\": \"foo\"}, " + + "{\"value\": \"bam\"}, " + + "{\"value\": \"boozled\"}]" ); EnumTrait trait = new EnumTrait.Provider().createTrait(ShapeId.from("ns.foo#baz"), node); @@ -41,8 +41,8 @@ public void expectsAtLeastOneConstant() { @Test public void checksIfAllDefineNames() { Node node = Node.parse( - "[{\"value\": \"foo\", \"name\": \"FOO\"}, " - + "{\"value\": \"bam\", \"name\": \"BAM\"}]" + "[{\"value\": \"foo\", \"name\": \"FOO\"}, " + + "{\"value\": \"bam\", \"name\": \"BAM\"}]" ); EnumTrait trait = new EnumTrait.Provider().createTrait(ShapeId.from("ns.foo#baz"), node); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/ExamplesTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/ExamplesTraitTest.java index 7603edbb66b..9aebbbec858 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/ExamplesTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/ExamplesTraitTest.java @@ -25,26 +25,29 @@ public class ExamplesTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); ArrayNode node = Node.arrayNode( - Node.objectNode() - .withMember("title", Node.from("foo")), - Node.objectNode() - .withMember("title", Node.from("qux")) - .withMember("documentation", Node.from("docs")) - .withMember("input", Node.objectNode().withMember("a", Node.from("b"))) - .withMember("output", Node.objectNode().withMember("c", Node.from("d"))) - .withMember( - "error", - Node.objectNode() - .withMember(Node.from("shapeId"), Node.from("smithy.example#FooError")) - .withMember(Node.from("content"), Node.objectNode().withMember("e", Node.from("f"))) - ) - .withMember("allowConstraintErrors", Node.from(true)) + Node.objectNode() + .withMember("title", Node.from("foo")), + Node.objectNode() + .withMember("title", Node.from("qux")) + .withMember("documentation", Node.from("docs")) + .withMember("input", Node.objectNode().withMember("a", Node.from("b"))) + .withMember("output", Node.objectNode().withMember("c", Node.from("d"))) + .withMember( + "error", + Node.objectNode() + .withMember(Node.from("shapeId"), Node.from("smithy.example#FooError")) + .withMember( + Node.from("content"), + Node.objectNode().withMember("e", Node.from("f")) + ) + ) + .withMember("allowConstraintErrors", Node.from(true)) ); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#examples"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#examples"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(ExamplesTrait.class)); @@ -58,25 +61,25 @@ public void loadsTrait() { public void omitsAllowConstraintErrorsFromSerializedNodeWhenNotTrue() { TraitFactory provider = TraitFactory.createServiceFactory(); ArrayNode node = Node.arrayNode( - Node.objectNode() - .withMember("title", Node.from("foo")), - Node.objectNode() - .withMember("title", Node.from("qux")) - .withMember("documentation", Node.from("docs")) - .withMember("input", Node.objectNode().withMember("a", Node.from("b"))) - .withMember("output", Node.objectNode().withMember("c", Node.from("d"))) - .withMember("allowConstraintErrors", Node.from(false)), - Node.objectNode() - .withMember("title", Node.from("qux")) - .withMember("documentation", Node.from("docs")) - .withMember("input", Node.objectNode().withMember("a", Node.from("b"))) - .withMember("output", Node.objectNode().withMember("c", Node.from("d"))) - .withMember("allowConstraintErrors", Node.from(true)) + Node.objectNode() + .withMember("title", Node.from("foo")), + Node.objectNode() + .withMember("title", Node.from("qux")) + .withMember("documentation", Node.from("docs")) + .withMember("input", Node.objectNode().withMember("a", Node.from("b"))) + .withMember("output", Node.objectNode().withMember("c", Node.from("d"))) + .withMember("allowConstraintErrors", Node.from(false)), + Node.objectNode() + .withMember("title", Node.from("qux")) + .withMember("documentation", Node.from("docs")) + .withMember("input", Node.objectNode().withMember("a", Node.from("b"))) + .withMember("output", Node.objectNode().withMember("c", Node.from("d"))) + .withMember("allowConstraintErrors", Node.from(true)) ); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#examples"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#examples"), + ShapeId.from("ns.qux#foo"), + node ); ArrayNode serialized = ((ExamplesTrait) trait.get()).createNode().expectArrayNode(); @@ -90,47 +93,47 @@ public void exampleEqualsWorks() { ObjectNode input = Node.objectNode().withMember("a", Node.from("b")); ObjectNode output = Node.objectNode().withMember("c", Node.from("d")); ErrorExample errorExample1 = ErrorExample.builder() - .shapeId(ShapeId.from("smithy.example#FooError")) - .content( - Node.objectNode() - .withMember("e", Node.from("f")) - ) - .build(); + .shapeId(ShapeId.from("smithy.example#FooError")) + .content( + Node.objectNode() + .withMember("e", Node.from("f")) + ) + .build(); ErrorExample errorExample2 = ErrorExample.builder() - .shapeId(ShapeId.from("smithy.example#FooError")) - .content( - Node.objectNode() - .withMember("e", Node.from("f")) - ) - .build(); + .shapeId(ShapeId.from("smithy.example#FooError")) + .content( + Node.objectNode() + .withMember("e", Node.from("f")) + ) + .build(); ErrorExample errorExample3 = ErrorExample.builder() - .shapeId(ShapeId.from("smithy.example#FooError")) - .content( - Node.objectNode() - .withMember("g", Node.from("h")) - ) - .build(); + .shapeId(ShapeId.from("smithy.example#FooError")) + .content( + Node.objectNode() + .withMember("g", Node.from("h")) + ) + .build(); Example example1 = Example.builder() - .title("foo") - .documentation("docs") - .input(input) - .output(output) - .error(errorExample1) - .build(); + .title("foo") + .documentation("docs") + .input(input) + .output(output) + .error(errorExample1) + .build(); Example example2 = Example.builder() - .title("foo") - .documentation("docs") - .input(input) - .output(output) - .error(errorExample2) - .build(); + .title("foo") + .documentation("docs") + .input(input) + .output(output) + .error(errorExample2) + .build(); Example example3 = Example.builder() - .title("foo") - .documentation("docs") - .input(input) - .output(output) - .error(errorExample3) - .build(); + .title("foo") + .documentation("docs") + .input(input) + .output(output) + .error(errorExample3) + .build(); assertThat(errorExample1, equalTo(errorExample2)); assertThat(errorExample1, not(equalTo(errorExample3))); assertThat(example1, equalTo(example2)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/ExternalDocumentationTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/ExternalDocumentationTraitTest.java index ecc6bd9d051..45b93b7352d 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/ExternalDocumentationTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/ExternalDocumentationTraitTest.java @@ -18,11 +18,11 @@ public class ExternalDocumentationTraitTest { @Test public void loadsTrait() { Node node = Node.parse( - "{\"API Reference\": \"https://foo.bar/api\"," - + "\"Usage Guide\": \"https://foo.bar/guide\"}" + "{\"API Reference\": \"https://foo.bar/api\"," + + "\"Usage Guide\": \"https://foo.bar/guide\"}" ); ExternalDocumentationTrait trait = new ExternalDocumentationTrait.Provider() - .createTrait(ShapeId.from("ns.foo#baz"), node); + .createTrait(ShapeId.from("ns.foo#baz"), node); assertThat(trait.toNode(), equalTo(node)); assertThat(trait.toBuilder().build(), equalTo(trait)); @@ -37,9 +37,9 @@ public void expectsValidUrls() { Assertions.assertThrows(SourceException.class, () -> { TraitFactory provider = TraitFactory.createServiceFactory(); provider.createTrait( - ShapeId.from("smithy.api#externalDocumentation"), - ShapeId.from("ns.qux#foo"), - Node.parse("{\"API Reference\": \"foobarapi\"") + ShapeId.from("smithy.api#externalDocumentation"), + ShapeId.from("ns.qux#foo"), + Node.parse("{\"API Reference\": \"foobarapi\"") ); }); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/HttpApiKeyAuthTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/HttpApiKeyAuthTraitTest.java index 43f5cefd21e..c8ffd282379 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/HttpApiKeyAuthTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/HttpApiKeyAuthTraitTest.java @@ -21,12 +21,12 @@ public class HttpApiKeyAuthTraitTest { public void loadsTraitWithHeader() { TraitFactory provider = TraitFactory.createServiceFactory(); ObjectNode node = Node.objectNode() - .withMember("name", "X-Foo") - .withMember("in", "header"); + .withMember("name", "X-Foo") + .withMember("in", "header"); Optional trait = provider.createTrait( - HttpApiKeyAuthTrait.ID, - ShapeId.from("ns.qux#foo"), - node + HttpApiKeyAuthTrait.ID, + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(HttpApiKeyAuthTrait.class)); @@ -43,12 +43,12 @@ public void loadsTraitWithHeader() { public void loadsTraitWithQuery() { TraitFactory provider = TraitFactory.createServiceFactory(); ObjectNode node = Node.objectNode() - .withMember("name", "blerg") - .withMember("in", "query"); + .withMember("name", "blerg") + .withMember("in", "query"); Optional trait = provider.createTrait( - HttpApiKeyAuthTrait.ID, - ShapeId.from("ns.qux#foo"), - node + HttpApiKeyAuthTrait.ID, + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(HttpApiKeyAuthTrait.class)); @@ -65,13 +65,13 @@ public void loadsTraitWithQuery() { public void loadsTraitWithHeaderAndScheme() { TraitFactory provider = TraitFactory.createServiceFactory(); ObjectNode node = Node.objectNode() - .withMember("scheme", "fenty") - .withMember("name", "X-Foo") - .withMember("in", "header"); + .withMember("scheme", "fenty") + .withMember("name", "X-Foo") + .withMember("in", "header"); Optional trait = provider.createTrait( - HttpApiKeyAuthTrait.ID, - ShapeId.from("ns.qux#foo"), - node + HttpApiKeyAuthTrait.ID, + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(HttpApiKeyAuthTrait.class)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/HttpResponseCodeTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/HttpResponseCodeTraitTest.java index 5fa7e8bf0a7..28e7f4e9ca4 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/HttpResponseCodeTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/HttpResponseCodeTraitTest.java @@ -19,9 +19,9 @@ public class HttpResponseCodeTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#httpResponseCode"), - ShapeId.from("ns.qux#Foo$bar"), - Node.objectNode() + ShapeId.from("smithy.api#httpResponseCode"), + ShapeId.from("ns.qux#Foo$bar"), + Node.objectNode() ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/HttpTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/HttpTraitTest.java index e71289ce740..fe48cc8b275 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/HttpTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/HttpTraitTest.java @@ -20,13 +20,13 @@ public class HttpTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); ObjectNode node = Node.objectNode() - .withMember("method", Node.from("PUT")) - .withMember("uri", Node.from("/foo.baz")) - .withMember("code", Node.from(200)); + .withMember("method", Node.from("PUT")) + .withMember("uri", Node.from("/foo.baz")) + .withMember("code", Node.from(200)); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#http"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#http"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(HttpTrait.class)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/IdRefTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/IdRefTraitTest.java index 2517c778502..565e217e6d3 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/IdRefTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/IdRefTraitTest.java @@ -21,13 +21,13 @@ public class IdRefTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); ObjectNode node = Node.objectNode() - .withMember("selector", Node.from("integer")) - .withMember("failWhenMissing", Node.from(true)) - .withMember("errorMessage", Node.from("foo")); + .withMember("selector", Node.from("integer")) + .withMember("failWhenMissing", Node.from(true)) + .withMember("errorMessage", Node.from("foo")); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#idRef"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#idRef"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(IdRefTrait.class)); @@ -38,9 +38,9 @@ public void loadsTrait() { assertThat(idRef.failWhenMissing(), is(true)); assertThat(idRef.toBuilder().build(), equalTo(idRef)); Trait duplicateTrait = provider.createTrait( - ShapeId.from("smithy.api#idRef"), - ShapeId.from("ns.qux#foo"), - idRef.toNode() + ShapeId.from("smithy.api#idRef"), + ShapeId.from("ns.qux#foo"), + idRef.toNode() ).get(); assertThat(duplicateTrait, equalTo(idRef)); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/IdempotencyTokenTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/IdempotencyTokenTraitTest.java index 369e8fbafde..399537ca946 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/IdempotencyTokenTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/IdempotencyTokenTraitTest.java @@ -19,9 +19,9 @@ public class IdempotencyTokenTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#idempotencyToken"), - ShapeId.from("ns.qux#foo"), - Node.objectNode() + ShapeId.from("smithy.api#idempotencyToken"), + ShapeId.from("ns.qux#foo"), + Node.objectNode() ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/InputTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/InputTraitTest.java index 0cccc592b3b..5c172e96734 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/InputTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/InputTraitTest.java @@ -20,9 +20,9 @@ public class InputTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#input"), - ShapeId.from("ns.qux#foo"), - Node.objectNode() + ShapeId.from("smithy.api#input"), + ShapeId.from("ns.qux#foo"), + Node.objectNode() ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/InternalTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/InternalTraitTest.java index 2977b3055ee..b7aef830d2e 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/InternalTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/InternalTraitTest.java @@ -20,9 +20,9 @@ public class InternalTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#internal"), - ShapeId.from("ns.qux#foo"), - Node.objectNode() + ShapeId.from("smithy.api#internal"), + ShapeId.from("ns.qux#foo"), + Node.objectNode() ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/LengthTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/LengthTraitTest.java index 5fde157b767..ba78eba4a7d 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/LengthTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/LengthTraitTest.java @@ -28,9 +28,9 @@ public void loadsTrait() { values.put(Node.from("max"), Node.from(10L)); Node node = Node.objectNode(values); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#length"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#length"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); @@ -51,9 +51,9 @@ public void requiresOneOfMinOrMax() { Map values = new HashMap<>(); provider.createTrait( - ShapeId.from("smithy.api#length"), - ShapeId.from("ns.qux#foo"), - Node.objectNode(values) + ShapeId.from("smithy.api#length"), + ShapeId.from("ns.qux#foo"), + Node.objectNode(values) ); }); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/MediaTypeTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/MediaTypeTraitTest.java index de30ce12b83..fc1e284db16 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/MediaTypeTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/MediaTypeTraitTest.java @@ -21,9 +21,9 @@ public void loadsTrait() { Node node = Node.from("application/json"); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#mediaType"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#mediaType"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/MixinTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/MixinTraitTest.java index 03de99b8e56..27b4ef709c7 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/MixinTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/MixinTraitTest.java @@ -24,9 +24,9 @@ public void loadsEmptyTrait() { Node node = Node.objectNode(); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#mixin"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#mixin"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/NestedPropertiesTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/NestedPropertiesTraitTest.java index 15c117f11a6..679d2c2b2de 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/NestedPropertiesTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/NestedPropertiesTraitTest.java @@ -19,9 +19,9 @@ public class NestedPropertiesTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#nestedProperties"), - ShapeId.from("ns.qux#foo"), - Node.objectNode() + ShapeId.from("smithy.api#nestedProperties"), + ShapeId.from("ns.qux#foo"), + Node.objectNode() ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/NotPropertyTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/NotPropertyTraitTest.java index 77fb4643094..cbd19c3c6e4 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/NotPropertyTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/NotPropertyTraitTest.java @@ -20,9 +20,9 @@ public class NotPropertyTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#notProperty"), - ShapeId.from("ns.qux#foo"), - Node.objectNode() + ShapeId.from("smithy.api#notProperty"), + ShapeId.from("ns.qux#foo"), + Node.objectNode() ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/OutputTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/OutputTraitTest.java index a435d9ee9a5..d2b99b8a2b8 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/OutputTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/OutputTraitTest.java @@ -20,9 +20,9 @@ public class OutputTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#output"), - ShapeId.from("ns.qux#foo"), - Node.objectNode() + ShapeId.from("smithy.api#output"), + ShapeId.from("ns.qux#foo"), + Node.objectNode() ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/PaginatedTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/PaginatedTraitTest.java index 2c38423a9e5..24c56f98169 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/PaginatedTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/PaginatedTraitTest.java @@ -18,10 +18,10 @@ public class PaginatedTraitTest { @Test public void doesNotRequireItems() { PaginatedTrait t = new PaginatedTrait.Provider().createTrait( - ShapeId.from("ns.qux#foo"), - Node.objectNode() - .withMember("inputToken", Node.from("inputToken")) - .withMember("outputToken", Node.from("outputToken")) + ShapeId.from("ns.qux#foo"), + Node.objectNode() + .withMember("inputToken", Node.from("inputToken")) + .withMember("outputToken", Node.from("outputToken")) ); assertThat(t.getItems(), equalTo(Optional.empty())); @@ -31,15 +31,15 @@ public void doesNotRequireItems() { public void loadsFullyConfiguredTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); Node node = Node.objectNode() - .withMember("items", Node.from("items")) - .withMember("inputToken", Node.from("inputToken")) - .withMember("outputToken", Node.from("outputToken")) - .withMember("pageSize", Node.from("pageSize")); + .withMember("items", Node.from("items")) + .withMember("inputToken", Node.from("inputToken")) + .withMember("outputToken", Node.from("outputToken")) + .withMember("pageSize", Node.from("pageSize")); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#paginated"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#paginated"), + ShapeId.from("ns.qux#foo"), + node ); assertThat(trait.isPresent(), is(true)); assertThat(trait.get(), instanceOf(PaginatedTrait.class)); @@ -57,15 +57,15 @@ public void allowsMissingPageSize() { TraitFactory provider = TraitFactory.createServiceFactory(); assertThat( - provider.createTrait( - ShapeId.from("smithy.api#paginated"), - ShapeId.from("ns.qux#foo"), - Node.objectNode() - .withMember("items", Node.from("items")) - .withMember("inputToken", Node.from("inputToken")) - .withMember("outputToken", Node.from("outputToken")) - ).isPresent(), - is(true) + provider.createTrait( + ShapeId.from("smithy.api#paginated"), + ShapeId.from("ns.qux#foo"), + Node.objectNode() + .withMember("items", Node.from("items")) + .withMember("inputToken", Node.from("inputToken")) + .withMember("outputToken", Node.from("outputToken")) + ).isPresent(), + is(true) ); } @@ -79,16 +79,16 @@ public void mergesWithNullReturnsSelf() { @Test public void mergesWithOtherTrait() { PaginatedTrait trait1 = PaginatedTrait.builder() - .inputToken("foo") - .items("baz") - .build(); + .inputToken("foo") + .items("baz") + .build(); PaginatedTrait trait2 = PaginatedTrait.builder() - .inputToken("foo2") - .outputToken("output") - .items("baz2") - .pageSize("bar") - .items("qux") - .build(); + .inputToken("foo2") + .outputToken("output") + .items("baz2") + .pageSize("bar") + .items("qux") + .build(); PaginatedTrait trait3 = trait1.merge(trait2); assertThat(trait3.getInputToken(), equalTo(Optional.of("foo"))); @@ -101,12 +101,12 @@ public void mergesWithOtherTrait() { public void allowsNestedOutputToken() { TraitFactory provider = TraitFactory.createServiceFactory(); Node node = Node.objectNode() - .withMember("inputToken", Node.from("inputToken")) - .withMember("outputToken", Node.from("result.outputToken")); + .withMember("inputToken", Node.from("inputToken")) + .withMember("outputToken", Node.from("result.outputToken")); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#paginated"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#paginated"), + ShapeId.from("ns.qux#foo"), + node ); assertThat(trait.isPresent(), is(true)); @@ -119,13 +119,13 @@ public void allowsNestedOutputToken() { public void allowsNestedOutputItems() { TraitFactory provider = TraitFactory.createServiceFactory(); Node node = Node.objectNode() - .withMember("items", Node.from("result.items")) - .withMember("inputToken", Node.from("inputToken")) - .withMember("outputToken", Node.from("outputToken")); + .withMember("items", Node.from("result.items")) + .withMember("inputToken", Node.from("inputToken")) + .withMember("outputToken", Node.from("outputToken")); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#paginated"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#paginated"), + ShapeId.from("ns.qux#foo"), + node ); assertThat(trait.isPresent(), is(true)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/PatternTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/PatternTraitTest.java index 4349e285f02..801af85f7e8 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/PatternTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/PatternTraitTest.java @@ -21,9 +21,9 @@ public void loadsTraitWithString() { Node node = Node.from("^[a-z]+$"); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#pattern"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#pattern"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/PropertyTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/PropertyTraitTest.java index 55a2ed17d84..4252f731c7e 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/PropertyTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/PropertyTraitTest.java @@ -28,9 +28,9 @@ public void loadsTrait() { values.put(Node.from("name"), Node.from("propertyName")); ObjectNode objectNode = Node.objectNode(values); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#property"), - ShapeId.from("ns.qux#foo"), - objectNode + ShapeId.from("smithy.api#property"), + ShapeId.from("ns.qux#foo"), + objectNode ); assertTrue(trait.isPresent()); @@ -50,9 +50,9 @@ public void loadsNoName() { Map values = new HashMap<>(); ObjectNode objectNode = Node.objectNode(values); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#property"), - ShapeId.from("ns.qux#foo"), - objectNode + ShapeId.from("smithy.api#property"), + ShapeId.from("ns.qux#foo"), + objectNode ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/ProtocolDefinitionTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/ProtocolDefinitionTraitTest.java index 725d08a5b0d..83416d7ef7e 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/ProtocolDefinitionTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/ProtocolDefinitionTraitTest.java @@ -21,25 +21,25 @@ public class ProtocolDefinitionTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); ArrayNode values = Node.fromStrings( - JsonNameTrait.ID.toString(), - XmlNameTrait.ID.toString() + JsonNameTrait.ID.toString(), + XmlNameTrait.ID.toString() ); Node node = Node.objectNode().withMember("traits", values); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#protocolDefinition"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#protocolDefinition"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(ProtocolDefinitionTrait.class)); ProtocolDefinitionTrait protocolDefinitionTrait = (ProtocolDefinitionTrait) trait.get(); assertThat( - protocolDefinitionTrait.getTraits(), - containsInAnyOrder( - JsonNameTrait.ID, - XmlNameTrait.ID - ) + protocolDefinitionTrait.getTraits(), + containsInAnyOrder( + JsonNameTrait.ID, + XmlNameTrait.ID + ) ); assertThat(protocolDefinitionTrait.toNode(), equalTo(node)); assertThat(protocolDefinitionTrait.toBuilder().build(), equalTo(protocolDefinitionTrait)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/RangeTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/RangeTraitTest.java index 67eb0f646f3..93868d79569 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/RangeTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/RangeTraitTest.java @@ -29,9 +29,9 @@ public void loadsTrait() { values.put(Node.from("max"), Node.from(10L)); Node node = Node.objectNode(values); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#range"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#range"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); @@ -53,9 +53,9 @@ public void loadsTraitFromNotation() { values.put(Node.from("max"), Node.from(10e0)); Node node = Node.objectNode(values); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#range"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#range"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/ReferencesTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/ReferencesTraitTest.java index 2f38a6a86fd..4c1121c3990 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/ReferencesTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/ReferencesTraitTest.java @@ -23,23 +23,23 @@ public void loadsTrait() { ShapeId id = ShapeId.from("ns.qux#foo"); TraitFactory provider = TraitFactory.createServiceFactory(); ArrayNode values = Node.arrayNode() - .withValue( - Node.objectNode() - .withMember("resource", Node.from("ns.qux#SomeShape")) - .withMember("ids", Node.parse("{\"a\": \"a\", \"b\": \"b\"}")) - ) - .withValue( - Node.objectNode() - .withMember("resource", Node.from("ns.foo#OtherShape")) - .withMember("ids", Node.parse("{\"c\": \"c\"}")) - .withMember("rel", Node.from("rel")) - ) - .withValue( - Node.objectNode() - .withMember("resource", Node.from("ns.foo#OtherShape")) - .withMember("ids", Node.parse("{\"c\": \"c\"}")) - .withMember("service", Node.from("com.foo#Baz")) - ); + .withValue( + Node.objectNode() + .withMember("resource", Node.from("ns.qux#SomeShape")) + .withMember("ids", Node.parse("{\"a\": \"a\", \"b\": \"b\"}")) + ) + .withValue( + Node.objectNode() + .withMember("resource", Node.from("ns.foo#OtherShape")) + .withMember("ids", Node.parse("{\"c\": \"c\"}")) + .withMember("rel", Node.from("rel")) + ) + .withValue( + Node.objectNode() + .withMember("resource", Node.from("ns.foo#OtherShape")) + .withMember("ids", Node.parse("{\"c\": \"c\"}")) + .withMember("service", Node.from("com.foo#Baz")) + ); Optional trait = provider.createTrait(ShapeId.from("smithy.api#references"), id, values); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(ReferencesTrait.class)); @@ -48,25 +48,25 @@ public void loadsTrait() { assertThat(referencesTrait.getReferences(), hasSize(3)); assertThat( - referencesTrait.getReferences().get(0).getResource(), - equalTo(ShapeId.from(id.getNamespace() + "#SomeShape")) + referencesTrait.getReferences().get(0).getResource(), + equalTo(ShapeId.from(id.getNamespace() + "#SomeShape")) ); assertThat(referencesTrait.getReferences().get(0).getIds(), hasKey("a")); assertThat(referencesTrait.getReferences().get(0).getIds(), hasKey("b")); assertThat( - referencesTrait.getReferences().get(1).getResource(), - equalTo(ShapeId.from("ns.foo#OtherShape")) + referencesTrait.getReferences().get(1).getResource(), + equalTo(ShapeId.from("ns.foo#OtherShape")) ); assertThat(referencesTrait.getReferences().get(1).getIds(), hasKey("c")); assertThat( - referencesTrait.getReferences().get(2).getResource(), - equalTo(ShapeId.from("ns.foo#OtherShape")) + referencesTrait.getReferences().get(2).getResource(), + equalTo(ShapeId.from("ns.foo#OtherShape")) ); assertThat( - referencesTrait.getReferences().get(2).getService(), - equalTo(Optional.of(ShapeId.from("com.foo#Baz"))) + referencesTrait.getReferences().get(2).getService(), + equalTo(Optional.of(ShapeId.from("com.foo#Baz"))) ); assertThat(referencesTrait.getReferences().get(2).getIds(), hasKey("c")); } @@ -75,23 +75,23 @@ public void loadsTrait() { public void convertsToNodeAndBuilder() { ShapeId id = ShapeId.from("ns.qux#foo"); ArrayNode values = Node.arrayNode() - .withValue( - Node.objectNode() - .withMember("resource", Node.from("ns.foo#SomeShape")) - .withMember("ids", Node.parse("{\"a\": \"a\", \"b\": \"b\"}")) - ) - .withValue( - Node.objectNode() - .withMember("resource", Node.from("ns.foo#OtherShape")) - .withMember("ids", Node.parse("{\"c\": \"c\"}")) - .withMember("rel", Node.from("rel")) - ) - .withValue( - Node.objectNode() - .withMember("resource", Node.from("ns.foo#OtherShape")) - .withMember("ids", Node.parse("{\"c\": \"c\"}")) - .withMember("service", Node.from("foo.baz#Bar")) - ); + .withValue( + Node.objectNode() + .withMember("resource", Node.from("ns.foo#SomeShape")) + .withMember("ids", Node.parse("{\"a\": \"a\", \"b\": \"b\"}")) + ) + .withValue( + Node.objectNode() + .withMember("resource", Node.from("ns.foo#OtherShape")) + .withMember("ids", Node.parse("{\"c\": \"c\"}")) + .withMember("rel", Node.from("rel")) + ) + .withValue( + Node.objectNode() + .withMember("resource", Node.from("ns.foo#OtherShape")) + .withMember("ids", Node.parse("{\"c\": \"c\"}")) + .withMember("service", Node.from("foo.baz#Bar")) + ); ReferencesTrait trait = new ReferencesTrait.Provider().createTrait(id, values); assertThat(trait.toNode(), equalTo(values)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/RequestCompressionTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/RequestCompressionTraitTest.java index 17444e943e6..e06ae4f53f4 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/RequestCompressionTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/RequestCompressionTraitTest.java @@ -21,13 +21,13 @@ public class RequestCompressionTraitTest { @Test public void loadsTrait() { Node node = ObjectNode.builder() - .withMember("encodings", ArrayNode.fromStrings("gzip")) - .build(); + .withMember("encodings", ArrayNode.fromStrings("gzip")) + .build(); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#requestCompression"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#requestCompression"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/RetryableTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/RetryableTraitTest.java index 9597136c579..b98ffce29a4 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/RetryableTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/RetryableTraitTest.java @@ -23,9 +23,9 @@ public void loadsTraitWithDefault() { SourceLocation sourceLocation = new SourceLocation("fileA"); Node node = Node.objectNodeBuilder().sourceLocation(sourceLocation).build(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#retryable"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#retryable"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); @@ -44,9 +44,9 @@ public void loadsTraitWithThrottling() { TraitFactory provider = TraitFactory.createServiceFactory(); Node node = Node.objectNodeBuilder().withMember("throttling", true).build(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#retryable"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#retryable"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/SensitiveTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/SensitiveTraitTest.java index a8765fb20fc..629991842eb 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/SensitiveTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/SensitiveTraitTest.java @@ -19,9 +19,9 @@ public class SensitiveTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#sensitive"), - ShapeId.from("ns.qux#foo"), - Node.objectNode() + ShapeId.from("smithy.api#sensitive"), + ShapeId.from("ns.qux#foo"), + Node.objectNode() ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/ServiceProviderTraitFactoryTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/ServiceProviderTraitFactoryTest.java index 60ea4ec458c..dd1acf7361e 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/ServiceProviderTraitFactoryTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/ServiceProviderTraitFactoryTest.java @@ -19,9 +19,9 @@ public class ServiceProviderTraitFactoryTest { public void createsTraitsUsingServiceLoader() { TraitFactory factory = TraitFactory.createServiceFactory(); Optional maybeTrait = factory.createTrait( - ShapeId.from("smithy.api#jsonName"), - ShapeId.from("ns.qux#foo"), - Node.from("hi") + ShapeId.from("smithy.api#jsonName"), + ShapeId.from("ns.qux#foo"), + Node.from("hi") ); assertTrue(maybeTrait.isPresent()); @@ -32,9 +32,9 @@ public void createsTraitsUsingServiceLoader() { public void returnsEmptyWhenNoMatchingTraitIsFound() { TraitFactory factory = TraitFactory.createServiceFactory(); Optional maybeTrait = factory.createTrait( - ShapeId.from("missing.baz#foo"), - ShapeId.from("ns.qux#foo"), - Node.nullNode() + ShapeId.from("missing.baz#foo"), + ShapeId.from("ns.qux#foo"), + Node.nullNode() ); assertFalse(maybeTrait.isPresent()); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/SinceTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/SinceTraitTest.java index ead079081ca..706fea811a0 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/SinceTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/SinceTraitTest.java @@ -20,9 +20,9 @@ public void loadsTraitWithString() { Node node = Node.from("Version"); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#since"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#since"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/StreamingTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/StreamingTraitTest.java index 39d6df5088e..6e512e6f69c 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/StreamingTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/StreamingTraitTest.java @@ -19,9 +19,9 @@ public class StreamingTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#streaming"), - ShapeId.from("ns.qux#foo"), - Node.objectNode() + ShapeId.from("smithy.api#streaming"), + ShapeId.from("ns.qux#foo"), + Node.objectNode() ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/TimestampFormatTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/TimestampFormatTraitTest.java index 1626683f2eb..464a8ba04f0 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/TimestampFormatTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/TimestampFormatTraitTest.java @@ -13,28 +13,28 @@ public class TimestampFormatTraitTest { @Test public void createsFromString() { assertThat( - TimestampFormatTrait.Format.fromString("date-time"), - equalTo(TimestampFormatTrait.Format.DATE_TIME) + TimestampFormatTrait.Format.fromString("date-time"), + equalTo(TimestampFormatTrait.Format.DATE_TIME) ); assertThat( - TimestampFormatTrait.Format.fromString("http-date"), - equalTo(TimestampFormatTrait.Format.HTTP_DATE) + TimestampFormatTrait.Format.fromString("http-date"), + equalTo(TimestampFormatTrait.Format.HTTP_DATE) ); assertThat( - TimestampFormatTrait.Format.fromString("epoch-seconds"), - equalTo(TimestampFormatTrait.Format.EPOCH_SECONDS) + TimestampFormatTrait.Format.fromString("epoch-seconds"), + equalTo(TimestampFormatTrait.Format.EPOCH_SECONDS) ); assertThat( - TimestampFormatTrait.Format.fromString("foo-baz"), - equalTo(TimestampFormatTrait.Format.UNKNOWN) + TimestampFormatTrait.Format.fromString("foo-baz"), + equalTo(TimestampFormatTrait.Format.UNKNOWN) ); } @Test public void convertsFormatToString() { assertThat( - TimestampFormatTrait.Format.fromString("date-time").toString(), - equalTo("date-time") + TimestampFormatTrait.Format.fromString("date-time").toString(), + equalTo("date-time") ); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/TitleTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/TitleTraitTest.java index 26856179315..8c97b8c1a2f 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/TitleTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/TitleTraitTest.java @@ -20,9 +20,9 @@ public void loadsTraitWithString() { Node node = Node.from("Title"); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#title"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#title"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/TraitDefinitionTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/TraitDefinitionTest.java index c30d9ce4b00..59d56058fc8 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/TraitDefinitionTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/TraitDefinitionTest.java @@ -24,10 +24,10 @@ public void hasGetters() { @Test public void isomorphicBuilder() { TraitDefinition trait = TraitDefinition.builder() - .selector(Selector.parse("string")) - .addConflict("com.foo#baz") - .structurallyExclusive(TraitDefinition.StructurallyExclusive.MEMBER) - .build(); + .selector(Selector.parse("string")) + .addConflict("com.foo#baz") + .structurallyExclusive(TraitDefinition.StructurallyExclusive.MEMBER) + .build(); assertThat(trait.toBuilder().build(), equalTo(trait)); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/TraitFactoryTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/TraitFactoryTest.java index e3d27d2e205..3162219a932 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/TraitFactoryTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/TraitFactoryTest.java @@ -16,8 +16,8 @@ public class TraitFactoryTest { public void returnsEmptyIfNoCustomTraitDefined() { TraitFactory factory = TraitFactory.createServiceFactory(ListUtils.of()); assertFalse( - factory.createTrait(ShapeId.from("ns.foo#baz"), ShapeId.from("ns.qux#foo"), Node.objectNode()) - .isPresent() + factory.createTrait(ShapeId.from("ns.foo#baz"), ShapeId.from("ns.qux#foo"), Node.objectNode()) + .isPresent() ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/TraitValidatorsTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/TraitValidatorsTest.java index d642ed7ba0c..f2acce35db6 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/TraitValidatorsTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/TraitValidatorsTest.java @@ -18,17 +18,17 @@ public class TraitValidatorsTest { public void convertsToNode() { SourceLocation s = new SourceLocation("foo.xml"); TraitValidatorsTrait trait1 = TraitValidatorsTrait.builder() - .sourceLocation(s) - .putValidator("hi", new TraitValidatorsTrait.Validator(Selector.parse("*"), "Error!")) - .putValidator( - "hi", - new TraitValidatorsTrait.Validator( - Selector.parse("string"), - "Warning!", - Severity.WARNING + .sourceLocation(s) + .putValidator("hi", new TraitValidatorsTrait.Validator(Selector.parse("*"), "Error!")) + .putValidator( + "hi", + new TraitValidatorsTrait.Validator( + Selector.parse("string"), + "Warning!", + Severity.WARNING + ) ) - ) - .build(); + .build(); TraitValidatorsTrait.Provider p = new TraitValidatorsTrait.Provider(); @@ -39,16 +39,16 @@ public void convertsToNode() { public void convertsToBuilder() { SourceLocation s = new SourceLocation("foo.xml"); TraitValidatorsTrait trait1 = TraitValidatorsTrait.builder() - .sourceLocation(s) - .putValidator( - "hi", - new TraitValidatorsTrait.Validator( - Selector.parse("*"), - "Error!", - Severity.DANGER + .sourceLocation(s) + .putValidator( + "hi", + new TraitValidatorsTrait.Validator( + Selector.parse("*"), + "Error!", + Severity.DANGER + ) ) - ) - .build(); + .build(); assertThat(trait1.toBuilder().build(), equalTo(trait1)); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/UniqueItemsTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/UniqueItemsTraitTest.java index 8186e1553b0..f67704dd3dd 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/UniqueItemsTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/UniqueItemsTraitTest.java @@ -20,9 +20,9 @@ public class UniqueItemsTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#uniqueItems"), - ShapeId.from("ns.qux#foo"), - Node.objectNode() + ShapeId.from("smithy.api#uniqueItems"), + ShapeId.from("ns.qux#foo"), + Node.objectNode() ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/UnstableTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/UnstableTraitTest.java index 33a7882d26b..68c12e70c8b 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/UnstableTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/UnstableTraitTest.java @@ -19,9 +19,9 @@ public class UnstableTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#unstable"), - ShapeId.from("ns.qux#foo"), - Node.objectNode() + ShapeId.from("smithy.api#unstable"), + ShapeId.from("ns.qux#foo"), + Node.objectNode() ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/XmlAttributeTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/XmlAttributeTraitTest.java index dc406695654..b624eb3c979 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/XmlAttributeTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/XmlAttributeTraitTest.java @@ -22,9 +22,9 @@ public void loadsTraitWithString() { Node node = Node.objectNode(); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#xmlAttribute"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#xmlAttribute"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/XmlNameTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/XmlNameTraitTest.java index 6fecc449581..e3a27b1f0ad 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/XmlNameTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/XmlNameTraitTest.java @@ -20,9 +20,9 @@ public void loadsTraitWithString() { Node node = Node.from("Text"); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#xmlName"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#xmlName"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); @@ -37,9 +37,9 @@ public void loadsWithColonInValue() { Node node = Node.from("xsi:type"); TraitFactory provider = TraitFactory.createServiceFactory(); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#xmlName"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#xmlName"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/XmlNamespaceTraitTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/XmlNamespaceTraitTest.java index 4b25f106fa5..0c684843e71 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/XmlNamespaceTraitTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/XmlNamespaceTraitTest.java @@ -21,11 +21,11 @@ public class XmlNamespaceTraitTest { public void loadsTrait() { TraitFactory provider = TraitFactory.createServiceFactory(); ObjectNode node = Node.objectNode() - .withMember("uri", Node.from("https://www.amazon.com")); + .withMember("uri", Node.from("https://www.amazon.com")); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#xmlNamespace"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#xmlNamespace"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(XmlNamespaceTrait.class)); @@ -38,11 +38,11 @@ public void loadsTrait() { public void omitsEmptiesFromSerializedNode() { TraitFactory provider = TraitFactory.createServiceFactory(); ObjectNode node = Node.objectNode() - .withMember("uri", Node.from("https://www.amazon.com")); + .withMember("uri", Node.from("https://www.amazon.com")); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#xmlNamespace"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#xmlNamespace"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(XmlNamespaceTrait.class)); @@ -55,12 +55,12 @@ public void omitsEmptiesFromSerializedNode() { public void loadsTraitWithPrefix() { TraitFactory provider = TraitFactory.createServiceFactory(); ObjectNode node = Node.objectNode() - .withMember("uri", Node.from("https://www.amazon.com")) - .withMember("prefix", Node.from("xsi")); + .withMember("uri", Node.from("https://www.amazon.com")) + .withMember("prefix", Node.from("xsi")); Optional trait = provider.createTrait( - ShapeId.from("smithy.api#xmlNamespace"), - ShapeId.from("ns.qux#foo"), - node + ShapeId.from("smithy.api#xmlNamespace"), + ShapeId.from("ns.qux#foo"), + node ); assertTrue(trait.isPresent()); assertThat(trait.get(), instanceOf(XmlNamespaceTrait.class)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/AddClientOptionalTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/AddClientOptionalTest.java index 0b12edd1e77..2d5876002c2 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/AddClientOptionalTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/AddClientOptionalTest.java @@ -19,11 +19,11 @@ public class AddClientOptionalTest { @Test public void addsClientOptionalToInputStructures() { StructureShape structure = StructureShape.builder() - .id("smithy.example#Struct") - .addTrait(new InputTrait()) - .addMember("foo", ShapeId.from("smithy.api#String")) - .addMember("bar", ShapeId.from("smithy.api#String"), bar -> bar.addTrait(new RequiredTrait())) - .build(); + .id("smithy.example#Struct") + .addTrait(new InputTrait()) + .addMember("foo", ShapeId.from("smithy.api#String")) + .addMember("bar", ShapeId.from("smithy.api#String"), bar -> bar.addTrait(new RequiredTrait())) + .build(); Model model = Model.assembler().addShape(structure).assemble().unwrap(); Model model2 = ModelTransformer.create().addClientOptional(model, false); StructureShape struct2 = model2.expectShape(structure.getId(), StructureShape.class); @@ -35,10 +35,10 @@ public void addsClientOptionalToInputStructures() { @Test public void addsClientOptionalToImplicitNulls() { StructureShape structure = StructureShape.builder() - .id("smithy.example#Struct") - .addMember("foo", ShapeId.from("smithy.api#String")) - .addMember("bar", ShapeId.from("smithy.api#String"), bar -> bar.addTrait(new RequiredTrait())) - .build(); + .id("smithy.example#Struct") + .addMember("foo", ShapeId.from("smithy.api#String")) + .addMember("bar", ShapeId.from("smithy.api#String"), bar -> bar.addTrait(new RequiredTrait())) + .build(); Model model = Model.assembler().addShape(structure).assemble().unwrap(); Model model2 = ModelTransformer.create().addClientOptional(model, false); StructureShape struct2 = model2.expectShape(structure.getId(), StructureShape.class); @@ -51,11 +51,11 @@ public void addsClientOptionalToImplicitNulls() { public void addsClientOptionalWhenNoZeroValue() { StructureShape other = StructureShape.builder().id("smithy.example#Other").build(); StructureShape structure = StructureShape.builder() - .id("smithy.example#Struct") - .addMember("foo", ShapeId.from("smithy.api#String")) - .addMember("bar", ShapeId.from("smithy.api#String"), bar -> bar.addTrait(new RequiredTrait())) - .addMember("baz", other.getId(), bar -> bar.addTrait(new RequiredTrait())) - .build(); + .id("smithy.example#Struct") + .addMember("foo", ShapeId.from("smithy.api#String")) + .addMember("bar", ShapeId.from("smithy.api#String"), bar -> bar.addTrait(new RequiredTrait())) + .addMember("baz", other.getId(), bar -> bar.addTrait(new RequiredTrait())) + .build(); Model model = Model.assembler().addShapes(structure, other).assemble().unwrap(); Model model2 = ModelTransformer.create().addClientOptional(model, true); StructureShape struct2 = model2.expectShape(structure.getId(), StructureShape.class); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/ChangeShapeTypeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/ChangeShapeTypeTest.java index 1e99bf7abaf..5c1bf79c8c9 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/ChangeShapeTypeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/ChangeShapeTypeTest.java @@ -52,24 +52,24 @@ public void changesSimpleShapeTypes(ShapeType start, ShapeType dest, boolean suc Shape startShape; if (start == ShapeType.ENUM) { startShape = EnumShape.builder() - .id(id) - .addMember("FOO", "foo") - .addTrait(docTrait) - .source(source) - .build(); + .id(id) + .addMember("FOO", "foo") + .addTrait(docTrait) + .source(source) + .build(); } else if (start == ShapeType.INT_ENUM) { startShape = IntEnumShape.builder() - .id(id) - .addMember("FOO", 1) - .addTrait(docTrait) - .source(source) - .build(); + .id(id) + .addMember("FOO", 1) + .addTrait(docTrait) + .source(source) + .build(); } else { startShape = start.createBuilderForType() - .addTrait(docTrait) - .id(id) - .source(source) - .build(); + .addTrait(docTrait) + .id(id) + .source(source) + .build(); } Model model = Model.builder().addShape(startShape).build(); @@ -121,11 +121,11 @@ public void changesListToSet() { ShapeId id = ShapeId.from("smithy.example#Test"); SourceLocation source = new SourceLocation("/foo", 1, 1); Shape startShape = ListShape.builder() - .addTrait(docTrait) - .id(id) - .source(source) - .member(ShapeId.from("smithy.api#String")) - .build(); + .addTrait(docTrait) + .id(id) + .source(source) + .member(ShapeId.from("smithy.api#String")) + .build(); Model model = Model.assembler().addShape(startShape).assemble().unwrap(); Model result = ModelTransformer.create().changeShapeType(model, MapUtils.of(id, ShapeType.SET)); @@ -137,9 +137,9 @@ public void changesListToSet() { @Test public void cannotConvertListToAnythingButSet() { Shape startShape = ListShape.builder() - .id(ShapeId.from("smithy.example#Test")) - .member(ShapeId.from("smithy.api#String")) - .build(); + .id(ShapeId.from("smithy.example#Test")) + .member(ShapeId.from("smithy.api#String")) + .build(); Model model = Model.assembler().addShape(startShape).assemble().unwrap(); Assertions.assertThrows(IllegalArgumentException.class, () -> { @@ -153,11 +153,11 @@ public void changesSetToList() { ShapeId id = ShapeId.from("smithy.example#Test"); SourceLocation source = new SourceLocation("/foo", 1, 1); Shape startShape = SetShape.builder() - .addTrait(docTrait) - .id(id) - .source(source) - .member(ShapeId.from("smithy.api#String")) - .build(); + .addTrait(docTrait) + .id(id) + .source(source) + .member(ShapeId.from("smithy.api#String")) + .build(); Model model = Model.assembler().addShape(startShape).assemble().unwrap(); Model result = ModelTransformer.create().changeShapeType(model, MapUtils.of(id, ShapeType.LIST)); @@ -169,9 +169,9 @@ public void changesSetToList() { @Test public void cannotConvertSetToAnythingButList() { Shape startShape = SetShape.builder() - .id(ShapeId.from("smithy.example#Test")) - .member(ShapeId.from("smithy.api#String")) - .build(); + .id(ShapeId.from("smithy.example#Test")) + .member(ShapeId.from("smithy.api#String")) + .build(); Model model = Model.assembler().addShape(startShape).assemble().unwrap(); Assertions.assertThrows(IllegalArgumentException.class, () -> { @@ -185,11 +185,11 @@ public void changesStructureToUnion() { ShapeId id = ShapeId.from("smithy.example#Test"); SourceLocation source = new SourceLocation("/foo", 1, 1); Shape startShape = StructureShape.builder() - .addTrait(docTrait) - .id(id) - .source(source) - .addMember("foo", ShapeId.from("smithy.api#String")) - .build(); + .addTrait(docTrait) + .id(id) + .source(source) + .addMember("foo", ShapeId.from("smithy.api#String")) + .build(); Model model = Model.assembler().addShape(startShape).assemble().unwrap(); Model result = ModelTransformer.create().changeShapeType(model, MapUtils.of(id, ShapeType.UNION)); @@ -198,8 +198,8 @@ public void changesStructureToUnion() { assertThat(result.expectShape(id).getSourceLocation(), Matchers.equalTo(source)); assertThat(result.expectShape(id).members(), Matchers.hasSize(1)); assertThat( - result.expectShape(id).members().iterator().next(), - Matchers.equalTo(startShape.members().iterator().next()) + result.expectShape(id).members().iterator().next(), + Matchers.equalTo(startShape.members().iterator().next()) ); } @@ -209,11 +209,11 @@ public void changesUnionToStructure() { ShapeId id = ShapeId.from("smithy.example#Test"); SourceLocation source = new SourceLocation("/foo", 1, 1); Shape startShape = UnionShape.builder() - .addTrait(docTrait) - .id(id) - .source(source) - .addMember("foo", ShapeId.from("smithy.api#String")) - .build(); + .addTrait(docTrait) + .id(id) + .source(source) + .addMember("foo", ShapeId.from("smithy.api#String")) + .build(); Model model = Model.assembler().addShape(startShape).assemble().unwrap(); Model result = ModelTransformer.create().changeShapeType(model, MapUtils.of(id, ShapeType.STRUCTURE)); @@ -222,8 +222,8 @@ public void changesUnionToStructure() { assertThat(result.expectShape(id).getSourceLocation(), Matchers.equalTo(source)); assertThat(result.expectShape(id).members(), Matchers.hasSize(1)); assertThat( - result.expectShape(id).members().iterator().next(), - Matchers.equalTo(startShape.members().iterator().next()) + result.expectShape(id).members().iterator().next(), + Matchers.equalTo(startShape.members().iterator().next()) ); } @@ -248,9 +248,9 @@ public void ignoresConversionToSameType() { @Test public void cannotConvertUnionToAnythingButStructure() { Shape startShape = UnionShape.builder() - .id(ShapeId.from("smithy.example#Test")) - .addMember("foo", ShapeId.from("smithy.api#String")) - .build(); + .id(ShapeId.from("smithy.example#Test")) + .addMember("foo", ShapeId.from("smithy.api#String")) + .build(); Model model = Model.assembler().addShape(startShape).assemble().unwrap(); Assertions.assertThrows(IllegalArgumentException.class, () -> { @@ -261,37 +261,37 @@ public void cannotConvertUnionToAnythingButStructure() { @Test public void canConvertStringToEnum() { EnumTrait trait = EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("foo") - .value("bar") - .addTag("internal") - .build() - ) - .build(); + .addEnum( + EnumDefinition.builder() + .name("foo") + .value("bar") + .addTag("internal") + .build() + ) + .build(); SourceLocation source = new SourceLocation("/foo", 1, 1); ShapeId id = ShapeId.fromParts("ns.foo", "bar"); StringShape startShape = StringShape.builder() - .id(id) - .addTrait(trait) - .source(source) - .build(); + .id(id) + .addTrait(trait) + .source(source) + .build(); Model model = Model.assembler().addShape(startShape).assemble().unwrap(); Model result = ModelTransformer.create().changeShapeType(model, MapUtils.of(id, ShapeType.ENUM)); assertThat(result.expectShape(id).getType(), Matchers.is(ShapeType.ENUM)); assertThat(result.expectShape(id).getSourceLocation(), Matchers.equalTo(source)); assertThat(result.expectShape(id).members(), Matchers.hasSize(1)); assertThat( - result.expectShape(id).members().iterator().next(), - Matchers.equalTo( - MemberShape.builder() - .id(id.withMember("foo")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bar").build()) - .addTrait(new InternalTrait()) - .addTrait(TagsTrait.builder().addValue("internal").build()) - .build() - ) + result.expectShape(id).members().iterator().next(), + Matchers.equalTo( + MemberShape.builder() + .id(id.withMember("foo")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bar").build()) + .addTrait(new InternalTrait()) + .addTrait(TagsTrait.builder().addValue("internal").build()) + .build() + ) ); } @@ -300,9 +300,9 @@ public void cantConvertBaseStringWithoutEnumTrait() { SourceLocation source = new SourceLocation("/foo", 1, 1); ShapeId id = ShapeId.fromParts("ns.foo", "bar"); StringShape startShape = StringShape.builder() - .id(id) - .source(source) - .build(); + .id(id) + .source(source) + .build(); Model model = Model.assembler().addShape(startShape).assemble().unwrap(); Assertions.assertThrows(IllegalArgumentException.class, () -> { @@ -313,19 +313,19 @@ public void cantConvertBaseStringWithoutEnumTrait() { @Test public void cantConvertBaseStringWithNamelessEnumTrait() { EnumTrait trait = EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .value("bar") - .build() - ) - .build(); + .addEnum( + EnumDefinition.builder() + .value("bar") + .build() + ) + .build(); SourceLocation source = new SourceLocation("/foo", 1, 1); ShapeId id = ShapeId.fromParts("ns.foo", "bar"); StringShape startShape = StringShape.builder() - .id(id) - .addTrait(trait) - .source(source) - .build(); + .id(id) + .addTrait(trait) + .source(source) + .build(); Model model = Model.assembler().addShape(startShape).assemble().unwrap(); Assertions.assertThrows(IllegalArgumentException.class, () -> { @@ -338,15 +338,15 @@ public void canConvertEnumToString() { SourceLocation source = new SourceLocation("/foo", 1, 1); ShapeId id = ShapeId.fromParts("ns.foo", "bar"); Shape startShape = EnumShape.builder() - .id(id) - .addMember("FOO", "foo") - .source(source) - .build(); + .id(id) + .addMember("FOO", "foo") + .source(source) + .build(); Model model = Model.assembler() - .addShape(startShape) - .assemble() - .unwrap(); + .addShape(startShape) + .assemble() + .unwrap(); Model result = ModelTransformer.create().changeShapeType(model, MapUtils.of(id, ShapeType.STRING)); assertThat(result.expectShape(id).getType(), Matchers.is(ShapeType.STRING)); @@ -357,65 +357,65 @@ public void canConvertEnumToString() { assertFalse(trait instanceof SyntheticEnumTrait); assertThat( - trait.getValues(), - Matchers.equalTo( - ListUtils.of( - EnumDefinition.builder() - .name("FOO") - .value("foo") - .build() + trait.getValues(), + Matchers.equalTo( + ListUtils.of( + EnumDefinition.builder() + .name("FOO") + .value("foo") + .build() + ) ) - ) ); } @Test public void canFindEnumsToConvert() { EnumTrait compatibleTrait = EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .name("foo") - .value("bar") - .build() - ) - .build(); + .addEnum( + EnumDefinition.builder() + .name("foo") + .value("bar") + .build() + ) + .build(); ShapeId compatibleStringId = ShapeId.fromParts("ns.foo", "CompatibleString"); StringShape compatibleString = StringShape.builder() - .id(compatibleStringId) - .addTrait(compatibleTrait) - .build(); + .id(compatibleStringId) + .addTrait(compatibleTrait) + .build(); EnumTrait incompatibleTrait = EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .value("bar") - .build() - ) - .build(); + .addEnum( + EnumDefinition.builder() + .value("bar") + .build() + ) + .build(); ShapeId incompatibleStringId = ShapeId.fromParts("ns.foo", "IncompatibleString"); StringShape incompatibleString = StringShape.builder() - .id(incompatibleStringId) - .addTrait(incompatibleTrait) - .build(); + .id(incompatibleStringId) + .addTrait(incompatibleTrait) + .build(); Model model = Model.assembler() - .addShape(compatibleString) - .addShape(incompatibleString) - .assemble() - .unwrap(); + .addShape(compatibleString) + .addShape(incompatibleString) + .assemble() + .unwrap(); Model result = ModelTransformer.create().changeStringEnumsToEnumShapes(model); assertThat(result.expectShape(compatibleStringId).getType(), Matchers.is(ShapeType.ENUM)); assertThat(result.expectShape(compatibleStringId).members(), Matchers.hasSize(1)); assertThat( - result.expectShape(compatibleStringId).members().iterator().next(), - Matchers.equalTo( - MemberShape.builder() - .id(compatibleStringId.withMember("foo")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("bar").build()) - .build() - ) + result.expectShape(compatibleStringId).members().iterator().next(), + Matchers.equalTo( + MemberShape.builder() + .id(compatibleStringId.withMember("foo")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("bar").build()) + .build() + ) ); assertThat(result.expectShape(incompatibleStringId).getType(), Matchers.is(ShapeType.STRING)); @@ -425,35 +425,35 @@ public void canFindEnumsToConvert() { @Test public void canSynthesizeEnumNames() { EnumTrait trait = EnumTrait.builder() - .addEnum( - EnumDefinition.builder() - .value("foo:bar") - .build() - ) - .build(); + .addEnum( + EnumDefinition.builder() + .value("foo:bar") + .build() + ) + .build(); ShapeId shapeId = ShapeId.fromParts("ns.foo", "ConvertableShape"); StringShape initialShape = StringShape.builder() - .id(shapeId) - .addTrait(trait) - .build(); + .id(shapeId) + .addTrait(trait) + .build(); Model model = Model.assembler() - .addShape(initialShape) - .assemble() - .unwrap(); + .addShape(initialShape) + .assemble() + .unwrap(); Model result = ModelTransformer.create().changeStringEnumsToEnumShapes(model, true); assertThat(result.expectShape(shapeId).getType(), Matchers.is(ShapeType.ENUM)); assertThat(result.expectShape(shapeId).members(), Matchers.hasSize(1)); assertThat( - result.expectShape(shapeId).members().iterator().next(), - Matchers.equalTo( - MemberShape.builder() - .id(shapeId.withMember("foo_bar")) - .target(UnitTypeTrait.UNIT) - .addTrait(EnumValueTrait.builder().stringValue("foo:bar").build()) - .build() - ) + result.expectShape(shapeId).members().iterator().next(), + Matchers.equalTo( + MemberShape.builder() + .id(shapeId.withMember("foo_bar")) + .target(UnitTypeTrait.UNIT) + .addTrait(EnumValueTrait.builder().stringValue("foo:bar").build()) + .build() + ) ); } @@ -466,9 +466,9 @@ public void canDowngradeEnums() { IntEnumShape intEnum = intEnumBuilder.addMember("FOO", 1).build(); Model model = Model.assembler() - .addShapes(stringEnum, intEnum) - .assemble() - .unwrap(); + .addShapes(stringEnum, intEnum) + .assemble() + .unwrap(); Model result = ModelTransformer.create().downgradeEnums(model); assertThat(result.expectShape(stringEnum.getId()).getType(), Matchers.is(ShapeType.STRING)); @@ -477,15 +477,15 @@ public void canDowngradeEnums() { EnumTrait trait = result.expectShape(stringEnum.getId()).expectTrait(EnumTrait.class); assertFalse(trait instanceof SyntheticEnumTrait); assertThat( - trait.getValues(), - Matchers.equalTo( - ListUtils.of( - EnumDefinition.builder() - .name("FOO") - .value("foo") - .build() + trait.getValues(), + Matchers.equalTo( + ListUtils.of( + EnumDefinition.builder() + .name("FOO") + .value("foo") + .build() + ) ) - ) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/CopyServiceErrorsToOperationsTransformTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/CopyServiceErrorsToOperationsTransformTest.java index 3d07f97f039..969e058878a 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/CopyServiceErrorsToOperationsTransformTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/CopyServiceErrorsToOperationsTransformTest.java @@ -18,29 +18,29 @@ public class CopyServiceErrorsToOperationsTransformTest { @Test public void copiesErrors() { StructureShape errorShape1 = StructureShape.builder() - .id("ns.foo#Error1") - .addTrait(new ErrorTrait("client")) - .build(); + .id("ns.foo#Error1") + .addTrait(new ErrorTrait("client")) + .build(); StructureShape errorShape2 = StructureShape.builder() - .id("ns.foo#Error2") - .addTrait(new ErrorTrait("client")) - .build(); + .id("ns.foo#Error2") + .addTrait(new ErrorTrait("client")) + .build(); OperationShape operation1 = OperationShape.builder() - .id("smithy.example#Operation1") - .addError(errorShape1) - .build(); + .id("smithy.example#Operation1") + .addError(errorShape1) + .build(); OperationShape operation2 = OperationShape.builder() - .id("smithy.example#Operation2") - .build(); + .id("smithy.example#Operation2") + .build(); ServiceShape service = ServiceShape.builder() - .id("ns.foo#Svc") - .version("2017-01-17") - .addError(errorShape2) - .addOperation(operation1) - .build(); + .id("ns.foo#Svc") + .version("2017-01-17") + .addError(errorShape2) + .addOperation(operation1) + .build(); Model model = Model.builder() - .addShapes(service, errorShape1, errorShape2, operation1, operation2) - .build(); + .addShapes(service, errorShape1, errorShape2, operation1, operation2) + .build(); Model result = ModelTransformer.create().copyServiceErrorsToOperations(model, service); // operation2 is not in the service closure so leave it alone. @@ -48,8 +48,8 @@ public void copiesErrors() { // Make sure service errors were copied to the operation bound within it. assertThat( - result.expectShape(operation1.getId(), OperationShape.class).getErrors(), - Matchers.containsInAnyOrder(errorShape1.getId(), errorShape2.getId()) + result.expectShape(operation1.getId(), OperationShape.class).getErrors(), + Matchers.containsInAnyOrder(errorShape1.getId(), errorShape2.getId()) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/CreateDedicatedInputAndOutputTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/CreateDedicatedInputAndOutputTest.java index 8faf3dbf3b0..7edc4b7c5a7 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/CreateDedicatedInputAndOutputTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/CreateDedicatedInputAndOutputTest.java @@ -22,14 +22,14 @@ public class CreateDedicatedInputAndOutputTest { private Model compareTransform(String prefix, Function transform) { Model before = Model.assembler() - .addImport(getClass().getResource("dedicated-input-output/" + prefix + "-before.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("dedicated-input-output/" + prefix + "-before.smithy")) + .assemble() + .unwrap(); Model actualResult = transform.apply(before); Model expectedResult = Model.assembler() - .addImport(getClass().getResource("dedicated-input-output/" + prefix + "-after.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("dedicated-input-output/" + prefix + "-after.smithy")) + .assemble() + .unwrap(); Node actualNode = ModelSerializer.builder().build().serialize(actualResult); Node expectedNode = ModelSerializer.builder().build().serialize(expectedResult); @@ -48,12 +48,12 @@ public void createsDedicatedInputHeuristic() { result.expectShape(ShapeId.from("smithy.example#GetFooInput")).expectTrait(InputTrait.class); result.expectShape(ShapeId.from("smithy.example#GetFooOutput")).expectTrait(OutputTrait.class); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooInput")).getTrait(OriginalShapeIdTrait.class), - Matchers.equalTo(Optional.empty()) + result.expectShape(ShapeId.from("smithy.example#GetFooInput")).getTrait(OriginalShapeIdTrait.class), + Matchers.equalTo(Optional.empty()) ); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooOutput")).getTrait(OriginalShapeIdTrait.class), - Matchers.equalTo(Optional.empty()) + result.expectShape(ShapeId.from("smithy.example#GetFooOutput")).getTrait(OriginalShapeIdTrait.class), + Matchers.equalTo(Optional.empty()) ); } @@ -66,12 +66,12 @@ public void createsDedicatedOutputHeuristic() { result.expectShape(ShapeId.from("smithy.example#GetFooInput")).expectTrait(InputTrait.class); result.expectShape(ShapeId.from("smithy.example#GetFooOutput")).expectTrait(OutputTrait.class); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooInput")).getTrait(OriginalShapeIdTrait.class), - Matchers.equalTo(Optional.empty()) + result.expectShape(ShapeId.from("smithy.example#GetFooInput")).getTrait(OriginalShapeIdTrait.class), + Matchers.equalTo(Optional.empty()) ); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooOutput")).getTrait(OriginalShapeIdTrait.class), - Matchers.equalTo(Optional.empty()) + result.expectShape(ShapeId.from("smithy.example#GetFooOutput")).getTrait(OriginalShapeIdTrait.class), + Matchers.equalTo(Optional.empty()) ); } @@ -84,12 +84,12 @@ public void createsDedicatedInputAndOutputHeuristic() { result.expectShape(ShapeId.from("smithy.example#GetFooRequest")).expectTrait(InputTrait.class); result.expectShape(ShapeId.from("smithy.example#GetFooResponse")).expectTrait(OutputTrait.class); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooRequest")).getTrait(OriginalShapeIdTrait.class), - Matchers.equalTo(Optional.empty()) + result.expectShape(ShapeId.from("smithy.example#GetFooRequest")).getTrait(OriginalShapeIdTrait.class), + Matchers.equalTo(Optional.empty()) ); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooResponse")).getTrait(OriginalShapeIdTrait.class), - Matchers.equalTo(Optional.empty()) + result.expectShape(ShapeId.from("smithy.example#GetFooResponse")).getTrait(OriginalShapeIdTrait.class), + Matchers.equalTo(Optional.empty()) ); } @@ -102,16 +102,16 @@ public void createsDedicatedCopies() { result.expectShape(ShapeId.from("smithy.example#GetFooInput")).expectTrait(InputTrait.class); result.expectShape(ShapeId.from("smithy.example#GetFooOutput")).expectTrait(OutputTrait.class); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooInput")) - .expectTrait(OriginalShapeIdTrait.class) - .getOriginalId(), - Matchers.equalTo(ShapeId.from("smithy.example#GetFooData")) + result.expectShape(ShapeId.from("smithy.example#GetFooInput")) + .expectTrait(OriginalShapeIdTrait.class) + .getOriginalId(), + Matchers.equalTo(ShapeId.from("smithy.example#GetFooData")) ); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooOutput")) - .expectTrait(OriginalShapeIdTrait.class) - .getOriginalId(), - Matchers.equalTo(ShapeId.from("smithy.example#Foo")) + result.expectShape(ShapeId.from("smithy.example#GetFooOutput")) + .expectTrait(OriginalShapeIdTrait.class) + .getOriginalId(), + Matchers.equalTo(ShapeId.from("smithy.example#Foo")) ); } @@ -124,16 +124,16 @@ public void createsDedicatedCopiesAndDeconflicts() { result.expectShape(ShapeId.from("smithy.example#GetFooOperationInput")).expectTrait(InputTrait.class); result.expectShape(ShapeId.from("smithy.example#GetFooOperationOutput")).expectTrait(OutputTrait.class); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooOperationInput")) - .expectTrait(OriginalShapeIdTrait.class) - .getOriginalId(), - Matchers.equalTo(ShapeId.from("smithy.example#GetFooData")) + result.expectShape(ShapeId.from("smithy.example#GetFooOperationInput")) + .expectTrait(OriginalShapeIdTrait.class) + .getOriginalId(), + Matchers.equalTo(ShapeId.from("smithy.example#GetFooData")) ); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooOperationOutput")) - .expectTrait(OriginalShapeIdTrait.class) - .getOriginalId(), - Matchers.equalTo(ShapeId.from("smithy.example#Foo")) + result.expectShape(ShapeId.from("smithy.example#GetFooOperationOutput")) + .expectTrait(OriginalShapeIdTrait.class) + .getOriginalId(), + Matchers.equalTo(ShapeId.from("smithy.example#Foo")) ); } @@ -150,16 +150,16 @@ public void removesDisconnectedShapes() { result.expectShape(ShapeId.from("smithy.example#GetFooOutput")).expectTrait(OutputTrait.class); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooInput")) - .expectTrait(OriginalShapeIdTrait.class) - .getOriginalId(), - Matchers.equalTo(ShapeId.from("smithy.example#GetFooData")) + result.expectShape(ShapeId.from("smithy.example#GetFooInput")) + .expectTrait(OriginalShapeIdTrait.class) + .getOriginalId(), + Matchers.equalTo(ShapeId.from("smithy.example#GetFooData")) ); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooOutput")) - .expectTrait(OriginalShapeIdTrait.class) - .getOriginalId(), - Matchers.equalTo(ShapeId.from("smithy.example#Foo")) + result.expectShape(ShapeId.from("smithy.example#GetFooOutput")) + .expectTrait(OriginalShapeIdTrait.class) + .getOriginalId(), + Matchers.equalTo(ShapeId.from("smithy.example#Foo")) ); } @@ -173,24 +173,24 @@ public void handlesUnitTypes() { result.expectShape(ShapeId.from("smithy.example#GetFooOutput")).expectTrait(OutputTrait.class); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooInput")) - .expectTrait(OriginalShapeIdTrait.class) - .getOriginalId(), - Matchers.equalTo(ShapeId.from("smithy.api#Unit")) + result.expectShape(ShapeId.from("smithy.example#GetFooInput")) + .expectTrait(OriginalShapeIdTrait.class) + .getOriginalId(), + Matchers.equalTo(ShapeId.from("smithy.api#Unit")) ); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooOutput")) - .expectTrait(OriginalShapeIdTrait.class) - .getOriginalId(), - Matchers.equalTo(ShapeId.from("smithy.api#Unit")) + result.expectShape(ShapeId.from("smithy.example#GetFooOutput")) + .expectTrait(OriginalShapeIdTrait.class) + .getOriginalId(), + Matchers.equalTo(ShapeId.from("smithy.api#Unit")) ); } @Test public void removesDisconnectedSharedShape() { Model result = compareTransform( - "removes-disconnected-shared-shape", - model -> ModelTransformer.create().createDedicatedInputAndOutput(model, "Input", "Output") + "removes-disconnected-shared-shape", + model -> ModelTransformer.create().createDedicatedInputAndOutput(model, "Input", "Output") ); assertThat(result.getShapeIds(), Matchers.not(Matchers.hasItem(ShapeId.from("smithy.example#MyGetFooOutput")))); @@ -199,41 +199,41 @@ public void removesDisconnectedSharedShape() { result.expectShape(ShapeId.from("smithy.example#GetFooOutput")).expectTrait(OutputTrait.class); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooInput")) - .expectTrait(OriginalShapeIdTrait.class) - .getOriginalId(), - Matchers.equalTo(ShapeId.from("smithy.example#MyGetFooOutput")) + result.expectShape(ShapeId.from("smithy.example#GetFooInput")) + .expectTrait(OriginalShapeIdTrait.class) + .getOriginalId(), + Matchers.equalTo(ShapeId.from("smithy.example#MyGetFooOutput")) ); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooOutput")) - .expectTrait(OriginalShapeIdTrait.class) - .getOriginalId(), - Matchers.equalTo(ShapeId.from("smithy.example#MyGetFooOutput")) + result.expectShape(ShapeId.from("smithy.example#GetFooOutput")) + .expectTrait(OriginalShapeIdTrait.class) + .getOriginalId(), + Matchers.equalTo(ShapeId.from("smithy.example#MyGetFooOutput")) ); } @Test public void createsDedicatedHeuristicForSharedShape() { Model result = compareTransform( - "creates-dedicated-heuristic-for-shared", - model -> ModelTransformer.create().createDedicatedInputAndOutput(model, "Input", "Output") + "creates-dedicated-heuristic-for-shared", + model -> ModelTransformer.create().createDedicatedInputAndOutput(model, "Input", "Output") ); result.expectShape(ShapeId.from("smithy.example#GetFooInput")).expectTrait(InputTrait.class); result.expectShape(ShapeId.from("smithy.example#GetFooOutput")).expectTrait(OutputTrait.class); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooInput")) - .expectTrait(OriginalShapeIdTrait.class) - .getOriginalId(), - Matchers.equalTo(ShapeId.from("smithy.example#GetFooOutput")) + result.expectShape(ShapeId.from("smithy.example#GetFooInput")) + .expectTrait(OriginalShapeIdTrait.class) + .getOriginalId(), + Matchers.equalTo(ShapeId.from("smithy.example#GetFooOutput")) ); assertThat( - result.expectShape(ShapeId.from("smithy.example#GetFooOutput")) - .getTrait(OriginalShapeIdTrait.class), - Matchers.equalTo(Optional.empty()) + result.expectShape(ShapeId.from("smithy.example#GetFooOutput")) + .getTrait(OriginalShapeIdTrait.class), + Matchers.equalTo(Optional.empty()) ); } @@ -241,9 +241,9 @@ public void createsDedicatedHeuristicForSharedShape() { public void detectsConflictResolverLoop() { Assertions.assertThrows(ModelTransformException.class, () -> { Model before = Model.assembler() - .addImport(getClass().getResource("dedicated-input-output/unable-to-deconflict.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("dedicated-input-output/unable-to-deconflict.smithy")) + .assemble() + .unwrap(); ModelTransformer.create().createDedicatedInputAndOutput(before, "Input", "Output"); }); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/DeconflictErrorsWithSharedStatusCodeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/DeconflictErrorsWithSharedStatusCodeTest.java index 56e1ef1eb88..1333159d463 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/DeconflictErrorsWithSharedStatusCodeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/DeconflictErrorsWithSharedStatusCodeTest.java @@ -17,13 +17,13 @@ public class DeconflictErrorsWithSharedStatusCodeTest { @Test public void deconflictErrorsWithSharedStatusCodes() { Model input = Model.assembler() - .addImport(getClass().getResource("conflicting-errors.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("conflicting-errors.smithy")) + .assemble() + .unwrap(); Model output = Model.assembler() - .addImport(getClass().getResource("deconflicted-errors.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("deconflicted-errors.smithy")) + .assemble() + .unwrap(); ModelTransformer transformer = ModelTransformer.create(); @@ -39,16 +39,16 @@ public void deconflictErrorsWithSharedStatusCodes() { @Test public void throwsWhenHeadersConflict() { Model model = Model.assembler() - .addImport(getClass().getResource("conflicting-errors-with-conflicting-headers.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("conflicting-errors-with-conflicting-headers.smithy")) + .assemble() + .unwrap(); ModelTransformer transformer = ModelTransformer.create(); ServiceShape service = model.expectShape(ShapeId.from("smithy.example#MyService"), ServiceShape.class); assertThrows( - ModelTransformException.class, - () -> transformer.deconflictErrorsWithSharedStatusCode(model, service) + ModelTransformException.class, + () -> transformer.deconflictErrorsWithSharedStatusCode(model, service) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/DowngradeToV1Test.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/DowngradeToV1Test.java index 5638a6e197a..e6bab927edf 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/DowngradeToV1Test.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/DowngradeToV1Test.java @@ -31,13 +31,13 @@ public class DowngradeToV1Test { @Test public void convertsIntEnums() { IntEnumShape intEnumShape = IntEnumShape.builder() - .id("smithy.example#IntEnum") - .addMember("foo", 1) - .build(); + .id("smithy.example#IntEnum") + .addMember("foo", 1) + .build(); Model model = Model.assembler() - .addShape(intEnumShape) - .assemble() - .unwrap(); + .addShape(intEnumShape) + .assemble() + .unwrap(); Model downgraded = ModelTransformer.create().downgradeToV1(model); @@ -49,13 +49,13 @@ public void convertsIntEnums() { @Test public void convertsEnumShapes() { EnumShape enumShape = EnumShape.builder() - .id("smithy.example#Enum") - .addMember("foo", "hello") - .build(); + .id("smithy.example#Enum") + .addMember("foo", "hello") + .build(); Model model = Model.assembler() - .addShape(enumShape) - .assemble() - .unwrap(); + .addShape(enumShape) + .assemble() + .unwrap(); Model downgraded = ModelTransformer.create().downgradeToV1(model); @@ -67,18 +67,18 @@ public void convertsEnumShapes() { @Test public void flattensMixins() { StringShape mixin = StringShape.builder() - .id("smithy.example#Mixin") - .addTrait(MixinTrait.builder().build()) - .addTrait(new SensitiveTrait()) - .build(); + .id("smithy.example#Mixin") + .addTrait(MixinTrait.builder().build()) + .addTrait(new SensitiveTrait()) + .build(); StringShape concrete = StringShape.builder() - .id("smithy.example#Concrete") - .addMixin(mixin) - .build(); + .id("smithy.example#Concrete") + .addMixin(mixin) + .build(); Model model = Model.assembler() - .addShapes(mixin, concrete) - .assemble() - .unwrap(); + .addShapes(mixin, concrete) + .assemble() + .unwrap(); Model downgraded = ModelTransformer.create().downgradeToV1(model); @@ -90,104 +90,104 @@ public void flattensMixins() { @Test public void removesResourceProperties() { StructureShape input = StructureShape.builder() - .id("smithy.example#Input") - .addMember("foo", ShapeId.from("smithy.api#String"), b -> b.addTrait(PropertyTrait.builder().build())) - .addMember("baz", ShapeId.from("smithy.api#String"), b -> b.addTrait(new NotPropertyTrait())) - .build(); + .id("smithy.example#Input") + .addMember("foo", ShapeId.from("smithy.api#String"), b -> b.addTrait(PropertyTrait.builder().build())) + .addMember("baz", ShapeId.from("smithy.api#String"), b -> b.addTrait(new NotPropertyTrait())) + .build(); OperationShape operation = OperationShape.builder() - .id(ShapeId.from("smithy.example#Op")) - .input(input) - .build(); + .id(ShapeId.from("smithy.example#Op")) + .input(input) + .build(); ResourceShape resource = ResourceShape.builder() - .id(ShapeId.from("smithy.example#Foo")) - .addProperty("foo", "smithy.api#String") - .addOperation(operation) - .build(); + .id(ShapeId.from("smithy.example#Foo")) + .addProperty("foo", "smithy.api#String") + .addOperation(operation) + .build(); Model model = Model.assembler() - .addShapes(input, operation, resource) - .assemble() - .unwrap(); + .addShapes(input, operation, resource) + .assemble() + .unwrap(); Model downgraded = ModelTransformer.create().downgradeToV1(model); assertThat( - downgraded.expectShape(resource.getId(), ResourceShape.class).getProperties(), - Matchers.anEmptyMap() + downgraded.expectShape(resource.getId(), ResourceShape.class).getProperties(), + Matchers.anEmptyMap() ); assertThat( - downgraded.expectShape(input.getMember("foo").get().getId()).hasTrait(PropertyTrait.class), - Matchers.is(false) + downgraded.expectShape(input.getMember("foo").get().getId()).hasTrait(PropertyTrait.class), + Matchers.is(false) ); assertThat( - downgraded.expectShape(input.getMember("baz").get().getId()).hasTrait(NotPropertyTrait.class), - Matchers.is(false) + downgraded.expectShape(input.getMember("baz").get().getId()).hasTrait(NotPropertyTrait.class), + Matchers.is(false) ); } @Test public void removesUnnecessaryDefaults() { String stringModel = "$version: \"2.0\"\n" - + "namespace smithy.example\n" - // A Root level shape with a 1.0 non-zero value drops the default value and is boxed - + "@default(10)\n" - + "integer MyInteger\n" - // A Root level shape with a 1.0 zero value keeps the default value - + "@default(0)\n" - + "integer ZeroInteger\n" - // A Root level shape with no default value is boxed - + "integer BoxedInteger\n" - // Omitted Test Case: [ERROR] The @default trait can be set to null only on members - + "// @default(null)\n" - + "// integer ExplicitlyBoxedInteger\n" - // StructureShape still exists - + "structure Struct {\n" - // A Member that targets a shape with a 1.0 non-zero value drops the default value and is not boxed - + " @default(10)\n" - + " foo: MyInteger\n" - // Omitted Test Case: [ERROR] Member defines a default value that differs from the default value of the target shape - + " // @default(5)\n" - + " // fooFive: MyInteger\n" - // A Member that targets a shape with a matching default 1.0 zero value keeps the default value - + " zeroTargetZeroMember: ZeroInteger = 0\n" - // Omitted Test Case: [ERROR] Member defines a default value that differs from the default value of the target shape - + " // zeroTargetNonzeroMember: ZeroInteger = 1\n" - // A Member that has a default value of null keeps the default value of null and is boxed - + " zeroTargetBoxedMember: ZeroInteger = null\n" - // Omitted Test Case: [ERROR] Member defines a default value that differs from the default value of the target shape - + " // zeroTargetImplicitBoxedMember: ZeroInteger\n" - // A Member that has a target shape with no default value drops the default value - + " boxedTargetZeroMember: BoxedInteger = 0\n" - // A Member that has a target shape with no default value drops the default value - + " boxedTargetNonzeroMember: BoxedInteger = 1\n" - // A Member that has a default value of null keeps the default value of null and is boxed - + " boxedTargetBoxedMember: BoxedInteger = null\n" - // A Member that has no default value has no default trait and the member is not boxed - + " boxedTargetImplicitBoxedMember: BoxedInteger\n" - // A Member that has a default value of null keeps the default value of null and is boxed - + " baz: PrimitiveInteger = null\n" - // A Member with the addedDefault trait drops both the default and addedDefault trait - + " @default(\"hi\")\n" - + " @addedDefault\n" - + " bar: String\n" - // A Member keeps the required trait and drops the clientOptional trait - + " @required\n" - + " @clientOptional\n" - + " bam: String\n" - + "}"; + + "namespace smithy.example\n" + // A Root level shape with a 1.0 non-zero value drops the default value and is boxed + + "@default(10)\n" + + "integer MyInteger\n" + // A Root level shape with a 1.0 zero value keeps the default value + + "@default(0)\n" + + "integer ZeroInteger\n" + // A Root level shape with no default value is boxed + + "integer BoxedInteger\n" + // Omitted Test Case: [ERROR] The @default trait can be set to null only on members + + "// @default(null)\n" + + "// integer ExplicitlyBoxedInteger\n" + // StructureShape still exists + + "structure Struct {\n" + // A Member that targets a shape with a 1.0 non-zero value drops the default value and is not boxed + + " @default(10)\n" + + " foo: MyInteger\n" + // Omitted Test Case: [ERROR] Member defines a default value that differs from the default value of the target shape + + " // @default(5)\n" + + " // fooFive: MyInteger\n" + // A Member that targets a shape with a matching default 1.0 zero value keeps the default value + + " zeroTargetZeroMember: ZeroInteger = 0\n" + // Omitted Test Case: [ERROR] Member defines a default value that differs from the default value of the target shape + + " // zeroTargetNonzeroMember: ZeroInteger = 1\n" + // A Member that has a default value of null keeps the default value of null and is boxed + + " zeroTargetBoxedMember: ZeroInteger = null\n" + // Omitted Test Case: [ERROR] Member defines a default value that differs from the default value of the target shape + + " // zeroTargetImplicitBoxedMember: ZeroInteger\n" + // A Member that has a target shape with no default value drops the default value + + " boxedTargetZeroMember: BoxedInteger = 0\n" + // A Member that has a target shape with no default value drops the default value + + " boxedTargetNonzeroMember: BoxedInteger = 1\n" + // A Member that has a default value of null keeps the default value of null and is boxed + + " boxedTargetBoxedMember: BoxedInteger = null\n" + // A Member that has no default value has no default trait and the member is not boxed + + " boxedTargetImplicitBoxedMember: BoxedInteger\n" + // A Member that has a default value of null keeps the default value of null and is boxed + + " baz: PrimitiveInteger = null\n" + // A Member with the addedDefault trait drops both the default and addedDefault trait + + " @default(\"hi\")\n" + + " @addedDefault\n" + + " bar: String\n" + // A Member keeps the required trait and drops the clientOptional trait + + " @required\n" + + " @clientOptional\n" + + " bam: String\n" + + "}"; Model model = Model.assembler() - .addUnparsedModel("example.smithy", stringModel) - .assemble() - .unwrap(); + .addUnparsedModel("example.smithy", stringModel) + .assemble() + .unwrap(); Model downgraded = ModelTransformer.create().downgradeToV1(model); Model.assembler() - .addModel(downgraded) - .assemble() - .unwrap(); + .addModel(downgraded) + .assemble() + .unwrap(); // A Root level shape with a 1.0 non-zero value drops the default value and is boxed ShapeId integerShape = ShapeId.from("smithy.example#MyInteger"); @@ -199,12 +199,12 @@ public void removesUnnecessaryDefaults() { ShapeId zeroIntegerShape = ShapeId.from("smithy.example#ZeroInteger"); assertThat(downgraded.expectShape(zeroIntegerShape).hasTrait(DefaultTrait.class), Matchers.is(true)); assertThat( - downgraded.expectShape(zeroIntegerShape) - .expectTrait(DefaultTrait.class) - .toNode() - .expectNumberNode() - .getValue(), - Matchers.is(0L) + downgraded.expectShape(zeroIntegerShape) + .expectTrait(DefaultTrait.class) + .toNode() + .expectNumberNode() + .getValue(), + Matchers.is(0L) ); assertThat(downgraded.expectShape(zeroIntegerShape).hasTrait(AddedDefaultTrait.class), Matchers.is(false)); assertThat(downgraded.expectShape(zeroIntegerShape).hasTrait(BoxTrait.class), Matchers.is(false)); @@ -226,94 +226,102 @@ public void removesUnnecessaryDefaults() { // A Member that targets a shape with a matching default 1.0 zero value keeps the default value assertThat(dStruct.getAllMembers().get("zeroTargetZeroMember").hasTrait(DefaultTrait.class), Matchers.is(true)); assertThat( - dStruct.getAllMembers() - .get("zeroTargetZeroMember") - .expectTrait(DefaultTrait.class) - .toNode() - .expectNumberNode() - .getValue(), - Matchers.is(0L) + dStruct.getAllMembers() + .get("zeroTargetZeroMember") + .expectTrait(DefaultTrait.class) + .toNode() + .expectNumberNode() + .getValue(), + Matchers.is(0L) ); assertThat( - dStruct.getAllMembers().get("zeroTargetZeroMember").hasTrait(AddedDefaultTrait.class), - Matchers.is(false) + dStruct.getAllMembers().get("zeroTargetZeroMember").hasTrait(AddedDefaultTrait.class), + Matchers.is(false) ); assertThat(dStruct.getAllMembers().get("zeroTargetZeroMember").hasTrait(BoxTrait.class), Matchers.is(false)); // A Member that has a default value of null keeps the default value of null and is boxed assertThat( - dStruct.getAllMembers().get("zeroTargetBoxedMember").hasTrait(DefaultTrait.class), - Matchers.is(true) + dStruct.getAllMembers().get("zeroTargetBoxedMember").hasTrait(DefaultTrait.class), + Matchers.is(true) ); assertThat( - dStruct.getAllMembers().get("zeroTargetBoxedMember").expectTrait(DefaultTrait.class).toNode().isNullNode(), - Matchers.is(true) + dStruct.getAllMembers() + .get("zeroTargetBoxedMember") + .expectTrait(DefaultTrait.class) + .toNode() + .isNullNode(), + Matchers.is(true) ); assertThat( - dStruct.getAllMembers().get("zeroTargetBoxedMember").hasTrait(AddedDefaultTrait.class), - Matchers.is(false) + dStruct.getAllMembers().get("zeroTargetBoxedMember").hasTrait(AddedDefaultTrait.class), + Matchers.is(false) ); assertThat(dStruct.getAllMembers().get("zeroTargetBoxedMember").hasTrait(BoxTrait.class), Matchers.is(true)); // A Member that has a target shape with no default value drops the default value assertThat( - dStruct.getAllMembers().get("boxedTargetZeroMember").hasTrait(DefaultTrait.class), - Matchers.is(false) + dStruct.getAllMembers().get("boxedTargetZeroMember").hasTrait(DefaultTrait.class), + Matchers.is(false) ); assertThat( - dStruct.getAllMembers().get("boxedTargetZeroMember").hasTrait(AddedDefaultTrait.class), - Matchers.is(false) + dStruct.getAllMembers().get("boxedTargetZeroMember").hasTrait(AddedDefaultTrait.class), + Matchers.is(false) ); assertThat(dStruct.getAllMembers().get("boxedTargetZeroMember").hasTrait(BoxTrait.class), Matchers.is(false)); // A Member that has a target shape with no default value drops the default value assertThat( - dStruct.getAllMembers().get("boxedTargetNonzeroMember").hasTrait(DefaultTrait.class), - Matchers.is(false) + dStruct.getAllMembers().get("boxedTargetNonzeroMember").hasTrait(DefaultTrait.class), + Matchers.is(false) ); assertThat( - dStruct.getAllMembers().get("boxedTargetNonzeroMember").hasTrait(AddedDefaultTrait.class), - Matchers.is(false) + dStruct.getAllMembers().get("boxedTargetNonzeroMember").hasTrait(AddedDefaultTrait.class), + Matchers.is(false) ); assertThat( - dStruct.getAllMembers().get("boxedTargetNonzeroMember").hasTrait(BoxTrait.class), - Matchers.is(false) + dStruct.getAllMembers().get("boxedTargetNonzeroMember").hasTrait(BoxTrait.class), + Matchers.is(false) ); // A Member that has a default value of null keeps the default value of null and is boxed assertThat( - dStruct.getAllMembers().get("boxedTargetBoxedMember").hasTrait(DefaultTrait.class), - Matchers.is(true) + dStruct.getAllMembers().get("boxedTargetBoxedMember").hasTrait(DefaultTrait.class), + Matchers.is(true) ); assertThat( - dStruct.getAllMembers().get("boxedTargetBoxedMember").expectTrait(DefaultTrait.class).toNode().isNullNode(), - Matchers.is(true) + dStruct.getAllMembers() + .get("boxedTargetBoxedMember") + .expectTrait(DefaultTrait.class) + .toNode() + .isNullNode(), + Matchers.is(true) ); assertThat( - dStruct.getAllMembers().get("boxedTargetBoxedMember").hasTrait(AddedDefaultTrait.class), - Matchers.is(false) + dStruct.getAllMembers().get("boxedTargetBoxedMember").hasTrait(AddedDefaultTrait.class), + Matchers.is(false) ); assertThat(dStruct.getAllMembers().get("boxedTargetBoxedMember").hasTrait(BoxTrait.class), Matchers.is(true)); // A Member that has no default value has no default trait and the member is not boxed assertThat( - dStruct.getAllMembers().get("boxedTargetImplicitBoxedMember").hasTrait(DefaultTrait.class), - Matchers.is(false) + dStruct.getAllMembers().get("boxedTargetImplicitBoxedMember").hasTrait(DefaultTrait.class), + Matchers.is(false) ); assertThat( - dStruct.getAllMembers().get("boxedTargetImplicitBoxedMember").hasTrait(AddedDefaultTrait.class), - Matchers.is(false) + dStruct.getAllMembers().get("boxedTargetImplicitBoxedMember").hasTrait(AddedDefaultTrait.class), + Matchers.is(false) ); assertThat( - dStruct.getAllMembers().get("boxedTargetImplicitBoxedMember").hasTrait(BoxTrait.class), - Matchers.is(false) + dStruct.getAllMembers().get("boxedTargetImplicitBoxedMember").hasTrait(BoxTrait.class), + Matchers.is(false) ); // A Member that has a default value of null keeps the default value of null and is boxed assertThat(dStruct.getAllMembers().get("baz").hasTrait(DefaultTrait.class), Matchers.is(true)); assertThat( - dStruct.getAllMembers().get("baz").expectTrait(DefaultTrait.class).toNode().isNullNode(), - Matchers.is(true) + dStruct.getAllMembers().get("baz").expectTrait(DefaultTrait.class).toNode().isNullNode(), + Matchers.is(true) ); assertThat(dStruct.getAllMembers().get("baz").hasTrait(AddedDefaultTrait.class), Matchers.is(false)); assertThat(dStruct.getAllMembers().get("baz").hasTrait(BoxTrait.class), Matchers.is(true)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeDateTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeDateTest.java index f3188d0d083..f6c5cd971cd 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeDateTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeDateTest.java @@ -22,14 +22,18 @@ public static List fileSource() { @MethodSource("fileSource") void compareTransform(String prefix) { Model before = Model.assembler() - .addImport(FilterDeprecatedRelativeDate.class.getResource("deprecated-date/" + prefix + "-before.smithy")) - .assemble() - .unwrap(); + .addImport( + FilterDeprecatedRelativeDate.class.getResource("deprecated-date/" + prefix + "-before.smithy") + ) + .assemble() + .unwrap(); Model actualResult = ModelTransformer.create().filterDeprecatedRelativeDate(before, "2024-10-10"); Model expectedResult = Model.assembler() - .addImport(FilterDeprecatedRelativeDate.class.getResource("deprecated-date/" + prefix + "-after.smithy")) - .assemble() - .unwrap(); + .addImport( + FilterDeprecatedRelativeDate.class.getResource("deprecated-date/" + prefix + "-after.smithy") + ) + .assemble() + .unwrap(); Node actualNode = ModelSerializer.builder().build().serialize(actualResult); Node expectedNode = ModelSerializer.builder().build().serialize(expectedResult); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeVersionTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeVersionTest.java index 2375c715854..9f596106cb9 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeVersionTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterDeprecatedRelativeVersionTest.java @@ -19,15 +19,15 @@ public class FilterDeprecatedRelativeVersionTest { static List semverSupplier() { return ListUtils.of( - Arguments.of("1.0.0", "1.0.0", 0), - Arguments.of("1.0.0", "1.0.1", -1), - Arguments.of("1.1.0", "1.1.1", -1), - Arguments.of("1.1.0", "1.0.1", 1), - Arguments.of("1.1.1", "1.1.1.1", -1), - Arguments.of("1.0.0.1", "1.0.0", 1), - Arguments.of("1.0.0", "1.0", 0), - Arguments.of("20.20.0.1", "20.20.1.0", -1), - Arguments.of("20.20.1.0", "20.20.1.0-PATCH", -1) + Arguments.of("1.0.0", "1.0.0", 0), + Arguments.of("1.0.0", "1.0.1", -1), + Arguments.of("1.1.0", "1.1.1", -1), + Arguments.of("1.1.0", "1.0.1", 1), + Arguments.of("1.1.1", "1.1.1.1", -1), + Arguments.of("1.0.0.1", "1.0.0", 1), + Arguments.of("1.0.0", "1.0", 0), + Arguments.of("20.20.0.1", "20.20.1.0", -1), + Arguments.of("20.20.1.0", "20.20.1.0-PATCH", -1) ); } @@ -58,16 +58,20 @@ public static List fileSource() { @MethodSource("fileSource") void compareTransform(String prefix) { Model before = Model.assembler() - .addImport( - FilterDeprecatedRelativeDate.class.getResource("deprecated-version/" + prefix + "-before.smithy") - ) - .assemble() - .unwrap(); + .addImport( + FilterDeprecatedRelativeDate.class.getResource( + "deprecated-version/" + prefix + "-before.smithy" + ) + ) + .assemble() + .unwrap(); Model actualResult = ModelTransformer.create().filterDeprecatedRelativeVersion(before, "1.1.0"); Model expectedResult = Model.assembler() - .addImport(FilterDeprecatedRelativeDate.class.getResource("deprecated-version/" + prefix + "-after.smithy")) - .assemble() - .unwrap(); + .addImport( + FilterDeprecatedRelativeDate.class.getResource("deprecated-version/" + prefix + "-after.smithy") + ) + .assemble() + .unwrap(); Node actualNode = ModelSerializer.builder().build().serialize(actualResult); Node expectedNode = ModelSerializer.builder().build().serialize(expectedResult); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterMetadataTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterMetadataTest.java index df797fae499..8ebfafc57be 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterMetadataTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterMetadataTest.java @@ -15,10 +15,10 @@ public class FilterMetadataTest { @Test public void filtersMetadata() { Model model = Model.builder() - .putMetadataProperty("foo", Node.from("string")) - .putMetadataProperty("baz", Node.from(1)) - .putMetadataProperty("lorem", Node.from(true)) - .build(); + .putMetadataProperty("foo", Node.from("string")) + .putMetadataProperty("baz", Node.from(1)) + .putMetadataProperty("lorem", Node.from(true)) + .build(); ModelTransformer transformer = ModelTransformer.create(); // Remove boolean and number metadata key-value pairs. Model result = transformer.filterMetadata(model, (k, v) -> !v.isBooleanNode() && !v.isNumberNode()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterShapesTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterShapesTest.java index 9d1acdbbb47..34309f8d5c1 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterShapesTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterShapesTest.java @@ -30,14 +30,14 @@ public class FilterShapesTest { public void removesShapesThatMatchPredicate() { ShapeId aId = ShapeId.from("ns.foo#A"); StringShape a = StringShape.builder() - .id(aId) - .addTrait(new SensitiveTrait()) - .build(); + .id(aId) + .addTrait(new SensitiveTrait()) + .build(); ShapeId bId = ShapeId.from("ns.foo#B"); StringShape b = StringShape.builder().id(bId).build(); Model model = Model.builder().addShapes(a, b).build(); Model result = ModelTransformer.create() - .filterShapes(model, shape -> !shape.getTrait(SensitiveTrait.class).isPresent()); + .filterShapes(model, shape -> !shape.getTrait(SensitiveTrait.class).isPresent()); assertThat(result.shapes().count(), Matchers.is(1L)); assertThat(result.getShape(bId), Matchers.not(Optional.empty())); @@ -56,8 +56,8 @@ public void doesNotFilterListOrMapMembers() { MapShape map = MapShape.builder().id("ns.foo#Map").key(mapKey).value(mapValue).build(); Model model = Model.builder() - .addShapes(string, list, listMember, map, mapKey, mapValue) - .build(); + .addShapes(string, list, listMember, map, mapKey, mapValue) + .build(); Model result = ModelTransformer.create().filterShapes(model, shape -> !shape.isMemberShape()); // No members should be removed because they are not eligible. @@ -73,14 +73,14 @@ public void updatesStructureContainerWhenMemberIsRemoved() { MemberShape member2 = MemberShape.builder().id("ns.foo#Structure$member2").target("ns.foo#String").build(); MemberShape member3 = MemberShape.builder().id("ns.foo#Structure$member3").target("ns.foo#String").build(); StructureShape structure = StructureShape.builder() - .id("ns.foo#Structure") - .addMember(member1) - .addMember(member2) - .addMember(member3) - .build(); + .id("ns.foo#Structure") + .addMember(member1) + .addMember(member2) + .addMember(member3) + .build(); Model model = Model.builder() - .addShapes(string, structure, member1, member2, member3) - .build(); + .addShapes(string, structure, member1, member2, member3) + .build(); // Remove "member2" from the structure. Model result = ModelTransformer.create().filterShapes(model, shape -> { @@ -95,46 +95,46 @@ public void updatesStructureContainerWhenMemberIsRemoved() { // Make sure the structure was updated so that it no longer has the removed member shape. assertThat( - result.getShape(structure.getId()).get().asStructureShape().get().getMember("member1"), - Matchers.not(Optional.empty()) + result.getShape(structure.getId()).get().asStructureShape().get().getMember("member1"), + Matchers.not(Optional.empty()) ); assertThat( - result.getShape(structure.getId()).get().asStructureShape().get().getMember("member3"), - Matchers.not(Optional.empty()) + result.getShape(structure.getId()).get().asStructureShape().get().getMember("member3"), + Matchers.not(Optional.empty()) ); assertThat( - result.getShape(structure.getId()).get().asStructureShape().get().getMember("member2"), - Matchers.is(Optional.empty()) + result.getShape(structure.getId()).get().asStructureShape().get().getMember("member2"), + Matchers.is(Optional.empty()) ); } @Test public void removesTraitsWhenDefinitionIsRemoved() { StringShape bazTrait = StringShape.builder() - .id("ns.foo#baz") - .addTrait(TraitDefinition.builder().build()) - .build(); + .id("ns.foo#baz") + .addTrait(TraitDefinition.builder().build()) + .build(); StringShape barTrait = StringShape.builder() - .id("ns.foo#bar") - .addTrait(TraitDefinition.builder().build()) - .build(); + .id("ns.foo#bar") + .addTrait(TraitDefinition.builder().build()) + .build(); ShapeId shapeId1 = ShapeId.from("ns.foo#id1"); StringShape shape1 = StringShape.builder() - .id(shapeId1) - .addTrait(new DynamicTrait(ShapeId.from("foo.baz#foo"), Node.from(true))) - .addTrait(new SensitiveTrait()) - .build(); + .id(shapeId1) + .addTrait(new DynamicTrait(ShapeId.from("foo.baz#foo"), Node.from(true))) + .addTrait(new SensitiveTrait()) + .build(); ShapeId shapeId2 = ShapeId.from("ns.foo#id2"); StringShape shape2 = StringShape.builder() - .id(shapeId2) - .addTrait(new DynamicTrait(ShapeId.from("ns.foo#baz"), Node.from(true))) - .addTrait(new DynamicTrait(ShapeId.from("ns.foo#bar"), Node.from(true))) - .addTrait(new SensitiveTrait()) - .build(); + .id(shapeId2) + .addTrait(new DynamicTrait(ShapeId.from("ns.foo#baz"), Node.from(true))) + .addTrait(new DynamicTrait(ShapeId.from("ns.foo#bar"), Node.from(true))) + .addTrait(new SensitiveTrait()) + .build(); Model model = Model.builder() - .addShapes(shape1, shape2, bazTrait, barTrait) - .build(); + .addShapes(shape1, shape2, bazTrait, barTrait) + .build(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.filterShapes(model, shape -> !shape.getId().toString().equals("ns.foo#baz")); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterTraitsTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterTraitsTest.java index 0ada09a7e3a..360ed957e6a 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterTraitsTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterTraitsTest.java @@ -23,21 +23,21 @@ public class FilterTraitsTest { public void removesTraits() { ShapeId aId = ShapeId.from("ns.foo#A"); StringShape a = StringShape.builder() - .id(aId) - .addTrait(new SensitiveTrait()) - .addTrait(DeprecatedTrait.builder().build()) - .build(); + .id(aId) + .addTrait(new SensitiveTrait()) + .addTrait(DeprecatedTrait.builder().build()) + .build(); ShapeId bId = ShapeId.from("ns.foo#B"); StringShape b = StringShape.builder() - .id(bId) - .addTrait(new SensitiveTrait()) - .addTrait(DeprecatedTrait.builder().build()) - .build(); + .id(bId) + .addTrait(new SensitiveTrait()) + .addTrait(DeprecatedTrait.builder().build()) + .build(); Model model = Model.builder().addShapes(a, b).build(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.filterTraits( - model, - (shape, trait) -> !trait.toShapeId().equals(ShapeId.from("smithy.api#sensitive")) + model, + (shape, trait) -> !trait.toShapeId().equals(ShapeId.from("smithy.api#sensitive")) ); assertThat(result.shapes().count(), Matchers.is(2L)); @@ -51,17 +51,17 @@ public void removesTraits() { public void removesTraitsWithComposedPredicate() { ShapeId aId = ShapeId.from("ns.foo#A"); StringShape a = StringShape.builder() - .id(aId) - .addTrait(new SensitiveTrait()) - .addTrait(new DocumentationTrait("docs", SourceLocation.NONE)) - .addTrait(DeprecatedTrait.builder().build()) - .build(); + .id(aId) + .addTrait(new SensitiveTrait()) + .addTrait(new DocumentationTrait("docs", SourceLocation.NONE)) + .addTrait(DeprecatedTrait.builder().build()) + .build(); Model model = Model.builder().addShape(a).build(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.filterTraits( - model, - (shape, trait) -> !trait.toShapeId().equals(ShapeId.from("smithy.api#sensitive")) - && !trait.toShapeId().equals(ShapeId.from("smithy.api#documentation")) + model, + (shape, trait) -> !trait.toShapeId().equals(ShapeId.from("smithy.api#sensitive")) + && !trait.toShapeId().equals(ShapeId.from("smithy.api#documentation")) ); assertThat(result.shapes().count(), Matchers.is(1L)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FlattenPaginationInfoTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FlattenPaginationInfoTest.java index c3038c69aec..c29853b61ba 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FlattenPaginationInfoTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FlattenPaginationInfoTest.java @@ -21,9 +21,9 @@ public class FlattenPaginationInfoTest { @Test void compareTransform() { Model before = Model.assembler() - .addImport(FlattenPaginationInfoTest.class.getResource("flatten-pagination-before.smithy")) - .assemble() - .unwrap(); + .addImport(FlattenPaginationInfoTest.class.getResource("flatten-pagination-before.smithy")) + .assemble() + .unwrap(); ServiceShape service = before.expectShape(serviceId).asServiceShape().get(); Model result = ModelTransformer.create().flattenPaginationInfoIntoOperations(before, service); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/IntegTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/IntegTest.java index a72f1f3f91a..ab20a35c64e 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/IntegTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/IntegTest.java @@ -21,9 +21,9 @@ public class IntegTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(IntegTest.class.getResource("integration-test-model.json")) - .assemble() - .unwrap(); + .addImport(IntegTest.class.getResource("integration-test-model.json")) + .assemble() + .unwrap(); } @Test @@ -63,8 +63,8 @@ public void removesUnreferencedShapes() { assertThat(result.getShape(ShapeId.from("ns.foo#CreateMyResourceOutput")), Matchers.is(Optional.empty())); assertThat(result.getShape(ShapeId.from("ns.foo#MyResourceOperationInput")), Matchers.is(Optional.empty())); assertThat( - result.getShape(ShapeId.from("ns.foo#MyResourceOperationInputString")), - Matchers.is(Optional.empty()) + result.getShape(ShapeId.from("ns.foo#MyResourceOperationInputString")), + Matchers.is(Optional.empty()) ); } @@ -81,8 +81,8 @@ public void removesUnreferencedShapesWithFilter() { assertThat(result.getShape(ShapeId.from("ns.foo#CreateMyResourceOutput")), Matchers.is(Optional.empty())); assertThat(result.getShape(ShapeId.from("ns.foo#MyResourceOperationInput")), Matchers.is(Optional.empty())); assertThat( - result.getShape(ShapeId.from("ns.foo#MyResourceOperationInputString")), - Matchers.not(Optional.empty()) + result.getShape(ShapeId.from("ns.foo#MyResourceOperationInputString")), + Matchers.not(Optional.empty()) ); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/MakeIdempotencyTokenClientOptionalTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/MakeIdempotencyTokenClientOptionalTest.java index 04f431f9c2b..68db5845e5c 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/MakeIdempotencyTokenClientOptionalTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/MakeIdempotencyTokenClientOptionalTest.java @@ -20,9 +20,9 @@ public class MakeIdempotencyTokenClientOptionalTest { @Test void compareTransform() { Model before = Model.assembler() - .addImport(FlattenPaginationInfoTest.class.getResource("idempotency-token.smithy")) - .assemble() - .unwrap(); + .addImport(FlattenPaginationInfoTest.class.getResource("idempotency-token.smithy")) + .assemble() + .unwrap(); Model result = ModelTransformer.create().makeIdempotencyTokensClientOptional(before); Shape input = result.expectShape(operationInput); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapShapesTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapShapesTest.java index 90b5adb5323..f8e3222b2ee 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapShapesTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapShapesTest.java @@ -25,9 +25,9 @@ public class MapShapesTest { public void replacesMappedShapes() { ShapeId shapeId = ShapeId.from("ns.foo#id1"); StringShape shape = StringShape.builder() - .id(shapeId) - .addTrait(new SensitiveTrait()) - .build(); + .id(shapeId) + .addTrait(new SensitiveTrait()) + .build(); Model model = Model.builder().addShape(shape).build(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.mapShapes(model, s -> Shape.shapeToBuilder(s).removeTrait("sensitive").build()); @@ -51,18 +51,18 @@ public void throwsWhenMapperChangesShapeId() { public void mapsUsingAllMappers() { ShapeId shapeId = ShapeId.from("ns.foo#id1"); StringShape shape = StringShape.builder() - .id(shapeId) - .addTrait(new SensitiveTrait()) - .addTrait(new DocumentationTrait("docs", SourceLocation.NONE)) - .build(); + .id(shapeId) + .addTrait(new SensitiveTrait()) + .addTrait(new DocumentationTrait("docs", SourceLocation.NONE)) + .build(); Model model = Model.builder().addShape(shape).build(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.mapShapes( - model, - Arrays.asList( - s -> Shape.shapeToBuilder(s).removeTrait("sensitive").build(), - s -> Shape.shapeToBuilder(s).removeTrait("documentation").build() - ) + model, + Arrays.asList( + s -> Shape.shapeToBuilder(s).removeTrait("sensitive").build(), + s -> Shape.shapeToBuilder(s).removeTrait("documentation").build() + ) ); assertThat(result.expectShape(shapeId).getTrait(SensitiveTrait.class), Matchers.is(Optional.empty())); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapTraitsTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapTraitsTest.java index 6f376ef5f37..eceffa5ec73 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapTraitsTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapTraitsTest.java @@ -24,9 +24,9 @@ public class MapTraitsTest { public void doesNotReplaceUnchangedShapes() { ShapeId shapeId = ShapeId.from("ns.foo#id1"); StringShape shape = StringShape.builder() - .id(shapeId) - .addTrait(new SensitiveTrait()) - .build(); + .id(shapeId) + .addTrait(new SensitiveTrait()) + .build(); Model model = Model.builder().addShape(shape).build(); ModelTransformer transformer = ModelTransformer.create(); transformer.mapTraits(model, (s, t) -> t); @@ -36,40 +36,43 @@ public void doesNotReplaceUnchangedShapes() { public void appliesAllMappersToShapes() { ShapeId shapeId = ShapeId.from("ns.foo#id1"); StringShape shape = StringShape.builder() - .id(shapeId) - .addTrait(DeprecatedTrait.builder().message("foo").build()) - .addTrait(new DocumentationTrait("docs", SourceLocation.NONE)) - .build(); + .id(shapeId) + .addTrait(DeprecatedTrait.builder().message("foo").build()) + .addTrait(new DocumentationTrait("docs", SourceLocation.NONE)) + .build(); Model model = Model.builder().addShape(shape).build(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.mapTraits( - model, - Arrays.asList( - (s, t) -> { - if (t instanceof DeprecatedTrait) { - return DeprecatedTrait.builder().sourceLocation(t.getSourceLocation()).message("baz").build(); - } else { - return t; - } - }, - (s, t) -> { - if (t instanceof DocumentationTrait) { - return new DocumentationTrait("changed", t.getSourceLocation()); - } else { - return t; - } - } - ) + model, + Arrays.asList( + (s, t) -> { + if (t instanceof DeprecatedTrait) { + return DeprecatedTrait.builder() + .sourceLocation(t.getSourceLocation()) + .message("baz") + .build(); + } else { + return t; + } + }, + (s, t) -> { + if (t instanceof DocumentationTrait) { + return new DocumentationTrait("changed", t.getSourceLocation()); + } else { + return t; + } + } + ) ); assertThat(result.expectShape(shapeId).getTrait(DeprecatedTrait.class), Matchers.not(Optional.empty())); assertThat( - result.expectShape(shapeId).getTrait(DeprecatedTrait.class).get().getMessage().get(), - Matchers.equalTo("baz") + result.expectShape(shapeId).getTrait(DeprecatedTrait.class).get().getMessage().get(), + Matchers.equalTo("baz") ); assertThat( - result.expectShape(shapeId).getTrait(DocumentationTrait.class).get().getValue(), - Matchers.equalTo("changed") + result.expectShape(shapeId).getTrait(DocumentationTrait.class).get().getValue(), + Matchers.equalTo("changed") ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/ModelTransformerTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/ModelTransformerTest.java index 74d21923ab9..fd22dbbc963 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/ModelTransformerTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/ModelTransformerTest.java @@ -34,9 +34,9 @@ public class ModelTransformerTest { private Model createTestModel() { return Model.assembler() - .addImport(ModelTransformerTest.class.getResource("test-model.json")) - .assemble() - .unwrap(); + .addImport(ModelTransformerTest.class.getResource("test-model.json")) + .assemble() + .unwrap(); } @Test @@ -48,16 +48,16 @@ public void discoversOnRemoveClassesWithSpi() { assertThat(result.expectShape(operation), Matchers.not(Optional.empty())); assertThat( - result.expectShape(operation).asOperationShape().map(OperationShape::getInputShape), - Matchers.equalTo(Optional.of(UnitTypeTrait.UNIT)) + result.expectShape(operation).asOperationShape().map(OperationShape::getInputShape), + Matchers.equalTo(Optional.of(UnitTypeTrait.UNIT)) ); assertThat( - result.expectShape(operation).asOperationShape().map(OperationShape::getOutputShape), - Matchers.equalTo(Optional.of(UnitTypeTrait.UNIT)) + result.expectShape(operation).asOperationShape().map(OperationShape::getOutputShape), + Matchers.equalTo(Optional.of(UnitTypeTrait.UNIT)) ); assertThat( - result.expectShape(operation).asOperationShape().map(OperationShape::getErrors), - Matchers.equalTo(Optional.of(Collections.emptyList())) + result.expectShape(operation).asOperationShape().map(OperationShape::getErrors), + Matchers.equalTo(Optional.of(Collections.emptyList())) ); } @@ -70,8 +70,8 @@ public void removesTraitShapesButNotTraitUsage() { assertThat(nonTraitShapes.getShape(operation), Matchers.not(Optional.empty())); assertThat( - nonTraitShapes.getShape(operation).get().getTrait(ReadonlyTrait.class), - Matchers.not(Optional.empty()) + nonTraitShapes.getShape(operation).get().getTrait(ReadonlyTrait.class), + Matchers.not(Optional.empty()) ); assertTrue(nonTraitShapes.getShape(operation).get().hasTrait("ns.foo#MyTrait")); assertTrue(nonTraitShapes.getShape(operation).get().hasTrait("ns.foo#MyOtherTrait")); @@ -90,8 +90,8 @@ public void removesTraitShapesExcludingFilteredButNotTraitUsage() { assertThat(nonTraitShapes.getShape(operation), Matchers.not(Optional.empty())); assertThat( - nonTraitShapes.getShape(operation).get().getTrait(ReadonlyTrait.class), - Matchers.not(Optional.empty()) + nonTraitShapes.getShape(operation).get().getTrait(ReadonlyTrait.class), + Matchers.not(Optional.empty()) ); assertTrue(nonTraitShapes.getShape(operation).get().hasTrait("ns.foo#MyTrait")); assertTrue(nonTraitShapes.getShape(operation).get().hasTrait("ns.foo#MyOtherTrait")); @@ -114,27 +114,27 @@ public void canFilterAndRemoveMixinsWhenMixinsArePresent() { Model.Builder builder = Model.builder(); StringShape string = StringShape.builder().id("smithy.example#String").build(); StructureShape mixin1 = StructureShape.builder() - .id("smithy.example#Mixin1") - .addTrait(MixinTrait.builder().build()) - .addMember("a", string.getId()) - .build(); + .id("smithy.example#Mixin1") + .addTrait(MixinTrait.builder().build()) + .addMember("a", string.getId()) + .build(); StructureShape mixin2 = StructureShape.builder() - .id("smithy.example#Mixin2") - .addMember("b", string.getId()) - .addTrait(MixinTrait.builder().build()) - .build(); + .id("smithy.example#Mixin2") + .addMember("b", string.getId()) + .addTrait(MixinTrait.builder().build()) + .build(); StructureShape mixin3 = StructureShape.builder() - .id("smithy.example#Mixin3") - .addMember("c", string.getId()) - .addTrait(MixinTrait.builder().build()) - .addMixin(mixin2) - .build(); + .id("smithy.example#Mixin3") + .addMember("c", string.getId()) + .addTrait(MixinTrait.builder().build()) + .addMixin(mixin2) + .build(); StructureShape concrete = StructureShape.builder() - .id("smithy.example#Concrete") - .addMember("d", string.getId()) - .addMixin(mixin1) - .addMixin(mixin3) - .build(); + .id("smithy.example#Concrete") + .addMember("d", string.getId()) + .addMixin(mixin1) + .addMixin(mixin3) + .build(); builder.addShapes(mixin1, mixin2, mixin3, concrete); Model model = builder.build(); Model result = transformer.flattenAndRemoveMixins(model); @@ -143,8 +143,8 @@ public void canFilterAndRemoveMixinsWhenMixinsArePresent() { assertThat(result.toSet(), Matchers.not(Matchers.hasItem(mixin2))); assertThat(result.toSet(), Matchers.not(Matchers.hasItem(mixin3))); assertThat( - result.getShape(concrete.getId()).get(), - Matchers.equalTo(concrete.toBuilder().flattenMixins().build()) + result.getShape(concrete.getId()).get(), + Matchers.equalTo(concrete.toBuilder().flattenMixins().build()) ); } @@ -154,21 +154,21 @@ public void canFilterAndRemoveMixinsWhenUnusedMixinsArePresent() { Model.Builder builder = Model.builder(); StringShape string = StringShape.builder().id("smithy.example#String").build(); StructureShape mixin1 = StructureShape.builder() - .id("smithy.example#Mixin1") - .addTrait(MixinTrait.builder().build()) - .addMember("a", string.getId()) - .build(); + .id("smithy.example#Mixin1") + .addTrait(MixinTrait.builder().build()) + .addMember("a", string.getId()) + .build(); StructureShape mixin2 = StructureShape.builder() - .id("smithy.example#Mixin2") - .addMember("b", string.getId()) - .addTrait(MixinTrait.builder().build()) - .build(); + .id("smithy.example#Mixin2") + .addMember("b", string.getId()) + .addTrait(MixinTrait.builder().build()) + .build(); StructureShape mixin3 = StructureShape.builder() - .id("smithy.example#Mixin3") - .addMember("c", string.getId()) - .addTrait(MixinTrait.builder().build()) - .addMixin(mixin2) - .build(); + .id("smithy.example#Mixin3") + .addMember("c", string.getId()) + .addTrait(MixinTrait.builder().build()) + .addMixin(mixin2) + .build(); builder.addShapes(mixin1, mixin2, mixin3); Model model = builder.build(); Model result = transformer.flattenAndRemoveMixins(model); @@ -182,13 +182,13 @@ public void canFilterAndRemoveMixinsWhenUnusedMixinsArePresent() { @MethodSource("flattenShapesData") public void flattenShapes(String name) { Model original = Model.assembler() - .addImport(Model.class.getResource("loader/valid/mixins/" + name + ".smithy")) - .assemble() - .unwrap(); + .addImport(Model.class.getResource("loader/valid/mixins/" + name + ".smithy")) + .assemble() + .unwrap(); Model expectedModel = Model.assembler() - .addImport(Model.class.getResource("loader/valid/mixins/" + name + ".flattened.smithy")) - .assemble() - .unwrap(); + .addImport(Model.class.getResource("loader/valid/mixins/" + name + ".flattened.smithy")) + .assemble() + .unwrap(); Model flattened = ModelTransformer.create().flattenAndRemoveMixins(original); Node result = ModelSerializer.builder().build().serialize(flattened); @@ -203,19 +203,19 @@ public void flattenShapes(String name) { public static String[] flattenShapesData() { return new String[]{ - "loads-mixins", - "mixins-with-members", - "mixins-with-members-and-traits", - "mixins-with-member-override-1", - "mixins-with-member-override-2", - "mixins-with-member-override-3", - "mixins-with-member-override-4", - "mixins-with-mixin-local-traits", - "operations", - "resources", - "services", - "idl-mixins-redefine-member", - "enum-mixins" + "loads-mixins", + "mixins-with-members", + "mixins-with-members-and-traits", + "mixins-with-member-override-1", + "mixins-with-member-override-2", + "mixins-with-member-override-3", + "mixins-with-member-override-4", + "mixins-with-mixin-local-traits", + "operations", + "resources", + "services", + "idl-mixins-redefine-member", + "enum-mixins" }; } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/RemoveInvalidDefaultsTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/RemoveInvalidDefaultsTest.java index 4813021bd15..64109c5727f 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/RemoveInvalidDefaultsTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/RemoveInvalidDefaultsTest.java @@ -13,13 +13,13 @@ public class RemoveInvalidDefaultsTest { @Test public void removeInvalidDefaultsBasedOnRangeTrait() { Model input = Model.assembler() - .addImport(getClass().getResource("bad-defaults-range-trait.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("bad-defaults-range-trait.smithy")) + .assemble() + .unwrap(); Model output = Model.assembler() - .addImport(getClass().getResource("bad-defaults-range-trait.fixed.smithy")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("bad-defaults-range-trait.fixed.smithy")) + .assemble() + .unwrap(); ModelTransformer transformer = ModelTransformer.create(); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/RemoveShapesTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/RemoveShapesTest.java index ae0586fb469..caf7182822d 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/RemoveShapesTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/RemoveShapesTest.java @@ -53,15 +53,15 @@ public class RemoveShapesTest { @BeforeAll public static void before() { mixinsModel = Model.assembler() - .addImport(RemoveShapesTest.class.getResource("mixin-removal/model.smithy")) - .assemble() - .unwrap(); + .addImport(RemoveShapesTest.class.getResource("mixin-removal/model.smithy")) + .assemble() + .unwrap(); } private void assertContainerMembersAreRemoved(Shape container, List members) { Model.Builder builder = Model.builder() - .addShape(container) - .addShape(StringShape.builder().id(STRING_TARGET).build()); + .addShape(container) + .addShape(StringShape.builder().id(STRING_TARGET).build()); members.forEach(builder::addShape); Model model = builder.build(); ModelTransformer transformer = ModelTransformer.create(); @@ -75,9 +75,9 @@ private void assertContainerMembersAreRemoved(Shape container, List membe @Test public void removesListMemberWhenRemoved() { MemberShape member = MemberShape.builder() - .id(ShapeId.from("ns.foo#Container$member")) - .target(STRING_TARGET) - .build(); + .id(ShapeId.from("ns.foo#Container$member")) + .target(STRING_TARGET) + .build(); ListShape container = ListShape.builder().id(ShapeId.from("ns.foo#Container")).member(member).build(); assertContainerMembersAreRemoved(container, Collections.singletonList(member)); } @@ -85,13 +85,13 @@ public void removesListMemberWhenRemoved() { @Test public void removesMapMembersWhenRemoved() { MemberShape key = MemberShape.builder() - .id(ShapeId.from("ns.foo#Container$key")) - .target(STRING_TARGET) - .build(); + .id(ShapeId.from("ns.foo#Container$key")) + .target(STRING_TARGET) + .build(); MemberShape value = MemberShape.builder() - .id(ShapeId.from("ns.foo#Container$value")) - .target(STRING_TARGET) - .build(); + .id(ShapeId.from("ns.foo#Container$value")) + .target(STRING_TARGET) + .build(); MapShape container = MapShape.builder().id(ShapeId.from("ns.foo#Container")).key(key).value(value).build(); assertContainerMembersAreRemoved(container, Arrays.asList(key, value)); } @@ -99,22 +99,22 @@ public void removesMapMembersWhenRemoved() { @Test public void removesEnumMembersWhenRemoved() { EnumShape container = EnumShape.builder() - .id(ShapeId.from("ns.foo#Enum")) - .addMember("foo", "foo") - .build(); + .id(ShapeId.from("ns.foo#Enum")) + .addMember("foo", "foo") + .build(); assertContainerMembersAreRemoved(container, new ArrayList<>(container.members())); } @Test public void notAllEnumMembersCanBeRemoved() { EnumShape container = EnumShape.builder() - .id(ShapeId.from("ns.foo#Enum")) - .addMember("foo", "foo") - .build(); + .id(ShapeId.from("ns.foo#Enum")) + .addMember("foo", "foo") + .build(); Model.Builder builder = Model.builder() - .addShape(container) - .addShape(StringShape.builder().id(STRING_TARGET).build()); + .addShape(container) + .addShape(StringShape.builder().id(STRING_TARGET).build()); container.members().forEach(builder::addShape); Model model = builder.build(); ModelTransformer transformer = ModelTransformer.create(); @@ -124,22 +124,22 @@ public void notAllEnumMembersCanBeRemoved() { @Test public void removesIntEnumMembersWhenRemoved() { IntEnumShape container = IntEnumShape.builder() - .id(ShapeId.from("ns.foo#Enum")) - .addMember("foo", 1) - .build(); + .id(ShapeId.from("ns.foo#Enum")) + .addMember("foo", 1) + .build(); assertContainerMembersAreRemoved(container, new ArrayList<>(container.members())); } @Test public void notAllIntEnumMembersCanBeRemoved() { IntEnumShape container = IntEnumShape.builder() - .id(ShapeId.from("ns.foo#Enum")) - .addMember("foo", 1) - .build(); + .id(ShapeId.from("ns.foo#Enum")) + .addMember("foo", 1) + .build(); Model.Builder builder = Model.builder() - .addShape(container) - .addShape(StringShape.builder().id(STRING_TARGET).build()); + .addShape(container) + .addShape(StringShape.builder().id(STRING_TARGET).build()); container.members().forEach(builder::addShape); Model model = builder.build(); ModelTransformer transformer = ModelTransformer.create(); @@ -149,51 +149,51 @@ public void notAllIntEnumMembersCanBeRemoved() { @Test public void removesStructureMembersWhenRemoved() { MemberShape a = MemberShape.builder() - .id(ShapeId.from("ns.foo#Container$a")) - .target(STRING_TARGET) - .build(); + .id(ShapeId.from("ns.foo#Container$a")) + .target(STRING_TARGET) + .build(); MemberShape b = MemberShape.builder() - .id(ShapeId.from("ns.foo#Container$b")) - .target(STRING_TARGET) - .build(); + .id(ShapeId.from("ns.foo#Container$b")) + .target(STRING_TARGET) + .build(); StructureShape container = StructureShape.builder() - .id(ShapeId.from("ns.foo#Container")) - .addMember(a) - .addMember(b) - .build(); + .id(ShapeId.from("ns.foo#Container")) + .addMember(a) + .addMember(b) + .build(); assertContainerMembersAreRemoved(container, Arrays.asList(a, b)); } @Test public void removesTaggedUnionMembersWhenRemoved() { MemberShape a = MemberShape.builder() - .id(ShapeId.from("ns.foo#Container$a")) - .target(STRING_TARGET) - .build(); + .id(ShapeId.from("ns.foo#Container$a")) + .target(STRING_TARGET) + .build(); MemberShape b = MemberShape.builder() - .id(ShapeId.from("ns.foo#Container$b")) - .target(STRING_TARGET) - .build(); + .id(ShapeId.from("ns.foo#Container$b")) + .target(STRING_TARGET) + .build(); UnionShape container = UnionShape.builder() - .id(ShapeId.from("ns.foo#Container")) - .addMember(a) - .addMember(b) - .build(); + .id(ShapeId.from("ns.foo#Container")) + .addMember(a) + .addMember(b) + .build(); assertContainerMembersAreRemoved(container, Arrays.asList(a, b)); } @Test public void removesOperationsFromResourcesWhenOperationRemoved() { ResourceShape container = ResourceShape.builder() - .id(ShapeId.from("ns.foo#Container")) - .addOperation("ns.foo#A") - .create(ShapeId.from("ns.foo#B")) - .addOperation("ns.foo#C") - .build(); + .id(ShapeId.from("ns.foo#Container")) + .addOperation("ns.foo#A") + .create(ShapeId.from("ns.foo#B")) + .addOperation("ns.foo#C") + .build(); OperationShape a = OperationShape.builder() - .id("ns.foo#A") - .addTrait(new ReadonlyTrait()) - .build(); + .id("ns.foo#A") + .addTrait(new ReadonlyTrait()) + .build(); OperationShape b = OperationShape.builder().id("ns.foo#B").build(); OperationShape c = OperationShape.builder().id("ns.foo#C").build(); @@ -205,17 +205,17 @@ public void removesOperationsFromResourcesWhenOperationRemoved() { assertThat(result.getShape(container.getId()), Matchers.not(Optional.empty())); assertThat(result.getShape(c.getId()), Matchers.not(Optional.empty())); assertThat( - result.expectShape(container.getId()).asResourceShape().get().getOperations(), - Matchers.contains(c.getId()) + result.expectShape(container.getId()).asResourceShape().get().getOperations(), + Matchers.contains(c.getId()) ); } @Test public void removesTraitsFromAuthDefinitionWhenReferenceRemoved() { Model model = Model.assembler() - .addImport(getClass().getResource("remove-shapes.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("remove-shapes.json")) + .assemble() + .unwrap(); ShapeId removedId = ShapeId.from("ns.foo#bar"); Shape removedShape = model.expectShape(removedId); @@ -232,9 +232,9 @@ public void removesTraitsFromAuthDefinitionWhenReferenceRemoved() { @Test public void removesTraitsFromProtocolDefinitionWhenReferenceRemoved() { Model model = Model.assembler() - .addImport(getClass().getResource("remove-shapes.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("remove-shapes.json")) + .assemble() + .unwrap(); ShapeId removedId = ShapeId.from("ns.foo#baz"); Shape removedShape = model.expectShape(removedId); @@ -252,10 +252,10 @@ public void removesTraitsFromProtocolDefinitionWhenReferenceRemoved() { public void removingShapeUpdatesServiceRename() { StringShape string = StringShape.builder().id("example.foo#A").build(); ServiceShape service = ServiceShape.builder() - .id("com.foo#Example") - .version("1") - .putRename(ShapeId.from("example.foo#A"), "AA") - .build(); + .id("com.foo#Example") + .version("1") + .putRename(ShapeId.from("example.foo#A"), "AA") + .build(); Model model = Model.builder().addShapes(string, service).build(); ModelTransformer transformer = ModelTransformer.create(); @@ -271,27 +271,27 @@ public void removingMixinsRemovesThemFromShapes() { Model.Builder builder = Model.builder(); StringShape string = StringShape.builder().id("smithy.example#String").build(); StructureShape mixin1 = StructureShape.builder() - .id("smithy.example#Mixin1") - .addTrait(MixinTrait.builder().build()) - .addMember("a", string.getId()) - .build(); + .id("smithy.example#Mixin1") + .addTrait(MixinTrait.builder().build()) + .addMember("a", string.getId()) + .build(); StructureShape mixin2 = StructureShape.builder() - .id("smithy.example#Mixin2") - .addMember("b", string.getId()) - .addTrait(MixinTrait.builder().build()) - .build(); + .id("smithy.example#Mixin2") + .addMember("b", string.getId()) + .addTrait(MixinTrait.builder().build()) + .build(); StructureShape mixin3 = StructureShape.builder() - .id("smithy.example#Mixin3") - .addMember("c", string.getId()) - .addTrait(MixinTrait.builder().build()) - .addMixin(mixin2) - .build(); + .id("smithy.example#Mixin3") + .addMember("c", string.getId()) + .addTrait(MixinTrait.builder().build()) + .addMixin(mixin2) + .build(); StructureShape concrete = StructureShape.builder() - .id("smithy.example#Concrete") - .addMember("d", string.getId()) - .addMixin(mixin1) - .addMixin(mixin3) - .build(); + .id("smithy.example#Concrete") + .addMember("d", string.getId()) + .addMixin(mixin1) + .addMixin(mixin3) + .build(); builder.addShapes(mixin1, mixin2, mixin3, concrete); Model model = builder.build(); @@ -324,9 +324,9 @@ public void RemoveMixinsTest(String mixinFile, String[] shapeNamesToRemove) { Model result = ModelTransformer.create().removeShapes(start, shapesToRemove); Model expected = Model.assembler() - .addImport(RemoveShapesTest.class.getResource("mixin-removal/" + mixinFile)) - .assemble() - .unwrap(); + .addImport(RemoveShapesTest.class.getResource("mixin-removal/" + mixinFile)) + .assemble() + .unwrap(); ModelSerializer serializer = ModelSerializer.builder().build(); Node.assertEquals(serializer.serialize(result), serializer.serialize(expected)); @@ -334,20 +334,20 @@ public void RemoveMixinsTest(String mixinFile, String[] shapeNamesToRemove) { public static Collection removeMixinData() { return Arrays.asList( - new Object[][]{ - {"without-a.smithy", new String[]{"A"}}, - {"without-a2.smithy", new String[]{"A2"}}, - {"without-a3.smithy", new String[]{"A3"}}, - {"without-a-a2.smithy", new String[]{"A", "A2"}}, - {"without-a-a2-a3.smithy", new String[]{"A", "A2", "A3"}}, - {"without-a-a2-a3-b-b2-b3.smithy", new String[]{"A", "A2", "A3", "B", "B2", "B3"}}, - {"without-a-b.smithy", new String[]{"A", "B"}}, - {"without-b.smithy", new String[]{"B"}}, - {"without-b2.smithy", new String[]{"B2"}}, - {"without-b3.smithy", new String[]{"B3"}}, - {"without-c.smithy", new String[]{"C"}}, - {"without-d.smithy", new String[]{"D"}} - } + new Object[][]{ + {"without-a.smithy", new String[]{"A"}}, + {"without-a2.smithy", new String[]{"A2"}}, + {"without-a3.smithy", new String[]{"A3"}}, + {"without-a-a2.smithy", new String[]{"A", "A2"}}, + {"without-a-a2-a3.smithy", new String[]{"A", "A2", "A3"}}, + {"without-a-a2-a3-b-b2-b3.smithy", new String[]{"A", "A2", "A3", "B", "B2", "B3"}}, + {"without-a-b.smithy", new String[]{"A", "B"}}, + {"without-b.smithy", new String[]{"B"}}, + {"without-b2.smithy", new String[]{"B2"}}, + {"without-b3.smithy", new String[]{"B3"}}, + {"without-c.smithy", new String[]{"C"}}, + {"without-d.smithy", new String[]{"D"}} + } ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/RenameShapesTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/RenameShapesTest.java index 0a9924ce008..c47df4eb889 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/RenameShapesTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/RenameShapesTest.java @@ -39,8 +39,8 @@ public void returnsUnmodifiedModelIfGivenEmptyRenameMapping() { ShapeId stringId = ShapeId.from("ns.foo#String"); StringShape fooTarget = StringShape.builder().id(stringId).build(); Model model = Model.builder() - .addShapes(fooTarget) - .build(); + .addShapes(fooTarget) + .build(); ModelTransformer transformer = ModelTransformer.create(); Map renamed = new HashMap<>(); Model result = transformer.renameShapes(model, renamed); @@ -54,8 +54,8 @@ public void returnsUnmodifiedModelIfToAndFromAreEqual() { ShapeId stringId = ShapeId.from("ns.foo#String"); StringShape target = StringShape.builder().id(stringId).build(); Model model = Model.builder() - .addShapes(target) - .build(); + .addShapes(target) + .build(); ModelTransformer transformer = ModelTransformer.create(); Map renamed = new HashMap<>(); renamed.put(stringId, stringId); @@ -77,8 +77,8 @@ public void returnsModelWithRenamedStringShape() { MemberShape valueMember = MemberShape.builder().id(valueId).target(fromStringId).build(); MapShape container = MapShape.builder().id(containerId).key(keyMember).value(valueMember).build(); Model model = Model.builder() - .addShapes(target, keyMember, valueMember, container) - .build(); + .addShapes(target, keyMember, valueMember, container) + .build(); ModelTransformer transformer = ModelTransformer.create(); ShapeId toStringId = ShapeId.from("ns.bar#String"); @@ -93,9 +93,9 @@ public void returnsModelWithRenamedStringShape() { @Test public void updatesMetadataReferences() { Model model = Model.assembler() - .addImport(IntegTest.class.getResource("rename-shape-test-model.json")) - .assemble() - .unwrap(); + .addImport(IntegTest.class.getResource("rename-shape-test-model.json")) + .assemble() + .unwrap(); Map renamed = new HashMap<>(); ShapeId fooUnreferenced = ShapeId.from("ns.foo#UnreferencedString"); @@ -111,9 +111,9 @@ public void updatesMetadataReferences() { @Test public void updatesIdRefValues() { Model model = Model.assembler() - .addImport(IntegTest.class.getResource("rename-shape-test-model.json")) - .assemble() - .unwrap(); + .addImport(IntegTest.class.getResource("rename-shape-test-model.json")) + .assemble() + .unwrap(); Map renamed = new HashMap<>(); ShapeId fromId = ShapeId.from("ns.foo#OldShape"); @@ -133,9 +133,9 @@ public void updatesIdRefValues() { @Test public void updatesShapeNamesAndReferences() { Model model = Model.assembler() - .addImport(IntegTest.class.getResource("rename-shape-test-model.json")) - .assemble() - .unwrap(); + .addImport(IntegTest.class.getResource("rename-shape-test-model.json")) + .assemble() + .unwrap(); Map renamed = new HashMap<>(); // Service @@ -204,9 +204,9 @@ public void updatesShapeNamesAndReferences() { assertTrue(resource.getAllOperations().contains(toOtherOperation)); StructureShape operationInput = result.getShape(ShapeId.from("ns.foo#MyOperationInput")) - .get() - .asStructureShape() - .get(); + .get() + .asStructureShape() + .get(); MemberShape struct = operationInput.getMember("struct").get(); MemberShape list = operationInput.getMember("list").get(); MemberShape map = operationInput.getMember("map").get(); @@ -237,8 +237,8 @@ public void updatesListMembersWhenContainerUpdated() { MemberShape member = MemberShape.builder().id(memberId).target(target).build(); ListShape container = ListShape.builder().id(containerId).addMember(member).build(); Model model = Model.builder() - .addShapes(target, member, container) - .build(); + .addShapes(target, member, container) + .build(); ModelTransformer transformer = ModelTransformer.create(); ShapeId newContainerId = ShapeId.from("ns.bar#Baz"); ShapeId newMemberId = ShapeId.from("ns.bar#Baz$member"); @@ -264,8 +264,8 @@ public void updatesMapMembersWhenContainerUpdated() { MemberShape valueMember = MemberShape.builder().id(valueId).target(stringId).build(); MapShape container = MapShape.builder().id(containerId).key(keyMember).value(valueMember).build(); Model model = Model.builder() - .addShapes(target, keyMember, valueMember, container) - .build(); + .addShapes(target, keyMember, valueMember, container) + .build(); ModelTransformer transformer = ModelTransformer.create(); ShapeId newContainerId = ShapeId.from("ns.bar#Baz"); ShapeId newKeyId = ShapeId.from("ns.bar#Baz$key"); @@ -291,8 +291,8 @@ public void updatesSetMembersWhenContainerUpdated() { MemberShape member = MemberShape.builder().id(memberId).target(target).build(); SetShape container = SetShape.builder().id(containerId).addMember(member).build(); Model model = Model.builder() - .addShapes(target, member, container) - .build(); + .addShapes(target, member, container) + .build(); ModelTransformer transformer = ModelTransformer.create(); ShapeId newContainerId = ShapeId.from("ns.bar#Baz"); ShapeId newMemberId = ShapeId.from("ns.bar#Baz$member"); @@ -316,8 +316,8 @@ public void updatesStructureMembersWhenContainerUpdated() { MemberShape member = MemberShape.builder().id(memberId).target(target).build(); StructureShape container = StructureShape.builder().id(containerId).addMember(member).build(); Model model = Model.builder() - .addShapes(target, member, container) - .build(); + .addShapes(target, member, container) + .build(); ModelTransformer transformer = ModelTransformer.create(); ShapeId newContainerId = ShapeId.from("ns.bar#Baz"); ShapeId newMemberId = ShapeId.from("ns.bar#Baz$member"); @@ -343,8 +343,8 @@ public void updatesUnionMembersWhenContainerUpdated() { MemberShape member = MemberShape.builder().id(memberId).target(target).build(); UnionShape container = UnionShape.builder().id(containerId).addMember(member).build(); Model model = Model.builder() - .addShapes(target, member, container) - .build(); + .addShapes(target, member, container) + .build(); ModelTransformer transformer = ModelTransformer.create(); ShapeId newContainerId = ShapeId.from("ns.bar#Baz"); ShapeId newMemberId = ShapeId.from("ns.bar#Baz$member"); @@ -363,18 +363,18 @@ public void updatesUnionMembersWhenContainerUpdated() { @Test public void transformationDoesntTriggerValidation() { Model model = Model.assembler() - .addImport(getClass().getResource("rename-with-resulting-errors.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("rename-with-resulting-errors.json")) + .assemble() + .unwrap(); Model result = ModelTransformer.create() - .renameShapes( - model, - Collections.singletonMap( - ShapeId.from("com.example.foo#string"), - ShapeId.from("com.example#string") - ) - ); + .renameShapes( + model, + Collections.singletonMap( + ShapeId.from("com.example.foo#string"), + ShapeId.from("com.example#string") + ) + ); assertTrue(result.getShape(ShapeId.from("com.example#string")).isPresent()); assertTrue(result.getShape(ShapeId.from("com.example#String")).isPresent()); @@ -383,62 +383,62 @@ public void transformationDoesntTriggerValidation() { @Test public void transformKeepsSyntheticBoxTraitsV2() { Model model1 = Model.assembler() - .addImport(ModelAssemblerTest.class.getResource("needs-downgrade-document-node.json")) - .assemble() - .unwrap(); + .addImport(ModelAssemblerTest.class.getResource("needs-downgrade-document-node.json")) + .assemble() + .unwrap(); ShapeId originalBoxedId = ShapeId.from("smithy.example#BoxDouble"); ShapeId originalPrimitiveId = ShapeId.from("smithy.example#PrimitiveDouble"); ShapeId updatedPrimitiveId = ShapeId.from("smithy.example2#PrimitiveDouble"); Model model2 = ModelTransformer.create() - .renameShapes( - model1, - MapUtils.of( - ShapeId.from("smithy.example#PrimitiveDouble"), - updatedPrimitiveId - ) - ); + .renameShapes( + model1, + MapUtils.of( + ShapeId.from("smithy.example#PrimitiveDouble"), + updatedPrimitiveId + ) + ); assertThat( - model2.expectShape(updatedPrimitiveId).getAllTraits(), - equalTo(model1.expectShape(originalPrimitiveId).getAllTraits()) + model2.expectShape(updatedPrimitiveId).getAllTraits(), + equalTo(model1.expectShape(originalPrimitiveId).getAllTraits()) ); assertThat( - model2.expectShape(originalBoxedId).getAllTraits(), - equalTo(model1.expectShape(originalBoxedId).getAllTraits()) + model2.expectShape(originalBoxedId).getAllTraits(), + equalTo(model1.expectShape(originalBoxedId).getAllTraits()) ); } @Test public void transformKeepsSyntheticBoxTraitsV1() { Model model1 = Model.assembler() - .addImport(ModelAssemblerTest.class.getResource("needs-upgrade-document-node.json")) - .assemble() - .unwrap(); + .addImport(ModelAssemblerTest.class.getResource("needs-upgrade-document-node.json")) + .assemble() + .unwrap(); ShapeId originalBoxedId = ShapeId.from("smithy.example#BoxDouble"); ShapeId originalPrimitiveId = ShapeId.from("smithy.example#PrimitiveDouble"); ShapeId updatedPrimitiveId = ShapeId.from("smithy.example2#PrimitiveDouble"); Model model2 = ModelTransformer.create() - .renameShapes( - model1, - MapUtils.of( - ShapeId.from("smithy.example#PrimitiveDouble"), - updatedPrimitiveId - ) - ); + .renameShapes( + model1, + MapUtils.of( + ShapeId.from("smithy.example#PrimitiveDouble"), + updatedPrimitiveId + ) + ); assertThat( - model2.expectShape(updatedPrimitiveId).getAllTraits(), - equalTo(model1.expectShape(originalPrimitiveId).getAllTraits()) + model2.expectShape(updatedPrimitiveId).getAllTraits(), + equalTo(model1.expectShape(originalPrimitiveId).getAllTraits()) ); assertThat( - model2.expectShape(originalBoxedId).getAllTraits(), - equalTo(model1.expectShape(originalBoxedId).getAllTraits()) + model2.expectShape(originalBoxedId).getAllTraits(), + equalTo(model1.expectShape(originalBoxedId).getAllTraits()) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/ReplaceShapesTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/ReplaceShapesTest.java index cb91d8ba702..fc15e7719d7 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/ReplaceShapesTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/ReplaceShapesTest.java @@ -39,21 +39,21 @@ public void cannotChangeComplexShapeTypes() { ShapeId shapeId = ShapeId.from("ns.foo#id1"); StringShape shape = StringShape.builder().id(shapeId).build(); Model model = Model.builder() - .addShape(shape) - .addShape(LongShape.builder().id("ns.foo#id2").build()) - .build(); + .addShape(shape) + .addShape(LongShape.builder().id("ns.foo#id2").build()) + .build(); ModelTransformer transformer = ModelTransformer.create(); transformer.mapShapes(model, s -> { if (s.getId().equals(shapeId)) { return StructureShape.builder() - .id(shapeId) - .addMember( - MemberShape.builder() - .id(ShapeId.from("ns.foo#id1$member1")) - .target("ns.foo#id2") - .build() - ) - .build(); + .id(shapeId) + .addMember( + MemberShape.builder() + .id(ShapeId.from("ns.foo#id1$member1")) + .target("ns.foo#id2") + .build() + ) + .build(); } return s; }); @@ -76,9 +76,9 @@ public void canExchangeSimilarListCollectionTypes() { ShapeId shapeId = ShapeId.from("ns.foo#id1"); ListShape shape = ListShape.builder().id(shapeId).member(ShapeId.from("smithy.api#Long")).build(); Model model = Model.builder() - .addShape(shape) - .addShape(LongShape.builder().id(ShapeId.from("smithy.api#Long")).build()) - .build(); + .addShape(shape) + .addShape(LongShape.builder().id(ShapeId.from("smithy.api#Long")).build()) + .build(); ModelTransformer transformer = ModelTransformer.create(); transformer.mapShapes(model, s -> { if (s.getId().equals(shapeId)) { @@ -97,14 +97,14 @@ public void updatesListMemberWhenContainerUpdated() { MemberShape member = MemberShape.builder().id(memberId).target(stringId).build(); ListShape container = ListShape.builder().id(containerId).member(member).build(); Model model = Model.builder() - .addShapes(target, member, container) - .build(); + .addShapes(target, member, container) + .build(); ModelTransformer transformer = ModelTransformer.create(); MemberShape newMember = MemberShape.builder() - .id(memberId) - .target(stringId) - .addTrait(new SensitiveTrait()) - .build(); + .id(memberId) + .target(stringId) + .addTrait(new SensitiveTrait()) + .build(); ListShape newList = ListShape.builder().id(containerId).member(newMember).build(); Model result = transformer.replaceShapes(model, Arrays.asList(newList)); @@ -126,20 +126,20 @@ public void updatesMapMembersWhenContainerUpdated() { MemberShape valueMember = MemberShape.builder().id(valueId).target(stringId).build(); MapShape container = MapShape.builder().id(containerId).key(keyMember).value(valueMember).build(); Model model = Model.builder() - .addShapes(target, keyMember, valueMember, container) - .build(); + .addShapes(target, keyMember, valueMember, container) + .build(); ModelTransformer transformer = ModelTransformer.create(); MemberShape newKey = MemberShape.builder() - .id(keyId) - .target(stringId) - .addTrait(new SensitiveTrait()) - .build(); + .id(keyId) + .target(stringId) + .addTrait(new SensitiveTrait()) + .build(); MemberShape newValue = MemberShape.builder() - .id(valueId) - .target(stringId) - .addTrait(new SensitiveTrait()) - .build(); + .id(valueId) + .target(stringId) + .addTrait(new SensitiveTrait()) + .build(); MapShape newMap = MapShape.builder().id(containerId).key(newKey).value(newValue).build(); Model result = transformer.replaceShapes(model, Arrays.asList(newMap)); @@ -160,26 +160,26 @@ public void updatesTaggedUnionMembersWhenContainerUpdated() { MemberShape member2 = MemberShape.builder().id("ns.foo#Shape$member2").target("ns.foo#String").build(); MemberShape member3 = MemberShape.builder().id("ns.foo#Shape$member3").target("ns.foo#String").build(); UnionShape shape = UnionShape.builder() - .id("ns.foo#Shape") - .addMember(member1) - .addMember(member2) - .addMember(member3) - .build(); + .id("ns.foo#Shape") + .addMember(member1) + .addMember(member2) + .addMember(member3) + .build(); Model model = Model.builder().addShapes(string, shape, member1, member2, member3).build(); // Add a trait to a replaced member3. MemberShape newMember3 = MemberShape.builder() - .id("ns.foo#Shape$member3") - .addTrait(new SensitiveTrait()) - .target("ns.foo#String") - .build(); + .id("ns.foo#Shape$member3") + .addTrait(new SensitiveTrait()) + .target("ns.foo#String") + .build(); // Replace the union with a shape that has the new member3. // Also remove member2. UnionShape other = UnionShape.builder() - .id("ns.foo#Shape") - .addMember(member1) - .addMember(newMember3) - .build(); + .id("ns.foo#Shape") + .addMember(member1) + .addMember(newMember3) + .build(); Model result = ModelTransformer.create().replaceShapes(model, Collections.singleton(other)); @@ -198,14 +198,14 @@ public void updatesListShapeWhenMemberModified() { MemberShape member = MemberShape.builder().id(memberId).target(stringId).build(); ListShape container = ListShape.builder().id(containerId).member(member).build(); Model model = Model.builder() - .addShapes(target, member, container) - .build(); + .addShapes(target, member, container) + .build(); ModelTransformer transformer = ModelTransformer.create(); MemberShape newMember = MemberShape.builder() - .id(memberId) - .target(stringId) - .addTrait(new SensitiveTrait()) - .build(); + .id(memberId) + .target(stringId) + .addTrait(new SensitiveTrait()) + .build(); Model result = transformer.replaceShapes(model, Arrays.asList(newMember)); assertThat(result.getShape(memberId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); @@ -223,38 +223,38 @@ public void updatesMapShapeWhenKeyOrValueIsUpdated() { MemberShape valueMember = MemberShape.builder().id(valueMemberId).target(stringId).build(); MapShape container = MapShape.builder().id(containerId).key(keyMember).value(valueMember).build(); Model model = Model.builder() - .addShapes(target, keyMember, valueMember, container) - .build(); + .addShapes(target, keyMember, valueMember, container) + .build(); ModelTransformer transformer = ModelTransformer.create(); MemberShape newKeyMember = MemberShape.builder() - .id(keyMemberId) - .target(stringId) - .addTrait(new SensitiveTrait()) - .build(); + .id(keyMemberId) + .target(stringId) + .addTrait(new SensitiveTrait()) + .build(); Model resultWithNewKey = transformer.replaceShapes(model, Arrays.asList(newKeyMember)); MemberShape newValueMember = MemberShape.builder() - .id(valueMemberId) - .target(stringId) - .addTrait(new SensitiveTrait()) - .build(); + .id(valueMemberId) + .target(stringId) + .addTrait(new SensitiveTrait()) + .build(); Model resultWithNewValue = transformer.replaceShapes(model, Arrays.asList(newValueMember)); assertThat( - resultWithNewKey.getShape(keyMemberId).get().getTrait(SensitiveTrait.class), - Matchers.not(Optional.empty()) + resultWithNewKey.getShape(keyMemberId).get().getTrait(SensitiveTrait.class), + Matchers.not(Optional.empty()) ); assertThat( - resultWithNewKey.getShape(containerId).get().asMapShape().get().getKey(), - Matchers.is(newKeyMember) + resultWithNewKey.getShape(containerId).get().asMapShape().get().getKey(), + Matchers.is(newKeyMember) ); assertThat( - resultWithNewValue.getShape(valueMemberId).get().getTrait(SensitiveTrait.class), - Matchers.not(Optional.empty()) + resultWithNewValue.getShape(valueMemberId).get().getTrait(SensitiveTrait.class), + Matchers.not(Optional.empty()) ); assertThat( - resultWithNewValue.getShape(containerId).get().asMapShape().get().getValue(), - Matchers.is(newValueMember) + resultWithNewValue.getShape(containerId).get().asMapShape().get().getValue(), + Matchers.is(newValueMember) ); } @@ -266,25 +266,25 @@ public void updatesStructureWhenMemberChanges() { ShapeId memberBId = ShapeId.from("ns.foo#Container$b"); StringShape target = StringShape.builder().id(stringId).build(); MemberShape memberA = MemberShape.builder() - .id(memberAId) - .target(stringId) - .addTrait(new RequiredTrait()) - .build(); + .id(memberAId) + .target(stringId) + .addTrait(new RequiredTrait()) + .build(); MemberShape memberB = MemberShape.builder().id(memberBId).target(stringId).build(); StructureShape container = StructureShape.builder() - .id(containerId) - .addMember(memberA) - .addMember(memberB) - .build(); + .id(containerId) + .addMember(memberA) + .addMember(memberB) + .build(); Model model = Model.builder() - .addShapes(target, memberA, memberB, container) - .build(); + .addShapes(target, memberA, memberB, container) + .build(); ModelTransformer transformer = ModelTransformer.create(); MemberShape newMemberB = MemberShape.builder() - .id(memberBId) - .target(stringId) - .addTrait(new SensitiveTrait()) - .build(); + .id(memberBId) + .target(stringId) + .addTrait(new SensitiveTrait()) + .build(); Model result = transformer.replaceShapes(model, Arrays.asList(newMemberB)); // Make sure the member has the trait that was applied. @@ -293,8 +293,8 @@ public void updatesStructureWhenMemberChanges() { assertTrue(result.getShape(containerId).get().asStructureShape().get().getMember("b").get().isOptional()); // Ensure that the structure that contains the shape was updated. assertThat( - result.getShape(containerId).get().asStructureShape().get().getMember("b").get(), - Matchers.is(newMemberB) + result.getShape(containerId).get().asStructureShape().get().getMember("b").get(), + Matchers.is(newMemberB) ); } @@ -308,13 +308,13 @@ public void canReplaceMultipleMembersOfSameShape() { MemberShape memberA = MemberShape.builder().id(memberAId).target(stringId).build(); MemberShape memberB = MemberShape.builder().id(memberBId).target(stringId).build(); StructureShape container = StructureShape.builder() - .id(containerId) - .addMember(memberA) - .addMember(memberB) - .build(); + .id(containerId) + .addMember(memberA) + .addMember(memberB) + .build(); Model model = Model.builder() - .addShapes(target, memberA, memberB, container) - .build(); + .addShapes(target, memberA, memberB, container) + .build(); ModelTransformer transformer = ModelTransformer.create(); MemberShape newMemberA = memberA.toBuilder().addTrait(new RequiredTrait()).build(); MemberShape newMemberB = memberB.toBuilder().addTrait(new RequiredTrait()).build(); @@ -325,22 +325,22 @@ public void canReplaceMultipleMembersOfSameShape() { // Make sure the members got updated inside of the container. assertTrue( - result.getShape(containerId) - .get() - .asStructureShape() - .get() - .getMember("a") - .get() - .hasTrait(RequiredTrait.class) + result.getShape(containerId) + .get() + .asStructureShape() + .get() + .getMember("a") + .get() + .hasTrait(RequiredTrait.class) ); assertTrue( - result.getShape(containerId) - .get() - .asStructureShape() - .get() - .getMember("b") - .get() - .hasTrait(RequiredTrait.class) + result.getShape(containerId) + .get() + .asStructureShape() + .get() + .getMember("b") + .get() + .hasTrait(RequiredTrait.class) ); } @@ -354,27 +354,27 @@ public void updatesTaggedUnionShapeWhenMemberChanges() { MemberShape memberA = MemberShape.builder().id(memberAId).target(stringId).build(); MemberShape memberB = MemberShape.builder().id(memberBId).target(stringId).build(); UnionShape container = UnionShape.builder() - .id(containerId) - .addMember(memberA) - .addMember(memberB) - .build(); + .id(containerId) + .addMember(memberA) + .addMember(memberB) + .build(); Model model = Model.builder() - .addShapes(target, memberA, memberB, container) - .build(); + .addShapes(target, memberA, memberB, container) + .build(); ModelTransformer transformer = ModelTransformer.create(); MemberShape newMemberB = MemberShape.builder() - .id(memberBId) - .target(stringId) - .addTrait(new SensitiveTrait()) - .build(); + .id(memberBId) + .target(stringId) + .addTrait(new SensitiveTrait()) + .build(); Model result = transformer.replaceShapes(model, Arrays.asList(newMemberB)); // Make sure the member has the trait that was applied. assertThat(result.getShape(memberBId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); // Ensure that the union that contains the shape was updated. assertThat( - result.getShape(containerId).get().asUnionShape().get().getMember("b").get(), - Matchers.is(newMemberB) + result.getShape(containerId).get().asUnionShape().get().getMember("b").get(), + Matchers.is(newMemberB) ); } @@ -387,31 +387,31 @@ public void doesNotOverwriteOtherContainerUpdatesWhenAlsoUpdatingMembers() { MemberShape member = MemberShape.builder().id(memberId).target(stringId).build(); ListShape container = ListShape.builder().id(containerId).member(member).build(); Model model = Model.builder() - .addShapes(target, member, container) - .build(); + .addShapes(target, member, container) + .build(); ModelTransformer transformer = ModelTransformer.create(); ListShape newContainer = container.toBuilder() - .addTrait( - LengthTrait.builder() - .min(1L) - .max(2L) - .sourceLocation(SourceLocation.NONE) - .build() - ) - .build(); + .addTrait( + LengthTrait.builder() + .min(1L) + .max(2L) + .sourceLocation(SourceLocation.NONE) + .build() + ) + .build(); MemberShape newMember = MemberShape.builder() - .id(memberId) - .target(stringId) - .addTrait(new SensitiveTrait()) - .build(); + .id(memberId) + .target(stringId) + .addTrait(new SensitiveTrait()) + .build(); Model result = transformer.replaceShapes(model, Arrays.asList(newMember, newContainer)); // Make sure the member has the trait that was applied. assertThat(result.getShape(memberId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); // Ensure that the list shape changes were not overwritten. assertThat( - result.getShape(containerId).get().asListShape().get().getTrait(LengthTrait.class), - Matchers.not(Optional.empty()) + result.getShape(containerId).get().asListShape().get().getTrait(LengthTrait.class), + Matchers.not(Optional.empty()) ); // Ensure that the list shape has the new member. assertThat(result.getShape(containerId).get().asListShape().get().getMember(), Matchers.is(newMember)); @@ -420,10 +420,10 @@ public void doesNotOverwriteOtherContainerUpdatesWhenAlsoUpdatingMembers() { @Test public void removingEnumMemberRemovesMemberFromUpdatedModel() { EnumShape shapeA = EnumShape.builder() - .id("example#Foo") - .addMember("a", "A") - .addMember("b", "B") - .build(); + .id("example#Foo") + .addMember("a", "A") + .addMember("b", "B") + .build(); EnumShape shapeB = shapeA.toBuilder().removeMember("b").build(); Model modelA = Model.builder().addShape(shapeA).build(); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/ScrubTraitDefinitionsTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/ScrubTraitDefinitionsTest.java index 77c778d08c6..72f91eee757 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/ScrubTraitDefinitionsTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/ScrubTraitDefinitionsTest.java @@ -19,9 +19,9 @@ public class ScrubTraitDefinitionsTest { @Test public void removesTracesOfTraitDefinitions() { Model model = Model.assembler() - .addImport(getClass().getResource("scrub-trait-def.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("scrub-trait-def.json")) + .assemble() + .unwrap(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.scrubTraitDefinitions(model); @@ -56,9 +56,9 @@ public void removesTracesOfTraitDefinitions() { @Test public void retainsSelectTraitDefinitions() { Model model = Model.assembler() - .addImport(getClass().getResource("scrub-trait-def.json")) - .assemble() - .unwrap(); + .addImport(getClass().getResource("scrub-trait-def.json")) + .assemble() + .unwrap(); Predicate keepFilter = shape -> !shape.getId().equals(ShapeId.from("ns.foo#bam")); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/SortMembersTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/SortMembersTest.java index 2c7c37da649..00910630a69 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/SortMembersTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/SortMembersTest.java @@ -21,15 +21,15 @@ public class SortMembersTest { public void sortsModelMembers() { ModelAssembler assembler = Model.assembler(); UnionShape u = UnionShape.builder() - .id("com.foo#U") - .addMember("zoo", ShapeId.from("smithy.api#String")) - .addMember("abc", ShapeId.from("smithy.api#String")) - .build(); + .id("com.foo#U") + .addMember("zoo", ShapeId.from("smithy.api#String")) + .addMember("abc", ShapeId.from("smithy.api#String")) + .build(); StructureShape s = StructureShape.builder() - .id("com.foo#S") - .addMember("zoo", ShapeId.from("smithy.api#String")) - .addMember("abc", ShapeId.from("smithy.api#String")) - .build(); + .id("com.foo#S") + .addMember("zoo", ShapeId.from("smithy.api#String")) + .addMember("abc", ShapeId.from("smithy.api#String")) + .build(); assembler.addShapes(u, s); Model model = assembler.assemble().unwrap(); ModelTransformer transformer = ModelTransformer.create(); @@ -41,12 +41,12 @@ public void sortsModelMembers() { // Members in the new model use the sorted order. assertThat( - sortedModel.expectShape(u.getId(), UnionShape.class).getMemberNames(), - Matchers.contains("abc", "zoo") + sortedModel.expectShape(u.getId(), UnionShape.class).getMemberNames(), + Matchers.contains("abc", "zoo") ); assertThat( - sortedModel.expectShape(s.getId(), StructureShape.class).getMemberNames(), - Matchers.contains("abc", "zoo") + sortedModel.expectShape(s.getId(), StructureShape.class).getMemberNames(), + Matchers.contains("abc", "zoo") ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/validation/ContextualValidationEventFormatterTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/validation/ContextualValidationEventFormatterTest.java index ed71cf643e4..3af9a12b98c 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/validation/ContextualValidationEventFormatterTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/validation/ContextualValidationEventFormatterTest.java @@ -21,57 +21,57 @@ public class ContextualValidationEventFormatterTest { @Test public void loadsContext() { Model model = Model.assembler() - // Use the shared context file. - .addImport(SourceContextLoader.class.getResource("context.smithy")) - .assemble() - .unwrap(); + // Use the shared context file. + .addImport(SourceContextLoader.class.getResource("context.smithy")) + .assemble() + .unwrap(); Shape shape = model.expectShape(ShapeId.from("example.smithy#Foo")); ValidationEvent event = ValidationEvent.builder() - .id("foo") - .severity(Severity.ERROR) - .message("This is the message") - .shape(shape) - .build(); + .id("foo") + .severity(Severity.ERROR) + .message("This is the message") + .shape(shape) + .build(); String format = new ContextualValidationEventFormatter().format(event); assertThat(format, startsWith("ERROR: example.smithy#Foo (foo)")); assertThat(format, containsString(String.format("%n @ "))); assertThat( - format, - endsWith( - String.format( - "%n |" - + "%n 3 | structure Foo {" - + "%n | ^" - + "%n = This is the message" - + "%n" + format, + endsWith( + String.format( + "%n |" + + "%n 3 | structure Foo {" + + "%n | ^" + + "%n = This is the message" + + "%n" + ) ) - ) ); } @Test public void doesNotLoadSourceLocationNone() { ValidationEvent event = ValidationEvent.builder() - .id("foo") - .severity(Severity.ERROR) - .message("This is the message") - .sourceLocation(SourceLocation.NONE) - .build(); + .id("foo") + .severity(Severity.ERROR) + .message("This is the message") + .sourceLocation(SourceLocation.NONE) + .build(); String format = new ContextualValidationEventFormatter().format(event); assertThat( - format, - equalTo( - String.format( - "ERROR: - (foo)" - + "%n = This is the message" - + "%n" + format, + equalTo( + String.format( + "ERROR: - (foo)" + + "%n = This is the message" + + "%n" + ) ) - ) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/validation/ExamplesTraitValidatorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/validation/ExamplesTraitValidatorTest.java index 3e1dfb38db8..f41c0bc985f 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/validation/ExamplesTraitValidatorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/validation/ExamplesTraitValidatorTest.java @@ -18,14 +18,14 @@ public class ExamplesTraitValidatorTest { @Test public void noNpeWhenInputOrOutputAreOmitted() { ExamplesTrait.Example example = ExamplesTrait.Example.builder() - .title("Title") - .documentation("Documentation") - .build(); + .title("Title") + .documentation("Documentation") + .build(); ExamplesTrait trait = ExamplesTrait.builder().addExample(example).build(); Shape shape = OperationShape.builder() - .id("foo.bar#Baz") - .addTrait(trait) - .build(); + .id("foo.bar#Baz") + .addTrait(trait) + .build(); Model model = Model.builder().addShape(shape).build(); ExamplesTraitValidator validator = new ExamplesTraitValidator(); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/validation/NodeValidationVisitorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/validation/NodeValidationVisitorTest.java index a67a9081455..f5b67a61306 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/validation/NodeValidationVisitorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/validation/NodeValidationVisitorTest.java @@ -34,9 +34,9 @@ public class NodeValidationVisitorTest { @BeforeAll public static void onlyOnce() { MODEL = Model.assembler() - .addImport(NodeValidationVisitorTest.class.getResource("node-validator.json")) - .assemble() - .unwrap(); + .addImport(NodeValidationVisitorTest.class.getResource("node-validator.json")) + .assemble() + .unwrap(); } @AfterAll @@ -50,9 +50,9 @@ public void nodeValidationVisitorTest(String target, String value, String[] erro ShapeId targetId = ShapeId.from(target); Node nodeValue = Node.parse(value); NodeValidationVisitor visitor = NodeValidationVisitor.builder() - .value(nodeValue) - .model(MODEL) - .build(); + .value(nodeValue) + .model(MODEL) + .build(); List events = MODEL.expectShape(targetId).accept(visitor); if (errors != null) { @@ -60,580 +60,597 @@ public void nodeValidationVisitorTest(String target, String value, String[] erro assertThat(messages, containsInAnyOrder(errors)); } else if (!events.isEmpty()) { Assertions.fail( - "Did not expect any problems with the value, but found: " - + events.stream().map(Object::toString).collect(Collectors.joining("\n")) + "Did not expect any problems with the value, but found: " + + events.stream().map(Object::toString).collect(Collectors.joining("\n")) ); } } public static Collection data() { return Arrays.asList( - new Object[][]{ - // Invalid shapes - {"ns.foo#Service", "true", new String[]{"Encountered invalid shape type: service"}}, - {"ns.foo#Operation", "true", new String[]{"Encountered invalid shape type: operation"}}, - {"ns.foo#Resource", "true", new String[]{"Encountered invalid shape type: resource"}}, - - // Booleans - {"ns.foo#Boolean", "true", null}, - {"ns.foo#Boolean", "false", null}, - { - "ns.foo#Boolean", - "\"string\"", - new String[]{ - "Expected boolean value for boolean shape, `ns.foo#Boolean`; found string value, `string`" - }}, - { - "ns.foo#Boolean", - "10", - new String[]{ - "Expected boolean value for boolean shape, `ns.foo#Boolean`; found number value, `10`" - }}, - { - "ns.foo#Boolean", - "{}", - new String[]{ - "Expected boolean value for boolean shape, `ns.foo#Boolean`; found object value" - }}, - { - "ns.foo#Boolean", - "[]", - new String[]{ - "Expected boolean value for boolean shape, `ns.foo#Boolean`; found array value" - }}, - { - "ns.foo#Boolean", - "null", - new String[]{ - "Expected boolean value for boolean shape, `ns.foo#Boolean`; found null value" - }}, - - // Blobs - {"ns.foo#Blob1", "\"\"", null}, - {"ns.foo#Blob1", "\"foo\"", null}, - { - "ns.foo#Blob1", - "true", - new String[]{ - "Expected string value for blob shape, `ns.foo#Blob1`; found boolean value, `true`" - }}, - {"ns.foo#Blob2", "\"f\"", null}, - { - "ns.foo#Blob2", - "\"fooo\"", - new String[]{ - "Value provided for `ns.foo#Blob2` must have no more than 3 bytes, but the provided value has 4 bytes"}}, - { - "ns.foo#Blob2", - "\"\"", - new String[]{ - "Value provided for `ns.foo#Blob2` must have at least 1 bytes, but the provided value only has 0 bytes"}}, - - // byte - {"ns.foo#Byte", "10", null}, - {"ns.foo#Byte", "-256", new String[]{"byte value must be > -128, but found -256"}}, - {"ns.foo#Byte", "256", new String[]{"byte value must be < 127, but found 256"}}, - { - "ns.foo#Byte", - "true", - new String[]{"Expected number value for byte shape, `ns.foo#Byte`; found boolean value, `true`"}}, - { - "ns.foo#Byte", - "21", - new String[]{"Value provided for `ns.foo#Byte` must be less than or equal to 20, but found 21"}}, - { - "ns.foo#Byte", - "9", - new String[]{"Value provided for `ns.foo#Byte` must be greater than or equal to 10, but found 9"}}, - { - "ns.foo#Byte", - "10.2", - new String[]{ - "byte shapes must not have floating point values, but found `10.2` provided for `ns.foo#Byte`"}}, - - // short - {"ns.foo#Short", "10", null}, - {"ns.foo#Short", "-999999", new String[]{"short value must be > -32768, but found -999999"}}, - {"ns.foo#Short", "9999999", new String[]{"short value must be < 32767, but found 9999999"}}, - { - "ns.foo#Short", - "true", - new String[]{"Expected number value for short shape, `ns.foo#Short`; found boolean value, `true`"}}, - { - "ns.foo#Short", - "21", - new String[]{"Value provided for `ns.foo#Short` must be less than or equal to 20, but found 21"}}, - { - "ns.foo#Short", - "9", - new String[]{"Value provided for `ns.foo#Short` must be greater than or equal to 10, but found 9"}}, - { - "ns.foo#Short", - "10.2", - new String[]{ - "short shapes must not have floating point values, but found `10.2` provided for `ns.foo#Short`"}}, - - // integer - {"ns.foo#Integer", "10", null}, - { - "ns.foo#Integer", - "true", - new String[]{ - "Expected number value for integer shape, `ns.foo#Integer`; found boolean value, `true`"}}, - { - "ns.foo#Integer", - "21", - new String[]{"Value provided for `ns.foo#Integer` must be less than or equal to 20, but found 21"}}, - { - "ns.foo#Integer", - "9", - new String[]{ - "Value provided for `ns.foo#Integer` must be greater than or equal to 10, but found 9"}}, - { - "ns.foo#Integer", - "10.2", - new String[]{ - "integer shapes must not have floating point values, but found `10.2` provided for `ns.foo#Integer`"}}, - - // intEnum - {"ns.foo#IntEnum", "1", null}, - {"ns.foo#IntEnum", "2", null}, - { - "ns.foo#IntEnum", - "3", - new String[]{ - "Integer value provided for `ns.foo#IntEnum` must be one of the following values: `1`, `2`, but found 3"}}, - { - "ns.foo#IntEnum", - "true", - new String[]{ - "Expected number value for intEnum shape, `ns.foo#IntEnum`; found boolean value, `true`"}}, - { - "ns.foo#IntEnum", - "1.1", - new String[]{ - "intEnum shapes must not have floating point values, but found `1.1` provided for `ns.foo#IntEnum`"}}, - - // long - {"ns.foo#Long", "10", null}, - { - "ns.foo#Long", - "true", - new String[]{"Expected number value for long shape, `ns.foo#Long`; found boolean value, `true`"}}, - { - "ns.foo#Long", - "21", - new String[]{"Value provided for `ns.foo#Long` must be less than or equal to 20, but found 21"}}, - { - "ns.foo#Long", - "9", - new String[]{"Value provided for `ns.foo#Long` must be greater than or equal to 10, but found 9"}}, - - // float - {"ns.foo#Float", "10", null}, - {"smithy.api#Float", "\"NaN\"", null}, - { - "ns.foo#Float", - "\"NaN\"", - new String[]{ - "Value provided for `ns.foo#Float` must be a number because the `smithy.api#range` trait is applied, but found \"NaN\""}}, - {"smithy.api#Float", "\"Infinity\"", null}, - {"smithy.api#Float", "\"-Infinity\"", null}, - { - "smithy.api#Float", - "\"+Infinity\"", - new String[]{ - "Value for `smithy.api#Float` must either be numeric or one of the following strings: [\"NaN\", \"Infinity\", \"-Infinity\"], but was \"+Infinity\""}}, - { - "ns.foo#Float", - "true", - new String[]{"Expected number value for float shape, `ns.foo#Float`; found boolean value, `true`"}}, - { - "ns.foo#Float", - "21", - new String[]{"Value provided for `ns.foo#Float` must be less than or equal to 20, but found 21"}}, - { - "ns.foo#Float", - "\"Infinity\"", - new String[]{ - "Value provided for `ns.foo#Float` must be less than or equal to 20, but found \"Infinity\""}}, - { - "ns.foo#Float", - "9", - new String[]{"Value provided for `ns.foo#Float` must be greater than or equal to 10, but found 9"}}, - { - "ns.foo#Float", - "\"-Infinity\"", - new String[]{ - "Value provided for `ns.foo#Float` must be greater than or equal to 10, but found \"-Infinity\""}}, - - // double - {"ns.foo#Double", "10", null}, - {"smithy.api#Double", "\"NaN\"", null}, - { - "ns.foo#Double", - "\"NaN\"", - new String[]{ - "Value provided for `ns.foo#Double` must be a number because the `smithy.api#range` trait is applied, but found \"NaN\""}}, - {"smithy.api#Double", "\"Infinity\"", null}, - {"smithy.api#Double", "\"-Infinity\"", null}, - { - "smithy.api#Double", - "\"+Infinity\"", - new String[]{ - "Value for `smithy.api#Double` must either be numeric or one of the following strings: [\"NaN\", \"Infinity\", \"-Infinity\"], but was \"+Infinity\""}}, - { - "ns.foo#Double", - "true", - new String[]{ - "Expected number value for double shape, `ns.foo#Double`; found boolean value, `true`"}}, - { - "ns.foo#Double", - "21", - new String[]{"Value provided for `ns.foo#Double` must be less than or equal to 20, but found 21"}}, - { - "ns.foo#Double", - "\"Infinity\"", - new String[]{ - "Value provided for `ns.foo#Double` must be less than or equal to 20, but found \"Infinity\""}}, - { - "ns.foo#Double", - "9", - new String[]{ - "Value provided for `ns.foo#Double` must be greater than or equal to 10, but found 9"}}, - { - "ns.foo#Double", - "\"-Infinity\"", - new String[]{ - "Value provided for `ns.foo#Double` must be greater than or equal to 10, but found \"-Infinity\""}}, - - // bigInteger - {"ns.foo#BigInteger", "10", null}, - { - "ns.foo#BigInteger", - "true", - new String[]{ - "Expected number value for bigInteger shape, `ns.foo#BigInteger`; found boolean value, `true`"}}, - { - "ns.foo#BigInteger", - "21", - new String[]{ - "Value provided for `ns.foo#BigInteger` must be less than or equal to 20, but found 21"}}, - { - "ns.foo#BigInteger", - "9", - new String[]{ - "Value provided for `ns.foo#BigInteger` must be greater than or equal to 10, but found 9"}}, - - // bigDecimal - {"ns.foo#BigDecimal", "10", null}, - { - "ns.foo#BigDecimal", - "true", - new String[]{ - "Expected number value for bigDecimal shape, `ns.foo#BigDecimal`; found boolean value, `true`"}}, - { - "ns.foo#BigDecimal", - "21", - new String[]{ - "Value provided for `ns.foo#BigDecimal` must be less than or equal to 20, but found 21"}}, - { - "ns.foo#BigDecimal", - "9", - new String[]{ - "Value provided for `ns.foo#BigDecimal` must be greater than or equal to 10, but found 9"}}, - - // timestamp - {"ns.foo#Timestamp", "\"1985-04-12T23:20:50.52Z\"", null}, - {"ns.foo#Timestamp", "1507837929", null}, - {"ns.foo#Timestamp", "1507837929.123", null}, - { - "ns.foo#Timestamp", - "true", - new String[]{ - "Invalid boolean value provided for timestamp, `ns.foo#Timestamp`. Expected a number that contains epoch seconds with optional millisecond precision, or a string that contains an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, - { - "ns.foo#Timestamp", - "\"2000-01-12T22:11:12\"", - new String[]{ - "Invalid string value, `2000-01-12T22:11:12`, provided for timestamp, `ns.foo#Timestamp`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, - { - "ns.foo#Timestamp", - "\"2000-01-12T22:11:12+\"", - new String[]{ - "Invalid string value, `2000-01-12T22:11:12+`, provided for timestamp, `ns.foo#Timestamp`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, - { - "ns.foo#Timestamp", - "\"200-01-12T22:11:12Z\"", - new String[]{ - "Invalid string value, `200-01-12T22:11:12Z`, provided for timestamp, `ns.foo#Timestamp`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, - { - "ns.foo#Timestamp", - "\"2000-01-12T22:11:12+01:02\"", - new String[]{ - "Invalid string value, `2000-01-12T22:11:12+01:02`, provided for timestamp, `ns.foo#Timestamp`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, - { - "ns.foo#Timestamp", - "\"2000-01-12T22:11:12-11:00\"", - new String[]{ - "Invalid string value, `2000-01-12T22:11:12-11:00`, provided for timestamp, `ns.foo#Timestamp`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, - - // string - {"ns.foo#String1", "\"true\"", null}, - { - "ns.foo#String2", - "\"fooo\"", - new String[]{ - "String value provided for `ns.foo#String2` must be <= 3 characters, but the provided value is 4 characters."}}, - { - "ns.foo#String2", - "\"\"", - new String[]{ - "String value provided for `ns.foo#String2` must be >= 1 characters, but the provided value is only 0 characters."}}, - {"ns.foo#String2", "\"foo\"", null}, - { - "ns.foo#String3", - "\"qux\"", - new String[]{ - "String value provided for `ns.foo#String3` must be one of the following values: `bar`, `foo`"}}, - {"ns.foo#String3", "\"foo\"", null}, - {"ns.foo#String3", "\"bar\"", null}, - {"ns.foo#String4", "\"ABC\"", null}, - { - "ns.foo#String4", - "\"abc\"", - new String[]{"String value provided for `ns.foo#String4` must match regular expression: ^[A-Z]+$"}}, - - // list - {"ns.foo#List", "[\"a\"]", null}, - {"ns.foo#List", "[\"a\", \"b\"]", null}, - { - "ns.foo#List", - "[]", - new String[]{ - "Value provided for `ns.foo#List` must have at least 1 elements, but the provided value only has 0 elements"}}, - { - "ns.foo#List", - "[\"a\", \"b\", \"c\"]", - new String[]{ - "Value provided for `ns.foo#List` must have no more than 2 elements, but the provided value has 3 elements"}}, - { - "ns.foo#List", - "[10]", - new String[]{ - "0: Expected string value for string shape, `ns.foo#String`; found number value, `10`"}}, - { - "ns.foo#List", - "10", - new String[]{"Expected array value for list shape, `ns.foo#List`; found number value, `10`"}}, - - // unique list - {"ns.foo#UniqueList", "[\"a\"]", null}, - {"ns.foo#UniqueList", "[\"a\", \"b\"]", null}, - { - "ns.foo#UniqueList", - "[\"a\", \"a\"]", - new String[]{ - "Value provided for `ns.foo#UniqueList` must have unique items, but the following items had multiple entries: [`a`]"}}, - { - "ns.foo#UniqueList", - "[\"a\", \"a\", \"a\"]", - new String[]{ - "Value provided for `ns.foo#UniqueList` must have unique items, but the following items had multiple entries: [`a`]"}}, - { - "ns.foo#UniqueList", - "[\"a\", \"a\", \"b\", \"b\"]", - new String[]{ - "Value provided for `ns.foo#UniqueList` must have unique items, but the following items had multiple entries: [`a`, `b`]"}}, - - // map - {"ns.foo#Map", "{\"a\":[\"b\"]}", null}, - {"ns.foo#Map", "{\"a\":[\"b\"], \"c\":[\"d\"]}", null}, - // Too many elements - { - "ns.foo#Map", - "{\"a\":[\"b\"], \"c\":[\"d\"], \"e\":[\"f\"]}", - new String[]{ - "Value provided for `ns.foo#Map` must have no more than 2 entries, but the provided value has 3 entries"}}, - // Not enough elements - { - "ns.foo#Map", - "{}", - new String[]{ - "Value provided for `ns.foo#Map` must have at least 1 entries, but the provided value only has 0 entries"}}, - // Too many characters in string. - { - "ns.foo#Map", - "{\"abc\":[\"b\"], \"c\":[\"d\"]}", - new String[]{ - "abc (map-key): String value provided for `ns.foo#KeyString` must be <= 2 characters, but the provided value is 3 characters."}}, - // Too many elements in nested list - { - "ns.foo#Map", - "{\"a\":[\"b\", \"c\", \"d\", \"e\"]}", - new String[]{ - "a: Value provided for `ns.foo#List` must have no more than 2 elements, but the provided value has 4 elements"}}, - - // structure - {"ns.foo#Structure", "{\"foo\": \"test\"}", null}, - { - "ns.foo#Structure", - "{\"foo\": \"test\", \"invalid\": true}", - new String[]{"Invalid structure member `invalid` found for `ns.foo#Structure`"}}, - {"ns.foo#Structure", "{\"foo\": \"test\", \"baz\": \"baz\"}", null}, - { - "ns.foo#Structure", - "{\"foo\": \"test\", \"baz\": \"baz\", \"bar\": [\"a\", \"b\"], \"bam\": {\"foo\": \"test\"}}", - null}, - { - "ns.foo#Structure", - "{\"baz\": \"test\"}", - new String[]{"Missing required structure member `foo` for `ns.foo#Structure`"}}, - { - "ns.foo#Structure", - "{\"foo\": 10}", - new String[]{ - "foo: Expected string value for string shape, `ns.foo#String`; found number value, `10`"}}, - { - "ns.foo#Structure", - "{\"foo\": \"test\", \"baz\": 10}", - new String[]{ - "baz: Expected string value for string shape, `ns.foo#String`; found number value, `10`"}}, - { - "ns.foo#Structure", - "{\"foo\": \"test\", \"bam\": {}}", - new String[]{"bam: Missing required structure member `foo` for `ns.foo#Structure`"}}, - { - "ns.foo#Structure", - "{\"foo\": \"test\", \"bam\": {\"foo\": 10}}", - new String[]{ - "bam.foo: Expected string value for string shape, `ns.foo#String`; found number value, `10`"}}, - - // taggged union - {"ns.foo#TaggedUnion", "{\"foo\": \"test\"}", null}, - {"ns.foo#TaggedUnion", "{\"baz\": \"test\"}", null}, - { - "ns.foo#TaggedUnion", - "{\"foo\": \"test\", \"baz\": \"baz\"}", - new String[]{"union values can contain a value for only a single member"}}, - { - "ns.foo#TaggedUnion", - "{\"foo\": 10}", - new String[]{ - "foo: Expected string value for string shape, `ns.foo#String`; found number value, `10`"}}, - { - "ns.foo#TaggedUnion", - "{\"invalid\": true}", - new String[]{"Invalid union member `invalid` found for `ns.foo#TaggedUnion`"}}, - - // http-date - {"ns.foo#HttpDate", "\"Tue, 29 Apr 2014 18:30:38 GMT\"", null}, - { - "ns.foo#HttpDate", - "\"Tuesday, 29 April 2014 18:30:38 GMT\"", - new String[]{ - "Invalid value provided for http-date formatted timestamp. Expected a string value that matches the IMF-fixdate production of RFC 9110 section-5.6.7. Found: Tuesday, 29 April 2014 18:30:38 GMT"}}, - { - "ns.foo#HttpDate", - "\"Tue, 29 Apr 2014 18:30:38 PST\"", - new String[]{ - "Invalid value provided for http-date formatted timestamp. Expected a string value that matches the IMF-fixdate production of RFC 9110 section-5.6.7. Found: Tue, 29 Apr 2014 18:30:38 PST"}}, - { - "ns.foo#HttpDate", - "11", - new String[]{ - "Invalid value provided for http-date formatted timestamp. Expected a string value that matches the IMF-fixdate production of RFC 9110 section-5.6.7. Found: number"}}, - - // date-time - {"ns.foo#DateTime", "\"1985-04-12T23:20:50.52Z\"", null}, - { - "ns.foo#DateTime", - "1234", - new String[]{ - "Expected a string value for a date-time timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, - { - "ns.foo#DateTime", - "\"1985-04-12\"", - new String[]{ - "Invalid string value, `1985-04-12`, provided for timestamp, `ns.foo#DateTime`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, - { - "ns.foo#DateTime", - "\"Tuesday, 29 April 2014 18:30:38 GMT\"", - new String[]{ - "Invalid string value, `Tuesday, 29 April 2014 18:30:38 GMT`, provided for timestamp, `ns.foo#DateTime`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, - { - "ns.foo#DateTime", - "\"1985-04-12T23:20:50.52-07:00\"", - new String[]{ - "Invalid string value, `1985-04-12T23:20:50.52-07:00`, provided for timestamp, `ns.foo#DateTime`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, - - // epoch seconds - {"ns.foo#EpochSeconds", "123", null}, - { - "ns.foo#EpochSeconds", - "\"1985-04-12T23:20:50.52Z\"", - new String[]{"Invalid string value provided for a timestamp with a `epoch-seconds` format."}}, - - // timestamp member with format. - {"ns.foo#TimestampList", "[\"1985-04-12T23:20:50.52Z\"]", null}, - { - "ns.foo#TimestampList", - "[\"1985-04-12T23:20:50.52-07:00\"]", - new String[]{ - "0: Invalid string value, `1985-04-12T23:20:50.52-07:00`, provided for timestamp, `ns.foo#TimestampList$member`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")" - }}, - { - "ns.foo#TimestampList", - "[123]", - new String[]{ - "0: Expected a string value for a date-time timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, - { - "ns.foo#Structure4", - "{\"httpDate\": 1234}", - new String[]{ - "httpDate: Invalid value provided for http-date formatted timestamp. Expected a string value that matches the IMF-fixdate production of RFC 9110 section-5.6.7. Found: number"}}, - { - "ns.foo#Structure4", - "{\"httpDateTarget\": 1234}", - new String[]{ - "httpDateTarget: Invalid value provided for http-date formatted timestamp. Expected a string value that matches the IMF-fixdate production of RFC 9110 section-5.6.7. Found: number"}}, - - // timestamp member with no format. - {"ns.foo#TimestampListNoFormatTrait", "[123]", null}, - - // Member validation - {"ns.foo#Structure2", "{\"a\": \"23 abc\"}", null}, - { - "ns.foo#Structure2", - "{\"a\": \"abc\"}", - new String[]{ - "a: String value provided for `ns.foo#Structure2$a` must match regular expression: ^[0-9]"}}, - {"ns.foo#Structure2", "{\"b\": \"12345678910\"}", null}, - { - "ns.foo#Structure2", - "{\"b\": \"123\"}", - new String[]{ - "b: String value provided for `ns.foo#Structure2$b` must be >= 10 characters, but the provided value is only 3 characters."}}, - {"ns.foo#Structure2", "{\"c\": 11}", null}, - { - "ns.foo#Structure2", - "{\"c\": 5}", - new String[]{ - "c: Value provided for `ns.foo#Structure2$c` must be greater than or equal to 10, but found 5"}} - } + new Object[][]{ + // Invalid shapes + {"ns.foo#Service", "true", new String[]{"Encountered invalid shape type: service"}}, + {"ns.foo#Operation", "true", new String[]{"Encountered invalid shape type: operation"}}, + {"ns.foo#Resource", "true", new String[]{"Encountered invalid shape type: resource"}}, + + // Booleans + {"ns.foo#Boolean", "true", null}, + {"ns.foo#Boolean", "false", null}, + { + "ns.foo#Boolean", + "\"string\"", + new String[]{ + "Expected boolean value for boolean shape, `ns.foo#Boolean`; found string value, `string`" + }}, + { + "ns.foo#Boolean", + "10", + new String[]{ + "Expected boolean value for boolean shape, `ns.foo#Boolean`; found number value, `10`" + }}, + { + "ns.foo#Boolean", + "{}", + new String[]{ + "Expected boolean value for boolean shape, `ns.foo#Boolean`; found object value" + }}, + { + "ns.foo#Boolean", + "[]", + new String[]{ + "Expected boolean value for boolean shape, `ns.foo#Boolean`; found array value" + }}, + { + "ns.foo#Boolean", + "null", + new String[]{ + "Expected boolean value for boolean shape, `ns.foo#Boolean`; found null value" + }}, + + // Blobs + {"ns.foo#Blob1", "\"\"", null}, + {"ns.foo#Blob1", "\"foo\"", null}, + { + "ns.foo#Blob1", + "true", + new String[]{ + "Expected string value for blob shape, `ns.foo#Blob1`; found boolean value, `true`" + }}, + {"ns.foo#Blob2", "\"f\"", null}, + { + "ns.foo#Blob2", + "\"fooo\"", + new String[]{ + "Value provided for `ns.foo#Blob2` must have no more than 3 bytes, but the provided value has 4 bytes"}}, + { + "ns.foo#Blob2", + "\"\"", + new String[]{ + "Value provided for `ns.foo#Blob2` must have at least 1 bytes, but the provided value only has 0 bytes"}}, + + // byte + {"ns.foo#Byte", "10", null}, + {"ns.foo#Byte", "-256", new String[]{"byte value must be > -128, but found -256"}}, + {"ns.foo#Byte", "256", new String[]{"byte value must be < 127, but found 256"}}, + { + "ns.foo#Byte", + "true", + new String[]{ + "Expected number value for byte shape, `ns.foo#Byte`; found boolean value, `true`"}}, + { + "ns.foo#Byte", + "21", + new String[]{ + "Value provided for `ns.foo#Byte` must be less than or equal to 20, but found 21"}}, + { + "ns.foo#Byte", + "9", + new String[]{ + "Value provided for `ns.foo#Byte` must be greater than or equal to 10, but found 9"}}, + { + "ns.foo#Byte", + "10.2", + new String[]{ + "byte shapes must not have floating point values, but found `10.2` provided for `ns.foo#Byte`"}}, + + // short + {"ns.foo#Short", "10", null}, + {"ns.foo#Short", "-999999", new String[]{"short value must be > -32768, but found -999999"}}, + {"ns.foo#Short", "9999999", new String[]{"short value must be < 32767, but found 9999999"}}, + { + "ns.foo#Short", + "true", + new String[]{ + "Expected number value for short shape, `ns.foo#Short`; found boolean value, `true`"}}, + { + "ns.foo#Short", + "21", + new String[]{ + "Value provided for `ns.foo#Short` must be less than or equal to 20, but found 21"}}, + { + "ns.foo#Short", + "9", + new String[]{ + "Value provided for `ns.foo#Short` must be greater than or equal to 10, but found 9"}}, + { + "ns.foo#Short", + "10.2", + new String[]{ + "short shapes must not have floating point values, but found `10.2` provided for `ns.foo#Short`"}}, + + // integer + {"ns.foo#Integer", "10", null}, + { + "ns.foo#Integer", + "true", + new String[]{ + "Expected number value for integer shape, `ns.foo#Integer`; found boolean value, `true`"}}, + { + "ns.foo#Integer", + "21", + new String[]{ + "Value provided for `ns.foo#Integer` must be less than or equal to 20, but found 21"}}, + { + "ns.foo#Integer", + "9", + new String[]{ + "Value provided for `ns.foo#Integer` must be greater than or equal to 10, but found 9"}}, + { + "ns.foo#Integer", + "10.2", + new String[]{ + "integer shapes must not have floating point values, but found `10.2` provided for `ns.foo#Integer`"}}, + + // intEnum + {"ns.foo#IntEnum", "1", null}, + {"ns.foo#IntEnum", "2", null}, + { + "ns.foo#IntEnum", + "3", + new String[]{ + "Integer value provided for `ns.foo#IntEnum` must be one of the following values: `1`, `2`, but found 3"}}, + { + "ns.foo#IntEnum", + "true", + new String[]{ + "Expected number value for intEnum shape, `ns.foo#IntEnum`; found boolean value, `true`"}}, + { + "ns.foo#IntEnum", + "1.1", + new String[]{ + "intEnum shapes must not have floating point values, but found `1.1` provided for `ns.foo#IntEnum`"}}, + + // long + {"ns.foo#Long", "10", null}, + { + "ns.foo#Long", + "true", + new String[]{ + "Expected number value for long shape, `ns.foo#Long`; found boolean value, `true`"}}, + { + "ns.foo#Long", + "21", + new String[]{ + "Value provided for `ns.foo#Long` must be less than or equal to 20, but found 21"}}, + { + "ns.foo#Long", + "9", + new String[]{ + "Value provided for `ns.foo#Long` must be greater than or equal to 10, but found 9"}}, + + // float + {"ns.foo#Float", "10", null}, + {"smithy.api#Float", "\"NaN\"", null}, + { + "ns.foo#Float", + "\"NaN\"", + new String[]{ + "Value provided for `ns.foo#Float` must be a number because the `smithy.api#range` trait is applied, but found \"NaN\""}}, + {"smithy.api#Float", "\"Infinity\"", null}, + {"smithy.api#Float", "\"-Infinity\"", null}, + { + "smithy.api#Float", + "\"+Infinity\"", + new String[]{ + "Value for `smithy.api#Float` must either be numeric or one of the following strings: [\"NaN\", \"Infinity\", \"-Infinity\"], but was \"+Infinity\""}}, + { + "ns.foo#Float", + "true", + new String[]{ + "Expected number value for float shape, `ns.foo#Float`; found boolean value, `true`"}}, + { + "ns.foo#Float", + "21", + new String[]{ + "Value provided for `ns.foo#Float` must be less than or equal to 20, but found 21"}}, + { + "ns.foo#Float", + "\"Infinity\"", + new String[]{ + "Value provided for `ns.foo#Float` must be less than or equal to 20, but found \"Infinity\""}}, + { + "ns.foo#Float", + "9", + new String[]{ + "Value provided for `ns.foo#Float` must be greater than or equal to 10, but found 9"}}, + { + "ns.foo#Float", + "\"-Infinity\"", + new String[]{ + "Value provided for `ns.foo#Float` must be greater than or equal to 10, but found \"-Infinity\""}}, + + // double + {"ns.foo#Double", "10", null}, + {"smithy.api#Double", "\"NaN\"", null}, + { + "ns.foo#Double", + "\"NaN\"", + new String[]{ + "Value provided for `ns.foo#Double` must be a number because the `smithy.api#range` trait is applied, but found \"NaN\""}}, + {"smithy.api#Double", "\"Infinity\"", null}, + {"smithy.api#Double", "\"-Infinity\"", null}, + { + "smithy.api#Double", + "\"+Infinity\"", + new String[]{ + "Value for `smithy.api#Double` must either be numeric or one of the following strings: [\"NaN\", \"Infinity\", \"-Infinity\"], but was \"+Infinity\""}}, + { + "ns.foo#Double", + "true", + new String[]{ + "Expected number value for double shape, `ns.foo#Double`; found boolean value, `true`"}}, + { + "ns.foo#Double", + "21", + new String[]{ + "Value provided for `ns.foo#Double` must be less than or equal to 20, but found 21"}}, + { + "ns.foo#Double", + "\"Infinity\"", + new String[]{ + "Value provided for `ns.foo#Double` must be less than or equal to 20, but found \"Infinity\""}}, + { + "ns.foo#Double", + "9", + new String[]{ + "Value provided for `ns.foo#Double` must be greater than or equal to 10, but found 9"}}, + { + "ns.foo#Double", + "\"-Infinity\"", + new String[]{ + "Value provided for `ns.foo#Double` must be greater than or equal to 10, but found \"-Infinity\""}}, + + // bigInteger + {"ns.foo#BigInteger", "10", null}, + { + "ns.foo#BigInteger", + "true", + new String[]{ + "Expected number value for bigInteger shape, `ns.foo#BigInteger`; found boolean value, `true`"}}, + { + "ns.foo#BigInteger", + "21", + new String[]{ + "Value provided for `ns.foo#BigInteger` must be less than or equal to 20, but found 21"}}, + { + "ns.foo#BigInteger", + "9", + new String[]{ + "Value provided for `ns.foo#BigInteger` must be greater than or equal to 10, but found 9"}}, + + // bigDecimal + {"ns.foo#BigDecimal", "10", null}, + { + "ns.foo#BigDecimal", + "true", + new String[]{ + "Expected number value for bigDecimal shape, `ns.foo#BigDecimal`; found boolean value, `true`"}}, + { + "ns.foo#BigDecimal", + "21", + new String[]{ + "Value provided for `ns.foo#BigDecimal` must be less than or equal to 20, but found 21"}}, + { + "ns.foo#BigDecimal", + "9", + new String[]{ + "Value provided for `ns.foo#BigDecimal` must be greater than or equal to 10, but found 9"}}, + + // timestamp + {"ns.foo#Timestamp", "\"1985-04-12T23:20:50.52Z\"", null}, + {"ns.foo#Timestamp", "1507837929", null}, + {"ns.foo#Timestamp", "1507837929.123", null}, + { + "ns.foo#Timestamp", + "true", + new String[]{ + "Invalid boolean value provided for timestamp, `ns.foo#Timestamp`. Expected a number that contains epoch seconds with optional millisecond precision, or a string that contains an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, + { + "ns.foo#Timestamp", + "\"2000-01-12T22:11:12\"", + new String[]{ + "Invalid string value, `2000-01-12T22:11:12`, provided for timestamp, `ns.foo#Timestamp`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, + { + "ns.foo#Timestamp", + "\"2000-01-12T22:11:12+\"", + new String[]{ + "Invalid string value, `2000-01-12T22:11:12+`, provided for timestamp, `ns.foo#Timestamp`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, + { + "ns.foo#Timestamp", + "\"200-01-12T22:11:12Z\"", + new String[]{ + "Invalid string value, `200-01-12T22:11:12Z`, provided for timestamp, `ns.foo#Timestamp`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, + { + "ns.foo#Timestamp", + "\"2000-01-12T22:11:12+01:02\"", + new String[]{ + "Invalid string value, `2000-01-12T22:11:12+01:02`, provided for timestamp, `ns.foo#Timestamp`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, + { + "ns.foo#Timestamp", + "\"2000-01-12T22:11:12-11:00\"", + new String[]{ + "Invalid string value, `2000-01-12T22:11:12-11:00`, provided for timestamp, `ns.foo#Timestamp`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, + + // string + {"ns.foo#String1", "\"true\"", null}, + { + "ns.foo#String2", + "\"fooo\"", + new String[]{ + "String value provided for `ns.foo#String2` must be <= 3 characters, but the provided value is 4 characters."}}, + { + "ns.foo#String2", + "\"\"", + new String[]{ + "String value provided for `ns.foo#String2` must be >= 1 characters, but the provided value is only 0 characters."}}, + {"ns.foo#String2", "\"foo\"", null}, + { + "ns.foo#String3", + "\"qux\"", + new String[]{ + "String value provided for `ns.foo#String3` must be one of the following values: `bar`, `foo`"}}, + {"ns.foo#String3", "\"foo\"", null}, + {"ns.foo#String3", "\"bar\"", null}, + {"ns.foo#String4", "\"ABC\"", null}, + { + "ns.foo#String4", + "\"abc\"", + new String[]{ + "String value provided for `ns.foo#String4` must match regular expression: ^[A-Z]+$"}}, + + // list + {"ns.foo#List", "[\"a\"]", null}, + {"ns.foo#List", "[\"a\", \"b\"]", null}, + { + "ns.foo#List", + "[]", + new String[]{ + "Value provided for `ns.foo#List` must have at least 1 elements, but the provided value only has 0 elements"}}, + { + "ns.foo#List", + "[\"a\", \"b\", \"c\"]", + new String[]{ + "Value provided for `ns.foo#List` must have no more than 2 elements, but the provided value has 3 elements"}}, + { + "ns.foo#List", + "[10]", + new String[]{ + "0: Expected string value for string shape, `ns.foo#String`; found number value, `10`"}}, + { + "ns.foo#List", + "10", + new String[]{ + "Expected array value for list shape, `ns.foo#List`; found number value, `10`"}}, + + // unique list + {"ns.foo#UniqueList", "[\"a\"]", null}, + {"ns.foo#UniqueList", "[\"a\", \"b\"]", null}, + { + "ns.foo#UniqueList", + "[\"a\", \"a\"]", + new String[]{ + "Value provided for `ns.foo#UniqueList` must have unique items, but the following items had multiple entries: [`a`]"}}, + { + "ns.foo#UniqueList", + "[\"a\", \"a\", \"a\"]", + new String[]{ + "Value provided for `ns.foo#UniqueList` must have unique items, but the following items had multiple entries: [`a`]"}}, + { + "ns.foo#UniqueList", + "[\"a\", \"a\", \"b\", \"b\"]", + new String[]{ + "Value provided for `ns.foo#UniqueList` must have unique items, but the following items had multiple entries: [`a`, `b`]"}}, + + // map + {"ns.foo#Map", "{\"a\":[\"b\"]}", null}, + {"ns.foo#Map", "{\"a\":[\"b\"], \"c\":[\"d\"]}", null}, + // Too many elements + { + "ns.foo#Map", + "{\"a\":[\"b\"], \"c\":[\"d\"], \"e\":[\"f\"]}", + new String[]{ + "Value provided for `ns.foo#Map` must have no more than 2 entries, but the provided value has 3 entries"}}, + // Not enough elements + { + "ns.foo#Map", + "{}", + new String[]{ + "Value provided for `ns.foo#Map` must have at least 1 entries, but the provided value only has 0 entries"}}, + // Too many characters in string. + { + "ns.foo#Map", + "{\"abc\":[\"b\"], \"c\":[\"d\"]}", + new String[]{ + "abc (map-key): String value provided for `ns.foo#KeyString` must be <= 2 characters, but the provided value is 3 characters."}}, + // Too many elements in nested list + { + "ns.foo#Map", + "{\"a\":[\"b\", \"c\", \"d\", \"e\"]}", + new String[]{ + "a: Value provided for `ns.foo#List` must have no more than 2 elements, but the provided value has 4 elements"}}, + + // structure + {"ns.foo#Structure", "{\"foo\": \"test\"}", null}, + { + "ns.foo#Structure", + "{\"foo\": \"test\", \"invalid\": true}", + new String[]{"Invalid structure member `invalid` found for `ns.foo#Structure`"}}, + {"ns.foo#Structure", "{\"foo\": \"test\", \"baz\": \"baz\"}", null}, + { + "ns.foo#Structure", + "{\"foo\": \"test\", \"baz\": \"baz\", \"bar\": [\"a\", \"b\"], \"bam\": {\"foo\": \"test\"}}", + null}, + { + "ns.foo#Structure", + "{\"baz\": \"test\"}", + new String[]{"Missing required structure member `foo` for `ns.foo#Structure`"}}, + { + "ns.foo#Structure", + "{\"foo\": 10}", + new String[]{ + "foo: Expected string value for string shape, `ns.foo#String`; found number value, `10`"}}, + { + "ns.foo#Structure", + "{\"foo\": \"test\", \"baz\": 10}", + new String[]{ + "baz: Expected string value for string shape, `ns.foo#String`; found number value, `10`"}}, + { + "ns.foo#Structure", + "{\"foo\": \"test\", \"bam\": {}}", + new String[]{"bam: Missing required structure member `foo` for `ns.foo#Structure`"}}, + { + "ns.foo#Structure", + "{\"foo\": \"test\", \"bam\": {\"foo\": 10}}", + new String[]{ + "bam.foo: Expected string value for string shape, `ns.foo#String`; found number value, `10`"}}, + + // taggged union + {"ns.foo#TaggedUnion", "{\"foo\": \"test\"}", null}, + {"ns.foo#TaggedUnion", "{\"baz\": \"test\"}", null}, + { + "ns.foo#TaggedUnion", + "{\"foo\": \"test\", \"baz\": \"baz\"}", + new String[]{"union values can contain a value for only a single member"}}, + { + "ns.foo#TaggedUnion", + "{\"foo\": 10}", + new String[]{ + "foo: Expected string value for string shape, `ns.foo#String`; found number value, `10`"}}, + { + "ns.foo#TaggedUnion", + "{\"invalid\": true}", + new String[]{"Invalid union member `invalid` found for `ns.foo#TaggedUnion`"}}, + + // http-date + {"ns.foo#HttpDate", "\"Tue, 29 Apr 2014 18:30:38 GMT\"", null}, + { + "ns.foo#HttpDate", + "\"Tuesday, 29 April 2014 18:30:38 GMT\"", + new String[]{ + "Invalid value provided for http-date formatted timestamp. Expected a string value that matches the IMF-fixdate production of RFC 9110 section-5.6.7. Found: Tuesday, 29 April 2014 18:30:38 GMT"}}, + { + "ns.foo#HttpDate", + "\"Tue, 29 Apr 2014 18:30:38 PST\"", + new String[]{ + "Invalid value provided for http-date formatted timestamp. Expected a string value that matches the IMF-fixdate production of RFC 9110 section-5.6.7. Found: Tue, 29 Apr 2014 18:30:38 PST"}}, + { + "ns.foo#HttpDate", + "11", + new String[]{ + "Invalid value provided for http-date formatted timestamp. Expected a string value that matches the IMF-fixdate production of RFC 9110 section-5.6.7. Found: number"}}, + + // date-time + {"ns.foo#DateTime", "\"1985-04-12T23:20:50.52Z\"", null}, + { + "ns.foo#DateTime", + "1234", + new String[]{ + "Expected a string value for a date-time timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, + { + "ns.foo#DateTime", + "\"1985-04-12\"", + new String[]{ + "Invalid string value, `1985-04-12`, provided for timestamp, `ns.foo#DateTime`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, + { + "ns.foo#DateTime", + "\"Tuesday, 29 April 2014 18:30:38 GMT\"", + new String[]{ + "Invalid string value, `Tuesday, 29 April 2014 18:30:38 GMT`, provided for timestamp, `ns.foo#DateTime`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, + { + "ns.foo#DateTime", + "\"1985-04-12T23:20:50.52-07:00\"", + new String[]{ + "Invalid string value, `1985-04-12T23:20:50.52-07:00`, provided for timestamp, `ns.foo#DateTime`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, + + // epoch seconds + {"ns.foo#EpochSeconds", "123", null}, + { + "ns.foo#EpochSeconds", + "\"1985-04-12T23:20:50.52Z\"", + new String[]{ + "Invalid string value provided for a timestamp with a `epoch-seconds` format."}}, + + // timestamp member with format. + {"ns.foo#TimestampList", "[\"1985-04-12T23:20:50.52Z\"]", null}, + { + "ns.foo#TimestampList", + "[\"1985-04-12T23:20:50.52-07:00\"]", + new String[]{ + "0: Invalid string value, `1985-04-12T23:20:50.52-07:00`, provided for timestamp, `ns.foo#TimestampList$member`. Expected an RFC 3339 formatted timestamp (e.g., \"1985-04-12T23:20:50.52Z\")" + }}, + { + "ns.foo#TimestampList", + "[123]", + new String[]{ + "0: Expected a string value for a date-time timestamp (e.g., \"1985-04-12T23:20:50.52Z\")"}}, + { + "ns.foo#Structure4", + "{\"httpDate\": 1234}", + new String[]{ + "httpDate: Invalid value provided for http-date formatted timestamp. Expected a string value that matches the IMF-fixdate production of RFC 9110 section-5.6.7. Found: number"}}, + { + "ns.foo#Structure4", + "{\"httpDateTarget\": 1234}", + new String[]{ + "httpDateTarget: Invalid value provided for http-date formatted timestamp. Expected a string value that matches the IMF-fixdate production of RFC 9110 section-5.6.7. Found: number"}}, + + // timestamp member with no format. + {"ns.foo#TimestampListNoFormatTrait", "[123]", null}, + + // Member validation + {"ns.foo#Structure2", "{\"a\": \"23 abc\"}", null}, + { + "ns.foo#Structure2", + "{\"a\": \"abc\"}", + new String[]{ + "a: String value provided for `ns.foo#Structure2$a` must match regular expression: ^[0-9]"}}, + {"ns.foo#Structure2", "{\"b\": \"12345678910\"}", null}, + { + "ns.foo#Structure2", + "{\"b\": \"123\"}", + new String[]{ + "b: String value provided for `ns.foo#Structure2$b` must be >= 10 characters, but the provided value is only 3 characters."}}, + {"ns.foo#Structure2", "{\"c\": 11}", null}, + { + "ns.foo#Structure2", + "{\"c\": 5}", + new String[]{ + "c: Value provided for `ns.foo#Structure2$c` must be greater than or equal to 10, but found 5"}} + } ); } @Test public void canSuccessfullyValidateTimestampsAsUnixTimestamps() { NodeValidationVisitor visitor = NodeValidationVisitor.builder() - .value(Node.from(1234)) - .model(MODEL) - .timestampValidationStrategy(TimestampValidationStrategy.EPOCH_SECONDS) - .build(); + .value(Node.from(1234)) + .model(MODEL) + .timestampValidationStrategy(TimestampValidationStrategy.EPOCH_SECONDS) + .build(); List events = MODEL - .expectShape(ShapeId.from("ns.foo#TimestampList$member")) - .accept(visitor); + .expectShape(ShapeId.from("ns.foo#TimestampList$member")) + .accept(visitor); assertThat(events, empty()); } @@ -641,13 +658,13 @@ public void canSuccessfullyValidateTimestampsAsUnixTimestamps() { @Test public void canUnsuccessfullyValidateTimestampsAsUnixTimestamps() { NodeValidationVisitor visitor = NodeValidationVisitor.builder() - .value(Node.from("foo")) - .model(MODEL) - .timestampValidationStrategy(TimestampValidationStrategy.EPOCH_SECONDS) - .build(); + .value(Node.from("foo")) + .model(MODEL) + .timestampValidationStrategy(TimestampValidationStrategy.EPOCH_SECONDS) + .build(); List events = MODEL - .expectShape(ShapeId.from("ns.foo#TimestampList$member")) - .accept(visitor); + .expectShape(ShapeId.from("ns.foo#TimestampList$member")) + .accept(visitor); assertThat(events, not(empty())); } @@ -655,12 +672,12 @@ public void canUnsuccessfullyValidateTimestampsAsUnixTimestamps() { @Test public void doesNotAllowNullByDefault() { NodeValidationVisitor visitor = NodeValidationVisitor.builder() - .value(Node.nullNode()) - .model(MODEL) - .build(); + .value(Node.nullNode()) + .model(MODEL) + .build(); List events = MODEL - .expectShape(ShapeId.from("smithy.api#String")) - .accept(visitor); + .expectShape(ShapeId.from("smithy.api#String")) + .accept(visitor); assertThat(events, not(empty())); } @@ -668,13 +685,13 @@ public void doesNotAllowNullByDefault() { @Test public void canConfigureToSupportNull() { NodeValidationVisitor visitor = NodeValidationVisitor.builder() - .value(Node.nullNode()) - .model(MODEL) - .allowOptionalNull(true) - .build(); + .value(Node.nullNode()) + .model(MODEL) + .allowOptionalNull(true) + .build(); List events = MODEL - .expectShape(ShapeId.from("smithy.api#String")) - .accept(visitor); + .expectShape(ShapeId.from("smithy.api#String")) + .accept(visitor); assertThat(events, empty()); } @@ -682,62 +699,62 @@ public void canConfigureToSupportNull() { @Test public void nullRequiredStructureMember() { ObjectNode structure = ObjectNode.builder() - .withMember("foo", Node.nullNode()) - .build(); + .withMember("foo", Node.nullNode()) + .build(); NodeValidationVisitor visitor = NodeValidationVisitor.builder() - .value(structure) - .model(MODEL) - .allowOptionalNull(true) - .build(); + .value(structure) + .model(MODEL) + .allowOptionalNull(true) + .build(); List events = MODEL - .expectShape(ShapeId.from("ns.foo#Structure")) - .accept(visitor); + .expectShape(ShapeId.from("ns.foo#Structure")) + .accept(visitor); assertThat(events, hasSize(1)); assertThat( - events.get(0).getMessage(), - containsString( - "foo: Required structure member `foo` for `ns.foo#Structure` cannot be null" - ) + events.get(0).getMessage(), + containsString( + "foo: Required structure member `foo` for `ns.foo#Structure` cannot be null" + ) ); } @Test public void nullNonSparseListMember() { ArrayNode list = ArrayNode.builder() - .withValue(Node.nullNode()) - .build(); + .withValue(Node.nullNode()) + .build(); NodeValidationVisitor visitor = NodeValidationVisitor.builder() - .value(list) - .model(MODEL) - .allowOptionalNull(true) - .build(); + .value(list) + .model(MODEL) + .allowOptionalNull(true) + .build(); List events = MODEL - .expectShape(ShapeId.from("ns.foo#List")) - .accept(visitor); + .expectShape(ShapeId.from("ns.foo#List")) + .accept(visitor); assertThat(events, hasSize(1)); assertThat( - events.get(0).getMessage(), - containsString( - "0: Non-sparse list shape `ns.foo#List` cannot contain null values" - ) + events.get(0).getMessage(), + containsString( + "0: Non-sparse list shape `ns.foo#List` cannot contain null values" + ) ); } @Test public void nullSparseListMember() { ArrayNode list = ArrayNode.builder() - .withValue(Node.nullNode()) - .build(); + .withValue(Node.nullNode()) + .build(); NodeValidationVisitor visitor = NodeValidationVisitor.builder() - .value(list) - .model(MODEL) - .allowOptionalNull(true) - .build(); + .value(list) + .model(MODEL) + .allowOptionalNull(true) + .build(); List events = MODEL - .expectShape(ShapeId.from("ns.foo#SparseList")) - .accept(visitor); + .expectShape(ShapeId.from("ns.foo#SparseList")) + .accept(visitor); assertThat(events, empty()); } @@ -745,39 +762,39 @@ public void nullSparseListMember() { @Test public void nullNonSparseMapValue() { ObjectNode map = ObjectNode.builder() - .withMember("a", Node.nullNode()) - .build(); + .withMember("a", Node.nullNode()) + .build(); NodeValidationVisitor visitor = NodeValidationVisitor.builder() - .value(map) - .model(MODEL) - .allowOptionalNull(true) - .build(); + .value(map) + .model(MODEL) + .allowOptionalNull(true) + .build(); List events = MODEL - .expectShape(ShapeId.from("ns.foo#Map")) - .accept(visitor); + .expectShape(ShapeId.from("ns.foo#Map")) + .accept(visitor); assertThat(events, hasSize(1)); assertThat( - events.get(0).getMessage(), - containsString( - "a: Non-sparse map shape `ns.foo#Map` cannot contain null values" - ) + events.get(0).getMessage(), + containsString( + "a: Non-sparse map shape `ns.foo#Map` cannot contain null values" + ) ); } @Test public void nullSparseMapValue() { ObjectNode map = ObjectNode.builder() - .withMember("a", Node.nullNode()) - .build(); + .withMember("a", Node.nullNode()) + .build(); NodeValidationVisitor visitor = NodeValidationVisitor.builder() - .value(map) - .model(MODEL) - .allowOptionalNull(true) - .build(); + .value(map) + .model(MODEL) + .allowOptionalNull(true) + .build(); List events = MODEL - .expectShape(ShapeId.from("ns.foo#SparseMap")) - .accept(visitor); + .expectShape(ShapeId.from("ns.foo#SparseMap")) + .accept(visitor); assertThat(events, empty()); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/validation/ServiceValidatorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/validation/ServiceValidatorTest.java index 980dd94fe66..8503da0d440 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/validation/ServiceValidatorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/validation/ServiceValidatorTest.java @@ -19,29 +19,29 @@ public class ServiceValidatorTest { @Test public void allowsValidRenames() { StructureShape baz1 = StructureShape.builder() - .id("smithy.example#Baz") - .build(); + .id("smithy.example#Baz") + .build(); StructureShape baz2 = StructureShape.builder() - .id("foo#Baz") - .build(); + .id("foo#Baz") + .build(); StructureShape output = StructureShape.builder() - .id("smithy.example#Ouput") - .addMember("a", baz1.getId()) - .addMember("b", baz2.getId()) - .build(); + .id("smithy.example#Ouput") + .addMember("a", baz1.getId()) + .addMember("b", baz2.getId()) + .build(); OperationShape operation = OperationShape.builder() - .id("smithy.example#Operation") - .output(output) - .build(); + .id("smithy.example#Operation") + .output(output) + .build(); ServiceShape service = ServiceShape.builder() - .version("1") - .id("smithy.example#Service") - .addOperation(operation) - .putRename(ShapeId.from("foo#Baz"), "FooBaz") - .build(); + .version("1") + .id("smithy.example#Service") + .addOperation(operation) + .putRename(ShapeId.from("foo#Baz"), "FooBaz") + .build(); Model model = Model.builder() - .addShapes(service, operation, output, baz2, baz1) - .build(); + .addShapes(service, operation, output, baz2, baz1) + .build(); ServiceValidator validator = new ServiceValidator(); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/validation/ValidationEventTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/validation/ValidationEventTest.java index 5f6e03e9889..767e264fee4 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/validation/ValidationEventTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/validation/ValidationEventTest.java @@ -28,9 +28,9 @@ public class ValidationEventTest { public void requiresMessage() { Assertions.assertThrows(IllegalStateException.class, () -> { ValidationEvent.builder() - .severity(Severity.ERROR) - .id("foo") - .build(); + .severity(Severity.ERROR) + .id("foo") + .build(); }); } @@ -38,9 +38,9 @@ public void requiresMessage() { public void requiresSeverity() { Assertions.assertThrows(IllegalStateException.class, () -> { ValidationEvent.builder() - .message("test") - .id("foo") - .build(); + .message("test") + .id("foo") + .build(); }); } @@ -48,9 +48,9 @@ public void requiresSeverity() { public void requiresId() { Assertions.assertThrows(IllegalStateException.class, () -> { ValidationEvent.builder() - .severity(Severity.ERROR) - .message("test") - .build(); + .severity(Severity.ERROR) + .message("test") + .build(); }); } @@ -58,11 +58,11 @@ public void requiresId() { public void suppressionIsOnlyValidWithSuppress() { Assertions.assertThrows(IllegalStateException.class, () -> { ValidationEvent.builder() - .severity(Severity.ERROR) - .message("test") - .id("foo") - .suppressionReason("Some reason") - .build(); + .severity(Severity.ERROR) + .message("test") + .id("foo") + .suppressionReason("Some reason") + .build(); }); } @@ -70,11 +70,11 @@ public void suppressionIsOnlyValidWithSuppress() { public void loadsWithFromNode() { ShapeId id = ShapeId.from("ns.foo#baz"); ValidationEvent event = ValidationEvent.fromNode( - Node.parse( - "{\"id\": \"abc.foo\", \"severity\": \"SUPPRESSED\", \"suppressionReason\": \"my reason\", " - + "\"shapeId\": \"ns.foo#baz\", \"message\": \"The message\", " - + "\"filename\": \"/path/to/file.smithy\", \"line\": 7, \"column\": 2}" - ) + Node.parse( + "{\"id\": \"abc.foo\", \"severity\": \"SUPPRESSED\", \"suppressionReason\": \"my reason\", " + + "\"shapeId\": \"ns.foo#baz\", \"message\": \"The message\", " + + "\"filename\": \"/path/to/file.smithy\", \"line\": 7, \"column\": 2}" + ) ); assertThat(event.getSeverity(), equalTo(Severity.SUPPRESSED)); @@ -88,11 +88,11 @@ public void loadsWithFromNode() { public void loadsWithFromNodeWithHint() { ShapeId id = ShapeId.from("ns.foo#baz"); ValidationEvent event = ValidationEvent.fromNode( - Node.parse( - "{\"id\": \"abc.foo\", \"severity\": \"SUPPRESSED\", \"suppressionReason\": \"my reason\", " - + "\"shapeId\": \"ns.foo#baz\", \"message\": \"The message\", " - + "\"hint\": \"The hint\", \"filename\": \"/path/to/file.smithy\", \"line\": 7, \"column\": 2}" - ) + Node.parse( + "{\"id\": \"abc.foo\", \"severity\": \"SUPPRESSED\", \"suppressionReason\": \"my reason\", " + + "\"shapeId\": \"ns.foo#baz\", \"message\": \"The message\", " + + "\"hint\": \"The hint\", \"filename\": \"/path/to/file.smithy\", \"line\": 7, \"column\": 2}" + ) ); assertThat(event.getSeverity(), equalTo(Severity.SUPPRESSED)); @@ -107,13 +107,13 @@ public void loadsWithFromNodeWithHint() { public void hasGetters() { ShapeId id = ShapeId.from("ns.foo#baz"); ValidationEvent event = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .shapeId(id) - .id("abc.foo") - .suppressionReason("my reason") - .hint("The hint") - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .shapeId(id) + .id("abc.foo") + .suppressionReason("my reason") + .hint("The hint") + .build(); assertThat(event.getSeverity(), equalTo(Severity.SUPPRESSED)); assertThat(event.getMessage(), equalTo("The message")); @@ -128,11 +128,11 @@ public void hasGetters() { public void usesShapeSourceWhenPresent() { StringShape stringShape = StringShape.builder().id("ns.foo#bar").source("file", 1, 2).build(); ValidationEvent event = ValidationEvent.builder() - .message("The message") - .severity(Severity.ERROR) - .shape(stringShape) - .id("abc.foo") - .build(); + .message("The message") + .severity(Severity.ERROR) + .shape(stringShape) + .id("abc.foo") + .build(); assertThat(event.getSourceLocation(), is(stringShape.getSourceLocation())); } @@ -141,12 +141,12 @@ public void usesShapeSourceWhenPresent() { public void usesEmptyLocationWhenNoneSet() { ShapeId id = ShapeId.from("ns.foo#baz"); ValidationEvent event = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .shapeId(id) - .id("abc.foo") - .suppressionReason("my reason") - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .shapeId(id) + .id("abc.foo") + .suppressionReason("my reason") + .build(); assertThat(event.getSourceLocation(), is(SourceLocation.none())); } @@ -154,13 +154,13 @@ public void usesEmptyLocationWhenNoneSet() { @Test public void createsEventBuilderFromEvent() { ValidationEvent event = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .shapeId(ShapeId.from("ns.foo#baz")) - .id("abc.foo") - .hint("The hint") - .suppressionReason("my reason") - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .shapeId(ShapeId.from("ns.foo#baz")) + .id("abc.foo") + .hint("The hint") + .suppressionReason("my reason") + .build(); ValidationEvent other = event.toBuilder().build(); assertThat(event, equalTo(other)); @@ -169,11 +169,11 @@ public void createsEventBuilderFromEvent() { @Test public void sameInstanceIsEqual() { ValidationEvent a = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .shapeId(ShapeId.from("ns.foo#bar")) - .id("abc.foo") - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .shapeId(ShapeId.from("ns.foo#bar")) + .id("abc.foo") + .build(); assertEquals(a, a); } @@ -181,11 +181,11 @@ public void sameInstanceIsEqual() { @Test public void differentTypesAreNotEqual() { ValidationEvent a = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .shapeId(ShapeId.from("ns.foo#bar")) - .id("abc.foo") - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .shapeId(ShapeId.from("ns.foo#bar")) + .id("abc.foo") + .build(); assertNotEquals(a, "test"); } @@ -193,11 +193,11 @@ public void differentTypesAreNotEqual() { @Test public void differentMessagesAreNotEqual() { ValidationEvent a = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .shapeId(ShapeId.from("ns.foo#bar")) - .id("abc.foo") - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .shapeId(ShapeId.from("ns.foo#bar")) + .id("abc.foo") + .build(); ValidationEvent b = a.toBuilder().message("other message").build(); assertNotEquals(a, b); @@ -207,11 +207,11 @@ public void differentMessagesAreNotEqual() { @Test public void differentSeveritiesAreNotEqual() { ValidationEvent a = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .shapeId(ShapeId.from("ns.foo#bar")) - .id("abc.foo") - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .shapeId(ShapeId.from("ns.foo#bar")) + .id("abc.foo") + .build(); ValidationEvent b = a.toBuilder().severity(Severity.ERROR).build(); assertNotEquals(a, b); @@ -221,13 +221,13 @@ public void differentSeveritiesAreNotEqual() { @Test public void differentSourceLocationsAreNotEqual() { ValidationEvent a = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .shapeId(ShapeId.from("ns.foo#bar")) - .id("abc.foo") - .suppressionReason("my reason") - .sourceLocation(SourceLocation.none()) - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .shapeId(ShapeId.from("ns.foo#bar")) + .id("abc.foo") + .suppressionReason("my reason") + .sourceLocation(SourceLocation.none()) + .build(); ValidationEvent b = a.toBuilder().sourceLocation(new SourceLocation("foo", 10, 0)).build(); assertNotEquals(a, b); @@ -237,13 +237,13 @@ public void differentSourceLocationsAreNotEqual() { @Test public void differentShapeIdAreNotEqual() { ValidationEvent a = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .shapeId(ShapeId.from("ns.foo#bar")) - .id("abc.foo") - .suppressionReason("my reason") - .sourceLocation(SourceLocation.none()) - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .shapeId(ShapeId.from("ns.foo#bar")) + .id("abc.foo") + .suppressionReason("my reason") + .sourceLocation(SourceLocation.none()) + .build(); ValidationEvent b = a.toBuilder().shapeId(ShapeId.from("ns.foo#qux")).build(); assertNotEquals(a, b); @@ -253,13 +253,13 @@ public void differentShapeIdAreNotEqual() { @Test public void differentEventIdAreNotEqual() { ValidationEvent a = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .shapeId(ShapeId.from("ns.foo#bar")) - .id("abc.foo") - .suppressionReason("my reason") - .sourceLocation(SourceLocation.none()) - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .shapeId(ShapeId.from("ns.foo#bar")) + .id("abc.foo") + .suppressionReason("my reason") + .sourceLocation(SourceLocation.none()) + .build(); ValidationEvent b = a.toBuilder().id("other.id").build(); assertNotEquals(a, b); @@ -269,13 +269,13 @@ public void differentEventIdAreNotEqual() { @Test public void differentSuppressionReasonAreNotEqual() { ValidationEvent a = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .shapeId(ShapeId.from("ns.foo#bar")) - .id("abc.foo") - .suppressionReason("my reason") - .sourceLocation(SourceLocation.none()) - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .shapeId(ShapeId.from("ns.foo#bar")) + .id("abc.foo") + .suppressionReason("my reason") + .sourceLocation(SourceLocation.none()) + .build(); ValidationEvent b = a.toBuilder().suppressionReason("other reason").build(); assertNotEquals(a, b); @@ -285,14 +285,14 @@ public void differentSuppressionReasonAreNotEqual() { @Test public void differentHintAreNotEqual() { ValidationEvent a = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .shapeId(ShapeId.from("ns.foo#bar")) - .id("abc.foo") - .suppressionReason("my reason") - .hint("The hint") - .sourceLocation(SourceLocation.none()) - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .shapeId(ShapeId.from("ns.foo#bar")) + .id("abc.foo") + .suppressionReason("my reason") + .hint("The hint") + .sourceLocation(SourceLocation.none()) + .build(); ValidationEvent b = a.toBuilder().hint("other hint").build(); assertNotEquals(a, b); @@ -302,10 +302,10 @@ public void differentHintAreNotEqual() { @Test public void toStringContainsSeverityAndEventId() { ValidationEvent a = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .id("abc.foo") - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .id("abc.foo") + .build(); assertEquals(a.toString(), "[SUPPRESSED] -: The message | abc.foo N/A:0:0"); } @@ -313,11 +313,11 @@ public void toStringContainsSeverityAndEventId() { @Test public void toStringContainsShapeId() { ValidationEvent a = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .id("abc.foo") - .shapeId(ShapeId.from("ns.foo#baz")) - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .id("abc.foo") + .shapeId(ShapeId.from("ns.foo#baz")) + .build(); assertEquals(a.toString(), "[SUPPRESSED] ns.foo#baz: The message | abc.foo N/A:0:0"); } @@ -325,12 +325,12 @@ public void toStringContainsShapeId() { @Test public void toStringContainsSourceLocation() { ValidationEvent a = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .id("abc.foo") - .shapeId(ShapeId.from("ns.foo#baz")) - .sourceLocation(new SourceLocation("file", 1, 2)) - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .id("abc.foo") + .shapeId(ShapeId.from("ns.foo#baz")) + .sourceLocation(new SourceLocation("file", 1, 2)) + .build(); assertEquals(a.toString(), "[SUPPRESSED] ns.foo#baz: The message | abc.foo file:1:2"); } @@ -338,13 +338,13 @@ public void toStringContainsSourceLocation() { @Test public void toStringContainsSuppressionReason() { ValidationEvent a = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .id("abc.foo") - .shapeId(ShapeId.from("ns.foo#baz")) - .suppressionReason("Foo baz bar") - .sourceLocation(new SourceLocation("file", 1, 2)) - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .id("abc.foo") + .shapeId(ShapeId.from("ns.foo#baz")) + .suppressionReason("Foo baz bar") + .sourceLocation(new SourceLocation("file", 1, 2)) + .build(); assertEquals(a.toString(), "[SUPPRESSED] ns.foo#baz: The message (Foo baz bar) | abc.foo file:1:2"); } @@ -352,14 +352,14 @@ public void toStringContainsSuppressionReason() { @Test public void toStringDoesContainsHint() { ValidationEvent a = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .id("abc.foo") - .shapeId(ShapeId.from("ns.foo#baz")) - .suppressionReason("Foo baz bar") - .hint("The hint") - .sourceLocation(new SourceLocation("file", 1, 2)) - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .id("abc.foo") + .shapeId(ShapeId.from("ns.foo#baz")) + .suppressionReason("Foo baz bar") + .hint("The hint") + .sourceLocation(new SourceLocation("file", 1, 2)) + .build(); assertEquals(a.toString(), "[SUPPRESSED] ns.foo#baz: The message (Foo baz bar) [The hint] | abc.foo file:1:2"); } @@ -367,12 +367,12 @@ public void toStringDoesContainsHint() { @Test public void convertsToNode() { ValidationEvent a = ValidationEvent.builder() - .message("The message") - .severity(Severity.SUPPRESSED) - .id("abc.foo") - .shapeId(ShapeId.from("ns.foo#baz")) - .sourceLocation(new SourceLocation("file", 1, 2)) - .build(); + .message("The message") + .severity(Severity.SUPPRESSED) + .id("abc.foo") + .shapeId(ShapeId.from("ns.foo#baz")) + .sourceLocation(new SourceLocation("file", 1, 2)) + .build(); ObjectNode result = a.toNode().expectObjectNode(); assertEquals(result.getMember("id").get().asStringNode().get().getValue(), "abc.foo"); @@ -391,24 +391,24 @@ public void suppressesEventIds(boolean match, String eventId, String testId) { public static Stream containsIdSupplier() { return Stream.of( - Arguments.of(true, "BadThing", "BadThing"), - Arguments.of(true, "BadThing.Foo", "BadThing"), - Arguments.of(true, "BadThing.Foo", "BadThing.Foo"), - Arguments.of(true, "BadThing.Foo.Bar", "BadThing.Foo.Bar"), - - Arguments.of(false, "BadThing.Foo", "BadThing.Foo.Bar"), - Arguments.of(false, "BadThing.Foo", "BadThing.Foo.Bar.Baz"), - Arguments.of(false, "BadThing.Fooz", "BadThing.Foo"), - Arguments.of(false, "BadThing.Foo.Bar", "BadThing.Foo.Bar.Baz"), - - // Tests for strange, but acceptable ids and suppression IDs. Preventing these now is - // technically backward incompatible, so they're acceptable. - Arguments.of(true, "BadThing.", "BadThing."), - Arguments.of(true, "BadThing.", "BadThing"), - Arguments.of(false, "BadThing", "BadThing."), - Arguments.of(true, "BadThing.Foo.", "BadThing.Foo"), - Arguments.of(true, "BadThing.Foo.", "BadThing.Foo."), - Arguments.of(false, "BadThing.Foo.", "BadThing.Foo.Bar") + Arguments.of(true, "BadThing", "BadThing"), + Arguments.of(true, "BadThing.Foo", "BadThing"), + Arguments.of(true, "BadThing.Foo", "BadThing.Foo"), + Arguments.of(true, "BadThing.Foo.Bar", "BadThing.Foo.Bar"), + + Arguments.of(false, "BadThing.Foo", "BadThing.Foo.Bar"), + Arguments.of(false, "BadThing.Foo", "BadThing.Foo.Bar.Baz"), + Arguments.of(false, "BadThing.Fooz", "BadThing.Foo"), + Arguments.of(false, "BadThing.Foo.Bar", "BadThing.Foo.Bar.Baz"), + + // Tests for strange, but acceptable ids and suppression IDs. Preventing these now is + // technically backward incompatible, so they're acceptable. + Arguments.of(true, "BadThing.", "BadThing."), + Arguments.of(true, "BadThing.", "BadThing"), + Arguments.of(false, "BadThing", "BadThing."), + Arguments.of(true, "BadThing.Foo.", "BadThing.Foo"), + Arguments.of(true, "BadThing.Foo.", "BadThing.Foo."), + Arguments.of(false, "BadThing.Foo.", "BadThing.Foo.Bar") ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/validation/linters/EmitEachSelectorValidatorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/validation/linters/EmitEachSelectorValidatorTest.java index bebd0e8e758..989b243b743 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/validation/linters/EmitEachSelectorValidatorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/validation/linters/EmitEachSelectorValidatorTest.java @@ -39,21 +39,21 @@ public void messageTemplateCanBeCastToString() { public void expandsMessageTemplates() { EmitEachSelectorValidator.Config config = new EmitEachSelectorValidator.Config(); Model model = Model.builder() - .addShape( - StringShape.builder() - .id(ShapeId.from("foo.bar#Baz")) - .addTrait(new DocumentationTrait("hello")) - .build() - ) - .build(); + .addShape( + StringShape.builder() + .id(ShapeId.from("foo.bar#Baz")) + .addTrait(new DocumentationTrait("hello")) + .build() + ) + .build(); config.setSelector(Selector.parse("$foo(*)")); config.setMessageTemplate("before `@{trait|documentation}` after. ID: @{id}. Var: @{var|foo|id}."); EmitEachSelectorValidator validator = new EmitEachSelectorValidator(config); List events = validator.validate(model); assertThat( - events.get(0).getMessage(), - equalTo("before `\"hello\"` after. ID: foo.bar#Baz. Var: [foo.bar#Baz].") + events.get(0).getMessage(), + equalTo("before `\"hello\"` after. ID: foo.bar#Baz. Var: [foo.bar#Baz].") ); } @@ -61,14 +61,14 @@ public void expandsMessageTemplates() { public void onlyEmitsEventsWhenShapeHasBoundTraitAndNoTemplate() { EmitEachSelectorValidator.Config config = new EmitEachSelectorValidator.Config(); Model model = Model.builder() - .addShape( - StringShape.builder() - .id(ShapeId.from("foo.bar#A")) - .addTrait(new DocumentationTrait("hello")) - .build() - ) - .addShape(StringShape.builder().id(ShapeId.from("foo.bar#B")).build()) - .build(); + .addShape( + StringShape.builder() + .id(ShapeId.from("foo.bar#A")) + .addTrait(new DocumentationTrait("hello")) + .build() + ) + .addShape(StringShape.builder().id(ShapeId.from("foo.bar#B")).build()) + .build(); config.setSelector(Selector.parse("*")); config.setBindToTrait(DocumentationTrait.ID); EmitEachSelectorValidator validator = new EmitEachSelectorValidator(config); @@ -82,14 +82,14 @@ public void onlyEmitsEventsWhenShapeHasBoundTraitAndNoTemplate() { public void onlyEmitsEventsWhenShapeHasBoundTraitAndHasTemplate() { EmitEachSelectorValidator.Config config = new EmitEachSelectorValidator.Config(); Model model = Model.builder() - .addShape( - StringShape.builder() - .id(ShapeId.from("foo.bar#A")) - .addTrait(new DocumentationTrait("hello")) - .build() - ) - .addShape(StringShape.builder().id(ShapeId.from("foo.bar#B")).build()) - .build(); + .addShape( + StringShape.builder() + .id(ShapeId.from("foo.bar#A")) + .addTrait(new DocumentationTrait("hello")) + .build() + ) + .addShape(StringShape.builder().id(ShapeId.from("foo.bar#B")).build()) + .build(); config.setSelector(Selector.parse("*")); config.setMessageTemplate("This is only set to test the necessary code path of using templates..."); config.setBindToTrait(DocumentationTrait.ID); @@ -104,8 +104,8 @@ public void onlyEmitsEventsWhenShapeHasBoundTraitAndHasTemplate() { public void skipsUsingTheActualValidatorIfNoTraitsUseTheBoundTrait() { EmitEachSelectorValidator.Config config = new EmitEachSelectorValidator.Config(); Model model = Model.builder() - .addShape(StringShape.builder().id(ShapeId.from("foo.bar#A")).build()) - .build(); + .addShape(StringShape.builder().id(ShapeId.from("foo.bar#A")).build()) + .build(); config.setSelector(Selector.parse("*")); config.setBindToTrait(DocumentationTrait.ID); EmitEachSelectorValidator validator = new EmitEachSelectorValidator(config); @@ -120,8 +120,8 @@ public void handlesEscapesAtSymbols() { config.setMessageTemplate("A@@@@B"); EmitEachSelectorValidator validator = new EmitEachSelectorValidator(config); Model model = Model.builder() - .addShape(StringShape.builder().id(ShapeId.from("foo.bar#Baz")).build()) - .build(); + .addShape(StringShape.builder().id(ShapeId.from("foo.bar#Baz")).build()) + .build(); List events = validator.validate(model); assertThat(events, hasSize(1)); @@ -138,8 +138,8 @@ public void validatesMessageTemplateIsNotUnclosed() { }); assertThat( - e.getMessage(), - containsString("Syntax error at line 1 column 12 of EmitEachSelector message template") + e.getMessage(), + containsString("Syntax error at line 1 column 12 of EmitEachSelector message template") ); } @@ -153,8 +153,8 @@ public void validatesMessageTemplateIsNotEmpty() { }); assertThat( - e.getMessage(), - containsString("Syntax error at line 1 column 3 of EmitEachSelector message template") + e.getMessage(), + containsString("Syntax error at line 1 column 3 of EmitEachSelector message template") ); } @@ -168,8 +168,8 @@ public void validatesMessageTemplateWithTrailingPipe() { }); assertThat( - e.getMessage(), - containsString("Syntax error at line 1 column 7 of EmitEachSelector message template") + e.getMessage(), + containsString("Syntax error at line 1 column 7 of EmitEachSelector message template") ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/validation/suppressions/MetadataSuppressionTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/validation/suppressions/MetadataSuppressionTest.java index e1a48296854..a719c340e4b 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/validation/suppressions/MetadataSuppressionTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/validation/suppressions/MetadataSuppressionTest.java @@ -24,17 +24,17 @@ public class MetadataSuppressionTest { @Test public void doesNotMatchWhenUsingDifferentNamespace() { ObjectNode node = Node.objectNodeBuilder() - .withMember("id", "Foo") - .withMember("namespace", "smithy.example.nested") - .build(); + .withMember("id", "Foo") + .withMember("namespace", "smithy.example.nested") + .build(); Shape s = StringShape.builder().id("smithy.example#String").build(); Suppression suppression = Suppression.fromMetadata(node); ValidationEvent event = ValidationEvent.builder() - .id("Foo") - .shape(s) - .severity(Severity.DANGER) - .message("test") - .build(); + .id("Foo") + .shape(s) + .severity(Severity.DANGER) + .message("test") + .build(); assertThat(suppression.test(event), is(false)); } @@ -43,15 +43,15 @@ public void doesNotMatchWhenUsingDifferentNamespace() { @MethodSource("suppressions") public void suppressesEventIds(boolean match, String eventId, String suppressionId) { ObjectNode node = Node.objectNodeBuilder() - .withMember("id", suppressionId) - .withMember("namespace", "*") - .build(); + .withMember("id", suppressionId) + .withMember("namespace", "*") + .build(); Suppression suppression = Suppression.fromMetadata(node); ValidationEvent event = ValidationEvent.builder() - .id(eventId) - .severity(Severity.DANGER) - .message("test") - .build(); + .id(eventId) + .severity(Severity.DANGER) + .message("test") + .build(); assertThat(eventId + " is " + match + " match for " + suppressionId, suppression.test(event), is(match)); } @@ -59,11 +59,11 @@ public void suppressesEventIds(boolean match, String eventId, String suppression // See tests for ValidationEvent#containsId for exhaustive test cases. public static Stream suppressions() { return Stream.of( - Arguments.of(true, "BadThing", "BadThing"), - Arguments.of(true, "BadThing.Foo", "BadThing"), - Arguments.of(false, "BadThing.Foo", "BadThing.Foo.Bar"), - Arguments.of(false, "BadThing.Foo", "BadThing.Foo.Bar.Baz"), - Arguments.of(false, "BadThing.Fooz", "BadThing.Foo") + Arguments.of(true, "BadThing", "BadThing"), + Arguments.of(true, "BadThing.Foo", "BadThing"), + Arguments.of(false, "BadThing.Foo", "BadThing.Foo.Bar"), + Arguments.of(false, "BadThing.Foo", "BadThing.Foo.Bar.Baz"), + Arguments.of(false, "BadThing.Fooz", "BadThing.Foo") ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/validation/suppressions/ModelBasedEventDecoratorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/validation/suppressions/ModelBasedEventDecoratorTest.java index 7ad4b1dda30..fc9255b90b8 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/validation/suppressions/ModelBasedEventDecoratorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/validation/suppressions/ModelBasedEventDecoratorTest.java @@ -28,10 +28,10 @@ public class ModelBasedEventDecoratorTest { @Test public void erroneousSuppressionsEmitEvents() { ValidatedResult result = Model.assembler() - .addImport(getClass().getResource("bad-suppressions.smithy")) - // Ensure that events found while loading the model are decorated too. - .validatorFactory(testFactory(event -> event.toBuilder().hint("hi").build())) - .assemble(); + .addImport(getClass().getResource("bad-suppressions.smithy")) + // Ensure that events found while loading the model are decorated too. + .validatorFactory(testFactory(event -> event.toBuilder().hint("hi").build())) + .assemble(); assertThat(result.getValidationEvents(Severity.ERROR), not(empty())); assertThat(result.getValidationEvents(Severity.ERROR).get(0).getMessage(), containsString("member `id`")); @@ -41,10 +41,10 @@ public void erroneousSuppressionsEmitEvents() { @Test public void erroneousOverridesEmitEvents() { ValidatedResult result = Model.assembler() - .addImport(getClass().getResource("bad-severityOverrides.smithy")) - // Ensure that events found while loading the model are decorated too. - .validatorFactory(testFactory(event -> event.toBuilder().hint("hi").build())) - .assemble(); + .addImport(getClass().getResource("bad-severityOverrides.smithy")) + // Ensure that events found while loading the model are decorated too. + .validatorFactory(testFactory(event -> event.toBuilder().hint("hi").build())) + .assemble(); assertThat(result.getValidationEvents(Severity.ERROR), not(empty())); assertThat(result.getValidationEvents(Severity.ERROR).get(0).getMessage(), containsString("member `id`")); @@ -54,13 +54,13 @@ public void erroneousOverridesEmitEvents() { @Test public void loadsSuppressionsAndOverrides() { ValidatedResult result = Model.assembler() - .addImport( - Model.class.getResource( - "errorfiles/validators/severityOverrides/suppressions-take-precedence.smithy" + .addImport( + Model.class.getResource( + "errorfiles/validators/severityOverrides/suppressions-take-precedence.smithy" + ) ) - ) - .validatorFactory(testFactory(event -> event.toBuilder().hint("hi").build())) - .assemble(); + .validatorFactory(testFactory(event -> event.toBuilder().hint("hi").build())) + .assemble(); assertThat(result.getValidationEvents(Severity.ERROR), empty()); assertThat(result.getValidationEvents(), not(empty())); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/validation/suppressions/TraitSuppressionTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/validation/suppressions/TraitSuppressionTest.java index 248a54c19b3..8dd35dedbc9 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/validation/suppressions/TraitSuppressionTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/validation/suppressions/TraitSuppressionTest.java @@ -25,17 +25,17 @@ public class TraitSuppressionTest { @Test public void doesNotMatchWhenUsingDifferentShape() { Shape s1 = StringShape.builder() - .id("smithy.example#String1") - .addTrait(SuppressTrait.builder().values(ListUtils.of("Foo")).build()) - .build(); + .id("smithy.example#String1") + .addTrait(SuppressTrait.builder().values(ListUtils.of("Foo")).build()) + .build(); Shape s2 = StringShape.builder().id("smithy.example#String2").build(); Suppression suppression = Suppression.fromSuppressTrait(s1); ValidationEvent event = ValidationEvent.builder() - .id("Foo") - .shape(s2) - .severity(Severity.DANGER) - .message("test") - .build(); + .id("Foo") + .shape(s2) + .severity(Severity.DANGER) + .message("test") + .build(); assertThat(suppression.test(event), is(false)); } @@ -47,11 +47,11 @@ public void suppressesEventIds(boolean match, String eventId, List suppr Shape s = StringShape.builder().id("smithy.example#String").addTrait(trait).build(); Suppression suppression = Suppression.fromSuppressTrait(s); ValidationEvent event = ValidationEvent.builder() - .id(eventId) - .shapeId(s) - .severity(Severity.DANGER) - .message("test") - .build(); + .id(eventId) + .shapeId(s) + .severity(Severity.DANGER) + .message("test") + .build(); assertThat(eventId + " is " + match + " match for " + suppressions, suppression.test(event), is(match)); } @@ -59,14 +59,14 @@ public void suppressesEventIds(boolean match, String eventId, List suppr // See tests for ValidationEvent#containsId for exhaustive test cases. public static Stream suppressions() { return Stream.of( - Arguments.of(true, "BadThing", ListUtils.of("BadThing")), - Arguments.of(true, "BadThing", ListUtils.of("BadThing", "NotBadThing")), - Arguments.of(true, "BadThing", ListUtils.of("NotBadThing", "BadThing")), - Arguments.of(true, "BadThing.Foo", ListUtils.of("BadThing")), - Arguments.of(false, "BadThing", ListUtils.of("NotBadThing")), - Arguments.of(false, "BadThing.Foo", ListUtils.of("BadThing.Foo.Bar")), - Arguments.of(false, "BadThing.Foo", ListUtils.of("BadThing.Foo.Bar.Baz")), - Arguments.of(false, "BadThing.Fooz", ListUtils.of("BadThing.Foo")) + Arguments.of(true, "BadThing", ListUtils.of("BadThing")), + Arguments.of(true, "BadThing", ListUtils.of("BadThing", "NotBadThing")), + Arguments.of(true, "BadThing", ListUtils.of("NotBadThing", "BadThing")), + Arguments.of(true, "BadThing.Foo", ListUtils.of("BadThing")), + Arguments.of(false, "BadThing", ListUtils.of("NotBadThing")), + Arguments.of(false, "BadThing.Foo", ListUtils.of("BadThing.Foo.Bar")), + Arguments.of(false, "BadThing.Foo", ListUtils.of("BadThing.Foo.Bar.Baz")), + Arguments.of(false, "BadThing.Fooz", ListUtils.of("BadThing.Foo")) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/validation/testrunner/SmithyTestCaseTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/validation/testrunner/SmithyTestCaseTest.java index 145b62927c7..02fc02834f7 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/validation/testrunner/SmithyTestCaseTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/validation/testrunner/SmithyTestCaseTest.java @@ -23,8 +23,8 @@ public class SmithyTestCaseTest { @Test public void validatesThatEventsAreValid() { IllegalArgumentException e = Assertions.assertThrows( - IllegalArgumentException.class, - () -> SmithyTestCase.parseValidationEvent("[ERROR] - m", "filename") + IllegalArgumentException.class, + () -> SmithyTestCase.parseValidationEvent("[ERROR] - m", "filename") ); assertTrue(e.getMessage().contains("`filename`")); @@ -44,10 +44,10 @@ public void requiresFileExtension() { @Test public void matchesMessageUsingPrefix() { ValidationEvent actual = ValidationEvent.builder() - .id("FooBar") - .severity(Severity.DANGER) - .message("This is a test") - .build(); + .id("FooBar") + .severity(Severity.DANGER) + .message("This is a test") + .build(); ValidationEvent expected = actual.toBuilder().message("This is").build(); SmithyTestCase testCase = new SmithyTestCase("/foo/bar.json", Collections.singletonList(expected)); ValidatedResult validated = ValidatedResult.fromErrors(Collections.singleton(actual)); @@ -59,10 +59,10 @@ public void matchesMessageUsingPrefix() { @Test public void failsWhenMessageDoesNotMatchPrefix() { ValidationEvent actual = ValidationEvent.builder() - .id("FooBar") - .severity(Severity.DANGER) - .message("Not a test") - .build(); + .id("FooBar") + .severity(Severity.DANGER) + .message("Not a test") + .build(); ValidationEvent expected = actual.toBuilder().message("This is").build(); SmithyTestCase testCase = new SmithyTestCase("/foo/bar.json", Collections.singletonList(expected)); ValidatedResult validated = ValidatedResult.fromErrors(Collections.singleton(actual)); @@ -74,11 +74,11 @@ public void failsWhenMessageDoesNotMatchPrefix() { @Test public void matchesOnShapeId() { ValidationEvent actual = ValidationEvent.builder() - .id("FooBar") - .severity(Severity.DANGER) - .message("abc") - .shapeId(ShapeId.from("foo.baz#Bar")) - .build(); + .id("FooBar") + .severity(Severity.DANGER) + .message("abc") + .shapeId(ShapeId.from("foo.baz#Bar")) + .build(); SmithyTestCase testCase = new SmithyTestCase("/foo/bar.json", Collections.singletonList(actual)); ValidatedResult validated = ValidatedResult.fromErrors(Collections.singleton(actual)); SmithyTestCase.Result result = testCase.createResult(validated); @@ -89,11 +89,11 @@ public void matchesOnShapeId() { @Test public void failsWhenShapeIdDoesNotMatch() { ValidationEvent actual = ValidationEvent.builder() - .id("FooBar") - .severity(Severity.DANGER) - .message("abc") - .shapeId(ShapeId.from("foo.baz#Bar")) - .build(); + .id("FooBar") + .severity(Severity.DANGER) + .message("abc") + .shapeId(ShapeId.from("foo.baz#Bar")) + .build(); ValidationEvent expected = actual.toBuilder().shapeId(null).build(); SmithyTestCase testCase = new SmithyTestCase("/foo/bar.json", Collections.singletonList(expected)); ValidatedResult validated = ValidatedResult.fromErrors(Collections.singleton(actual)); @@ -105,43 +105,43 @@ public void failsWhenShapeIdDoesNotMatch() { @Test public void newlinesAreBetweenEventsWhenFormatting() { ValidationEvent e1 = ValidationEvent.builder() - .id("FooBar") - .severity(Severity.DANGER) - .message("a") - .shapeId(ShapeId.from("foo.baz#Bar")) - .build(); + .id("FooBar") + .severity(Severity.DANGER) + .message("a") + .shapeId(ShapeId.from("foo.baz#Bar")) + .build(); ValidationEvent e2 = ValidationEvent.builder() - .id("FooBar") - .severity(Severity.DANGER) - .message("b") - .shapeId(ShapeId.from("foo.baz#Bar")) - .build(); + .id("FooBar") + .severity(Severity.DANGER) + .message("b") + .shapeId(ShapeId.from("foo.baz#Bar")) + .build(); SmithyTestCase.Result result = new SmithyTestCase.Result( - "/foo/bar.json", - ListUtils.of(e1, e2), - ListUtils.of(e1, e2) + "/foo/bar.json", + ListUtils.of(e1, e2), + ListUtils.of(e1, e2) ); assertThat( - result.toString(), - equalTo( - "=======================\n" - + "Model Validation Result\n" - + "=======================\n" - + "/foo/bar.json\n" - + "\n" - + "Did not match the following events\n" - + "----------------------------------\n" - + "[DANGER] foo.baz#Bar: a | FooBar N/A:0:0\n" - + "[DANGER] foo.baz#Bar: b | FooBar N/A:0:0\n" - + "\n" - + "\n" - + "Encountered unexpected events\n" - + "-----------------------------\n" - + "[DANGER] foo.baz#Bar: a | FooBar N/A:0:0\n" - + "[DANGER] foo.baz#Bar: b | FooBar N/A:0:0\n\n" - ) + result.toString(), + equalTo( + "=======================\n" + + "Model Validation Result\n" + + "=======================\n" + + "/foo/bar.json\n" + + "\n" + + "Did not match the following events\n" + + "----------------------------------\n" + + "[DANGER] foo.baz#Bar: a | FooBar N/A:0:0\n" + + "[DANGER] foo.baz#Bar: b | FooBar N/A:0:0\n" + + "\n" + + "\n" + + "Encountered unexpected events\n" + + "-----------------------------\n" + + "[DANGER] foo.baz#Bar: a | FooBar N/A:0:0\n" + + "[DANGER] foo.baz#Bar: b | FooBar N/A:0:0\n\n" + ) ); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/validation/testrunner/SmithyTestSuiteTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/validation/testrunner/SmithyTestSuiteTest.java index c12f9b05a1e..4d391d29997 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/validation/testrunner/SmithyTestSuiteTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/validation/testrunner/SmithyTestSuiteTest.java @@ -18,8 +18,8 @@ public class SmithyTestSuiteTest { public void throwsWhenFailed() { try { SmithyTestSuite.runner() - .addTestCasesFromUrl(getClass().getResource("testrunner/invalid")) - .run(); + .addTestCasesFromUrl(getClass().getResource("testrunner/invalid")) + .run(); Assertions.fail("Expected to throw"); } catch (SmithyTestSuite.Error e) { assertThat(e.result.getSuccessCount(), is(1)); @@ -32,8 +32,8 @@ public void throwsWhenFailed() { @Test public void runsCaseWithFile() { SmithyTestSuite.Result result = SmithyTestSuite.runner() - .addTestCasesFromUrl(getClass().getResource("testrunner/valid")) - .run(); + .addTestCasesFromUrl(getClass().getResource("testrunner/valid")) + .run(); assertThat(result.getFailedResults().size(), is(0)); assertThat(result.getSuccessCount(), is(4)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/validation/validators/ServiceValidatorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/validation/validators/ServiceValidatorTest.java index 4aab69db118..6ac20db7ccd 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/validation/validators/ServiceValidatorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/validation/validators/ServiceValidatorTest.java @@ -30,37 +30,37 @@ public void syntheticTraitsDoNotCauseConflicts() { // These two string conflict by name, but are functionally identical. // The fact that they have differing synthetic traits can be ignored. StringShape string1 = StringShape.builder() - .id("smithy.example#String1") - .addTrait(new OriginalShapeIdTrait(ShapeId.from("com.foo#Str"))) - .build(); + .id("smithy.example#String1") + .addTrait(new OriginalShapeIdTrait(ShapeId.from("com.foo#Str"))) + .build(); StringShape string2 = StringShape.builder() - .id("smithy.other#String1") - .addTrait(new BoxTrait()) // box is synthetic since IDL 2.0 - .build(); + .id("smithy.other#String1") + .addTrait(new BoxTrait()) // box is synthetic since IDL 2.0 + .build(); StructureShape input = StructureShape.builder() - .id("smithy.example#OperationInput") - .addTrait(new InputTrait()) - .addMember("foo", string1.getId()) - .addMember("bar", string2.getId()) - .build(); + .id("smithy.example#OperationInput") + .addTrait(new InputTrait()) + .addMember("foo", string1.getId()) + .addMember("bar", string2.getId()) + .build(); StructureShape output = StructureShape.builder() - .id("smithy.example#OperationOutput") - .addTrait(new OutputTrait()) - .build(); + .id("smithy.example#OperationOutput") + .addTrait(new OutputTrait()) + .build(); OperationShape operation = OperationShape.builder() - .id("smithy.example#Operation") - .input(input) - .output(output) - .build(); + .id("smithy.example#Operation") + .input(input) + .output(output) + .build(); ServiceShape service = ServiceShape.builder() - .id("smithy.example#Service") - .version("X") - .addOperation(operation) - .build(); + .id("smithy.example#Service") + .version("X") + .addOperation(operation) + .build(); Model model = Model.builder() - .addShapes(service, operation, input, output, string1, string2) - .build(); + .addShapes(service, operation, input, output, string1, string2) + .build(); List events = new ServiceValidator().validate(model); ValidatedResult result = new ValidatedResult<>(model, events); @@ -72,32 +72,32 @@ public void syntheticTraitsDoNotCauseConflicts() { public void detectsTraitsThatDoNotMatch() { StringShape string1 = StringShape.builder().id("smithy.example#String1").build(); StringShape string2 = StringShape.builder() - .id("smithy.other#String1") - .addTrait(new SensitiveTrait()) - .build(); + .id("smithy.other#String1") + .addTrait(new SensitiveTrait()) + .build(); StructureShape input = StructureShape.builder() - .id("smithy.example#OperationInput") - .addTrait(new InputTrait()) - .addMember("foo", string1.getId()) - .addMember("bar", string2.getId()) - .build(); + .id("smithy.example#OperationInput") + .addTrait(new InputTrait()) + .addMember("foo", string1.getId()) + .addMember("bar", string2.getId()) + .build(); StructureShape output = StructureShape.builder() - .id("smithy.example#OperationOutput") - .addTrait(new OutputTrait()) - .build(); + .id("smithy.example#OperationOutput") + .addTrait(new OutputTrait()) + .build(); OperationShape operation = OperationShape.builder() - .id("smithy.example#Operation") - .input(input) - .output(output) - .build(); + .id("smithy.example#Operation") + .input(input) + .output(output) + .build(); ServiceShape service = ServiceShape.builder() - .id("smithy.example#Service") - .version("X") - .addOperation(operation) - .build(); + .id("smithy.example#Service") + .version("X") + .addOperation(operation) + .build(); Model model = Model.builder() - .addShapes(service, operation, input, output, string1, string2) - .build(); + .addShapes(service, operation, input, output, string1, string2) + .build(); List events = new ServiceValidator().validate(model); ValidatedResult result = new ValidatedResult<>(model, events); diff --git a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/ResolvedTopicIndex.java b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/ResolvedTopicIndex.java index dd01608ab81..2ce89cc7576 100644 --- a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/ResolvedTopicIndex.java +++ b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/ResolvedTopicIndex.java @@ -76,8 +76,8 @@ public static ResolvedTopicIndex of(Model model) { public List> getOperationBindings(ToShapeId operation) { ShapeId id = operation.toShapeId(); return topicBindings() - .filter(binding -> binding.getOperation().getId().equals(id)) - .collect(Collectors.toList()); + .filter(binding -> binding.getOperation().getId().equals(id)) + .collect(Collectors.toList()); } /** @@ -124,9 +124,9 @@ public Optional getSubcribeEventStreamInfo(ToShapeId operation) } private void createPublishBindings( - OperationIndex operationIndex, - OperationShape operation, - PublishTrait trait + OperationIndex operationIndex, + OperationShape operation, + PublishTrait trait ) { StructureShape input = operationIndex.expectInputShape(operation); TopicBinding topicBinding = new TopicBinding<>(operation, trait, trait.getTopic(), input, input); @@ -134,10 +134,10 @@ private void createPublishBindings( } private void createSubscribeBinding( - StructureShape input, - EventStreamIndex eventStreamIndex, - OperationShape operation, - SubscribeTrait trait + StructureShape input, + EventStreamIndex eventStreamIndex, + OperationShape operation, + SubscribeTrait trait ) { EventStreamInfo outputInfo = eventStreamIndex.getOutputInfo(operation).orElse(null); @@ -145,11 +145,11 @@ private void createSubscribeBinding( // if an event stream is not found. if (outputInfo != null) { TopicBinding binding = new TopicBinding<>( - operation, - trait, - trait.getTopic(), - outputInfo.getEventStreamTarget(), - input + operation, + trait, + trait.getTopic(), + outputInfo.getEventStreamTarget(), + input ); subscribeBindings.put(operation.getId(), binding); subscribeInfo.put(operation.getId(), outputInfo); diff --git a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/Topic.java b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/Topic.java index f38beea7c4a..9dfe943c505 100644 --- a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/Topic.java +++ b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/Topic.java @@ -43,21 +43,21 @@ public static Topic parse(String topic) { for (String level : topic.split("/")) { if (level.contains("#") || level.contains("+")) { throw new TopicSyntaxException( - format( - "Wildcard levels are not allowed in MQTT topics. Found `%s` in `%s`", - level, - topic - ) + format( + "Wildcard levels are not allowed in MQTT topics. Found `%s` in `%s`", + level, + topic + ) ); } else if (level.startsWith("{") && level.endsWith("}")) { String label = level.substring(1, level.length() - 1); if (!LABEL_PATTERN.matcher(label).matches()) { throw new TopicSyntaxException( - format( - "Invalid topic label name `%s` found in `%s`", - label, - topic - ) + format( + "Invalid topic label name `%s` found in `%s`", + label, + topic + ) ); } else if (labels.contains(label)) { throw new TopicSyntaxException(format("Duplicate topic label `%s` found in `%s`", label, topic)); @@ -66,11 +66,11 @@ public static Topic parse(String topic) { levels.add(new Level(label, true)); } else if (level.contains("{") || level.contains("}")) { throw new TopicSyntaxException( - format( - "Topic labels must span an entire level. Found `%s` in `%s`", - level, - topic - ) + format( + "Topic labels must span an entire level. Found `%s` in `%s`", + level, + topic + ) ); } else { levels.add(new Level(level, false)); @@ -96,8 +96,8 @@ public List getLevels() { */ public List getLabels() { return levels.stream() - .filter(Level::isLabel) - .collect(Collectors.toList()); + .filter(Level::isLabel) + .collect(Collectors.toList()); } /** @@ -130,7 +130,7 @@ public boolean conflictsWith(Topic other) { Level otherLevel = other.levels.get(i); // Both are static levels with different values. if (!thisLevel.isLabel() && !otherLevel.isLabel() - && !thisLevel.getContent().equals(otherLevel.getContent())) { + && !thisLevel.getContent().equals(otherLevel.getContent())) { return false; } else if (thisLevel.isLabel() != otherLevel.isLabel()) { // One is static and the other is not, so there is not a diff --git a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/TopicBinding.java b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/TopicBinding.java index 1496ef0eb97..1a69b26af09 100644 --- a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/TopicBinding.java +++ b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/TopicBinding.java @@ -58,11 +58,11 @@ public final class TopicBinding { private final StructureShape input; TopicBinding( - OperationShape operation, - T mqttTrait, - Topic topic, - Shape payloadShape, - StructureShape input + OperationShape operation, + T mqttTrait, + Topic topic, + Shape payloadShape, + StructureShape input ) { this.operation = operation; this.mqttTrait = mqttTrait; @@ -192,10 +192,10 @@ public boolean equals(Object o) { } TopicBinding that = (TopicBinding) o; return operation.equals(that.operation) - && getInput().equals(that.getInput()) - && mqttTrait.equals(that.mqttTrait) - && getTopic().equals(that.getTopic()) - && getPayloadShape().equals(that.getPayloadShape()); + && getInput().equals(that.getInput()) + && mqttTrait.equals(that.mqttTrait) + && getTopic().equals(that.getTopic()) + && getPayloadShape().equals(that.getPayloadShape()); } @Override @@ -206,11 +206,11 @@ public int hashCode() { @Override public String toString() { return "TopicBinding{" - + "operation=" + operation.getId() - + ", input=" + getInput().map(Shape::getId).map(ShapeId::toString).orElse("null") - + ", mqttTrait=" + mqttTrait.toShapeId() - + ", topic=" + topic - + ", payloadShape=" + String.valueOf(payloadShape) - + '}'; + + "operation=" + operation.getId() + + ", input=" + getInput().map(Shape::getId).map(ShapeId::toString).orElse("null") + + ", mqttTrait=" + mqttTrait.toShapeId() + + ", topic=" + topic + + ", payloadShape=" + String.valueOf(payloadShape) + + '}'; } } diff --git a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttTopicConflictValidator.java b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttTopicConflictValidator.java index 3dbfdd6e37d..5696af43277 100644 --- a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttTopicConflictValidator.java +++ b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttTopicConflictValidator.java @@ -30,49 +30,49 @@ public List validate(Model model) { // Find conflicting topic bindings for each resolved topic. return bindingIndex.topicBindings() - .map( - binding -> Pair.of( - binding, - bindingIndex.topicBindings() - .filter(other -> other.conflictsWith(binding)) - .collect(Collectors.toList()) + .map( + binding -> Pair.of( + binding, + bindingIndex.topicBindings() + .filter(other -> other.conflictsWith(binding)) + .collect(Collectors.toList()) + ) ) - ) - // Only care when multiple entries are present. - .filter(conflictingPair -> !conflictingPair.getRight().isEmpty()) - .map(conflictingPair -> invalidBindings(conflictingPair.getLeft(), conflictingPair.getRight())) - .collect(Collectors.toList()); + // Only care when multiple entries are present. + .filter(conflictingPair -> !conflictingPair.getRight().isEmpty()) + .map(conflictingPair -> invalidBindings(conflictingPair.getLeft(), conflictingPair.getRight())) + .collect(Collectors.toList()); } private ValidationEvent invalidBindings( - TopicBinding binding, - List> conflicts + TopicBinding binding, + List> conflicts ) { String payloadShape = binding.getPayloadShape() - .map(shape -> shape.getId().toString()) - .orElse("N/A"); + .map(shape -> shape.getId().toString()) + .orElse("N/A"); String conflictingStrings = conflicts.stream() - .filter(b -> !b.equals(binding)) - .map(this::createConflictingBindingDescriptor) - .sorted() - .collect(Collectors.joining(", ")); + .filter(b -> !b.equals(binding)) + .map(this::createConflictingBindingDescriptor) + .sorted() + .collect(Collectors.joining(", ")); String message = String.format( - "This shape resolves to an MQTT topic `%s` as part of the `%s` operation, and its payload of " - + "`%s` conflicts with other topic payloads: [%s]", - binding.getTopic(), - binding.getOperation().getId(), - payloadShape, - conflictingStrings + "This shape resolves to an MQTT topic `%s` as part of the `%s` operation, and its payload of " + + "`%s` conflicts with other topic payloads: [%s]", + binding.getTopic(), + binding.getOperation().getId(), + payloadShape, + conflictingStrings ); return error(binding.getOperation(), binding.getMqttTrait(), message); } private String createConflictingBindingDescriptor(TopicBinding binding) { return String.format( - "`%s` trait payload %s of `%s`", - Trait.getIdiomaticTraitName(binding.getMqttTrait().toShapeId()), - binding.getPayloadShape().map(Shape::getId).map(id -> "`" + id + "`").orElse("N/A"), - binding.getOperation().getId() + "`%s` trait payload %s of `%s`", + Trait.getIdiomaticTraitName(binding.getMqttTrait().toShapeId()), + binding.getPayloadShape().map(Shape::getId).map(id -> "`" + id + "`").orElse("N/A"), + binding.getOperation().getId() ); } } diff --git a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttTopicLabelValidator.java b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttTopicLabelValidator.java index 761fa67c8e8..10e7b3dfa40 100644 --- a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttTopicLabelValidator.java +++ b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttTopicLabelValidator.java @@ -75,17 +75,17 @@ private List validateMqtt(OperationIndex index, TopicCollection labels.remove(member.getMemberName()); } else { events.add( - error( - member, - member.expectTrait(TopicLabelTrait.class), - String.format( - "This member is marked with the `smithy.mqtt#topicLabel` trait, but when this member is " - + "used as part of the input of the `%s` operation, a corresponding label cannot be " - + "found in the `%s` trait", - topics.operation.getId(), - Trait.getIdiomaticTraitName(topics.trait.toShapeId()) + error( + member, + member.expectTrait(TopicLabelTrait.class), + String.format( + "This member is marked with the `smithy.mqtt#topicLabel` trait, but when this member is " + + "used as part of the input of the `%s` operation, a corresponding label cannot be " + + "found in the `%s` trait", + topics.operation.getId(), + Trait.getIdiomaticTraitName(topics.trait.toShapeId()) + ) ) - ) ); } } @@ -93,16 +93,16 @@ private List validateMqtt(OperationIndex index, TopicCollection if (!labels.isEmpty()) { events.add( - error( - topics.operation, - topics.trait, - String.format( - "The `%s` trait contains the following topic labels that could not be found in the input " - + "structure of the operation or were not marked with the `smithy.mqtt#topicLabel` trait: [%s]", - Trait.getIdiomaticTraitName(topics.trait.toShapeId()), - ValidationUtils.tickedList(labels) + error( + topics.operation, + topics.trait, + String.format( + "The `%s` trait contains the following topic labels that could not be found in the input " + + "structure of the operation or were not marked with the `smithy.mqtt#topicLabel` trait: [%s]", + Trait.getIdiomaticTraitName(topics.trait.toShapeId()), + ValidationUtils.tickedList(labels) + ) ) - ) ); } @@ -122,8 +122,8 @@ private static final class TopicCollection { Set getLabels() { return topics.stream() - .flatMap(topic -> topic.getLabels().stream().map(Topic.Level::getContent)) - .collect(Collectors.toSet()); + .flatMap(topic -> topic.getLabels().stream().map(Topic.Level::getContent)) + .collect(Collectors.toSet()); } } } diff --git a/smithy-mqtt-traits/src/test/java/software/amazon/smithy/mqtt/traits/TopicConflictTest.java b/smithy-mqtt-traits/src/test/java/software/amazon/smithy/mqtt/traits/TopicConflictTest.java index 23c2ee90080..e70703a460e 100644 --- a/smithy-mqtt-traits/src/test/java/software/amazon/smithy/mqtt/traits/TopicConflictTest.java +++ b/smithy-mqtt-traits/src/test/java/software/amazon/smithy/mqtt/traits/TopicConflictTest.java @@ -28,34 +28,34 @@ public void patternConflicts(String topicA, String topicB, boolean isConflicting public static Collection data() { return Arrays.asList( - new Object[][]{ - // No conflict because a is more specific. - {"a", "{x}", false}, - // No conflict because "a" is more specific than "{y}". - {"a/{x}", "{y}/a", false}, - // No conflict because "a" is more specific than "{x}". - {"{x}/a", "a/{y}", false}, - // Conflicts because the topics are equivalent and the same length. - {"a/{x}", "a/{y}", true}, - // Does not conflict because "{x}" and "{y}" are under different level prefixes. - {"a/{x}", "b/{y}", false}, - // Conflicts because they have the same levels and the same length. - {"a/{x}/b", "a/{y}/b", true}, - // Does not conflict because one is longer than the other. - {"a/{x}/b", "a/{y}/b/{z}", false}, - // Does not conflict because one is longer than the other. - {"a/{x}/b", "a/{y}/b/{z}/c", false}, - // Do not conflict because "b" is more specific than "{b}" - {"a/b/c", "a/{b}/c", false}, - // Conflicts because they are all labels at the same level. - {"{a}/{b}/{c}", "{x}/{y}/{z}", true}, - // No conflicts because one is longer than the other. - {"{a}/{b}/{c}", "{x}/{y}/{z}/{a}", false}, - // No conflict - {"a/b/c/d", "a/{b}/c/{d}", false}, - // No conflict. - {"$aws/things/{thingName}/jobs/get", "$aws/things/{thingName}/jobs/start-next", false} - } + new Object[][]{ + // No conflict because a is more specific. + {"a", "{x}", false}, + // No conflict because "a" is more specific than "{y}". + {"a/{x}", "{y}/a", false}, + // No conflict because "a" is more specific than "{x}". + {"{x}/a", "a/{y}", false}, + // Conflicts because the topics are equivalent and the same length. + {"a/{x}", "a/{y}", true}, + // Does not conflict because "{x}" and "{y}" are under different level prefixes. + {"a/{x}", "b/{y}", false}, + // Conflicts because they have the same levels and the same length. + {"a/{x}/b", "a/{y}/b", true}, + // Does not conflict because one is longer than the other. + {"a/{x}/b", "a/{y}/b/{z}", false}, + // Does not conflict because one is longer than the other. + {"a/{x}/b", "a/{y}/b/{z}/c", false}, + // Do not conflict because "b" is more specific than "{b}" + {"a/b/c", "a/{b}/c", false}, + // Conflicts because they are all labels at the same level. + {"{a}/{b}/{c}", "{x}/{y}/{z}", true}, + // No conflicts because one is longer than the other. + {"{a}/{b}/{c}", "{x}/{y}/{z}/{a}", false}, + // No conflict + {"a/b/c/d", "a/{b}/c/{d}", false}, + // No conflict. + {"$aws/things/{thingName}/jobs/get", "$aws/things/{thingName}/jobs/start-next", false} + } ); } } diff --git a/smithy-mqtt-traits/src/test/java/software/amazon/smithy/mqtt/traits/TopicTest.java b/smithy-mqtt-traits/src/test/java/software/amazon/smithy/mqtt/traits/TopicTest.java index f5051559705..d995a50fde1 100644 --- a/smithy-mqtt-traits/src/test/java/software/amazon/smithy/mqtt/traits/TopicTest.java +++ b/smithy-mqtt-traits/src/test/java/software/amazon/smithy/mqtt/traits/TopicTest.java @@ -58,12 +58,12 @@ public void parsesTopicWithNoLabels() { assertThat(topic.toString(), equalTo("foo/bar/baz")); assertThat( - topic.getLevels(), - contains( - new Topic.Level("foo"), - new Topic.Level("bar"), - new Topic.Level("baz") - ) + topic.getLevels(), + contains( + new Topic.Level("foo"), + new Topic.Level("bar"), + new Topic.Level("baz") + ) ); assertThat(topic.conflictsWith(topic), is(true)); assertThat(topic.getLabels(), empty()); @@ -79,20 +79,20 @@ public void parsesTopicWithLabels() { assertThat(topic.toString(), equalTo("foo/{foo}/bar/{baz}")); assertThat( - topic.getLevels(), - contains( - new Topic.Level("foo"), - new Topic.Level("foo", true), - new Topic.Level("bar"), - new Topic.Level("baz", true) - ) + topic.getLevels(), + contains( + new Topic.Level("foo"), + new Topic.Level("foo", true), + new Topic.Level("bar"), + new Topic.Level("baz", true) + ) ); assertThat( - topic.getLabels(), - contains( - new Topic.Level("foo", true), - new Topic.Level("baz", true) - ) + topic.getLabels(), + contains( + new Topic.Level("foo", true), + new Topic.Level("baz", true) + ) ); assertTrue(topic.hasLabel("foo")); diff --git a/smithy-openapi-traits/src/main/java/software/amazon/smithy/openapi/traits/SpecificationExtensionTrait.java b/smithy-openapi-traits/src/main/java/software/amazon/smithy/openapi/traits/SpecificationExtensionTrait.java index 34df13a8411..0363b00fca3 100644 --- a/smithy-openapi-traits/src/main/java/software/amazon/smithy/openapi/traits/SpecificationExtensionTrait.java +++ b/smithy-openapi-traits/src/main/java/software/amazon/smithy/openapi/traits/SpecificationExtensionTrait.java @@ -17,7 +17,7 @@ * smithy.openapi#specificationExtension - Indicates a trait shape should be converted into an OpenAPI specification extension. */ public final class SpecificationExtensionTrait extends AbstractTrait - implements ToSmithyBuilder { + implements ToSmithyBuilder { public static final ShapeId ID = ShapeId.from("smithy.openapi#specificationExtension"); private final String as; @@ -64,8 +64,8 @@ protected Node createNode() { @Override public Builder toBuilder() { return builder() - .sourceLocation(getSourceLocation()) - .as(this.as); + .sourceLocation(getSourceLocation()) + .as(this.as); } /** diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/OpenApiConfig.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/OpenApiConfig.java index 3cca06f4d71..50beaa65bb2 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/OpenApiConfig.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/OpenApiConfig.java @@ -72,8 +72,8 @@ public String toString() { DEPRECATED_PROPERTY_RENAMES.put("openapi.substitutions", "substitutions"); // Cheating a little here, but oh well. DEPRECATED_PROPERTY_RENAMES.put( - "apigateway.disableCloudFormationSubstitution", - "disableCloudFormationSubstitution" + "apigateway.disableCloudFormationSubstitution", + "disableCloudFormationSubstitution" ); } @@ -90,12 +90,12 @@ public String toString() { private Map substitutions = Collections.emptyMap(); private Map jsonAdd = Collections.emptyMap(); private List externalDocs = ListUtils.of( - "Homepage", - "API Reference", - "User Guide", - "Developer Guide", - "Reference", - "Guide" + "Homepage", + "API Reference", + "User Guide", + "Developer Guide", + "Reference", + "Guide" ); private boolean disableIntegerFormat = false; private boolean syncCorsPreflightIntegration = false; @@ -426,8 +426,8 @@ private static ObjectNode fixDeprecatedKeys(ObjectNode node) { // Fixes specific renamed keys. String rename = DEPRECATED_PROPERTY_RENAMES.get(entry.getKey()); LOGGER.warning( - "Deprecated `openapi` configuration setting found: " + entry.getKey() - + ". Use " + rename + " instead" + "Deprecated `openapi` configuration setting found: " + entry.getKey() + + ". Use " + rename + " instead" ); mapped = mapped.withMember(rename, entry.getValue()); mapped = mapped.withoutMember(entry.getKey()); @@ -435,16 +435,16 @@ private static ObjectNode fixDeprecatedKeys(ObjectNode node) { // These are now added into the "disableFeatures" property. String property = StringUtils.uncapitalize(entry.getKey().substring(8)); throw new OpenApiException( - "Unsupported `openapi` configuration setting found: " + entry.getKey() - + ". Add `" + property + "` to the `disableFeatures` property instead" + "Unsupported `openapi` configuration setting found: " + entry.getKey() + + ". Add `" + property + "` to the `disableFeatures` property instead" ); } else if (entry.getKey().startsWith("openapi.use.")) { throw new OpenApiException( - String.format( - "The `%s` `openapi` plugin property is no longer supported. Use the " - + "`disableFeatures` property instead to disable features.", - entry.getKey() - ) + String.format( + "The `%s` `openapi` plugin property is no longer supported. Use the " + + "`disableFeatures` property instead to disable features.", + entry.getKey() + ) ); } } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/OpenApiUtils.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/OpenApiUtils.java index d26ba24fbb1..6b252ee5f02 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/OpenApiUtils.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/OpenApiUtils.java @@ -27,11 +27,11 @@ private OpenApiUtils() {} * @return Extension name for the given trait shape. */ public static String getSpecificationExtensionName( - ShapeId metaTraitId, - SpecificationExtensionTrait specificationExtensionTrait + ShapeId metaTraitId, + SpecificationExtensionTrait specificationExtensionTrait ) { return specificationExtensionTrait.getAs() - .orElse("x-" + metaTraitId.toString().replaceAll("[.#]", "-")); + .orElse("x-" + metaTraitId.toString().replaceAll("[.#]", "-")); } /** @@ -46,12 +46,12 @@ public static Map getSpecificationExtensionsMap(Model model, Shape shape.getAllTraits().forEach((traitId, trait) -> // Get Applied Trait model.getShape(traitId) - // Get SpecificationExtensionTrait on the Applied Trait - .flatMap(traitShape -> traitShape.getTrait(SpecificationExtensionTrait.class)) - // Get specification extension name from the Applied Trait and SpecificationExtensionTrait - .map(specificationExtension -> getSpecificationExtensionName(traitId, specificationExtension)) - // Put the specification extension name and Applied Meta trait into the map. - .ifPresent(name -> specificationExtensions.put(name, trait.toNode()))); + // Get SpecificationExtensionTrait on the Applied Trait + .flatMap(traitShape -> traitShape.getTrait(SpecificationExtensionTrait.class)) + // Get specification extension name from the Applied Trait and SpecificationExtensionTrait + .map(specificationExtension -> getSpecificationExtensionName(traitId, specificationExtension)) + // Put the specification extension name and Applied Meta trait into the map. + .ifPresent(name -> specificationExtensions.put(name, trait.toNode()))); return specificationExtensions; } } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/OpenApiVersion.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/OpenApiVersion.java index 8bce121c5aa..a02cb811f67 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/OpenApiVersion.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/OpenApiVersion.java @@ -23,10 +23,10 @@ public enum OpenApiVersion { private final Set unsupportedKeywords; OpenApiVersion( - String version, - boolean supportsContentEncodingKeyword, - JsonSchemaVersion jsonSchemaVersion, - Set unsupportedKeywords + String version, + boolean supportsContentEncodingKeyword, + JsonSchemaVersion jsonSchemaVersion, + Set unsupportedKeywords ) { this.version = version; this.supportsContentEncodingKeyword = supportsContentEncodingKeyword; diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/Context.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/Context.java index 96893dd162d..e3f3c442d82 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/Context.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/Context.java @@ -38,13 +38,13 @@ public final class Context { private OpenApiConfig config; Context( - Model model, - ServiceShape service, - OpenApiConfig config, - JsonSchemaConverter jsonSchemaConverter, - OpenApiProtocol openApiProtocol, - SchemaDocument schemas, - List> securitySchemeConverters + Model model, + ServiceShape service, + OpenApiConfig config, + JsonSchemaConverter jsonSchemaConverter, + OpenApiProtocol openApiProtocol, + SchemaDocument schemas, + List> securitySchemeConverters ) { this.model = model; this.service = service; @@ -122,7 +122,7 @@ public OpenApiProtocol getOpenApiProtocol() { */ public Schema getSchema(String pointer) { return schemas.getDefinition(pointer) - .orElseThrow(() -> new OpenApiException("Expected JSON schema definition not found: " + pointer)); + .orElseThrow(() -> new OpenApiException("Expected JSON schema definition not found: " + pointer)); } /** @@ -218,16 +218,16 @@ public Set getAllSecuritySchemeResponseHeaders() { } private static Set getSecuritySchemeRequestHeaders( - Context context, - SecuritySchemeConverter converter + Context context, + SecuritySchemeConverter converter ) { T t = context.getService().expectTrait(converter.getAuthSchemeType()); return converter.getAuthRequestHeaders(context, t); } private static Set getSecuritySchemeResponseHeaders( - Context context, - SecuritySchemeConverter converter + Context context, + SecuritySchemeConverter converter ) { T t = context.getService().expectTrait(converter.getAuthSchemeType()); return converter.getAuthResponseHeaders(context, t); diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/CoreExtension.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/CoreExtension.java index d7cab99f798..deb4de4d5e9 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/CoreExtension.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/CoreExtension.java @@ -30,11 +30,11 @@ public final class CoreExtension implements Smithy2OpenApiExtension { @Override public List> getSecuritySchemeConverters() { return ListUtils.of( - new HttpBasicConverter(), - new HttpBearerConverter(), - new HttpDigestConverter(), - new AwsV4Converter(), - new HttpApiKeyAuthConverter() + new HttpBasicConverter(), + new HttpBearerConverter(), + new HttpDigestConverter(), + new AwsV4Converter(), + new HttpApiKeyAuthConverter() ); } @@ -46,14 +46,14 @@ public List> getProtocols() { @Override public List getOpenApiMappers() { return ListUtils.of( - new CheckForGreedyLabels(), - new CheckForPrefixHeaders(), - new OpenApiJsonSubstitutions(), - new OpenApiJsonAdd(), - new RemoveUnusedComponents(), - new UnsupportedTraits(), - new RemoveEmptyComponents(), - new SpecificationExtensionsMapper() + new CheckForGreedyLabels(), + new CheckForPrefixHeaders(), + new OpenApiJsonSubstitutions(), + new OpenApiJsonAdd(), + new RemoveUnusedComponents(), + new UnsupportedTraits(), + new RemoveEmptyComponents(), + new SpecificationExtensionsMapper() ); } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConverter.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConverter.java index b5f930e0834..c704c0c19a7 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConverter.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConverter.java @@ -166,30 +166,30 @@ private ConversionEnvironment createConversionEnvironment(Model if (config.getAddReferenceDescriptions() && config.getVersion() == OpenApiVersion.VERSION_3_0_2) { throw new OpenApiException( - "openapi property `addReferenceDescriptions` requires openapi version 3.1.0 or later.\n" - + "Suggestion: Add `\"version\"`: \"3.1.0\" to your openapi config." + "openapi property `addReferenceDescriptions` requires openapi version 3.1.0 or later.\n" + + "Suggestion: Add `\"version\"`: \"3.1.0\" to your openapi config." ); } // Find the service shape. ServiceShape service = model.getShape(serviceShapeId) - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "Shape `%s` not found in model", - serviceShapeId - ) - ) - ) - .asServiceShape() - .orElseThrow( - () -> new IllegalArgumentException( - String.format( - "Shape `%s` is not a service shape", - serviceShapeId - ) + .orElseThrow( + () -> new IllegalArgumentException( + String.format( + "Shape `%s` not found in model", + serviceShapeId + ) + ) ) - ); + .asServiceShape() + .orElseThrow( + () -> new IllegalArgumentException( + String.format( + "Shape `%s` is not a service shape", + serviceShapeId + ) + ) + ); // Copy service errors onto each operation to ensure that common errors are // generated for each operation. @@ -244,33 +244,33 @@ private ConversionEnvironment createConversionEnvironment(Model // Load security scheme converters. List> securitySchemeConverters = loadSecuritySchemes( - model, - service, - extensions + model, + service, + extensions ); Context context = new Context<>( - model, - service, - config, - jsonSchemaConverter, - openApiProtocol, - document, - securitySchemeConverters + model, + service, + config, + jsonSchemaConverter, + openApiProtocol, + document, + securitySchemeConverters ); return new ConversionEnvironment<>(context, extensions, components, composedMapper); } private static OpenApiMapper createComposedMapper( - List extensions, - List mappers + List extensions, + List mappers ) { return OpenApiMapper.compose( - Stream.concat( - extensions.stream().flatMap(extension -> extension.getOpenApiMappers().stream()), - mappers.stream() - ).collect(Collectors.toList()) + Stream.concat( + extensions.stream().flatMap(extension -> extension.getOpenApiMappers().stream()), + mappers.stream() + ).collect(Collectors.toList()) ); } @@ -289,29 +289,29 @@ private Trait loadOrDeriveProtocolTrait(Model model, ServiceShape service) { ShapeId protocolTraitId = config.getProtocol(); return service.findTrait(protocolTraitId).orElseThrow(() -> { return new OpenApiException( - String.format( - "Unable to find protocol `%s` on service `%s`. This service supports the following " - + "protocols: %s", - protocolTraitId, - service.getId(), - serviceProtocols - ) + String.format( + "Unable to find protocol `%s` on service `%s`. This service supports the following " + + "protocols: %s", + protocolTraitId, + service.getId(), + serviceProtocols + ) ); }); } else if (serviceProtocols.isEmpty()) { throw new OpenApiException( - String.format( - "No Smithy protocol was configured and `%s` does not define any protocols.", - service.getId() - ) + String.format( + "No Smithy protocol was configured and `%s` does not define any protocols.", + service.getId() + ) ); } else if (serviceProtocols.size() > 1) { throw new OpenApiException( - String.format( - "No Smithy protocol was configured and `%s` defines multiple protocols: %s", - service.getId(), - serviceProtocols - ) + String.format( + "No Smithy protocol was configured and `%s` defines multiple protocols: %s", + service.getId(), + serviceProtocols + ) ); } else { // Get the first and only service protocol trait. @@ -326,10 +326,10 @@ private static final class ConversionEnvironment { private final OpenApiMapper mapper; private ConversionEnvironment( - Context context, - List extensions, - ComponentsObject.Builder components, - OpenApiMapper composedMapper + Context context, + List extensions, + ComponentsObject.Builder components, + OpenApiMapper composedMapper ) { this.context = context; this.extensions = extensions; @@ -350,7 +350,7 @@ private OpenApi convertWithEnvironment(ConversionEnvironment OpenApi convertWithEnvironment(ConversionEnvironment OpenApiProtocol loadOpenApiProtocol( - ServiceShape service, - T protocolTrait, - List extensions + ServiceShape service, + T protocolTrait, + List extensions ) { // Collect into a list so that a better error message can be presented if the // protocol converter can't be found. List protocolProviders = extensions.stream() - .flatMap(e -> e.getProtocols().stream()) - .collect(Collectors.toList()); + .flatMap(e -> e.getProtocols().stream()) + .collect(Collectors.toList()); return protocolProviders.stream() - .filter(openApiProtocol -> openApiProtocol.getProtocolType().equals(protocolTrait.getClass())) - .findFirst() - .map(result -> (OpenApiProtocol) result) - .orElseThrow(() -> { - Stream supportedProtocols = protocolProviders.stream() - .map(OpenApiProtocol::getProtocolType) - .map(Class::getCanonicalName); - return new OpenApiException( - String.format( - "Unable to find an OpenAPI service provider for the `%s` protocol when converting `%s`. " - + "Protocol service providers were found for the following protocol classes: [%s].", - protocolTrait.toShapeId(), - service.getId(), - ValidationUtils.tickedList(supportedProtocols) - ) - ); - }); + .filter(openApiProtocol -> openApiProtocol.getProtocolType().equals(protocolTrait.getClass())) + .findFirst() + .map(result -> (OpenApiProtocol) result) + .orElseThrow(() -> { + Stream supportedProtocols = protocolProviders.stream() + .map(OpenApiProtocol::getProtocolType) + .map(Class::getCanonicalName); + return new OpenApiException( + String.format( + "Unable to find an OpenAPI service provider for the `%s` protocol when converting `%s`. " + + "Protocol service providers were found for the following protocol classes: [%s].", + protocolTrait.toShapeId(), + service.getId(), + ValidationUtils.tickedList(supportedProtocols) + ) + ); + }); } // Loads all of the OpenAPI security scheme implementations that are referenced by a service. private List> loadSecuritySchemes( - Model model, - ServiceShape service, - List extensions + Model model, + ServiceShape service, + List extensions ) { // Note: Using a LinkedHashSet here in case order is ever important. ServiceIndex serviceIndex = ServiceIndex.of(model); Set> schemes = getTraitMapTypes(serviceIndex.getAuthSchemes(service)); List> converters = extensions.stream() - .flatMap(extension -> extension.getSecuritySchemeConverters().stream()) - .collect(Collectors.toList()); + .flatMap(extension -> extension.getSecuritySchemeConverters().stream()) + .collect(Collectors.toList()); List> resolved = new ArrayList<>(); for (SecuritySchemeConverter converter : converters) { @@ -429,10 +429,10 @@ private List> loadSecuritySchemes( if (!schemes.isEmpty()) { LOGGER.warning( - () -> String.format( - "Unable to find an OpenAPI authentication converter for the following schemes: [%s]", - schemes - ) + () -> String.format( + "Unable to find an OpenAPI authentication converter for the following schemes: [%s]", + schemes + ) ); } @@ -447,9 +447,9 @@ private List getSupportedTags(Tagged tagged) { List supported = config.getSupportedTags(); return tagged.getTags() - .stream() - .filter(tag -> supported == null || supported.contains(tag)) - .collect(Collectors.toList()); + .stream() + .filter(tag -> supported == null || supported.contains(tag)) + .collect(Collectors.toList()); } private InfoObject createInfo(ServiceShape service) { @@ -460,18 +460,18 @@ private InfoObject createInfo(ServiceShape service) { infoBuilder.version(service.getVersion()); // The title trait maps to info.title. infoBuilder.title( - service.getTrait(TitleTrait.class) - .map(TitleTrait::getValue) - .orElse(service.getId().getName()) + service.getTrait(TitleTrait.class) + .map(TitleTrait::getValue) + .orElse(service.getId().getName()) ); return infoBuilder.build(); } private void addPaths( - Context context, - OpenApi.Builder openApiBuilder, - OpenApiProtocol protocolService, - OpenApiMapper plugin + Context context, + OpenApi.Builder openApiBuilder, + OpenApiProtocol protocolService, + OpenApiMapper plugin ) { TopDownIndex topDownIndex = TopDownIndex.of(context.getModel()); Map paths = new HashMap<>(); @@ -493,12 +493,12 @@ private void addPaths( // Add the documentation trait to the operation if present. shape.getTrait(DocumentationTrait.class) - .map(DocumentationTrait::getValue) - .ifPresent(description -> result.getOperation().description(description)); + .map(DocumentationTrait::getValue) + .ifPresent(description -> result.getOperation().description(description)); // The externalDocumentation trait of the operation maps to externalDocs. OpenApiJsonSchemaMapper.getResolvedExternalDocs(shape, context.getConfig()) - .ifPresent(result.getOperation()::externalDocs); + .ifPresent(result.getOperation()::externalDocs); OperationObject builtOperation = result.getOperation().build(); @@ -542,23 +542,23 @@ private void addPaths( break; default: LOGGER.warning( - String.format( - "The %s HTTP method of `%s` is not supported by OpenAPI", - result.getMethod(), - shape.getId() - ) + String.format( + "The %s HTTP method of `%s` is not supported by OpenAPI", + result.getMethod(), + shape.getId() + ) ); } }, - () -> LOGGER.warning( - String.format( - "The `%s` operation is not supported by the `%s` protocol (implemented by `%s`), and " - + "was omitted", - shape.getId(), - protocolService.getClass().getName(), - context.getProtocolTrait().toShapeId() + () -> LOGGER.warning( + String.format( + "The `%s` operation is not supported by the `%s` protocol (implemented by `%s`), and " + + "was omitted", + shape.getId(), + protocolService.getClass().getName(), + context.getProtocolTrait().toShapeId() + ) ) - ) ); }); @@ -571,10 +571,10 @@ private void addPaths( } private void addOperationSecurity( - Context context, - OperationObject.Builder builder, - OperationShape shape, - OpenApiMapper plugin + Context context, + OperationObject.Builder builder, + OperationShape shape, + OpenApiMapper plugin ) { ServiceShape service = context.getService(); ServiceIndex serviceIndex = ServiceIndex.of(context.getModel()); @@ -594,8 +594,8 @@ private void addOperationSecurity( Collection> authSchemeClasses = getTraitMapTypes(operationSchemes); // Find all the converters with matching types of auth traits on the service. Collection> converters = findMatchingConverters( - context, - authSchemeClasses + context, + authSchemeClasses ); for (SecuritySchemeConverter converter : converters) { List result = createSecurityRequirements(context, converter, service); @@ -611,21 +611,21 @@ private void addOperationSecurity( // This method exists primarily to appease the type-checker. private

List createSecurityRequirements( - Context

context, - SecuritySchemeConverter converter, - ServiceShape service + Context

context, + SecuritySchemeConverter converter, + ServiceShape service ) { return converter.createSecurityRequirements( - context, - service.expectTrait(converter.getAuthSchemeType()), - context.getService() + context, + service.expectTrait(converter.getAuthSchemeType()), + context.getService() ); } private OperationObject addOperationTags( - Context context, - Shape shape, - OperationObject operation + Context context, + Shape shape, + OperationObject operation ) { // Include @tags trait tags of the operation that are compatible with OpenAPI settings. if (context.getConfig().getTags()) { @@ -637,12 +637,12 @@ private OperationObject addOperationTags( // Applies mappers to parameters and updates the operation if parameters change. private OperationObject updateParameters( - Context context, - OperationShape shape, - OperationObject operation, - String method, - String path, - OpenApiMapper plugin + Context context, + OperationShape shape, + OperationObject operation, + String method, + String path, + OpenApiMapper plugin ) { List parameters = new ArrayList<>(); for (ParameterObject parameter : operation.getParameters()) { @@ -650,49 +650,49 @@ private OperationObject updateParameters( } return !parameters.equals(operation.getParameters()) - ? operation.toBuilder().parameters(parameters).build() - : operation; + ? operation.toBuilder().parameters(parameters).build() + : operation; } // Applies mappers to each request body and update the operation if the body changes. private OperationObject updateRequestBody( - Context context, - OperationShape shape, - OperationObject operation, - String method, - String path, - OpenApiMapper plugin + Context context, + OperationShape shape, + OperationObject operation, + String method, + String path, + OpenApiMapper plugin ) { return operation.getRequestBody() - .map(body -> { - RequestBodyObject updatedBody = plugin.updateRequestBody(context, shape, method, path, body); - return body.equals(updatedBody) - ? operation - : operation.toBuilder().requestBody(updatedBody).build(); - }) - .orElse(operation); + .map(body -> { + RequestBodyObject updatedBody = plugin.updateRequestBody(context, shape, method, path, body); + return body.equals(updatedBody) + ? operation + : operation.toBuilder().requestBody(updatedBody).build(); + }) + .orElse(operation); } // Ensures that responses have at least one entry, and applies mappers to // responses and updates the operation is a response changes. private OperationObject updateResponses( - Context context, - OperationShape shape, - OperationObject operation, - String methodName, - String path, - OpenApiMapper plugin + Context context, + OperationShape shape, + OperationObject operation, + String methodName, + String path, + OpenApiMapper plugin ) { Map newResponses = new LinkedHashMap<>(); for (Map.Entry entry : operation.getResponses().entrySet()) { String status = entry.getKey(); ResponseObject responseObject = plugin.updateResponse( - context, - shape, - status, - methodName, - path, - entry.getValue() + context, + shape, + status, + methodName, + path, + entry.getValue() ); newResponses.put(status, responseObject); } @@ -705,10 +705,10 @@ private OperationObject updateResponses( } private void addSecurityComponents( - Context context, - OpenApi.Builder openApiBuilder, - ComponentsObject.Builder components, - OpenApiMapper plugin + Context context, + OpenApi.Builder openApiBuilder, + ComponentsObject.Builder components, + OpenApiMapper plugin ) { ServiceShape service = context.getService(); ServiceIndex serviceIndex = ServiceIndex.of(context.getModel()); @@ -731,10 +731,10 @@ private void addSecurityComponents( List result = createSecurityRequirements(context, converter, context.getService()); String authSchemeName = converter.getOpenApiAuthSchemeName(); Map> requirement = plugin.updateSecurity( - context, - context.getService(), - converter, - MapUtils.of(authSchemeName, result) + context, + context.getService(), + converter, + MapUtils.of(authSchemeName, result) ); if (requirement != null) { openApiBuilder.addSecurity(requirement); @@ -749,10 +749,10 @@ private Set> getTraitMapTypes(Map traitMa // This method exists primarily to appease the type-checker. private

SecurityScheme createAndUpdateSecurityScheme( - Context

context, - OpenApiMapper plugin, - SecuritySchemeConverter converter, - ServiceShape service + Context

context, + OpenApiMapper plugin, + SecuritySchemeConverter converter, + ServiceShape service ) { A authTrait = service.expectTrait(converter.getAuthSchemeType()); SecurityScheme createdScheme = converter.createSecurityScheme(context, authTrait); @@ -761,13 +761,13 @@ private

SecurityScheme createAndUpdateSecurit @SuppressWarnings("unchecked") private Collection> findMatchingConverters( - Context context, - Collection> schemes + Context context, + Collection> schemes ) { return context.getSecuritySchemeConverters() - .stream() - .filter(converter -> schemes.contains(converter.getAuthSchemeType())) - .map(converter -> (SecuritySchemeConverter) converter) - .collect(Collectors.toList()); + .stream() + .filter(converter -> schemes.contains(converter.getAuthSchemeType())) + .map(converter -> (SecuritySchemeConverter) converter) + .collect(Collectors.toList()); } } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiJsonSchemaMapper.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiJsonSchemaMapper.java index 4c2d31ceea2..39fe5fd03a8 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiJsonSchemaMapper.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiJsonSchemaMapper.java @@ -39,21 +39,21 @@ public final class OpenApiJsonSchemaMapper implements JsonSchemaMapper { public Schema.Builder updateSchema(JsonSchemaMapperContext context, Schema.Builder builder) { Shape shape = context.getShape(); OpenApiUtils.getSpecificationExtensionsMap(context.getModel(), shape) - .entrySet() - .forEach(entry -> builder.putExtension(entry.getKey(), entry.getValue())); + .entrySet() + .forEach(entry -> builder.putExtension(entry.getKey(), entry.getValue())); JsonSchemaConfig config = context.getConfig(); getResolvedExternalDocs(shape, config) - .map(ExternalDocumentation::toNode) - .ifPresent(docs -> builder.putExtension("externalDocs", docs)); + .map(ExternalDocumentation::toNode) + .ifPresent(docs -> builder.putExtension("externalDocs", docs)); if (shape.hasTrait(DeprecatedTrait.class)) { builder.putExtension("deprecated", Node.from(true)); } boolean useOpenApiIntegerType = config instanceof OpenApiConfig - && ((OpenApiConfig) config).getUseIntegerType() - && !((OpenApiConfig) config).getDisableIntegerFormat(); + && ((OpenApiConfig) config).getUseIntegerType() + && !((OpenApiConfig) config).getDisableIntegerFormat(); // Don't overwrite an existing format setting. if (!builder.getFormat().isPresent()) { @@ -75,8 +75,8 @@ public Schema.Builder updateSchema(JsonSchemaMapperContext context, Schema.Build // Add the "double" format when epoch-seconds is used // to account for optional millisecond precision. config.detectJsonTimestampFormat(shape) - .filter(format -> format.equals(TimestampFormatTrait.EPOCH_SECONDS)) - .ifPresent(format -> builder.format("double")); + .filter(format -> format.equals(TimestampFormatTrait.EPOCH_SECONDS)) + .ifPresent(format -> builder.format("double")); } else if (shape.hasTrait(SensitiveTrait.class)) { builder.format("password"); } @@ -134,8 +134,8 @@ static Optional getResolvedExternalDocs(Shape shape, Json // Get lower case keys to check for when converting. Map traitUrls = traitOptional.get().getUrls(); Map lowercaseKeyMap = traitUrls.keySet() - .stream() - .collect(MapUtils.toUnmodifiableMap(i -> i.toLowerCase(Locale.US), identity())); + .stream() + .collect(MapUtils.toUnmodifiableMap(i -> i.toLowerCase(Locale.US), identity())); for (String externalDocKey : externalDocKeys) { // Compare the lower case name, but use the specified name. @@ -143,10 +143,10 @@ static Optional getResolvedExternalDocs(Shape shape, Json String traitKey = lowercaseKeyMap.get(externalDocKey); // Return an ExternalDocumentation object assembled from the trait. return Optional.of( - ExternalDocumentation.builder() - .description(traitKey) - .url(traitUrls.get(traitKey)) - .build() + ExternalDocumentation.builder() + .description(traitKey) + .url(traitUrls.get(traitKey)) + .build() ); } } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiMapper.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiMapper.java index f2183352004..308c24499d8 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiMapper.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiMapper.java @@ -74,11 +74,11 @@ default void updateDefaultSettings(Model model, OpenApiConfig config) { * @return Returns the updated operation object. */ default OperationObject updateOperation( - Context context, - OperationShape shape, - OperationObject operation, - String httpMethodName, - String path + Context context, + OperationShape shape, + OperationObject operation, + String httpMethodName, + String path ) { return operation; } @@ -97,11 +97,11 @@ default OperationObject updateOperation( * @return Returns the updated operation object. */ default OperationObject postProcessOperation( - Context context, - OperationShape shape, - OperationObject operation, - String httpMethodName, - String path + Context context, + OperationShape shape, + OperationObject operation, + String httpMethodName, + String path ) { return operation; } @@ -129,11 +129,11 @@ default PathItem updatePathItem(Context context, String path, P * @return Returns the updated parameter. */ default ParameterObject updateParameter( - Context context, - OperationShape operation, - String httpMethodName, - String path, - ParameterObject parameterObject + Context context, + OperationShape operation, + String httpMethodName, + String path, + ParameterObject parameterObject ) { return parameterObject; } @@ -149,11 +149,11 @@ default ParameterObject updateParameter( * @return Returns the updated request body. */ default RequestBodyObject updateRequestBody( - Context context, - OperationShape operation, - String httpMethodName, - String path, - RequestBodyObject requestBody + Context context, + OperationShape operation, + String httpMethodName, + String path, + RequestBodyObject requestBody ) { return requestBody; } @@ -170,12 +170,12 @@ default RequestBodyObject updateRequestBody( * @return Returns the updated response object. */ default ResponseObject updateResponse( - Context context, - OperationShape operation, - String status, - String httpMethodName, - String path, - ResponseObject response + Context context, + OperationShape operation, + String status, + String httpMethodName, + String path, + ResponseObject response ) { return response; } @@ -198,9 +198,9 @@ default void before(Context context, OpenApi.Builder builder) { * @return Returns the updated security scheme object. Return null to remove the scheme. */ default SecurityScheme updateSecurityScheme( - Context context, - Trait authTrait, - SecurityScheme securityScheme + Context context, + Trait authTrait, + SecurityScheme securityScheme ) { return securityScheme; } @@ -220,10 +220,10 @@ default SecurityScheme updateSecurityScheme( * @return Returns the updated security requirement, a mapping of scheme to requirements. */ default Map> updateSecurity( - Context context, - Shape shape, - SecuritySchemeConverter converter, - Map> requirement + Context context, + Shape shape, + SecuritySchemeConverter converter, + Map> requirement ) { return requirement; } @@ -271,11 +271,11 @@ public void updateDefaultSettings(Model model, OpenApiConfig config) { @Override public OperationObject updateOperation( - Context context, - OperationShape shape, - OperationObject operation, - String httpMethodName, - String path + Context context, + OperationShape shape, + OperationObject operation, + String httpMethodName, + String path ) { for (OpenApiMapper plugin : sorted) { if (operation == null) { @@ -288,11 +288,11 @@ public OperationObject updateOperation( @Override public OperationObject postProcessOperation( - Context context, - OperationShape shape, - OperationObject operation, - String httpMethodName, - String path + Context context, + OperationShape shape, + OperationObject operation, + String httpMethodName, + String path ) { for (OpenApiMapper plugin : sorted) { if (operation == null) { @@ -316,22 +316,22 @@ public PathItem updatePathItem(Context context, String path, Pa @Override public ParameterObject updateParameter( - Context context, - OperationShape operation, - String httpMethodName, - String path, - ParameterObject parameterObject + Context context, + OperationShape operation, + String httpMethodName, + String path, + ParameterObject parameterObject ) { for (OpenApiMapper plugin : sorted) { if (parameterObject == null) { return null; } parameterObject = plugin.updateParameter( - context, - operation, - httpMethodName, - path, - parameterObject + context, + operation, + httpMethodName, + path, + parameterObject ); } return parameterObject; @@ -339,11 +339,11 @@ public ParameterObject updateParameter( @Override public RequestBodyObject updateRequestBody( - Context context, - OperationShape shape, - String httpMethodName, - String path, - RequestBodyObject requestBody + Context context, + OperationShape shape, + String httpMethodName, + String path, + RequestBodyObject requestBody ) { for (OpenApiMapper plugin : sorted) { if (requestBody == null) { @@ -356,12 +356,12 @@ public RequestBodyObject updateRequestBody( @Override public ResponseObject updateResponse( - Context context, - OperationShape shape, - String status, - String httpMethodName, - String path, - ResponseObject response + Context context, + OperationShape shape, + String status, + String httpMethodName, + String path, + ResponseObject response ) { for (OpenApiMapper plugin : sorted) { if (response == null) { @@ -374,9 +374,9 @@ public ResponseObject updateResponse( @Override public SecurityScheme updateSecurityScheme( - Context context, - Trait authTrait, - SecurityScheme securityScheme + Context context, + Trait authTrait, + SecurityScheme securityScheme ) { for (OpenApiMapper plugin : sorted) { if (securityScheme == null) { @@ -389,10 +389,10 @@ public SecurityScheme updateSecurityScheme( @Override public Map> updateSecurity( - Context context, - Shape shape, - SecuritySchemeConverter converter, - Map> requirement + Context context, + Shape shape, + SecuritySchemeConverter converter, + Map> requirement ) { for (OpenApiMapper plugin : sorted) { if (requirement == null || requirement.isEmpty()) { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiProtocol.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiProtocol.java index b5549700183..3d19909d4e7 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiProtocol.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiProtocol.java @@ -81,14 +81,14 @@ default void updateDefaultSettings(Model model, OpenApiConfig config) { */ default String getOperationUri(Context context, OperationShape operation) { return operation.getTrait(HttpTrait.class) - .map(HttpTrait::getUri) - .map(UriPattern::toString) - .orElseThrow( - () -> new OpenApiException( - "The `" + operation.getId() + "` operation has no `http` binding trait, which is " - + "required to compute a URI (using the default protocol implementation)" - ) - ); + .map(HttpTrait::getUri) + .map(UriPattern::toString) + .orElseThrow( + () -> new OpenApiException( + "The `" + operation.getId() + "` operation has no `http` binding trait, which is " + + "required to compute a URI (using the default protocol implementation)" + ) + ); } /** @@ -104,13 +104,13 @@ default String getOperationUri(Context context, OperationShape operation) { */ default String getOperationMethod(Context context, OperationShape operation) { return operation.getTrait(HttpTrait.class) - .map(HttpTrait::getMethod) - .orElseThrow( - () -> new OpenApiException( - "The `" + operation.getId() + "` operation has no `http` binding trait, which is " - + "required to compute a method (using the default protocol implementation)" - ) - ); + .map(HttpTrait::getMethod) + .orElseThrow( + () -> new OpenApiException( + "The `" + operation.getId() + "` operation has no `http` binding trait, which is " + + "required to compute a method (using the default protocol implementation)" + ) + ); } /** diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForGreedyLabels.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForGreedyLabels.java index 55ceb370408..8f70a537d3f 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForGreedyLabels.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForGreedyLabels.java @@ -33,9 +33,9 @@ public OpenApi after(Context context, OpenApi openApi) { // Throw an exception or warning when greedy URI labels are found in the path. if (path.contains("+}")) { String message = "Greedy URI path label found in path `" + path + "`. Not all OpenAPI " - + "tools support this style of URI labels. Greedy URI labels are expected " - + "to capture all remaining components of a URI, so if a tool does not " - + "support them, the API will not function properly."; + + "tools support this style of URI labels. Greedy URI labels are expected " + + "to capture all remaining components of a URI, so if a tool does not " + + "support them, the API will not function properly."; if (context.getConfig().getForbidGreedyLabels()) { throw new OpenApiException(message); } else { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForPrefixHeaders.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForPrefixHeaders.java index b52b9b2fd34..8e0400db752 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForPrefixHeaders.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForPrefixHeaders.java @@ -48,9 +48,9 @@ public void before(Context context, OpenApi.Builder builder) { } private void checkForResponseHeaders( - Context context, - HttpBindingIndex bindingIndex, - ToShapeId shapeId + Context context, + HttpBindingIndex bindingIndex, + ToShapeId shapeId ) { check(context, bindingIndex.getResponseBindings(shapeId, HttpBinding.Location.PREFIX_HEADERS)); } @@ -74,8 +74,8 @@ private void check(Context context, List bindings) private static String createMessage(HttpBinding binding) { MemberShape member = binding.getMember(); return String.format( - "The `httpPrefixHeaders` trait is not supported by OpenAPI and was found on `%s`", - member.getId() + "The `httpPrefixHeaders` trait is not supported by OpenAPI and was found on `%s`", + member.getId() ); } } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonAdd.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonAdd.java index 780fdb652ee..19ed3f2f846 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonAdd.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonAdd.java @@ -50,16 +50,16 @@ public ObjectNode updateNode(Context context, OpenApi openapi, if (entry.getKey().startsWith("/components/schemas")) { LOGGER.severe( - "Adding schemas to the generated OpenAPI model directly means that " - + "clients, servers, and other artifacts generated from your Smithy " - + "model don't know about all of the shapes used in the service. You " - + "almost certainly should not do this." + "Adding schemas to the generated OpenAPI model directly means that " + + "clients, servers, and other artifacts generated from your Smithy " + + "model don't know about all of the shapes used in the service. You " + + "almost certainly should not do this." ); } result = NodePointer.parse(entry.getKey()) - .addWithIntermediateValues(result, entry.getValue().toNode()) - .expectObjectNode(); + .addWithIntermediateValues(result, entry.getValue().toNode()) + .expectObjectNode(); } catch (IllegalArgumentException e) { throw new OpenApiException(e.getMessage(), e); } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonSubstitutions.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonSubstitutions.java index 4f776918156..76488002703 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonSubstitutions.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonSubstitutions.java @@ -37,11 +37,11 @@ public ObjectNode updateNode(Context context, OpenApi openapi, } LOGGER.warning( - "Using `substitutions` is discouraged. DO NOT use placeholders in your Smithy model " - + "for properties that are used by other tools like SDKs or service frameworks; " - + "placeholders should only ever be used in models for metadata that is specific to " - + "generating OpenAPI artifacts.\n\n" - + "Prefer safer alternatives like `jsonAdd`" + "Using `substitutions` is discouraged. DO NOT use placeholders in your Smithy model " + + "for properties that are used by other tools like SDKs or service frameworks; " + + "placeholders should only ever be used in models for metadata that is specific to " + + "generating OpenAPI artifacts.\n\n" + + "Prefer safer alternatives like `jsonAdd`" ); return JsonSubstitutions.create(substitutions).apply(node).expectObjectNode(); diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/RemoveEmptyComponents.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/RemoveEmptyComponents.java index ae7d87c052a..8794bee78c9 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/RemoveEmptyComponents.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/RemoveEmptyComponents.java @@ -36,15 +36,15 @@ public ObjectNode updateNode(Context context, OpenApi openapi, // Remove all component key value pairs that are empty objects. ObjectNode updatedComponents = components.getMembers() - .entrySet() - .stream() - .filter(entry -> !isEmptyObject(entry.getValue())) - .collect(ObjectNode.collect(Map.Entry::getKey, Map.Entry::getValue)); + .entrySet() + .stream() + .filter(entry -> !isEmptyObject(entry.getValue())) + .collect(ObjectNode.collect(Map.Entry::getKey, Map.Entry::getValue)); // Remove the "components" key from the model if it's empty. return updatedComponents.isEmpty() - ? node.withoutMember(COMPONENTS) - : node.withMember(COMPONENTS, updatedComponents); + ? node.withoutMember(COMPONENTS) + : node.withMember(COMPONENTS, updatedComponents); } private static boolean isEmptyObject(Node node) { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/RemoveUnusedComponents.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/RemoveUnusedComponents.java index a0ba643f61d..29e489bda72 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/RemoveUnusedComponents.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/RemoveUnusedComponents.java @@ -67,11 +67,11 @@ private OpenApi removalRound(Context context, OpenApi openapi) // Create a set of every component pointer (currently just schemas). String schemaPointerPrefix = context.getConfig().getDefinitionPointer() + "/"; Set pointers = openapi.getComponents() - .getSchemas() - .keySet() - .stream() - .map(key -> schemaPointerPrefix + key) - .collect(Collectors.toSet()); + .getSchemas() + .keySet() + .stream() + .map(key -> schemaPointerPrefix + key) + .collect(Collectors.toSet()); // Remove all found "$ref" pointers from the set, leaving only unreferenced. pointers.removeAll(findAllRefs(openapi.toNode().expectObjectNode())); @@ -116,9 +116,9 @@ public Set objectNode(ObjectNode node) { if (node.getMember("$ref").isPresent()) { node.getMember("$ref") - .flatMap(Node::asStringNode) - .map(StringNode::getValue) - .ifPresent(result::add); + .flatMap(Node::asStringNode) + .map(StringNode::getValue) + .ifPresent(result::add); } else { for (Node member : node.getMembers().values()) { result.addAll(member.accept(this)); @@ -133,9 +133,9 @@ public Set objectNode(ObjectNode node) { private OpenApi removeUnusedSecuritySchemes(OpenApi openapi) { // Determine which security schemes were actually used. Set used = openapi.getSecurity() - .stream() - .flatMap(map -> map.keySet().stream()) - .collect(Collectors.toSet()); + .stream() + .flatMap(map -> map.keySet().stream()) + .collect(Collectors.toSet()); for (PathItem path : openapi.getPaths().values()) { for (OperationObject operation : path.getOperations().values()) { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/SpecificationExtensionsMapper.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/SpecificationExtensionsMapper.java index 46e28674435..b2d1086d944 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/SpecificationExtensionsMapper.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/SpecificationExtensionsMapper.java @@ -23,9 +23,9 @@ public class SpecificationExtensionsMapper implements OpenApiMapper { @Override public OpenApi after(Context context, OpenApi openapi) { openapi.getExtensions() - .putAll( - OpenApiUtils.getSpecificationExtensionsMap(context.getModel(), context.getService()) - ); + .putAll( + OpenApiUtils.getSpecificationExtensionsMap(context.getModel(), context.getService()) + ); return openapi; } @@ -34,11 +34,11 @@ public OpenApi after(Context context, OpenApi openapi) { */ @Override public OperationObject updateOperation( - Context context, - OperationShape shape, - OperationObject operation, - String httpMethodName, - String path + Context context, + OperationShape shape, + OperationObject operation, + String httpMethodName, + String path ) { operation.getExtensions().putAll(OpenApiUtils.getSpecificationExtensionsMap(context.getModel(), shape)); return operation; diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/UnsupportedTraits.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/UnsupportedTraits.java index ca09156ece7..fc98727d916 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/UnsupportedTraits.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/UnsupportedTraits.java @@ -35,38 +35,38 @@ public byte getOrder() { @Override public void before(Context context, OpenApi.Builder builder) { List>> violations = context.getModel() - .shapes() - .map( - shape -> Pair.of( - shape.getId(), - TRAITS.stream() - .filter(trait -> shape.findTrait(trait).isPresent()) - .collect(Collectors.toList()) + .shapes() + .map( + shape -> Pair.of( + shape.getId(), + TRAITS.stream() + .filter(trait -> shape.findTrait(trait).isPresent()) + .collect(Collectors.toList()) + ) ) - ) - .filter(pair -> pair.getRight().size() > 0) - .collect(Collectors.toList()); + .filter(pair -> pair.getRight().size() > 0) + .collect(Collectors.toList()); if (violations.isEmpty()) { return; } StringBuilder message = new StringBuilder( - "Encountered unsupported Smithy traits when converting to OpenAPI:" + "Encountered unsupported Smithy traits when converting to OpenAPI:" ); violations.forEach( - pair -> message.append( - String.format( - " (`%s`: [%s])", - pair.getLeft(), - String.join(",", pair.getRight()) + pair -> message.append( + String.format( + " (`%s`: [%s])", + pair.getLeft(), + String.join(",", pair.getRight()) + ) ) - ) ); message.append( - ". While these traits may still be meaningful to clients and servers using the Smithy " - + "model directly, they have no direct corollary in OpenAPI and can not be included in " - + "the generated model." + ". While these traits may still be meaningful to clients and servers using the Smithy " + + "model directly, they have no direct corollary in OpenAPI and can not be included in " + + "the generated model." ); if (context.getConfig().getIgnoreUnsupportedTraits()) { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/AbstractRestProtocol.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/AbstractRestProtocol.java index a395e887c83..dea4cee8af9 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/AbstractRestProtocol.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/AbstractRestProtocol.java @@ -105,10 +105,10 @@ enum MessageType { * @return Returns the created document schema. */ abstract Schema createDocumentSchema( - Context context, - Shape operationOrError, - List bindings, - MessageType messageType + Context context, + Shape operationOrError, + List bindings, + MessageType messageType ); /** @@ -138,7 +138,7 @@ public Set getProtocolRequestHeaders(Context context, OperationShape String documentMediaType = getDocumentMediaType(context, operationShape, MessageType.REQUEST); // If the request has a body with a content type, allow the content-type and content-length headers. bindingIndex.determineRequestContentType(operationShape, documentMediaType) - .ifPresent(c -> headers.addAll(ProtocolUtils.CONTENT_HEADERS)); + .ifPresent(c -> headers.addAll(ProtocolUtils.CONTENT_HEADERS)); if (operationShape.hasTrait(HttpChecksumRequiredTrait.class)) { headers.add("Content-Md5"); @@ -164,7 +164,7 @@ public Optional createOperation(Context context, OperationShape op String method = context.getOpenApiProtocol().getOperationMethod(context, operation); String uri = context.getOpenApiProtocol().getOperationUri(context, operation); OperationObject.Builder builder = OperationObject.builder() - .operationId(serviceShape.getContextualName(operation)); + .operationId(serviceShape.getContextualName(operation)); createPathParameters(context, operation).forEach(builder::addParameter); createQueryParameters(context, operation).forEach(builder::addParameter); createRequestHeaderParameters(context, operation).forEach(builder::addParameter); @@ -184,17 +184,17 @@ private List createPathParameters(Context context, Operation String memberName = binding.getMemberName(); SmithyPattern.Segment label = httpTrait.getUri() - .getLabel(memberName) - .orElseThrow( - () -> new OpenApiException( - String.format( - "Unable to find URI label on %s for %s: %s", - operation.getId(), - binding.getMemberName(), - httpTrait.getUri() - ) - ) - ); + .getLabel(memberName) + .orElseThrow( + () -> new OpenApiException( + String.format( + "Unable to find URI label on %s for %s: %s", + operation.getId(), + binding.getMemberName(), + httpTrait.getUri() + ) + ) + ); // Greedy labels in OpenAPI need to include the label in the generated parameter. // For example, given "/{foo+}", the parameter name must be "foo+". @@ -207,19 +207,19 @@ private List createPathParameters(Context context, Operation } result.add( - ModelUtils.createParameterMember(context, binding.getMember()) - .name(name) - .in("path") - .schema(schema) - .examples( - createExamplesForMembersWithHttpTraits( - operation, - binding, - MessageType.REQUEST, - null - ) - ) - .build() + ModelUtils.createParameterMember(context, binding.getMember()) + .name(name) + .in("path") + .schema(schema) + .examples( + createExamplesForMembersWithHttpTraits( + operation, + binding, + MessageType.REQUEST, + null + ) + ) + .build() ); } @@ -231,10 +231,10 @@ private List createPathParameters(Context context, Operation * path parameters, query parameters, header parameters, and payload. */ private Map createExamplesForMembersWithHttpTraits( - Shape operationOrError, - HttpBinding binding, - MessageType type, - OperationShape operation + Shape operationOrError, + HttpBinding binding, + MessageType type, + OperationShape operation ) { if (operation == null && type == MessageType.ERROR) { return Collections.emptyMap(); @@ -249,25 +249,25 @@ private Map createExamplesForMembersWithHttpTraits( Optional examplesTrait = operationOrError.getTrait(ExamplesTrait.class); for (ExamplesTrait.Example example : examplesTrait.map(ExamplesTrait::getExamples) - .orElse(Collections.emptyList())) { + .orElse(Collections.emptyList())) { ObjectNode inputOrOutput = type == MessageType.REQUEST - ? example.getInput() - : example.getOutput().orElse(Node.objectNode()); + ? example.getInput() + : example.getOutput().orElse(Node.objectNode()); String name = operationOrError.getId().getName() + "_example" + uniqueNum++; // this if condition is needed to avoid errors when converting examples of response. if ((!example.getError().isPresent() || type == MessageType.REQUEST) - && inputOrOutput.containsMember(binding.getMemberName())) { + && inputOrOutput.containsMember(binding.getMemberName())) { Node values = inputOrOutput.getMember(binding.getMemberName()).get(); examples.put( - name, - ExampleObject.builder() - .summary(example.getTitle()) - .description(example.getDocumentation().orElse("")) - .value(transformSmithyValueToProtocolValue(values)) - .build() - .toNode() + name, + ExampleObject.builder() + .summary(example.getTitle()) + .description(example.getDocumentation().orElse("")) + .value(transformSmithyValueToProtocolValue(values)) + .build() + .toNode() ); } } @@ -279,9 +279,9 @@ private Map createExamplesForMembersWithHttpTraits( * Helper method for createExamples() method. */ private Map createErrorExamplesForMembersWithHttpTraits( - Shape error, - HttpBinding binding, - OperationShape operation + Shape error, + HttpBinding binding, + OperationShape operation ) { Map examples = new TreeMap<>(); @@ -289,26 +289,26 @@ private Map createErrorExamplesForMembersWithHttpTraits( int uniqueNum = 1; Optional examplesTrait = operation.getTrait(ExamplesTrait.class); for (ExamplesTrait.Example example : examplesTrait.map(ExamplesTrait::getExamples) - .orElse(Collections.emptyList())) { + .orElse(Collections.emptyList())) { String name = operation.getId().getName() + "_example" + uniqueNum++; // this has to be checked because an operation can have more than one error linked to it. ExamplesTrait.ErrorExample errorExample = example.getError().orElse(null); if (errorExample != null - && errorExample.getShapeId() == error.toShapeId() - && errorExample.getContent().containsMember(binding.getMemberName())) { + && errorExample.getShapeId() == error.toShapeId() + && errorExample.getContent().containsMember(binding.getMemberName())) { Node values = errorExample.getContent() - .getMember(binding.getMemberName()) - .get(); + .getMember(binding.getMemberName()) + .get(); examples.put( - name, - ExampleObject.builder() - .summary(example.getTitle()) - .description(example.getDocumentation().orElse("")) - .value(transformSmithyValueToProtocolValue(values)) - .build() - .toNode() + name, + ExampleObject.builder() + .summary(example.getTitle()) + .description(example.getDocumentation().orElse("")) + .value(transformSmithyValueToProtocolValue(values)) + .build() + .toNode() ); } } @@ -319,10 +319,10 @@ private Map createErrorExamplesForMembersWithHttpTraits( * This method is used for converting the Smithy examples to OpenAPI examples for non-payload HTTP message body. */ private Map createBodyExamples( - Shape operationOrError, - List bindings, - MessageType type, - OperationShape operation + Shape operationOrError, + List bindings, + MessageType type, + OperationShape operation ) { if (operation == null && type == MessageType.ERROR) { return Collections.emptyMap(); @@ -337,25 +337,25 @@ private Map createBodyExamples( Optional examplesTrait = operationOrError.getTrait(ExamplesTrait.class); for (ExamplesTrait.Example example : examplesTrait.map(ExamplesTrait::getExamples) - .orElse(Collections.emptyList())) { + .orElse(Collections.emptyList())) { // get members included in bindings ObjectNode values = getMembersWithHttpBindingTrait( - bindings, - type == MessageType.REQUEST - ? example.getInput() - : example.getOutput().orElse(Node.objectNode()) + bindings, + type == MessageType.REQUEST + ? example.getInput() + : example.getOutput().orElse(Node.objectNode()) ); String name = operationOrError.getId().getName() + "_example" + uniqueNum++; // this if condition is needed to avoid errors when converting examples of response. if (!example.getError().isPresent() || type == MessageType.REQUEST) { examples.put( - name, - ExampleObject.builder() - .summary(example.getTitle()) - .description(example.getDocumentation().orElse("")) - .value(transformSmithyValueToProtocolValue(values)) - .build() - .toNode() + name, + ExampleObject.builder() + .summary(example.getTitle()) + .description(example.getDocumentation().orElse("")) + .value(transformSmithyValueToProtocolValue(values)) + .build() + .toNode() ); } } @@ -364,30 +364,30 @@ private Map createBodyExamples( } private Map createErrorBodyExamples( - Shape error, - List bindings, - OperationShape operation + Shape error, + List bindings, + OperationShape operation ) { Map examples = new TreeMap<>(); // unique numbering for unique example names in OpenAPI. int uniqueNum = 1; Optional examplesTrait = operation.getTrait(ExamplesTrait.class); for (ExamplesTrait.Example example : examplesTrait.map(ExamplesTrait::getExamples) - .orElse(Collections.emptyList())) { + .orElse(Collections.emptyList())) { String name = operation.getId().getName() + "_example" + uniqueNum++; // this has to be checked because an operation can have more than one error linked to it. if (example.getError().isPresent() - && example.getError().get().getShapeId() == error.toShapeId()) { + && example.getError().get().getShapeId() == error.toShapeId()) { // get members included in bindings ObjectNode values = getMembersWithHttpBindingTrait(bindings, example.getError().get().getContent()); examples.put( - name, - ExampleObject.builder() - .summary(example.getTitle()) - .description(example.getDocumentation().orElse("")) - .value(transformSmithyValueToProtocolValue(values)) - .build() - .toNode() + name, + ExampleObject.builder() + .summary(example.getTitle()) + .description(example.getDocumentation().orElse("")) + .value(transformSmithyValueToProtocolValue(values)) + .build() + .toNode() ); } } @@ -421,7 +421,7 @@ private Schema createPathParameterSchema(Context context, HttpBinding binding if (needsInlineTimestampSchema(context, member)) { // Create a copy of the targeted schema and remove any possible numeric keywords. Schema.Builder copiedBuilder = ModelUtils.convertSchemaToStringBuilder( - context.getSchema(context.getPointer(member)) + context.getSchema(context.getPointer(member)) ); return copiedBuilder.format("date-time").build(); } else if (context.getJsonSchemaConverter().isInlined(member)) { @@ -437,9 +437,9 @@ private boolean needsInlineTimestampSchema(Context context, Mem } return context.getModel() - .getShape(member.getTarget()) - .filter(Shape::isTimestampShape) - .isPresent(); + .getShape(member.getTarget()) + .filter(Shape::isTimestampShape) + .isPresent(); } // Creates parameters that appear in the query string. Each input member @@ -456,8 +456,8 @@ private List createQueryParameters(Context context, Operatio for (HttpBinding binding : bindings) { MemberShape member = binding.getMember(); ParameterObject.Builder param = ModelUtils.createParameterMember(context, member) - .in("query") - .name(binding.getLocationName()); + .in("query") + .name(binding.getLocationName()); Shape target = context.getModel().expectShape(member.getTarget()); // List and set shapes in the query string are repeated, so we need to "explode" them @@ -497,16 +497,16 @@ private Schema createQuerySchema(Context context, MemberShape member, Shape t private Collection createRequestHeaderParameters(Context context, OperationShape operation) { List bindings = HttpBindingIndex.of(context.getModel()) - .getRequestBindings(operation, HttpBinding.Location.HEADER); + .getRequestBindings(operation, HttpBinding.Location.HEADER); return createHeaderParameters(context, bindings, MessageType.REQUEST, operation, null).values(); } private Map createHeaderParameters( - Context context, - List bindings, - MessageType messageType, - Shape operationOrError, - OperationShape operation + Context context, + List bindings, + MessageType messageType, + Shape operationOrError, + OperationShape operation ) { Map result = new TreeMap<>(); @@ -536,14 +536,14 @@ private Map createHeaderParameters( } private Optional createRequestBody( - Context context, - HttpBindingIndex bindingIndex, - EventStreamIndex eventStreamIndex, - OperationShape operation + Context context, + HttpBindingIndex bindingIndex, + EventStreamIndex eventStreamIndex, + OperationShape operation ) { List payloadBindings = bindingIndex.getRequestBindings( - operation, - HttpBinding.Location.PAYLOAD + operation, + HttpBinding.Location.PAYLOAD ); // Get the default media type if one cannot be resolved. @@ -551,16 +551,16 @@ private Optional createRequestBody( // Get the event stream media type if an event stream is in use. String eventStreamMediaType = eventStreamIndex.getInputInfo(operation) - .map(info -> getEventStreamMediaType(context, info)) - .orElse(null); + .map(info -> getEventStreamMediaType(context, info)) + .orElse(null); String mediaType = bindingIndex - .determineRequestContentType(operation, documentMediaType, eventStreamMediaType) - .orElse(null); + .determineRequestContentType(operation, documentMediaType, eventStreamMediaType) + .orElse(null); return payloadBindings.isEmpty() - ? createRequestDocument(mediaType, context, bindingIndex, operation) - : createRequestPayload(mediaType, context, payloadBindings.get(0), operation); + ? createRequestDocument(mediaType, context, bindingIndex, operation) + : createRequestPayload(mediaType, context, payloadBindings.get(0), operation); } /** @@ -578,10 +578,10 @@ protected String getEventStreamMediaType(Context context, EventStreamInfo inf } private Optional createRequestPayload( - String mediaTypeRange, - Context context, - HttpBinding binding, - OperationShape operation + String mediaTypeRange, + Context context, + HttpBinding binding, + OperationShape operation ) { // API Gateway validation requires that in-line schemas must be objects // or arrays. These schemas are synthesized as references so that @@ -591,27 +591,27 @@ private Optional createRequestPayload( String shapeName = context.getService().getContextualName(shape.getId()); return shapeName + "InputPayload"; }).toBuilder() - .examples( - createExamplesForMembersWithHttpTraits( - operation, - binding, - MessageType.REQUEST, - null + .examples( + createExamplesForMembersWithHttpTraits( + operation, + binding, + MessageType.REQUEST, + null + ) ) - ) - .build(); + .build(); RequestBodyObject requestBodyObject = RequestBodyObject.builder() - .putContent(Objects.requireNonNull(mediaTypeRange), mediaTypeObject) - .required(binding.getMember().isRequired()) - .build(); + .putContent(Objects.requireNonNull(mediaTypeRange), mediaTypeObject) + .required(binding.getMember().isRequired()) + .build(); return Optional.of(requestBodyObject); } private Optional createRequestDocument( - String mediaType, - Context context, - HttpBindingIndex bindingIndex, - OperationShape operation + String mediaType, + Context context, + HttpBindingIndex bindingIndex, + OperationShape operation ) { List bindings = bindingIndex.getRequestBindings(operation, HttpBinding.Location.DOCUMENT); @@ -626,9 +626,9 @@ private Optional createRequestDocument( String synthesizedName = stripNonAlphaNumericCharsIfNecessary(context, contextName) + "RequestContent"; String pointer = context.putSynthesizedSchema(synthesizedName, schema); MediaTypeObject mediaTypeObject = MediaTypeObject.builder() - .schema(Schema.builder().ref(pointer).build()) - .examples(createBodyExamples(operation, bindings, MessageType.REQUEST, null)) - .build(); + .schema(Schema.builder().ref(pointer).build()) + .examples(createBodyExamples(operation, bindings, MessageType.REQUEST, null)) + .build(); // If any of the top level bindings are required, then the body itself must be required. boolean required = false; @@ -640,105 +640,105 @@ private Optional createRequestDocument( } return Optional.of( - RequestBodyObject.builder() - .putContent(mediaType, mediaTypeObject) - .required(required) - .build() + RequestBodyObject.builder() + .putContent(mediaType, mediaTypeObject) + .required(required) + .build() ); } private Map createResponses( - Context context, - HttpBindingIndex bindingIndex, - EventStreamIndex eventStreamIndex, - OperationShape operation + Context context, + HttpBindingIndex bindingIndex, + EventStreamIndex eventStreamIndex, + OperationShape operation ) { Map result = new TreeMap<>(); OperationIndex operationIndex = OperationIndex.of(context.getModel()); StructureShape output = operationIndex.expectOutputShape(operation); updateResponsesMapWithResponseStatusAndObject( - context, - bindingIndex, - eventStreamIndex, - operation, - output, - result - ); - - for (StructureShape error : operationIndex.getErrors(operation)) { - updateResponsesMapWithResponseStatusAndObject( context, bindingIndex, eventStreamIndex, operation, - error, + output, result + ); + + for (StructureShape error : operationIndex.getErrors(operation)) { + updateResponsesMapWithResponseStatusAndObject( + context, + bindingIndex, + eventStreamIndex, + operation, + error, + result ); } return result; } private void updateResponsesMapWithResponseStatusAndObject( - Context context, - HttpBindingIndex bindingIndex, - EventStreamIndex eventStreamIndex, - OperationShape operation, - StructureShape shape, - Map responses + Context context, + HttpBindingIndex bindingIndex, + EventStreamIndex eventStreamIndex, + OperationShape operation, + StructureShape shape, + Map responses ) { Shape operationOrError = shape.hasTrait(ErrorTrait.class) ? shape : operation; String statusCode = context.getOpenApiProtocol().getOperationResponseStatusCode(context, operationOrError); ResponseObject response = createResponse( - context, - bindingIndex, - eventStreamIndex, - statusCode, - operationOrError, - operation + context, + bindingIndex, + eventStreamIndex, + statusCode, + operationOrError, + operation ); responses.put(statusCode, response); } private ResponseObject createResponse( - Context context, - HttpBindingIndex bindingIndex, - EventStreamIndex eventStreamIndex, - String statusCode, - Shape operationOrError, - OperationShape operation + Context context, + HttpBindingIndex bindingIndex, + EventStreamIndex eventStreamIndex, + String statusCode, + Shape operationOrError, + OperationShape operation ) { ResponseObject.Builder responseBuilder = ResponseObject.builder(); String contextName = context.getService().getContextualName(operationOrError); String responseName = stripNonAlphaNumericCharsIfNecessary(context, contextName); responseBuilder.description(String.format("%s %s response", responseName, statusCode)); createResponseHeaderParameters(context, operationOrError, operation) - .forEach((k, v) -> responseBuilder.putHeader(k, Ref.local(v))); + .forEach((k, v) -> responseBuilder.putHeader(k, Ref.local(v))); addResponseContent(context, bindingIndex, eventStreamIndex, responseBuilder, operationOrError, operation); return responseBuilder.build(); } private Map createResponseHeaderParameters( - Context context, - Shape operationOrError, - OperationShape operation + Context context, + Shape operationOrError, + OperationShape operation ) { List bindings = HttpBindingIndex.of(context.getModel()) - .getResponseBindings(operationOrError, HttpBinding.Location.HEADER); + .getResponseBindings(operationOrError, HttpBinding.Location.HEADER); MessageType type = !operationOrError.hasTrait(ErrorTrait.class) ? MessageType.RESPONSE : MessageType.ERROR; return createHeaderParameters(context, bindings, type, operationOrError, operation); } private void addResponseContent( - Context context, - HttpBindingIndex bindingIndex, - EventStreamIndex eventStreamIndex, - ResponseObject.Builder responseBuilder, - Shape operationOrError, - OperationShape operation + Context context, + HttpBindingIndex bindingIndex, + EventStreamIndex eventStreamIndex, + ResponseObject.Builder responseBuilder, + Shape operationOrError, + OperationShape operation ) { List payloadBindings = bindingIndex.getResponseBindings( - operationOrError, - HttpBinding.Location.PAYLOAD + operationOrError, + HttpBinding.Location.PAYLOAD ); // Get the default media type if one cannot be resolved. @@ -746,41 +746,41 @@ private void addResponseContent( // Get the event stream media type if an event stream is in use. String eventStreamMediaType = eventStreamIndex.getOutputInfo(operationOrError) - .map(info -> getEventStreamMediaType(context, info)) - .orElse(null); + .map(info -> getEventStreamMediaType(context, info)) + .orElse(null); String mediaType = bindingIndex - .determineResponseContentType(operationOrError, documentMediaType, eventStreamMediaType) - .orElse(null); + .determineResponseContentType(operationOrError, documentMediaType, eventStreamMediaType) + .orElse(null); if (!payloadBindings.isEmpty()) { createResponsePayload( - mediaType, - context, - payloadBindings.get(0), - responseBuilder, - operationOrError, - operation + mediaType, + context, + payloadBindings.get(0), + responseBuilder, + operationOrError, + operation ); } else { createResponseDocumentIfNeeded( - mediaType, - context, - bindingIndex, - responseBuilder, - operationOrError, - operation + mediaType, + context, + bindingIndex, + responseBuilder, + operationOrError, + operation ); } } private void createResponsePayload( - String mediaType, - Context context, - HttpBinding binding, - ResponseObject.Builder responseBuilder, - Shape operationOrError, - OperationShape operation + String mediaType, + Context context, + HttpBinding binding, + ResponseObject.Builder responseBuilder, + Shape operationOrError, + OperationShape operation ) { Objects.requireNonNull(mediaType, "Unable to determine response media type for " + operationOrError); @@ -792,18 +792,18 @@ private void createResponsePayload( MediaTypeObject mediaTypeObject = getMediaTypeObject(context, schema, operationOrError, shape -> { String shapeName = context.getService().getContextualName(shape.getId()); return shape instanceof OperationShape - ? shapeName + "OutputPayload" - : shapeName + "ErrorPayload"; + ? shapeName + "OutputPayload" + : shapeName + "ErrorPayload"; }).toBuilder() - .examples( - createExamplesForMembersWithHttpTraits( - operationOrError, - binding, - type, - operation + .examples( + createExamplesForMembersWithHttpTraits( + operationOrError, + binding, + type, + operation + ) ) - ) - .build(); + .build(); responseBuilder.putContent(mediaType, mediaTypeObject); } @@ -812,35 +812,35 @@ private void createResponsePayload( // MediaTypeObject using the pointer to the existing schema, otherwise add // the synthetic schema and create the MediaTypeObject using a new pointer. private MediaTypeObject getMediaTypeObject( - Context context, - Schema schema, - Shape shape, - Function createSynthesizedName + Context context, + Schema schema, + Shape shape, + Function createSynthesizedName ) { if (!schema.getType().isPresent() && schema.getRef().isPresent()) { return MediaTypeObject.builder() - .schema(Schema.builder().ref(schema.getRef().get()).build()) - .build(); + .schema(Schema.builder().ref(schema.getRef().get()).build()) + .build(); } else { String synthesizedName = createSynthesizedName.apply(shape); String pointer = context.putSynthesizedSchema(synthesizedName, schema); return MediaTypeObject.builder() - .schema(Schema.builder().ref(pointer).build()) - .build(); + .schema(Schema.builder().ref(pointer).build()) + .build(); } } private void createResponseDocumentIfNeeded( - String mediaType, - Context context, - HttpBindingIndex bindingIndex, - ResponseObject.Builder responseBuilder, - Shape operationOrError, - OperationShape operation + String mediaType, + Context context, + HttpBindingIndex bindingIndex, + ResponseObject.Builder responseBuilder, + Shape operationOrError, + OperationShape operation ) { List bindings = bindingIndex.getResponseBindings( - operationOrError, - HttpBinding.Location.DOCUMENT + operationOrError, + HttpBinding.Location.DOCUMENT ); // If the operation doesn't have any document bindings, then do nothing. @@ -851,8 +851,8 @@ private void createResponseDocumentIfNeeded( // Document bindings needs to be synthesized into a new schema that contains // just the document bindings separate from other parameters. MessageType messageType = operationOrError instanceof OperationShape - ? MessageType.RESPONSE - : MessageType.ERROR; + ? MessageType.RESPONSE + : MessageType.ERROR; // This "synthesizes" a new schema that just contains the document bindings. // While we *could* just use the referenced output/error shape as-is, that @@ -879,12 +879,12 @@ private void createResponseDocumentIfNeeded( Schema schema = createDocumentSchema(context, operationOrError, bindings, messageType); String contextName = context.getService().getContextualName(operationOrError); String synthesizedName = stripNonAlphaNumericCharsIfNecessary(context, contextName) - + "ResponseContent"; + + "ResponseContent"; String pointer = context.putSynthesizedSchema(synthesizedName, schema); MediaTypeObject mediaTypeObject = MediaTypeObject.builder() - .schema(Schema.builder().ref(pointer).build()) - .examples(createBodyExamples(operationOrError, bindings, messageType, operation)) - .build(); + .schema(Schema.builder().ref(pointer).build()) + .examples(createBodyExamples(operationOrError, bindings, messageType, operation)) + .build(); responseBuilder.putContent(mediaType, mediaTypeObject); } @@ -893,11 +893,11 @@ private String stripNonAlphaNumericCharsIfNecessary(Context context, String n String alphanumericOnly = NON_ALPHA_NUMERIC.matcher(name).replaceAll(""); if (context.getConfig().getAlphanumericOnlyRefs() && !alphanumericOnly.equals(name)) { LOGGER.info( - () -> String.format( - "Removing non-alphanumeric characters from %s to assure compatibility with" - + " vendors that only allow alphanumeric shape names.", - name - ) + () -> String.format( + "Removing non-alphanumeric characters from %s to assure compatibility with" + + " vendors that only allow alphanumeric shape names.", + name + ) ); return alphanumericOnly; } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/AwsRestJson1Protocol.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/AwsRestJson1Protocol.java index 9984ce0075f..fce482656fe 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/AwsRestJson1Protocol.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/AwsRestJson1Protocol.java @@ -34,20 +34,20 @@ public final class AwsRestJson1Protocol extends AbstractRestProtocol { private static final Set AWS_REQUEST_HEADERS = SetUtils.of( - // Used by clients for a purpose similar to the standard user-agent header. - "X-Amz-User-Agent", - // Used by clients configured to work with X-Ray. - "X-Amzn-Trace-Id", - // Used by clients for adaptive retry behavior. - "Amz-Sdk-Request", - "Amz-Sdk-Invocation-Id" + // Used by clients for a purpose similar to the standard user-agent header. + "X-Amz-User-Agent", + // Used by clients configured to work with X-Ray. + "X-Amzn-Trace-Id", + // Used by clients for adaptive retry behavior. + "Amz-Sdk-Request", + "Amz-Sdk-Invocation-Id" ); private static final Set AWS_RESPONSE_HEADERS = SetUtils.of( - // Used to identify a given request/response, primarily for debugging. - "X-Amzn-Requestid", - // Used to indicate which modeled error a given HTTP error represents. - "X-Amzn-Errortype" + // Used to identify a given request/response, primarily for debugging. + "X-Amzn-Requestid", + // Used to indicate which modeled error a given HTTP error represents. + "X-Amzn-Errortype" ); @Override @@ -88,10 +88,10 @@ String getDocumentMediaType(Context context, Shape operationOrError, MessageType @Override Schema createDocumentSchema( - Context context, - Shape operationOrError, - List bindings, - MessageType message + Context context, + Shape operationOrError, + List bindings, + MessageType message ) { if (bindings.isEmpty()) { return Schema.builder().type("object").build(); @@ -112,8 +112,8 @@ Schema createDocumentSchema( // result in things like "required" properties pointing to members that // don't exist. Set documentMemberNames = bindings.stream() - .map(HttpBinding::getMemberName) - .collect(Collectors.toSet()); + .map(HttpBinding::getMemberName) + .collect(Collectors.toSet()); // Remove non-document members. StructureShape.Builder containerShapeBuilder = containerShape.toBuilder(); @@ -130,14 +130,14 @@ Schema createDocumentSchema( // the error structure to a union, so that a `oneOf` can be used // in the output without added nesting. if (context.getConfig().getOnErrorStatusConflict() != null - && context.getConfig().getOnErrorStatusConflict().equals(ONE_OF) - && targetsSyntheticError(cleanedShape, context)) { + && context.getConfig().getOnErrorStatusConflict().equals(ONE_OF) + && targetsSyntheticError(cleanedShape, context)) { UnionShape.Builder asUnion = UnionShape.builder().id(cleanedShape.getId()); UnionShape targetUnion = context.getModel() - .expectShape( - cleanedShape.getAllMembers().values().stream().findFirst().get().getTarget(), - UnionShape.class - ); + .expectShape( + cleanedShape.getAllMembers().values().stream().findFirst().get().getTarget(), + UnionShape.class + ); for (MemberShape member : targetUnion.getAllMembers().values()) { String name = member.getMemberName(); asUnion.addMember(member.toBuilder().id(cleanedShape.getId().withMember(name)).build()); @@ -160,11 +160,11 @@ private boolean targetsSyntheticError(StructureShape shape, Context context) { private boolean hasSingleUnionMember(StructureShape shape, Model model) { long unionCount = shape.getAllMembers() - .values() - .stream() - .map(member -> model.expectShape(member.getTarget())) - .filter(Shape::isUnionShape) - .count(); + .values() + .stream() + .map(member -> model.expectShape(member.getTarget())) + .filter(Shape::isUnionShape) + .count(); return unionCount == 1; } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/HeaderSchemaVisitor.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/HeaderSchemaVisitor.java index e1871529ce5..b380cd92c86 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/HeaderSchemaVisitor.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/HeaderSchemaVisitor.java @@ -45,14 +45,14 @@ public Schema listShape(ListShape shape) { // Recursively change the items schema and its targets as needed. Schema refSchema = context.inlineOrReferenceSchema(collectionMember); Schema itemsSchema = collectionTarget.accept( - new HeaderSchemaVisitor<>(context, refSchema, collectionMember) + new HeaderSchemaVisitor<>(context, refSchema, collectionMember) ); // Copy the collection schema, remove any $ref, and change the items. return schema.toBuilder() - .ref(null) - .type("array") - .items(itemsSchema) - .build(); + .ref(null) + .type("array") + .items(itemsSchema) + .build(); } // Header timestamps in Smithy use the HTTP-Date format if a @@ -74,7 +74,7 @@ public Schema timestampShape(TimestampShape shape) { public Schema stringShape(StringShape shape) { // String shapes with the mediaType trait must be base64 encoded. return shape.hasTrait(MediaTypeTrait.class) - ? schema.toBuilder().ref(null).type("string").format("byte").build() - : schema; + ? schema.toBuilder().ref(null).type("string").format("byte").build() + : schema; } } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/ModelUtils.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/ModelUtils.java index 475d6767b64..f1f440382f7 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/ModelUtils.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/ModelUtils.java @@ -38,8 +38,8 @@ static ParameterObject.Builder createParameterMember(Context context, MemberShap builder.required(member.isRequired()); builder.name(member.getMemberName()); member.getMemberTrait(context.getModel(), DocumentationTrait.class) - .map(DocumentationTrait::getValue) - .ifPresent(builder::description); + .map(DocumentationTrait::getValue) + .ifPresent(builder::description); return builder; } @@ -53,23 +53,23 @@ static ParameterObject.Builder createParameterMember(Context context, MemberShap */ static Schema.Builder convertSchemaToStringBuilder(Schema schema) { return schema.toBuilder() - .type("string") - .maximum(null) - .minimum(null) - .exclusiveMaximum(null) - .exclusiveMinimum(null) - .multipleOf(null) - .items(null) - .properties(null) - .required(null) - .propertyNames(null) - .oneOf(null) - .anyOf(null) - .not(null) - .ref(null) - .minProperties(null) - .maxProperties(null) - .minItems(null) - .maxItems(null); + .type("string") + .maximum(null) + .minimum(null) + .exclusiveMaximum(null) + .exclusiveMinimum(null) + .multipleOf(null) + .items(null) + .properties(null) + .required(null) + .propertyNames(null) + .oneOf(null) + .anyOf(null) + .not(null) + .ref(null) + .minProperties(null) + .maxProperties(null) + .minItems(null) + .maxItems(null); } } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/QuerySchemaVisitor.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/QuerySchemaVisitor.java index 6228e7f2024..b3e0cff4b5e 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/QuerySchemaVisitor.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/QuerySchemaVisitor.java @@ -43,14 +43,14 @@ public Schema listShape(ListShape shape) { // Recursively change the items schema and its targets as needed. Schema refSchema = context.inlineOrReferenceSchema(collectionMember); Schema itemsSchema = collectionTarget.accept( - new QuerySchemaVisitor<>(context, refSchema, collectionMember) + new QuerySchemaVisitor<>(context, refSchema, collectionMember) ); // Copy the collection schema, remove any $ref, and change the items. return schema.toBuilder() - .ref(null) - .type("array") - .items(itemsSchema) - .build(); + .ref(null) + .type("array") + .items(itemsSchema) + .build(); } // Query string timestamps in Smithy are date-time strings by default @@ -67,7 +67,7 @@ public Schema timestampShape(TimestampShape shape) { // Synthesize a new inline shape that defines an explicit format. Schema originalSchema = context.getJsonSchemaConverter().convertShape(member).getRootSchema(); return ModelUtils.convertSchemaToStringBuilder(originalSchema) - .format("date-time") - .build(); + .format("date-time") + .build(); } } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/AwsV4Converter.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/AwsV4Converter.java index 22f1d577e7c..e4bea9230e7 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/AwsV4Converter.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/AwsV4Converter.java @@ -21,13 +21,13 @@ public final class AwsV4Converter implements SecuritySchemeConverter { private static final String AUTH_HEADER = "Authorization"; private static final Set REQUEST_HEADERS = SetUtils.of( - AUTH_HEADER, - "Date", - "Host", - "X-Amz-Content-Sha256", - "X-Amz-Date", - "X-Amz-Target", - "X-Amz-Security-Token" + AUTH_HEADER, + "Date", + "Host", + "X-Amz-Content-Sha256", + "X-Amz-Date", + "X-Amz-Target", + "X-Amz-Security-Token" ); @Override @@ -38,12 +38,12 @@ public Class getAuthSchemeType() { @Override public SecurityScheme createSecurityScheme(Context context, SigV4Trait trait) { return SecurityScheme.builder() - .type("apiKey") - .description("AWS Signature Version 4 authentication") - .name(AUTH_HEADER) - .in("header") - .putExtension("x-amazon-apigateway-authtype", Node.from("awsSigv4")) - .build(); + .type("apiKey") + .description("AWS Signature Version 4 authentication") + .name(AUTH_HEADER) + .in("header") + .putExtension("x-amazon-apigateway-authtype", Node.from("awsSigv4")) + .build(); } @Override diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpApiKeyAuthConverter.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpApiKeyAuthConverter.java index e36197ac29b..337a3de2d75 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpApiKeyAuthConverter.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpApiKeyAuthConverter.java @@ -30,9 +30,9 @@ public Class getAuthSchemeType() { @Override public SecurityScheme createSecurityScheme(Context context, HttpApiKeyAuthTrait trait) { StringBuilder description = new StringBuilder() - .append("API key authentication via the '") - .append(trait.getName()) - .append("' "); + .append("API key authentication via the '") + .append(trait.getName()) + .append("' "); if (trait.getIn().equals(HttpApiKeyAuthTrait.Location.QUERY)) { description.append(" query string parameter"); @@ -42,20 +42,20 @@ public SecurityScheme createSecurityScheme(Context context, Htt if (trait.getScheme().isPresent()) { return SecurityScheme.builder() - .type("http") - .scheme(trait.getScheme().get()) + .type("http") + .scheme(trait.getScheme().get()) + .name(trait.getName()) + .in(trait.getIn().toString()) + .description(description.toString()) + .build(); + } + + return SecurityScheme.builder() + .type("apiKey") .name(trait.getName()) .in(trait.getIn().toString()) .description(description.toString()) .build(); - } - - return SecurityScheme.builder() - .type("apiKey") - .name(trait.getName()) - .in(trait.getIn().toString()) - .description(description.toString()) - .build(); } @Override diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpBasicConverter.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpBasicConverter.java index 63c56f1369f..a50f890354a 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpBasicConverter.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpBasicConverter.java @@ -24,9 +24,9 @@ public Class getAuthSchemeType() { @Override public SecurityScheme createSecurityScheme(Context context, HttpBasicAuthTrait trait) { return SecurityScheme.builder() - .type("http") - .scheme("Basic") - .description("HTTP Basic authentication") - .build(); + .type("http") + .scheme("Basic") + .description("HTTP Basic authentication") + .build(); } } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpBearerConverter.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpBearerConverter.java index 7f8399a4a7e..6eb69dc3019 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpBearerConverter.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpBearerConverter.java @@ -24,9 +24,9 @@ public Class getAuthSchemeType() { @Override public SecurityScheme createSecurityScheme(Context context, HttpBearerAuthTrait trait) { return SecurityScheme.builder() - .type("http") - .scheme("Bearer") - .description("HTTP Bearer authentication") - .build(); + .type("http") + .scheme("Bearer") + .description("HTTP Bearer authentication") + .build(); } } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpDigestConverter.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpDigestConverter.java index bf456ac3f56..0468fc5191a 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpDigestConverter.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/security/HttpDigestConverter.java @@ -24,9 +24,9 @@ public Class getAuthSchemeType() { @Override public SecurityScheme createSecurityScheme(Context context, HttpDigestAuthTrait trait) { return SecurityScheme.builder() - .type("http") - .scheme("Digest") - .description("HTTP Digest authentication") - .build(); + .type("http") + .scheme("Digest") + .description("HTTP Digest authentication") + .build(); } } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ComponentsObject.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ComponentsObject.java index aec1c803aaf..408bf0b13f6 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ComponentsObject.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ComponentsObject.java @@ -75,73 +75,73 @@ protected ObjectNode.Builder createNodeBuilder() { if (!schemas.isEmpty()) { builder.withMember( - "schemas", - schemas.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "schemas", + schemas.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } if (!responses.isEmpty()) { builder.withMember( - "responses", - responses.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "responses", + responses.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } if (!parameters.isEmpty()) { builder.withMember( - "parameters", - parameters.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "parameters", + parameters.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } if (!requestBodies.isEmpty()) { builder.withMember( - "requestBodies", - requestBodies.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "requestBodies", + requestBodies.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } if (!headers.isEmpty()) { builder.withMember( - "headers", - headers.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "headers", + headers.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } if (!securitySchemes.isEmpty()) { builder.withMember( - "securitySchemes", - securitySchemes.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "securitySchemes", + securitySchemes.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } if (!links.isEmpty()) { builder.withMember( - "links", - links.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "links", + links.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } if (!callbacks.isEmpty()) { builder.withMember( - "callbacks", - callbacks.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "callbacks", + callbacks.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } @@ -151,15 +151,15 @@ protected ObjectNode.Builder createNodeBuilder() { @Override public Builder toBuilder() { return builder() - .schemas(schemas) - .responses(responses) - .parameters(parameters) - .requestBodies(requestBodies) - .headers(headers) - .securitySchemes(securitySchemes) - .links(links) - .callbacks(callbacks) - .extensions(getExtensions()); + .schemas(schemas) + .responses(responses) + .parameters(parameters) + .requestBodies(requestBodies) + .headers(headers) + .securitySchemes(securitySchemes) + .links(links) + .callbacks(callbacks) + .extensions(getExtensions()); } public static final class Builder extends Component.Builder { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/EncodingObject.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/EncodingObject.java index 07a74471092..371a6324fb4 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/EncodingObject.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/EncodingObject.java @@ -54,15 +54,15 @@ public boolean isAllowReserved() { @Override protected ObjectNode.Builder createNodeBuilder() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withOptionalMember("contentType", getContentType().map(Node::from)) - .withOptionalMember("style", getStyle().map(Node::from)); + .withOptionalMember("contentType", getContentType().map(Node::from)) + .withOptionalMember("style", getStyle().map(Node::from)); if (!headers.isEmpty()) { builder.withMember( - "headers", - headers.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "headers", + headers.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } @@ -80,12 +80,12 @@ protected ObjectNode.Builder createNodeBuilder() { @Override public Builder toBuilder() { return builder() - .extensions(getExtensions()) - .headers(headers) - .contentType(contentType) - .style(style) - .explode(explode) - .allowReserved(allowReserved); + .extensions(getExtensions()) + .headers(headers) + .contentType(contentType) + .style(style) + .explode(explode) + .allowReserved(allowReserved); } public static final class Builder extends Component.Builder { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ExampleObject.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ExampleObject.java index 04b4a2c3249..d71da77e35d 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ExampleObject.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ExampleObject.java @@ -48,20 +48,20 @@ public Optional getExternalValue() { @Override public Builder toBuilder() { return builder() - .extensions(getExtensions()) - .summary(summary) - .description(description) - .value(value) - .externalValue(externalValue); + .extensions(getExtensions()) + .summary(summary) + .description(description) + .value(value) + .externalValue(externalValue); } @Override protected ObjectNode.Builder createNodeBuilder() { return Node.objectNodeBuilder() - .withOptionalMember("summary", getSummary().map(Node::from)) - .withOptionalMember("description", getDescription().map(Node::from)) - .withOptionalMember("value", getValue().map(Node::from)) - .withOptionalMember("externalValue", getExternalValue().map(Node::from)); + .withOptionalMember("summary", getSummary().map(Node::from)) + .withOptionalMember("description", getDescription().map(Node::from)) + .withOptionalMember("value", getValue().map(Node::from)) + .withOptionalMember("externalValue", getExternalValue().map(Node::from)); } public static ExampleObject fromNode(Node exampleObject) { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ExternalDocumentation.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ExternalDocumentation.java index 99fdef7ec8b..b0df6b2e78c 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ExternalDocumentation.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ExternalDocumentation.java @@ -12,10 +12,10 @@ import software.amazon.smithy.utils.ToSmithyBuilder; public final class ExternalDocumentation extends Component - implements ToSmithyBuilder, Comparable { + implements ToSmithyBuilder, Comparable { private static final Comparator STRING_COMPARATOR = Comparator - .nullsFirst(String::compareTo); + .nullsFirst(String::compareTo); private final String description; private final String url; @@ -41,23 +41,23 @@ public String getUrl() { @Override public Builder toBuilder() { return builder() - .extensions(getExtensions()) - .description(description) - .url(url); + .extensions(getExtensions()) + .description(description) + .url(url); } @Override protected ObjectNode.Builder createNodeBuilder() { return Node.objectNodeBuilder() - .withOptionalMember("description", getDescription().map(Node::from)) - .withMember("url", url); + .withOptionalMember("description", getDescription().map(Node::from)) + .withMember("url", url); } @Override public int compareTo(ExternalDocumentation that) { return Comparator.comparing(ExternalDocumentation::getUrl, STRING_COMPARATOR) - .thenComparing(ed -> ed.description, STRING_COMPARATOR) - .compare(this, that); + .thenComparing(ed -> ed.description, STRING_COMPARATOR) + .compare(this, that); } public static final class Builder extends Component.Builder { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/InfoObject.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/InfoObject.java index 2da307897e4..b93cbe86fbf 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/InfoObject.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/InfoObject.java @@ -59,24 +59,24 @@ public Optional getContact() { @Override public Builder toBuilder() { return builder() - .extensions(getExtensions()) - .title(title) - .version(version) - .description(description) - .termsOfService(termsOfService) - .license(license) - .contact(contact); + .extensions(getExtensions()) + .title(title) + .version(version) + .description(description) + .termsOfService(termsOfService) + .license(license) + .contact(contact); } @Override protected ObjectNode.Builder createNodeBuilder() { return Node.objectNodeBuilder() - .withMember("title", getTitle()) - .withMember("version", getVersion()) - .withOptionalMember("termsOfService", getTermsOfService().map(Node::from)) - .withOptionalMember("description", getDescription().map(Node::from)) - .withOptionalMember("license", getLicense()) - .withOptionalMember("contact", getContact()); + .withMember("title", getTitle()) + .withMember("version", getVersion()) + .withOptionalMember("termsOfService", getTermsOfService().map(Node::from)) + .withOptionalMember("description", getDescription().map(Node::from)) + .withOptionalMember("license", getLicense()) + .withOptionalMember("contact", getContact()); } public static final class Builder extends Component.Builder { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/LinkObject.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/LinkObject.java index bd86794511e..3e3bc1158b3 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/LinkObject.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/LinkObject.java @@ -60,18 +60,18 @@ public Optional getServer() { @Override protected ObjectNode.Builder createNodeBuilder() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withOptionalMember("operationRef", getOperationRef().map(Node::from)) - .withOptionalMember("operationId", getOperationId().map(Node::from)) - .withOptionalMember("requestBody", getRequestBody()) - .withOptionalMember("description", getDescription().map(Node::from)) - .withOptionalMember("server", getServer()); + .withOptionalMember("operationRef", getOperationRef().map(Node::from)) + .withOptionalMember("operationId", getOperationId().map(Node::from)) + .withOptionalMember("requestBody", getRequestBody()) + .withOptionalMember("description", getDescription().map(Node::from)) + .withOptionalMember("server", getServer()); if (!parameters.isEmpty()) { builder.withMember( - "parameters", - parameters.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "parameters", + parameters.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } @@ -81,13 +81,13 @@ protected ObjectNode.Builder createNodeBuilder() { @Override public Builder toBuilder() { return builder() - .extensions(getExtensions()) - .parameters(parameters) - .operationId(operationId) - .operationRef(operationRef) - .requestBody(requestBody) - .description(description) - .server(server); + .extensions(getExtensions()) + .parameters(parameters) + .operationId(operationId) + .operationRef(operationRef) + .requestBody(requestBody) + .description(description) + .server(server); } public static final class Builder extends Component.Builder { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/MediaTypeObject.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/MediaTypeObject.java index d596bdadd1b..f72fb743871 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/MediaTypeObject.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/MediaTypeObject.java @@ -49,24 +49,24 @@ public Map getEncoding() { @Override protected ObjectNode.Builder createNodeBuilder() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withOptionalMember("schema", getSchema()) - .withOptionalMember("example", getExample()); + .withOptionalMember("schema", getSchema()) + .withOptionalMember("example", getExample()); if (!examples.isEmpty()) { builder.withMember( - "examples", - examples.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "examples", + examples.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } if (!encoding.isEmpty()) { builder.withMember( - "encoding", - encoding.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "encoding", + encoding.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } @@ -76,10 +76,10 @@ protected ObjectNode.Builder createNodeBuilder() { @Override public Builder toBuilder() { Builder builder = builder() - .extensions(getExtensions()) - .schema(schema) - .example(example == null ? null : example.toNode()) - .encoding(encoding); + .extensions(getExtensions()) + .schema(schema) + .example(example == null ? null : example.toNode()) + .encoding(encoding); for (Map.Entry ex : examples.entrySet()) { builder.putExample(ex.getKey(), ex.getValue()); diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/OpenApi.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/OpenApi.java index a3b25461505..e293d65996b 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/OpenApi.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/OpenApi.java @@ -81,12 +81,12 @@ public Optional getExternalDocs() { @Override public Builder toBuilder() { Builder builder = builder() - .openapi(openapi) - .info(info) - .paths(paths) - .components(components) - .externalDocs(externalDocs) - .extensions(getExtensions()); + .openapi(openapi) + .info(info) + .paths(paths) + .components(components) + .externalDocs(externalDocs) + .extensions(getExtensions()); security.forEach(builder::addSecurity); servers.forEach(builder::addServer); tags.forEach(builder::addTag); @@ -96,9 +96,9 @@ public Builder toBuilder() { @Override protected ObjectNode.Builder createNodeBuilder() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withMember("openapi", openapi) - .withMember("info", info) - .withOptionalMember("externalDocumentation", getExternalDocs()); + .withMember("openapi", openapi) + .withMember("info", info) + .withOptionalMember("externalDocumentation", getExternalDocs()); if (!servers.isEmpty()) { builder.withMember("servers", servers.stream().collect(ArrayNode.collect())); @@ -106,10 +106,10 @@ protected ObjectNode.Builder createNodeBuilder() { if (!paths.isEmpty()) { builder.withMember( - "paths", - paths.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "paths", + paths.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } @@ -117,20 +117,23 @@ protected ObjectNode.Builder createNodeBuilder() { if (!security.isEmpty()) { builder.withMember( - "security", - security.stream() - .map( - mapping -> mapping.entrySet() - .stream() - .sorted(Comparator.comparing(Map.Entry::getKey)) - .collect( - ObjectNode.collectStringKeys( - Map.Entry::getKey, - entry -> entry.getValue().stream().map(Node::from).collect(ArrayNode.collect()) - ) + "security", + security.stream() + .map( + mapping -> mapping.entrySet() + .stream() + .sorted(Comparator.comparing(Map.Entry::getKey)) + .collect( + ObjectNode.collectStringKeys( + Map.Entry::getKey, + entry -> entry.getValue() + .stream() + .map(Node::from) + .collect(ArrayNode.collect()) + ) + ) ) - ) - .collect(ArrayNode.collect()) + .collect(ArrayNode.collect()) ); } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/OperationObject.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/OperationObject.java index 9e362236cfc..018246dd78d 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/OperationObject.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/OperationObject.java @@ -110,11 +110,11 @@ public List getServers() { @Override protected ObjectNode.Builder createNodeBuilder() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withOptionalMember("description", getDescription().map(Node::from)) - .withOptionalMember("summary", getSummary().map(Node::from)) - .withOptionalMember("externalDocs", getExternalDocs()) - .withOptionalMember("operationId", getOperationId().map(Node::from)) - .withOptionalMember("requestBody", getRequestBody()); + .withOptionalMember("description", getDescription().map(Node::from)) + .withOptionalMember("summary", getSummary().map(Node::from)) + .withOptionalMember("externalDocs", getExternalDocs()) + .withOptionalMember("operationId", getOperationId().map(Node::from)) + .withOptionalMember("requestBody", getRequestBody()); if (isDeprecated()) { builder.withMember("deprecated", Node.from(true)); @@ -126,52 +126,52 @@ protected ObjectNode.Builder createNodeBuilder() { if (!responses.isEmpty()) { builder.withMember( - "responses", - getResponses().entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "responses", + getResponses().entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } if (!callbacks.isEmpty()) { builder.withMember( - "callbacks", - getCallbacks().entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "callbacks", + getCallbacks().entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } if (getSecurity().isPresent()) { builder.withMember( - "security", - getSecurity().get() - .stream() - .map( - map -> map.entrySet() + "security", + getSecurity().get() .stream() - .sorted(Comparator.comparing(Map.Entry::getKey)) .map( - entry -> Pair.of( - entry.getKey(), - entry.getValue() - .stream() - .map(Node::from) - .collect(ArrayNode.collect()) - ) + map -> map.entrySet() + .stream() + .sorted(Comparator.comparing(Map.Entry::getKey)) + .map( + entry -> Pair.of( + entry.getKey(), + entry.getValue() + .stream() + .map(Node::from) + .collect(ArrayNode.collect()) + ) + ) + .collect(ObjectNode.collectStringKeys(Pair::getLeft, Pair::getRight)) ) - .collect(ObjectNode.collectStringKeys(Pair::getLeft, Pair::getRight)) - ) - .collect(ArrayNode.collect()) + .collect(ArrayNode.collect()) ); } if (!servers.isEmpty()) { builder.withMember( - "servers", - getServers().stream() - .map(ServerObject::toNode) - .collect(ArrayNode.collect()) + "servers", + getServers().stream() + .map(ServerObject::toNode) + .collect(ArrayNode.collect()) ); } @@ -185,18 +185,18 @@ protected ObjectNode.Builder createNodeBuilder() { @Override public Builder toBuilder() { Builder builder = builder() - .extensions(getExtensions()) - .callbacks(callbacks) - .responses(responses) - .parameters(parameters) - .servers(servers) - .summary(summary) - .tags(tags) - .deprecated(deprecated) - .description(description) - .externalDocs(externalDocs) - .operationId(operationId) - .requestBody(requestBody); + .extensions(getExtensions()) + .callbacks(callbacks) + .responses(responses) + .parameters(parameters) + .servers(servers) + .summary(summary) + .tags(tags) + .deprecated(deprecated) + .description(description) + .externalDocs(externalDocs) + .operationId(operationId) + .requestBody(requestBody); getSecurity().ifPresent(builder::security); return builder; } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ParameterObject.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ParameterObject.java index d586ed542b2..37520def543 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ParameterObject.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ParameterObject.java @@ -104,12 +104,12 @@ public Optional getExample() { @Override protected ObjectNode.Builder createNodeBuilder() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withOptionalMember("name", getName().map(Node::from)) - .withOptionalMember("in", getIn().map(Node::from)) - .withOptionalMember("description", getDescription().map(Node::from)) - .withOptionalMember("style", getStyle().map(Node::from)) - .withOptionalMember("schema", getSchema()) - .withOptionalMember("example", getExample()); + .withOptionalMember("name", getName().map(Node::from)) + .withOptionalMember("in", getIn().map(Node::from)) + .withOptionalMember("description", getDescription().map(Node::from)) + .withOptionalMember("style", getStyle().map(Node::from)) + .withOptionalMember("schema", getSchema()) + .withOptionalMember("example", getExample()); if (isDeprecated()) { builder.withMember("deprecated", Node.from(true)); @@ -133,19 +133,19 @@ protected ObjectNode.Builder createNodeBuilder() { if (!examples.isEmpty()) { builder.withMember( - "examples", - getExamples().entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "examples", + getExamples().entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } if (!content.isEmpty()) { builder.withMember( - "content", - getContent().entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "content", + getContent().entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } @@ -155,19 +155,19 @@ protected ObjectNode.Builder createNodeBuilder() { @Override public Builder toBuilder() { Builder builder = builder() - .extensions(getExtensions()) - .name(name) - .in(in) - .description(description) - .required(required) - .deprecated(deprecated) - .allowEmptyValue(allowEmptyValue) - .style(style) - .explode(explode) - .allowReserved(allowReserved) - .schema(schema) - .example(example == null ? null : example.toNode()) - .content(content); + .extensions(getExtensions()) + .name(name) + .in(in) + .description(description) + .required(required) + .deprecated(deprecated) + .allowEmptyValue(allowEmptyValue) + .style(style) + .explode(explode) + .allowReserved(allowReserved) + .schema(schema) + .example(example == null ? null : example.toNode()) + .content(content); for (Map.Entry ex : examples.entrySet()) { builder.putExample(ex.getKey(), ex.getValue().toNode()); diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/PathItem.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/PathItem.java index 4dfa8b247d7..eb290c0683e 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/PathItem.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/PathItem.java @@ -118,16 +118,16 @@ public Stream operations() { @Override protected ObjectNode.Builder createNodeBuilder() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withOptionalMember("description", getDescription().map(Node::from)) - .withOptionalMember("summary", getSummary().map(Node::from)) - .withOptionalMember("delete", getDelete()) - .withOptionalMember("get", getGet()) - .withOptionalMember("head", getHead()) - .withOptionalMember("options", getOptions()) - .withOptionalMember("patch", getPatch()) - .withOptionalMember("post", getPost()) - .withOptionalMember("put", getPut()) - .withOptionalMember("trace", getTrace()); + .withOptionalMember("description", getDescription().map(Node::from)) + .withOptionalMember("summary", getSummary().map(Node::from)) + .withOptionalMember("delete", getDelete()) + .withOptionalMember("get", getGet()) + .withOptionalMember("head", getHead()) + .withOptionalMember("options", getOptions()) + .withOptionalMember("patch", getPatch()) + .withOptionalMember("post", getPost()) + .withOptionalMember("put", getPut()) + .withOptionalMember("trace", getTrace()); if (!parameters.isEmpty()) { builder.withMember("parameters", getParameters().stream().map(Ref::toNode).collect(ArrayNode.collect())); @@ -135,10 +135,10 @@ protected ObjectNode.Builder createNodeBuilder() { if (!servers.isEmpty()) { builder.withMember( - "servers", - getServers().stream() - .map(ServerObject::toNode) - .collect(ArrayNode.collect()) + "servers", + getServers().stream() + .map(ServerObject::toNode) + .collect(ArrayNode.collect()) ); } @@ -148,19 +148,19 @@ protected ObjectNode.Builder createNodeBuilder() { @Override public Builder toBuilder() { return builder() - .extensions(getExtensions()) - .summary(summary) - .description(description) - .servers(servers) - .parameters(parameters) - .get(get) - .put(put) - .post(post) - .delete(delete) - .options(options) - .head(head) - .patch(patch) - .trace(trace); + .extensions(getExtensions()) + .summary(summary) + .description(description) + .servers(servers) + .parameters(parameters) + .get(get) + .put(put) + .post(post) + .delete(delete) + .options(options) + .head(head) + .patch(patch) + .trace(trace); } public static final class Builder extends Component.Builder { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/RemoteRef.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/RemoteRef.java index 9f57fc75355..d822edf7f71 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/RemoteRef.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/RemoteRef.java @@ -28,11 +28,11 @@ public T deref(ComponentsObject components) { if (!paths[0].equals("components")) { throw new OpenApiException( - "Cannot deref a path that does not start with components: " + pointer + "Cannot deref a path that does not start with components: " + pointer ); } else if (paths.length != 2) { throw new OpenApiException( - "Cannot deref a path that does not have exactly two segments: " + pointer + "Cannot deref a path that does not have exactly two segments: " + pointer ); } @@ -74,12 +74,12 @@ public T deref(ComponentsObject components) { return (T) result; } catch (ClassCastException e) { throw new OpenApiException( - String.format( - "$ref pointer `%s` pointer to a value of an unexpected type, %s: %s", - pointer, - result.getClass().getName(), - result - ) + String.format( + "$ref pointer `%s` pointer to a value of an unexpected type, %s: %s", + pointer, + result.getClass().getName(), + result + ) ); } } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/RequestBodyObject.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/RequestBodyObject.java index 1eb5c0dc988..6649f00557c 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/RequestBodyObject.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/RequestBodyObject.java @@ -42,13 +42,13 @@ public boolean isRequired() { @Override protected ObjectNode.Builder createNodeBuilder() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withOptionalMember("description", getDescription().map(Node::from)) - .withMember( - "content", - content.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) - ); + .withOptionalMember("description", getDescription().map(Node::from)) + .withMember( + "content", + content.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + ); if (required) { builder.withMember("required", Node.from(true)); @@ -60,10 +60,10 @@ protected ObjectNode.Builder createNodeBuilder() { @Override public Builder toBuilder() { return builder() - .extensions(getExtensions()) - .description(description) - .content(content) - .required(required); + .extensions(getExtensions()) + .description(description) + .content(content) + .required(required); } public static final class Builder extends Component.Builder { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ResponseObject.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ResponseObject.java index 41dbdc65b4e..18b6d88b9a5 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ResponseObject.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ResponseObject.java @@ -66,32 +66,32 @@ public Map> getLinks() { @Override protected ObjectNode.Builder createNodeBuilder() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withMember("description", description); + .withMember("description", description); if (!headers.isEmpty()) { builder.withMember( - "headers", - headers.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "headers", + headers.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } if (!content.isEmpty()) { builder.withMember( - "content", - content.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "content", + content.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } if (!links.isEmpty()) { builder.withMember( - "links", - links.entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "links", + links.entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } @@ -101,11 +101,11 @@ protected ObjectNode.Builder createNodeBuilder() { @Override public Builder toBuilder() { return builder() - .extensions(getExtensions()) - .description(description) - .headers(headers) - .content(content) - .links(links); + .extensions(getExtensions()) + .description(description) + .headers(headers) + .content(content) + .links(links); } public static final class Builder extends Component.Builder { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/SecurityScheme.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/SecurityScheme.java index 1c87c0b2b55..dc293de04a9 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/SecurityScheme.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/SecurityScheme.java @@ -71,27 +71,27 @@ public Optional getFlows() { @Override public Builder toBuilder() { return builder() - .extensions(getExtensions()) - .type(type) - .description(description) - .name(name) - .in(in) - .scheme(scheme) - .bearerFormat(bearerFormat) - .openIdConnectUrl(openIdConnectUrl) - .flows(flows); + .extensions(getExtensions()) + .type(type) + .description(description) + .name(name) + .in(in) + .scheme(scheme) + .bearerFormat(bearerFormat) + .openIdConnectUrl(openIdConnectUrl) + .flows(flows); } protected ObjectNode.Builder createNodeBuilder() { return Node.objectNodeBuilder() - .withMember("type", type) - .withOptionalMember("description", getDescription().map(Node::from)) - .withOptionalMember("name", getName().map(Node::from)) - .withOptionalMember("in", getIn().map(Node::from)) - .withOptionalMember("scheme", getScheme().map(Node::from)) - .withOptionalMember("bearerFormat", getBearerFormat().map(Node::from)) - .withOptionalMember("openIdConnectUrl", getOpenIdConnectUrl().map(Node::from)) - .withOptionalMember("flows", getFlows()); + .withMember("type", type) + .withOptionalMember("description", getDescription().map(Node::from)) + .withOptionalMember("name", getName().map(Node::from)) + .withOptionalMember("in", getIn().map(Node::from)) + .withOptionalMember("scheme", getScheme().map(Node::from)) + .withOptionalMember("bearerFormat", getBearerFormat().map(Node::from)) + .withOptionalMember("openIdConnectUrl", getOpenIdConnectUrl().map(Node::from)) + .withOptionalMember("flows", getFlows()); } public static final class Builder extends Component.Builder { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ServerObject.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ServerObject.java index 5528a3355a7..064c19a1af7 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ServerObject.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/ServerObject.java @@ -47,24 +47,24 @@ public Map getVariables() { @Override public Builder toBuilder() { return builder() - .extensions(getExtensions()) - .url(url) - .description(description) - .variables(variables); + .extensions(getExtensions()) + .url(url) + .description(description) + .variables(variables); } @Override protected ObjectNode.Builder createNodeBuilder() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withMember("url", getUrl()) - .withOptionalMember("description", getDescription().map(Node::from)); + .withMember("url", getUrl()) + .withOptionalMember("description", getDescription().map(Node::from)); if (!variables.isEmpty()) { builder.withMember( - "variables", - getVariables().entrySet() - .stream() - .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) + "variables", + getVariables().entrySet() + .stream() + .collect(ObjectNode.collectStringKeys(Map.Entry::getKey, Map.Entry::getValue)) ); } diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/TagObject.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/TagObject.java index a20c29fd306..3a7b42451c4 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/TagObject.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/TagObject.java @@ -13,10 +13,10 @@ public final class TagObject extends Component implements ToSmithyBuilder, Comparable { private static final Comparator STRING_COMPARATOR = Comparator - .nullsFirst(String::compareToIgnoreCase); + .nullsFirst(String::compareToIgnoreCase); private static final Comparator EXTERNAL_DOCUMENTATION_COMPARATOR = Comparator - .nullsFirst(ExternalDocumentation::compareTo); + .nullsFirst(ExternalDocumentation::compareTo); private final String name; private final String description; @@ -48,26 +48,26 @@ public Optional getDescription() { @Override public Builder toBuilder() { return builder() - .extensions(getExtensions()) - .name(name) - .description(description) - .externalDocs(externalDocs); + .extensions(getExtensions()) + .name(name) + .description(description) + .externalDocs(externalDocs); } @Override protected ObjectNode.Builder createNodeBuilder() { return Node.objectNodeBuilder() - .withMember("name", Node.from(getName())) - .withOptionalMember("description", getDescription().map(Node::from)) - .withOptionalMember("externalDocs", getExternalDocs().map(ExternalDocumentation::toNode)); + .withMember("name", Node.from(getName())) + .withOptionalMember("description", getDescription().map(Node::from)) + .withOptionalMember("externalDocs", getExternalDocs().map(ExternalDocumentation::toNode)); } @Override public int compareTo(TagObject that) { return Comparator.comparing(TagObject::getName, STRING_COMPARATOR) - .thenComparing(to -> to.description, STRING_COMPARATOR) - .thenComparing(to -> to.externalDocs, EXTERNAL_DOCUMENTATION_COMPARATOR) - .compare(this, that); + .thenComparing(to -> to.description, STRING_COMPARATOR) + .thenComparing(to -> to.externalDocs, EXTERNAL_DOCUMENTATION_COMPARATOR) + .compare(this, that); } public static final class Builder extends Component.Builder { diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/XmlObject.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/XmlObject.java index 38e9c8b59ba..ced78d0b0fe 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/XmlObject.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/XmlObject.java @@ -52,9 +52,9 @@ public boolean isWrapped() { @Override protected ObjectNode.Builder createNodeBuilder() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withOptionalMember("name", getName().map(Node::from)) - .withOptionalMember("namespace", getNamespace().map(Node::from)) - .withOptionalMember("prefix", getPrefix().map(Node::from)); + .withOptionalMember("name", getName().map(Node::from)) + .withOptionalMember("namespace", getNamespace().map(Node::from)) + .withOptionalMember("prefix", getPrefix().map(Node::from)); if (isWrapped()) { builder.withMember("wrapped", Node.from(true)); @@ -70,12 +70,12 @@ protected ObjectNode.Builder createNodeBuilder() { @Override public Builder toBuilder() { return builder() - .extensions(getExtensions()) - .name(name) - .namespace(namespace) - .prefix(prefix) - .attribute(attribute) - .wrapped(wrapped); + .extensions(getExtensions()) + .name(name) + .namespace(namespace) + .prefix(prefix) + .attribute(attribute) + .wrapped(wrapped); } public static final class Builder extends Component.Builder { diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConfigTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConfigTest.java index c905fb56e37..63aff35a096 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConfigTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConfigTest.java @@ -43,8 +43,8 @@ public void throwsOnOpenApiUseProperties() { @Test public void convertsExplicitlyMappedProperties() { Node mappedTest = Node.objectNode() - .withMember("openapi.tags", Node.from(true)) - .withMember("openapi.ignoreUnsupportedTraits", Node.from(true)); + .withMember("openapi.tags", Node.from(true)) + .withMember("openapi.ignoreUnsupportedTraits", Node.from(true)); OpenApiConfig config = OpenApiConfig.fromNode(mappedTest); assertThat(config.getTags(), equalTo(true)); @@ -54,8 +54,8 @@ public void convertsExplicitlyMappedProperties() { @Test public void putsAdditionalPropertiesInExtensions() { Node mappedTest = Node.objectNode() - .withMember("tags", true) - .withMember("apiGatewayType", "REST"); + .withMember("tags", true) + .withMember("apiGatewayType", "REST"); OpenApiConfig config = OpenApiConfig.fromNode(mappedTest); assertThat(config.getTags(), equalTo(true)); diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConverterTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConverterTest.java index f488ec46060..1e06bd47335 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConverterTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConverterTest.java @@ -42,10 +42,10 @@ public class OpenApiConverterTest { @BeforeAll private static void setup() { testService = Model.assembler() - .addImport(OpenApiConverterTest.class.getResource("test-service.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(OpenApiConverterTest.class.getResource("test-service.json")) + .discoverModels() + .assemble() + .unwrap(); } @Test @@ -53,12 +53,12 @@ public void convertsModelsToOpenApi() { OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.rest#RestService")); ObjectNode result = OpenApiConverter.create() - .config(config) - .convertToNode(testService); + .config(config) + .convertToNode(testService); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("test-service.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("test-service.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -67,20 +67,20 @@ public void convertsModelsToOpenApi() { @Test public void passesThroughAllTags() { Model model = Model.assembler() - .addImport(getClass().getResource("tagged-service.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("tagged-service.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); config.setTags(true); OpenApi result = OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("tagged-service-all-tags.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("tagged-service-all-tags.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -89,21 +89,21 @@ public void passesThroughAllTags() { @Test public void passesThroughSupportedTags() { Model model = Model.assembler() - .addImport(getClass().getResource("tagged-service.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("tagged-service.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); config.setTags(true); config.setSupportedTags(ListUtils.of("baz", "foo")); OpenApi result = OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("tagged-service-supported-tags.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("tagged-service-supported-tags.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -112,21 +112,21 @@ public void passesThroughSupportedTags() { @Test public void doesNotPassThroughTagsWithEmptySupportedTagList() { Model model = Model.assembler() - .addImport(getClass().getResource("tagged-service.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("tagged-service.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); config.setTags(true); config.setSupportedTags(ListUtils.of()); OpenApi result = OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("tagged-service-empty-supported-tags.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("tagged-service-empty-supported-tags.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -135,20 +135,20 @@ public void doesNotPassThroughTagsWithEmptySupportedTagList() { @Test public void preservesUserSpecifiedOrderOfTags() { Model model = Model.assembler() - .addImport(getClass().getResource("tagged-service-order.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("tagged-service-order.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); config.setTags(true); OpenApi result = OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("tagged-service-order.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("tagged-service-order.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -157,21 +157,21 @@ public void preservesUserSpecifiedOrderOfTags() { @Test public void preservesUserSpecifiedOrderOfTagsWhenFilteringSupportedTags() { Model model = Model.assembler() - .addImport(getClass().getResource("tagged-service-order.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("tagged-service-order.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); config.setTags(true); config.setSupportedTags(ListUtils.of("one", "two", "three", "four")); OpenApi result = OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("tagged-service-order-supported-tags.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("tagged-service-order-supported-tags.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -183,12 +183,12 @@ public void usesOpenApiIntegers() { config.setService(ShapeId.from("example.rest#RestService")); config.setUseIntegerType(true); ObjectNode result = OpenApiConverter.create() - .config(config) - .convertToNode(testService); + .config(config) + .convertToNode(testService); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("test-service-integer.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("test-service-integer.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -198,15 +198,15 @@ public void usesOpenApiIntegers() { public void requiresProtocolsTrait() { Exception thrown = Assertions.assertThrows(OpenApiException.class, () -> { Model model = Model.assembler() - .addImport(getClass().getResource("missing-protocols-trait.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("missing-protocols-trait.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); }); assertThat(thrown.getMessage(), containsString("does not define any protocols")); @@ -216,15 +216,15 @@ public void requiresProtocolsTrait() { public void mustBeAbleToResolveProtocolServiceProvider() { Exception thrown = Assertions.assertThrows(OpenApiException.class, () -> { Model model = Model.assembler() - .addImport(getClass().getResource("unable-to-resolve-protocol.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("unable-to-resolve-protocol.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); }); assertThat(thrown.getMessage(), containsString("Unable to find an OpenAPI service provider")); @@ -236,12 +236,12 @@ public void loadsProtocolFromConfiguration() { config.setService(ShapeId.from("example.rest#RestService")); config.setProtocol(ShapeId.from("aws.protocols#restJson1")); ObjectNode result = OpenApiConverter.create() - .config(config) - .convertToNode(testService); + .config(config) + .convertToNode(testService); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("test-service.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("test-service.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -251,15 +251,15 @@ public void loadsProtocolFromConfiguration() { public void failsToDeriveFromMultipleProtocols() { Exception thrown = Assertions.assertThrows(OpenApiException.class, () -> { Model model = Model.assembler() - .addImport(getClass().getResource("service-with-multiple-protocols.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("service-with-multiple-protocols.smithy")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); }); assertThat(thrown.getMessage(), containsString("defines multiple protocols")); @@ -272,8 +272,8 @@ public void failsWhenConfiguredProtocolIsNoFound() { config.setService(ShapeId.from("example.rest#RestService")); config.setProtocol(ShapeId.from("aws.protocols#restJson99")); OpenApiConverter.create() - .config(config) - .convertToNode(testService); + .config(config) + .convertToNode(testService); }); assertThat(thrown.getMessage(), containsString("Unable to find protocol")); @@ -282,17 +282,17 @@ public void failsWhenConfiguredProtocolIsNoFound() { @Test public void omitsUnsupportedHttpMethods() { Model model = Model.assembler() - .addImport(getClass().getResource("unsupported-http-method.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("unsupported-http-method.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create().config(config).convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("unsupported-http-method.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("unsupported-http-method.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -301,15 +301,15 @@ public void omitsUnsupportedHttpMethods() { @Test public void protocolsCanOmitOperations() { Model model = Model.assembler() - .addImport(getClass().getResource("missing-http-bindings.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("missing-http-bindings.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); for (PathItem pathItem : result.getPaths().values()) { assertFalse(pathItem.getGet().isPresent()); @@ -326,10 +326,10 @@ public void protocolsCanOmitOperations() { @Test public void addsEmptyResponseByDefault() { Model model = Model.assembler() - .addImport(getClass().getResource("adds-empty-response.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("adds-empty-response.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create().config(config).convert(model); @@ -340,17 +340,17 @@ public void addsEmptyResponseByDefault() { @Test public void addsMixedSecurityService() { Model model = Model.assembler() - .addImport(getClass().getResource("mixed-security-service.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("mixed-security-service.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create().config(config).convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("mixed-security-service.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("mixed-security-service.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -359,10 +359,10 @@ public void addsMixedSecurityService() { private static final class NullSecurity implements OpenApiMapper { @Override public Map> updateSecurity( - Context context, - Shape shape, - SecuritySchemeConverter converter, - Map> requirement + Context context, + Shape shape, + SecuritySchemeConverter converter, + Map> requirement ) { return null; } @@ -371,16 +371,16 @@ public Map> updateSecurity( @Test public void canOmitSecurityRequirements() { Model model = Model.assembler() - .addImport(getClass().getResource("mixed-security-service.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("mixed-security-service.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create() - .addOpenApiMapper(new NullSecurity()) - .config(config) - .convert(model); + .addOpenApiMapper(new NullSecurity()) + .config(config) + .convert(model); assertThat(result.getSecurity(), empty()); assertThat(result.getPaths().get("/2").getGet().get().getSecurity().orElse(Collections.emptyList()), empty()); @@ -389,10 +389,10 @@ public void canOmitSecurityRequirements() { private static final class ConstantSecurity implements OpenApiMapper { @Override public Map> updateSecurity( - Context context, - Shape shape, - SecuritySchemeConverter converter, - Map> requirement + Context context, + Shape shape, + SecuritySchemeConverter converter, + Map> requirement ) { return MapUtils.of("foo_baz", ListUtils.of()); } @@ -401,16 +401,16 @@ public Map> updateSecurity( @Test public void canChangeSecurityRequirementName() { Model model = Model.assembler() - .addImport(getClass().getResource("mixed-security-service.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("mixed-security-service.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create() - .addOpenApiMapper(new ConstantSecurity()) - .config(config) - .convert(model); + .addOpenApiMapper(new ConstantSecurity()) + .config(config) + .convert(model); assertThat(result.getSecurity().get(0).keySet(), contains("foo_baz")); assertThat(result.getPaths().get("/2").getGet().get().getSecurity().get().get(0).keySet(), contains("foo_baz")); @@ -423,16 +423,16 @@ public void consolidatesSameSecurityRequirements() { // after they're set to use the same name, they're consolidated for // being the same. Model model = Model.assembler() - .addImport(getClass().getResource("consolidates-security-service.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("consolidates-security-service.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create() - .addOpenApiMapper(new ConstantSecurity()) - .config(config) - .convert(model); + .addOpenApiMapper(new ConstantSecurity()) + .config(config) + .convert(model); assertThat(result.getSecurity().size(), equalTo(1)); assertThat(result.getSecurity().get(0).keySet(), contains("foo_baz")); @@ -450,8 +450,8 @@ public void mergesInSchemaDocumentExtensions() { config.setService(ShapeId.from("example.rest#RestService")); config.setSchemaDocumentExtensions(Node.objectNode().withMember("foo", "baz")); ObjectNode result = OpenApiConverter.create() - .config(config) - .convertToNode(testService); + .config(config) + .convertToNode(testService); assertThat(result.getMember("foo"), equalTo(Optional.of(Node.from("baz")))); } @@ -460,20 +460,20 @@ public void mergesInSchemaDocumentExtensions() { @Test public void convertsStreamingService() { Model model = Model.assembler() - .addImport(getClass().getResource("streaming-service.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("streaming-service.smithy")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Streaming")); config.setProtocol(ShapeId.from("aws.protocols#restJson1")); ObjectNode result = OpenApiConverter.create() - .config(config) - .convertToNode(model); + .config(config) + .convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("streaming-service.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("streaming-service.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -485,14 +485,14 @@ public void addsDefaultSettings() { config.setService(ShapeId.from("example.rest#RestService")); config.setSchemaDocumentExtensions(Node.objectNode().withMember("foo", "baz")); OpenApiConverter.create() - .addOpenApiMapper(new OpenApiMapper() { - @Override - public void updateDefaultSettings(Model model, OpenApiConfig config) { - config.putExtension("hello", "goodbye"); - } - }) - .config(config) - .convertToNode(testService); + .addOpenApiMapper(new OpenApiMapper() { + @Override + public void updateDefaultSettings(Model model, OpenApiConfig config) { + config.putExtension("hello", "goodbye"); + } + }) + .config(config) + .convertToNode(testService); assertThat(config.getExtensions().getMember("hello"), not(Optional.empty())); } @@ -503,17 +503,17 @@ public void updateDefaultSettings(Model model, OpenApiConfig config) { @Test public void properlyRemovesRequiredPropertiesFromSynthesizedInput() { Model model = Model.assembler() - .addImport(getClass().getResource("service-with-required-path.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("service-with-required-path.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.rest#RestService")); OpenApi result = OpenApiConverter.create().config(config).convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("service-with-required-path.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("service-with-required-path.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -522,17 +522,17 @@ public void properlyRemovesRequiredPropertiesFromSynthesizedInput() { @Test public void convertsUnions() { Model model = Model.assembler() - .addImport(getClass().getResource("union-test.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("union-test.smithy")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Example")); Node result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("union-test.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("union-test.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -541,17 +541,17 @@ public void convertsUnions() { @Test public void convertsDocumentation() { Model model = Model.assembler() - .addImport(getClass().getResource("documentation-test.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("documentation-test.smithy")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#MyDocs")); Node result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("documentation-test.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("documentation-test.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -560,17 +560,17 @@ public void convertsDocumentation() { @Test public void convertsExternalDocumentation() { Model model = Model.assembler() - .addImport(getClass().getResource("externaldocs-test.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("externaldocs-test.smithy")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#MyDocs")); Node result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("externaldocs-test.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("externaldocs-test.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -579,17 +579,17 @@ public void convertsExternalDocumentation() { @Test public void properlyDealsWithServiceRenames() { Model model = Model.assembler() - .addImport(getClass().getResource("service-with-renames.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("service-with-renames.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#MyService")); Node result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("service-with-renames.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("service-with-renames.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -598,17 +598,17 @@ public void properlyDealsWithServiceRenames() { @Test public void generatesOpenApiForSharedErrors() { Model model = Model.assembler() - .addImport(getClass().getResource("service-with-common-errors.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("service-with-common-errors.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#MyService")); Node result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("service-with-common-errors.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("service-with-common-errors.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -617,17 +617,17 @@ public void generatesOpenApiForSharedErrors() { @Test public void convertsUnitsThatDoNotConflict() { Model model = Model.assembler() - .addImport(getClass().getResource("nonconflicting-unit.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("nonconflicting-unit.smithy")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example.rest#RestService")); Node result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("nonconflicting-unit.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("nonconflicting-unit.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -636,18 +636,18 @@ public void convertsUnitsThatDoNotConflict() { @Test public void convertsToOpenAPI3_0_2() { Model model = Model.assembler() - .addImport(getClass().getResource("nullability-and-format.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("nullability-and-format.smithy")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example#Example")); config.setVersion(OpenApiVersion.VERSION_3_0_2); Node result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("openapi-3-0-2.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("openapi-3-0-2.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -656,18 +656,18 @@ public void convertsToOpenAPI3_0_2() { @Test public void convertsToOpenAPI3_1_0() { Model model = Model.assembler() - .addImport(getClass().getResource("nullability-and-format.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("nullability-and-format.smithy")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example#Example")); config.setVersion(OpenApiVersion.VERSION_3_1_0); Node result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("openapi-3-1-0.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("openapi-3-1-0.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -676,20 +676,20 @@ public void convertsToOpenAPI3_1_0() { @Test public void removesMixins() { Model model = Model.assembler() - .addImport(getClass().getResource("model-with-mixins.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("model-with-mixins.smithy")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#HasMixin")); config.setProtocol(ShapeId.from("aws.protocols#restJson1")); ObjectNode result = OpenApiConverter.create() - .config(config) - .convertToNode(model); + .config(config) + .convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("model-with-mixins.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("model-with-mixins.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -698,19 +698,19 @@ public void removesMixins() { @Test public void convertsMemberDocumentation() { Model model = Model.assembler() - .addImport(getClass().getResource("documentation-test-members.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("documentation-test-members.smithy")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#MyDocs")); config.setVersion(OpenApiVersion.VERSION_3_1_0); config.setAddReferenceDescriptions(true); Node result = OpenApiConverter.create().config(config).convertToNode(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("documentation-test-members.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("documentation-test-members.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -719,10 +719,10 @@ public void convertsMemberDocumentation() { @Test public void convertingMemberDocsRequired3_1() { Model model = Model.assembler() - .addImport(getClass().getResource("documentation-test-members.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("documentation-test-members.smithy")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#MyDocs")); config.setAddReferenceDescriptions(true); diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/OpenApiJsonSchemaMapperTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/OpenApiJsonSchemaMapperTest.java index e377f67d89f..f2eae790250 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/OpenApiJsonSchemaMapperTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/OpenApiJsonSchemaMapperTest.java @@ -43,16 +43,16 @@ public class OpenApiJsonSchemaMapperTest { @Test public void convertsModels() { Model model = Model.assembler() - .addImport(getClass().getResource("test-service.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("test-service.json")) + .discoverModels() + .assemble() + .unwrap(); SchemaDocument document = JsonSchemaConverter.builder() - .addMapper(new OpenApiJsonSchemaMapper()) - .config(new OpenApiConfig()) - .model(model) - .build() - .convert(); + .addMapper(new OpenApiJsonSchemaMapper()) + .config(new OpenApiConfig()) + .model(model) + .build() + .convert(); assertTrue(document.toNode().expectObjectNode().getMember("components").isPresent()); } @@ -62,21 +62,21 @@ public void supportsExternalDocs() { String key = "Homepage"; String link = "https://foo.com"; StringShape shape = StringShape.builder() - .id("a.b#C") - .addTrait(ExternalDocumentationTrait.builder().addUrl(key, link).build()) - .build(); + .id("a.b#C") + .addTrait(ExternalDocumentationTrait.builder().addUrl(key, link).build()) + .build(); Model model = Model.builder().addShape(shape).build(); SchemaDocument document = JsonSchemaConverter.builder() - .addMapper(new OpenApiJsonSchemaMapper()) - .config(new OpenApiConfig()) - .model(model) - .build() - .convertShape(shape); + .addMapper(new OpenApiJsonSchemaMapper()) + .config(new OpenApiConfig()) + .model(model) + .build() + .convertShape(shape); ObjectNode expectedDocs = ObjectNode.objectNodeBuilder() - .withMember("description", key) - .withMember("url", link) - .build(); + .withMember("description", key) + .withMember("url", link) + .build(); Node.assertEquals(document.getRootSchema().getExtension("externalDocs").get(), expectedDocs); } @@ -86,23 +86,23 @@ public void supportsCustomExternalDocNames() { String key = "CuStOm NaMe"; String link = "https://foo.com"; StringShape shape = StringShape.builder() - .id("a.b#C") - .addTrait(ExternalDocumentationTrait.builder().addUrl(key, link).build()) - .build(); + .id("a.b#C") + .addTrait(ExternalDocumentationTrait.builder().addUrl(key, link).build()) + .build(); Model model = Model.builder().addShape(shape).build(); OpenApiConfig config = new OpenApiConfig(); config.setExternalDocs(ListUtils.of("Custom Name")); SchemaDocument document = JsonSchemaConverter.builder() - .config(config) - .addMapper(new OpenApiJsonSchemaMapper()) - .model(model) - .build() - .convertShape(shape); + .config(config) + .addMapper(new OpenApiJsonSchemaMapper()) + .model(model) + .build() + .convertShape(shape); ObjectNode expectedDocs = ObjectNode.objectNodeBuilder() - .withMember("description", key) - .withMember("url", link) - .build(); + .withMember("description", key) + .withMember("url", link) + .build(); Node.assertEquals(document.getRootSchema().getExtension("externalDocs").get(), expectedDocs); } @@ -111,10 +111,10 @@ public void supportsDeprecatedTrait() { IntegerShape shape = IntegerShape.builder().id("a.b#C").addTrait(DeprecatedTrait.builder().build()).build(); Model model = Model.builder().addShape(shape).build(); SchemaDocument document = JsonSchemaConverter.builder() - .addMapper(new OpenApiJsonSchemaMapper()) - .model(model) - .build() - .convertShape(shape); + .addMapper(new OpenApiJsonSchemaMapper()) + .model(model) + .build() + .convertShape(shape); assertThat(document.getRootSchema().getExtension("deprecated").get(), equalTo(Node.from(true))); } @@ -124,16 +124,16 @@ public void appendsDeprecatedInfoInDescription() { String message = "Use a.b#D instead."; String since = "2020-01-01"; IntegerShape shape = IntegerShape.builder() - .id("a.b#C") - .addTrait(DeprecatedTrait.builder().message(message).since(since).build()) - .addTrait(new DocumentationTrait("This is an integer.")) - .build(); + .id("a.b#C") + .addTrait(DeprecatedTrait.builder().message(message).since(since).build()) + .addTrait(new DocumentationTrait("This is an integer.")) + .build(); Model model = Model.builder().addShape(shape).build(); SchemaDocument document = JsonSchemaConverter.builder() - .addMapper(new OpenApiJsonSchemaMapper()) - .model(model) - .build() - .convertShape(shape); + .addMapper(new OpenApiJsonSchemaMapper()) + .model(model) + .build() + .convertShape(shape); String expected = "This is an integer.\nThis shape is deprecated since 2020-01-01: Use a.b#D instead."; assertThat(document.getRootSchema().getDescription().get(), equalTo(expected)); @@ -146,11 +146,11 @@ public void supportsInt32() { OpenApiConfig config = new OpenApiConfig(); config.setUseIntegerType(true); SchemaDocument document = JsonSchemaConverter.builder() - .addMapper(new OpenApiJsonSchemaMapper()) - .config(config) - .model(model) - .build() - .convertShape(shape); + .addMapper(new OpenApiJsonSchemaMapper()) + .config(config) + .model(model) + .build() + .convertShape(shape); assertThat(document.getRootSchema().getFormat().get(), equalTo("int32")); } @@ -162,11 +162,11 @@ public void supportsInt64() { OpenApiConfig config = new OpenApiConfig(); config.setUseIntegerType(true); SchemaDocument document = JsonSchemaConverter.builder() - .addMapper(new OpenApiJsonSchemaMapper()) - .config(config) - .model(model) - .build() - .convertShape(shape); + .addMapper(new OpenApiJsonSchemaMapper()) + .config(config) + .model(model) + .build() + .convertShape(shape); assertThat(document.getRootSchema().getFormat().get(), equalTo("int64")); } @@ -180,10 +180,10 @@ public void canDisableIntegerFormats() { config.setUseIntegerType(true); config.setDisableIntegerFormat(true); JsonSchemaConverter converter = JsonSchemaConverter.builder() - .addMapper(new OpenApiJsonSchemaMapper()) - .config(config) - .model(model) - .build(); + .addMapper(new OpenApiJsonSchemaMapper()) + .config(config) + .model(model) + .build(); SchemaDocument integerDocument = converter.convertShape(integerShape); SchemaDocument longDocument = converter.convertShape(longShape); @@ -199,10 +199,10 @@ public void supportsFloatFormat() { FloatShape shape = FloatShape.builder().id("a.b#C").build(); Model model = Model.builder().addShape(shape).build(); SchemaDocument document = JsonSchemaConverter.builder() - .addMapper(new OpenApiJsonSchemaMapper()) - .model(model) - .build() - .convertShape(shape); + .addMapper(new OpenApiJsonSchemaMapper()) + .model(model) + .build() + .convertShape(shape); assertThat(document.getRootSchema().getFormat().get(), equalTo("float")); } @@ -214,11 +214,11 @@ public void supportsNonNumericFloatFormat() { JsonSchemaConfig config = new JsonSchemaConfig(); config.setSupportNonNumericFloats(true); SchemaDocument document = JsonSchemaConverter.builder() - .addMapper(new OpenApiJsonSchemaMapper()) - .config(config) - .model(model) - .build() - .convertShape(shape); + .addMapper(new OpenApiJsonSchemaMapper()) + .config(config) + .model(model) + .build() + .convertShape(shape); Schema rootSchema = document.getRootSchema(); assertFalse(rootSchema.getFormat().isPresent()); @@ -238,10 +238,10 @@ public void supportsDoubleFormat() { DoubleShape shape = DoubleShape.builder().id("a.b#C").build(); Model model = Model.builder().addShape(shape).build(); SchemaDocument document = JsonSchemaConverter.builder() - .addMapper(new OpenApiJsonSchemaMapper()) - .model(model) - .build() - .convertShape(shape); + .addMapper(new OpenApiJsonSchemaMapper()) + .model(model) + .build() + .convertShape(shape); assertThat(document.getRootSchema().getFormat().get(), equalTo("double")); } @@ -253,11 +253,11 @@ public void supportsNonNumericDoubleFormat() { JsonSchemaConfig config = new JsonSchemaConfig(); config.setSupportNonNumericFloats(true); SchemaDocument document = JsonSchemaConverter.builder() - .addMapper(new OpenApiJsonSchemaMapper()) - .config(config) - .model(model) - .build() - .convertShape(shape); + .addMapper(new OpenApiJsonSchemaMapper()) + .config(config) + .model(model) + .build() + .convertShape(shape); Schema rootSchema = document.getRootSchema(); assertFalse(rootSchema.getFormat().isPresent()); @@ -277,11 +277,11 @@ public void blobFormatDefaultsToByte() { BlobShape shape = BlobShape.builder().id("a.b#C").build(); Model model = Model.builder().addShape(shape).build(); SchemaDocument document = JsonSchemaConverter.builder() - .config(new OpenApiConfig()) - .addMapper(new OpenApiJsonSchemaMapper()) - .model(model) - .build() - .convertShape(shape); + .config(new OpenApiConfig()) + .addMapper(new OpenApiJsonSchemaMapper()) + .model(model) + .build() + .convertShape(shape); assertThat(document.getRootSchema().getFormat().get(), equalTo("byte")); } @@ -293,11 +293,11 @@ public void blobFormatOverriddenToBinary() { OpenApiConfig config = new OpenApiConfig(); config.setDefaultBlobFormat("binary"); SchemaDocument document = JsonSchemaConverter.builder() - .config(config) - .addMapper(new OpenApiJsonSchemaMapper()) - .model(model) - .build() - .convertShape(shape); + .config(config) + .addMapper(new OpenApiJsonSchemaMapper()) + .model(model) + .build() + .convertShape(shape); assertThat(document.getRootSchema().getFormat().get(), equalTo("binary")); } @@ -309,22 +309,22 @@ public void integerTypesDefaultsToNumber() { IntegerShape integerShape = IntegerShape.builder().id("a.b#Integer").build(); LongShape longShape = LongShape.builder().id("a.b#Long").build(); StructureShape structureShape = StructureShape.builder() - .id("a.b#Structure") - .addMember("byte", byteShape.getId()) - .addMember("short", shortShape.getId()) - .addMember("int", integerShape.getId()) - .addMember("long", longShape.getId()) - .build(); + .id("a.b#Structure") + .addMember("byte", byteShape.getId()) + .addMember("short", shortShape.getId()) + .addMember("int", integerShape.getId()) + .addMember("long", longShape.getId()) + .build(); Model model = Model.builder() - .addShapes(byteShape, shortShape, integerShape, longShape, structureShape) - .build(); + .addShapes(byteShape, shortShape, integerShape, longShape, structureShape) + .build(); SchemaDocument document = JsonSchemaConverter.builder() - .config(new OpenApiConfig()) - .addMapper(new OpenApiJsonSchemaMapper()) - .model(model) - .build() - .convertShape(structureShape); + .config(new OpenApiConfig()) + .addMapper(new OpenApiJsonSchemaMapper()) + .model(model) + .build() + .convertShape(structureShape); assertThat(document.getRootSchema().getType().get(), equalTo("object")); assertThat(document.getRootSchema().getProperties().size(), equalTo(4)); @@ -342,24 +342,24 @@ public void integerTypesOverriddenToInteger() { IntegerShape integerShape = IntegerShape.builder().id("a.b#Integer").build(); LongShape longShape = LongShape.builder().id("a.b#Long").build(); StructureShape structureShape = StructureShape.builder() - .id("a.b#Structure") - .addMember("byte", byteShape.getId()) - .addMember("short", shortShape.getId()) - .addMember("int", integerShape.getId()) - .addMember("long", longShape.getId()) - .build(); + .id("a.b#Structure") + .addMember("byte", byteShape.getId()) + .addMember("short", shortShape.getId()) + .addMember("int", integerShape.getId()) + .addMember("long", longShape.getId()) + .build(); Model model = Model.builder() - .addShapes(byteShape, shortShape, integerShape, longShape, structureShape) - .build(); + .addShapes(byteShape, shortShape, integerShape, longShape, structureShape) + .build(); OpenApiConfig config = new OpenApiConfig(); config.setUseIntegerType(true); SchemaDocument document = JsonSchemaConverter.builder() - .config(config) - .addMapper(new OpenApiJsonSchemaMapper()) - .model(model) - .build() - .convertShape(structureShape); + .config(config) + .addMapper(new OpenApiJsonSchemaMapper()) + .model(model) + .build() + .convertShape(structureShape); assertThat(document.getRootSchema().getType().get(), equalTo("object")); assertThat(document.getRootSchema().getProperties().size(), equalTo(4)); @@ -375,10 +375,10 @@ public void supportsSensitiveTrait() { StringShape shape = StringShape.builder().id("a.b#C").addTrait(new SensitiveTrait()).build(); Model model = Model.builder().addShape(shape).build(); SchemaDocument document = JsonSchemaConverter.builder() - .addMapper(new OpenApiJsonSchemaMapper()) - .model(model) - .build() - .convertShape(shape); + .addMapper(new OpenApiJsonSchemaMapper()) + .model(model) + .build() + .convertShape(shape); assertThat(document.getRootSchema().getFormat().get(), equalTo("password")); } @@ -386,32 +386,37 @@ public void supportsSensitiveTrait() { @Test public void supportsSpecificationExtensionTrait() { StringShape extensionTraitShape = StringShape.builder() - .id("a.b#extensionTrait") - .addTrait(TraitDefinition.builder().build()) - .addTrait(SpecificationExtensionTrait.builder().as("x-important-metadata").build()) - .build(); + .id("a.b#extensionTrait") + .addTrait(TraitDefinition.builder().build()) + .addTrait(SpecificationExtensionTrait.builder().as("x-important-metadata").build()) + .build(); DynamicTrait extensionTraitInstance = new DynamicTrait( - extensionTraitShape.getId(), - StringNode.from("string content") + extensionTraitShape.getId(), + StringNode.from("string content") ); IntegerShape integerShape = IntegerShape.builder().id("a.b#Integer").build(); StructureShape structure = StructureShape.builder() - .id("a.b#Struct") - .addTrait(extensionTraitInstance) - .addMember("c", integerShape.getId()) - .build(); + .id("a.b#Struct") + .addTrait(extensionTraitInstance) + .addMember("c", integerShape.getId()) + .build(); Model model = Model.builder().addShapes(extensionTraitShape, integerShape, structure).build(); SchemaDocument document = JsonSchemaConverter.builder() - .addMapper(new OpenApiJsonSchemaMapper()) - .model(model) - .build() - .convertShape(structure); + .addMapper(new OpenApiJsonSchemaMapper()) + .model(model) + .build() + .convertShape(structure); assertThat( - document.getRootSchema().getExtension("x-important-metadata").get().toNode().expectStringNode().getValue(), - equalTo("string content") + document.getRootSchema() + .getExtension("x-important-metadata") + .get() + .toNode() + .expectStringNode() + .getValue(), + equalTo("string content") ); } } diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/Smithy2OpenApiTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/Smithy2OpenApiTest.java index dbb7add0026..4b5773683d9 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/Smithy2OpenApiTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/Smithy2OpenApiTest.java @@ -18,20 +18,20 @@ public class Smithy2OpenApiTest { @Test public void pluginConvertsModel() { Model model = Model.assembler() - .addImport(OpenApiConverterTest.class.getResource("test-service.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(OpenApiConverterTest.class.getResource("test-service.json")) + .discoverModels() + .assemble() + .unwrap(); MockManifest manifest = new MockManifest(); PluginContext context = PluginContext.builder() - .settings( - Node.objectNode() - .withMember("service", "example.rest#RestService") - ) - .fileManifest(manifest) - .model(model) - .originalModel(model) - .build(); + .settings( + Node.objectNode() + .withMember("service", "example.rest#RestService") + ) + .fileManifest(manifest) + .model(model) + .originalModel(model) + .build(); new Smithy2OpenApi().execute(context); assertTrue(manifest.hasFile("RestService.openapi.json")); } @@ -39,17 +39,17 @@ public void pluginConvertsModel() { @Test public void throwsWhenServiceNotConfigured() { Model model = Model.assembler() - .addImport(OpenApiConverterTest.class.getResource("test-service.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(OpenApiConverterTest.class.getResource("test-service.json")) + .discoverModels() + .assemble() + .unwrap(); MockManifest manifest = new MockManifest(); PluginContext context = PluginContext.builder() - .settings(Node.objectNode()) - .fileManifest(manifest) - .model(model) - .originalModel(model) - .build(); + .settings(Node.objectNode()) + .fileManifest(manifest) + .model(model) + .originalModel(model) + .build(); assertThrows(OpenApiException.class, () -> { new Smithy2OpenApi().execute(context); }); diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForGreedyLabelsTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForGreedyLabelsTest.java index 44b17a28b12..58a8685eb42 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForGreedyLabelsTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForGreedyLabelsTest.java @@ -20,10 +20,10 @@ public class CheckForGreedyLabelsTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(RemoveUnusedComponentsTest.class.getResource("greedy-labels.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(RemoveUnusedComponentsTest.class.getResource("greedy-labels.smithy")) + .discoverModels() + .assemble() + .unwrap(); } @AfterAll @@ -46,8 +46,8 @@ public void keepsUnusedSchemas() { Exception thrown = Assertions.assertThrows(OpenApiException.class, () -> { OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); }); Assertions.assertTrue(thrown.getMessage().contains("greedy")); diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForPrefixHeadersTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForPrefixHeadersTest.java index 84ad01f03d5..b7cd2140cc8 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForPrefixHeadersTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForPrefixHeadersTest.java @@ -20,10 +20,10 @@ public class CheckForPrefixHeadersTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(RemoveUnusedComponentsTest.class.getResource("prefix-headers.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(RemoveUnusedComponentsTest.class.getResource("prefix-headers.smithy")) + .discoverModels() + .assemble() + .unwrap(); } @AfterAll @@ -37,8 +37,8 @@ public void canIgnorePrefixHeaders() { config.setService(ShapeId.from("smithy.example#PrefixHeaders")); config.setOnHttpPrefixHeaders(OpenApiConfig.HttpPrefixHeadersStrategy.WARN); OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); } @Test diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonAddTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonAddTest.java index 2beb1627d55..b723a699b13 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonAddTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonAddTest.java @@ -25,30 +25,30 @@ public class OpenApiJsonAddTest { @BeforeAll public static void before() { MODEL = Model.assembler() - // Reusing another test cases's model, but that doesn't matter for the - // purpose of this test. - .addImport(RemoveUnusedComponentsTest.class.getResource("substitutions.smithy")) - .discoverModels() - .assemble() - .unwrap(); + // Reusing another test cases's model, but that doesn't matter for the + // purpose of this test. + .addImport(RemoveUnusedComponentsTest.class.getResource("substitutions.smithy")) + .discoverModels() + .assemble() + .unwrap(); } @Test public void addsWithPointers() { ObjectNode addNode = Node.objectNodeBuilder() - .withMember("/info/description", "hello") - .withMember("/info/foo", "bar") - .withMember("/info/nested/abc", "nested") - .withMember("/info/title", "custom") - .build(); + .withMember("/info/description", "hello") + .withMember("/info/foo", "bar") + .withMember("/info/nested/abc", "nested") + .withMember("/info/title", "custom") + .build(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); config.setJsonAdd(addNode.getStringMap()); ObjectNode openApi = OpenApiConverter.create() - .config(config) - .convertToNode(MODEL); + .config(config) + .convertToNode(MODEL); String description = NodePointer.parse("/info/description").getValue(openApi).expectStringNode().getValue(); String infoFoo = NodePointer.parse("/info/foo").getValue(openApi).expectStringNode().getValue(); @@ -90,7 +90,7 @@ public void warnsWhenAddingSchemas() { logger.addHandler(handler); ObjectNode addNode = Node.objectNode() - .withMember("/components/schemas/Merged", Node.objectNode().withMember("type", "string")); + .withMember("/components/schemas/Merged", Node.objectNode().withMember("type", "string")); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonSubstitutionsPluginTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonSubstitutionsPluginTest.java index 1338895903a..9e8d4e3884e 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonSubstitutionsPluginTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/OpenApiJsonSubstitutionsPluginTest.java @@ -18,17 +18,17 @@ public class OpenApiJsonSubstitutionsPluginTest { @Test public void removesBySubstitution() { Model model = Model.assembler() - .addImport(RemoveUnusedComponentsTest.class.getResource("substitutions.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(RemoveUnusedComponentsTest.class.getResource("substitutions.smithy")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); config.setSubstitutions(MapUtils.of("SUB_HELLO", Node.from("hello"))); ObjectNode openApi = OpenApiConverter.create() - .config(config) - .convertToNode(model); + .config(config) + .convertToNode(model); String description = openApi.getObjectMember("info").get().getStringMember("description").get().getValue(); Assertions.assertEquals("hello", description); diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/RemoveUnusedComponentsTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/RemoveUnusedComponentsTest.java index b7e41845e24..305a5dea48a 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/RemoveUnusedComponentsTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/RemoveUnusedComponentsTest.java @@ -23,10 +23,10 @@ public class RemoveUnusedComponentsTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(RemoveUnusedComponentsTest.class.getResource("small-service.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(RemoveUnusedComponentsTest.class.getResource("small-service.smithy")) + .discoverModels() + .assemble() + .unwrap(); } @AfterAll @@ -44,7 +44,7 @@ public void removesUnusedSchemas() { Assertions.assertTrue(result.getComponents().getSchemas().containsKey("SmallOperationRequestContent")); Assertions.assertTrue(result.getComponents().getSchemas().containsKey("StringMap")); Assertions.assertFalse( - result.getComponents().getSchemas().containsKey("SmallOperationExceptionResponseContent") + result.getComponents().getSchemas().containsKey("SmallOperationExceptionResponseContent") ); } @@ -54,8 +54,8 @@ public void keepsUnusedSchemas() { config.setService(ShapeId.from("smithy.example#Small")); config.setKeepUnusedComponents(true); OpenApi result = OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); // The input structure remains in the output even though it's unreferenced. Assertions.assertFalse(result.getComponents().getSchemas().isEmpty()); @@ -67,21 +67,24 @@ public void removesUnusedSchemes() { config.setService(ShapeId.from("smithy.example#Small")); OpenApi result = OpenApiConverter.create() - .config(config) - .addOpenApiMapper(new OpenApiMapper() { - @Override - public OpenApi after(Context context, OpenApi openapi) { - return openapi.toBuilder() - .components( - openapi.getComponents() - .toBuilder() - .putSecurityScheme("foo", SecurityScheme.builder().type("apiKey").build()) - .build() - ) - .build(); - } - }) - .convert(model); + .config(config) + .addOpenApiMapper(new OpenApiMapper() { + @Override + public OpenApi after(Context context, OpenApi openapi) { + return openapi.toBuilder() + .components( + openapi.getComponents() + .toBuilder() + .putSecurityScheme( + "foo", + SecurityScheme.builder().type("apiKey").build() + ) + .build() + ) + .build(); + } + }) + .convert(model); Assertions.assertFalse(result.getComponents().getSecuritySchemes().keySet().contains("foo")); } diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/SpecificationExtensionsMapperTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/SpecificationExtensionsMapperTest.java index cc490f1737d..af73bfa4b4a 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/SpecificationExtensionsMapperTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/SpecificationExtensionsMapperTest.java @@ -18,21 +18,21 @@ public class SpecificationExtensionsMapperTest { @ParameterizedTest @ValueSource( - strings = { - "inlined-type-target", - "structure-target", - "operation-target", - "service-target" - } + strings = { + "inlined-type-target", + "structure-target", + "operation-target", + "service-target" + } ) public void checkMapping(String name) { OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); Node actual = OpenApiConverter - .create() - .config(config) - .convertToNode(getSpecificationExtensionTraits(name)); + .create() + .config(config) + .convertToNode(getSpecificationExtensionTraits(name)); Node expected = getExpectedOpenAPI(name); Node.assertEquals(actual, expected); @@ -40,11 +40,11 @@ public void checkMapping(String name) { private static Model getSpecificationExtensionTraits(String name) { return Model.assembler() - .addImport(getResource(name + ".smithy")) - .addImport(getResource("specification-extension-traits.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getResource(name + ".smithy")) + .addImport(getResource("specification-extension-traits.smithy")) + .discoverModels() + .assemble() + .unwrap(); } private static Node getExpectedOpenAPI(String name) { diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/UnsupportedTraitsPluginTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/UnsupportedTraitsPluginTest.java index f00149787a1..bc73078a26d 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/UnsupportedTraitsPluginTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/mappers/UnsupportedTraitsPluginTest.java @@ -20,10 +20,10 @@ public class UnsupportedTraitsPluginTest { @BeforeAll public static void before() { model = Model.assembler() - .addImport(UnsupportedTraitsPluginTest.class.getResource("endpoint-service.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(UnsupportedTraitsPluginTest.class.getResource("endpoint-service.smithy")) + .discoverModels() + .assemble() + .unwrap(); } @AfterAll @@ -37,8 +37,8 @@ public void logsWhenUnsupportedTraitsAreFound() { config.setService(ShapeId.from("smithy.example#EndpointService")); config.setIgnoreUnsupportedTraits(true); OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); } @Test diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/protocols/AwsRestJson1ProtocolTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/protocols/AwsRestJson1ProtocolTest.java index 6ae32033301..5650fb8b87b 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/protocols/AwsRestJson1ProtocolTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/protocols/AwsRestJson1ProtocolTest.java @@ -35,30 +35,30 @@ public class AwsRestJson1ProtocolTest { @ParameterizedTest @ValueSource( - strings = { - "adds-json-document-bodies.json", - "adds-path-timestamp-format.json", - "adds-query-timestamp-format.json", - "adds-header-timestamp-format.json", - "adds-header-mediatype-format.json", - "supports-payloads.json", - "aws-rest-json-uses-jsonname.json", - "synthesizes-contents.json", - "greedy-labels.json" - } + strings = { + "adds-json-document-bodies.json", + "adds-path-timestamp-format.json", + "adds-query-timestamp-format.json", + "adds-header-timestamp-format.json", + "adds-header-mediatype-format.json", + "supports-payloads.json", + "aws-rest-json-uses-jsonname.json", + "synthesizes-contents.json", + "greedy-labels.json" + } ) public void testProtocolResult(String smithy) { Model model = Model.assembler() - .addImport(getClass().getResource(smithy)) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource(smithy)) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); ObjectNode result = OpenApiConverter.create() - .config(config) - .convertToNode(model); + .config(config) + .convertToNode(model); String openApiModel = smithy.replace(".json", ".openapi.json"); InputStream openApiStream = getClass().getResourceAsStream(openApiModel); @@ -73,16 +73,16 @@ public void testProtocolResult(String smithy) { @Test public void canUseCustomMediaType() { Model model = Model.assembler() - .addImport(getClass().getResource("adds-json-document-bodies.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("adds-json-document-bodies.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); config.setJsonContentType("application/x-amz-json-1.0"); OpenApi result = OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); Assertions.assertTrue(Node.printJson(result.toNode()).contains("application/x-amz-json-1.0")); } @@ -91,16 +91,16 @@ public void canUseCustomMediaType() { public void canRemoveGreedyLabelNameParameterSuffix() { String smithy = "greedy-labels-name-parameter-without-suffix.json"; Model model = Model.assembler() - .addImport(getClass().getResource(smithy)) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource(smithy)) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); config.setRemoveGreedyParameterSuffix(true); OpenApi result = OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); String openApiModel = smithy.replace(".json", ".openapi.json"); InputStream openApiStream = getClass().getResourceAsStream(openApiModel); @@ -116,16 +116,16 @@ public void canRemoveGreedyLabelNameParameterSuffix() { public void canRemoveNonAlphaNumericDocumentNames() { String smithy = "non-alphanumeric-content-names.json"; Model model = Model.assembler() - .addImport(getClass().getResource(smithy)) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource(smithy)) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); config.setAlphanumericOnlyRefs(true); OpenApi result = OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); String openApiModel = smithy.replace(".json", ".openapi.json"); InputStream openApiStream = getClass().getResourceAsStream(openApiModel); @@ -139,83 +139,83 @@ public void canRemoveNonAlphaNumericDocumentNames() { private static Stream protocolHeaderCases() { return Stream.of( - Arguments.of( - "NoInputOrOutput", - SetUtils.of( - "X-Amz-User-Agent", - "X-Amzn-Trace-Id", - "Amz-Sdk-Request", - "Amz-Sdk-Invocation-Id" - ), - SetUtils.of( - "X-Amzn-Requestid", - "X-Amzn-Errortype", - "Content-Length", - "Content-Type" - ) - ), - Arguments.of( - "EmptyInputAndOutput", - SetUtils.of( - "X-Amz-User-Agent", - "X-Amzn-Trace-Id", - "Amz-Sdk-Request", - "Amz-Sdk-Invocation-Id" + Arguments.of( + "NoInputOrOutput", + SetUtils.of( + "X-Amz-User-Agent", + "X-Amzn-Trace-Id", + "Amz-Sdk-Request", + "Amz-Sdk-Invocation-Id" + ), + SetUtils.of( + "X-Amzn-Requestid", + "X-Amzn-Errortype", + "Content-Length", + "Content-Type" + ) ), - SetUtils.of( - "X-Amzn-Requestid", - "X-Amzn-Errortype", - "Content-Length", - "Content-Type" - ) - ), - Arguments.of( - "OnlyErrorOutput", - SetUtils.of( - "X-Amz-User-Agent", - "X-Amzn-Trace-Id", - "Amz-Sdk-Request", - "Amz-Sdk-Invocation-Id" + Arguments.of( + "EmptyInputAndOutput", + SetUtils.of( + "X-Amz-User-Agent", + "X-Amzn-Trace-Id", + "Amz-Sdk-Request", + "Amz-Sdk-Invocation-Id" + ), + SetUtils.of( + "X-Amzn-Requestid", + "X-Amzn-Errortype", + "Content-Length", + "Content-Type" + ) ), - SetUtils.of( - "X-Amzn-Requestid", - "X-Amzn-Errortype", - "Content-Length", - "Content-Type" - ) - ), - Arguments.of( - "HttpChecksumRequired", - SetUtils.of( - "X-Amz-User-Agent", - "X-Amzn-Trace-Id", - "Amz-Sdk-Request", - "Amz-Sdk-Invocation-Id", - "Content-Md5" + Arguments.of( + "OnlyErrorOutput", + SetUtils.of( + "X-Amz-User-Agent", + "X-Amzn-Trace-Id", + "Amz-Sdk-Request", + "Amz-Sdk-Invocation-Id" + ), + SetUtils.of( + "X-Amzn-Requestid", + "X-Amzn-Errortype", + "Content-Length", + "Content-Type" + ) ), - SetUtils.of( - "X-Amzn-Requestid", - "X-Amzn-Errortype", - "Content-Length", - "Content-Type" - ) - ), - Arguments.of( - "HasDiscoveredEndpoint", - SetUtils.of( - "X-Amz-User-Agent", - "X-Amzn-Trace-Id", - "Amz-Sdk-Request", - "Amz-Sdk-Invocation-Id", - "X-Amz-Api-Version" + Arguments.of( + "HttpChecksumRequired", + SetUtils.of( + "X-Amz-User-Agent", + "X-Amzn-Trace-Id", + "Amz-Sdk-Request", + "Amz-Sdk-Invocation-Id", + "Content-Md5" + ), + SetUtils.of( + "X-Amzn-Requestid", + "X-Amzn-Errortype", + "Content-Length", + "Content-Type" + ) ), - SetUtils.of( - "X-Amzn-Requestid", - "X-Amzn-Errortype", - "Content-Length", - "Content-Type" + Arguments.of( + "HasDiscoveredEndpoint", + SetUtils.of( + "X-Amz-User-Agent", + "X-Amzn-Trace-Id", + "Amz-Sdk-Request", + "Amz-Sdk-Invocation-Id", + "X-Amz-Api-Version" + ), + SetUtils.of( + "X-Amzn-Requestid", + "X-Amzn-Errortype", + "Content-Length", + "Content-Type" + ) ) - ) ); } @@ -223,30 +223,30 @@ private static Stream protocolHeaderCases() { @MethodSource("protocolHeaderCases") @SuppressWarnings("unchecked") public void assertProtocolHeaders( - String operationId, - Set expectedRequestHeaders, - Set expectedResponseHeaders + String operationId, + Set expectedRequestHeaders, + Set expectedResponseHeaders ) { Model model = Model.assembler() - .addImport(getClass().getResource("rest-json-protocol-headers.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("rest-json-protocol-headers.smithy")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); config.setAlphanumericOnlyRefs(true); AwsRestJson1Protocol protocol = new AwsRestJson1Protocol(); OperationShape operation = model.expectShape( - ShapeId.fromParts("smithy.example", operationId), - OperationShape.class + ShapeId.fromParts("smithy.example", operationId), + OperationShape.class ); ContextCapturingMapper contextCaptor = new ContextCapturingMapper(); OpenApiConverter.create() - .config(config) - .addOpenApiMapper(contextCaptor) - .convert(model); + .config(config) + .addOpenApiMapper(contextCaptor) + .convert(model); Context context = (Context) contextCaptor.capturedContext; @@ -268,11 +268,11 @@ public byte getOrder() { @Override public OperationObject updateOperation( - Context context, - OperationShape shape, - OperationObject operation, - String httpMethodName, - String path + Context context, + OperationShape shape, + OperationObject operation, + String httpMethodName, + String path ) { this.capturedContext = context; return OpenApiMapper.super.updateOperation(context, shape, operation, httpMethodName, path); @@ -282,15 +282,15 @@ public OperationObject updateOperation( @Test public void convertsExamples() { Model model = Model.assembler() - .addImport(getClass().getResource("examples-test.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("examples-test.smithy")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.examplestrait#Banking")); ObjectNode result = OpenApiConverter.create() - .config(config) - .convertToNode(model); + .config(config) + .convertToNode(model); InputStream openApiStream = getClass().getResourceAsStream("examples-test.openapi.json"); if (openApiStream == null) { @@ -304,23 +304,23 @@ public void convertsExamples() { @Test public void combinesErrorsWithSameStatusCode() { Model model = Model.assembler() - .addImport(getClass().getResource("error-code-collision-test.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("error-code-collision-test.smithy")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("example#Example")); config.setOnErrorStatusConflict(OpenApiConfig.ErrorStatusConflictHandlingStrategy.ONE_OF); ObjectNode result = OpenApiConverter.create() - .config(config) - .convertToNode(model); + .config(config) + .convertToNode(model); InputStream openApiStream = getClass() - .getResourceAsStream("error-code-collision-test-use-oneof.openapi.json"); + .getResourceAsStream("error-code-collision-test-use-oneof.openapi.json"); if (openApiStream == null) { throw new RuntimeException( - "OpenAPI model not found for test case: " - + "error-code-collision-test-use-properties.openapi.json" + "OpenAPI model not found for test case: " + + "error-code-collision-test-use-properties.openapi.json" ); } else { Node expectedNode = Node.parse(IoUtils.toUtf8String(openApiStream)); diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/AwsV4ConverterTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/AwsV4ConverterTest.java index 58d22babc80..d0d5315f80c 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/AwsV4ConverterTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/AwsV4ConverterTest.java @@ -17,17 +17,17 @@ public class AwsV4ConverterTest { @Test public void addsAwsV4() { Model model = Model.assembler() - .addImport(getClass().getResource("awsv4-security.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("awsv4-security.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create().config(config).convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("awsv4-security.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("awsv4-security.openapi.json") + ) ); Node.assertEquals(result, expectedNode); diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/HttpApiKeyAuthConverterTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/HttpApiKeyAuthConverterTest.java index bf6e6f21d64..447b526adbd 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/HttpApiKeyAuthConverterTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/HttpApiKeyAuthConverterTest.java @@ -21,17 +21,17 @@ public class HttpApiKeyAuthConverterTest { @Test public void addsCustomApiKeyAuth() { Model model = Model.assembler() - .addImport(getClass().getResource("http-api-key-security.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("http-api-key-security.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create().config(config).convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("http-api-key-security.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("http-api-key-security.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -40,17 +40,17 @@ public void addsCustomApiKeyAuth() { @Test public void addsCustomApiKeyBearerAuth() { Model model = Model.assembler() - .addImport(getClass().getResource("http-api-key-bearer-security.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("http-api-key-bearer-security.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create().config(config).convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("http-api-key-bearer-security.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("http-api-key-bearer-security.openapi.json") + ) ); Node.assertEquals(result, expectedNode); @@ -60,9 +60,9 @@ public void addsCustomApiKeyBearerAuth() { public void returnsTraitHeader() { HttpApiKeyAuthConverter converter = new HttpApiKeyAuthConverter(); HttpApiKeyAuthTrait trait = HttpApiKeyAuthTrait.builder() - .name("x-api-key") - .in(HttpApiKeyAuthTrait.Location.HEADER) - .build(); + .name("x-api-key") + .in(HttpApiKeyAuthTrait.Location.HEADER) + .build(); assertThat(converter.getAuthRequestHeaders(null, trait), containsInAnyOrder("x-api-key")); } diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/HttpBasicConverterTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/HttpBasicConverterTest.java index 6f954e9b63b..a0c49d5320a 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/HttpBasicConverterTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/HttpBasicConverterTest.java @@ -17,17 +17,17 @@ public class HttpBasicConverterTest { @Test public void addsHttpBasicAuth() { Model model = Model.assembler() - .addImport(getClass().getResource("http-basic-security.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("http-basic-security.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create().config(config).convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("http-basic-security.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("http-basic-security.openapi.json") + ) ); Node.assertEquals(result, expectedNode); diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/HttpDigestConverterTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/HttpDigestConverterTest.java index dcce14cf9a8..e628bb20e06 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/HttpDigestConverterTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/HttpDigestConverterTest.java @@ -17,17 +17,17 @@ public class HttpDigestConverterTest { @Test public void addsHttpDigestAuth() { Model model = Model.assembler() - .addImport(getClass().getResource("http-digest-security.json")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("http-digest-security.json")) + .discoverModels() + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create().config(config).convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("http-digest-security.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("http-digest-security.openapi.json") + ) ); Node.assertEquals(result, expectedNode); diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/XApiKeyTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/XApiKeyTest.java index be84fdea489..161ea700994 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/XApiKeyTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/fromsmithy/security/XApiKeyTest.java @@ -17,20 +17,20 @@ public class XApiKeyTest { @Test public void addsXApiKey() { Model model = Model.assembler() - .discoverModels() - .addImport(getClass().getResource("http-api-key-security.json")) - .assemble() - .unwrap(); + .discoverModels() + .addImport(getClass().getResource("http-api-key-security.json")) + .assemble() + .unwrap(); OpenApiConfig config = new OpenApiConfig(); config.setService(ShapeId.from("smithy.example#Service")); OpenApi result = OpenApiConverter.create() - .config(config) - .convert(model); + .config(config) + .convert(model); Node expectedNode = Node.parse( - IoUtils.toUtf8String( - getClass().getResourceAsStream("http-api-key-security.openapi.json") - ) + IoUtils.toUtf8String( + getClass().getResourceAsStream("http-api-key-security.openapi.json") + ) ); Node.assertEquals(result, expectedNode); diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/model/ExternalDocumentationTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/model/ExternalDocumentationTest.java index 7634af32783..98a82c4bd03 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/model/ExternalDocumentationTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/model/ExternalDocumentationTest.java @@ -14,18 +14,18 @@ class ExternalDocumentationTest { private static final ExternalDocumentation DOC_1 = ExternalDocumentation.builder() - .url("url1") - .description("description1") - .build(); + .url("url1") + .description("description1") + .build(); private static Stream testData() { return Stream.of( - Arguments.of(ExternalDocumentation.builder().url("url1").description("description1").build(), 0), - Arguments.of(ExternalDocumentation.builder().url("url1").description("description0").build(), 1), - Arguments.of(ExternalDocumentation.builder().url("url1").description("description2").build(), -1), - Arguments.of(ExternalDocumentation.builder().url("url0").description("description1").build(), 1), - Arguments.of(ExternalDocumentation.builder().url("url2").description("description1").build(), -1), - Arguments.of(ExternalDocumentation.builder().url("url1").build(), 1) + Arguments.of(ExternalDocumentation.builder().url("url1").description("description1").build(), 0), + Arguments.of(ExternalDocumentation.builder().url("url1").description("description0").build(), 1), + Arguments.of(ExternalDocumentation.builder().url("url1").description("description2").build(), -1), + Arguments.of(ExternalDocumentation.builder().url("url0").description("description1").build(), 1), + Arguments.of(ExternalDocumentation.builder().url("url2").description("description1").build(), -1), + Arguments.of(ExternalDocumentation.builder().url("url1").build(), 1) ); } diff --git a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/model/TagObjectTest.java b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/model/TagObjectTest.java index 5f5fc47bdd4..a9d0c0253c7 100644 --- a/smithy-openapi/src/test/java/software/amazon/smithy/openapi/model/TagObjectTest.java +++ b/smithy-openapi/src/test/java/software/amazon/smithy/openapi/model/TagObjectTest.java @@ -14,20 +14,20 @@ class TagObjectTest { private static final TagObject TAG_OBJECT_1 = TagObject.builder() - .name("tag1") - .description("description1") - .externalDocs(ExternalDocumentation.builder().url("url1").build()) - .build(); + .name("tag1") + .description("description1") + .externalDocs(ExternalDocumentation.builder().url("url1").build()) + .build(); private static Stream testData() { return Stream.of( - Arguments.of("tag1", "description1", ExternalDocumentation.builder().url("url1").build(), 0), - Arguments.of("tag0", "description1", ExternalDocumentation.builder().url("url1").build(), 1), - Arguments.of("tag1", "description1", ExternalDocumentation.builder().url("url2").build(), -1), - Arguments.of("tag2", "description1", ExternalDocumentation.builder().url("url1").build(), -1), - Arguments.of("tag1", "description2", ExternalDocumentation.builder().url("url1").build(), -1), - Arguments.of("tag1", null, ExternalDocumentation.builder().url("url1").build(), 1), - Arguments.of("tag1", "description1", null, 1) + Arguments.of("tag1", "description1", ExternalDocumentation.builder().url("url1").build(), 0), + Arguments.of("tag0", "description1", ExternalDocumentation.builder().url("url1").build(), 1), + Arguments.of("tag1", "description1", ExternalDocumentation.builder().url("url2").build(), -1), + Arguments.of("tag2", "description1", ExternalDocumentation.builder().url("url1").build(), -1), + Arguments.of("tag1", "description2", ExternalDocumentation.builder().url("url1").build(), -1), + Arguments.of("tag1", null, ExternalDocumentation.builder().url("url1").build(), 1), + Arguments.of("tag1", "description1", null, 1) ); } diff --git a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/AppliesTo.java b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/AppliesTo.java index 514d609ca81..f53746f2d7e 100644 --- a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/AppliesTo.java +++ b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/AppliesTo.java @@ -23,8 +23,8 @@ public String toString() { public static AppliesTo fromNode(Node node) { String value = node.expectStringNode() - .expectOneOf("client", "server") - .toUpperCase(Locale.ENGLISH); + .expectOneOf("client", "server") + .toUpperCase(Locale.ENGLISH); return AppliesTo.valueOf(value); } diff --git a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestDefinition.java b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestDefinition.java index b1ab626a264..dca9f863dfc 100644 --- a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestDefinition.java +++ b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestDefinition.java @@ -107,28 +107,28 @@ public static HttpMalformedRequestDefinition fromNode(Node node) { @Override public Node toNode() { return Node.objectNodeBuilder() - .withOptionalMember(BODY, getBody().map(Node::from)) - .withOptionalMember(BODY_MEDIA_TYPE, getBodyMediaType().map(Node::from)) - .withOptionalMember( - HEADERS, - headers.isEmpty() ? Optional.empty() : Optional.of(ObjectNode.fromStringMap(getHeaders())) - ) - .withOptionalMember(HOST, getHost().map(StringNode::from)) - .withMember(METHOD, getMethod()) - .withOptionalMember(URI, getUri().map(Node::from)) - .withOptionalMember( - QUERY_PARAMS, - queryParams.isEmpty() ? Optional.empty() : Optional.of(ArrayNode.fromStrings(getQueryParams())) - ) - .build(); + .withOptionalMember(BODY, getBody().map(Node::from)) + .withOptionalMember(BODY_MEDIA_TYPE, getBodyMediaType().map(Node::from)) + .withOptionalMember( + HEADERS, + headers.isEmpty() ? Optional.empty() : Optional.of(ObjectNode.fromStringMap(getHeaders())) + ) + .withOptionalMember(HOST, getHost().map(StringNode::from)) + .withMember(METHOD, getMethod()) + .withOptionalMember(URI, getUri().map(Node::from)) + .withOptionalMember( + QUERY_PARAMS, + queryParams.isEmpty() ? Optional.empty() : Optional.of(ArrayNode.fromStrings(getQueryParams())) + ) + .build(); } @Override public Builder toBuilder() { Builder builder = builder() - .headers(getHeaders()) - .method(getMethod()) - .queryParams(getQueryParams()); + .headers(getHeaders()) + .method(getMethod()) + .queryParams(getQueryParams()); getBody().ifPresent(builder::body); getBodyMediaType().ifPresent(builder::bodyMediaType); getHost().ifPresent(builder::host); diff --git a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestTestCase.java b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestTestCase.java index 7f03c208876..80b40da0040 100644 --- a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestTestCase.java +++ b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestTestCase.java @@ -70,11 +70,11 @@ public List getTags() { @Override public Builder toBuilder() { Builder builder = builder() - .id(getId()) - .protocol(getProtocol()) - .request(getRequest()) - .response(getResponse()) - .tags(getTags()); + .id(getId()) + .protocol(getProtocol()) + .request(getRequest()) + .response(getResponse()) + .tags(getTags()); getDocumentation().ifPresent(builder::documentation); return builder; } diff --git a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestTestsTrait.java b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestTestsTrait.java index bd4f71b73a9..4ee9df20700 100644 --- a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestTestsTrait.java +++ b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestTestsTrait.java @@ -28,8 +28,8 @@ public HttpMalformedRequestTestsTrait(List testCases + SourceLocation sourceLocation, + List testCases ) { super(ID, sourceLocation); this.testCases = ListUtils.copyOf(testCases); @@ -44,11 +44,11 @@ public Provider() { public Trait createTrait(ShapeId target, Node value) { ArrayNode values = value.expectArrayNode(); List testCases = values.getElementsAs( - ParameterizedHttpMalformedRequestTestCase::fromNode + ParameterizedHttpMalformedRequestTestCase::fromNode ); HttpMalformedRequestTestsTrait result = new HttpMalformedRequestTestsTrait( - value.getSourceLocation(), - testCases + value.getSourceLocation(), + testCases ); result.setNodeCache(value); return result; @@ -57,10 +57,10 @@ public Trait createTrait(ShapeId target, Node value) { public List getTestCases() { return testCases - .stream() - .map(ParameterizedHttpMalformedRequestTestCase::generateTestCasesFromParameters) - .flatMap(List::stream) - .collect(ListUtils.toUnmodifiableList()); + .stream() + .map(ParameterizedHttpMalformedRequestTestCase::generateTestCasesFromParameters) + .flatMap(List::stream) + .collect(ListUtils.toUnmodifiableList()); } /** diff --git a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestTestsValidator.java b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestTestsValidator.java index f84910e998d..b78bb659a03 100644 --- a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestTestsValidator.java +++ b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedRequestTestsValidator.java @@ -30,18 +30,18 @@ public List validate(Model model) { trait.getParameterizedTestCases().forEach(testCase -> { if (!testCase.getTestParameters().isEmpty()) { Set sizes = testCase.getTestParameters() - .values() - .stream() - .map(List::size) - .collect(Collectors.toSet()); + .values() + .stream() + .map(List::size) + .collect(Collectors.toSet()); if (sizes.size() != 1) { events.add( - error( - shape, - trait.getSourceLocation(), - "Each list associated to a key " - + "in `testParameters` must be of the same length." - ) + error( + shape, + trait.getSourceLocation(), + "Each list associated to a key " + + "in `testParameters` must be of the same length." + ) ); } } diff --git a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedResponseBodyDefinition.java b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedResponseBodyDefinition.java index 57f18ba5bcc..ab201ee9414 100644 --- a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedResponseBodyDefinition.java +++ b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedResponseBodyDefinition.java @@ -18,7 +18,7 @@ */ @SmithyUnstableApi public final class HttpMalformedResponseBodyDefinition - implements ToNode, ToSmithyBuilder { + implements ToNode, ToSmithyBuilder { private static final String ASSERTION = "assertion"; private static final String CONTENTS = "contents"; @@ -60,21 +60,21 @@ public static HttpMalformedResponseBodyDefinition fromNode(Node node) { @Override public Node toNode() { return Node.objectNodeBuilder() - .withMember(MEDIA_TYPE, getMediaType()) - .withMember( - ASSERTION, - ObjectNode.objectNodeBuilder() - .withOptionalMember(CONTENTS, getContents().map(StringNode::from)) - .withOptionalMember(MESSAGE_REGEX, getMessageRegex().map(StringNode::from)) - .build() - ) - .build(); + .withMember(MEDIA_TYPE, getMediaType()) + .withMember( + ASSERTION, + ObjectNode.objectNodeBuilder() + .withOptionalMember(CONTENTS, getContents().map(StringNode::from)) + .withOptionalMember(MESSAGE_REGEX, getMessageRegex().map(StringNode::from)) + .build() + ) + .build(); } @Override public Builder toBuilder() { Builder builder = builder() - .mediaType(getMediaType()); + .mediaType(getMediaType()); getContents().ifPresent(builder::mediaType); getMessageRegex().ifPresent(builder::messageRegex); return builder; diff --git a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedResponseDefinition.java b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedResponseDefinition.java index 90f5583e497..5aa9d9dd872 100644 --- a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedResponseDefinition.java +++ b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMalformedResponseDefinition.java @@ -63,20 +63,20 @@ public static HttpMalformedResponseDefinition fromNode(Node node) { @Override public Node toNode() { return Node.objectNodeBuilder() - .withOptionalMember(BODY, getBody().map(HttpMalformedResponseBodyDefinition::toNode)) - .withMember(CODE, getCode()) - .withOptionalMember( - HEADERS, - headers.isEmpty() ? Optional.empty() : Optional.of(ObjectNode.fromStringMap(getHeaders())) - ) - .build(); + .withOptionalMember(BODY, getBody().map(HttpMalformedResponseBodyDefinition::toNode)) + .withMember(CODE, getCode()) + .withOptionalMember( + HEADERS, + headers.isEmpty() ? Optional.empty() : Optional.of(ObjectNode.fromStringMap(getHeaders())) + ) + .build(); } @Override public Builder toBuilder() { Builder builder = builder() - .headers(getHeaders()) - .code(getCode()); + .headers(getHeaders()) + .code(getCode()); getBody().ifPresent(builder::body); return builder; } diff --git a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMessageTestCase.java b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMessageTestCase.java index 96916b78e78..4b433090076 100644 --- a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMessageTestCase.java +++ b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpMessageTestCase.java @@ -161,14 +161,14 @@ static void updateBuilderFromNode(Builder builder, Node node) { @Override public Node toNode() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withMember(ID, getId()) - .withMember(PROTOCOL, getProtocol().toString()) - .withOptionalMember(DOCUMENTATION, getDocumentation().map(Node::from)) - .withOptionalMember(AUTH_SCHEME, getAuthScheme().map(ShapeId::toString).map(Node::from)) - .withOptionalMember(BODY, getBody().map(Node::from)) - .withOptionalMember(BODY_MEDIA_TYPE, getBodyMediaType().map(Node::from)) - .withOptionalMember(APPLIES_TO, getAppliesTo()) - .withOptionalMember(VENDOR_PARAMS_SHAPE, getVendorParamsShape().map(ShapeId::toString).map(Node::from)); + .withMember(ID, getId()) + .withMember(PROTOCOL, getProtocol().toString()) + .withOptionalMember(DOCUMENTATION, getDocumentation().map(Node::from)) + .withOptionalMember(AUTH_SCHEME, getAuthScheme().map(ShapeId::toString).map(Node::from)) + .withOptionalMember(BODY, getBody().map(Node::from)) + .withOptionalMember(BODY_MEDIA_TYPE, getBodyMediaType().map(Node::from)) + .withOptionalMember(APPLIES_TO, getAppliesTo()) + .withOptionalMember(VENDOR_PARAMS_SHAPE, getVendorParamsShape().map(ShapeId::toString).map(Node::from)); if (!headers.isEmpty()) { builder.withMember(HEADERS, ObjectNode.fromStringMap(getHeaders())); @@ -215,20 +215,20 @@ public int hashCode() { void updateBuilder(Builder builder) { builder - .id(id) - .headers(headers) - .forbidHeaders(forbidHeaders) - .requireHeaders(requireHeaders) - .params(params) - .vendorParamsShape(vendorParamsShape) - .vendorParams(vendorParams) - .documentation(documentation) - .authScheme(authScheme) - .protocol(protocol) - .body(body) - .bodyMediaType(bodyMediaType) - .tags(tags) - .appliesTo(appliesTo); + .id(id) + .headers(headers) + .forbidHeaders(forbidHeaders) + .requireHeaders(requireHeaders) + .params(params) + .vendorParamsShape(vendorParamsShape) + .vendorParams(vendorParams) + .documentation(documentation) + .authScheme(authScheme) + .protocol(protocol) + .body(body) + .bodyMediaType(bodyMediaType) + .tags(tags) + .appliesTo(appliesTo); } abstract static class Builder, T extends HttpMessageTestCase> implements SmithyBuilder { diff --git a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpRequestTestCase.java b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpRequestTestCase.java index 58e6ba50c2e..a8ca00acbea 100644 --- a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpRequestTestCase.java +++ b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpRequestTestCase.java @@ -117,11 +117,11 @@ public Node toNode() { @Override public Builder toBuilder() { Builder builder = builder() - .method(getMethod()) - .uri(getUri()) - .queryParams(getQueryParams()) - .forbidQueryParams(getForbidQueryParams()) - .requireQueryParams(getRequireQueryParams()); + .method(getMethod()) + .uri(getUri()) + .queryParams(getQueryParams()) + .forbidQueryParams(getForbidQueryParams()) + .requireQueryParams(getRequireQueryParams()); getHost().ifPresent(builder::host); getResolvedHost().ifPresent(builder::resolvedHost); updateBuilder(builder); diff --git a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpRequestTestsTrait.java b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpRequestTestsTrait.java index dd0131d920a..b1990d45f0f 100644 --- a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpRequestTestsTrait.java +++ b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpRequestTestsTrait.java @@ -63,8 +63,8 @@ public List getTestCases() { */ public List getTestCasesFor(AppliesTo appliesTo) { return testCases.stream() - .filter(test -> !test.getAppliesTo().filter(value -> value != appliesTo).isPresent()) - .collect(Collectors.toList()); + .filter(test -> !test.getAppliesTo().filter(value -> value != appliesTo).isPresent()) + .collect(Collectors.toList()); } @Override diff --git a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpResponseTestsTrait.java b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpResponseTestsTrait.java index 00904118ec2..4f4f4bee6f6 100644 --- a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpResponseTestsTrait.java +++ b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/HttpResponseTestsTrait.java @@ -63,8 +63,8 @@ public List getTestCases() { */ public List getTestCasesFor(AppliesTo appliesTo) { return testCases.stream() - .filter(test -> !test.getAppliesTo().filter(value -> value != appliesTo).isPresent()) - .collect(Collectors.toList()); + .filter(test -> !test.getAppliesTo().filter(value -> value != appliesTo).isPresent()) + .collect(Collectors.toList()); } @Override diff --git a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/ParameterizedHttpMalformedRequestTestCase.java b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/ParameterizedHttpMalformedRequestTestCase.java index c487a219fe8..6db1771a435 100644 --- a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/ParameterizedHttpMalformedRequestTestCase.java +++ b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/ParameterizedHttpMalformedRequestTestCase.java @@ -33,7 +33,7 @@ */ @SmithyUnstableApi final class ParameterizedHttpMalformedRequestTestCase - implements Tagged, ToNode, ToSmithyBuilder { + implements Tagged, ToNode, ToSmithyBuilder { private static final String DOCUMENTATION = "documentation"; private static final String ID = "id"; @@ -93,20 +93,20 @@ public Map> getTestParameters() { public List generateTestCasesFromParameters() { if (testParameters.isEmpty()) { HttpMalformedRequestTestCase.Builder builder = HttpMalformedRequestTestCase.builder() - .id(getId()) - .protocol(getProtocol()) - .request(request) - .response(response) - .tags(getTags()); + .id(getId()) + .protocol(getProtocol()) + .request(request) + .response(response) + .tags(getTags()); getDocumentation().ifPresent(builder::documentation); return ListUtils.of(builder.build()); } int paramLength = testParameters.values() - .stream() - .findFirst() - .map(List::size) - .orElseThrow(IllegalStateException::new); + .stream() + .findFirst() + .map(List::size) + .orElseThrow(IllegalStateException::new); final List testCases = new ArrayList<>(paramLength); for (int i = 0; i < paramLength; i++) { final SimpleCodeWriter writer = new SimpleCodeWriter(); @@ -115,45 +115,45 @@ public List generateTestCasesFromParameters() { } HttpMalformedRequestTestCase.Builder builder = HttpMalformedRequestTestCase.builder() - .id(String.format(getId() + "_case%d", i)) - .protocol(getProtocol()) - .tags(getTags().stream().map(writer::format).collect(Collectors.toList())); + .id(String.format(getId() + "_case%d", i)) + .protocol(getProtocol()) + .tags(getTags().stream().map(writer::format).collect(Collectors.toList())); getDocumentation().map(writer::format).ifPresent(builder::documentation); testCases.add( - builder.request(interpolateRequest(request, writer)) - .response(interpolateResponse(response, writer)) - .build() + builder.request(interpolateRequest(request, writer)) + .response(interpolateResponse(response, writer)) + .build() ); } return testCases; } private static HttpMalformedResponseDefinition interpolateResponse( - HttpMalformedResponseDefinition response, - SimpleCodeWriter writer + HttpMalformedResponseDefinition response, + SimpleCodeWriter writer ) { HttpMalformedResponseDefinition.Builder responseBuilder = response.toBuilder() - .headers(formatHeaders(writer, response.getHeaders())); + .headers(formatHeaders(writer, response.getHeaders())); response.getBody() - .map(responseBody -> { - HttpMalformedResponseBodyDefinition.Builder bodyBuilder = responseBody.toBuilder() - .mediaType(writer.format(responseBody.getMediaType())); - responseBody.getContents().map(writer::format).ifPresent(bodyBuilder::contents); - responseBody.getMessageRegex().map(writer::format).ifPresent(bodyBuilder::messageRegex); - return bodyBuilder.build(); - }) - .ifPresent(responseBuilder::body); + .map(responseBody -> { + HttpMalformedResponseBodyDefinition.Builder bodyBuilder = responseBody.toBuilder() + .mediaType(writer.format(responseBody.getMediaType())); + responseBody.getContents().map(writer::format).ifPresent(bodyBuilder::contents); + responseBody.getMessageRegex().map(writer::format).ifPresent(bodyBuilder::messageRegex); + return bodyBuilder.build(); + }) + .ifPresent(responseBuilder::body); return responseBuilder.build(); } private static HttpMalformedRequestDefinition interpolateRequest( - HttpMalformedRequestDefinition request, - SimpleCodeWriter writer + HttpMalformedRequestDefinition request, + SimpleCodeWriter writer ) { HttpMalformedRequestDefinition.Builder requestBuilder = request.toBuilder() - .headers(formatHeaders(writer, request.getHeaders())) - .queryParams(request.getQueryParams().stream().map(writer::format).collect(Collectors.toList())); + .headers(formatHeaders(writer, request.getHeaders())) + .queryParams(request.getQueryParams().stream().map(writer::format).collect(Collectors.toList())); request.getBody().map(writer::format).ifPresent(requestBuilder::body); request.getUri().map(writer::format).ifPresent(requestBuilder::uri); return requestBuilder.build(); @@ -182,8 +182,8 @@ public static ParameterizedHttpMalformedRequestTestCase fromNode(Node node) { Map> paramsMap = new HashMap<>(); for (Map.Entry e : params.getStringMap().entrySet()) { paramsMap.put( - e.getKey(), - e.getValue().expectArrayNode().getElementsAs(n -> n.expectStringNode().getValue()) + e.getKey(), + e.getValue().expectArrayNode().getElementsAs(n -> n.expectStringNode().getValue()) ); } builder.testParameters(paramsMap); @@ -194,11 +194,11 @@ public static ParameterizedHttpMalformedRequestTestCase fromNode(Node node) { @Override public Node toNode() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withOptionalMember(DOCUMENTATION, getDocumentation().map(Node::from)) - .withMember(ID, getId()) - .withMember(PROTOCOL, getProtocol().toString()) - .withMember(REQUEST, getRequest().toNode()) - .withMember(RESPONSE, getResponse().toNode()); + .withOptionalMember(DOCUMENTATION, getDocumentation().map(Node::from)) + .withMember(ID, getId()) + .withMember(PROTOCOL, getProtocol().toString()) + .withMember(REQUEST, getRequest().toNode()) + .withMember(RESPONSE, getResponse().toNode()); if (!tags.isEmpty()) { builder.withMember(TAGS, ArrayNode.fromStrings(getTags())); @@ -216,12 +216,12 @@ public Node toNode() { @Override public Builder toBuilder() { Builder builder = builder() - .id(getId()) - .protocol(getProtocol()) - .request(getRequest()) - .response(getResponse()) - .tags(getTags()) - .testParameters(getTestParameters()); + .id(getId()) + .protocol(getProtocol()) + .request(getRequest()) + .response(getResponse()) + .tags(getTags()) + .testParameters(getTestParameters()); getDocumentation().ifPresent(builder::documentation); return builder; } diff --git a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/ProtocolTestCaseValidator.java b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/ProtocolTestCaseValidator.java index 0c066a6394f..fb2dc09fa38 100644 --- a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/ProtocolTestCaseValidator.java +++ b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/ProtocolTestCaseValidator.java @@ -89,10 +89,10 @@ boolean isValidatedBy(Shape shape) { } private List validateShape( - Model model, - OperationIndex operationIndex, - Shape shape, - T trait + Model model, + OperationIndex operationIndex, + Shape shape, + T trait ) { List events = new ArrayList<>(); List testCases = getTestCases(trait); @@ -110,21 +110,21 @@ private List validateShape( if (vendorParams.isEmpty()) { // Warn if vendorParamsShape is set on the case and no vendorParams is set. events.add( - warning( - shape, - trait, - "Protocol test case defined a `vendorParamsShape` but no `vendorParams`" - ) + warning( + shape, + trait, + "Protocol test case defined a `vendorParamsShape` but no `vendorParams`" + ) ); } else { // Otherwise, validate the params against the shape. Shape vendorParamsShape = model.expectShape(vendorParamsShapeOptional.get()); NodeValidationVisitor vendorParamsValidator = createVisitor( - vendorParams, - model, - shape, - i, - ".vendorParams" + vendorParams, + model, + shape, + i, + ".vendorParams" ); events.addAll(vendorParamsShape.accept(vendorParamsValidator)); } @@ -137,16 +137,16 @@ private List validateShape( events.addAll(struct.accept(validator)); } else if (!testCase.getParams().isEmpty() && isValidatedBy(shape)) { events.add( - error( - shape, - trait, - String.format( - "Protocol test %s parameters provided for operation with no %s: `%s`", - descriptor, - descriptor, - Node.printJson(testCase.getParams()) + error( + shape, + trait, + String.format( + "Protocol test %s parameters provided for operation with no %s: `%s`", + descriptor, + descriptor, + Node.printJson(testCase.getParams()) + ) ) - ) ); } } @@ -155,21 +155,21 @@ private List validateShape( } private NodeValidationVisitor createVisitor( - ObjectNode value, - Model model, - Shape shape, - int position, - String contextSuffix + ObjectNode value, + Model model, + Shape shape, + int position, + String contextSuffix ) { return NodeValidationVisitor.builder() - .model(model) - .eventShapeId(shape.getId()) - .value(value) - .startingContext(traitId + "." + position + contextSuffix) - .eventId(getName()) - .timestampValidationStrategy(TimestampValidationStrategy.EPOCH_SECONDS) - .addFeature(NodeValidationVisitor.Feature.ALLOW_OPTIONAL_NULLS) - .build(); + .model(model) + .eventShapeId(shape.getId()) + .value(value) + .startingContext(traitId + "." + position + contextSuffix) + .eventId(getName()) + .timestampValidationStrategy(TimestampValidationStrategy.EPOCH_SECONDS) + .addFeature(NodeValidationVisitor.Feature.ALLOW_OPTIONAL_NULLS) + .build(); } private List validateMediaType(Shape shape, Trait trait, HttpMessageTestCase test) { @@ -220,15 +220,15 @@ private Optional validateJson(Shape shape, Trait trait, HttpMes private ValidationEvent emitMediaTypeError(Shape shape, Trait trait, HttpMessageTestCase test, Throwable e) { return danger( - shape, - trait, - String.format( - "Invalid %s content in `%s` protocol test case `%s`: %s", - test.getBodyMediaType().orElse(""), - trait.toShapeId(), - test.getId(), - e.getMessage() - ) + shape, + trait, + String.format( + "Invalid %s content in `%s` protocol test case `%s`: %s", + test.getBodyMediaType().orElse(""), + trait.toShapeId(), + test.getId(), + e.getMessage() + ) ); } } diff --git a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/UniqueProtocolTestCaseIdValidator.java b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/UniqueProtocolTestCaseIdValidator.java index 0b49c8367b7..45cc8c16b65 100644 --- a/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/UniqueProtocolTestCaseIdValidator.java +++ b/smithy-protocol-test-traits/src/main/java/software/amazon/smithy/protocoltests/traits/UniqueProtocolTestCaseIdValidator.java @@ -36,13 +36,13 @@ public List validate(Model model) { Stream.concat(model.shapes(OperationShape.class), model.shapes(StructureShape.class)).forEach(shape -> { shape.getTrait(HttpRequestTestsTrait.class) - .ifPresent(trait -> addTestCaseIdsToMap(shape, trait.getTestCases(), requestIdsToTraits)); + .ifPresent(trait -> addTestCaseIdsToMap(shape, trait.getTestCases(), requestIdsToTraits)); shape.getTrait(HttpResponseTestsTrait.class) - .ifPresent(trait -> addTestCaseIdsToMap(shape, trait.getTestCases(), responseIdsToTraits)); + .ifPresent(trait -> addTestCaseIdsToMap(shape, trait.getTestCases(), responseIdsToTraits)); // This deliberately uses the expanded, instead of parameterized test cases, // in case someone does something wild with naming, like add _case0 to the end of the id shape.getTrait(HttpMalformedRequestTestsTrait.class) - .ifPresent(t -> addMalformedRequestTestCaseIdsToMap(shape, t.getTestCases(), responseIdsToTraits)); + .ifPresent(t -> addMalformedRequestTestCaseIdsToMap(shape, t.getTestCases(), responseIdsToTraits)); }); removeEntriesWithSingleValue(requestIdsToTraits); @@ -53,9 +53,9 @@ public List validate(Model model) { } private void addTestCaseIdsToMap( - Shape shape, - List testCases, - Map> map + Shape shape, + List testCases, + Map> map ) { for (HttpMessageTestCase testCase : testCases) { map.computeIfAbsent(testCase.getId(), id -> new ArrayList<>()).add(shape); @@ -63,9 +63,9 @@ private void addTestCaseIdsToMap( } private void addMalformedRequestTestCaseIdsToMap( - Shape shape, - List testCases, - Map> map + Shape shape, + List testCases, + Map> map ) { for (HttpMalformedRequestTestCase testCase : testCases) { map.computeIfAbsent(testCase.getId(), id -> new ArrayList<>()).add(shape); @@ -77,9 +77,9 @@ private void removeEntriesWithSingleValue(Map> map) { } private List collectEvents( - Map> requestIdsToTraits, - Map> responseIdsToTraits, - Map> malformedRequestIdsToTraits + Map> requestIdsToTraits, + Map> responseIdsToTraits, + Map> malformedRequestIdsToTraits ) { if (requestIdsToTraits.isEmpty() && responseIdsToTraits.isEmpty() && malformedRequestIdsToTraits.isEmpty()) { return Collections.emptyList(); @@ -93,22 +93,22 @@ private List collectEvents( } private void addValidationEvents( - Map> conflicts, - List mutableEvents, - ShapeId trait + Map> conflicts, + List mutableEvents, + ShapeId trait ) { for (Map.Entry> entry : conflicts.entrySet()) { for (Shape shape : entry.getValue()) { mutableEvents.add( - error( - shape, - String.format( - "Conflicting `%s` test case IDs found for ID `%s`: %s", - trait, - entry.getKey(), - ValidationUtils.tickedList(entry.getValue().stream().map(Shape::getId)) + error( + shape, + String.format( + "Conflicting `%s` test case IDs found for ID `%s`: %s", + trait, + entry.getKey(), + ValidationUtils.tickedList(entry.getValue().stream().map(Shape::getId)) + ) ) - ) ); } } diff --git a/smithy-protocol-test-traits/src/test/java/software/amazon/smithy/protocoltests/traits/TraitTest.java b/smithy-protocol-test-traits/src/test/java/software/amazon/smithy/protocoltests/traits/TraitTest.java index 1ead8e6a45b..3e0330417e8 100644 --- a/smithy-protocol-test-traits/src/test/java/software/amazon/smithy/protocoltests/traits/TraitTest.java +++ b/smithy-protocol-test-traits/src/test/java/software/amazon/smithy/protocoltests/traits/TraitTest.java @@ -24,24 +24,24 @@ public class TraitTest { @BeforeAll public static void before() { appliesToModel = Model.assembler() - .discoverModels() - .addImport(TraitTest.class.getResource("test-with-appliesto.smithy")) - .assemble() - .unwrap(); + .discoverModels() + .addImport(TraitTest.class.getResource("test-with-appliesto.smithy")) + .assemble() + .unwrap(); } @Test public void simpleRequestTest() { Model model = Model.assembler() - .addImport(getClass().getResource("say-hello.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("say-hello.smithy")) + .discoverModels() + .assemble() + .unwrap(); HttpRequestTestCase testCase = model.expectShape(ShapeId.from("smithy.example#SayHello")) - .getTrait(HttpRequestTestsTrait.class) - .get() - .getTestCases() - .get(0); + .getTrait(HttpRequestTestsTrait.class) + .get() + .getTestCases() + .get(0); assertThat(testCase.toBuilder().build(), equalTo(testCase)); assertThat(HttpRequestTestCase.fromNode(testCase.toNode()), equalTo(testCase)); @@ -50,15 +50,15 @@ public void simpleRequestTest() { @Test public void simpleResponseTest() { Model model = Model.assembler() - .addImport(getClass().getResource("say-goodbye.smithy")) - .discoverModels() - .assemble() - .unwrap(); + .addImport(getClass().getResource("say-goodbye.smithy")) + .discoverModels() + .assemble() + .unwrap(); HttpResponseTestCase testCase = model.expectShape(ShapeId.from("smithy.example#SayGoodbye")) - .getTrait(HttpResponseTestsTrait.class) - .get() - .getTestCases() - .get(0); + .getTrait(HttpResponseTestsTrait.class) + .get() + .getTestCases() + .get(0); assertThat(testCase.toBuilder().build(), equalTo(testCase)); assertThat(HttpResponseTestCase.fromNode(testCase.toNode()), equalTo(testCase)); @@ -67,20 +67,20 @@ public void simpleResponseTest() { @Test public void messageHasTags() { Model model = Model.assembler() - .discoverModels() - .addImport(getClass().getResource("test-with-tags.smithy")) - .assemble() - .unwrap(); + .discoverModels() + .addImport(getClass().getResource("test-with-tags.smithy")) + .assemble() + .unwrap(); HttpRequestTestCase request = model.expectShape(ShapeId.from("smithy.example#SaySomething")) - .getTrait(HttpRequestTestsTrait.class) - .get() - .getTestCases() - .get(0); + .getTrait(HttpRequestTestsTrait.class) + .get() + .getTestCases() + .get(0); HttpResponseTestCase response = model.expectShape(ShapeId.from("smithy.example#SaySomething")) - .getTrait(HttpResponseTestsTrait.class) - .get() - .getTestCases() - .get(0); + .getTrait(HttpResponseTestsTrait.class) + .get() + .getTestCases() + .get(0); assertThat(request.getTags(), contains("foo", "bar")); assertThat(request.toBuilder().build().getTags(), contains("foo", "bar")); @@ -97,7 +97,7 @@ public void messageHasTags() { @Test public void messageHasAppliesTo() { HttpRequestTestsTrait requestTrait = appliesToModel.expectShape(ShapeId.from("smithy.example#SaySomething")) - .expectTrait(HttpRequestTestsTrait.class); + .expectTrait(HttpRequestTestsTrait.class); HttpRequestTestCase request = requestTrait.getTestCases().get(1); assertThat(request.getAppliesTo().isPresent(), is(true)); @@ -106,7 +106,7 @@ public void messageHasAppliesTo() { assertThat(HttpRequestTestCase.fromNode(request.toNode()), equalTo(request)); HttpResponseTestsTrait responseTrait = appliesToModel.expectShape(ShapeId.from("smithy.example#SaySomething")) - .expectTrait(HttpResponseTestsTrait.class); + .expectTrait(HttpResponseTestsTrait.class); HttpResponseTestCase response = responseTrait.getTestCases().get(1); assertThat(response.getAppliesTo().isPresent(), is(true)); @@ -118,32 +118,32 @@ public void messageHasAppliesTo() { @Test public void canFilterTestsByAppliesTo() { HttpRequestTestsTrait requestTrait = appliesToModel.expectShape(ShapeId.from("smithy.example#SaySomething")) - .expectTrait(HttpRequestTestsTrait.class); + .expectTrait(HttpRequestTestsTrait.class); HttpResponseTestsTrait responseTrait = appliesToModel.expectShape(ShapeId.from("smithy.example#SaySomething")) - .expectTrait(HttpResponseTestsTrait.class); + .expectTrait(HttpResponseTestsTrait.class); assertThat( - getCaseIds(requestTrait.getTestCasesFor(AppliesTo.CLIENT)), - containsInAnyOrder("say_hello_all", "say_hello_client") + getCaseIds(requestTrait.getTestCasesFor(AppliesTo.CLIENT)), + containsInAnyOrder("say_hello_all", "say_hello_client") ); assertThat( - getCaseIds(requestTrait.getTestCasesFor(AppliesTo.SERVER)), - containsInAnyOrder("say_hello_all", "say_hello_server") + getCaseIds(requestTrait.getTestCasesFor(AppliesTo.SERVER)), + containsInAnyOrder("say_hello_all", "say_hello_server") ); assertThat( - getCaseIds(responseTrait.getTestCasesFor(AppliesTo.CLIENT)), - containsInAnyOrder("say_goodbye_all", "say_goodbye_client") + getCaseIds(responseTrait.getTestCasesFor(AppliesTo.CLIENT)), + containsInAnyOrder("say_goodbye_all", "say_goodbye_client") ); assertThat( - getCaseIds(responseTrait.getTestCasesFor(AppliesTo.SERVER)), - containsInAnyOrder("say_goodbye_all", "say_goodbye_server") + getCaseIds(responseTrait.getTestCasesFor(AppliesTo.SERVER)), + containsInAnyOrder("say_goodbye_all", "say_goodbye_server") ); } private List getCaseIds(List cases) { return cases.stream() - .map(HttpMessageTestCase::getId) - .collect(Collectors.toList()); + .map(HttpMessageTestCase::getId) + .collect(Collectors.toList()); } } diff --git a/smithy-protocol-traits/src/main/java/software/amazon/smithy/protocol/traits/Rpcv2CborTrait.java b/smithy-protocol-traits/src/main/java/software/amazon/smithy/protocol/traits/Rpcv2CborTrait.java index 7420fc23508..122a04dd79c 100644 --- a/smithy-protocol-traits/src/main/java/software/amazon/smithy/protocol/traits/Rpcv2CborTrait.java +++ b/smithy-protocol-traits/src/main/java/software/amazon/smithy/protocol/traits/Rpcv2CborTrait.java @@ -48,11 +48,11 @@ public static Rpcv2CborTrait fromNode(Node node) { Builder builder = builder().sourceLocation(node); ObjectNode objectNode = node.expectObjectNode(); objectNode.getArrayMember(HTTP) - .map(values -> Node.loadArrayOfString(HTTP, values)) - .ifPresent(builder::http); + .map(values -> Node.loadArrayOfString(HTTP, values)) + .ifPresent(builder::http); objectNode.getArrayMember(EVENT_STREAM_HTTP) - .map(values -> Node.loadArrayOfString(EVENT_STREAM_HTTP, values)) - .ifPresent(builder::eventStreamHttp); + .map(values -> Node.loadArrayOfString(EVENT_STREAM_HTTP, values)) + .ifPresent(builder::eventStreamHttp); return builder.build(); } diff --git a/smithy-protocol-traits/src/main/java/software/amazon/smithy/protocol/traits/Rpcv2CborTraitValidator.java b/smithy-protocol-traits/src/main/java/software/amazon/smithy/protocol/traits/Rpcv2CborTraitValidator.java index 2da6d434270..c477b7ad681 100644 --- a/smithy-protocol-traits/src/main/java/software/amazon/smithy/protocol/traits/Rpcv2CborTraitValidator.java +++ b/smithy-protocol-traits/src/main/java/software/amazon/smithy/protocol/traits/Rpcv2CborTraitValidator.java @@ -31,17 +31,17 @@ public List validate(Model model) { invalid.removeAll(protocolTrait.getHttp()); if (!invalid.isEmpty()) { events.add( - error( - serviceShape, - protocolTrait, - String.format( - "The following values of the `eventStreamHttp` property do " - + "not also appear in the `http` property of the %s protocol " - + "trait: %s", - protocolTrait.toShapeId(), - invalid + error( + serviceShape, + protocolTrait, + String.format( + "The following values of the `eventStreamHttp` property do " + + "not also appear in the `http` property of the %s protocol " + + "trait: %s", + protocolTrait.toShapeId(), + invalid + ) ) - ) ); } } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/analysis/CoverageChecker.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/analysis/CoverageChecker.java index b74dcd934e7..83822673632 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/analysis/CoverageChecker.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/analysis/CoverageChecker.java @@ -150,7 +150,7 @@ public boolean getResult() { */ public String pretty() { return "leaf: " + condition + "(" + condition.getSourceLocation().getFilename() + ":" - + condition.getSourceLocation().getLine() + ")"; + + condition.getSourceLocation().getLine() + ")"; } } } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/analysis/OperationContextParamsChecker.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/analysis/OperationContextParamsChecker.java index 83b116e4b83..599b9b12895 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/analysis/OperationContextParamsChecker.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/analysis/OperationContextParamsChecker.java @@ -54,9 +54,9 @@ private OperationContextParamsChecker() { } public static LinterResult lint( - OperationContextParamDefinition paramDefinition, - OperationShape operationShape, - Model model + OperationContextParamDefinition paramDefinition, + OperationShape operationShape, + Model model ) { JmespathExpression path = JmespathExpression.parse(paramDefinition.getPath()); StructureShape input = OperationIndex.of(model).expectInputShape(operationShape); @@ -64,9 +64,9 @@ public static LinterResult lint( } public static Optional inferParameterType( - OperationContextParamDefinition paramDefinition, - OperationShape operationShape, - Model model + OperationContextParamDefinition paramDefinition, + OperationShape operationShape, + Model model ) { RuntimeType runtimeType = lint(paramDefinition, operationShape, model).getReturnType(); switch (runtimeType) { @@ -83,8 +83,8 @@ public static Optional inferParameterType( private static LiteralExpression createCurrentNodeFromShape(Shape shape, Model model) { return shape == null - ? LiteralExpression.ANY - : new LiteralExpression(shape.accept(new ModelRuntimeTypeGenerator(model))); + ? LiteralExpression.ANY + : new LiteralExpression(shape.accept(new ModelRuntimeTypeGenerator(model))); } /** @@ -237,10 +237,10 @@ public Object memberShape(MemberShape shape) { } return model.getShape(shape.getTarget()) - .map(target -> target.accept(this)) - // Rather than fail on broken models during waiter validation, - // return an ANY to get *some* validation. - .orElse(LiteralExpression.ANY); + .map(target -> target.accept(this)) + // Rather than fail on broken models during waiter validation, + // return an ANY to get *some* validation. + .orElse(LiteralExpression.ANY); } @Override diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/CoreExtension.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/CoreExtension.java index ff9447b4466..e7328277f22 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/CoreExtension.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/CoreExtension.java @@ -31,15 +31,15 @@ public List getBuiltIns() { @Override public List getLibraryFunctions() { return ListUtils.of( - BooleanEquals.getDefinition(), - GetAttr.getDefinition(), - IsSet.getDefinition(), - IsValidHostLabel.getDefinition(), - Not.getDefinition(), - ParseUrl.getDefinition(), - StringEquals.getDefinition(), - Substring.getDefinition(), - UriEncode.getDefinition() + BooleanEquals.getDefinition(), + GetAttr.getDefinition(), + IsSet.getDefinition(), + IsValidHostLabel.getDefinition(), + Not.getDefinition(), + ParseUrl.getDefinition(), + StringEquals.getDefinition(), + Substring.getDefinition(), + UriEncode.getDefinition() ); } } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/Endpoint.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/Endpoint.java index ada6f516f5a..e405f3a0e28 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/Endpoint.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/Endpoint.java @@ -93,10 +93,10 @@ public static Endpoint fromNode(Node node) { objectNode.getObjectMember(HEADERS, headers -> { for (Map.Entry header : headers.getStringMap().entrySet()) { builder.putHeader( - header.getKey(), - header.getValue() - .expectArrayNode("header values should be an array") - .getElementsAs(Expression::fromNode) + header.getKey(), + header.getValue() + .expectArrayNode("header values should be an array") + .getElementsAs(Expression::fromNode) ); } }); @@ -152,14 +152,14 @@ public Map getProperties() { */ public List> getEndpointAuthSchemes() { return Optional.ofNullable(getProperties().get(ID_AUTH_SCHEMES)) - .map( - a -> a.asTupleLiteral() - .get() - .stream() - .map(l -> l.asRecordLiteral().get()) - .collect(Collectors.toList()) - ) - .orElse(Collections.emptyList()); + .map( + a -> a.asTupleLiteral() + .get() + .stream() + .map(l -> l.asRecordLiteral().get()) + .collect(Collectors.toList()) + ) + .orElse(Collections.emptyList()); } @Override @@ -184,10 +184,10 @@ public Node toNode() { } return ObjectNode.builder() - .withMember(URL, url) - .withMember(PROPERTIES, propertiesBuilder.build()) - .withMember(HEADERS, headersBuilder.build()) - .build(); + .withMember(URL, url) + .withMember(PROPERTIES, propertiesBuilder.build()) + .withMember(HEADERS, headersBuilder.build()) + .build(); } @Override @@ -216,7 +216,7 @@ public String toString() { sb.append("headers:\n"); for (Map.Entry> entry : headers.entrySet()) { sb.append(StringUtils.indent(String.format("%s: %s", entry.getKey(), entry.getValue()), 2)) - .append("\n"); + .append("\n"); } } @@ -224,7 +224,7 @@ public String toString() { sb.append("properties:\n"); for (Map.Entry entry : properties.entrySet()) { sb.append(StringUtils.indent(String.format("%s: %s", entry.getKey(), entry.getValue()), 2)) - .append("\n"); + .append("\n"); } } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/EndpointComponentFactory.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/EndpointComponentFactory.java index ee8604f2aa1..6dec776cb36 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/EndpointComponentFactory.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/EndpointComponentFactory.java @@ -54,9 +54,9 @@ public interface EndpointComponentFactory { List getAuthSchemeValidators(); static EndpointComponentFactory createServiceFactory( - Map builtIns, - Map libraryFunctions, - List authSchemeValidators + Map builtIns, + Map libraryFunctions, + List authSchemeValidators ) { return new EndpointComponentFactory() { @Override diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/EndpointRuleSet.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/EndpointRuleSet.java index b6742b0e576..356f62c95bf 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/EndpointRuleSet.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/EndpointRuleSet.java @@ -51,7 +51,7 @@ public final class EndpointRuleSet implements FromSourceLocation, ToNode, ToSmit private static final class LazyEndpointComponentFactoryHolder { static final EndpointComponentFactory INSTANCE = EndpointComponentFactory.createServiceFactory( - EndpointRuleSet.class.getClassLoader() + EndpointRuleSet.class.getClassLoader() ); } @@ -149,10 +149,10 @@ public Type typeCheck(Scope scope) { @Override public Builder toBuilder() { return builder() - .sourceLocation(getSourceLocation()) - .parameters(parameters) - .rules(rules) - .version(version); + .sourceLocation(getSourceLocation()) + .parameters(parameters) + .rules(rules) + .version(version); } @Override @@ -161,10 +161,10 @@ public Node toNode() { rules.forEach(rulesBuilder::withValue); return ObjectNode.builder() - .withMember(VERSION, version) - .withMember(PARAMETERS, parameters) - .withMember(RULES, rulesBuilder.build()) - .build(); + .withMember(VERSION, version) + .withMember(PARAMETERS, parameters) + .withMember(RULES, rulesBuilder.build()) + .build(); } @Override @@ -356,13 +356,13 @@ public Map collect() { private void objectNode(ObjectNode node, String parentPath) { boolean isEndpointRuleObject = node - .getMember(TYPE) - .map( - n -> n.asStringNode() - .map(s -> s.getValue().equals(ENDPOINT)) - .orElse(false) - ) - .orElse(false); + .getMember(TYPE) + .map( + n -> n.asStringNode() + .map(s -> s.getValue().equals(ENDPOINT)) + .orElse(false) + ) + .orElse(false); if (isEndpointRuleObject) { Endpoint endpoint = Endpoint.fromNode(node.expectMember(ENDPOINT)); visitedEndpoints.put(parentPath + "/" + ENDPOINT, endpoint); diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/RulesComponentBuilder.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/RulesComponentBuilder.java index c71013694a0..24e6d1401fd 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/RulesComponentBuilder.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/RulesComponentBuilder.java @@ -17,7 +17,7 @@ */ @SmithyUnstableApi public abstract class RulesComponentBuilder, T> - implements SmithyBuilder, FromSourceLocation { + implements SmithyBuilder, FromSourceLocation { private SourceLocation sourceLocation; @@ -85,8 +85,8 @@ public static SourceLocation javaLocation() { static boolean isStackTraceRelevant(StackTraceElement e) { String normalized = e.getClassName().replace("$", "."); return !normalized.startsWith("java.") - && !normalized.startsWith("jdk.") - && !normalized.startsWith(RulesComponentBuilder.class.getCanonicalName()) - && !normalized.startsWith("software.amazon.smithy.rulesengine"); + && !normalized.startsWith("jdk.") + && !normalized.startsWith(RulesComponentBuilder.class.getCanonicalName()) + && !normalized.startsWith("software.amazon.smithy.rulesengine"); } } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/TraversingVisitor.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/TraversingVisitor.java index dba0ac5a85d..97b22050cbb 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/TraversingVisitor.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/TraversingVisitor.java @@ -20,7 +20,7 @@ */ @SmithyUnstableApi public class TraversingVisitor extends ExpressionVisitor.Default> - implements RuleValueVisitor> { + implements RuleValueVisitor> { /** * Given an {@link EndpointRuleSet} will invoke the visitor methods for each rule. @@ -65,8 +65,8 @@ public Stream visitEndpointRule(Endpoint endpoint) { */ public Stream visitEndpoint(Endpoint endpoint) { return Stream.concat( - endpoint.getUrl().accept(this), - endpoint.getProperties().values().stream().flatMap(value -> value.accept(this)) + endpoint.getUrl().accept(this), + endpoint.getProperties().values().stream().flatMap(value -> value.accept(this)) ); } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/error/RuleError.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/error/RuleError.java index f25d6f1ec54..8207dd475b0 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/error/RuleError.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/error/RuleError.java @@ -80,9 +80,9 @@ public static void context(String message, FromSourceLocation sourceLocation, Ru * @throws RuleError when the rule being evaluated in the context fails. */ public static T context( - String message, - FromSourceLocation sourceLocation, - Evaluator runnable + String message, + FromSourceLocation sourceLocation, + Evaluator runnable ) throws RuleError { try { return runnable.call(); @@ -95,7 +95,7 @@ public static T context( throw new RuntimeException(ex); } throw new RuleError(new SourceException(ex.getMessage(), sourceLocation.getSourceLocation(), ex)) - .withContext(message, sourceLocation.getSourceLocation()); + .withContext(message, sourceLocation.getSourceLocation()); } } @@ -121,10 +121,10 @@ public String toString() { message.append(System.lineSeparator()); if (context.right != SourceLocation.NONE && context.right != lastLoc) { message.append(" at ") - .append(context.right.getSourceLocation().getFilename()) - .append(":") - .append(context.right.getSourceLocation().getLine()) - .append(System.lineSeparator()); + .append(context.right.getSourceLocation().getFilename()) + .append(":") + .append(context.right.getSourceLocation().getLine()) + .append(System.lineSeparator()); lastLoc = context.right; } } @@ -132,10 +132,10 @@ public String toString() { message.append(root.getMessageWithoutLocation()); if (root.getSourceLocation() != SourceLocation.none() && root.getSourceLocation() != lastLoc) { message.append(System.lineSeparator()) - .append(" at ") - .append(root.getSourceLocation().getFilename()) - .append(":") - .append(root.getSourceLocation().getLine()); + .append(" at ") + .append(root.getSourceLocation().getFilename()) + .append(":") + .append(root.getSourceLocation().getLine()); } return message.toString(); } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/RuleEvaluator.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/RuleEvaluator.java index 629750ebde5..6cb86749976 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/RuleEvaluator.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/RuleEvaluator.java @@ -92,8 +92,8 @@ public Value visitLiteral(Literal literal) { @Override public Value visitRef(Reference reference) { return scope - .getValue(reference.getName()) - .orElse(Value.emptyValue()); + .getValue(reference.getName()) + .orElse(Value.emptyValue()); } @Override @@ -109,18 +109,18 @@ public Value visitNot(Expression not) { @Override public Value visitBoolEquals(Expression left, Expression right) { return Value.booleanValue( - left.accept(this) - .expectBooleanValue() - .equals(right.accept(this).expectBooleanValue()) + left.accept(this) + .expectBooleanValue() + .equals(right.accept(this).expectBooleanValue()) ); } @Override public Value visitStringEquals(Expression left, Expression right) { return Value.booleanValue( - left.accept(this) - .expectStringValue() - .equals(right.accept(this).expectStringValue()) + left.accept(this) + .expectStringValue() + .equals(right.accept(this).expectStringValue()) ); } @@ -158,7 +158,7 @@ public Value visitTreeRule(List rules) { } } throw new RuntimeException( - String.format("no rules inside of tree rule matched—invalid rules (%s)", rule) + String.format("no rules inside of tree rule matched—invalid rules (%s)", rule) ); } @@ -170,13 +170,13 @@ public Value visitErrorRule(Expression error) { @Override public Value visitEndpointRule(Endpoint endpoint) { EndpointValue.Builder builder = EndpointValue.builder() - .sourceLocation(endpoint) - .url( - endpoint.getUrl() - .accept(RuleEvaluator.this) - .expectStringValue() - .getValue() - ); + .sourceLocation(endpoint) + .url( + endpoint.getUrl() + .accept(RuleEvaluator.this) + .expectStringValue() + .getValue() + ); for (Map.Entry entry : endpoint.getProperties().entrySet()) { builder.putProperty(entry.getKey().toString(), entry.getValue().accept(RuleEvaluator.this)); diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/ScopeLayer.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/ScopeLayer.java index 37f0cec8008..f553c7a6e0d 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/ScopeLayer.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/ScopeLayer.java @@ -71,7 +71,7 @@ public int hashCode() { @Override public String toString() { return "ScopeLayer[" - + "types=" + types + ", " - + "facts=" + nonNullReferences + ']'; + + "types=" + types + ", " + + "facts=" + nonNullReferences + ']'; } } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/TestEvaluator.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/TestEvaluator.java index 5507d3eefcd..dce69c1e14a 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/TestEvaluator.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/TestEvaluator.java @@ -55,20 +55,20 @@ private static void evaluateExpectation(EndpointTestExpectation expected, Value if (expected.getEndpoint().isPresent()) { ExpectedEndpoint expectedEndpoint = expected.getEndpoint().get(); EndpointValue.Builder builder = EndpointValue.builder() - .url(expectedEndpoint.getUrl()) - .headers(expectedEndpoint.getHeaders()); + .url(expectedEndpoint.getUrl()) + .headers(expectedEndpoint.getHeaders()); for (Map.Entry entry : expectedEndpoint.getProperties().entrySet()) { builder.putProperty(entry.getKey(), Value.fromNode(entry.getValue())); } if (!actual.expectEndpointValue().equals(builder.build())) { throw new AssertionError( - String.format( - "Expected endpoint:%n%s but got:%n%s (generated by %s)", - StringUtils.indent(expectedEndpoint.toString(), 2), - StringUtils.indent(actual.toString(), 2), - expectedEndpoint.getSourceLocation() - ) + String.format( + "Expected endpoint:%n%s but got:%n%s (generated by %s)", + StringUtils.indent(expectedEndpoint.toString(), 2), + StringUtils.indent(actual.toString(), 2), + expectedEndpoint.getSourceLocation() + ) ); } } else { diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/type/OptionalType.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/type/OptionalType.java index 6e3b1c2f943..04b327caeb6 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/type/OptionalType.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/type/OptionalType.java @@ -43,22 +43,22 @@ public Type inner() { @Override public StringType expectStringType() throws InnerParseError { throw new InnerParseError( - String.format( - "Expected string but found %s. hint: use `assign` in a condition " - + "or `isSet` to prove that this value is non-null", - this - ) + String.format( + "Expected string but found %s. hint: use `assign` in a condition " + + "or `isSet` to prove that this value is non-null", + this + ) ); } @Override public BooleanType expectBooleanType() throws InnerParseError { throw new InnerParseError( - String.format( - "Expected boolean but found %s. hint: use `isSet` to convert " - + "OptionalType[BooleanType] to bool", - this - ) + String.format( + "Expected boolean but found %s. hint: use `isSet` to convert " + + "OptionalType[BooleanType] to bool", + this + ) ); } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/value/EndpointValue.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/value/EndpointValue.java index 5ff18dc6a6b..35c453b14e1 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/value/EndpointValue.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/value/EndpointValue.java @@ -70,10 +70,10 @@ public static EndpointValue fromNode(Node node) { objectNode.getObjectMember("headers", headers -> { for (Map.Entry entry : headers.getStringMap().entrySet()) { builder.putHeader( - entry.getKey(), - entry.getValue() - .expectArrayNode("Header values must be an array") - .getElementsAs(n -> n.expectStringNode().getValue()) + entry.getKey(), + entry.getValue() + .expectArrayNode("Header values must be an array") + .getElementsAs(n -> n.expectStringNode().getValue()) ); } }); @@ -128,10 +128,10 @@ public Node toNode() { } return ObjectNode.builder() - .withMember(URL, url) - .withMember(PROPERTIES, propertiesBuilder.build()) - .withMember(HEADERS, headersBuilder.build()) - .build(); + .withMember(URL, url) + .withMember(PROPERTIES, propertiesBuilder.build()) + .withMember(HEADERS, headersBuilder.build()) + .build(); } @Override @@ -144,8 +144,8 @@ public boolean equals(Object o) { } EndpointValue endpoint = (EndpointValue) o; return url.equals(endpoint.url) - && properties.equals(endpoint.properties) - && headers.equals(endpoint.headers); + && properties.equals(endpoint.properties) + && headers.equals(endpoint.headers); } @Override @@ -156,9 +156,9 @@ public int hashCode() { @Override public String toString() { StringBuilder sb = new StringBuilder("url: ") - .append(url) - .append("\nproperties:\n") - .append(StringUtils.indent(properties.toString(), 2)); + .append(url) + .append("\nproperties:\n") + .append(StringUtils.indent(properties.toString(), 2)); for (Map.Entry> entry : headers.entrySet()) { sb.append(StringUtils.indent(String.format("%s:%s", entry.getKey(), entry.getValue()), 2)); } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/value/Value.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/value/Value.java index 42bfef2b390..f0d1ad10d53 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/value/Value.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/evaluation/value/Value.java @@ -226,12 +226,12 @@ public StringValue expectStringValue() { private RuntimeException throwTypeMismatch(String expectedType) { return new RuntimeException( - format( - "Expected `%s` but was `%s` with value: `%s`", - expectedType, - getType(), - this - ) + format( + "Expected `%s` but was `%s` with value: `%s`", + expectedType, + getType(), + this + ) ); } } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/Expression.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/Expression.java index fa3c85f1853..5cf324824be 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/Expression.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/Expression.java @@ -78,9 +78,9 @@ public static Expression fromNode(Node node) { Optional fn = on.getMember("fn"); if ((ref.isPresent() ? 1 : 0) + (fn.isPresent() ? 1 : 0) != 1) { throw new SourceException( - "expected exactly one of `ref` or `fn` to be set, found " - + Node.printJson(node), - node + "expected exactly one of `ref` or `fn` to be set, found " + + Node.printJson(node), + node ); } if (ref.isPresent()) { @@ -103,14 +103,14 @@ public static Expression parseShortform(String shortForm, FromSourceLocation con if (shortForm.contains("#")) { String[] parts = shortForm.split("#", 2); return GetAttr.getDefinition() - .createFunction( - FunctionNode.ofExpressions( - GetAttr.ID, - context, - getReference(Identifier.of(parts[0]), context), - of(parts[1]) - ) - ); + .createFunction( + FunctionNode.ofExpressions( + GetAttr.ID, + context, + getReference(Identifier.of(parts[0]), context), + of(parts[1]) + ) + ); } else { return Expression.getReference(Identifier.of(shortForm), context); } @@ -188,11 +188,11 @@ public Type typeCheck(Scope scope) { if (cachedType != null && !type.equals(cachedType)) { throw new RuntimeException( - String.format( - "Checking type `%s` that doesn't match cached type `%s`", - type, - cachedType - ) + String.format( + "Checking type `%s` that doesn't match cached type `%s`", + type, + cachedType + ) ); } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/Reference.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/Reference.java index f81533abc52..1f8a757d38a 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/Reference.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/Reference.java @@ -67,8 +67,8 @@ protected Type typeCheckLocal(Scope scope) { @Override public Node toNode() { return ObjectNode.builder() - .withMember("ref", name.toString()) - .build(); + .withMember("ref", name.toString()) + .build(); } @Override diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/FunctionNode.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/FunctionNode.java index ab33d4b34c0..3adb7a86b5a 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/FunctionNode.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/FunctionNode.java @@ -66,15 +66,15 @@ public static FunctionNode ofExpressions(String functionName, ToExpression... ar * @return the {@link FunctionNode}. */ public static FunctionNode ofExpressions( - String functionName, - FromSourceLocation sourceLocation, - ToExpression... arguments + String functionName, + FromSourceLocation sourceLocation, + ToExpression... arguments ) { return builder() - .sourceLocation(sourceLocation) - .name(StringNode.from(functionName)) - .arguments(Arrays.asList(arguments)) - .build(); + .sourceLocation(sourceLocation) + .name(StringNode.from(functionName)) + .arguments(Arrays.asList(arguments)) + .build(); } /** @@ -98,10 +98,10 @@ public static FunctionNode fromNode(ObjectNode function) { arguments.add(Expression.fromNode(node)); } return builder() - .sourceLocation(function) - .name(function.expectStringMember(FN)) - .arguments(arguments) - .build(); + .sourceLocation(function) + .name(function.expectStringMember(FN)) + .arguments(arguments) + .build(); } /** @@ -111,15 +111,15 @@ public static FunctionNode fromNode(ObjectNode function) { */ public Expression createFunction() { return EndpointRuleSet.createFunctionFactory() - .apply(this) - .orElseThrow( - () -> new RuleError( - new SourceException( - String.format("`%s` is not a valid function", name), - name - ) - ) - ); + .apply(this) + .orElseThrow( + () -> new RuleError( + new SourceException( + String.format("`%s` is not a valid function", name), + name + ) + ) + ); } /** @@ -152,9 +152,9 @@ public SourceLocation getSourceLocation() { */ public Builder toBuilder() { return builder() - .sourceLocation(sourceLocation) - .name(name) - .arguments(arguments); + .sourceLocation(sourceLocation) + .name(name) + .arguments(arguments); } @Override @@ -165,9 +165,9 @@ public Node toNode() { } return ObjectNode.builder() - .withMember(FN, name) - .withMember(ARGV, builder.build()) - .build(); + .withMember(FN, name) + .withMember(ARGV, builder.build()) + .build(); } @Override diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/GetAttr.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/GetAttr.java index bdc7a1f2c16..06a8c568ad1 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/GetAttr.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/GetAttr.java @@ -95,8 +95,8 @@ private static List parse(String path, FromSourceLocation sourceLocation) String slicePart = component.substring(slicePartIndex); if (!slicePart.endsWith("]")) { throw new InvalidRulesException( - "Invalid path component: %s. Must end with `]`", - sourceLocation + "Invalid path component: %s. Must end with `]`", + sourceLocation ); } try { @@ -104,8 +104,8 @@ private static List parse(String path, FromSourceLocation sourceLocation) int slice = Integer.parseInt(number); if (slice < 0) { throw new InvalidRulesException( - "Invalid path component: slice index must be >= 0", - sourceLocation + "Invalid path component: slice index must be >= 0", + sourceLocation ); } if (slicePartIndex > 0) { @@ -114,8 +114,8 @@ private static List parse(String path, FromSourceLocation sourceLocation) result.add(new Part.Index(slice)); } catch (NumberFormatException ex) { throw new InvalidRulesException( - String.format("%s could not be parsed as a number", slicePart), - sourceLocation + String.format("%s could not be parsed as a number", slicePart), + sourceLocation ); } } else { @@ -185,9 +185,9 @@ public String template() { public Node toNode() { // Synthesize an fn-node: return ObjectNode.builder() - .withMember("fn", GetAttr.ID) - .withMember("argv", ArrayNode.arrayNode(target.toNode(), StringNode.from(unparsedPath))) - .build(); + .withMember("fn", GetAttr.ID) + .withMember("argv", ArrayNode.arrayNode(target.toNode(), StringNode.from(unparsedPath))) + .build(); } @Override @@ -264,15 +264,15 @@ public static Key of(String key) { public Type typeCheck(Type container) throws InnerParseError { RecordType record = container.expectRecordType( - String.format( - "cannot index into %s, expected object", - container - ) + String.format( + "cannot index into %s, expected object", + container + ) ); return record.get(key) - .orElseThrow( - () -> new InnerParseError(String.format("%s does not contain field %s", container, key)) - ); + .orElseThrow( + () -> new InnerParseError(String.format("%s does not contain field %s", container, key)) + ); } @Override diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/IsSet.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/IsSet.java index ec64a029054..b98373cb73e 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/IsSet.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/IsSet.java @@ -57,11 +57,11 @@ protected Type typeCheckLocal(Scope scope) { Type type = arg.typeCheck(scope); if (!type.isA(Type.optionalType(Type.anyType()))) { throw new RuntimeException( - String.format( - "Expected %s but found %s", - Type.optionalType(Type.anyType()), - type - ) + String.format( + "Expected %s but found %s", + Type.optionalType(Type.anyType()), + type + ) ); } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/LibraryFunction.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/LibraryFunction.java index bd595681d17..df1ef1fa5af 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/LibraryFunction.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/LibraryFunction.java @@ -74,17 +74,17 @@ protected Type typeCheckLocal(Scope scope) { } private void checkTypeSignature( - List expectedArgs, - List actualArguments, - Scope scope + List expectedArgs, + List actualArguments, + Scope scope ) throws InnerParseError { if (expectedArgs.size() != actualArguments.size()) { throw new InnerParseError( - String.format( - "Expected %s arguments but found %s", - expectedArgs.size(), - actualArguments - ) + String.format( + "Expected %s arguments but found %s", + expectedArgs.size(), + actualArguments + ) ); } for (int i = 0; i < expectedArgs.size(); i++) { @@ -94,21 +94,21 @@ private void checkTypeSignature( Type optAny = Type.optionalType(Type.anyType()); String hint = ""; if (actual.isA(optAny) && !expected.isA(optAny) - && actual.expectOptionalType().inner().equals(expected)) { + && actual.expectOptionalType().inner().equals(expected)) { hint = String.format( - "hint: use `assign` in a condition or `isSet(%s)` to prove that this value is non-null", - actualArguments.get(i) + "hint: use `assign` in a condition or `isSet(%s)` to prove that this value is non-null", + actualArguments.get(i) ); hint = StringUtils.indent(hint, 2); } throw new InnerParseError( - String.format( - "Unexpected type in the %s argument: Expected %s but found %s%n%s", - ordinal(i + 1), - expected, - actual, - hint - ) + String.format( + "Unexpected type in the %s argument: Expected %s but found %s%n%s", + ordinal(i + 1), + expected, + actual, + hint + ) ); } } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/Not.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/Not.java index 372ea6a42c5..8cfe59c8b94 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/Not.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/Not.java @@ -52,11 +52,11 @@ public R accept(ExpressionVisitor visitor) { protected Type typeCheckLocal(Scope scope) { // Not must be typechecked in an interior scope because information doesn't flow back out of `not`. return scope.inScope( - () -> context( - "while typechecking `not`", - this, - () -> expectOneArgument().typeCheck(scope).expectBooleanType() - ) + () -> context( + "while typechecking `not`", + this, + () -> expectOneArgument().typeCheck(scope).expectBooleanType() + ) ); } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/Substring.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/Substring.java index 26914ee4193..f0c0e237844 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/Substring.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/Substring.java @@ -44,10 +44,10 @@ public static Definition getDefinition() { * @return The resulting {@link Substring} function. */ public static Substring ofExpressions( - ToExpression expression, - ToExpression startIndex, - ToExpression stopIndex, - ToExpression reverse + ToExpression expression, + ToExpression startIndex, + ToExpression stopIndex, + ToExpression reverse ) { return DEFINITION.createFunction(FunctionNode.ofExpressions(ID, expression, startIndex, stopIndex, reverse)); } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/UriEncode.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/UriEncode.java index cd0549a5b92..29a65f9b534 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/UriEncode.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/expressions/functions/UriEncode.java @@ -57,12 +57,12 @@ public T accept(ExpressionVisitor visitor) { */ public static final class Definition implements FunctionDefinition { private static final Map ENCODING_REPLACEMENTS = MapUtils.of( - "+", - "%20", - "*", - "%2A", - "%7E", - "~" + "+", + "%20", + "*", + "%2A", + "%7E", + "~" ); private Definition() {} diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/BuiltIns.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/BuiltIns.java index e6c311701f9..514a1e76dc9 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/BuiltIns.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/BuiltIns.java @@ -15,11 +15,11 @@ public final class BuiltIns { * Built-in parameter that enables a customer to wholesale override the URL used by the SDK. */ public static final Parameter SDK_ENDPOINT = Parameter.builder() - .name("Endpoint") - .type(ParameterType.STRING) - .documentation("Override the endpoint used to send this request") - .builtIn("SDK::Endpoint") - .build(); + .name("Endpoint") + .type(ParameterType.STRING) + .documentation("Override the endpoint used to send this request") + .builtIn("SDK::Endpoint") + .build(); private BuiltIns() {} } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/Deprecated.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/Deprecated.java index db63111e2c8..639508c5ac1 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/Deprecated.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/Deprecated.java @@ -73,7 +73,7 @@ public boolean equals(Object obj) { } Deprecated that = (Deprecated) obj; return Objects.equals(this.message, that.message) - && Objects.equals(this.since, that.since); + && Objects.equals(this.since, that.since); } @Override @@ -84,7 +84,7 @@ public int hashCode() { @Override public String toString() { return "Deprecated[" - + "message=" + message + ", " - + "since=" + since + ']'; + + "message=" + message + ", " + + "since=" + since + ']'; } } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/Parameter.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/Parameter.java index 060edca65a8..c501f47de57 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/Parameter.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/Parameter.java @@ -38,12 +38,12 @@ public final class Parameter extends SyntaxElement implements ToSmithyBuilder PROPERTIES = ListUtils.of( - BUILT_IN, - REQUIRED, - TYPE, - DEPRECATED, - DOCUMENTATION, - DEFAULT + BUILT_IN, + REQUIRED, + TYPE, + DEPRECATED, + DOCUMENTATION, + DEFAULT ); private final ParameterType type; @@ -91,11 +91,11 @@ public static Parameter fromNode(StringNode name, ObjectNode objectNode) throws objectNode.getMember(DEFAULT).map(Value::fromNode).ifPresent(builder::defaultValue); builder.type( - RuleError.context( - "while parsing the parameter type", - objectNode, - () -> ParameterType.fromNode(objectNode.expectStringMember(TYPE)) - ) + RuleError.context( + "while parsing the parameter type", + objectNode, + () -> ParameterType.fromNode(objectNode.expectStringMember(TYPE)) + ) ); return builder.build(); }); @@ -166,12 +166,12 @@ public Type toType() { if (defaultValue != null && !defaultValue.getType().equals(out)) { throw new RuntimeException( - String.format( - "Invalid type for field \"default\": Type must match " - + "parameter type. Expected `%s`, found `%s`.", - out, - defaultValue.getType() - ) + String.format( + "Invalid type for field \"default\": Type must match " + + "parameter type. Expected `%s`, found `%s`.", + out, + defaultValue.getType() + ) ); } @@ -248,15 +248,15 @@ public Expression toExpression() { @Override public Builder toBuilder() { return builder() - .type(type) - .name(name) - .builtIn(builtIn) - .value(value) - .required(required) - .sourceLocation(sourceLocation) - .deprecated(deprecated) - .documentation(documentation) - .defaultValue(defaultValue); + .type(type) + .name(name) + .builtIn(builtIn) + .value(value) + .required(required) + .sourceLocation(sourceLocation) + .deprecated(deprecated) + .documentation(documentation) + .defaultValue(defaultValue); } @Override @@ -289,13 +289,13 @@ public boolean equals(Object o) { } Parameter parameter = (Parameter) o; return required == parameter.required - && Objects.equals(type, parameter.type) - && name.equals(parameter.name) - && Objects.equals(value, parameter.value) - && Objects.equals(builtIn, parameter.builtIn) - && Objects.equals(defaultValue, parameter.defaultValue) - && Objects.equals(deprecated, parameter.deprecated) - && Objects.equals(documentation, parameter.documentation); + && Objects.equals(type, parameter.type) + && name.equals(parameter.name) + && Objects.equals(value, parameter.value) + && Objects.equals(builtIn, parameter.builtIn) + && Objects.equals(defaultValue, parameter.defaultValue) + && Objects.equals(deprecated, parameter.deprecated) + && Objects.equals(documentation, parameter.documentation); } @Override diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/ParameterType.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/ParameterType.java index 0e97c9680d8..daaf273cd55 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/ParameterType.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/ParameterType.java @@ -54,13 +54,13 @@ public static ParameterType fromNode(StringNode node) throws RuleError { return STRING_ARRAY; } throw new RuleError( - new SourceException( - String.format( - "Unexpected parameter type `%s`. Expected `string`, `boolean`, or `stringArray`.", - value - ), - node - ) + new SourceException( + String.format( + "Unexpected parameter type `%s`. Expected `string`, `boolean`, or `stringArray`.", + value + ), + node + ) ); } @@ -83,23 +83,23 @@ public static ParameterType fromNode(Node node) throws RuleError { node.expectArrayNode().getElements().forEach(memberNode -> { if (!memberNode.isStringNode()) { throw new RuleError( - new SourceException( - String.format( - "Unexpected array member parameter type `%s`. Expected a string.", - memberNode.getType() - ), - memberNode - ) + new SourceException( + String.format( + "Unexpected array member parameter type `%s`. Expected a string.", + memberNode.getType() + ), + memberNode + ) ); } }); return STRING_ARRAY; } throw new RuleError( - new SourceException( - String.format("Unexpected parameter type `%s`. Expected a string or boolean.", node.getType()), - node - ) + new SourceException( + String.format("Unexpected parameter type `%s`. Expected a string or boolean.", node.getType()), + node + ) ); } @@ -124,7 +124,7 @@ public static ParameterType fromType(Type type) { } } throw new RuntimeException( - String.format("Unexpected parameter type `%s`. Expected a string, boolean, or array.", type) + String.format("Unexpected parameter type `%s`. Expected a string, boolean, or array.", type) ); } @@ -143,7 +143,7 @@ public static ParameterType fromShapeType(ShapeType type) { return BOOLEAN; } throw new RuntimeException( - String.format("Unexpected parameter type `%s`. Expected string or boolean.", type) + String.format("Unexpected parameter type `%s`. Expected string or boolean.", type) ); } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/Parameters.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/Parameters.java index 016f4cef6f4..b67e93dbd03 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/Parameters.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/parameters/Parameters.java @@ -58,10 +58,10 @@ public static Parameters fromNode(ObjectNode node) throws RuleError { Builder builder = new Builder(node); for (Map.Entry entry : node.getMembers().entrySet()) { builder.addParameter( - Parameter.fromNode( - entry.getKey(), - RuleError.context("when parsing parameter", () -> entry.getValue().expectObjectNode()) - ) + Parameter.fromNode( + entry.getKey(), + RuleError.context("when parsing parameter", () -> entry.getValue().expectObjectNode()) + ) ); } return builder.build(); @@ -75,9 +75,9 @@ public static Parameters fromNode(ObjectNode node) throws RuleError { public void writeToScope(Scope scope) { for (Parameter parameter : parameters) { RuleError.context( - String.format("while typechecking par %s", parameter.getName()), - parameter, - () -> scope.insert(parameter.getName(), parameter.toType()) + String.format("while typechecking par %s", parameter.getName()), + parameter, + () -> scope.insert(parameter.getName(), parameter.toType()) ); } } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/Condition.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/Condition.java index 43dc56972c2..b6d5bc4f9b6 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/Condition.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/Condition.java @@ -110,8 +110,8 @@ public Expression toExpression() { public Builder toBuilder() { return builder() - .fn(function) - .result(result); + .fn(function) + .result(result); } @Override @@ -121,12 +121,12 @@ public Type typeCheck(Scope scope) { if (result != null) { scope.getDeclaration(result).ifPresent(entry -> { throw new SourceException( - String.format( - "Invalid shadowing of `%s` (first declared on line %s)", - result, - entry.getKey().getSourceLocation().getLine() - ), - result + String.format( + "Invalid shadowing of `%s` (first declared on line %s)", + result, + entry.getKey().getSourceLocation().getLine() + ), + result ); }); scope.insert(result, conditionType.provenTruthy()); diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/ErrorRule.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/ErrorRule.java index ef9c4d9e8c7..03a60388f49 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/ErrorRule.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/ErrorRule.java @@ -52,6 +52,6 @@ void withValueNode(ObjectNode.Builder builder) { @Override public String toString() { return super.toString() - + StringUtils.indent(String.format("error(%s)", error), 2); + + StringUtils.indent(String.format("error(%s)", error), 2); } } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/Rule.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/Rule.java index 270aeaed9ed..907d2f214fc 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/Rule.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/Rule.java @@ -289,8 +289,8 @@ public Builder errorOrElse(String error, ToCondition... condition) { public Builder validateOrElse(String error, ToCondition... condition) { Builder next = new Builder(javaLocation()); next.onBuild = (Rule rule) -> this.treeRule( - Rule.builder().conditions(condition).treeRule(rule), - Rule.builder().error(error) + Rule.builder().conditions(condition).treeRule(rule), + Rule.builder().error(error) ); return next; } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/TreeRule.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/TreeRule.java index 1bc654db680..ac093c0d58e 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/TreeRule.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/language/syntax/rule/TreeRule.java @@ -48,8 +48,8 @@ protected Type typecheckValue(Scope scope) { } for (Rule rule : rules) { RuleError.context( - "while checking nested rule in tree rule", - () -> scope.inScope(() -> rule.typeCheck(scope)) + "while checking nested rule in tree rule", + () -> scope.inScope(() -> rule.typeCheck(scope)) ); } return Type.endpointType(); diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/CleanEndpointTestOperationInput.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/CleanEndpointTestOperationInput.java index 86e29f754b1..1cc11dc22e4 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/CleanEndpointTestOperationInput.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/CleanEndpointTestOperationInput.java @@ -56,9 +56,9 @@ private Set getServicesToUpdate(Model model, Collection removed) { // Update the shape if the trait has changed. if (updatedTestCases.size() != trait.getTestCases().size()) { result.add( - serviceShape.toBuilder() - .addTrait(trait.toBuilder().testCases(updatedTestCases).build()) - .build() + serviceShape.toBuilder() + .addTrait(trait.toBuilder().testCases(updatedTestCases).build()) + .build() ); } } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ClientContextParamDefinition.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ClientContextParamDefinition.java index 78e674f2784..d3eb4985e14 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ClientContextParamDefinition.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ClientContextParamDefinition.java @@ -38,8 +38,8 @@ public Optional getDocumentation() { public Builder toBuilder() { return builder() - .type(type) - .documentation(documentation); + .type(type) + .documentation(documentation); } @Override diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ClientContextParamsTrait.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ClientContextParamsTrait.java index 5c63bac2870..ace635bc97d 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ClientContextParamsTrait.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ClientContextParamsTrait.java @@ -48,8 +48,8 @@ protected Node createNode() { @Override public Builder toBuilder() { return builder() - .sourceLocation(getSourceLocation()) - .parameters(getParameters()); + .sourceLocation(getSourceLocation()) + .parameters(getParameters()); } public static final class Provider extends AbstractTrait.Provider { @@ -67,9 +67,9 @@ public Trait createTrait(ShapeId target, Node value) { }); ClientContextParamsTrait trait = builder() - .parameters(parameters) - .sourceLocation(value) - .build(); + .parameters(parameters) + .sourceLocation(value) + .build(); trait.setNodeCache(value); return trait; } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ContextParamTrait.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ContextParamTrait.java index 6b32c3e6df8..d83a491d672 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ContextParamTrait.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ContextParamTrait.java @@ -47,8 +47,8 @@ protected Node createNode() { @Override public Builder toBuilder() { return new Builder() - .sourceLocation(getSourceLocation()) - .name(name); + .sourceLocation(getSourceLocation()) + .name(name); } public static final class Provider extends AbstractTrait.Provider { diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointRuleSetTrait.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointRuleSetTrait.java index c7197c878ff..1a6293f41d1 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointRuleSetTrait.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointRuleSetTrait.java @@ -54,8 +54,8 @@ protected Node createNode() { @Override public Builder toBuilder() { return builder() - .sourceLocation(getSourceLocation()) - .ruleSet(ruleSet); + .sourceLocation(getSourceLocation()) + .ruleSet(ruleSet); } public static final class Provider extends AbstractTrait.Provider { @@ -66,8 +66,8 @@ public Provider() { @Override public Trait createTrait(ShapeId target, Node value) { EndpointRuleSetTrait trait = builder().sourceLocation(value) - .ruleSet(value) - .build(); + .ruleSet(value) + .build(); trait.setNodeCache(value); return trait; } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestCase.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestCase.java index 9f02434dd0a..6960e7ee10e 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestCase.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestCase.java @@ -62,11 +62,11 @@ public SourceLocation getSourceLocation() { @Override public Builder toBuilder() { return builder() - .sourceLocation(sourceLocation) - .documentation(documentation) - .params(params) - .operationInputs(operationInputs) - .expect(expect); + .sourceLocation(sourceLocation) + .documentation(documentation) + .params(params) + .operationInputs(operationInputs) + .expect(expect); } @Override @@ -84,9 +84,9 @@ public boolean equals(Object o) { } EndpointTestCase that = (EndpointTestCase) o; return Objects.equals(getDocumentation(), that.getDocumentation()) - && Objects.equals(getParams(), that.getParams()) - && Objects.equals(getOperationInputs(), that.getOperationInputs()) - && Objects.equals(getExpect(), that.getExpect()); + && Objects.equals(getParams(), that.getParams()) + && Objects.equals(getOperationInputs(), that.getOperationInputs()) + && Objects.equals(getExpect(), that.getExpect()); } public static final class Builder implements SmithyBuilder { diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestExpectation.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestExpectation.java index b9c8a2c11ef..d498ae93774 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestExpectation.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestExpectation.java @@ -47,9 +47,9 @@ public SourceLocation getSourceLocation() { @Override public Builder toBuilder() { return builder() - .sourceLocation(sourceLocation) - .endpoint(endpoint) - .error(error); + .sourceLocation(sourceLocation) + .endpoint(endpoint) + .error(error); } @Override diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestOperationInput.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestOperationInput.java index 97be518143e..5ba3d54f648 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestOperationInput.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestOperationInput.java @@ -17,7 +17,7 @@ */ @SmithyUnstableApi public final class EndpointTestOperationInput implements FromSourceLocation, - ToSmithyBuilder { + ToSmithyBuilder { private final SourceLocation sourceLocation; private final String operationName; private final ObjectNode operationParams; @@ -67,9 +67,9 @@ public boolean equals(Object o) { } EndpointTestOperationInput that = (EndpointTestOperationInput) o; return getOperationName().equals(that.getOperationName()) - && Objects.equals(getOperationParams(), that.getOperationParams()) - && Objects.equals(getBuiltInParams(), that.getBuiltInParams()) - && Objects.equals(getClientParams(), that.getClientParams()); + && Objects.equals(getOperationParams(), that.getOperationParams()) + && Objects.equals(getBuiltInParams(), that.getBuiltInParams()) + && Objects.equals(getClientParams(), that.getClientParams()); } @Override @@ -80,11 +80,11 @@ public int hashCode() { @Override public Builder toBuilder() { return builder() - .sourceLocation(sourceLocation) - .operationName(operationName) - .operationParams(operationParams) - .builtInParams(builtInParams) - .clientParams(clientParams); + .sourceLocation(sourceLocation) + .operationName(operationName) + .operationParams(operationParams) + .builtInParams(builtInParams) + .clientParams(clientParams); } public static final class Builder implements SmithyBuilder { diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestsTrait.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestsTrait.java index 50a67e8e304..6f6fae0f8de 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestsTrait.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestsTrait.java @@ -62,9 +62,9 @@ protected Node createNode() { @Override public Builder toBuilder() { return builder() - .sourceLocation(getSourceLocation()) - .version(version) - .testCases(testCases); + .sourceLocation(getSourceLocation()) + .version(version) + .testCases(testCases); } public static final class Provider extends AbstractTrait.Provider { diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestsTraitValidator.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestsTraitValidator.java index 513a30f2e9e..1f5b8dd6134 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestsTraitValidator.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/EndpointTestsTraitValidator.java @@ -43,30 +43,30 @@ public List validate(Model model) { // It's possible for an operation defined to not be in the service closure. if (!operationNameMap.containsKey(operationName)) { events.add( - error( - serviceShape, - testOperationInput, - String.format( - "Test case operation `%s` does not exist in service `%s`", - operationName, - serviceShape.getId() + error( + serviceShape, + testOperationInput, + String.format( + "Test case operation `%s` does not exist in service `%s`", + operationName, + serviceShape.getId() + ) ) - ) ); } // Still emit events if the operation exists, but was just not bound. if (operationNameMap.containsKey(operationName)) { StructureShape inputShape = model.expectShape( - operationNameMap.get(operationName).getInputShape(), - StructureShape.class + operationNameMap.get(operationName).getInputShape(), + StructureShape.class ); List operationInputEvents = validateOperationInput( - model, - serviceShape, - inputShape, - testOperationInput + model, + serviceShape, + inputShape, + testOperationInput ); // Error test cases may use invalid inputs as the mechanism to trigger their error, @@ -87,21 +87,21 @@ public List validate(Model model) { } private List validateOperationInput( - Model model, - ServiceShape serviceShape, - StructureShape inputShape, - EndpointTestOperationInput testOperationInput + Model model, + ServiceShape serviceShape, + StructureShape inputShape, + EndpointTestOperationInput testOperationInput ) { NodeValidationVisitor validator = NodeValidationVisitor.builder() - .model(model) - .value(testOperationInput.getOperationParams()) - .eventId(getName()) - .eventShapeId(serviceShape.toShapeId()) - .startingContext( - "The operationInput value for an endpoint test " - + "does not match the operation's input shape" - ) - .build(); + .model(model) + .value(testOperationInput.getOperationParams()) + .eventId(getName()) + .eventShapeId(serviceShape.toShapeId()) + .startingContext( + "The operationInput value for an endpoint test " + + "does not match the operation's input shape" + ) + .build(); return inputShape.accept(validator); } } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ExpectedEndpoint.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ExpectedEndpoint.java index 159a5b6e098..19aa8b6ed3c 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ExpectedEndpoint.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/ExpectedEndpoint.java @@ -57,10 +57,10 @@ public SourceLocation getSourceLocation() { @Override public Builder toBuilder() { return builder() - .sourceLocation(sourceLocation) - .url(url) - .headers(headers) - .properties(properties); + .sourceLocation(sourceLocation) + .url(url) + .headers(headers) + .properties(properties); } @Override @@ -78,7 +78,7 @@ public boolean equals(Object o) { } ExpectedEndpoint that = (ExpectedEndpoint) o; return getUrl().equals(that.getUrl()) && Objects.equals(getHeaders(), that.getHeaders()) - && Objects.equals(getProperties(), that.getProperties()); + && Objects.equals(getProperties(), that.getProperties()); } @Override @@ -87,21 +87,21 @@ public String toString() { sb.append("url: ").append(url).append("\n"); if (!headers.isEmpty()) { headers.forEach( - (key, value) -> { - sb.append(StringUtils.indent(String.format("%s:%s", key, value), 2)); - } + (key, value) -> { + sb.append(StringUtils.indent(String.format("%s:%s", key, value), 2)); + } ); } if (!properties.isEmpty()) { sb.append("properties:\n"); properties.forEach( - (k, v) -> sb - .append( - StringUtils.indent( - String.format("%s: %s", k, Node.prettyPrintJson(v)), - 2 - ) - ) + (k, v) -> sb + .append( + StringUtils.indent( + String.format("%s: %s", k, Node.prettyPrintJson(v)), + 2 + ) + ) ); } return sb.toString(); diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/OperationContextParamsTrait.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/OperationContextParamsTrait.java index 8cd64d070f1..b314fa28c58 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/OperationContextParamsTrait.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/OperationContextParamsTrait.java @@ -21,7 +21,7 @@ */ @SmithyUnstableApi public final class OperationContextParamsTrait extends AbstractTrait - implements ToSmithyBuilder { + implements ToSmithyBuilder { public static final ShapeId ID = ShapeId.from("smithy.rules#operationContextParams"); private final Map parameters; @@ -49,8 +49,8 @@ protected Node createNode() { @Override public Builder toBuilder() { return new Builder() - .sourceLocation(getSourceLocation()) - .parameters(parameters); + .sourceLocation(getSourceLocation()) + .parameters(parameters); } public static final class Provider extends AbstractTrait.Provider { @@ -66,9 +66,9 @@ public Trait createTrait(ShapeId target, Node value) { parameters.put(stringNode.getValue(), mapper.deserialize(node, OperationContextParamDefinition.class)); }); OperationContextParamsTrait trait = builder() - .sourceLocation(value) - .parameters(parameters) - .build(); + .sourceLocation(value) + .parameters(parameters) + .build(); trait.setNodeCache(value); return trait; } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/OperationContextParamsTraitValidator.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/OperationContextParamsTraitValidator.java index ce758e4452e..ffae5c87f75 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/OperationContextParamsTraitValidator.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/OperationContextParamsTraitValidator.java @@ -50,72 +50,72 @@ public List validate(Model model) { List events = new ArrayList<>(); for (OperationShape operationShape : model.getOperationShapes()) { Map definitionMap = index.getOperationContextParams(operationShape) - .map(OperationContextParamsTrait::getParameters) - .orElse(Collections.emptyMap()); + .map(OperationContextParamsTrait::getParameters) + .orElse(Collections.emptyMap()); for (Map.Entry entry : definitionMap.entrySet()) { try { JmespathExpression path = JmespathExpression.parse(entry.getValue().getPath()); LinterResult linterResult = OperationContextParamsChecker.lint( - entry.getValue(), - operationShape, - model + entry.getValue(), + operationShape, + model ); if (!linterResult.getProblems().isEmpty()) { events.add( - error( - operationShape, - String.format( - "The operation `%s` is marked with `%s` which contains a " - + "path `%s` with an invalid JMESPath path `%s`: %s.", - operationShape.getId(), - OperationContextParamsTrait.ID.toString(), - entry.getKey(), - entry.getValue().getPath(), - linterResult.getProblems() - .stream() - .map(p -> "'" + p.message + "'") - .collect(Collectors.joining(", ")) + error( + operationShape, + String.format( + "The operation `%s` is marked with `%s` which contains a " + + "path `%s` with an invalid JMESPath path `%s`: %s.", + operationShape.getId(), + OperationContextParamsTrait.ID.toString(), + entry.getKey(), + entry.getValue().getPath(), + linterResult.getProblems() + .stream() + .map(p -> "'" + p.message + "'") + .collect(Collectors.joining(", ")) + ) ) - ) ); } List unsupportedExpressions = path.accept(new UnsupportedJmesPathVisitor()); if (!unsupportedExpressions.isEmpty()) { events.add( - error( - operationShape, - String.format( - "The operation `%s` is marked with `%s` which contains a " - + "key `%s` with a JMESPath path `%s` with " - + "unsupported expressions: %s.", - operationShape.getId(), - OperationContextParamsTrait.ID.toString(), - entry.getKey(), - entry.getValue().getPath(), - unsupportedExpressions.stream() - .map(e -> "'" + e + "'") - .collect(Collectors.joining(", ")) + error( + operationShape, + String.format( + "The operation `%s` is marked with `%s` which contains a " + + "key `%s` with a JMESPath path `%s` with " + + "unsupported expressions: %s.", + operationShape.getId(), + OperationContextParamsTrait.ID.toString(), + entry.getKey(), + entry.getValue().getPath(), + unsupportedExpressions.stream() + .map(e -> "'" + e + "'") + .collect(Collectors.joining(", ")) + ) ) - ) ); } } catch (JmespathException e) { events.add( - error( - operationShape, - String.format( - "The operation `%s` is marked with `%s` which contains a " - + "key `%s` with an unparseable JMESPath path `%s`: %s.", - operationShape.getId(), - OperationContextParamsTrait.ID.toString(), - entry.getKey(), - entry.getValue().getPath(), - e.getMessage() + error( + operationShape, + String.format( + "The operation `%s` is marked with `%s` which contains a " + + "key `%s` with an unparseable JMESPath path `%s`: %s.", + operationShape.getId(), + OperationContextParamsTrait.ID.toString(), + entry.getKey(), + entry.getValue().getPath(), + e.getMessage() + ) ) - ) ); } } @@ -149,10 +149,10 @@ public List visitFlatten(FlattenExpression expression) { public List visitFunction(FunctionExpression expression) { if (expression.getName().equals("keys")) { return expression.getArguments() - .stream() - .map(e -> e.accept(this)) - .flatMap(List::stream) - .collect(Collectors.toList()); + .stream() + .map(e -> e.accept(this)) + .flatMap(List::stream) + .collect(Collectors.toList()); } else { return ListUtils.of("`" + expression.getName() + "` function"); } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/StaticContextParamsTrait.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/StaticContextParamsTrait.java index 7025fd9d915..660772c731d 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/StaticContextParamsTrait.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/StaticContextParamsTrait.java @@ -48,8 +48,8 @@ protected Node createNode() { @Override public Builder toBuilder() { return new Builder() - .sourceLocation(getSourceLocation()) - .parameters(parameters); + .sourceLocation(getSourceLocation()) + .parameters(parameters); } public static final class Provider extends AbstractTrait.Provider { @@ -65,9 +65,9 @@ public Trait createTrait(ShapeId target, Node value) { parameters.put(stringNode.getValue(), mapper.deserialize(node, StaticContextParamDefinition.class)); }); StaticContextParamsTrait trait = builder() - .sourceLocation(value) - .parameters(parameters) - .build(); + .sourceLocation(value) + .parameters(parameters) + .build(); trait.setNodeCache(value); return trait; } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/StaticContextParamsTraitValidator.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/StaticContextParamsTraitValidator.java index c4ab88894be..fbef080c25c 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/StaticContextParamsTraitValidator.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/traits/StaticContextParamsTraitValidator.java @@ -26,25 +26,25 @@ public List validate(Model model) { List events = new ArrayList<>(); for (OperationShape operationShape : model.getOperationShapes()) { Map definitionMap = index.getStaticContextParams(operationShape) - .map(StaticContextParamsTrait::getParameters) - .orElse(Collections.emptyMap()); + .map(StaticContextParamsTrait::getParameters) + .orElse(Collections.emptyMap()); for (Map.Entry entry : definitionMap.entrySet()) { Node node = entry.getValue().getValue(); if (supportedType(node)) { continue; } events.add( - error( - operationShape, - String.format( - "The operation `%s` is marked with `%s` which contains a " - + "key `%s` with an unsupported document type value `%s`.", - operationShape.getId(), - StaticContextParamsTrait.ID.toString(), - entry.getKey(), - entry.getValue().getValue().getType().toString() + error( + operationShape, + String.format( + "The operation `%s` is marked with `%s` which contains a " + + "key `%s` with an unsupported document type value `%s`.", + operationShape.getId(), + StaticContextParamsTrait.ID.toString(), + entry.getKey(), + entry.getValue().getValue().getType().toString() + ) ) - ) ); } } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/AuthSchemeValidator.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/AuthSchemeValidator.java index 938cb5dd936..8b2ee6da6e0 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/AuthSchemeValidator.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/AuthSchemeValidator.java @@ -29,8 +29,8 @@ public interface AuthSchemeValidator extends Predicate { * @return a list of validation events. */ List validateScheme( - Map authScheme, - FromSourceLocation sourceLocation, - BiFunction emitter + Map authScheme, + FromSourceLocation sourceLocation, + BiFunction emitter ); } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetAuthSchemesValidator.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetAuthSchemesValidator.java index dd2982bb1d4..b9b1e30e643 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetAuthSchemesValidator.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetAuthSchemesValidator.java @@ -38,10 +38,10 @@ public List validate(Model model) { for (ServiceShape serviceShape : model.getServiceShapesWithTrait(EndpointRuleSetTrait.class)) { Validator validator = new Validator(serviceShape); events.addAll( - validator.visitRuleset( - serviceShape.expectTrait(EndpointRuleSetTrait.class).getEndpointRuleSet() - ) - .collect(Collectors.toList()) + validator.visitRuleset( + serviceShape.expectTrait(EndpointRuleSetTrait.class).getEndpointRuleSet() + ) + .collect(Collectors.toList()) ); } return events; @@ -64,10 +64,10 @@ public Stream visitEndpoint(Endpoint endpoint) { Optional> authSchemeList = authSchemes.asTupleLiteral(); if (!authSchemeList.isPresent()) { return Stream.of( - emitter.apply( - authSchemes, - String.format("Expected `authSchemes` to be a list, found: `%s`", authSchemes) - ) + emitter.apply( + authSchemes, + String.format("Expected `authSchemes` to be a list, found: `%s`", authSchemes) + ) ); } @@ -91,13 +91,13 @@ public Stream visitEndpoint(Endpoint endpoint) { events.addAll(validateAuthScheme(schemeName, authScheme, authSchemeEntry)); } else { events.add( - emitter.apply( - authSchemes, - String.format( - "Expected `authSchemes` to be a list of objects, but found: `%s`", - authSchemeEntry + emitter.apply( + authSchemes, + String.format( + "Expected `authSchemes` to be a list of objects, but found: `%s`", + authSchemeEntry + ) ) - ) ); } } @@ -105,14 +105,14 @@ public Stream visitEndpoint(Endpoint endpoint) { // Emit events for each duplicated auth scheme name. for (String duplicateAuthSchemeName : duplicateAuthSchemeNames) { events.add( - emitter.apply( - authSchemes, - String.format( - "Found duplicate `name` of `%s` in the " - + "`authSchemes` list", - duplicateAuthSchemeName + emitter.apply( + authSchemes, + String.format( + "Found duplicate `name` of `%s` in the " + + "`authSchemes` list", + duplicateAuthSchemeName + ) ) - ) ); } } @@ -121,29 +121,29 @@ public Stream visitEndpoint(Endpoint endpoint) { } private Optional validateAuthSchemeName( - Map authScheme, - FromSourceLocation sourceLocation + Map authScheme, + FromSourceLocation sourceLocation ) { if (!authScheme.containsKey(NAME) || !authScheme.get(NAME).asStringLiteral().isPresent()) { return Optional.of( - error( - serviceShape, - sourceLocation, - String.format( - "Expected `authSchemes` to have a `name` key with a string value but it did not: " - + "`%s`", - authScheme + error( + serviceShape, + sourceLocation, + String.format( + "Expected `authSchemes` to have a `name` key with a string value but it did not: " + + "`%s`", + authScheme + ) ) - ) ); } return Optional.empty(); } private List validateAuthScheme( - String schemeName, - Map authScheme, - FromSourceLocation sourceLocation + String schemeName, + Map authScheme, + FromSourceLocation sourceLocation ) { List events = new ArrayList<>(); @@ -161,14 +161,14 @@ private List validateAuthScheme( return events; } return ListUtils.of( - warning( - serviceShape, - String.format( - "Did not find a validator for the `%s` " - + "auth scheme", - schemeName + warning( + serviceShape, + String.format( + "Did not find a validator for the `%s` " + + "auth scheme", + schemeName + ) ) - ) ); } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetBuiltInValidator.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetBuiltInValidator.java index 8d3d9a8249c..94d0a74661b 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetBuiltInValidator.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetBuiltInValidator.java @@ -30,11 +30,11 @@ public List validate(Model model) { List events = new ArrayList<>(); for (ServiceShape serviceShape : model.getServiceShapesWithTrait(EndpointRuleSetTrait.class)) { events.addAll( - validateRuleSetBuiltIns( - serviceShape, - serviceShape.expectTrait(EndpointRuleSetTrait.class) - .getEndpointRuleSet() - ) + validateRuleSetBuiltIns( + serviceShape, + serviceShape.expectTrait(EndpointRuleSetTrait.class) + .getEndpointRuleSet() + ) ); } @@ -49,7 +49,7 @@ private List validateRuleSetBuiltIns(ServiceShape serviceShape, for (Parameter parameter : ruleSet.getParameters()) { if (parameter.isBuiltIn()) { validateBuiltIn(serviceShape, parameter.getBuiltIn().get(), parameter, "RuleSet") - .ifPresent(events::add); + .ifPresent(events::add); } } return events; @@ -63,15 +63,15 @@ private List validateTestTraitBuiltIns(ServiceShape serviceShap for (EndpointTestOperationInput operationInput : testCase.getOperationInputs()) { for (StringNode builtInNode : operationInput.getBuiltInParams().getMembers().keySet()) { validateBuiltIn( - serviceShape, - builtInNode.getValue(), - operationInput, - "TestCase", - String.valueOf(testIndex), - "Inputs", - String.valueOf(inputIndex) + serviceShape, + builtInNode.getValue(), + operationInput, + "TestCase", + String.valueOf(testIndex), + "Inputs", + String.valueOf(inputIndex) ) - .ifPresent(events::add); + .ifPresent(events::add); } inputIndex++; } @@ -81,23 +81,23 @@ private List validateTestTraitBuiltIns(ServiceShape serviceShap } private Optional validateBuiltIn( - ServiceShape serviceShape, - String builtInName, - FromSourceLocation source, - String... eventIdSuffixes + ServiceShape serviceShape, + String builtInName, + FromSourceLocation source, + String... eventIdSuffixes ) { if (!EndpointRuleSet.hasBuiltIn(builtInName)) { return Optional.of( - error( - serviceShape, - source, - String.format( - "The `%s` built-in used is not registered, valid built-ins: %s", - builtInName, - EndpointRuleSet.getKeyString() - ), - String.join(".", Arrays.asList(eventIdSuffixes)) - ) + error( + serviceShape, + source, + String.format( + "The `%s` built-in used is not registered, valid built-ins: %s", + builtInName, + EndpointRuleSet.getKeyString() + ), + String.join(".", Arrays.asList(eventIdSuffixes)) + ) ); } return Optional.empty(); diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetParamMissingDocsValidator.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetParamMissingDocsValidator.java index ef3bd777cf5..81b885722ff 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetParamMissingDocsValidator.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetParamMissingDocsValidator.java @@ -23,11 +23,11 @@ public List validate(Model model) { List events = new ArrayList<>(); for (ServiceShape serviceShape : model.getServiceShapesWithTrait(EndpointRuleSetTrait.class)) { events.addAll( - validateRuleSet( - serviceShape, - serviceShape.expectTrait(EndpointRuleSetTrait.class) - .getEndpointRuleSet() - ) + validateRuleSet( + serviceShape, + serviceShape.expectTrait(EndpointRuleSetTrait.class) + .getEndpointRuleSet() + ) ); } return events; @@ -38,11 +38,11 @@ public List validateRuleSet(ServiceShape serviceShape, Endpoint for (Parameter parameter : ruleSet.getParameters()) { if (!parameter.getDocumentation().isPresent()) { events.add( - warning( - serviceShape, - parameter, - String.format("Parameter `%s` does not have documentation", parameter.getName()) - ) + warning( + serviceShape, + parameter, + String.format("Parameter `%s` does not have documentation", parameter.getName()) + ) ); } } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetParameterValidator.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetParameterValidator.java index 991b937c58d..68ec742e81d 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetParameterValidator.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetParameterValidator.java @@ -54,32 +54,32 @@ public List validate(Model model) { // Pull all the parameters used in this service related to endpoints, validating that // they are of matching types across the traits that can define them. Pair, Map> errorsParamsPair = validateAndExtractParameters( - model, - serviceShape, - topDownIndex.getContainedOperations(serviceShape) + model, + serviceShape, + topDownIndex.getContainedOperations(serviceShape) ); errors.addAll(errorsParamsPair.getLeft()); // Make sure parameters align across Params <-> RuleSet transitions. EndpointRuleSet ruleSet = serviceShape.expectTrait(EndpointRuleSetTrait.class).getEndpointRuleSet(); errors.addAll( - validateParametersMatching( - serviceShape, - ruleSet.getParameters(), - errorsParamsPair.getRight() - ) + validateParametersMatching( + serviceShape, + ruleSet.getParameters(), + errorsParamsPair.getRight() + ) ); // Check that tests declare required parameters, only defined parameters, etc. if (serviceShape.hasTrait(EndpointTestsTrait.class)) { errors.addAll( - validateTestsParameters( - model, - topDownIndex, - serviceShape, - serviceShape.expectTrait(EndpointTestsTrait.class), - ruleSet - ) + validateTestsParameters( + model, + topDownIndex, + serviceShape, + serviceShape.expectTrait(EndpointTestsTrait.class), + ruleSet + ) ); } } @@ -88,9 +88,9 @@ public List validate(Model model) { } private Pair, Map> validateAndExtractParameters( - Model model, - ServiceShape serviceShape, - Set containedOperations + Model model, + ServiceShape serviceShape, + Set containedOperations ) { List errors = new ArrayList<>(); Map endpointParams = new HashMap<>(); @@ -99,11 +99,11 @@ private Pair, Map> validateAndExtractPa ClientContextParamsTrait trait = serviceShape.expectTrait(ClientContextParamsTrait.class); for (Map.Entry entry : trait.getParameters().entrySet()) { endpointParams.put( - entry.getKey(), - Parameter.builder() - .name(entry.getKey()) - .type(ParameterType.fromShapeType(entry.getValue().getType())) - .build() + entry.getKey(), + Parameter.builder() + .name(entry.getKey()) + .type(ParameterType.fromShapeType(entry.getValue().getType())) + .build() ); } } @@ -117,21 +117,21 @@ private Pair, Map> validateAndExtractPa if (endpointParams.containsKey(name) && endpointParams.get(name).getType() != parameterType) { errors.add( - parameterError( - operationShape, - trait, - "StaticContextParams.InconsistentType", - String.format("Inconsistent type for `%s` parameter", name) - ) + parameterError( + operationShape, + trait, + "StaticContextParams.InconsistentType", + String.format("Inconsistent type for `%s` parameter", name) + ) ); } else { endpointParams.put( - name, - Parameter.builder() - .name(name) - .value(entry.getValue().getValue()) - .type(parameterType) - .build() + name, + Parameter.builder() + .name(name) + .value(entry.getValue().getValue()) + .type(parameterType) + .build() ); } } @@ -141,24 +141,24 @@ private Pair, Map> validateAndExtractPa OperationContextParamsTrait trait = operationShape.expectTrait(OperationContextParamsTrait.class); trait.getParameters().forEach((name, p) -> { Optional maybeType = OperationContextParamsChecker - .inferParameterType(p, operationShape, model); + .inferParameterType(p, operationShape, model); maybeType.ifPresent(parameterType -> { if (endpointParams.containsKey(name) && endpointParams.get(name).getType() != parameterType) { errors.add( - parameterError( - operationShape, - trait, - "OperationContextParams.InconsistentType", - String.format("Inconsistent type for `%s` parameter", name) - ) + parameterError( + operationShape, + trait, + "OperationContextParams.InconsistentType", + String.format("Inconsistent type for `%s` parameter", name) + ) ); } else { endpointParams.put( - name, - Parameter.builder() - .name(name) - .type(parameterType) - .build() + name, + Parameter.builder() + .name(name) + .type(parameterType) + .build() ); } }); @@ -174,33 +174,33 @@ private Pair, Map> validateAndExtractPa if (!targetType.isStringShape() && !targetType.isBooleanShape()) { errors.add( - parameterError( - memberShape, - trait, - "ContextParam.UnsupportedType", - String.format("Unsupported type `%s` for `%s` parameter", targetType, name) - ) + parameterError( + memberShape, + trait, + "ContextParam.UnsupportedType", + String.format("Unsupported type `%s` for `%s` parameter", targetType, name) + ) ); } else { ParameterType type = targetType.isStringShape() ? ParameterType.STRING : ParameterType.BOOLEAN; if (endpointParams.containsKey(name) && type != endpointParams.get(name).getType()) { errors.add( - parameterError( - memberShape, - trait, - "ContextParam.InconsistentType", - String.format("Inconsistent type for `%s` parameter", name) - ) + parameterError( + memberShape, + trait, + "ContextParam.InconsistentType", + String.format("Inconsistent type for `%s` parameter", name) + ) ); } else { endpointParams.put( - name, - Parameter.builder() - .name(name) - .type(type) - .sourceLocation(trait) - .build() + name, + Parameter.builder() + .name(name) + .type(type) + .sourceLocation(trait) + .build() ); } } @@ -212,9 +212,9 @@ private Pair, Map> validateAndExtractPa } private List validateParametersMatching( - ServiceShape serviceShape, - Parameters ruleSetParams, - Map modelParams + ServiceShape serviceShape, + Parameters ruleSetParams, + Map modelParams ) { List errors = new ArrayList<>(); Set matchedParams = new HashSet<>(); @@ -229,27 +229,27 @@ private List validateParametersMatching( if (!modelParams.containsKey(name)) { errors.add( - parameterError( - serviceShape, - parameter, - "RuleSet.UnmatchedName", - String.format( - "Parameter `%s` exists in ruleset but not in service model, existing params: %s", - name, - String.join(", ", modelParams.keySet()) + parameterError( + serviceShape, + parameter, + "RuleSet.UnmatchedName", + String.format( + "Parameter `%s` exists in ruleset but not in service model, existing params: %s", + name, + String.join(", ", modelParams.keySet()) + ) ) - ) ); } else { matchedParams.add(name); if (parameter.getType() != modelParams.get(name).getType()) { errors.add( - parameterError( - serviceShape, - parameter, - "RuleSet.TypeMismatch", - String.format("Type mismatch for parameter `%s`", name) - ) + parameterError( + serviceShape, + parameter, + "RuleSet.TypeMismatch", + String.format("Type mismatch for parameter `%s`", name) + ) ); } } @@ -258,16 +258,16 @@ private List validateParametersMatching( for (Map.Entry entry : modelParams.entrySet()) { if (!matchedParams.contains(entry.getKey())) { errors.add( - parameterError( - serviceShape, - serviceShape.expectTrait(EndpointRuleSetTrait.class), - "RuleSet.UnmatchedName", - String.format( - "Parameter `%s` exists in service model but not in ruleset, existing params: %s", - entry.getKey(), - matchedParams + parameterError( + serviceShape, + serviceShape.expectTrait(EndpointRuleSetTrait.class), + "RuleSet.UnmatchedName", + String.format( + "Parameter `%s` exists in service model but not in ruleset, existing params: %s", + entry.getKey(), + matchedParams + ) ) - ) ); } } @@ -276,20 +276,20 @@ private List validateParametersMatching( } private List validateTestsParameters( - Model model, - TopDownIndex topDownIndex, - ServiceShape serviceShape, - EndpointTestsTrait trait, - EndpointRuleSet ruleSet + Model model, + TopDownIndex topDownIndex, + ServiceShape serviceShape, + EndpointTestsTrait trait, + EndpointRuleSet ruleSet ) { List errors = new ArrayList<>(); Set rulesetParamNames = new HashSet<>(); Map> testSuiteParams = extractTestSuiteParameters( - model, - topDownIndex, - serviceShape, - ruleSet, - trait + model, + topDownIndex, + serviceShape, + ruleSet, + trait ); for (Parameter parameter : ruleSet.getParameters()) { @@ -300,29 +300,29 @@ private List validateTestsParameters( // All test parameter types from corresponding ruleset parameters must match in all test cases. if (!testSuiteHasParam) { errors.add( - danger( - serviceShape, - parameter, - String.format("Parameter `%s` is never used in an `EndpointTests` test case", name) - ) - .toBuilder() - .id(getName() + ".TestCase.Unused") - .build() + danger( + serviceShape, + parameter, + String.format("Parameter `%s` is never used in an `EndpointTests` test case", name) + ) + .toBuilder() + .id(getName() + ".TestCase.Unused") + .build() ); } else { for (Parameter testParam : testSuiteParams.get(name)) { if (testParam.getType() != parameter.getType()) { errors.add( - parameterError( - serviceShape, - testParam, - "TestCase.TypeMismatch", - String.format( - "Type mismatch for parameter `%s`, `%s` expected", - testParam.getName().toString(), - parameter.getType() + parameterError( + serviceShape, + testParam, + "TestCase.TypeMismatch", + String.format( + "Type mismatch for parameter `%s`, `%s` expected", + testParam.getName().toString(), + parameter.getType() + ) ) - ) ); } } @@ -330,15 +330,15 @@ private List validateTestsParameters( // All required params from a ruleset must be present in all test cases. if (parameter.isRequired() && !parameter.getDefault().isPresent() - && (!testSuiteHasParam || testSuiteParams.get(name).size() != trait.getTestCases().size()) + && (!testSuiteHasParam || testSuiteParams.get(name).size() != trait.getTestCases().size()) ) { errors.add( - parameterError( - serviceShape, - parameter, - "TestCase.RequiredMissing", - String.format("Required parameter `%s` is missing in at least one test case", name) - ) + parameterError( + serviceShape, + parameter, + "TestCase.RequiredMissing", + String.format("Required parameter `%s` is missing in at least one test case", name) + ) ); } } @@ -347,12 +347,12 @@ private List validateTestsParameters( for (Map.Entry> entry : testSuiteParams.entrySet()) { if (!rulesetParamNames.contains(entry.getKey())) { errors.add( - parameterError( - serviceShape, - entry.getValue().get(0), - "TestCase.Undefined", - String.format("Test parameter `%s` is not defined in ruleset", entry.getKey()) - ) + parameterError( + serviceShape, + entry.getValue().get(0), + "TestCase.Undefined", + String.format("Test parameter `%s` is not defined in ruleset", entry.getKey()) + ) ); } } @@ -361,11 +361,11 @@ private List validateTestsParameters( } private Map> extractTestSuiteParameters( - Model model, - TopDownIndex topDownIndex, - ServiceShape serviceShape, - EndpointRuleSet ruleSet, - EndpointTestsTrait trait + Model model, + TopDownIndex topDownIndex, + ServiceShape serviceShape, + EndpointRuleSet ruleSet, + EndpointTestsTrait trait ) { Map> params = new HashMap<>(); for (EndpointTestCase testCase : trait.getTestCases()) { @@ -394,20 +394,20 @@ private Map> extractTestSuiteParameters( for (OperationShape operationShape : topDownIndex.getContainedOperations(serviceShape)) { if (operationShape.getId().getName().equals(input.getOperationName())) { StructureShape inputShape = model.expectShape( - operationShape.getInputShape(), - StructureShape.class + operationShape.getInputShape(), + StructureShape.class ); for (String name : inputShape.getMemberNames()) { MemberShape memberShape = inputShape.getMember(name).get(); if (input.getOperationParams().containsMember(name) - && memberShape.hasTrait(ContextParamTrait.class) + && memberShape.hasTrait(ContextParamTrait.class) ) { String paramName = memberShape.expectTrait(ContextParamTrait.class).getName(); testParams.add( - buildParameter( - paramName, - input.getOperationParams().expectMember(name) - ) + buildParameter( + paramName, + input.getOperationParams().expectMember(name) + ) ); } } @@ -435,11 +435,11 @@ private Parameter buildParameter(Map.Entry entry, String name) { private Parameter buildParameter(String name, Node node) { Value value = Value.fromNode(node); return Parameter.builder() - .sourceLocation(value) - .name(name) - .value(value) - .type(ParameterType.fromType(value.getType())) - .build(); + .sourceLocation(value) + .name(name) + .value(value) + .type(ParameterType.fromType(value.getType())) + .build(); } private List merge(List previousList, List newList) { @@ -448,10 +448,10 @@ private List merge(List previousList, List newL } private ValidationEvent parameterError( - Shape shape, - FromSourceLocation sourceLocation, - String id, - String message + Shape shape, + FromSourceLocation sourceLocation, + String id, + String message ) { return error(shape, sourceLocation, message).toBuilder().id(getName() + "." + id).build(); } diff --git a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetUriValidator.java b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetUriValidator.java index fd22941dfc2..91352289712 100644 --- a/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetUriValidator.java +++ b/smithy-rules-engine/src/main/java/software/amazon/smithy/rulesengine/validators/RuleSetUriValidator.java @@ -34,9 +34,9 @@ public List validate(Model model) { List events = new ArrayList<>(); for (ServiceShape serviceShape : model.getServiceShapesWithTrait(EndpointRuleSetTrait.class)) { events.addAll( - new UriSchemeVisitor(serviceShape) - .visitRuleset(serviceShape.expectTrait(EndpointRuleSetTrait.class).getEndpointRuleSet()) - .collect(Collectors.toList()) + new UriSchemeVisitor(serviceShape) + .visitRuleset(serviceShape.expectTrait(EndpointRuleSetTrait.class).getEndpointRuleSet()) + .collect(Collectors.toList()) ); } return events; @@ -95,12 +95,12 @@ private Optional validateTemplate(Template template) { String scheme = ((Template.Literal) part).getValue(); if (!(scheme.startsWith("http://") || scheme.startsWith("https://"))) { return Optional.of( - error( - serviceShape, - template, - "URI should start with `http://` or `https://` but the URI started with " - + scheme - ) + error( + serviceShape, + template, + "URI should start with `http://` or `https://` but the URI started with " + + scheme + ) ); } } diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/analysis/CoverageCheckerTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/analysis/CoverageCheckerTest.java index d86ee115983..c4ab0254055 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/analysis/CoverageCheckerTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/analysis/CoverageCheckerTest.java @@ -20,12 +20,12 @@ public class CoverageCheckerTest { @Test public void checkCoverage() { EndpointRuleSet endpointRuleSet = EndpointRuleSet.fromNode( - Node.parse( - IoUtils.readUtf8Resource( - CoverageCheckerTest.class, - "local-region-override.json" + Node.parse( + IoUtils.readUtf8Resource( + CoverageCheckerTest.class, + "local-region-override.json" + ) ) - ) ); CoverageChecker checker = new CoverageChecker(endpointRuleSet); @@ -36,12 +36,12 @@ public void checkCoverage() { assertEquals(0, (int) checker.checkCoverage().count()); EndpointTestsTrait endpointTestsTrait = EndpointTestsTrait.fromNode( - Node.parse( - IoUtils.readUtf8Resource( - CoverageCheckerTest.class, - "local-region-override-tests.json" + Node.parse( + IoUtils.readUtf8Resource( + CoverageCheckerTest.class, + "local-region-override-tests.json" + ) ) - ) ); for (EndpointTestCase testCase : endpointTestsTrait.getTestCases()) { checker.evaluateTestCase(testCase); diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/EndpointRuleSetTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/EndpointRuleSetTest.java index 794abb5083d..504d1166b7b 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/EndpointRuleSetTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/EndpointRuleSetTest.java @@ -27,49 +27,49 @@ public class EndpointRuleSetTest { private static final Endpoint MINIMAL_ENDPOINT = Endpoint.builder() - .sourceLocation(SourceLocation.none()) - .url(Literal.of("https://{Region}.amazonaws.com")) - .addAuthScheme( - Identifier.of("sigv4"), - MapUtils.of( - Identifier.of("signingRegion"), - Literal.of("{Region}"), - Identifier.of("signingName"), - Literal.of("serviceName") + .sourceLocation(SourceLocation.none()) + .url(Literal.of("https://{Region}.amazonaws.com")) + .addAuthScheme( + Identifier.of("sigv4"), + MapUtils.of( + Identifier.of("signingRegion"), + Literal.of("{Region}"), + Identifier.of("signingName"), + Literal.of("serviceName") + ) ) - ) - .build(); + .build(); @Test public void testRuleEval() { EndpointRuleSet actual = TestRunnerTest.getMinimalEndpointRuleSet(); Value result = RuleEvaluator.evaluate( - actual, - MapUtils.of( - Identifier.of("Region"), - Value.stringValue("us-east-1") - ) + actual, + MapUtils.of( + Identifier.of("Region"), + Value.stringValue("us-east-1") + ) ); EndpointValue expected = new EndpointValue.Builder(SourceLocation.none()) - .url("https://us-east-1.amazonaws.com") - .putProperty( - "authSchemes", - Value.arrayValue( - Collections.singletonList( - Value.recordValue( - MapUtils.of( - Identifier.of("name"), - Value.stringValue("sigv4"), - Identifier.of("signingRegion"), - Value.stringValue("us-east-1"), - Identifier.of("signingName"), - Value.stringValue("serviceName") - ) + .url("https://us-east-1.amazonaws.com") + .putProperty( + "authSchemes", + Value.arrayValue( + Collections.singletonList( + Value.recordValue( + MapUtils.of( + Identifier.of("name"), + Value.stringValue("sigv4"), + Identifier.of("signingRegion"), + Value.stringValue("us-east-1"), + Identifier.of("signingName"), + Value.stringValue("serviceName") + ) + ) + ) ) - ) ) - ) - .build(); + .build(); assertEquals(expected, result.expectEndpointValue()); } @@ -84,29 +84,29 @@ public void testDeterministicSerde() { public void testMinimalRuleset() { EndpointRuleSet actual = TestRunnerTest.getMinimalEndpointRuleSet(); assertEquals( - EndpointRuleSet.builder() - .version("1.3") - .parameters( - Parameters - .builder() - .addParameter( - Parameter.builder() - .name("Region") - .builtIn("AWS::Region") - .type(ParameterType.STRING) - .required(true) - .build() + EndpointRuleSet.builder() + .version("1.3") + .parameters( + Parameters + .builder() + .addParameter( + Parameter.builder() + .name("Region") + .builtIn("AWS::Region") + .type(ParameterType.STRING) + .required(true) + .build() + ) + .build() ) - .build() - ) - .addRule( - Rule - .builder() - .description("base rule") - .endpoint(MINIMAL_ENDPOINT) - ) - .build(), - actual + .addRule( + Rule + .builder() + .description("base rule") + .endpoint(MINIMAL_ENDPOINT) + ) + .build(), + actual ); } @@ -114,12 +114,12 @@ public void testMinimalRuleset() { public void testEndpointCollectorMinimalRuleset() { EndpointRuleSet ers = TestRunnerTest.getMinimalEndpointRuleSet(); Map actual = EndpointRuleSet.EndpointPathCollector - .from( - EndpointRuleSetTrait.builder() - .ruleSet(ers.toNode()) - .build() - ) - .collect(); + .from( + EndpointRuleSetTrait.builder() + .ruleSet(ers.toNode()) + .build() + ) + .collect(); Map expected = MapUtils.of("/rules/0/endpoint", MINIMAL_ENDPOINT); assertEquals(expected, actual); } @@ -127,15 +127,15 @@ public void testEndpointCollectorMinimalRuleset() { @Test public void testEndpointCollectorEmptyRuleset() { EndpointRuleSet ers = EndpointRuleSet.builder() - .parameters(Parameters.builder().build()) - .build(); + .parameters(Parameters.builder().build()) + .build(); Map actual = EndpointRuleSet.EndpointPathCollector - .from( - EndpointRuleSetTrait.builder() - .ruleSet(ers.toNode()) - .build() - ) - .collect(); + .from( + EndpointRuleSetTrait.builder() + .ruleSet(ers.toNode()) + .build() + ) + .collect(); Map expected = Collections.emptyMap(); assertEquals(expected, actual); } @@ -143,37 +143,37 @@ public void testEndpointCollectorEmptyRuleset() { @Test public void testEndpointCollectorComplexRuleset() { EndpointRuleSet ers = TestRunnerTest.getEndpointRuleSet( - EndpointRuleSetTest.class, - "example-complex-ruleset.json" + EndpointRuleSetTest.class, + "example-complex-ruleset.json" ); Map actual = EndpointRuleSet.EndpointPathCollector - .from( - EndpointRuleSetTrait.builder() - .ruleSet(ers.toNode()) - .build() - ) - .collect(); + .from( + EndpointRuleSetTrait.builder() + .ruleSet(ers.toNode()) + .build() + ) + .collect(); Map expected = MapUtils.of( - "/rules/1/rules/0/rules/0/rules/1/endpoint", - Endpoint.builder() - .url(Literal.of("https://example.{Region}.dual-stack-dns-suffix.com")) - .build(), - "/rules/1/rules/0/rules/1/rules/0/rules/0/endpoint", - Endpoint.builder() - .url(Literal.of("https://example-fips.{Region}.dual-stack-dns-suffix.com")) - .build(), - "/rules/1/rules/0/rules/2/endpoint", - Endpoint.builder() - .url(Literal.of("https://example.{Region}.dual-stack-dns-suffix.com")) - .build(), - "/rules/0/rules/1/endpoint", - Endpoint.builder() - .url(new Reference(Identifier.of("Endpoint"), SourceLocation.NONE)) - .build(), - "/rules/1/rules/0/rules/0/rules/0/rules/0/rules/0/endpoint", - Endpoint.builder() - .url(Literal.of("https://example-fips.{Region}.dual-stack-dns-suffix.com")) - .build() + "/rules/1/rules/0/rules/0/rules/1/endpoint", + Endpoint.builder() + .url(Literal.of("https://example.{Region}.dual-stack-dns-suffix.com")) + .build(), + "/rules/1/rules/0/rules/1/rules/0/rules/0/endpoint", + Endpoint.builder() + .url(Literal.of("https://example-fips.{Region}.dual-stack-dns-suffix.com")) + .build(), + "/rules/1/rules/0/rules/2/endpoint", + Endpoint.builder() + .url(Literal.of("https://example.{Region}.dual-stack-dns-suffix.com")) + .build(), + "/rules/0/rules/1/endpoint", + Endpoint.builder() + .url(new Reference(Identifier.of("Endpoint"), SourceLocation.NONE)) + .build(), + "/rules/1/rules/0/rules/0/rules/0/rules/0/rules/0/endpoint", + Endpoint.builder() + .url(Literal.of("https://example-fips.{Region}.dual-stack-dns-suffix.com")) + .build() ); assertEquals(expected, actual); } diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/EndpointTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/EndpointTest.java index 7afa9e3370a..315bcdadc8d 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/EndpointTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/EndpointTest.java @@ -20,28 +20,28 @@ public class EndpointTest { private static final Pair> SIGV4_AUTH_SCHEME = Pair.of( - "sigv4", - Collections.emptyMap() + "sigv4", + Collections.emptyMap() ); private static final Pair> SIGV4A_AUTH_SCHEME = Pair.of( - "sigv4a", - MapUtils.of( - Identifier.of("signingRegionSet"), - Literal.tupleLiteral(ListUtils.of(Literal.of("*"))) - ) + "sigv4a", + MapUtils.of( + Identifier.of("signingRegionSet"), + Literal.tupleLiteral(ListUtils.of(Literal.of("*"))) + ) ); @Test public void testGetEndpointAuthSchemes() { Endpoint endpoint = Endpoint.builder() - .url(Literal.of("https://abc.service.com")) - .addAuthScheme(Identifier.of(SIGV4A_AUTH_SCHEME.getLeft()), SIGV4A_AUTH_SCHEME.getRight()) - .addAuthScheme(Identifier.of(SIGV4_AUTH_SCHEME.getLeft()), SIGV4_AUTH_SCHEME.getRight()) - .build(); + .url(Literal.of("https://abc.service.com")) + .addAuthScheme(Identifier.of(SIGV4A_AUTH_SCHEME.getLeft()), SIGV4A_AUTH_SCHEME.getRight()) + .addAuthScheme(Identifier.of(SIGV4_AUTH_SCHEME.getLeft()), SIGV4_AUTH_SCHEME.getRight()) + .build(); List> actual = endpoint.getEndpointAuthSchemes(); List> expected = ListUtils.of( - convertAuthSchemeToMap(SIGV4A_AUTH_SCHEME), - convertAuthSchemeToMap(SIGV4_AUTH_SCHEME) + convertAuthSchemeToMap(SIGV4A_AUTH_SCHEME), + convertAuthSchemeToMap(SIGV4_AUTH_SCHEME) ); assertEquals(expected, actual); } @@ -49,8 +49,8 @@ public void testGetEndpointAuthSchemes() { @Test public void testEmptyGetEndpointAuthSchemes() { Endpoint endpoint = Endpoint.builder() - .url(Literal.of("https://abc.service.com")) - .build(); + .url(Literal.of("https://abc.service.com")) + .build(); List> actual = endpoint.getEndpointAuthSchemes(); List> expected = Collections.emptyList(); assertEquals(expected, actual); diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/IntegrationTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/IntegrationTest.java index a854cb7a717..aa950ed6e06 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/IntegrationTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/IntegrationTest.java @@ -28,32 +28,32 @@ public class IntegrationTest { public static List validRules() throws Exception { try ( - Stream paths = Files.list( - Paths.get(IntegrationTest.class.getResource("errorfiles/valid/").toURI()) - ) + Stream paths = Files.list( + Paths.get(IntegrationTest.class.getResource("errorfiles/valid/").toURI()) + ) ) { return paths.filter(path -> path.toString().endsWith(".smithy")) - .map(path -> Model.assembler().discoverModels().addImport(path).assemble().unwrap()) - .flatMap(model -> model.getServiceShapesWithTrait(EndpointRuleSetTrait.class).stream()) - .map(serviceShape -> serviceShape.expectTrait(EndpointRuleSetTrait.class).getEndpointRuleSet()) - .collect(Collectors.toList()); + .map(path -> Model.assembler().discoverModels().addImport(path).assemble().unwrap()) + .flatMap(model -> model.getServiceShapesWithTrait(EndpointRuleSetTrait.class).stream()) + .map(serviceShape -> serviceShape.expectTrait(EndpointRuleSetTrait.class).getEndpointRuleSet()) + .collect(Collectors.toList()); } } public static List> invalidRules() throws Exception { try ( - Stream paths = Files.list( - Paths.get(IntegrationTest.class.getResource("invalid-rules/").toURI()) - ) + Stream paths = Files.list( + Paths.get(IntegrationTest.class.getResource("invalid-rules/").toURI()) + ) ) { return paths.map(path -> { try { String pathContents = IoUtils.toUtf8String(new FileInputStream(path.toFile())); Node content = Node.parseJsonWithComments( - pathContents, - path.subpath(path.getNameCount() - 2, path.getNameCount()) - .toString() - .replace("\\", "/") + pathContents, + path.subpath(path.getNameCount() - 2, path.getNameCount()) + .toString() + .replace("\\", "/") ); List commentLines = new ArrayList<>(); diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/TypeIntrospectionTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/TypeIntrospectionTest.java index 84ba4437868..710e7bd1dc7 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/TypeIntrospectionTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/TypeIntrospectionTest.java @@ -17,12 +17,12 @@ public class TypeIntrospectionTest { @Test public void introspectCorrectTypesForFunctions() { EndpointRuleSet endpointRuleSet = EndpointRuleSet.fromNode( - Node.parse( - IoUtils.readUtf8Resource( - TypeIntrospectionTest.class, - "substring.json" + Node.parse( + IoUtils.readUtf8Resource( + TypeIntrospectionTest.class, + "substring.json" + ) ) - ) ); List conditions = endpointRuleSet.getRules().get(0).getConditions(); // stringEquals({TestCaseId}, 1) @@ -35,12 +35,12 @@ public void introspectCorrectTypesForFunctions() { @Test public void introspectCorrectTypesForGetAttr() { EndpointRuleSet endpointRuleSet = EndpointRuleSet.fromNode( - Node.parse( - IoUtils.readUtf8Resource( - TypeIntrospectionTest.class, - "get-attr-type-inference.json" + Node.parse( + IoUtils.readUtf8Resource( + TypeIntrospectionTest.class, + "get-attr-type-inference.json" + ) ) - ) ); // bucketUrl.authority Type actualType = endpointRuleSet.getRules().get(0).getConditions().get(2).getFunction().type(); diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/evaluation/RuleEngineTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/evaluation/RuleEngineTest.java index 4297485aa67..2dd07f840d1 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/evaluation/RuleEngineTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/evaluation/RuleEngineTest.java @@ -21,32 +21,32 @@ public class RuleEngineTest { public void testRuleEval() { EndpointRuleSet actual = TestRunnerTest.getMinimalEndpointRuleSet(); Value result = RuleEvaluator.evaluate( - actual, - MapUtils.of( - Identifier.of("Region"), - Value.stringValue("us-east-1") - ) + actual, + MapUtils.of( + Identifier.of("Region"), + Value.stringValue("us-east-1") + ) ); EndpointValue expected = new EndpointValue.Builder(SourceLocation.none()) - .url("https://us-east-1.amazonaws.com") - .putProperty( - "authSchemes", - Value.arrayValue( - Collections.singletonList( - Value.recordValue( - MapUtils.of( - Identifier.of("name"), - Value.stringValue("sigv4"), - Identifier.of("signingRegion"), - Value.stringValue("us-east-1"), - Identifier.of("signingName"), - Value.stringValue("serviceName") - ) + .url("https://us-east-1.amazonaws.com") + .putProperty( + "authSchemes", + Value.arrayValue( + Collections.singletonList( + Value.recordValue( + MapUtils.of( + Identifier.of("name"), + Value.stringValue("sigv4"), + Identifier.of("signingRegion"), + Value.stringValue("us-east-1"), + Identifier.of("signingName"), + Value.stringValue("serviceName") + ) + ) + ) ) - ) ) - ) - .build(); + .build(); assertEquals(expected, result.expectEndpointValue()); } } diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/ParameterTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/ParameterTest.java index 141c25f939d..2ef57f810e3 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/ParameterTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/ParameterTest.java @@ -18,22 +18,22 @@ public class ParameterTest { @Test public void parameterToBuilderRoundTrips() { Parameter p = Parameter.builder() - .name("test") - .builtIn("Test::BuiltIn") - .required(true) - .defaultValue(Value.booleanValue(true)) - .type(ParameterType.BOOLEAN) - .deprecated( - Deprecated.fromNode( - ObjectNode.builder() - .withMember("message", "message") - .withMember("since", "2020-07-02") - .build() + .name("test") + .builtIn("Test::BuiltIn") + .required(true) + .defaultValue(Value.booleanValue(true)) + .type(ParameterType.BOOLEAN) + .deprecated( + Deprecated.fromNode( + ObjectNode.builder() + .withMember("message", "message") + .withMember("since", "2020-07-02") + .build() + ) ) - ) - .value(Node.from(true)) - .documentation("here are some docs") - .build(); + .value(Node.from(true)) + .documentation("here are some docs") + .build(); assertEquals(p, p.toBuilder().build()); } } diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/functions/FunctionsTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/functions/FunctionsTest.java index 67c804edf18..7c86631bb66 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/functions/FunctionsTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/functions/FunctionsTest.java @@ -33,14 +33,14 @@ public void booleanEqualsOfExpressions() { @Test public void getAttrOfExpressions() { GetAttr function = GetAttr.ofExpressions( - Expression.getReference(Identifier.of("a"), SourceLocation.none()), - "b" + Expression.getReference(Identifier.of("a"), SourceLocation.none()), + "b" ); assertThat(function, instanceOf(GetAttr.class)); GetAttr function2 = GetAttr.ofExpressions( - Expression.getReference(Identifier.of("a"), SourceLocation.none()), - Expression.of("b") + Expression.getReference(Identifier.of("a"), SourceLocation.none()), + Expression.of("b") ); assertThat(function2, instanceOf(GetAttr.class)); } @@ -83,10 +83,10 @@ public void substringOfExpression() { assertThat(function, instanceOf(Substring.class)); Substring function2 = Substring.ofExpressions( - Expression.of("foobar"), - Expression.of(1), - Expression.of(2), - Expression.of(false) + Expression.of("foobar"), + Expression.of(1), + Expression.of(2), + Expression.of(false) ); assertThat(function2, instanceOf(Substring.class)); } diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/functions/GetAttrTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/functions/GetAttrTest.java index be518b3321e..cf17bba2371 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/functions/GetAttrTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/functions/GetAttrTest.java @@ -18,17 +18,17 @@ public class GetAttrTest { public void getAttrManualEqualToTemplate() { Expression asTemplate = Expression.parseShortform("a#b[5]", SourceLocation.none()); Expression asGetAttr = GetAttr.fromNode( - ObjectNode - .builder() - .withMember("fn", Node.from("getAttr")) - .withMember( - "argv", - Node.fromNodes( - ObjectNode.builder().withMember("ref", "a").build(), - Node.from("b[5]") - ) - ) - .build() + ObjectNode + .builder() + .withMember("fn", Node.from("getAttr")) + .withMember( + "argv", + Node.fromNodes( + ObjectNode.builder().withMember("ref", "a").build(), + Node.from("b[5]") + ) + ) + .build() ); assertEquals(asTemplate, asGetAttr); assertEquals(asTemplate.hashCode(), asGetAttr.hashCode()); diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/rule/RuleTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/rule/RuleTest.java index f6357442f22..e61288846dd 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/rule/RuleTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/syntax/rule/RuleTest.java @@ -29,69 +29,69 @@ public void validateAndErrorsTest() { StringEquals equalsB = StringEquals.ofExpressions(p2.toExpression(), "b"); StringEquals equalsC = StringEquals.ofExpressions(p3.toExpression(), "c"); Rule rule = Rule.builder() - .validateOrElse("param1 value is not a", condition(equalsA)) - .errorOrElse("param2 is b", condition(equalsB)) - .validateOrElse("param3 value is not c", condition(equalsC)) - .errorOrElse("param2 is b", condition(equalsB)) - .treeRule(Rule.builder().error("rule matched: p3")); + .validateOrElse("param1 value is not a", condition(equalsA)) + .errorOrElse("param2 is b", condition(equalsB)) + .validateOrElse("param3 value is not c", condition(equalsC)) + .errorOrElse("param2 is b", condition(equalsB)) + .treeRule(Rule.builder().error("rule matched: p3")); Parameters parameters = Parameters.builder().addParameter(p1).addParameter(p2).addParameter(p3).build(); EndpointRuleSet ruleset = EndpointRuleSet.builder().version("1.1").parameters(parameters).addRule(rule).build(); ruleset.typeCheck(new Scope<>()); assertEquals( - RuleEvaluator.evaluate( - ruleset, - MapUtils.of( - Identifier.of("param1"), - Value.stringValue("a"), - Identifier.of("param2"), - Value.stringValue("c"), - Identifier.of("param3"), - Value.stringValue("c") - ) - ), - Value.stringValue("rule matched: p3") + RuleEvaluator.evaluate( + ruleset, + MapUtils.of( + Identifier.of("param1"), + Value.stringValue("a"), + Identifier.of("param2"), + Value.stringValue("c"), + Identifier.of("param3"), + Value.stringValue("c") + ) + ), + Value.stringValue("rule matched: p3") ); assertEquals( - RuleEvaluator.evaluate( - ruleset, - MapUtils.of( - Identifier.of("param1"), - Value.stringValue("b"), - Identifier.of("param2"), - Value.stringValue("c"), - Identifier.of("param3"), - Value.stringValue("c") - ) - ), - Value.stringValue("param1 value is not a") + RuleEvaluator.evaluate( + ruleset, + MapUtils.of( + Identifier.of("param1"), + Value.stringValue("b"), + Identifier.of("param2"), + Value.stringValue("c"), + Identifier.of("param3"), + Value.stringValue("c") + ) + ), + Value.stringValue("param1 value is not a") ); assertEquals( - RuleEvaluator.evaluate( - ruleset, - MapUtils.of( - Identifier.of("param1"), - Value.stringValue("a"), - Identifier.of("param2"), - Value.stringValue("b"), - Identifier.of("param3"), - Value.stringValue("c") - ) - ), - Value.stringValue("param2 is b") + RuleEvaluator.evaluate( + ruleset, + MapUtils.of( + Identifier.of("param1"), + Value.stringValue("a"), + Identifier.of("param2"), + Value.stringValue("b"), + Identifier.of("param3"), + Value.stringValue("c") + ) + ), + Value.stringValue("param2 is b") ); assertEquals( - RuleEvaluator.evaluate( - ruleset, - MapUtils.of( - Identifier.of("param1"), - Value.stringValue("a"), - Identifier.of("param2"), - Value.stringValue("c"), - Identifier.of("param3"), - Value.stringValue("d") - ) - ), - Value.stringValue("param3 value is not c") + RuleEvaluator.evaluate( + ruleset, + MapUtils.of( + Identifier.of("param1"), + Value.stringValue("a"), + Identifier.of("param2"), + Value.stringValue("c"), + Identifier.of("param3"), + Value.stringValue("d") + ) + ), + Value.stringValue("param3 value is not c") ); } diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/value/TemplateTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/value/TemplateTest.java index 4eb1cc1912e..d6c3fb4d93d 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/value/TemplateTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/language/value/TemplateTest.java @@ -23,12 +23,12 @@ public void validateTemplate() { checkTemplateParts("a{B}c", "a", "{B}", "c"); checkTemplateParts("a{{b}}c", "a{b}c"); checkTemplateParts( - "https://{Bucket#arn-region}.{Region}.amazonaws.com", - "https://", - "{Bucket#arn-region}", - ".", - "{Region}", - ".amazonaws.com" + "https://{Bucket#arn-region}.{Region}.amazonaws.com", + "https://", + "{Bucket#arn-region}", + ".", + "{Region}", + ".amazonaws.com" ); checkTemplateParts("https://{Partition#meta.dnsSuffix}", "https://", "{Partition#meta.dnsSuffix}"); checkTemplateParts("https://{ {\"ref\": \"Foo\"} }.com", "https://", "{ {\"ref\": \"Foo\"} }", ".com"); @@ -47,22 +47,22 @@ private void checkTemplateParts(String templateInput, String... parts) { @Test public void validateShortformParsing() { assertEquals( - Expression.parseShortform("a", SourceLocation.none()), - Expression.getReference(Identifier.of("a"), SourceLocation.none()) + Expression.parseShortform("a", SourceLocation.none()), + Expression.getReference(Identifier.of("a"), SourceLocation.none()) ); assertEquals( - Expression.parseShortform("a#b", SourceLocation.none()), - GetAttr.ofExpressions( - Expression.getReference(Identifier.of("a"), SourceLocation.none()), - "b" - ) + Expression.parseShortform("a#b", SourceLocation.none()), + GetAttr.ofExpressions( + Expression.getReference(Identifier.of("a"), SourceLocation.none()), + "b" + ) ); assertEquals( - Expression.parseShortform("a#b.c", SourceLocation.none()), - GetAttr.ofExpressions( - Expression.getReference(Identifier.of("a"), SourceLocation.none()), - "b.c" - ) + Expression.parseShortform("a#b.c", SourceLocation.none()), + GetAttr.ofExpressions( + Expression.getReference(Identifier.of("a"), SourceLocation.none()), + "b.c" + ) ); } diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/CleanEndpointTestOperationInputTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/CleanEndpointTestOperationInputTest.java index b1b86b7f6a3..777e9ebd9e7 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/CleanEndpointTestOperationInputTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/CleanEndpointTestOperationInputTest.java @@ -26,10 +26,10 @@ public class CleanEndpointTestOperationInputTest { @BeforeAll public static void before() { model = Model.assembler() - .discoverModels(ContextIndexTest.class.getClassLoader()) - .addImport(ContextIndexTest.class.getResource("traits-test-model.smithy")) - .assemble() - .unwrap(); + .discoverModels(ContextIndexTest.class.getClassLoader()) + .addImport(ContextIndexTest.class.getResource("traits-test-model.smithy")) + .assemble() + .unwrap(); } @Test @@ -45,8 +45,8 @@ public void retainsTestsIfOperationRemains() { assertTrue(transformedService.hasTrait(EndpointTestsTrait.class)); Node.assertEquals( - transformedService.expectTrait(EndpointTestsTrait.class).toNode(), - mainService.expectTrait(EndpointTestsTrait.class).toNode() + transformedService.expectTrait(EndpointTestsTrait.class).toNode(), + mainService.expectTrait(EndpointTestsTrait.class).toNode() ); } @@ -74,10 +74,10 @@ public void retainsTraitIfAllTestsRemoved() { ModelTransformer modelTransformer = ModelTransformer.create(); replacementTrait = replacementTrait.toBuilder().removeTestCase(replacementTrait.getTestCases().get(0)).build(); Model transformed = modelTransformer.replaceShapes( - model, - ListUtils.of( - serviceShape.toBuilder().addTrait(replacementTrait).build() - ) + model, + ListUtils.of( + serviceShape.toBuilder().addTrait(replacementTrait).build() + ) ); // Then do the filtering. diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/ClientContextParamsTraitTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/ClientContextParamsTraitTest.java index 0e152c6452c..d2e83cb465f 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/ClientContextParamsTraitTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/ClientContextParamsTraitTest.java @@ -18,31 +18,31 @@ public final class ClientContextParamsTraitTest { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("traits-test-model.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("traits-test-model.smithy")) + .assemble() + .unwrap(); ServiceShape service = result - .expectShape(ShapeId.from("smithy.example#ExampleService")) - .asServiceShape() - .get(); + .expectShape(ShapeId.from("smithy.example#ExampleService")) + .asServiceShape() + .get(); ClientContextParamsTrait trait = service.getTrait(ClientContextParamsTrait.class).get(); assertEquals( - trait.getParameters(), - MapUtils.of( - "stringFoo", - ClientContextParamDefinition.builder() - .type(ShapeType.STRING) - .documentation("a client string parameter") - .build(), - "boolFoo", - ClientContextParamDefinition.builder() - .type(ShapeType.BOOLEAN) - .documentation("a client boolean parameter") - .build() - ) + trait.getParameters(), + MapUtils.of( + "stringFoo", + ClientContextParamDefinition.builder() + .type(ShapeType.STRING) + .documentation("a client string parameter") + .build(), + "boolFoo", + ClientContextParamDefinition.builder() + .type(ShapeType.BOOLEAN) + .documentation("a client boolean parameter") + .build() + ) ); } } diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/ContextIndexTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/ContextIndexTest.java index a03ec4021de..518e83c3a4c 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/ContextIndexTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/ContextIndexTest.java @@ -22,10 +22,10 @@ public class ContextIndexTest { @BeforeAll public static void before() { model = Model.assembler() - .discoverModels(ContextIndexTest.class.getClassLoader()) - .addImport(ContextIndexTest.class.getResource("traits-test-model.smithy")) - .assemble() - .unwrap(); + .discoverModels(ContextIndexTest.class.getClassLoader()) + .addImport(ContextIndexTest.class.getResource("traits-test-model.smithy")) + .assemble() + .unwrap(); } @Test @@ -33,22 +33,22 @@ public void indexesClientContextParams() { ContextIndex index = ContextIndex.of(model); Map clientContexts = index.getClientContextParams( - model.expectShape(ShapeId.from("smithy.example#ExampleService")) + model.expectShape(ShapeId.from("smithy.example#ExampleService")) ).get().getParameters(); assertEquals( - ClientContextParamDefinition.builder() - .type(ShapeType.STRING) - .documentation("a client string parameter") - .build(), - clientContexts.get("stringFoo") + ClientContextParamDefinition.builder() + .type(ShapeType.STRING) + .documentation("a client string parameter") + .build(), + clientContexts.get("stringFoo") ); assertEquals( - ClientContextParamDefinition.builder() - .type(ShapeType.BOOLEAN) - .documentation("a client boolean parameter") - .build(), - clientContexts.get("boolFoo") + ClientContextParamDefinition.builder() + .type(ShapeType.BOOLEAN) + .documentation("a client boolean parameter") + .build(), + clientContexts.get("boolFoo") ); } @@ -57,21 +57,21 @@ public void indexesStaticContextParams() { ContextIndex index = ContextIndex.of(model); Map staticContexts = index.getStaticContextParams( - model.expectShape(ShapeId.from("smithy.example#GetThing")) + model.expectShape(ShapeId.from("smithy.example#GetThing")) ).get().getParameters(); assertEquals( - StaticContextParamDefinition.builder() - .value(StringNode.from("some value")) - .build(), - staticContexts.get("stringBar") + StaticContextParamDefinition.builder() + .value(StringNode.from("some value")) + .build(), + staticContexts.get("stringBar") ); assertEquals( - StaticContextParamDefinition.builder() - .value(BooleanNode.from(true)) - .build(), - staticContexts.get("boolBar") + StaticContextParamDefinition.builder() + .value(BooleanNode.from(true)) + .build(), + staticContexts.get("boolBar") ); } @@ -80,21 +80,21 @@ public void indexesContextParam() { ContextIndex index = ContextIndex.of(model); Map contexts = index.getContextParams( - model.expectShape(ShapeId.from("smithy.example#GetThing")) + model.expectShape(ShapeId.from("smithy.example#GetThing")) ); assertEquals( - contexts.get(model.expectShape(ShapeId.from("smithy.example#GetThingInput$buzz"), MemberShape.class)), - ContextParamTrait.builder() - .name("stringBaz") - .build() + contexts.get(model.expectShape(ShapeId.from("smithy.example#GetThingInput$buzz"), MemberShape.class)), + ContextParamTrait.builder() + .name("stringBaz") + .build() ); assertEquals( - contexts.get(model.expectShape(ShapeId.from("smithy.example#GetThingInput$fuzz"), MemberShape.class)), - ContextParamTrait.builder() - .name("boolBaz") - .build() + contexts.get(model.expectShape(ShapeId.from("smithy.example#GetThingInput$fuzz"), MemberShape.class)), + ContextParamTrait.builder() + .name("boolBaz") + .build() ); } } diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/ContextParamTraitTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/ContextParamTraitTest.java index f4e5259728e..b9c6932dbbc 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/ContextParamTraitTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/ContextParamTraitTest.java @@ -17,14 +17,14 @@ public final class ContextParamTraitTest { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("traits-test-model.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("traits-test-model.smithy")) + .assemble() + .unwrap(); StructureShape structureShape = result.expectShape( - ShapeId.from("smithy.example#GetThingInput"), - StructureShape.class + ShapeId.from("smithy.example#GetThingInput"), + StructureShape.class ); MemberShape buzz = structureShape.getMember("buzz").get(); diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/EndpointRuleSetTraitTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/EndpointRuleSetTraitTest.java index 3cac10bf88a..c475ed85b03 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/EndpointRuleSetTraitTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/EndpointRuleSetTraitTest.java @@ -20,14 +20,14 @@ public final class EndpointRuleSetTraitTest { @Test public void indexesTheModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("traits-test-model.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("traits-test-model.smithy")) + .assemble() + .unwrap(); ServiceShape serviceShape = result.expectShape( - ShapeId.from("smithy.example#ExampleService"), - ServiceShape.class + ShapeId.from("smithy.example#ExampleService"), + ServiceShape.class ); EndpointRuleSetTrait ruleSetTrait = serviceShape.getTrait(EndpointRuleSetTrait.class).get(); @@ -40,15 +40,15 @@ public void indexesTheModel() { @Test public void roundTrips() { Node expectedNode = Node.parse( - "{\"version\":\"1.0\",\"parameters\":{\"stringParam\":{\"type\":\"string\"}" - + ",\"booleanParam\":{\"type\":\"boolean\"}},\"rules\":[]}" + "{\"version\":\"1.0\",\"parameters\":{\"stringParam\":{\"type\":\"string\"}" + + ",\"booleanParam\":{\"type\":\"boolean\"}},\"rules\":[]}" ); TraitFactory traitFactory = TraitFactory.createServiceFactory(); EndpointRuleSetTrait expectedTrait = (EndpointRuleSetTrait) traitFactory.createTrait( - EndpointRuleSetTrait.ID, - ShapeId.from("ns.example#Foo"), - expectedNode + EndpointRuleSetTrait.ID, + ShapeId.from("ns.example#Foo"), + expectedNode ).get(); EndpointRuleSetTrait actualTrait = expectedTrait.toBuilder().build(); diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/EndpointTestsTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/EndpointTestsTest.java index 42ddd9f0caf..f88fe15e53c 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/EndpointTestsTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/EndpointTestsTest.java @@ -22,106 +22,109 @@ public final class EndpointTestsTest { @Test public void loadsFromTheModel() { Model model = Model.assembler() - .discoverModels(EndpointTestsTest.class.getClassLoader()) - .addImport(EndpointTestsTest.class.getResource("traits-test-model.smithy")) - .assemble() - .unwrap(); + .discoverModels(EndpointTestsTest.class.getClassLoader()) + .addImport(EndpointTestsTest.class.getResource("traits-test-model.smithy")) + .assemble() + .unwrap(); ServiceShape serviceShape = model.expectShape( - ShapeId.from("smithy.example#ExampleService"), - ServiceShape.class + ShapeId.from("smithy.example#ExampleService"), + ServiceShape.class ); EndpointTestsTrait ruleSetTrait = serviceShape.getTrait(EndpointTestsTrait.class).get(); List testCases = ruleSetTrait.getTestCases(); assertThat(2, equalTo(testCases.size())); assertThat( - EndpointTestCase.builder() - .documentation("a documentation string") - .params( - ObjectNode.builder() - .withMember("stringFoo", "a b") - .withMember("boolFoo", false) - .build() - ) - .expect( - EndpointTestExpectation.builder() - .error("endpoint error") - .build() - ) - .build(), - equalTo(testCases.get(0)) + EndpointTestCase.builder() + .documentation("a documentation string") + .params( + ObjectNode.builder() + .withMember("stringFoo", "a b") + .withMember("boolFoo", false) + .build() + ) + .expect( + EndpointTestExpectation.builder() + .error("endpoint error") + .build() + ) + .build(), + equalTo(testCases.get(0)) ); assertThat( - EndpointTestCase.builder() - .params( - ObjectNode.builder() - .withMember("stringFoo", "c d") - .withMember("boolFoo", true) - .build() - ) - .operationInputs( - ListUtils.of( - EndpointTestOperationInput.builder() - .operationName("GetThing") - .clientParams( - ObjectNode.builder() - .withMember("stringFoo", "client value") - .build() - ) - .operationParams( + EndpointTestCase.builder() + .params( ObjectNode.builder() - .withMember("buzz", "a buzz value") - .withMember("fizz", "a required value") - .build() - ) - .builtInParams( - ObjectNode.builder() - .withMember("SDK::Endpoint", "https://custom.example.com") - .build() - ) - .build() - ) - ) - .expect( - EndpointTestExpectation.builder() - .endpoint( - ExpectedEndpoint.builder() - .url("https://example.com") - .properties(MapUtils.of()) - .headers( - MapUtils.of( - "single", - ListUtils.of("foo"), - "multi", - ListUtils.of("foo", "bar", "baz") - ) + .withMember("stringFoo", "c d") + .withMember("boolFoo", true) + .build() + ) + .operationInputs( + ListUtils.of( + EndpointTestOperationInput.builder() + .operationName("GetThing") + .clientParams( + ObjectNode.builder() + .withMember("stringFoo", "client value") + .build() + ) + .operationParams( + ObjectNode.builder() + .withMember("buzz", "a buzz value") + .withMember("fizz", "a required value") + .build() + ) + .builtInParams( + ObjectNode.builder() + .withMember( + "SDK::Endpoint", + "https://custom.example.com" + ) + .build() + ) + .build() ) - .build() ) - .build() - ) - .build(), - equalTo(testCases.get(1)) + .expect( + EndpointTestExpectation.builder() + .endpoint( + ExpectedEndpoint.builder() + .url("https://example.com") + .properties(MapUtils.of()) + .headers( + MapUtils.of( + "single", + ListUtils.of("foo"), + "multi", + ListUtils.of("foo", "bar", "baz") + ) + ) + .build() + ) + .build() + ) + .build(), + equalTo(testCases.get(1)) ); } @Test public void roundTrips() { Node expectedNode = Node.parse( - "{\"version\":\"1.0\",\"testCases\":[{\"documentation\":\"foo bar\",\"params\":{\"foo\":\"bar\"" - + ",\"bar\":\"foo\"},\"operationInputs\":[{\"operationName\":\"GetThing\",\"clientParams\":" - + "{\"stringFoo\":\"client value\"},\"operationParams\":{\"buzz\":\"a buzz value\"},\"builtInParams\":" - + "{\"SDK::Endpoint\":\"https://custom.example.com\"}}],\"expect\":{\"endpoint\":{\"url\":" - + "\"example.com\",\"headers\":{\"single\":[\"one\"],\"multi\":[\"one\",\"two\"]},\"properties\":" - + "{\"foo\":{\"bar\":\"thing\",\"baz\":false}}}}},{\"documentation\":\"bar foo\",\"params\":{\"foo\":" - + "\"foo\"},\"expect\":{\"error\":\"error string\"}}]}" + "{\"version\":\"1.0\",\"testCases\":[{\"documentation\":\"foo bar\",\"params\":{\"foo\":\"bar\"" + + ",\"bar\":\"foo\"},\"operationInputs\":[{\"operationName\":\"GetThing\",\"clientParams\":" + + "{\"stringFoo\":\"client value\"},\"operationParams\":{\"buzz\":\"a buzz value\"},\"builtInParams\":" + + "{\"SDK::Endpoint\":\"https://custom.example.com\"}}],\"expect\":{\"endpoint\":{\"url\":" + + "\"example.com\",\"headers\":{\"single\":[\"one\"],\"multi\":[\"one\",\"two\"]},\"properties\":" + + "{\"foo\":{\"bar\":\"thing\",\"baz\":false}}}}},{\"documentation\":\"bar foo\",\"params\":{\"foo\":" + + "\"foo\"},\"expect\":{\"error\":\"error string\"}}]}" ); TraitFactory traitFactory = TraitFactory.createServiceFactory(); EndpointTestsTrait expectedTrait = (EndpointTestsTrait) traitFactory.createTrait( - EndpointTestsTrait.ID, - ShapeId.from("ns.example#Foo"), - expectedNode + EndpointTestsTrait.ID, + ShapeId.from("ns.example#Foo"), + expectedNode ).get(); EndpointTestsTrait actualTrait = expectedTrait.toBuilder().build(); diff --git a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/StaticContextParamsTraitTest.java b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/StaticContextParamsTraitTest.java index dab4333e238..bb23405682f 100644 --- a/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/StaticContextParamsTraitTest.java +++ b/smithy-rules-engine/src/test/java/software/amazon/smithy/rulesengine/traits/StaticContextParamsTraitTest.java @@ -19,29 +19,29 @@ public class StaticContextParamsTraitTest { @Test public void loadsFromModel() { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(getClass().getResource("traits-test-model.smithy")) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(getClass().getResource("traits-test-model.smithy")) + .assemble() + .unwrap(); OperationShape operationShape = result.expectShape( - ShapeId.from("smithy.example#GetThing"), - OperationShape.class + ShapeId.from("smithy.example#GetThing"), + OperationShape.class ); StaticContextParamsTrait trait = operationShape.getTrait(StaticContextParamsTrait.class).get(); assertEquals( - trait.getParameters(), - MapUtils.of( - "stringBar", - StaticContextParamDefinition.builder() - .value(StringNode.from("some value")) - .build(), - "boolBar", - StaticContextParamDefinition.builder() - .value(Node.from(true)) - .build() - ) + trait.getParameters(), + MapUtils.of( + "stringBar", + StaticContextParamDefinition.builder() + .value(StringNode.from("some value")) + .build(), + "boolBar", + StaticContextParamDefinition.builder() + .value(Node.from(true)) + .build() + ) ); } } diff --git a/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/Expectation.java b/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/Expectation.java index d8b855935de..df2aed7b498 100644 --- a/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/Expectation.java +++ b/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/Expectation.java @@ -62,9 +62,11 @@ public static Expectation fromNode(Node node) { return Expectation.failure(failure); } else { throw new ExpectationNotMetException( - "Expected an object with exactly one `" + SUCCESS + "` or `" + FAILURE - + "` property, but found properties: " + ValidationUtils.tickedList(o.getStringMap().keySet()), - o + "Expected an object with exactly one `" + SUCCESS + "` or `" + FAILURE + + "` property, but found properties: " + ValidationUtils.tickedList( + o.getStringMap().keySet() + ), + o ); } } @@ -97,8 +99,8 @@ public Node toNode() { builder.withMember(SUCCESS, Node.objectNode()); } else { Node failureNode = this.getFailure() - .map(FailureExpectation::toNode) - .orElse(Node.objectNode()); + .map(FailureExpectation::toNode) + .orElse(Node.objectNode()); builder.withMember(FAILURE, failureNode); } return builder.build(); diff --git a/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/FailureExpectation.java b/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/FailureExpectation.java index 62c581f4041..556e541aa32 100644 --- a/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/FailureExpectation.java +++ b/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/FailureExpectation.java @@ -57,16 +57,16 @@ public Optional getErrorId() { @Override public Node toNode() { return Node.objectNodeBuilder() - .withOptionalMember(ERROR_ID, this.getErrorId().map(ShapeId::toString).map(StringNode::from)) - .build(); + .withOptionalMember(ERROR_ID, this.getErrorId().map(ShapeId::toString).map(StringNode::from)) + .build(); } public static FailureExpectation fromNode(Node node) { ObjectNode o = node.expectObjectNode(); return o.getStringMember(ERROR_ID) - .map(ShapeId::fromNode) - .map(FailureExpectation::errorWithId) - .orElse(FailureExpectation.anyError()); + .map(ShapeId::fromNode) + .map(FailureExpectation::errorWithId) + .orElse(FailureExpectation.anyError()); } @Override diff --git a/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/SmokeTestCase.java b/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/SmokeTestCase.java index 5ecdbbd0bae..22331233b93 100644 --- a/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/SmokeTestCase.java +++ b/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/SmokeTestCase.java @@ -142,25 +142,25 @@ public List getTags() { @Override public Builder toBuilder() { return builder() - .id(this.getId()) - .params(this.getParams().orElse(null)) - .vendorParams(this.getVendorParams().orElse(null)) - .vendorParamsShape(this.getVendorParamsShape().orElse(null)) - .expectation(this.getExpectation()) - .tags(this.getTags()); + .id(this.getId()) + .params(this.getParams().orElse(null)) + .vendorParams(this.getVendorParams().orElse(null)) + .vendorParamsShape(this.getVendorParamsShape().orElse(null)) + .expectation(this.getExpectation()) + .tags(this.getTags()); } @Override public Node toNode() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withMember(ID, this.getId()) - .withOptionalMember(PARAMS, this.getParams()) - .withOptionalMember(VENDOR_PARAMS, this.getVendorParams()) - .withOptionalMember( - VENDOR_PARAMS_SHAPE, - this.getVendorParamsShape().map(ShapeId::toString).map(Node::from) - ) - .withMember(EXPECT, this.getExpectation()); + .withMember(ID, this.getId()) + .withOptionalMember(PARAMS, this.getParams()) + .withOptionalMember(VENDOR_PARAMS, this.getVendorParams()) + .withOptionalMember( + VENDOR_PARAMS_SHAPE, + this.getVendorParamsShape().map(ShapeId::toString).map(Node::from) + ) + .withMember(EXPECT, this.getExpectation()); if (!this.tags.isEmpty()) { builder.withMember(TAGS, ArrayNode.fromStrings(tags)); diff --git a/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/SmokeTestCaseValidator.java b/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/SmokeTestCaseValidator.java index 821e8d6fe56..c4f265ed048 100644 --- a/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/SmokeTestCaseValidator.java +++ b/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/SmokeTestCaseValidator.java @@ -45,25 +45,25 @@ public List validate(Model model) { if (vendorParamsShapeIdOptional.isPresent()) { if (!vendorParamsOptional.isPresent()) { events.add( - warning( - shape, - trait, - String.format( - "Smoke test case with ID `%s` defined a `vendorParamsShape` but no `vendorParams`", - testCase.getId() + warning( + shape, + trait, + String.format( + "Smoke test case with ID `%s` defined a `vendorParamsShape` but no `vendorParams`", + testCase.getId() + ) ) - ) ); } else { Optional vendorParamsShapeOptional = model.getShape(vendorParamsShapeIdOptional.get()); if (vendorParamsShapeOptional.isPresent()) { Shape vendorParamsShape = vendorParamsShapeOptional.get(); NodeValidationVisitor vendorParamsValidator = createVisitor( - vendorParamsOptional.get(), - model, - shape, - testCase.getId(), - ".vendorParams" + vendorParamsOptional.get(), + model, + shape, + testCase.getId(), + ".vendorParams" ); events.addAll(vendorParamsShape.accept(vendorParamsValidator)); } @@ -71,14 +71,14 @@ public List validate(Model model) { } } else if (vendorParamsOptional.isPresent()) { events.add( - warning( - shape, - trait, - String.format( - "Smoke test case with ID `%s` defined `vendorParams` but no `vendorParamsShape`", - testCase.getId() + warning( + shape, + trait, + String.format( + "Smoke test case with ID `%s` defined `vendorParams` but no `vendorParamsShape`", + testCase.getId() + ) ) - ) ); } @@ -86,24 +86,24 @@ public List validate(Model model) { StructureShape input = operationIndex.expectInputShape(shape); if (input != null && testCase.getParams().isPresent()) { NodeValidationVisitor paramsValidator = createVisitor( - testCase.getParams().get(), - model, - shape, - testCase.getId(), - ".params" + testCase.getParams().get(), + model, + shape, + testCase.getId(), + ".params" ); events.addAll(input.accept(paramsValidator)); } else if (testCase.getParams().isPresent()) { events.add( - error( - shape, - trait, - String.format( - "Smoke test parameters provided for operation with no input: `%s`", - Node.printJson(testCase.getParams().get()) + error( + shape, + trait, + String.format( + "Smoke test parameters provided for operation with no input: `%s`", + Node.printJson(testCase.getParams().get()) + ) ) - ) ); } } @@ -112,20 +112,20 @@ public List validate(Model model) { } private NodeValidationVisitor createVisitor( - ObjectNode node, - Model model, - Shape shape, - String caseId, - String contextSuffix + ObjectNode node, + Model model, + Shape shape, + String caseId, + String contextSuffix ) { return NodeValidationVisitor.builder() - .model(model) - .eventShapeId(shape.getId()) - .value(node) - .startingContext(SmokeTestsTrait.ID + "." + caseId + contextSuffix) - .eventId(getName()) - .timestampValidationStrategy(TimestampValidationStrategy.EPOCH_SECONDS) - .addFeature(NodeValidationVisitor.Feature.ALLOW_OPTIONAL_NULLS) - .build(); + .model(model) + .eventShapeId(shape.getId()) + .value(node) + .startingContext(SmokeTestsTrait.ID + "." + caseId + contextSuffix) + .eventId(getName()) + .timestampValidationStrategy(TimestampValidationStrategy.EPOCH_SECONDS) + .addFeature(NodeValidationVisitor.Feature.ALLOW_OPTIONAL_NULLS) + .build(); } } diff --git a/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/UniqueSmokeTestCaseIdValidator.java b/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/UniqueSmokeTestCaseIdValidator.java index 40a4e832f85..23684cbee7d 100644 --- a/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/UniqueSmokeTestCaseIdValidator.java +++ b/smithy-smoke-test-traits/src/main/java/software/amazon/smithy/smoketests/traits/UniqueSmokeTestCaseIdValidator.java @@ -42,9 +42,9 @@ public List validate(Model model) { // Also validate ids are unique within each non-service bound operation List shapes = model.getOperationShapesWithTrait(SmokeTestsTrait.class) - .stream() - .filter(shape -> !serviceBoundOperations.contains(shape)) - .collect(Collectors.toList()); + .stream() + .filter(shape -> !serviceBoundOperations.contains(shape)) + .collect(Collectors.toList()); for (OperationShape shape : shapes) { addValidationEventsForShapes(SetUtils.of(shape), events); @@ -69,15 +69,15 @@ private void addValidationEventsForShapes(Set shapes, List 1) { for (Shape shape : entry.getValue()) { events.add( - error( - shape, - String.format( - "Conflicting `%s` test case IDs found for ID `%s`: %s", - SmokeTestsTrait.ID, - entry.getKey(), - ValidationUtils.tickedList(entry.getValue().stream().map(Shape::getId)) + error( + shape, + String.format( + "Conflicting `%s` test case IDs found for ID `%s`: %s", + SmokeTestsTrait.ID, + entry.getKey(), + ValidationUtils.tickedList(entry.getValue().stream().map(Shape::getId)) + ) ) - ) ); } } diff --git a/smithy-smoke-test-traits/src/test/java/software/amazon/smithy/smoketests/traits/SmokeTestsTraitTest.java b/smithy-smoke-test-traits/src/test/java/software/amazon/smithy/smoketests/traits/SmokeTestsTraitTest.java index 30a2da0dc39..51105f85636 100644 --- a/smithy-smoke-test-traits/src/test/java/software/amazon/smithy/smoketests/traits/SmokeTestsTraitTest.java +++ b/smithy-smoke-test-traits/src/test/java/software/amazon/smithy/smoketests/traits/SmokeTestsTraitTest.java @@ -114,13 +114,13 @@ public void withTags() { private static SmokeTestCase getSmokeTestCase(String filename) { Model model = Model.assembler() - .addImport(SmokeTestsTraitTest.class.getResource(filename)) - .discoverModels() - .assemble() - .unwrap(); + .addImport(SmokeTestsTraitTest.class.getResource(filename)) + .discoverModels() + .assemble() + .unwrap(); return model.expectShape(ShapeId.from("smithy.example#SayHello")) - .expectTrait(SmokeTestsTrait.class) - .getTestCases() - .get(0); + .expectTrait(SmokeTestsTrait.class) + .getTestCases() + .get(0); } } diff --git a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/BracketFormatter.java b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/BracketFormatter.java index 55faeb57b51..d720648c715 100644 --- a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/BracketFormatter.java +++ b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/BracketFormatter.java @@ -24,36 +24,36 @@ final class BracketFormatter { private boolean forceInline = false; static Function> extractor( - Function visitor, - Function> mapper + Function visitor, + Function> mapper ) { return extractor(visitor, mapper, TreeCursor::children); } static Function> extractor( - Function visitor, - Function> mapper, - Function> childrenSupplier + Function visitor, + Function> mapper, + Function> childrenSupplier ) { return (cursor) -> childrenSupplier.apply(cursor) - .flatMap(c -> { - TreeType type = c.getTree().getType(); - return type == TreeType.WS || type == TreeType.COMMENT ? Stream.of(c) : mapper.apply(c); - }) - .flatMap(c -> { - // If the child extracts WS, then filter it down to just comments. - return c.getTree().getType() == TreeType.WS - ? c.getChildrenByType(TreeType.COMMENT).stream() - : Stream.of(c); - }) - .map(visitor) - .filter(doc -> doc != Doc.empty()); + .flatMap(c -> { + TreeType type = c.getTree().getType(); + return type == TreeType.WS || type == TreeType.COMMENT ? Stream.of(c) : mapper.apply(c); + }) + .flatMap(c -> { + // If the child extracts WS, then filter it down to just comments. + return c.getTree().getType() == TreeType.WS + ? c.getChildrenByType(TreeType.COMMENT).stream() + : Stream.of(c); + }) + .map(visitor) + .filter(doc -> doc != Doc.empty()); } static Function> byTypeMapper(TreeType childType) { return child -> child.getTree().getType() == childType - ? Stream.of(child) - : Stream.empty(); + ? Stream.of(child) + : Stream.empty(); } static Function> siblingChildrenSupplier() { @@ -63,8 +63,8 @@ static Function> siblingChildrenSupplier() { // Brackets children of childType between open and closed brackets. If the children can fit together // on a single line, they are comma separated. If not, they are split onto multiple lines with no commas. static Function> extractByType( - TreeType childType, - Function visitor + TreeType childType, + Function visitor ) { return extractor(visitor, byTypeMapper(childType)); } @@ -96,11 +96,11 @@ BracketFormatter detectHardLines(TreeCursor hardLineSubject) { // Check if the given tree has any hard lines. Nested arrays and objects are always considered hard lines. private boolean hasHardLine(TreeCursor cursor) { List children = cursor.findChildrenByType( - TreeType.COMMENT, - TreeType.TEXT_BLOCK, - TreeType.NODE_ARRAY, - TreeType.NODE_OBJECT, - TreeType.QUOTED_TEXT + TreeType.COMMENT, + TreeType.TEXT_BLOCK, + TreeType.NODE_ARRAY, + TreeType.NODE_OBJECT, + TreeType.QUOTED_TEXT ); for (TreeCursor child : children) { if (child.getTree().getType() != TreeType.QUOTED_TEXT) { diff --git a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/CapturedToken.java b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/CapturedToken.java index 94e9e36d18d..b5cf2b7c774 100644 --- a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/CapturedToken.java +++ b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/CapturedToken.java @@ -37,17 +37,17 @@ public final class CapturedToken implements FromSourceLocation, ToSmithyBuilder< private final Number numberValue; private CapturedToken( - IdlToken token, - String filename, - int position, - int startLine, - int startColumn, - int endLine, - int endColumn, - CharSequence lexeme, - String stringContents, - Number numberValue, - String errorMessage + IdlToken token, + String filename, + int position, + int startLine, + int startColumn, + int endLine, + int endColumn, + CharSequence lexeme, + String stringContents, + Number numberValue, + String errorMessage ) { this.token = Objects.requireNonNull(token, "Missing required token"); this.lexeme = Objects.requireNonNull(lexeme, "Missing required lexeme"); @@ -59,7 +59,7 @@ private CapturedToken( this.endColumn = endColumn; if (stringContents == null - && (token == IdlToken.IDENTIFIER || token == IdlToken.STRING || token == IdlToken.TEXT_BLOCK)) { + && (token == IdlToken.IDENTIFIER || token == IdlToken.STRING || token == IdlToken.TEXT_BLOCK)) { this.stringContents = lexeme.toString(); } else { this.stringContents = stringContents; @@ -100,17 +100,17 @@ private Builder() {} @Override public CapturedToken build() { return new CapturedToken( - token, - filename, - position, - startLine, - startColumn, - endLine, - endColumn, - lexeme, - stringContents, - numberValue, - errorMessage + token, + filename, + position, + startLine, + startColumn, + endLine, + endColumn, + lexeme, + stringContents, + numberValue, + errorMessage ); } @@ -190,38 +190,38 @@ public static CapturedToken from(IdlTokenizer tokenizer) { public static CapturedToken from(IdlTokenizer tokenizer, Function stringTable) { IdlToken tok = tokenizer.getCurrentToken(); return builder() - .token(tok) - .filename(tokenizer.getSourceFilename()) - .position(tokenizer.getCurrentTokenStart()) - .startLine(tokenizer.getCurrentTokenLine()) - .startColumn(tokenizer.getCurrentTokenColumn()) - .endLine(tokenizer.getLine()) - .endColumn(tokenizer.getColumn()) - .lexeme(tokenizer.getCurrentTokenLexeme()) - .stringContents( - tok == IdlToken.STRING || tok == IdlToken.TEXT_BLOCK || tok == IdlToken.IDENTIFIER - ? stringTable.apply(tokenizer.getCurrentTokenStringSlice()) - : null - ) - .numberValue(tok == IdlToken.NUMBER ? tokenizer.getCurrentTokenNumberValue() : null) - .errorMessage(tok == IdlToken.ERROR ? tokenizer.getCurrentTokenError() : null) - .build(); + .token(tok) + .filename(tokenizer.getSourceFilename()) + .position(tokenizer.getCurrentTokenStart()) + .startLine(tokenizer.getCurrentTokenLine()) + .startColumn(tokenizer.getCurrentTokenColumn()) + .endLine(tokenizer.getLine()) + .endColumn(tokenizer.getColumn()) + .lexeme(tokenizer.getCurrentTokenLexeme()) + .stringContents( + tok == IdlToken.STRING || tok == IdlToken.TEXT_BLOCK || tok == IdlToken.IDENTIFIER + ? stringTable.apply(tokenizer.getCurrentTokenStringSlice()) + : null + ) + .numberValue(tok == IdlToken.NUMBER ? tokenizer.getCurrentTokenNumberValue() : null) + .errorMessage(tok == IdlToken.ERROR ? tokenizer.getCurrentTokenError() : null) + .build(); } @Override public Builder toBuilder() { return builder() - .token(token) - .filename(filename) - .position(position) - .startLine(startLine) - .startColumn(startColumn) - .endLine(endLine) - .endColumn(endColumn) - .lexeme(lexeme) - .errorMessage(errorMessage) - .numberValue(numberValue) - .stringContents(stringContents); + .token(token) + .filename(filename) + .position(position) + .startLine(startLine) + .startColumn(startColumn) + .endLine(endLine) + .endColumn(endColumn) + .lexeme(lexeme) + .errorMessage(errorMessage) + .numberValue(numberValue) + .stringContents(stringContents); } /** diff --git a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/CapturingTokenizer.java b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/CapturingTokenizer.java index bab4353d5d5..38eb50bb108 100644 --- a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/CapturingTokenizer.java +++ b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/CapturingTokenizer.java @@ -187,7 +187,7 @@ private void defaultErrorRecovery() { if (getCurrentTokenColumn() == 1) { IdlToken token = getCurrentToken(); if (token == IdlToken.DOLLAR || token == IdlToken.IDENTIFIER || token == IdlToken.AT - || token == IdlToken.RBRACE) { + || token == IdlToken.RBRACE) { return; } } diff --git a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/FixBadDocComments.java b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/FixBadDocComments.java index a8a0dc149b3..19a559da5b4 100644 --- a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/FixBadDocComments.java +++ b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/FixBadDocComments.java @@ -108,18 +108,18 @@ private void updateChildren(List children) { private boolean isDocComment(TreeCursor cursor) { return cursor.getTree() - .tokens() - .findFirst() - .filter(token -> token.getIdlToken() == IdlToken.DOC_COMMENT) - .isPresent(); + .tokens() + .findFirst() + .filter(token -> token.getIdlToken() == IdlToken.DOC_COMMENT) + .isPresent(); } private void updateComment(TreeCursor cursor) { cursor.getTree().tokens().findFirst().ifPresent(token -> { CapturedToken updatedToken = token.toBuilder() - // Trim the first "/" from the lexeme. Note that this does make the spans inaccurate. - .lexeme(token.getLexeme().subSequence(1, token.getLexeme().length())) - .build(); + // Trim the first "/" from the lexeme. Note that this does make the spans inaccurate. + .lexeme(token.getLexeme().subSequence(1, token.getLexeme().length())) + .build(); TokenTree updatedTree = TokenTree.of(TreeType.COMMENT); updatedTree.appendChild(TokenTree.of(updatedToken)); cursor.getParent().getTree().replaceChild(cursor.getTree(), updatedTree); diff --git a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/FormatVisitor.java b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/FormatVisitor.java index b3a3213e40c..5de13d9a163 100644 --- a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/FormatVisitor.java +++ b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/FormatVisitor.java @@ -29,9 +29,9 @@ final class FormatVisitor { // Renders members and anything bracketed that are known to need expansion on multiple lines. static Doc renderBlock(Doc open, Doc close, Doc contents) { return open - .append(Doc.line().append(contents).indent(4)) - .append(Doc.line()) - .append(close); + .append(Doc.line().append(contents).indent(4)) + .append(Doc.line()) + .append(close); } Doc visit(TreeCursor cursor) { @@ -44,10 +44,10 @@ Doc visit(TreeCursor cursor) { switch (tree.getType()) { case IDL: { return visit(cursor.getFirstChild(TreeType.WS)) - .append(visit(cursor.getFirstChild(TreeType.CONTROL_SECTION))) - .append(visit(cursor.getFirstChild(TreeType.METADATA_SECTION))) - .append(visit(cursor.getFirstChild(TreeType.SHAPE_SECTION))) - .append(flushBrBuffer()); + .append(visit(cursor.getFirstChild(TreeType.CONTROL_SECTION))) + .append(visit(cursor.getFirstChild(TreeType.METADATA_SECTION))) + .append(visit(cursor.getFirstChild(TreeType.SHAPE_SECTION))) + .append(flushBrBuffer()); } case CONTROL_SECTION: { @@ -71,36 +71,36 @@ Doc visit(TreeCursor cursor) { result = result.append(Doc.line()); } result = result.append(visit(childIterator.next())) // SHAPE - .append(visit(childIterator.next())) // BR - .append(Doc.line()); + .append(visit(childIterator.next())) // BR + .append(Doc.line()); } return result; } case CONTROL_STATEMENT: { return flushBrBuffer() - .append(Doc.text("$")) - .append(visit(cursor.getFirstChild(TreeType.NODE_OBJECT_KEY))) - .append(Doc.text(": ")) - .append(visit(cursor.getFirstChild(TreeType.NODE_VALUE))) - .append(visit(cursor.getFirstChild(TreeType.BR))); + .append(Doc.text("$")) + .append(visit(cursor.getFirstChild(TreeType.NODE_OBJECT_KEY))) + .append(Doc.text(": ")) + .append(visit(cursor.getFirstChild(TreeType.NODE_VALUE))) + .append(visit(cursor.getFirstChild(TreeType.BR))); } case METADATA_STATEMENT: { return flushBrBuffer() - .append(Doc.text("metadata ")) - .append(visit(cursor.getFirstChild(TreeType.NODE_OBJECT_KEY))) - .append(Doc.text(" = ")) - .append(visit(cursor.getFirstChild(TreeType.NODE_VALUE))) - .append(visit(cursor.getFirstChild(TreeType.BR))); + .append(Doc.text("metadata ")) + .append(visit(cursor.getFirstChild(TreeType.NODE_OBJECT_KEY))) + .append(Doc.text(" = ")) + .append(visit(cursor.getFirstChild(TreeType.NODE_VALUE))) + .append(visit(cursor.getFirstChild(TreeType.BR))); } case NAMESPACE_STATEMENT: { return Doc.line() - .append(flushBrBuffer()) - .append(Doc.text("namespace ")) - .append(visit(cursor.getFirstChild(TreeType.NAMESPACE))) - .append(visit(cursor.getFirstChild(TreeType.BR))); + .append(flushBrBuffer()) + .append(Doc.text("namespace ")) + .append(visit(cursor.getFirstChild(TreeType.NAMESPACE))) + .append(visit(cursor.getFirstChild(TreeType.BR))); } case USE_SECTION: { @@ -109,9 +109,9 @@ Doc visit(TreeCursor cursor) { case USE_STATEMENT: { return flushBrBuffer() - .append(Doc.text("use ")) - .append(visit(cursor.getFirstChild(TreeType.ABSOLUTE_ROOT_SHAPE_ID))) - .append(visit(cursor.getFirstChild(TreeType.BR))); + .append(Doc.text("use ")) + .append(visit(cursor.getFirstChild(TreeType.ABSOLUTE_ROOT_SHAPE_ID))) + .append(visit(cursor.getFirstChild(TreeType.BR))); } case SHAPE_OR_APPLY_STATEMENT: @@ -130,9 +130,9 @@ Doc visit(TreeCursor cursor) { case SHAPE_STATEMENT: { return flushBrBuffer() - .append(visit(cursor.getFirstChild(TreeType.WS))) - .append(visit(cursor.getFirstChild(TreeType.TRAIT_STATEMENTS))) - .append(visit(cursor.getFirstChild(TreeType.SHAPE))); + .append(visit(cursor.getFirstChild(TreeType.WS))) + .append(visit(cursor.getFirstChild(TreeType.TRAIT_STATEMENTS))) + .append(visit(cursor.getFirstChild(TreeType.SHAPE))); } case SIMPLE_SHAPE: { @@ -141,13 +141,13 @@ Doc visit(TreeCursor cursor) { case ENUM_SHAPE: { return skippedComments(cursor, false) - .append( - formatShape( - cursor, - visit(cursor.getFirstChild(TreeType.ENUM_TYPE_NAME)), - visit(cursor.getFirstChild(TreeType.ENUM_SHAPE_MEMBERS)) - ) - ); + .append( + formatShape( + cursor, + visit(cursor.getFirstChild(TreeType.ENUM_TYPE_NAME)), + visit(cursor.getFirstChild(TreeType.ENUM_SHAPE_MEMBERS)) + ) + ); } case ENUM_SHAPE_MEMBERS: { @@ -156,19 +156,19 @@ Doc visit(TreeCursor cursor) { case ENUM_SHAPE_MEMBER: { return visit(cursor.getFirstChild(TreeType.TRAIT_STATEMENTS)) - .append(visit(cursor.getFirstChild(TreeType.IDENTIFIER))) - .append(visit(cursor.getFirstChild(TreeType.VALUE_ASSIGNMENT))); + .append(visit(cursor.getFirstChild(TreeType.IDENTIFIER))) + .append(visit(cursor.getFirstChild(TreeType.VALUE_ASSIGNMENT))); } case AGGREGATE_SHAPE: { return skippedComments(cursor, false) - .append( - formatShape( - cursor, - visit(cursor.getFirstChild(TreeType.AGGREGATE_TYPE_NAME)), - visit(cursor.getFirstChild(TreeType.SHAPE_MEMBERS)) - ) - ); + .append( + formatShape( + cursor, + visit(cursor.getFirstChild(TreeType.AGGREGATE_TYPE_NAME)), + visit(cursor.getFirstChild(TreeType.SHAPE_MEMBERS)) + ) + ); } case FOR_RESOURCE: { @@ -181,15 +181,15 @@ Doc visit(TreeCursor cursor) { case SHAPE_MEMBER: { return visit(cursor.getFirstChild(TreeType.TRAIT_STATEMENTS)) - .append(visit(cursor.getFirstChild(TreeType.ELIDED_SHAPE_MEMBER))) - .append(visit(cursor.getFirstChild(TreeType.EXPLICIT_SHAPE_MEMBER))) - .append(visit(cursor.getFirstChild(TreeType.VALUE_ASSIGNMENT))); + .append(visit(cursor.getFirstChild(TreeType.ELIDED_SHAPE_MEMBER))) + .append(visit(cursor.getFirstChild(TreeType.EXPLICIT_SHAPE_MEMBER))) + .append(visit(cursor.getFirstChild(TreeType.VALUE_ASSIGNMENT))); } case EXPLICIT_SHAPE_MEMBER: { return visit(cursor.getFirstChild(TreeType.IDENTIFIER)) - .append(Doc.text(": ")) - .append(visit(cursor.getFirstChild(TreeType.SHAPE_ID))); + .append(Doc.text(": ")) + .append(visit(cursor.getFirstChild(TreeType.SHAPE_ID))); } case ELIDED_SHAPE_MEMBER: { @@ -204,22 +204,22 @@ Doc visit(TreeCursor cursor) { // Place the values of resources, operations, and errors on multiple lines. Doc body = new BracketFormatter() - .extractChildren(nodeCursor, BracketFormatter.extractByType(TreeType.NODE_OBJECT_KVP, visitor)) - .detectHardLines(nodeCursor) // If the list is empty, then keep it as "[]". - .write(); + .extractChildren(nodeCursor, BracketFormatter.extractByType(TreeType.NODE_OBJECT_KVP, visitor)) + .detectHardLines(nodeCursor) // If the list is empty, then keep it as "[]". + .write(); return skippedComments.append(formatShape(cursor, entityType, Doc.lineOrSpace().append(body))); } case OPERATION_SHAPE: { return skippedComments(cursor, false) - .append( - formatShape( - cursor, - Doc.text("operation"), - visit(cursor.getFirstChild(TreeType.OPERATION_BODY)) - ) - ); + .append( + formatShape( + cursor, + Doc.text("operation"), + visit(cursor.getFirstChild(TreeType.OPERATION_BODY)) + ) + ); } case OPERATION_BODY: { @@ -229,40 +229,40 @@ Doc visit(TreeCursor cursor) { case OPERATION_INPUT: { TreeCursor simpleTarget = cursor.getFirstChild(TreeType.SHAPE_ID); return skippedComments(cursor, false) - .append(Doc.text("input")) - .append( - simpleTarget == null - ? visit(cursor.getFirstChild(TreeType.INLINE_AGGREGATE_SHAPE)) - : Doc.text(": ") - ) - .append(visit(simpleTarget)); + .append(Doc.text("input")) + .append( + simpleTarget == null + ? visit(cursor.getFirstChild(TreeType.INLINE_AGGREGATE_SHAPE)) + : Doc.text(": ") + ) + .append(visit(simpleTarget)); } case OPERATION_OUTPUT: { TreeCursor simpleTarget = cursor.getFirstChild(TreeType.SHAPE_ID); return skippedComments(cursor, false) - .append(Doc.text("output")) - .append( - simpleTarget == null - ? visit(cursor.getFirstChild(TreeType.INLINE_AGGREGATE_SHAPE)) - : Doc.text(": ") - ) - .append(visit(simpleTarget)); + .append(Doc.text("output")) + .append( + simpleTarget == null + ? visit(cursor.getFirstChild(TreeType.INLINE_AGGREGATE_SHAPE)) + : Doc.text(": ") + ) + .append(visit(simpleTarget)); } case INLINE_AGGREGATE_SHAPE: { boolean hasComment = hasComment(cursor); boolean hasTraits = Optional.ofNullable(cursor.getFirstChild(TreeType.TRAIT_STATEMENTS)) - .filter(c -> !c.getChildrenByType(TreeType.TRAIT).isEmpty()) - .isPresent(); + .filter(c -> !c.getChildrenByType(TreeType.TRAIT).isEmpty()) + .isPresent(); Doc memberDoc = visit(cursor.getFirstChild(TreeType.SHAPE_MEMBERS)); if (hasComment || hasTraits) { return Doc.text(" :=") - .append(Doc.line()) - .append(skippedComments(cursor, false)) - .append(visit(cursor.getFirstChild(TreeType.TRAIT_STATEMENTS))) - .append(formatShape(cursor, Doc.empty(), memberDoc)) - .indent(4); + .append(Doc.line()) + .append(skippedComments(cursor, false)) + .append(visit(cursor.getFirstChild(TreeType.TRAIT_STATEMENTS))) + .append(formatShape(cursor, Doc.empty(), memberDoc)) + .indent(4); } return formatShape(cursor, Doc.text(" :="), memberDoc); @@ -283,114 +283,114 @@ Doc visit(TreeCursor cursor) { child = child.getNextSibling(); } return comments.append( - Doc.text("errors: ") - .append( - new BracketFormatter() - .open(Formatter.LBRACKET) - .close(Formatter.RBRACKET) - .extractChildren( - child, - BracketFormatter.extractor( - this::visit, - BracketFormatter.byTypeMapper(TreeType.SHAPE_ID), - BracketFormatter.siblingChildrenSupplier() - ) + Doc.text("errors: ") + .append( + new BracketFormatter() + .open(Formatter.LBRACKET) + .close(Formatter.RBRACKET) + .extractChildren( + child, + BracketFormatter.extractor( + this::visit, + BracketFormatter.byTypeMapper(TreeType.SHAPE_ID), + BracketFormatter.siblingChildrenSupplier() + ) + ) + .forceLineBreaks() // always put each error on separate lines. + .write() ) - .forceLineBreaks() // always put each error on separate lines. - .write() - ) ); } case MIXINS: { return Doc.text("with ") - .append( - new BracketFormatter() - .open(Formatter.LBRACKET) - .close(Formatter.RBRACKET) - .extractChildren(cursor, BracketFormatter.extractor(this::visit, child -> { - return child.getTree().getType() == TreeType.SHAPE_ID - ? Stream.of(child) - : Stream.empty(); - })) - .detectHardLines(cursor) - .write() - ); + .append( + new BracketFormatter() + .open(Formatter.LBRACKET) + .close(Formatter.RBRACKET) + .extractChildren(cursor, BracketFormatter.extractor(this::visit, child -> { + return child.getTree().getType() == TreeType.SHAPE_ID + ? Stream.of(child) + : Stream.empty(); + })) + .detectHardLines(cursor) + .write() + ); } case VALUE_ASSIGNMENT: { return Doc.text(" = ") - .append(visit(cursor.getFirstChild(TreeType.NODE_VALUE))) - .append(visit(cursor.getFirstChild(TreeType.BR))); + .append(visit(cursor.getFirstChild(TreeType.NODE_VALUE))) + .append(visit(cursor.getFirstChild(TreeType.BR))); } case TRAIT_STATEMENTS: { return Doc.intersperse( - Doc.line(), - cursor.children() - // Skip WS nodes that have no comments. - .filter(c -> c.getTree().getType() == TreeType.TRAIT || hasComment(c)) - .map(this::visit) + Doc.line(), + cursor.children() + // Skip WS nodes that have no comments. + .filter(c -> c.getTree().getType() == TreeType.TRAIT || hasComment(c)) + .map(this::visit) ) - .append(tree.isEmpty() ? Doc.empty() : Doc.line()); + .append(tree.isEmpty() ? Doc.empty() : Doc.line()); } case TRAIT: { return Doc.text("@") - .append(visit(cursor.getFirstChild(TreeType.SHAPE_ID))) - .append(visit(cursor.getFirstChild(TreeType.TRAIT_BODY))); + .append(visit(cursor.getFirstChild(TreeType.SHAPE_ID))) + .append(visit(cursor.getFirstChild(TreeType.TRAIT_BODY))); } case TRAIT_BODY: { TreeCursor structuredBody = cursor.getFirstChild(TreeType.TRAIT_STRUCTURE); if (structuredBody != null) { return new BracketFormatter() - .open(Formatter.LPAREN) - .close(Formatter.RPAREN) - .extractChildren(cursor, BracketFormatter.extractor(this::visit, child -> { - if (child.getTree().getType() == TreeType.TRAIT_STRUCTURE) { - // Split WS and NODE_OBJECT_KVP so that they appear on different lines. - return child.getChildrenByType(TreeType.NODE_OBJECT_KVP, TreeType.WS).stream(); - } - return Stream.empty(); - })) - .detectHardLines(cursor) - .write(); + .open(Formatter.LPAREN) + .close(Formatter.RPAREN) + .extractChildren(cursor, BracketFormatter.extractor(this::visit, child -> { + if (child.getTree().getType() == TreeType.TRAIT_STRUCTURE) { + // Split WS and NODE_OBJECT_KVP so that they appear on different lines. + return child.getChildrenByType(TreeType.NODE_OBJECT_KVP, TreeType.WS).stream(); + } + return Stream.empty(); + })) + .detectHardLines(cursor) + .write(); } else if (cursor.getFirstChild(TreeType.TRAIT_NODE) != null) { TreeCursor traitNode = cursor.getFirstChild(TreeType.TRAIT_NODE); // Check the inner trait node for hard line breaks rather than the wrapper. TreeCursor actualTraitNodeValue = traitNode - .getFirstChild(TreeType.NODE_VALUE) - .getFirstChild(); // The actual node value. + .getFirstChild(TreeType.NODE_VALUE) + .getFirstChild(); // The actual node value. BracketFormatter formatter = new BracketFormatter() - .open(Formatter.LPAREN) - .close(Formatter.RPAREN) - .extractChildren(cursor, BracketFormatter.extractor(this::visit, child -> { - if (child.getTree().getType() == TreeType.TRAIT_NODE) { - // Split WS and NODE_VALUE so that they appear on different lines. - return child.getChildrenByType(TreeType.NODE_VALUE, TreeType.WS).stream(); - } else { - return Stream.empty(); - } - })); + .open(Formatter.LPAREN) + .close(Formatter.RPAREN) + .extractChildren(cursor, BracketFormatter.extractor(this::visit, child -> { + if (child.getTree().getType() == TreeType.TRAIT_NODE) { + // Split WS and NODE_VALUE so that they appear on different lines. + return child.getChildrenByType(TreeType.NODE_VALUE, TreeType.WS).stream(); + } else { + return Stream.empty(); + } + })); // TraitBody may have leading comments and TraitNode may have trailing comments // which both require line break TreeCursor bodyWs = cursor.getFirstChild(TreeType.WS); TreeCursor traitNodeWs = traitNode.getFirstChild(TreeType.WS); if ((bodyWs != null && !bodyWs.findChildrenByType(TreeType.COMMENT).isEmpty()) - || (traitNodeWs != null && !traitNodeWs.findChildrenByType(TreeType.COMMENT).isEmpty())) { + || (traitNodeWs != null && !traitNodeWs.findChildrenByType(TreeType.COMMENT).isEmpty())) { // Need to line break if there's a leading comment in the trait body no matter what formatter.forceLineBreaks(); } else if (actualTraitNodeValue.getTree().getType() == TreeType.NODE_ARRAY - || actualTraitNodeValue.getTree().getType() == TreeType.NODE_OBJECT) { - // Just inline arrays and objects in trait body - formatter.forceInline(); - } else { - // Any other values can use normal detection - formatter.detectHardLines(cursor); - } + || actualTraitNodeValue.getTree().getType() == TreeType.NODE_OBJECT) { + // Just inline arrays and objects in trait body + formatter.forceInline(); + } else { + // Any other values can use normal detection + formatter.detectHardLines(cursor); + } return formatter.write(); } else { @@ -410,11 +410,11 @@ Doc visit(TreeCursor cursor) { case APPLY_STATEMENT_SINGULAR: { // If there is an awkward comment before the TRAIT value, hoist it above the statement. return flushBrBuffer() - .append(skippedComments(cursor, false)) - .append(Doc.text("apply ")) - .append(visit(cursor.getFirstChild(TreeType.SHAPE_ID))) - .append(Formatter.SPACE) - .append(visit(cursor.getFirstChild(TreeType.TRAIT))); + .append(skippedComments(cursor, false)) + .append(Doc.text("apply ")) + .append(visit(cursor.getFirstChild(TreeType.SHAPE_ID))) + .append(Formatter.SPACE) + .append(visit(cursor.getFirstChild(TreeType.TRAIT))); } case APPLY_STATEMENT_BLOCK: { @@ -422,49 +422,49 @@ Doc visit(TreeCursor cursor) { // the trailing newline + closing bracket. Otherwise, we'll get a blank, indented line, before // the closing brace. return flushBrBuffer() - .append( - Doc.text( - skippedComments(cursor, false) - .append(Doc.text("apply ")) - .append(visit(cursor.getFirstChild(TreeType.SHAPE_ID))) - .append(Doc.text(" {")) - .append( - Doc.line() - .append( - visit( - cursor.getFirstChild( - TreeType.TRAIT_STATEMENTS + .append( + Doc.text( + skippedComments(cursor, false) + .append(Doc.text("apply ")) + .append(visit(cursor.getFirstChild(TreeType.SHAPE_ID))) + .append(Doc.text(" {")) + .append( + Doc.line() + .append( + visit( + cursor.getFirstChild( + TreeType.TRAIT_STATEMENTS + ) + ) + ) + .indent(4) ) - ) - ) - .indent(4) + .render(width) + .trim() ) - .render(width) - .trim() - ) - .append(Doc.line()) - .append(Formatter.RBRACE) - ); + .append(Doc.line()) + .append(Formatter.RBRACE) + ); } case NODE_ARRAY: { return new BracketFormatter() - .open(Formatter.LBRACKET) - .close(Formatter.RBRACKET) - .extractChildren(cursor, BracketFormatter.extractByType(TreeType.NODE_VALUE, this::visit)) - .detectHardLines(cursor) - .write(); + .open(Formatter.LBRACKET) + .close(Formatter.RBRACKET) + .extractChildren(cursor, BracketFormatter.extractByType(TreeType.NODE_VALUE, this::visit)) + .detectHardLines(cursor) + .write(); } case NODE_OBJECT: { BracketFormatter formatter = new BracketFormatter() - .extractChildren( - cursor, - BracketFormatter.extractByType( - TreeType.NODE_OBJECT_KVP, - this::visit - ) - ); + .extractChildren( + cursor, + BracketFormatter.extractByType( + TreeType.NODE_OBJECT_KVP, + this::visit + ) + ); if (cursor.getParent().getParent().getTree().getType() == TreeType.NODE_ARRAY) { // Always break objects inside arrays if not empty formatter.forceLineBreaksIfNotEmpty(); @@ -477,18 +477,18 @@ Doc visit(TreeCursor cursor) { case NODE_OBJECT_KVP: { return skippedComments(cursor, false) - .append(formatNodeObjectKvp(cursor, this::visit, this::visit)); + .append(formatNodeObjectKvp(cursor, this::visit, this::visit)); } case NODE_OBJECT_KEY: { // Unquote object keys that can be unquoted. CharSequence unquoted = Optional.ofNullable(cursor.getFirstChild(TreeType.QUOTED_TEXT)) - .flatMap(quoted -> quoted.getTree().tokens().findFirst()) - .map(token -> token.getLexeme().subSequence(1, token.getSpan() - 1)) - .orElse(""); + .flatMap(quoted -> quoted.getTree().tokens().findFirst()) + .map(token -> token.getLexeme().subSequence(1, token.getSpan() - 1)) + .orElse(""); return ShapeId.isValidIdentifier(unquoted) - ? Doc.text(unquoted.toString()) - : Doc.text(tree.concatTokens()); + ? Doc.text(unquoted.toString()) + : Doc.text(tree.concatTokens()); } case TEXT_BLOCK: { @@ -498,10 +498,10 @@ Doc visit(TreeCursor cursor) { // We need to rebuild the text block to remove any incidental leading whitespace. The easiest way to // do that is to use the already parsed and resolved value from the lexer. String stringValue = cursor.getTree() - .tokens() - .findFirst() - .orElseThrow(() -> new RuntimeException("TEXT_BLOCK cursor does not have an IDL token")) - .getStringContents(); + .tokens() + .findFirst() + .orElseThrow(() -> new RuntimeException("TEXT_BLOCK cursor does not have an IDL token")) + .getStringContents(); // If the last character is a newline, then the closing triple quote must be on the next line. boolean endQuoteOnNextLine = stringValue.endsWith("\n") || stringValue.endsWith("\r"); @@ -566,8 +566,8 @@ Doc visit(TreeCursor cursor) { case WS: { // Ignore all whitespace except for comments and doc comments. return Doc.intersperse( - Doc.line(), - cursor.getChildrenByType(TreeType.COMMENT).stream().map(this::visit) + Doc.line(), + cursor.getChildrenByType(TreeType.COMMENT).stream().map(this::visit) ); } @@ -734,17 +734,17 @@ private Doc section(TreeCursor cursor, TreeType childType) { } private static Doc formatNodeObjectKvp( - TreeCursor cursor, - Function keyVisitor, - Function valueVisitor + TreeCursor cursor, + Function keyVisitor, + Function valueVisitor ) { // Since text blocks span multiple lines, when they are the NODE_VALUE for NODE_OBJECT_KVP, // they have to be indented. Since we only format valid models, NODE_OBJECT_KVP is guaranteed to // have a NODE_VALUE child. TreeCursor nodeValue = cursor.getFirstChild(TreeType.NODE_VALUE); boolean isTextBlock = Optional.ofNullable(nodeValue.getFirstChild(TreeType.NODE_STRING_VALUE)) - .map(nodeString -> nodeString.getFirstChild(TreeType.TEXT_BLOCK)) - .isPresent(); + .map(nodeString -> nodeString.getFirstChild(TreeType.TEXT_BLOCK)) + .isPresent(); Doc nodeValueDoc = valueVisitor.apply(nodeValue); if (isTextBlock) { @@ -754,8 +754,8 @@ private static Doc formatNodeObjectKvp( // Hoist awkward comments in the KVP *before* the KVP rather than between the values and colon. // If there is an awkward comment before the TRAIT value, hoist it above the statement. return keyVisitor.apply(cursor.getFirstChild(TreeType.NODE_OBJECT_KEY)) - .append(Doc.text(": ")) - .append(nodeValueDoc); + .append(Doc.text(": ")) + .append(nodeValueDoc); } // Ensure that special key-value pairs of service and resource shapes are always on multiple lines if not empty. @@ -765,28 +765,28 @@ private final class EntityShapeExtractorVisitor implements Function hardLineList = value -> { value = value.getFirstChild(TreeType.NODE_ARRAY); return new BracketFormatter() - .open(Formatter.LBRACKET) - .close(Formatter.RBRACKET) - .extractChildren( - value, - BracketFormatter - .extractByType(TreeType.NODE_VALUE, FormatVisitor.this::visit) - ) - .forceLineBreaksIfNotEmpty() - .write(); + .open(Formatter.LBRACKET) + .close(Formatter.RBRACKET) + .extractChildren( + value, + BracketFormatter + .extractByType(TreeType.NODE_VALUE, FormatVisitor.this::visit) + ) + .forceLineBreaksIfNotEmpty() + .write(); }; // Format known NODE_OBJECT_KVP object values to always place them on multiple lines. private final Function hardLineObject = value -> { value = value.getFirstChild(TreeType.NODE_OBJECT); return new BracketFormatter() - .extractChildren( - value, - BracketFormatter - .extractByType(TreeType.NODE_OBJECT_KVP, FormatVisitor.this::visit) - ) - .forceLineBreaksIfNotEmpty() - .write(); + .extractChildren( + value, + BracketFormatter + .extractByType(TreeType.NODE_OBJECT_KVP, FormatVisitor.this::visit) + ) + .forceLineBreaksIfNotEmpty() + .write(); }; @Override diff --git a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/Formatter.java b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/Formatter.java index fde421d1fca..d44a6a3f980 100644 --- a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/Formatter.java +++ b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/Formatter.java @@ -53,8 +53,8 @@ public static String format(TokenTree root, int maxWidth) { if (!errors.isEmpty()) { throw new ModelSyntaxException( - "Cannot format invalid models: " + errors.get(0).getTree().getError(), - errors.get(0) + "Cannot format invalid models: " + errors.get(0).getTree().getError(), + errors.get(0) ); } diff --git a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/RemoveUnusedUseStatements.java b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/RemoveUnusedUseStatements.java index 25bf1508e1f..5264435d12c 100644 --- a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/RemoveUnusedUseStatements.java +++ b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/RemoveUnusedUseStatements.java @@ -29,7 +29,7 @@ public TokenTree apply(TokenTree tree) { // SHAPE_SECTION is always present at this point if there are detected use statements. TreeCursor shapeStatements = Objects.requireNonNull(root.getFirstChild(TreeType.SHAPE_SECTION)) - .getFirstChild(TreeType.SHAPE_STATEMENTS); + .getFirstChild(TreeType.SHAPE_STATEMENTS); if (shapeStatements == null) { return tree; @@ -54,10 +54,10 @@ public TokenTree apply(TokenTree tree) { // Anything left in the map needs to be removed from the tree. for (TreeCursor unused : useShapeNames.values()) { LOGGER.fine( - () -> "Removing unused use statement: " - + unused.getFirstChild(TreeType.ABSOLUTE_ROOT_SHAPE_ID) - .getTree() - .concatTokens() + () -> "Removing unused use statement: " + + unused.getFirstChild(TreeType.ABSOLUTE_ROOT_SHAPE_ID) + .getTree() + .concatTokens() ); unused.getParent().getTree().removeChild(unused.getTree()); } @@ -68,9 +68,9 @@ public TokenTree apply(TokenTree tree) { // Create a map of shape name to the TreeCursor of the use statement. private Map parseShapeIds(TreeCursor root) { List useStatements = Optional.ofNullable(root.getFirstChild(TreeType.SHAPE_SECTION)) - .flatMap(shapeSection -> Optional.ofNullable(shapeSection.getFirstChild(TreeType.USE_SECTION))) - .map(useSection -> useSection.getChildrenByType(TreeType.USE_STATEMENT)) - .orElse(Collections.emptyList()); + .flatMap(shapeSection -> Optional.ofNullable(shapeSection.getFirstChild(TreeType.USE_SECTION))) + .map(useSection -> useSection.getChildrenByType(TreeType.USE_STATEMENT)) + .orElse(Collections.emptyList()); Map result = new HashMap<>(useStatements.size()); for (TreeCursor useStatement : useStatements) { diff --git a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/SortUseStatements.java b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/SortUseStatements.java index 627b57d67d2..76b3bdfa61e 100644 --- a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/SortUseStatements.java +++ b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/SortUseStatements.java @@ -25,7 +25,7 @@ final class SortUseStatements implements Function { @Override public TokenTree apply(TokenTree tree) { TreeCursor useSection = Objects.requireNonNull(tree.zipper().getFirstChild(TreeType.SHAPE_SECTION)) - .getFirstChild(TreeType.USE_SECTION); + .getFirstChild(TreeType.USE_SECTION); // All trees should have a USE_SECTION. If the section is empty, then no use statements need to be sorted. // Note that if it isn't empty, then there is a guaranteed NAMESPACE_STATEMENT too. @@ -37,7 +37,7 @@ public TokenTree apply(TokenTree tree) { // Remove the original statements since they get sorted and re-added. useSection.getChildrenByType(TreeType.USE_STATEMENT) - .forEach(s -> useSection.getTree().removeChild(s.getTree())); + .forEach(s -> useSection.getTree().removeChild(s.getTree())); dataModel.addFirstUse(useSection); dataModel.addSubsequentUse(useSection); @@ -89,9 +89,9 @@ private void findOrCreateNamespaceBrWs(TreeCursor root) { // statement is moved, then the comments from the previous section need to be removed and moved into this // section, and potentially replaced with comments from USE_SECTION. TreeCursor br = root.findChildrenByType(TreeType.NAMESPACE_STATEMENT) - .get(0) - .findChildrenByType(TreeType.BR) - .get(0); + .get(0) + .findChildrenByType(TreeType.BR) + .get(0); namespaceBrWs = br.getFirstChild(TreeType.WS); @@ -164,16 +164,16 @@ private TokenTree createUseStatement(TokenTree id, TreeCursor lineComment, List< br.appendChild(lineComment.getTree()); } else { br.appendChild( - TokenTree.of( - CapturedToken.builder() - .token(IdlToken.NEWLINE) - .lexeme("\n") - // Set the start line to be the start line of the use statement - // so the formatter knows it's a line comment. - .startLine(id.getStartLine()) - .endLine(id.getStartLine() + 1) - .build() - ) + TokenTree.of( + CapturedToken.builder() + .token(IdlToken.NEWLINE) + .lexeme("\n") + // Set the start line to be the start line of the use statement + // so the formatter knows it's a line comment. + .startLine(id.getStartLine()) + .endLine(id.getStartLine() + 1) + .build() + ) ); } diff --git a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/TokenTreeLeaf.java b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/TokenTreeLeaf.java index 9bdbd5f7121..7246c4c78a8 100644 --- a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/TokenTreeLeaf.java +++ b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/TokenTreeLeaf.java @@ -69,8 +69,8 @@ public String toString() { return token.getIdlToken() + "(" + token.getErrorMessage() + ')'; } else { return token.getIdlToken().getDebug(token.getLexeme()) - + " (" + getStartLine() + ", " + getStartColumn() + ")" - + " - (" + getEndLine() + ", " + getEndColumn() + ")"; + + " (" + getStartLine() + ", " + getStartColumn() + ")" + + " - (" + getEndLine() + ", " + getEndColumn() + ")"; } } diff --git a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/TokenTreeNode.java b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/TokenTreeNode.java index 62f13036795..c4c164b1c88 100644 --- a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/TokenTreeNode.java +++ b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/TokenTreeNode.java @@ -76,16 +76,16 @@ public boolean replaceChild(TokenTree find, TokenTree replacement) { public final String toString() { StringBuilder result = new StringBuilder(); result.append(getType()) - .append(" (") - .append(getStartLine()) - .append(", ") - .append(getStartColumn()) - .append(") - (") - .append(getEndLine()) - .append(", ") - .append(getEndColumn()) - .append(") {") - .append('\n'); + .append(" (") + .append(getStartLine()) + .append(", ") + .append(getStartColumn()) + .append(") - (") + .append(getEndLine()) + .append(", ") + .append(getEndColumn()) + .append(") {") + .append('\n'); if (getError() != null) { result.append(" ").append(getError()).append("\n ---\n"); } diff --git a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/TreeType.java b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/TreeType.java index c96d4854882..1784b2aea67 100644 --- a/smithy-syntax/src/main/java/software/amazon/smithy/syntax/TreeType.java +++ b/smithy-syntax/src/main/java/software/amazon/smithy/syntax/TreeType.java @@ -118,9 +118,9 @@ void parse(CapturingTokenizer tokenizer) { } else if (tokenizer.hasNext()) { tokenizer.withState(this, () -> { throw new ModelSyntaxException( - "Expected a namespace definition but found " - + tokenizer.getCurrentToken().getDebug(tokenizer.getCurrentTokenLexeme()), - tokenizer.getCurrentTokenLocation() + "Expected a namespace definition but found " + + tokenizer.getCurrentToken().getDebug(tokenizer.getCurrentTokenLexeme()), + tokenizer.getCurrentTokenLocation() ); }); } @@ -197,12 +197,12 @@ void parse(CapturingTokenizer tokenizer) { void parse(CapturingTokenizer tokenizer) { tokenizer.withState(this, () -> { ShapeType type = ShapeType.fromString(tokenizer.internString(tokenizer.getCurrentTokenLexeme())) - .orElseThrow( - () -> new ModelSyntaxException( - "Expected a valid shape type", - tokenizer.getCurrentTokenLocation() - ) - ); + .orElseThrow( + () -> new ModelSyntaxException( + "Expected a valid shape type", + tokenizer.getCurrentTokenLocation() + ) + ); switch (type) { case ENUM: case INT_ENUM: @@ -457,9 +457,9 @@ void parse(CapturingTokenizer tokenizer) { OPERATION_ERRORS.parse(tokenizer); } else { throw new ModelSyntaxException( - "Expected 'input', 'output', or 'errors'. Found '" - + tokenizer.getCurrentTokenLexeme() + "'", - tokenizer.getCurrentTokenLocation() + "Expected 'input', 'output', or 'errors'. Found '" + + tokenizer.getCurrentTokenLexeme() + "'", + tokenizer.getCurrentTokenLocation() ); } }); @@ -609,12 +609,12 @@ void parse(CapturingTokenizer tokenizer) { if (tokenizer.getCurrentToken() != IdlToken.RPAREN) { tokenizer.expect( - IdlToken.LBRACE, - IdlToken.LBRACKET, - IdlToken.TEXT_BLOCK, - IdlToken.STRING, - IdlToken.NUMBER, - IdlToken.IDENTIFIER + IdlToken.LBRACE, + IdlToken.LBRACKET, + IdlToken.TEXT_BLOCK, + IdlToken.STRING, + IdlToken.NUMBER, + IdlToken.IDENTIFIER ); switch (tokenizer.getCurrentToken()) { case LBRACE: @@ -627,8 +627,8 @@ void parse(CapturingTokenizer tokenizer) { case IDENTIFIER: default: CapturedToken nextPastWs = tokenizer.peekWhile( - 1, - token -> token.isWhitespace() || token == IdlToken.DOC_COMMENT + 1, + token -> token.isWhitespace() || token == IdlToken.DOC_COMMENT ); if (nextPastWs.getIdlToken() == IdlToken.COLON) { TRAIT_STRUCTURE.parse(tokenizer); @@ -673,8 +673,8 @@ void parse(CapturingTokenizer tokenizer) { tokenizer.withState(this, () -> { // Try to see if this is a singular or block apply statement. IdlToken peek = tokenizer - .peekWhile(1, t -> t != IdlToken.AT && t != IdlToken.LBRACE) - .getIdlToken(); + .peekWhile(1, t -> t != IdlToken.AT && t != IdlToken.LBRACE) + .getIdlToken(); if (peek == IdlToken.LBRACE) { APPLY_STATEMENT_BLOCK.parse(tokenizer); } else { @@ -721,17 +721,17 @@ void parse(CapturingTokenizer tokenizer) { void parse(CapturingTokenizer tokenizer) { tokenizer.withState(this, () -> { IdlToken token = tokenizer.expect( - IdlToken.STRING, - IdlToken.TEXT_BLOCK, - IdlToken.NUMBER, - IdlToken.IDENTIFIER, - IdlToken.LBRACE, - IdlToken.LBRACKET + IdlToken.STRING, + IdlToken.TEXT_BLOCK, + IdlToken.NUMBER, + IdlToken.IDENTIFIER, + IdlToken.LBRACE, + IdlToken.LBRACKET ); switch (token) { case IDENTIFIER: if (tokenizer.isCurrentLexeme("true") || tokenizer.isCurrentLexeme("false") - || tokenizer.isCurrentLexeme("null")) { + || tokenizer.isCurrentLexeme("null")) { NODE_KEYWORD.parse(tokenizer); } else { NODE_STRING_VALUE.parse(tokenizer); @@ -899,8 +899,8 @@ void parse(CapturingTokenizer tokenizer) { void parse(CapturingTokenizer tokenizer) { tokenizer.withState(this, () -> { IdlToken after = tokenizer - .peekWhile(0, t -> t == IdlToken.DOT || t == IdlToken.IDENTIFIER) - .getIdlToken(); + .peekWhile(0, t -> t == IdlToken.DOT || t == IdlToken.IDENTIFIER) + .getIdlToken(); if (after == IdlToken.POUND) { ABSOLUTE_ROOT_SHAPE_ID.parse(tokenizer); } else { @@ -990,8 +990,8 @@ void parse(CapturingTokenizer tokenizer) { break; default: throw new UnsupportedOperationException( - "Unexpected WS token: " - + tokenizer.getCurrentToken() + "Unexpected WS token: " + + tokenizer.getCurrentToken() ); } } while (TreeType.isToken(tokenizer, WS_CHARS)); @@ -1067,11 +1067,11 @@ void parse(CapturingTokenizer tokenizer) { // For now, this also skips doc comments. We may later move doc comments out of WS. private static final IdlToken[] WS_CHARS = { - IdlToken.SPACE, - IdlToken.NEWLINE, - IdlToken.COMMA, - IdlToken.COMMENT, - IdlToken.DOC_COMMENT}; + IdlToken.SPACE, + IdlToken.NEWLINE, + IdlToken.COMMA, + IdlToken.COMMENT, + IdlToken.DOC_COMMENT}; abstract void parse(CapturingTokenizer tokenizer); diff --git a/smithy-syntax/src/test/java/software/amazon/smithy/syntax/ParseAndFormatTest.java b/smithy-syntax/src/test/java/software/amazon/smithy/syntax/ParseAndFormatTest.java index e3c6288b757..a994a0e42ab 100644 --- a/smithy-syntax/src/test/java/software/amazon/smithy/syntax/ParseAndFormatTest.java +++ b/smithy-syntax/src/test/java/software/amazon/smithy/syntax/ParseAndFormatTest.java @@ -37,18 +37,18 @@ public void testRunner(Path filename) { // Ensure that the tests can be parsed by smithy-model too. Model.assembler() - .addImport(filename) - .putProperty(ModelAssembler.ALLOW_UNKNOWN_TRAITS, true) - .disableValidation() - .assemble() - .unwrap(); - if (!formattedFile.equals(filename)) { - Model.assembler() - .addImport(formattedFile) + .addImport(filename) .putProperty(ModelAssembler.ALLOW_UNKNOWN_TRAITS, true) .disableValidation() .assemble() .unwrap(); + if (!formattedFile.equals(filename)) { + Model.assembler() + .addImport(formattedFile) + .putProperty(ModelAssembler.ALLOW_UNKNOWN_TRAITS, true) + .disableValidation() + .assemble() + .unwrap(); } String model = IoUtils.readUtf8File(filename); @@ -65,12 +65,12 @@ public static List tests() throws Exception { try (Stream files = Files.walk(Paths.get(ParseAndFormatTest.class.getResource(CORPUS_DIR).toURI()))) { files - .filter(Files::isRegularFile) - .filter(file -> { - String filename = file.toString(); - return filename.endsWith(".smithy") && !filename.endsWith(".formatted.smithy"); - }) - .forEach(paths::add); + .filter(Files::isRegularFile) + .filter(file -> { + String filename = file.toString(); + return filename.endsWith(".smithy") && !filename.endsWith(".formatted.smithy"); + }) + .forEach(paths::add); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/smithy-syntax/src/test/java/software/amazon/smithy/syntax/TreeTypeTest.java b/smithy-syntax/src/test/java/software/amazon/smithy/syntax/TreeTypeTest.java index 7ca88e0ff11..369616fc8a8 100644 --- a/smithy-syntax/src/test/java/software/amazon/smithy/syntax/TreeTypeTest.java +++ b/smithy-syntax/src/test/java/software/amazon/smithy/syntax/TreeTypeTest.java @@ -21,11 +21,11 @@ public void idl() { TreeType.IDL.parse(tokenizer); assertTreeIsValid(tokenizer.getRoot()); rootAndChildTypesEqual( - tokenizer.getRoot(), - TreeType.IDL, - TreeType.CONTROL_SECTION, - TreeType.METADATA_SECTION, - TreeType.SHAPE_SECTION + tokenizer.getRoot(), + TreeType.IDL, + TreeType.CONTROL_SECTION, + TreeType.METADATA_SECTION, + TreeType.SHAPE_SECTION ); } @@ -35,10 +35,10 @@ public void controlSection() { TokenTree tree = getTree(TreeType.CONTROL_SECTION, controlSection); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.CONTROL_SECTION, - TreeType.CONTROL_STATEMENT, - TreeType.CONTROL_STATEMENT + tree, + TreeType.CONTROL_SECTION, + TreeType.CONTROL_STATEMENT, + TreeType.CONTROL_STATEMENT ); } @@ -48,14 +48,14 @@ public void controlStatement() { TokenTree tree = getTree(TreeType.CONTROL_STATEMENT, controlStatement); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.CONTROL_STATEMENT, - TreeType.TOKEN, - TreeType.NODE_OBJECT_KEY, - TreeType.TOKEN, - TreeType.SP, - TreeType.NODE_VALUE, - TreeType.BR + tree, + TreeType.CONTROL_STATEMENT, + TreeType.TOKEN, + TreeType.NODE_OBJECT_KEY, + TreeType.TOKEN, + TreeType.SP, + TreeType.NODE_VALUE, + TreeType.BR ); } @@ -65,9 +65,9 @@ public void identifierNodeObjectKey() { TokenTree tree = getTree(TreeType.NODE_OBJECT_KEY, identifier); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.NODE_OBJECT_KEY, - TreeType.IDENTIFIER + tree, + TreeType.NODE_OBJECT_KEY, + TreeType.IDENTIFIER ); } @@ -77,9 +77,9 @@ public void stringNodeObjectKey() { TokenTree tree = getTree(TreeType.NODE_OBJECT_KEY, string); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.NODE_OBJECT_KEY, - TreeType.QUOTED_TEXT + tree, + TreeType.NODE_OBJECT_KEY, + TreeType.QUOTED_TEXT ); } @@ -89,10 +89,10 @@ public void metadataSection() { TokenTree tree = getTree(TreeType.METADATA_SECTION, metadataSection); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.METADATA_SECTION, - TreeType.METADATA_STATEMENT, - TreeType.METADATA_STATEMENT + tree, + TreeType.METADATA_SECTION, + TreeType.METADATA_STATEMENT, + TreeType.METADATA_STATEMENT ); } @@ -102,16 +102,16 @@ public void metadataStatement() { TokenTree tree = getTree(TreeType.METADATA_STATEMENT, statement); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.METADATA_STATEMENT, - TreeType.TOKEN, - TreeType.SP, - TreeType.NODE_OBJECT_KEY, - TreeType.SP, - TreeType.TOKEN, - TreeType.SP, - TreeType.NODE_VALUE, - TreeType.BR + tree, + TreeType.METADATA_STATEMENT, + TreeType.TOKEN, + TreeType.SP, + TreeType.NODE_OBJECT_KEY, + TreeType.SP, + TreeType.TOKEN, + TreeType.SP, + TreeType.NODE_VALUE, + TreeType.BR ); } @@ -121,11 +121,11 @@ public void shapeSection() { TokenTree tree = getTree(TreeType.SHAPE_SECTION, shapeSection); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.SHAPE_SECTION, - TreeType.NAMESPACE_STATEMENT, - TreeType.USE_SECTION, - TreeType.SHAPE_STATEMENTS + tree, + TreeType.SHAPE_SECTION, + TreeType.NAMESPACE_STATEMENT, + TreeType.USE_SECTION, + TreeType.SHAPE_STATEMENTS ); } @@ -135,12 +135,12 @@ public void namespaceStatement() { TokenTree tree = getTree(TreeType.NAMESPACE_STATEMENT, namespaceStatement); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.NAMESPACE_STATEMENT, - TreeType.TOKEN, - TreeType.SP, - TreeType.NAMESPACE, - TreeType.BR + tree, + TreeType.NAMESPACE_STATEMENT, + TreeType.TOKEN, + TreeType.SP, + TreeType.NAMESPACE, + TreeType.BR ); } @@ -150,15 +150,15 @@ public void namespace() { TokenTree tree = getTree(TreeType.NAMESPACE, namespace); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.NAMESPACE, - TreeType.IDENTIFIER, - TreeType.TOKEN, - TreeType.IDENTIFIER, - TreeType.TOKEN, - TreeType.IDENTIFIER, - TreeType.TOKEN, - TreeType.IDENTIFIER + tree, + TreeType.NAMESPACE, + TreeType.IDENTIFIER, + TreeType.TOKEN, + TreeType.IDENTIFIER, + TreeType.TOKEN, + TreeType.IDENTIFIER, + TreeType.TOKEN, + TreeType.IDENTIFIER ); } @@ -168,35 +168,35 @@ public void identifier() { TokenTree tree1 = getTree(TreeType.IDENTIFIER, identifier1); assertTreeIsValid(tree1); rootAndChildTypesEqual( - tree1, - TreeType.IDENTIFIER, - TreeType.TOKEN + tree1, + TreeType.IDENTIFIER, + TreeType.TOKEN ); String identifier2 = "_foo"; TokenTree tree2 = getTree(TreeType.IDENTIFIER, identifier2); assertTreeIsValid(tree2); rootAndChildTypesEqual( - tree2, - TreeType.IDENTIFIER, - TreeType.TOKEN + tree2, + TreeType.IDENTIFIER, + TreeType.TOKEN ); String identifier3 = "_1foo"; TokenTree tree3 = getTree(TreeType.IDENTIFIER, identifier3); assertTreeIsValid(tree3); rootAndChildTypesEqual( - tree3, - TreeType.IDENTIFIER, - TreeType.TOKEN + tree3, + TreeType.IDENTIFIER, + TreeType.TOKEN ); String identifier4 = "1foo"; TokenTree tree4 = getTree(TreeType.IDENTIFIER, identifier4); rootAndChildTypesEqual( - tree4, - TreeType.IDENTIFIER, - TreeType.ERROR + tree4, + TreeType.IDENTIFIER, + TreeType.ERROR ); } @@ -206,10 +206,10 @@ public void useSection() { TokenTree tree = getTree(TreeType.USE_SECTION, useSection); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.USE_SECTION, - TreeType.USE_STATEMENT, - TreeType.USE_STATEMENT + tree, + TreeType.USE_SECTION, + TreeType.USE_STATEMENT, + TreeType.USE_STATEMENT ); } @@ -219,12 +219,12 @@ public void useStatement() { TokenTree tree = getTree(TreeType.USE_STATEMENT, useStatement); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.USE_STATEMENT, - TreeType.TOKEN, - TreeType.SP, - TreeType.ABSOLUTE_ROOT_SHAPE_ID, - TreeType.BR + tree, + TreeType.USE_STATEMENT, + TreeType.TOKEN, + TreeType.SP, + TreeType.ABSOLUTE_ROOT_SHAPE_ID, + TreeType.BR ); } @@ -234,19 +234,19 @@ public void shapeId() { TokenTree idTree = getTree(TreeType.SHAPE_ID, id); assertTreeIsValid(idTree); rootAndChildTypesEqual( - idTree, - TreeType.SHAPE_ID, - TreeType.ROOT_SHAPE_ID + idTree, + TreeType.SHAPE_ID, + TreeType.ROOT_SHAPE_ID ); String withMember = "foo$bar"; TokenTree withMemberTree = getTree(TreeType.SHAPE_ID, withMember); assertTreeIsValid(withMemberTree); rootAndChildTypesEqual( - withMemberTree, - TreeType.SHAPE_ID, - TreeType.ROOT_SHAPE_ID, - TreeType.SHAPE_ID_MEMBER + withMemberTree, + TreeType.SHAPE_ID, + TreeType.ROOT_SHAPE_ID, + TreeType.SHAPE_ID_MEMBER ); } @@ -256,18 +256,18 @@ public void rootShapeId() { TokenTree absoluteTree = getTree(TreeType.ROOT_SHAPE_ID, absolute); assertTreeIsValid(absoluteTree); rootAndChildTypesEqual( - absoluteTree, - TreeType.ROOT_SHAPE_ID, - TreeType.ABSOLUTE_ROOT_SHAPE_ID + absoluteTree, + TreeType.ROOT_SHAPE_ID, + TreeType.ABSOLUTE_ROOT_SHAPE_ID ); String id = "foo"; TokenTree idTree = getTree(TreeType.ROOT_SHAPE_ID, id); assertTreeIsValid(idTree); rootAndChildTypesEqual( - idTree, - TreeType.ROOT_SHAPE_ID, - TreeType.IDENTIFIER + idTree, + TreeType.ROOT_SHAPE_ID, + TreeType.IDENTIFIER ); } @@ -277,11 +277,11 @@ public void absoluteRootShapeId() { TokenTree tree = getTree(TreeType.ABSOLUTE_ROOT_SHAPE_ID, absolute); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.ABSOLUTE_ROOT_SHAPE_ID, - TreeType.NAMESPACE, - TreeType.TOKEN, - TreeType.IDENTIFIER + tree, + TreeType.ABSOLUTE_ROOT_SHAPE_ID, + TreeType.NAMESPACE, + TreeType.TOKEN, + TreeType.IDENTIFIER ); } @@ -291,10 +291,10 @@ public void shapeIdMember() { TokenTree tree = getTree(TreeType.SHAPE_ID_MEMBER, shapeIdMember); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.SHAPE_ID_MEMBER, - TreeType.TOKEN, - TreeType.IDENTIFIER + tree, + TreeType.SHAPE_ID_MEMBER, + TreeType.TOKEN, + TreeType.IDENTIFIER ); } @@ -304,12 +304,12 @@ public void shapeStatements() { TokenTree tree = getTree(TreeType.SHAPE_STATEMENTS, statements); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.SHAPE_STATEMENTS, - TreeType.SHAPE_OR_APPLY_STATEMENT, - TreeType.BR, - TreeType.SHAPE_OR_APPLY_STATEMENT, - TreeType.BR + tree, + TreeType.SHAPE_STATEMENTS, + TreeType.SHAPE_OR_APPLY_STATEMENT, + TreeType.BR, + TreeType.SHAPE_OR_APPLY_STATEMENT, + TreeType.BR ); } @@ -319,18 +319,18 @@ public void shapeOrApplyStatement() { TokenTree shapeTree = getTree(TreeType.SHAPE_OR_APPLY_STATEMENT, shape); assertTreeIsValid(shapeTree); rootAndChildTypesEqual( - shapeTree, - TreeType.SHAPE_OR_APPLY_STATEMENT, - TreeType.SHAPE_STATEMENT + shapeTree, + TreeType.SHAPE_OR_APPLY_STATEMENT, + TreeType.SHAPE_STATEMENT ); String apply = "apply foo @bar"; TokenTree applyTree = getTree(TreeType.SHAPE_OR_APPLY_STATEMENT, apply); assertTreeIsValid(applyTree); rootAndChildTypesEqual( - applyTree, - TreeType.SHAPE_OR_APPLY_STATEMENT, - TreeType.APPLY_STATEMENT + applyTree, + TreeType.SHAPE_OR_APPLY_STATEMENT, + TreeType.APPLY_STATEMENT ); } @@ -340,10 +340,10 @@ public void shapeStatement() { TokenTree tree = getTree(TreeType.SHAPE_STATEMENT, statement); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.SHAPE_STATEMENT, - TreeType.TRAIT_STATEMENTS, - TreeType.SHAPE + tree, + TreeType.SHAPE_STATEMENT, + TreeType.TRAIT_STATEMENTS, + TreeType.SHAPE ); } @@ -353,9 +353,9 @@ public void shape() { TokenTree tree = getTree(TreeType.SHAPE, shape); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.SHAPE, - TreeType.AGGREGATE_SHAPE + tree, + TreeType.SHAPE, + TreeType.AGGREGATE_SHAPE ); } @@ -365,24 +365,24 @@ public void simpleShape() { TokenTree shapeTree = getTree(TreeType.SIMPLE_SHAPE, shape); assertTreeIsValid(shapeTree); rootAndChildTypesEqual( - shapeTree, - TreeType.SIMPLE_SHAPE, - TreeType.SIMPLE_TYPE_NAME, - TreeType.SP, - TreeType.IDENTIFIER + shapeTree, + TreeType.SIMPLE_SHAPE, + TreeType.SIMPLE_TYPE_NAME, + TreeType.SP, + TreeType.IDENTIFIER ); String withMixins = "string Foo with [Bar]"; TokenTree withMixinsTree = getTree(TreeType.SIMPLE_SHAPE, withMixins); assertTreeIsValid(withMixinsTree); rootAndChildTypesEqual( - withMixinsTree, - TreeType.SIMPLE_SHAPE, - TreeType.SIMPLE_TYPE_NAME, - TreeType.SP, - TreeType.IDENTIFIER, - TreeType.SP, - TreeType.MIXINS + withMixinsTree, + TreeType.SIMPLE_SHAPE, + TreeType.SIMPLE_TYPE_NAME, + TreeType.SP, + TreeType.IDENTIFIER, + TreeType.SP, + TreeType.MIXINS ); } @@ -392,9 +392,9 @@ public void simpleTypeName() { TokenTree tree = getTree(TreeType.SIMPLE_TYPE_NAME, simpleTypeName); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.SIMPLE_TYPE_NAME, - TreeType.TOKEN + tree, + TreeType.SIMPLE_TYPE_NAME, + TreeType.TOKEN ); } @@ -404,28 +404,28 @@ public void enumShape() { TokenTree tree = getTree(TreeType.ENUM_SHAPE, enumShape); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.ENUM_SHAPE, - TreeType.ENUM_TYPE_NAME, - TreeType.SP, - TreeType.IDENTIFIER, - TreeType.WS, - TreeType.ENUM_SHAPE_MEMBERS + tree, + TreeType.ENUM_SHAPE, + TreeType.ENUM_TYPE_NAME, + TreeType.SP, + TreeType.IDENTIFIER, + TreeType.WS, + TreeType.ENUM_SHAPE_MEMBERS ); String withMixins = "enum Foo with [Bar] \n{foo}"; TokenTree withMixinsTree = getTree(TreeType.ENUM_SHAPE, withMixins); assertTreeIsValid(withMixinsTree); rootAndChildTypesEqual( - withMixinsTree, - TreeType.ENUM_SHAPE, - TreeType.ENUM_TYPE_NAME, - TreeType.SP, - TreeType.IDENTIFIER, - TreeType.SP, - TreeType.MIXINS, - TreeType.WS, - TreeType.ENUM_SHAPE_MEMBERS + withMixinsTree, + TreeType.ENUM_SHAPE, + TreeType.ENUM_TYPE_NAME, + TreeType.SP, + TreeType.IDENTIFIER, + TreeType.SP, + TreeType.MIXINS, + TreeType.WS, + TreeType.ENUM_SHAPE_MEMBERS ); } @@ -435,9 +435,9 @@ public void enumTypeName() { TokenTree tree = getTree(TreeType.ENUM_TYPE_NAME, enumTypeName); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.ENUM_TYPE_NAME, - TreeType.TOKEN + tree, + TreeType.ENUM_TYPE_NAME, + TreeType.TOKEN ); } @@ -447,17 +447,17 @@ public void enumShapeMembers() { TokenTree tree = getTree(TreeType.ENUM_SHAPE_MEMBERS, members); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.ENUM_SHAPE_MEMBERS, - TreeType.TOKEN, - TreeType.WS, - TreeType.ENUM_SHAPE_MEMBER, - TreeType.WS, - TreeType.ENUM_SHAPE_MEMBER, - TreeType.WS, - TreeType.ENUM_SHAPE_MEMBER, - TreeType.WS, - TreeType.TOKEN + tree, + TreeType.ENUM_SHAPE_MEMBERS, + TreeType.TOKEN, + TreeType.WS, + TreeType.ENUM_SHAPE_MEMBER, + TreeType.WS, + TreeType.ENUM_SHAPE_MEMBER, + TreeType.WS, + TreeType.ENUM_SHAPE_MEMBER, + TreeType.WS, + TreeType.TOKEN ); } @@ -467,42 +467,42 @@ public void enumShapeMember() { TokenTree tree = getTree(TreeType.ENUM_SHAPE_MEMBER, member); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.ENUM_SHAPE_MEMBER, - TreeType.TRAIT_STATEMENTS, - TreeType.IDENTIFIER + tree, + TreeType.ENUM_SHAPE_MEMBER, + TreeType.TRAIT_STATEMENTS, + TreeType.IDENTIFIER ); String withValue = "FOO = BAR\n"; TokenTree withValueTree = getTree(TreeType.ENUM_SHAPE_MEMBER, withValue); assertTreeIsValid(withValueTree); rootAndChildTypesEqual( - withValueTree, - TreeType.ENUM_SHAPE_MEMBER, - TreeType.TRAIT_STATEMENTS, - TreeType.IDENTIFIER, - TreeType.VALUE_ASSIGNMENT + withValueTree, + TreeType.ENUM_SHAPE_MEMBER, + TreeType.TRAIT_STATEMENTS, + TreeType.IDENTIFIER, + TreeType.VALUE_ASSIGNMENT ); String noWs = "FOO=BAR\n"; TokenTree noWsTree = getTree(TreeType.ENUM_SHAPE_MEMBER, noWs); assertTreeIsValid(noWsTree); rootAndChildTypesEqual( - noWsTree, - TreeType.ENUM_SHAPE_MEMBER, - TreeType.TRAIT_STATEMENTS, - TreeType.IDENTIFIER, - TreeType.VALUE_ASSIGNMENT + noWsTree, + TreeType.ENUM_SHAPE_MEMBER, + TreeType.TRAIT_STATEMENTS, + TreeType.IDENTIFIER, + TreeType.VALUE_ASSIGNMENT ); String withTraits = "@foo\n@bar\nFOO"; TokenTree withTraitsTree = getTree(TreeType.ENUM_SHAPE_MEMBER, withTraits); assertTreeIsValid(withTraitsTree); rootAndChildTypesEqual( - withTraitsTree, - TreeType.ENUM_SHAPE_MEMBER, - TreeType.TRAIT_STATEMENTS, - TreeType.IDENTIFIER + withTraitsTree, + TreeType.ENUM_SHAPE_MEMBER, + TreeType.TRAIT_STATEMENTS, + TreeType.IDENTIFIER ); } @@ -512,13 +512,13 @@ public void aggregateShape() { TokenTree tree = getTree(TreeType.AGGREGATE_SHAPE, shape); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.AGGREGATE_SHAPE, - TreeType.AGGREGATE_TYPE_NAME, - TreeType.SP, - TreeType.IDENTIFIER, - TreeType.SP, - TreeType.SHAPE_MEMBERS + tree, + TreeType.AGGREGATE_SHAPE, + TreeType.AGGREGATE_TYPE_NAME, + TreeType.SP, + TreeType.IDENTIFIER, + TreeType.SP, + TreeType.SHAPE_MEMBERS ); } @@ -528,9 +528,9 @@ public void aggregateTypeName() { TokenTree tree = getTree(TreeType.AGGREGATE_TYPE_NAME, typeName); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.AGGREGATE_TYPE_NAME, - TreeType.TOKEN + tree, + TreeType.AGGREGATE_TYPE_NAME, + TreeType.TOKEN ); } @@ -540,15 +540,15 @@ public void aggregateShapeForResource() { TokenTree tree = getTree(TreeType.AGGREGATE_SHAPE, shape); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.AGGREGATE_SHAPE, - TreeType.AGGREGATE_TYPE_NAME, - TreeType.SP, - TreeType.IDENTIFIER, - TreeType.SP, - TreeType.FOR_RESOURCE, - TreeType.SP, - TreeType.SHAPE_MEMBERS + tree, + TreeType.AGGREGATE_SHAPE, + TreeType.AGGREGATE_TYPE_NAME, + TreeType.SP, + TreeType.IDENTIFIER, + TreeType.SP, + TreeType.FOR_RESOURCE, + TreeType.SP, + TreeType.SHAPE_MEMBERS ); } @@ -558,15 +558,15 @@ public void aggregateShapeMixins() { TokenTree tree = getTree(TreeType.AGGREGATE_SHAPE, shape); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.AGGREGATE_SHAPE, - TreeType.AGGREGATE_TYPE_NAME, - TreeType.SP, - TreeType.IDENTIFIER, - TreeType.SP, - TreeType.MIXINS, - TreeType.WS, - TreeType.SHAPE_MEMBERS + tree, + TreeType.AGGREGATE_SHAPE, + TreeType.AGGREGATE_TYPE_NAME, + TreeType.SP, + TreeType.IDENTIFIER, + TreeType.SP, + TreeType.MIXINS, + TreeType.WS, + TreeType.SHAPE_MEMBERS ); } @@ -576,17 +576,17 @@ public void aggregateShapeForResourceAndMixins() { TokenTree tree = getTree(TreeType.AGGREGATE_SHAPE, shape); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.AGGREGATE_SHAPE, - TreeType.AGGREGATE_TYPE_NAME, - TreeType.SP, - TreeType.IDENTIFIER, - TreeType.SP, - TreeType.FOR_RESOURCE, - TreeType.SP, - TreeType.MIXINS, - TreeType.WS, - TreeType.SHAPE_MEMBERS + tree, + TreeType.AGGREGATE_SHAPE, + TreeType.AGGREGATE_TYPE_NAME, + TreeType.SP, + TreeType.IDENTIFIER, + TreeType.SP, + TreeType.FOR_RESOURCE, + TreeType.SP, + TreeType.MIXINS, + TreeType.WS, + TreeType.SHAPE_MEMBERS ); } @@ -596,11 +596,11 @@ public void forResource() { TokenTree tree = getTree(TreeType.FOR_RESOURCE, forResource); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.FOR_RESOURCE, - TreeType.TOKEN, - TreeType.SP, - TreeType.SHAPE_ID + tree, + TreeType.FOR_RESOURCE, + TreeType.TOKEN, + TreeType.SP, + TreeType.SHAPE_ID ); } @@ -610,15 +610,15 @@ public void mixins() { TokenTree tree = getTree(TreeType.MIXINS, mixins); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.MIXINS, - TreeType.TOKEN, - TreeType.WS, - TreeType.TOKEN, - TreeType.SHAPE_ID, - TreeType.WS, - TreeType.SHAPE_ID, - TreeType.TOKEN + tree, + TreeType.MIXINS, + TreeType.TOKEN, + TreeType.WS, + TreeType.TOKEN, + TreeType.SHAPE_ID, + TreeType.WS, + TreeType.SHAPE_ID, + TreeType.TOKEN ); } @@ -628,15 +628,15 @@ public void shapeMembers() { TokenTree tree = getTree(TreeType.SHAPE_MEMBERS, shapeMembers); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.SHAPE_MEMBERS, - TreeType.TOKEN, - TreeType.WS, - TreeType.SHAPE_MEMBER, - TreeType.WS, - TreeType.SHAPE_MEMBER, - TreeType.WS, - TreeType.TOKEN + tree, + TreeType.SHAPE_MEMBERS, + TreeType.TOKEN, + TreeType.WS, + TreeType.SHAPE_MEMBER, + TreeType.WS, + TreeType.SHAPE_MEMBER, + TreeType.WS, + TreeType.TOKEN ); } @@ -646,10 +646,10 @@ public void shapeMember() { TokenTree tree = getTree(TreeType.SHAPE_MEMBER, shapeMember); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.SHAPE_MEMBER, - TreeType.TRAIT_STATEMENTS, - TreeType.EXPLICIT_SHAPE_MEMBER + tree, + TreeType.SHAPE_MEMBER, + TreeType.TRAIT_STATEMENTS, + TreeType.EXPLICIT_SHAPE_MEMBER ); } @@ -659,12 +659,12 @@ public void traitStatements() { TokenTree tree = getTree(TreeType.TRAIT_STATEMENTS, traitStatements); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.TRAIT_STATEMENTS, - TreeType.TRAIT, - TreeType.WS, - TreeType.TRAIT, - TreeType.WS + tree, + TreeType.TRAIT_STATEMENTS, + TreeType.TRAIT, + TreeType.WS, + TreeType.TRAIT, + TreeType.WS ); } @@ -674,10 +674,10 @@ public void trait() { TokenTree tree = getTree(TreeType.TRAIT, trait); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.TRAIT, - TreeType.TOKEN, - TreeType.SHAPE_ID + tree, + TreeType.TRAIT, + TreeType.TOKEN, + TreeType.SHAPE_ID ); } @@ -687,11 +687,11 @@ public void traitWithEmptyBody() { TokenTree tree = getTree(TreeType.TRAIT, trait); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.TRAIT, - TreeType.TOKEN, - TreeType.SHAPE_ID, - TreeType.TRAIT_BODY + tree, + TreeType.TRAIT, + TreeType.TOKEN, + TreeType.SHAPE_ID, + TreeType.TRAIT_BODY ); } @@ -701,11 +701,11 @@ public void traitWithNonEmptyBody() { TokenTree tree = getTree(TreeType.TRAIT, trait); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.TRAIT, - TreeType.TOKEN, - TreeType.SHAPE_ID, - TreeType.TRAIT_BODY + tree, + TreeType.TRAIT, + TreeType.TOKEN, + TreeType.SHAPE_ID, + TreeType.TRAIT_BODY ); } @@ -715,12 +715,12 @@ public void traitBody() { TokenTree tree = getTree(TreeType.TRAIT_BODY, traitBody); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.TRAIT_BODY, - TreeType.TOKEN, - TreeType.WS, - TreeType.TRAIT_STRUCTURE, - TreeType.TOKEN + tree, + TreeType.TRAIT_BODY, + TreeType.TOKEN, + TreeType.WS, + TreeType.TRAIT_STRUCTURE, + TreeType.TOKEN ); } @@ -746,12 +746,12 @@ public void traitBodyWithWs() { TokenTree tree = getTree(TreeType.TRAIT_BODY, traitBody); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.TRAIT_BODY, - TreeType.TOKEN, - TreeType.WS, - TreeType.TRAIT_NODE, - TreeType.TOKEN + tree, + TreeType.TRAIT_BODY, + TreeType.TOKEN, + TreeType.WS, + TreeType.TRAIT_NODE, + TreeType.TOKEN ); } @@ -777,14 +777,14 @@ public void traitStructure() { TokenTree tree = getTree(TreeType.TRAIT_STRUCTURE, traitStructure); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.TRAIT_STRUCTURE, - TreeType.NODE_OBJECT_KVP, - TreeType.WS, - TreeType.NODE_OBJECT_KVP, - TreeType.WS, - TreeType.NODE_OBJECT_KVP, - TreeType.WS + tree, + TreeType.TRAIT_STRUCTURE, + TreeType.NODE_OBJECT_KVP, + TreeType.WS, + TreeType.NODE_OBJECT_KVP, + TreeType.WS, + TreeType.NODE_OBJECT_KVP, + TreeType.WS ); } @@ -794,13 +794,13 @@ public void explicitShapeMember() { TokenTree tree = getTree(TreeType.EXPLICIT_SHAPE_MEMBER, explicitShapeMember); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.EXPLICIT_SHAPE_MEMBER, - TreeType.IDENTIFIER, - TreeType.SP, - TreeType.TOKEN, - TreeType.SP, - TreeType.SHAPE_ID + tree, + TreeType.EXPLICIT_SHAPE_MEMBER, + TreeType.IDENTIFIER, + TreeType.SP, + TreeType.TOKEN, + TreeType.SP, + TreeType.SHAPE_ID ); } @@ -810,10 +810,10 @@ public void elidedShapeMember() { TokenTree tree = getTree(TreeType.ELIDED_SHAPE_MEMBER, elidedShapeMember); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.ELIDED_SHAPE_MEMBER, - TreeType.TOKEN, - TreeType.IDENTIFIER + tree, + TreeType.ELIDED_SHAPE_MEMBER, + TreeType.TOKEN, + TreeType.IDENTIFIER ); } @@ -823,15 +823,15 @@ public void valueAssignment() { TokenTree tree = getTree(TreeType.VALUE_ASSIGNMENT, valueAssignment); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.VALUE_ASSIGNMENT, - TreeType.SP, - TreeType.TOKEN, - TreeType.SP, - TreeType.NODE_VALUE, - TreeType.SP, - TreeType.COMMA, - TreeType.BR + tree, + TreeType.VALUE_ASSIGNMENT, + TreeType.SP, + TreeType.TOKEN, + TreeType.SP, + TreeType.NODE_VALUE, + TreeType.SP, + TreeType.COMMA, + TreeType.BR ); } @@ -841,40 +841,40 @@ public void entityShape() { TokenTree entityShapeTree = getTree(TreeType.ENTITY_SHAPE, entityShape); assertTreeIsValid(entityShapeTree); rootAndChildTypesEqual( - entityShapeTree, - TreeType.ENTITY_SHAPE, - TreeType.ENTITY_TYPE_NAME, - TreeType.SP, - TreeType.IDENTIFIER, - TreeType.SP, - TreeType.NODE_OBJECT + entityShapeTree, + TreeType.ENTITY_SHAPE, + TreeType.ENTITY_TYPE_NAME, + TreeType.SP, + TreeType.IDENTIFIER, + TreeType.SP, + TreeType.NODE_OBJECT ); String noWs = "service Foo{}"; TokenTree noWsTree = getTree(TreeType.ENTITY_SHAPE, noWs); assertTreeIsValid(noWsTree); rootAndChildTypesEqual( - noWsTree, - TreeType.ENTITY_SHAPE, - TreeType.ENTITY_TYPE_NAME, - TreeType.SP, - TreeType.IDENTIFIER, - TreeType.NODE_OBJECT + noWsTree, + TreeType.ENTITY_SHAPE, + TreeType.ENTITY_TYPE_NAME, + TreeType.SP, + TreeType.IDENTIFIER, + TreeType.NODE_OBJECT ); String withMixins = "service Foo with [Bar] {}"; TokenTree withMixinsTree = getTree(TreeType.ENTITY_SHAPE, withMixins); assertTreeIsValid(withMixinsTree); rootAndChildTypesEqual( - withMixinsTree, - TreeType.ENTITY_SHAPE, - TreeType.ENTITY_TYPE_NAME, - TreeType.SP, - TreeType.IDENTIFIER, - TreeType.SP, - TreeType.MIXINS, - TreeType.WS, - TreeType.NODE_OBJECT + withMixinsTree, + TreeType.ENTITY_SHAPE, + TreeType.ENTITY_TYPE_NAME, + TreeType.SP, + TreeType.IDENTIFIER, + TreeType.SP, + TreeType.MIXINS, + TreeType.WS, + TreeType.NODE_OBJECT ); } @@ -884,9 +884,9 @@ public void entityTypeName() { TokenTree tree = getTree(TreeType.ENTITY_TYPE_NAME, typeName); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.ENTITY_TYPE_NAME, - TreeType.TOKEN + tree, + TreeType.ENTITY_TYPE_NAME, + TreeType.TOKEN ); } @@ -896,40 +896,40 @@ public void operationShape() { TokenTree shapeTree = getTree(TreeType.OPERATION_SHAPE, shape); assertTreeIsValid(shapeTree); rootAndChildTypesEqual( - shapeTree, - TreeType.OPERATION_SHAPE, - TreeType.TOKEN, - TreeType.SP, - TreeType.IDENTIFIER, - TreeType.SP, - TreeType.OPERATION_BODY + shapeTree, + TreeType.OPERATION_SHAPE, + TreeType.TOKEN, + TreeType.SP, + TreeType.IDENTIFIER, + TreeType.SP, + TreeType.OPERATION_BODY ); String noWs = "operation Foo{input: Foo output: Bar}"; TokenTree noWsTree = getTree(TreeType.OPERATION_SHAPE, noWs); assertTreeIsValid(noWsTree); rootAndChildTypesEqual( - noWsTree, - TreeType.OPERATION_SHAPE, - TreeType.TOKEN, - TreeType.SP, - TreeType.IDENTIFIER, - TreeType.OPERATION_BODY + noWsTree, + TreeType.OPERATION_SHAPE, + TreeType.TOKEN, + TreeType.SP, + TreeType.IDENTIFIER, + TreeType.OPERATION_BODY ); String withMixins = "operation Foo with [Bar] {input: Foo output: Bar}"; TokenTree withMixinsTree = getTree(TreeType.OPERATION_SHAPE, withMixins); assertTreeIsValid(withMixinsTree); rootAndChildTypesEqual( - withMixinsTree, - TreeType.OPERATION_SHAPE, - TreeType.TOKEN, - TreeType.SP, - TreeType.IDENTIFIER, - TreeType.SP, - TreeType.MIXINS, - TreeType.WS, - TreeType.OPERATION_BODY + withMixinsTree, + TreeType.OPERATION_SHAPE, + TreeType.TOKEN, + TreeType.SP, + TreeType.IDENTIFIER, + TreeType.SP, + TreeType.MIXINS, + TreeType.WS, + TreeType.OPERATION_BODY ); } @@ -939,37 +939,37 @@ public void operationBody() { TokenTree operationBodyTree = getTree(TreeType.OPERATION_BODY, operationBody); assertTreeIsValid(operationBodyTree); rootAndChildTypesEqual( - operationBodyTree, - TreeType.OPERATION_BODY, - TreeType.TOKEN, - TreeType.WS, - TreeType.OPERATION_PROPERTY, - TreeType.WS, - TreeType.OPERATION_PROPERTY, - TreeType.WS, - TreeType.TOKEN + operationBodyTree, + TreeType.OPERATION_BODY, + TreeType.TOKEN, + TreeType.WS, + TreeType.OPERATION_PROPERTY, + TreeType.WS, + TreeType.OPERATION_PROPERTY, + TreeType.WS, + TreeType.TOKEN ); String noWs = "{input:foo}"; TokenTree noWsTree = getTree(TreeType.OPERATION_BODY, noWs); assertTreeIsValid(noWsTree); rootAndChildTypesEqual( - noWsTree, - TreeType.OPERATION_BODY, - TreeType.TOKEN, - TreeType.OPERATION_PROPERTY, - TreeType.TOKEN + noWsTree, + TreeType.OPERATION_BODY, + TreeType.TOKEN, + TreeType.OPERATION_PROPERTY, + TreeType.TOKEN ); String onlyWs = "{\n// Foo\n \n}"; TokenTree onlyWsTree = getTree(TreeType.OPERATION_BODY, onlyWs); assertTreeIsValid(onlyWsTree); rootAndChildTypesEqual( - onlyWsTree, - TreeType.OPERATION_BODY, - TreeType.TOKEN, - TreeType.WS, - TreeType.TOKEN + onlyWsTree, + TreeType.OPERATION_BODY, + TreeType.TOKEN, + TreeType.WS, + TreeType.TOKEN ); } @@ -979,27 +979,27 @@ public void operationProperty() { TokenTree inputTree = getTree(TreeType.OPERATION_PROPERTY, input); assertTreeIsValid(inputTree); rootAndChildTypesEqual( - inputTree, - TreeType.OPERATION_PROPERTY, - TreeType.OPERATION_INPUT + inputTree, + TreeType.OPERATION_PROPERTY, + TreeType.OPERATION_INPUT ); String output = "output: foo"; TokenTree outputTree = getTree(TreeType.OPERATION_PROPERTY, output); assertTreeIsValid(outputTree); rootAndChildTypesEqual( - outputTree, - TreeType.OPERATION_PROPERTY, - TreeType.OPERATION_OUTPUT + outputTree, + TreeType.OPERATION_PROPERTY, + TreeType.OPERATION_OUTPUT ); String errors = "errors: []"; TokenTree errorsTree = getTree(TreeType.OPERATION_PROPERTY, errors); assertTreeIsValid(errorsTree); rootAndChildTypesEqual( - errorsTree, - TreeType.OPERATION_PROPERTY, - TreeType.OPERATION_ERRORS + errorsTree, + TreeType.OPERATION_PROPERTY, + TreeType.OPERATION_ERRORS ); } @@ -1009,47 +1009,47 @@ public void operationInput() { TokenTree withWsTree = getTree(TreeType.OPERATION_INPUT, withWs); assertTreeIsValid(withWsTree); rootAndChildTypesEqual( - withWsTree, - TreeType.OPERATION_INPUT, - TreeType.TOKEN, - TreeType.WS, - TreeType.TOKEN, - TreeType.WS, - TreeType.SHAPE_ID + withWsTree, + TreeType.OPERATION_INPUT, + TreeType.TOKEN, + TreeType.WS, + TreeType.TOKEN, + TreeType.WS, + TreeType.SHAPE_ID ); String noWs = "input:foo"; TokenTree noWsTree = getTree(TreeType.OPERATION_INPUT, noWs); assertTreeIsValid(noWsTree); rootAndChildTypesEqual( - noWsTree, - TreeType.OPERATION_INPUT, - TreeType.TOKEN, - TreeType.TOKEN, - TreeType.SHAPE_ID + noWsTree, + TreeType.OPERATION_INPUT, + TreeType.TOKEN, + TreeType.TOKEN, + TreeType.SHAPE_ID ); String shapeId = "input: foo.bar#Baz"; TokenTree shapeIdTree = getTree(TreeType.OPERATION_INPUT, shapeId); assertTreeIsValid(shapeIdTree); rootAndChildTypesEqual( - shapeIdTree, - TreeType.OPERATION_INPUT, - TreeType.TOKEN, - TreeType.TOKEN, - TreeType.WS, - TreeType.SHAPE_ID + shapeIdTree, + TreeType.OPERATION_INPUT, + TreeType.TOKEN, + TreeType.TOKEN, + TreeType.WS, + TreeType.SHAPE_ID ); String inline = "input := {}"; TokenTree inlineTree = getTree(TreeType.OPERATION_INPUT, inline); assertTreeIsValid(inlineTree); rootAndChildTypesEqual( - inlineTree, - TreeType.OPERATION_INPUT, - TreeType.TOKEN, - TreeType.WS, - TreeType.INLINE_AGGREGATE_SHAPE + inlineTree, + TreeType.OPERATION_INPUT, + TreeType.TOKEN, + TreeType.WS, + TreeType.INLINE_AGGREGATE_SHAPE ); } @@ -1059,47 +1059,47 @@ public void operationOutput() { TokenTree withWsTree = getTree(TreeType.OPERATION_OUTPUT, withWs); assertTreeIsValid(withWsTree); rootAndChildTypesEqual( - withWsTree, - TreeType.OPERATION_OUTPUT, - TreeType.TOKEN, - TreeType.WS, - TreeType.TOKEN, - TreeType.WS, - TreeType.SHAPE_ID + withWsTree, + TreeType.OPERATION_OUTPUT, + TreeType.TOKEN, + TreeType.WS, + TreeType.TOKEN, + TreeType.WS, + TreeType.SHAPE_ID ); String noWs = "output:foo"; TokenTree noWsTree = getTree(TreeType.OPERATION_OUTPUT, noWs); assertTreeIsValid(noWsTree); rootAndChildTypesEqual( - noWsTree, - TreeType.OPERATION_OUTPUT, - TreeType.TOKEN, - TreeType.TOKEN, - TreeType.SHAPE_ID + noWsTree, + TreeType.OPERATION_OUTPUT, + TreeType.TOKEN, + TreeType.TOKEN, + TreeType.SHAPE_ID ); String shapeId = "output: foo.bar#Baz"; TokenTree shapeIdTree = getTree(TreeType.OPERATION_OUTPUT, shapeId); assertTreeIsValid(shapeIdTree); rootAndChildTypesEqual( - shapeIdTree, - TreeType.OPERATION_OUTPUT, - TreeType.TOKEN, - TreeType.TOKEN, - TreeType.WS, - TreeType.SHAPE_ID + shapeIdTree, + TreeType.OPERATION_OUTPUT, + TreeType.TOKEN, + TreeType.TOKEN, + TreeType.WS, + TreeType.SHAPE_ID ); String inline = "output := {}"; TokenTree inlineTree = getTree(TreeType.OPERATION_OUTPUT, inline); assertTreeIsValid(inlineTree); rootAndChildTypesEqual( - inlineTree, - TreeType.OPERATION_OUTPUT, - TreeType.TOKEN, - TreeType.WS, - TreeType.INLINE_AGGREGATE_SHAPE + inlineTree, + TreeType.OPERATION_OUTPUT, + TreeType.TOKEN, + TreeType.WS, + TreeType.INLINE_AGGREGATE_SHAPE ); } @@ -1109,24 +1109,24 @@ public void inlineAggregateShape() { TokenTree basicTree = getTree(TreeType.INLINE_AGGREGATE_SHAPE, basic); assertTreeIsValid(basicTree); rootAndChildTypesEqual( - basicTree, - TreeType.INLINE_AGGREGATE_SHAPE, - TreeType.TOKEN, - TreeType.WS, - TreeType.TRAIT_STATEMENTS, - TreeType.SHAPE_MEMBERS + basicTree, + TreeType.INLINE_AGGREGATE_SHAPE, + TreeType.TOKEN, + TreeType.WS, + TreeType.TRAIT_STATEMENTS, + TreeType.SHAPE_MEMBERS ); String withTraits = ":= @foo\n\n@bar\n\n{ foo: bar }"; TokenTree withTraitsTree = getTree(TreeType.INLINE_AGGREGATE_SHAPE, withTraits); assertTreeIsValid(withTraitsTree); rootAndChildTypesEqual( - withTraitsTree, - TreeType.INLINE_AGGREGATE_SHAPE, - TreeType.TOKEN, - TreeType.WS, - TreeType.TRAIT_STATEMENTS, - TreeType.SHAPE_MEMBERS + withTraitsTree, + TreeType.INLINE_AGGREGATE_SHAPE, + TreeType.TOKEN, + TreeType.WS, + TreeType.TRAIT_STATEMENTS, + TreeType.SHAPE_MEMBERS ); } @@ -1136,45 +1136,45 @@ public void operationErrors() { TokenTree emptyTree = getTree(TreeType.OPERATION_ERRORS, empty); assertTreeIsValid(emptyTree); rootAndChildTypesEqual( - emptyTree, - TreeType.OPERATION_ERRORS, - TreeType.TOKEN, - TreeType.TOKEN, - TreeType.WS, - TreeType.TOKEN, - TreeType.TOKEN + emptyTree, + TreeType.OPERATION_ERRORS, + TreeType.TOKEN, + TreeType.TOKEN, + TreeType.WS, + TreeType.TOKEN, + TreeType.TOKEN ); String noWs = "errors:[foo]"; TokenTree noWsTree = getTree(TreeType.OPERATION_ERRORS, noWs); assertTreeIsValid(noWsTree); rootAndChildTypesEqual( - noWsTree, - TreeType.OPERATION_ERRORS, - TreeType.TOKEN, - TreeType.TOKEN, - TreeType.TOKEN, - TreeType.SHAPE_ID, - TreeType.TOKEN + noWsTree, + TreeType.OPERATION_ERRORS, + TreeType.TOKEN, + TreeType.TOKEN, + TreeType.TOKEN, + TreeType.SHAPE_ID, + TreeType.TOKEN ); String withWs = "errors\n//Foo\n: \n[\nfoo // Foo\nbar ]"; TokenTree withWsTree = getTree(TreeType.OPERATION_ERRORS, withWs); assertTreeIsValid(withWsTree); rootAndChildTypesEqual( - withWsTree, - TreeType.OPERATION_ERRORS, - TreeType.TOKEN, - TreeType.WS, - TreeType.TOKEN, - TreeType.WS, - TreeType.TOKEN, - TreeType.WS, - TreeType.SHAPE_ID, - TreeType.WS, - TreeType.SHAPE_ID, - TreeType.WS, - TreeType.TOKEN + withWsTree, + TreeType.OPERATION_ERRORS, + TreeType.TOKEN, + TreeType.WS, + TreeType.TOKEN, + TreeType.WS, + TreeType.TOKEN, + TreeType.WS, + TreeType.SHAPE_ID, + TreeType.WS, + TreeType.SHAPE_ID, + TreeType.WS, + TreeType.TOKEN ); } @@ -1184,9 +1184,9 @@ public void applyStatement() { TokenTree tree = getTree(TreeType.APPLY_STATEMENT, applyStatement); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.APPLY_STATEMENT, - TreeType.APPLY_STATEMENT_SINGULAR + tree, + TreeType.APPLY_STATEMENT, + TreeType.APPLY_STATEMENT_SINGULAR ); } @@ -1196,13 +1196,13 @@ public void applyStatementSingular() { TokenTree tree = getTree(TreeType.APPLY_STATEMENT_SINGULAR, singular); assertTreeIsValid(tree); rootAndChildTypesEqual( - tree, - TreeType.APPLY_STATEMENT_SINGULAR, - TreeType.TOKEN, - TreeType.SP, - TreeType.SHAPE_ID, - TreeType.WS, - TreeType.TRAIT + tree, + TreeType.APPLY_STATEMENT_SINGULAR, + TreeType.TOKEN, + TreeType.SP, + TreeType.SHAPE_ID, + TreeType.WS, + TreeType.TRAIT ); } @@ -1212,46 +1212,46 @@ public void applyStatementBlock() { TokenTree blockTree = getTree(TreeType.APPLY_STATEMENT_BLOCK, block); assertTreeIsValid(blockTree); rootAndChildTypesEqual( - blockTree, - TreeType.APPLY_STATEMENT_BLOCK, - TreeType.TOKEN, - TreeType.SP, - TreeType.SHAPE_ID, - TreeType.WS, - TreeType.TOKEN, - TreeType.TRAIT_STATEMENTS, - TreeType.TOKEN + blockTree, + TreeType.APPLY_STATEMENT_BLOCK, + TreeType.TOKEN, + TreeType.SP, + TreeType.SHAPE_ID, + TreeType.WS, + TreeType.TOKEN, + TreeType.TRAIT_STATEMENTS, + TreeType.TOKEN ); String withLeadingWsInBlock = "apply foo\n{// Bar\n@foo\n}"; TokenTree withLeadingWsInBlockTree = getTree(TreeType.APPLY_STATEMENT_BLOCK, withLeadingWsInBlock); assertTreeIsValid(withLeadingWsInBlockTree); rootAndChildTypesEqual( - withLeadingWsInBlockTree, - TreeType.APPLY_STATEMENT_BLOCK, - TreeType.TOKEN, - TreeType.SP, - TreeType.SHAPE_ID, - TreeType.WS, - TreeType.TOKEN, - TreeType.WS, - TreeType.TRAIT_STATEMENTS, - TreeType.TOKEN + withLeadingWsInBlockTree, + TreeType.APPLY_STATEMENT_BLOCK, + TreeType.TOKEN, + TreeType.SP, + TreeType.SHAPE_ID, + TreeType.WS, + TreeType.TOKEN, + TreeType.WS, + TreeType.TRAIT_STATEMENTS, + TreeType.TOKEN ); String minimalWs = "apply foo {@bar}"; TokenTree minimalWsTree = getTree(TreeType.APPLY_STATEMENT_BLOCK, minimalWs); assertTreeIsValid(minimalWsTree); rootAndChildTypesEqual( - minimalWsTree, - TreeType.APPLY_STATEMENT_BLOCK, - TreeType.TOKEN, - TreeType.SP, - TreeType.SHAPE_ID, - TreeType.WS, - TreeType.TOKEN, - TreeType.TRAIT_STATEMENTS, - TreeType.TOKEN + minimalWsTree, + TreeType.APPLY_STATEMENT_BLOCK, + TreeType.TOKEN, + TreeType.SP, + TreeType.SHAPE_ID, + TreeType.WS, + TreeType.TOKEN, + TreeType.TRAIT_STATEMENTS, + TreeType.TOKEN ); } @@ -1261,81 +1261,81 @@ public void nodeValue() { TokenTree arrayTree = getTree(TreeType.NODE_VALUE, array); assertTreeIsValid(arrayTree); rootAndChildTypesEqual( - arrayTree, - TreeType.NODE_VALUE, - TreeType.NODE_ARRAY + arrayTree, + TreeType.NODE_VALUE, + TreeType.NODE_ARRAY ); String object = "{}"; TokenTree objectTree = getTree(TreeType.NODE_VALUE, object); assertTreeIsValid(objectTree); rootAndChildTypesEqual( - objectTree, - TreeType.NODE_VALUE, - TreeType.NODE_OBJECT + objectTree, + TreeType.NODE_VALUE, + TreeType.NODE_OBJECT ); String number = "1"; TokenTree numberTree = getTree(TreeType.NODE_VALUE, number); assertTreeIsValid(numberTree); rootAndChildTypesEqual( - numberTree, - TreeType.NODE_VALUE, - TreeType.NUMBER + numberTree, + TreeType.NODE_VALUE, + TreeType.NUMBER ); String trueKeyword = "true"; TokenTree trueTree = getTree(TreeType.NODE_VALUE, trueKeyword); assertTreeIsValid(trueTree); rootAndChildTypesEqual( - trueTree, - TreeType.NODE_VALUE, - TreeType.NODE_KEYWORD + trueTree, + TreeType.NODE_VALUE, + TreeType.NODE_KEYWORD ); String falseKeyword = "false"; TokenTree falseTree = getTree(TreeType.NODE_VALUE, falseKeyword); assertTreeIsValid(falseTree); rootAndChildTypesEqual( - falseTree, - TreeType.NODE_VALUE, - TreeType.NODE_KEYWORD + falseTree, + TreeType.NODE_VALUE, + TreeType.NODE_KEYWORD ); String nullKeyword = "null"; TokenTree nullTree = getTree(TreeType.NODE_VALUE, nullKeyword); assertTreeIsValid(nullTree); rootAndChildTypesEqual( - nullTree, - TreeType.NODE_VALUE, - TreeType.NODE_KEYWORD + nullTree, + TreeType.NODE_VALUE, + TreeType.NODE_KEYWORD ); String shapeId = "foo"; TokenTree shapeIdTree = getTree(TreeType.NODE_VALUE, shapeId); assertTreeIsValid(shapeIdTree); rootAndChildTypesEqual( - shapeIdTree, - TreeType.NODE_VALUE, - TreeType.NODE_STRING_VALUE + shapeIdTree, + TreeType.NODE_VALUE, + TreeType.NODE_STRING_VALUE ); String quotedText = "\"foo\""; TokenTree quotedTextTree = getTree(TreeType.NODE_VALUE, quotedText); assertTreeIsValid(quotedTextTree); rootAndChildTypesEqual( - quotedTextTree, - TreeType.NODE_VALUE, - TreeType.NODE_STRING_VALUE + quotedTextTree, + TreeType.NODE_VALUE, + TreeType.NODE_STRING_VALUE ); String textBlock = "\"\"\"\nfoo\"\"\""; TokenTree textBlockTree = getTree(TreeType.NODE_VALUE, textBlock); assertTreeIsValid(textBlockTree); rootAndChildTypesEqual( - textBlockTree, - TreeType.NODE_VALUE, - TreeType.NODE_STRING_VALUE + textBlockTree, + TreeType.NODE_VALUE, + TreeType.NODE_STRING_VALUE ); } @@ -1345,51 +1345,51 @@ public void nodeArray() { TokenTree emptyTree = getTree(TreeType.NODE_ARRAY, empty); assertTreeIsValid(emptyTree); rootAndChildTypesEqual( - emptyTree, - TreeType.NODE_ARRAY, - TreeType.TOKEN, - TreeType.TOKEN + emptyTree, + TreeType.NODE_ARRAY, + TreeType.TOKEN, + TreeType.TOKEN ); String emptyWs = "[\n\n\t//Foo\n]"; TokenTree emptyWsTree = getTree(TreeType.NODE_ARRAY, emptyWs); assertTreeIsValid(emptyWsTree); rootAndChildTypesEqual( - emptyWsTree, - TreeType.NODE_ARRAY, - TreeType.TOKEN, - TreeType.WS, - TreeType.TOKEN + emptyWsTree, + TreeType.NODE_ARRAY, + TreeType.TOKEN, + TreeType.WS, + TreeType.TOKEN ); String withElements = "[ foo\n bar, baz // foo\n\tqux ]"; TokenTree withElementsTree = getTree(TreeType.NODE_ARRAY, withElements); assertTreeIsValid(withElementsTree); rootAndChildTypesEqual( - withElementsTree, - TreeType.NODE_ARRAY, - TreeType.TOKEN, - TreeType.WS, - TreeType.NODE_VALUE, - TreeType.WS, - TreeType.NODE_VALUE, - TreeType.WS, - TreeType.NODE_VALUE, - TreeType.WS, - TreeType.NODE_VALUE, - TreeType.WS, - TreeType.TOKEN + withElementsTree, + TreeType.NODE_ARRAY, + TreeType.TOKEN, + TreeType.WS, + TreeType.NODE_VALUE, + TreeType.WS, + TreeType.NODE_VALUE, + TreeType.WS, + TreeType.NODE_VALUE, + TreeType.WS, + TreeType.NODE_VALUE, + TreeType.WS, + TreeType.TOKEN ); String noWs = "[foo]"; TokenTree noWsTree = getTree(TreeType.NODE_ARRAY, noWs); assertTreeIsValid(noWsTree); rootAndChildTypesEqual( - noWsTree, - TreeType.NODE_ARRAY, - TreeType.TOKEN, - TreeType.NODE_VALUE, - TreeType.TOKEN + noWsTree, + TreeType.NODE_ARRAY, + TreeType.TOKEN, + TreeType.NODE_VALUE, + TreeType.TOKEN ); } @@ -1399,47 +1399,47 @@ public void nodeObject() { TokenTree emptyTree = getTree(TreeType.NODE_OBJECT, empty); assertTreeIsValid(emptyTree); rootAndChildTypesEqual( - emptyTree, - TreeType.NODE_OBJECT, - TreeType.TOKEN, - TreeType.TOKEN + emptyTree, + TreeType.NODE_OBJECT, + TreeType.TOKEN, + TreeType.TOKEN ); String emptyWs = "{// Foo\n\n\t}"; TokenTree emptyWsTree = getTree(TreeType.NODE_OBJECT, emptyWs); assertTreeIsValid(emptyWsTree); rootAndChildTypesEqual( - emptyWsTree, - TreeType.NODE_OBJECT, - TreeType.TOKEN, - TreeType.WS, - TreeType.TOKEN + emptyWsTree, + TreeType.NODE_OBJECT, + TreeType.TOKEN, + TreeType.WS, + TreeType.TOKEN ); String withElements = "{ foo: bar\n// Foo\n\tbaz: qux\n}"; TokenTree withElementsTree = getTree(TreeType.NODE_OBJECT, withElements); assertTreeIsValid(withElementsTree); rootAndChildTypesEqual( - withElementsTree, - TreeType.NODE_OBJECT, - TreeType.TOKEN, - TreeType.WS, - TreeType.NODE_OBJECT_KVP, - TreeType.WS, - TreeType.NODE_OBJECT_KVP, - TreeType.WS, - TreeType.TOKEN + withElementsTree, + TreeType.NODE_OBJECT, + TreeType.TOKEN, + TreeType.WS, + TreeType.NODE_OBJECT_KVP, + TreeType.WS, + TreeType.NODE_OBJECT_KVP, + TreeType.WS, + TreeType.TOKEN ); String noWs = "{foo:bar}"; TokenTree noWsTree = getTree(TreeType.NODE_OBJECT, noWs); assertTreeIsValid(noWsTree); rootAndChildTypesEqual( - noWsTree, - TreeType.NODE_OBJECT, - TreeType.TOKEN, - TreeType.NODE_OBJECT_KVP, - TreeType.TOKEN + noWsTree, + TreeType.NODE_OBJECT, + TreeType.TOKEN, + TreeType.NODE_OBJECT_KVP, + TreeType.TOKEN ); } @@ -1449,24 +1449,24 @@ public void nodeObjectKvp() { TokenTree kvpTree = getTree(TreeType.NODE_OBJECT_KVP, kvp); assertTreeIsValid(kvpTree); rootAndChildTypesEqual( - kvpTree, - TreeType.NODE_OBJECT_KVP, - TreeType.NODE_OBJECT_KEY, - TreeType.WS, - TreeType.TOKEN, - TreeType.WS, - TreeType.NODE_VALUE + kvpTree, + TreeType.NODE_OBJECT_KVP, + TreeType.NODE_OBJECT_KEY, + TreeType.WS, + TreeType.TOKEN, + TreeType.WS, + TreeType.NODE_VALUE ); String noWs = "foo:bar"; TokenTree noWsTree = getTree(TreeType.NODE_OBJECT_KVP, noWs); assertTreeIsValid(noWsTree); rootAndChildTypesEqual( - noWsTree, - TreeType.NODE_OBJECT_KVP, - TreeType.NODE_OBJECT_KEY, - TreeType.TOKEN, - TreeType.NODE_VALUE + noWsTree, + TreeType.NODE_OBJECT_KVP, + TreeType.NODE_OBJECT_KEY, + TreeType.TOKEN, + TreeType.NODE_VALUE ); } @@ -2054,15 +2054,15 @@ public void invalidComment() { } private static void rootAndChildTypesEqual( - TokenTree actualTree, - TreeType expectedRoot, - TreeType... expectedChildren + TokenTree actualTree, + TreeType expectedRoot, + TreeType... expectedChildren ) { assertEquals(expectedRoot, actualTree.getType()); String actual = actualTree.getChildren() - .stream() - .map(t -> t.getType().toString()) - .collect(Collectors.joining(",")); + .stream() + .map(t -> t.getType().toString()) + .collect(Collectors.joining(",")); String expected = Arrays.stream(expectedChildren).map(Object::toString).collect(Collectors.joining(",")); assertEquals(expected, actual); } diff --git a/smithy-trait-codegen/src/it/java/software/amazon/smithy/traitcodegen/test/CreatesTraitTest.java b/smithy-trait-codegen/src/it/java/software/amazon/smithy/traitcodegen/test/CreatesTraitTest.java index 246816f310d..3b092818f2b 100644 --- a/smithy-trait-codegen/src/it/java/software/amazon/smithy/traitcodegen/test/CreatesTraitTest.java +++ b/smithy-trait-codegen/src/it/java/software/amazon/smithy/traitcodegen/test/CreatesTraitTest.java @@ -66,160 +66,160 @@ public class CreatesTraitTest { static Stream createTraitTests() { return Stream.of( - // Document traits - Arguments.of( - DocumentTrait.ID, - Node.objectNodeBuilder() - .withMember("metadata", "woo") - .withMember("more", "yay") - .build() - ), - Arguments.of( - StructWithNestedDocumentTrait.ID, - ObjectNode.objectNodeBuilder() - .withMember( - "doc", + // Document traits + Arguments.of( + DocumentTrait.ID, + Node.objectNodeBuilder() + .withMember("metadata", "woo") + .withMember("more", "yay") + .build() + ), + Arguments.of( + StructWithNestedDocumentTrait.ID, + ObjectNode.objectNodeBuilder() + .withMember( + "doc", + ObjectNode.builder() + .withMember("foo", "bar") + .withMember("fizz", "buzz") + .build() + ) + .build() + ), + // Enums + Arguments.of(StringEnumTrait.ID, Node.from("no")), + Arguments.of(IntEnumTrait.ID, Node.from(2)), + Arguments.of(SuitTrait.ID, Node.from("clubs")), + Arguments.of( + EnumListMemberTrait.ID, + ObjectNode.objectNodeBuilder() + .withMember("value", ArrayNode.fromStrings("some", "none", "some")) + .build() + ), + // Lists + Arguments.of( + NumberListTrait.ID, + ArrayNode.fromNodes( + Node.from(1), + Node.from(2), + Node.from(3) + ) + ), + Arguments.of(StringListTrait.ID, ArrayNode.fromStrings("a", "b", "c")), + Arguments.of( + StructureListTrait.ID, + ArrayNode.fromNodes( + ListMember.builder().a("first").b(1).c("other").build().toNode(), + ListMember.builder().a("second").b(2).c("more").build().toNode() + ) + ), + Arguments.of( + DocumentListTrait.ID, + ArrayNode.fromNodes( + ObjectNode.builder().withMember("a", "b").build(), + ObjectNode.builder().withMember("c", "d").withMember("e", "f").build() + ) + ), + // Maps + Arguments.of( + StringStringMapTrait.ID, + StringStringMapTrait.builder() + .putValues("a", "first") + .putValues("b", "other") + .build() + .toNode() + ), + Arguments.of( + StringToStructMapTrait.ID, + StringToStructMapTrait.builder() + .putValues("one", MapValue.builder().a("foo").b(2).build()) + .putValues("two", MapValue.builder().a("bar").b(4).build()) + .build() + .toNode() + ), + Arguments.of( + StringDocumentMapTrait.ID, + StringDocumentMapTrait.builder() + .putValues("a", ObjectNode.builder().withMember("a", "a").build().toNode()) + .putValues("b", ObjectNode.builder().withMember("b", "b").build().toNode()) + .putValues("string", Node.from("stuff")) + .putValues("number", Node.from(1)) + .build() + .toNode() + ), + // Mixins + Arguments.of( + StructureListWithMixinMemberTrait.ID, + ArrayNode.fromNodes(ObjectNode.builder().withMember("a", "a").withMember("d", "d").build()) + ), + Arguments.of( + StructWithMixinTrait.ID, + StructWithMixinTrait.builder() + .d("d") + .build() + .toNode() + ), + // Naming Conflicts + Arguments.of( + SnakeCaseStructureTrait.ID, ObjectNode.builder() - .withMember("foo", "bar") - .withMember("fizz", "buzz") - .build() - ) - .build() - ), - // Enums - Arguments.of(StringEnumTrait.ID, Node.from("no")), - Arguments.of(IntEnumTrait.ID, Node.from(2)), - Arguments.of(SuitTrait.ID, Node.from("clubs")), - Arguments.of( - EnumListMemberTrait.ID, - ObjectNode.objectNodeBuilder() - .withMember("value", ArrayNode.fromStrings("some", "none", "some")) - .build() - ), - // Lists - Arguments.of( - NumberListTrait.ID, - ArrayNode.fromNodes( - Node.from(1), - Node.from(2), - Node.from(3) - ) - ), - Arguments.of(StringListTrait.ID, ArrayNode.fromStrings("a", "b", "c")), - Arguments.of( - StructureListTrait.ID, - ArrayNode.fromNodes( - ListMember.builder().a("first").b(1).c("other").build().toNode(), - ListMember.builder().a("second").b(2).c("more").build().toNode() - ) - ), - Arguments.of( - DocumentListTrait.ID, - ArrayNode.fromNodes( - ObjectNode.builder().withMember("a", "b").build(), - ObjectNode.builder().withMember("c", "d").withMember("e", "f").build() - ) - ), - // Maps - Arguments.of( - StringStringMapTrait.ID, - StringStringMapTrait.builder() - .putValues("a", "first") - .putValues("b", "other") - .build() - .toNode() - ), - Arguments.of( - StringToStructMapTrait.ID, - StringToStructMapTrait.builder() - .putValues("one", MapValue.builder().a("foo").b(2).build()) - .putValues("two", MapValue.builder().a("bar").b(4).build()) - .build() - .toNode() - ), - Arguments.of( - StringDocumentMapTrait.ID, - StringDocumentMapTrait.builder() - .putValues("a", ObjectNode.builder().withMember("a", "a").build().toNode()) - .putValues("b", ObjectNode.builder().withMember("b", "b").build().toNode()) - .putValues("string", Node.from("stuff")) - .putValues("number", Node.from(1)) - .build() - .toNode() - ), - // Mixins - Arguments.of( - StructureListWithMixinMemberTrait.ID, - ArrayNode.fromNodes(ObjectNode.builder().withMember("a", "a").withMember("d", "d").build()) - ), - Arguments.of( - StructWithMixinTrait.ID, - StructWithMixinTrait.builder() - .d("d") - .build() - .toNode() - ), - // Naming Conflicts - Arguments.of( - SnakeCaseStructureTrait.ID, - ObjectNode.builder() - .withMember("snake_case_member", "stuff") - .build() - ), - // Numbers - Arguments.of(BigDecimalTrait.ID, Node.from(1)), - Arguments.of(BigIntegerTrait.ID, Node.from(1)), - Arguments.of(ByteTrait.ID, Node.from(1)), - Arguments.of(DoubleTrait.ID, Node.from(1.2)), - Arguments.of(FloatTrait.ID, Node.from(1.2)), - Arguments.of(IntegerTrait.ID, Node.from(1)), - Arguments.of(LongTrait.ID, Node.from(1L)), - Arguments.of(ShortTrait.ID, Node.from(1)), - // Structures - Arguments.of(BasicAnnotationTrait.ID, Node.objectNode()), - Arguments.of( - StructureTrait.ID, - StructureTrait.builder() - .fieldA("a") - .fieldB(true) - .fieldC( - NestedA.builder() - .fieldN("nested") - .fieldQ(false) - .fieldZ(NestedB.B) - .build() - ) - .fieldD(ListUtils.of("a", "b", "c")) - .fieldE(MapUtils.of("a", "one", "b", "two")) - .build() - .toNode() - ), - // Timestamps - Arguments.of(TimestampTrait.ID, Node.from("1985-04-12T23:20:50.52Z")), - Arguments.of(DateTimeTimestampTrait.ID, Node.from("1985-04-12T23:20:50.52Z")), - Arguments.of(HttpDateTimestampTrait.ID, Node.from("Tue, 29 Apr 2014 18:30:38 GMT")), - Arguments.of(EpochSecondsTimestampTrait.ID, Node.from(1515531081.123)), - // Unique Items (sets) - Arguments.of( - NumberSetTrait.ID, - ArrayNode.fromNodes( - Node.from(1), - Node.from(2), - Node.from(3) - ) - ), - Arguments.of(StringSetTrait.ID, ArrayNode.fromStrings("a", "b", "c")), - Arguments.of( - StructureSetTrait.ID, - ArrayNode.fromNodes( - SetMember.builder().a("first").b(1).c("other").build().toNode(), - SetMember.builder().a("second").b(2).c("more").build().toNode() - ) - ), - // Strings - Arguments.of(StringTrait.ID, Node.from("SPORKZ SPOONS YAY! Utensils.")), - // Defaults - Arguments.of(StructDefaultsTrait.ID, Node.objectNode()) + .withMember("snake_case_member", "stuff") + .build() + ), + // Numbers + Arguments.of(BigDecimalTrait.ID, Node.from(1)), + Arguments.of(BigIntegerTrait.ID, Node.from(1)), + Arguments.of(ByteTrait.ID, Node.from(1)), + Arguments.of(DoubleTrait.ID, Node.from(1.2)), + Arguments.of(FloatTrait.ID, Node.from(1.2)), + Arguments.of(IntegerTrait.ID, Node.from(1)), + Arguments.of(LongTrait.ID, Node.from(1L)), + Arguments.of(ShortTrait.ID, Node.from(1)), + // Structures + Arguments.of(BasicAnnotationTrait.ID, Node.objectNode()), + Arguments.of( + StructureTrait.ID, + StructureTrait.builder() + .fieldA("a") + .fieldB(true) + .fieldC( + NestedA.builder() + .fieldN("nested") + .fieldQ(false) + .fieldZ(NestedB.B) + .build() + ) + .fieldD(ListUtils.of("a", "b", "c")) + .fieldE(MapUtils.of("a", "one", "b", "two")) + .build() + .toNode() + ), + // Timestamps + Arguments.of(TimestampTrait.ID, Node.from("1985-04-12T23:20:50.52Z")), + Arguments.of(DateTimeTimestampTrait.ID, Node.from("1985-04-12T23:20:50.52Z")), + Arguments.of(HttpDateTimestampTrait.ID, Node.from("Tue, 29 Apr 2014 18:30:38 GMT")), + Arguments.of(EpochSecondsTimestampTrait.ID, Node.from(1515531081.123)), + // Unique Items (sets) + Arguments.of( + NumberSetTrait.ID, + ArrayNode.fromNodes( + Node.from(1), + Node.from(2), + Node.from(3) + ) + ), + Arguments.of(StringSetTrait.ID, ArrayNode.fromStrings("a", "b", "c")), + Arguments.of( + StructureSetTrait.ID, + ArrayNode.fromNodes( + SetMember.builder().a("first").b(1).c("other").build().toNode(), + SetMember.builder().a("second").b(2).c("more").build().toNode() + ) + ), + // Strings + Arguments.of(StringTrait.ID, Node.from("SPORKZ SPOONS YAY! Utensils.")), + // Defaults + Arguments.of(StructDefaultsTrait.ID, Node.objectNode()) ); } diff --git a/smithy-trait-codegen/src/it/java/software/amazon/smithy/traitcodegen/test/LoadsFromModelTest.java b/smithy-trait-codegen/src/it/java/software/amazon/smithy/traitcodegen/test/LoadsFromModelTest.java index 2558a4e9354..073f8390a7c 100644 --- a/smithy-trait-codegen/src/it/java/software/amazon/smithy/traitcodegen/test/LoadsFromModelTest.java +++ b/smithy-trait-codegen/src/it/java/software/amazon/smithy/traitcodegen/test/LoadsFromModelTest.java @@ -85,456 +85,458 @@ public class LoadsFromModelTest { static Stream loadsModelTests() { return Stream.of( - // Document types - Arguments.of( - "documents/document-trait.smithy", - DocumentTrait.class, - MapUtils.of( - "getValue", - Node.objectNodeBuilder() - .withMember("metadata", "woo") - .withMember("more", "yay") - .build() - ) - ), - Arguments.of( - "documents/struct-with-nested-document.smithy", - StructWithNestedDocumentTrait.class, - MapUtils.of( - "getDoc", - Optional.of( - ObjectNode.builder() - .withMember("foo", "bar") - .withMember("fizz", "buzz") - .build() - ) - ) - ), - // Enums - Arguments.of( - "enums/enum-trait.smithy", - StringEnumTrait.class, - MapUtils.of("getValue", "yes", "getEnumValue", StringEnumTrait.StringEnum.YES) - ), - Arguments.of( - "enums/int-enum-trait.smithy", - IntEnumTrait.class, - MapUtils.of("getValue", 1, "getEnumValue", IntEnumTrait.IntEnum.YES) - ), - Arguments.of( - "enums/string-enum-compatibility.smithy", - SuitTrait.class, - MapUtils.of("getEnumValue", SuitTrait.Suit.CLUB, "getValue", "club") - ), - Arguments.of( - "enums/enum-list-member-trait.smithy", - EnumListMemberTrait.class, - MapUtils.of("getValue", Optional.of(ListUtils.of(SomeEnum.SOME, SomeEnum.NONE, SomeEnum.SOME))) - ), - // Id Refs - Arguments.of( - "idref/idref-string.smithy", - IdRefStringTrait.class, - MapUtils.of("getValue", TARGET_ONE) - ), - Arguments.of( - "idref/idref-list.smithy", - IdRefListTrait.class, - MapUtils.of("getValues", ListUtils.of(TARGET_ONE, TARGET_TWO)) - ), - Arguments.of( - "idref/idref-map.smithy", - IdRefMapTrait.class, - MapUtils.of("getValues", MapUtils.of("a", TARGET_ONE, "b", TARGET_TWO)) - ), - Arguments.of( - "idref/idref-struct.smithy", - IdRefStructTrait.class, - MapUtils.of("getFieldA", Optional.of(TARGET_ONE)) - ), - Arguments.of( - "idref/idref-struct-with-nested-refs.smithy", - IdRefStructWithNestedIdsTrait.class, - MapUtils.of( - "getIdRefHolder", - NestedIdRefHolder.builder().id(TARGET_ONE).build(), - "getIdList", - Optional.of(ListUtils.of(TARGET_ONE, TARGET_TWO)), - "getIdMap", - Optional.of(MapUtils.of("a", TARGET_ONE, "b", TARGET_TWO)) - ) - ), - // Lists - Arguments.of( - "lists/number-list-trait.smithy", - NumberListTrait.class, - MapUtils.of("getValues", ListUtils.of(1, 2, 3, 4, 5)) - ), - Arguments.of( - "lists/string-list-trait.smithy", - StringListTrait.class, - MapUtils.of("getValues", ListUtils.of("a", "b", "c", "d")) - ), - Arguments.of( - "lists/struct-list-trait.smithy", - StructureListTrait.class, - MapUtils.of( - "getValues", - ListUtils.of( - ListMember.builder().a("first").b(1).c("other").build(), - ListMember.builder().a("second").b(2).c("more").build() - ) - ) - ), - Arguments.of( - "lists/document-list-trait.smithy", - DocumentListTrait.class, - MapUtils.of( - "getValues", - ListUtils.of( - ObjectNode.builder().withMember("a", "a").build().toNode(), - ObjectNode.builder().withMember("b", "b").withMember("c", 1).build().toNode(), - Node.from("string") - ) - ) - ), - // Maps - Arguments.of( - "maps/string-string-map-trait.smithy", - StringStringMapTrait.class, - MapUtils.of( - "getValues", - MapUtils.of( - "a", - "stuff", - "b", - "other", - "c", - "more!" - ) - ) - ), - Arguments.of( - "maps/string-to-struct-map-trait.smithy", - StringToStructMapTrait.class, - MapUtils.of( - "getValues", - MapUtils.of( - "one", - MapValue.builder().a("foo").b(2).build(), - "two", - MapValue.builder().a("bar").b(4).build() - ) - ) - ), - Arguments.of( - "maps/string-to-document-map-trait.smithy", - StringDocumentMapTrait.class, - MapUtils.of( - "getValues", - MapUtils.of( - "a", - ObjectNode.builder().withMember("a", "a").build().toNode(), - "b", - ObjectNode.builder().withMember("b", "b").withMember("c", 1).build().toNode(), - "c", - Node.from("stuff"), - "d", - Node.from(1) - ) - ) - ), - // Mixins - Arguments.of( - "mixins/struct-with-mixin-member.smithy", - StructureListWithMixinMemberTrait.class, - MapUtils.of( - "getValues", - ListUtils.of( - ListMemberWithMixin.builder() - .a("first") - .b(1) - .c("other") - .d("mixed-in") - .build(), - ListMemberWithMixin.builder() - .a("second") - .b(2) - .c("more") - .d("mixins are cool") - .build() - ) - ) - ), - Arguments.of( - "mixins/struct-with-only-mixin-member.smithy", - StructWithMixinTrait.class, - MapUtils.of("getD", "mixed-in") - ), - // Naming conflicts - Arguments.of( - "names/snake-case-struct.smithy", - SnakeCaseStructureTrait.class, - MapUtils.of("getSnakeCaseMember", Optional.of("stuff")) - ), - // Numbers - Arguments.of( - "numbers/big-decimal-trait.smithy", - BigDecimalTrait.class, - MapUtils.of("getValue", new BigDecimal("100.01")) - ), - Arguments.of( - "numbers/big-integer-trait.smithy", - BigIntegerTrait.class, - MapUtils.of("getValue", new BigInteger("100")) - ), - Arguments.of( - "numbers/byte-trait.smithy", - ByteTrait.class, - MapUtils.of("getValue", (byte) 1) - ), - Arguments.of( - "numbers/double-trait.smithy", - DoubleTrait.class, - MapUtils.of("getValue", 100.01) - ), - Arguments.of( - "numbers/float-trait.smithy", - FloatTrait.class, - MapUtils.of("getValue", 1.1F) - ), - Arguments.of( - "numbers/integer-trait.smithy", - IntegerTrait.class, - MapUtils.of("getValue", 1) - ), - Arguments.of( - "numbers/long-trait.smithy", - LongTrait.class, - MapUtils.of("getValue", 1L) - ), - Arguments.of( - "numbers/short-trait.smithy", - ShortTrait.class, - MapUtils.of("getValue", (short) 1) - ), - // Structures - Arguments.of( - "structures/annotation-trait.smithy", - BasicAnnotationTrait.class, - Collections.emptyMap() - ), - Arguments.of( - "structures/struct-trait.smithy", - StructureTrait.class, - MapUtils.of( - "getFieldA", - "first", - "getFieldB", - Optional.of(false), - "getFieldC", - Optional.of( - NestedA.builder() - .fieldN("nested") - .fieldQ(true) - .fieldZ(NestedB.A) - .build() - ), - "getFieldD", - Optional.of(ListUtils.of("a", "b", "c")), - "getFieldDOrEmpty", - ListUtils.of("a", "b", "c"), - "getFieldE", - Optional.of(MapUtils.of("a", "one", "b", "two")), - "getFieldEOrEmpty", - MapUtils.of("a", "one", "b", "two"), - "getFieldF", - Optional.of(new BigDecimal("100.01")), - "getFieldG", - Optional.of(new BigInteger("100")) - ) - ), - Arguments.of( - "structures/struct-with-non-existent-collections.smithy", - StructureTrait.class, - MapUtils.of( - "getFieldA", - "first", - "getFieldB", - Optional.of(false), - "getFieldC", - Optional.of( - NestedA.builder() - .fieldN("nested") - .fieldQ(true) - .fieldZ(NestedB.A) - .build() - ), - "getFieldD", - Optional.empty() - ), - "getFieldDOrEmpty", - null, - "getFieldE", - Optional.empty(), - "getFieldEOrEmpty", - null - ), - // Timestamps - Arguments.of( - "timestamps/struct-with-nested-timestamps.smithy", - StructWithNestedTimestampsTrait.class, - MapUtils.of( - "getBaseTime", - Instant.parse("1985-04-12T23:20:50.52Z"), - "getDateTime", - Instant.parse("1985-04-12T23:20:50.52Z"), - "getHttpDate", - Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse("Tue, 29 Apr 2014 18:30:38 GMT")), - "getEpochSeconds", - Instant.ofEpochSecond((long) 1515531081.123) - ) - ), - Arguments.of( - "timestamps/timestamp-trait-date-time.smithy", - TimestampTrait.class, - MapUtils.of("getValue", Instant.parse("1985-04-12T23:20:50.52Z")) - ), - Arguments.of( - "timestamps/timestamp-trait-epoch-sec.smithy", - TimestampTrait.class, - MapUtils.of("getValue", Instant.ofEpochSecond((long) 1515531081.123)) - ), - Arguments.of( - "timestamps/date-time-format-timestamp-trait.smithy", - DateTimeTimestampTrait.class, - MapUtils.of("getValue", Instant.parse("1985-04-12T23:20:50.52Z")) - ), - Arguments.of( - "timestamps/http-date-format-timestamp-trait.smithy", - HttpDateTimestampTrait.class, - MapUtils.of( - "getValue", - Instant.from( - DateTimeFormatter.RFC_1123_DATE_TIME - .parse("Tue, 29 Apr 2014 18:30:38 GMT") - ) - ) - ), - Arguments.of( - "timestamps/epoch-seconds-format-timestamp-trait.smithy", - EpochSecondsTimestampTrait.class, - MapUtils.of("getValue", Instant.ofEpochSecond((long) 1515531081.123)) - ), - // Uniques items (sets) - Arguments.of( - "uniqueitems/number-set-trait.smithy", - NumberSetTrait.class, - MapUtils.of("getValues", SetUtils.of(1, 2, 3, 4)) - ), - Arguments.of( - "uniqueitems/string-set-trait.smithy", - StringSetTrait.class, - MapUtils.of("getValues", SetUtils.of("a", "b", "c", "d")) - ), - Arguments.of( - "uniqueitems/struct-set-trait.smithy", - StructureSetTrait.class, - MapUtils.of( - "getValues", - ListUtils.of( - SetMember.builder().a("first").b(1).c("other").build(), - SetMember.builder().a("second").b(2).c("more").build() - ) + // Document types + Arguments.of( + "documents/document-trait.smithy", + DocumentTrait.class, + MapUtils.of( + "getValue", + Node.objectNodeBuilder() + .withMember("metadata", "woo") + .withMember("more", "yay") + .build() + ) + ), + Arguments.of( + "documents/struct-with-nested-document.smithy", + StructWithNestedDocumentTrait.class, + MapUtils.of( + "getDoc", + Optional.of( + ObjectNode.builder() + .withMember("foo", "bar") + .withMember("fizz", "buzz") + .build() + ) + ) + ), + // Enums + Arguments.of( + "enums/enum-trait.smithy", + StringEnumTrait.class, + MapUtils.of("getValue", "yes", "getEnumValue", StringEnumTrait.StringEnum.YES) + ), + Arguments.of( + "enums/int-enum-trait.smithy", + IntEnumTrait.class, + MapUtils.of("getValue", 1, "getEnumValue", IntEnumTrait.IntEnum.YES) + ), + Arguments.of( + "enums/string-enum-compatibility.smithy", + SuitTrait.class, + MapUtils.of("getEnumValue", SuitTrait.Suit.CLUB, "getValue", "club") + ), + Arguments.of( + "enums/enum-list-member-trait.smithy", + EnumListMemberTrait.class, + MapUtils.of("getValue", Optional.of(ListUtils.of(SomeEnum.SOME, SomeEnum.NONE, SomeEnum.SOME))) + ), + // Id Refs + Arguments.of( + "idref/idref-string.smithy", + IdRefStringTrait.class, + MapUtils.of("getValue", TARGET_ONE) + ), + Arguments.of( + "idref/idref-list.smithy", + IdRefListTrait.class, + MapUtils.of("getValues", ListUtils.of(TARGET_ONE, TARGET_TWO)) + ), + Arguments.of( + "idref/idref-map.smithy", + IdRefMapTrait.class, + MapUtils.of("getValues", MapUtils.of("a", TARGET_ONE, "b", TARGET_TWO)) + ), + Arguments.of( + "idref/idref-struct.smithy", + IdRefStructTrait.class, + MapUtils.of("getFieldA", Optional.of(TARGET_ONE)) + ), + Arguments.of( + "idref/idref-struct-with-nested-refs.smithy", + IdRefStructWithNestedIdsTrait.class, + MapUtils.of( + "getIdRefHolder", + NestedIdRefHolder.builder().id(TARGET_ONE).build(), + "getIdList", + Optional.of(ListUtils.of(TARGET_ONE, TARGET_TWO)), + "getIdMap", + Optional.of(MapUtils.of("a", TARGET_ONE, "b", TARGET_TWO)) + ) + ), + // Lists + Arguments.of( + "lists/number-list-trait.smithy", + NumberListTrait.class, + MapUtils.of("getValues", ListUtils.of(1, 2, 3, 4, 5)) + ), + Arguments.of( + "lists/string-list-trait.smithy", + StringListTrait.class, + MapUtils.of("getValues", ListUtils.of("a", "b", "c", "d")) + ), + Arguments.of( + "lists/struct-list-trait.smithy", + StructureListTrait.class, + MapUtils.of( + "getValues", + ListUtils.of( + ListMember.builder().a("first").b(1).c("other").build(), + ListMember.builder().a("second").b(2).c("more").build() + ) + ) + ), + Arguments.of( + "lists/document-list-trait.smithy", + DocumentListTrait.class, + MapUtils.of( + "getValues", + ListUtils.of( + ObjectNode.builder().withMember("a", "a").build().toNode(), + ObjectNode.builder().withMember("b", "b").withMember("c", 1).build().toNode(), + Node.from("string") + ) + ) + ), + // Maps + Arguments.of( + "maps/string-string-map-trait.smithy", + StringStringMapTrait.class, + MapUtils.of( + "getValues", + MapUtils.of( + "a", + "stuff", + "b", + "other", + "c", + "more!" + ) + ) + ), + Arguments.of( + "maps/string-to-struct-map-trait.smithy", + StringToStructMapTrait.class, + MapUtils.of( + "getValues", + MapUtils.of( + "one", + MapValue.builder().a("foo").b(2).build(), + "two", + MapValue.builder().a("bar").b(4).build() + ) + ) + ), + Arguments.of( + "maps/string-to-document-map-trait.smithy", + StringDocumentMapTrait.class, + MapUtils.of( + "getValues", + MapUtils.of( + "a", + ObjectNode.builder().withMember("a", "a").build().toNode(), + "b", + ObjectNode.builder().withMember("b", "b").withMember("c", 1).build().toNode(), + "c", + Node.from("stuff"), + "d", + Node.from(1) + ) + ) + ), + // Mixins + Arguments.of( + "mixins/struct-with-mixin-member.smithy", + StructureListWithMixinMemberTrait.class, + MapUtils.of( + "getValues", + ListUtils.of( + ListMemberWithMixin.builder() + .a("first") + .b(1) + .c("other") + .d("mixed-in") + .build(), + ListMemberWithMixin.builder() + .a("second") + .b(2) + .c("more") + .d("mixins are cool") + .build() + ) + ) + ), + Arguments.of( + "mixins/struct-with-only-mixin-member.smithy", + StructWithMixinTrait.class, + MapUtils.of("getD", "mixed-in") + ), + // Naming conflicts + Arguments.of( + "names/snake-case-struct.smithy", + SnakeCaseStructureTrait.class, + MapUtils.of("getSnakeCaseMember", Optional.of("stuff")) + ), + // Numbers + Arguments.of( + "numbers/big-decimal-trait.smithy", + BigDecimalTrait.class, + MapUtils.of("getValue", new BigDecimal("100.01")) + ), + Arguments.of( + "numbers/big-integer-trait.smithy", + BigIntegerTrait.class, + MapUtils.of("getValue", new BigInteger("100")) + ), + Arguments.of( + "numbers/byte-trait.smithy", + ByteTrait.class, + MapUtils.of("getValue", (byte) 1) + ), + Arguments.of( + "numbers/double-trait.smithy", + DoubleTrait.class, + MapUtils.of("getValue", 100.01) + ), + Arguments.of( + "numbers/float-trait.smithy", + FloatTrait.class, + MapUtils.of("getValue", 1.1F) + ), + Arguments.of( + "numbers/integer-trait.smithy", + IntegerTrait.class, + MapUtils.of("getValue", 1) + ), + Arguments.of( + "numbers/long-trait.smithy", + LongTrait.class, + MapUtils.of("getValue", 1L) + ), + Arguments.of( + "numbers/short-trait.smithy", + ShortTrait.class, + MapUtils.of("getValue", (short) 1) + ), + // Structures + Arguments.of( + "structures/annotation-trait.smithy", + BasicAnnotationTrait.class, + Collections.emptyMap() + ), + Arguments.of( + "structures/struct-trait.smithy", + StructureTrait.class, + MapUtils.of( + "getFieldA", + "first", + "getFieldB", + Optional.of(false), + "getFieldC", + Optional.of( + NestedA.builder() + .fieldN("nested") + .fieldQ(true) + .fieldZ(NestedB.A) + .build() + ), + "getFieldD", + Optional.of(ListUtils.of("a", "b", "c")), + "getFieldDOrEmpty", + ListUtils.of("a", "b", "c"), + "getFieldE", + Optional.of(MapUtils.of("a", "one", "b", "two")), + "getFieldEOrEmpty", + MapUtils.of("a", "one", "b", "two"), + "getFieldF", + Optional.of(new BigDecimal("100.01")), + "getFieldG", + Optional.of(new BigInteger("100")) + ) + ), + Arguments.of( + "structures/struct-with-non-existent-collections.smithy", + StructureTrait.class, + MapUtils.of( + "getFieldA", + "first", + "getFieldB", + Optional.of(false), + "getFieldC", + Optional.of( + NestedA.builder() + .fieldN("nested") + .fieldQ(true) + .fieldZ(NestedB.A) + .build() + ), + "getFieldD", + Optional.empty() + ), + "getFieldDOrEmpty", + null, + "getFieldE", + Optional.empty(), + "getFieldEOrEmpty", + null + ), + // Timestamps + Arguments.of( + "timestamps/struct-with-nested-timestamps.smithy", + StructWithNestedTimestampsTrait.class, + MapUtils.of( + "getBaseTime", + Instant.parse("1985-04-12T23:20:50.52Z"), + "getDateTime", + Instant.parse("1985-04-12T23:20:50.52Z"), + "getHttpDate", + Instant.from( + DateTimeFormatter.RFC_1123_DATE_TIME.parse("Tue, 29 Apr 2014 18:30:38 GMT") + ), + "getEpochSeconds", + Instant.ofEpochSecond((long) 1515531081.123) + ) + ), + Arguments.of( + "timestamps/timestamp-trait-date-time.smithy", + TimestampTrait.class, + MapUtils.of("getValue", Instant.parse("1985-04-12T23:20:50.52Z")) + ), + Arguments.of( + "timestamps/timestamp-trait-epoch-sec.smithy", + TimestampTrait.class, + MapUtils.of("getValue", Instant.ofEpochSecond((long) 1515531081.123)) + ), + Arguments.of( + "timestamps/date-time-format-timestamp-trait.smithy", + DateTimeTimestampTrait.class, + MapUtils.of("getValue", Instant.parse("1985-04-12T23:20:50.52Z")) + ), + Arguments.of( + "timestamps/http-date-format-timestamp-trait.smithy", + HttpDateTimestampTrait.class, + MapUtils.of( + "getValue", + Instant.from( + DateTimeFormatter.RFC_1123_DATE_TIME + .parse("Tue, 29 Apr 2014 18:30:38 GMT") + ) + ) + ), + Arguments.of( + "timestamps/epoch-seconds-format-timestamp-trait.smithy", + EpochSecondsTimestampTrait.class, + MapUtils.of("getValue", Instant.ofEpochSecond((long) 1515531081.123)) + ), + // Uniques items (sets) + Arguments.of( + "uniqueitems/number-set-trait.smithy", + NumberSetTrait.class, + MapUtils.of("getValues", SetUtils.of(1, 2, 3, 4)) + ), + Arguments.of( + "uniqueitems/string-set-trait.smithy", + StringSetTrait.class, + MapUtils.of("getValues", SetUtils.of("a", "b", "c", "d")) + ), + Arguments.of( + "uniqueitems/struct-set-trait.smithy", + StructureSetTrait.class, + MapUtils.of( + "getValues", + ListUtils.of( + SetMember.builder().a("first").b(1).c("other").build(), + SetMember.builder().a("second").b(2).c("more").build() + ) + ) + ), + // Strings + Arguments.of( + "string-trait.smithy", + StringTrait.class, + MapUtils.of("getValue", "Testing String Trait") + ), + // Defaults + Arguments.of( + "defaults/defaults.smithy", + StructDefaultsTrait.class, + MapUtils.of("getDefaultList", ListUtils.of()) + ), + Arguments.of( + "defaults/defaults.smithy", + StructDefaultsTrait.class, + MapUtils.of("getDefaultMap", MapUtils.of()) + ), + Arguments.of( + "defaults/defaults.smithy", + StructDefaultsTrait.class, + MapUtils.of("getDefaultBoolean", true) + ), + Arguments.of( + "defaults/defaults.smithy", + StructDefaultsTrait.class, + MapUtils.of("getDefaultString", "default") + ), + Arguments.of( + "defaults/defaults.smithy", + StructDefaultsTrait.class, + MapUtils.of("getDefaultByte", (byte) 1) + ), + Arguments.of( + "defaults/defaults.smithy", + StructDefaultsTrait.class, + MapUtils.of("getDefaultShort", (short) 1) + ), + Arguments.of( + "defaults/defaults.smithy", + StructDefaultsTrait.class, + MapUtils.of("getDefaultInt", 1) + ), + Arguments.of( + "defaults/defaults.smithy", + StructDefaultsTrait.class, + MapUtils.of("getDefaultLong", 1L) + ), + Arguments.of( + "defaults/defaults.smithy", + StructDefaultsTrait.class, + MapUtils.of("getDefaultFloat", 2.2F) + ), + Arguments.of( + "defaults/defaults.smithy", + StructDefaultsTrait.class, + MapUtils.of("getDefaultDouble", 1.1) + ), + Arguments.of( + "defaults/defaults.smithy", + StructDefaultsTrait.class, + MapUtils.of("getDefaultBigInt", new BigInteger("100")) + ), + Arguments.of( + "defaults/defaults.smithy", + StructDefaultsTrait.class, + MapUtils.of("getDefaultBigDecimal", new BigDecimal("100.01")) + ), + Arguments.of( + "defaults/defaults.smithy", + StructDefaultsTrait.class, + MapUtils.of("getDefaultTimestamp", Instant.parse("1985-04-12T23:20:50.52Z")) ) - ), - // Strings - Arguments.of( - "string-trait.smithy", - StringTrait.class, - MapUtils.of("getValue", "Testing String Trait") - ), - // Defaults - Arguments.of( - "defaults/defaults.smithy", - StructDefaultsTrait.class, - MapUtils.of("getDefaultList", ListUtils.of()) - ), - Arguments.of( - "defaults/defaults.smithy", - StructDefaultsTrait.class, - MapUtils.of("getDefaultMap", MapUtils.of()) - ), - Arguments.of( - "defaults/defaults.smithy", - StructDefaultsTrait.class, - MapUtils.of("getDefaultBoolean", true) - ), - Arguments.of( - "defaults/defaults.smithy", - StructDefaultsTrait.class, - MapUtils.of("getDefaultString", "default") - ), - Arguments.of( - "defaults/defaults.smithy", - StructDefaultsTrait.class, - MapUtils.of("getDefaultByte", (byte) 1) - ), - Arguments.of( - "defaults/defaults.smithy", - StructDefaultsTrait.class, - MapUtils.of("getDefaultShort", (short) 1) - ), - Arguments.of( - "defaults/defaults.smithy", - StructDefaultsTrait.class, - MapUtils.of("getDefaultInt", 1) - ), - Arguments.of( - "defaults/defaults.smithy", - StructDefaultsTrait.class, - MapUtils.of("getDefaultLong", 1L) - ), - Arguments.of( - "defaults/defaults.smithy", - StructDefaultsTrait.class, - MapUtils.of("getDefaultFloat", 2.2F) - ), - Arguments.of( - "defaults/defaults.smithy", - StructDefaultsTrait.class, - MapUtils.of("getDefaultDouble", 1.1) - ), - Arguments.of( - "defaults/defaults.smithy", - StructDefaultsTrait.class, - MapUtils.of("getDefaultBigInt", new BigInteger("100")) - ), - Arguments.of( - "defaults/defaults.smithy", - StructDefaultsTrait.class, - MapUtils.of("getDefaultBigDecimal", new BigDecimal("100.01")) - ), - Arguments.of( - "defaults/defaults.smithy", - StructDefaultsTrait.class, - MapUtils.of("getDefaultTimestamp", Instant.parse("1985-04-12T23:20:50.52Z")) - ) ); } @ParameterizedTest @MethodSource("loadsModelTests") void executeTests( - String resourceFile, - Class traitClass, - Map valueChecks + String resourceFile, + Class traitClass, + Map valueChecks ) { Model result = Model.assembler() - .discoverModels(getClass().getClassLoader()) - .addImport(Objects.requireNonNull(getClass().getResource(resourceFile))) - .assemble() - .unwrap(); + .discoverModels(getClass().getClassLoader()) + .addImport(Objects.requireNonNull(getClass().getResource(resourceFile))) + .assemble() + .unwrap(); T trait = result.expectShape(ID).expectTrait(traitClass); valueChecks.forEach((k, v) -> checkValue(traitClass, trait, k, v)); } @@ -545,19 +547,19 @@ void checkValue(Class traitClass, T trait, String accessor, // Float values need a delta specified for equals checks if (value instanceof Float) { assertEquals( - (Float) expected, - (Float) value, - 0.0001, - "Value of accessor `" + accessor + "` invalid for " + trait + (Float) expected, + (Float) value, + 0.0001, + "Value of accessor `" + accessor + "` invalid for " + trait ); } else if (value instanceof Iterable) { assertIterableEquals((Iterable) expected, (Iterable) value); } else { assertEquals( - expected, - value, - "Value of accessor `" + accessor - + "` invalid for " + trait + expected, + value, + "Value of accessor `" + accessor + + "` invalid for " + trait ); } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegen.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegen.java index 8054c1a5c51..a5200da6ca3 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegen.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegen.java @@ -61,10 +61,10 @@ final class TraitCodegen { private TraitCodegenContext codegenContext; private TraitCodegen( - Model model, - TraitCodegenSettings settings, - FileManifest fileManifest, - PluginContext pluginContext + Model model, + TraitCodegenSettings settings, + FileManifest fileManifest, + PluginContext pluginContext ) { this.model = Objects.requireNonNull(model); this.settings = Objects.requireNonNull(settings); @@ -79,10 +79,10 @@ private TraitCodegen( public static TraitCodegen fromPluginContext(PluginContext context) { return new TraitCodegen( - context.getModel(), - TraitCodegenSettings.fromNode(context.getSettings()), - context.getFileManifest(), - context + context.getModel(), + TraitCodegenSettings.fromNode(context.getSettings()), + context.getFileManifest(), + context ); } @@ -157,17 +157,17 @@ private Set getTraitClosure(Model model) { // for traits we have already manually defined a provider for. Set existingProviders = new HashSet<>(); ServiceLoader.load(TraitService.class, TraitCodegen.class.getClassLoader()) - .forEach(service -> existingProviders.add(service.getShapeId())); + .forEach(service -> existingProviders.add(service.getShapeId())); // Get all trait shapes within the specified namespace, but filter out // any trait shapes for which a provider is already defined or which have // excluded tags Set traitClosure = traitSelector.select(model) - .stream() - .filter(pluginContext::isSourceShape) - .filter(shape -> !existingProviders.contains(shape.getId())) - .filter(shape -> !this.hasExcludeTag(shape)) - .collect(Collectors.toSet()); + .stream() + .filter(pluginContext::isSourceShape) + .filter(shape -> !existingProviders.contains(shape.getId())) + .filter(shape -> !this.hasExcludeTag(shape)) + .collect(Collectors.toSet()); if (traitClosure.isEmpty()) { LOGGER.warning("Could not find any trait definitions to generate."); @@ -181,22 +181,22 @@ private Set getTraitClosure(Model model) { Walker walker = new Walker(model); for (Shape traitShape : traitClosure) { nested.addAll( - walker.walkShapes(traitShape) - .stream() - .filter(shape -> !shape.isMemberShape()) - .filter(shape -> !Prelude.isPreludeShape(shape)) - .collect(Collectors.toSet()) + walker.walkShapes(traitShape) + .stream() + .filter(shape -> !shape.isMemberShape()) + .filter(shape -> !Prelude.isPreludeShape(shape)) + .collect(Collectors.toSet()) ); } // If any nested shapes are not in the specified namespace, throw an error. Set invalidNested = nested.stream() - .filter(shape -> !shape.getId().getNamespace().startsWith(settings.smithyNamespace())) - .collect(Collectors.toSet()); + .filter(shape -> !shape.getId().getNamespace().startsWith(settings.smithyNamespace())) + .collect(Collectors.toSet()); if (!invalidNested.isEmpty()) { throw new RuntimeException( - "Shapes: " + invalidNested + " are within the trait closure but are not within " - + "the specified namespace `" + settings.smithyNamespace() + "`." + "Shapes: " + invalidNested + " are within the trait closure but are not within " + + "the specified namespace `" + settings.smithyNamespace() + "`." ); } traitClosure.addAll(nested); diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenContext.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenContext.java index e7982c5a2f1..ab81ff7b194 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenContext.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenContext.java @@ -19,7 +19,7 @@ */ @SmithyUnstableApi public final class TraitCodegenContext implements - CodegenContext { + CodegenContext { private final Model model; private final TraitCodegenSettings settings; private final SymbolProvider symbolProvider; @@ -28,11 +28,11 @@ public final class TraitCodegenContext implements private final WriterDelegator writerDelegator; TraitCodegenContext( - Model model, - TraitCodegenSettings settings, - SymbolProvider symbolProvider, - FileManifest fileManifest, - List integrations + Model model, + TraitCodegenSettings settings, + SymbolProvider symbolProvider, + FileManifest fileManifest, + List integrations ) { this.model = model; this.settings = settings; @@ -40,9 +40,9 @@ public final class TraitCodegenContext implements this.fileManifest = fileManifest; this.integrations = integrations; this.writerDelegator = new WriterDelegator<>( - fileManifest, - symbolProvider, - new TraitCodegenWriter.Factory(settings) + fileManifest, + symbolProvider, + new TraitCodegenWriter.Factory(settings) ); } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenSettings.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenSettings.java index 1f2d460e4a2..e1b616c56fd 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenSettings.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenSettings.java @@ -49,10 +49,10 @@ public final class TraitCodegenSettings { * ignored when generating java classes. */ TraitCodegenSettings( - String packageName, - String smithyNamespace, - List headerLines, - List excludeTags + String packageName, + String smithyNamespace, + List headerLines, + List excludeTags ) { this.packageName = Objects.requireNonNull(packageName); if (packageName.startsWith(SMITHY_MODEL_NAMESPACE)) { @@ -74,13 +74,13 @@ public final class TraitCodegenSettings { */ public static TraitCodegenSettings fromNode(ObjectNode node) { return new TraitCodegenSettings( - node.expectStringMember("package").getValue(), - node.expectStringMember("namespace").getValue(), - node.expectArrayMember("header") - .getElementsAs(el -> el.expectStringNode().getValue()), - node.getArrayMember("excludeTags") - .map(n -> n.getElementsAs(el -> el.expectStringNode().getValue())) - .orElse(Collections.emptyList()) + node.expectStringMember("package").getValue(), + node.expectStringMember("namespace").getValue(), + node.expectArrayMember("header") + .getElementsAs(el -> el.expectStringNode().getValue()), + node.getArrayMember("excludeTags") + .map(n -> n.getElementsAs(el -> el.expectStringNode().getValue())) + .orElse(Collections.emptyList()) ); } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenSymbolProvider.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenSymbolProvider.java index 18319287ecc..662c9f55808 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenSymbolProvider.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenSymbolProvider.java @@ -68,25 +68,25 @@ public Symbol booleanShape(BooleanShape shape) { @Override public Symbol byteShape(ByteShape shape) { return TraitCodegenUtils.fromClass(Byte.class) - .toBuilder() - .putProperty(SymbolProperties.UNBOXED_SYMBOL, TraitCodegenUtils.fromClass(byte.class)) - .build(); + .toBuilder() + .putProperty(SymbolProperties.UNBOXED_SYMBOL, TraitCodegenUtils.fromClass(byte.class)) + .build(); } @Override public Symbol shortShape(ShortShape shape) { return TraitCodegenUtils.fromClass(Short.class) - .toBuilder() - .putProperty(SymbolProperties.UNBOXED_SYMBOL, TraitCodegenUtils.fromClass(short.class)) - .build(); + .toBuilder() + .putProperty(SymbolProperties.UNBOXED_SYMBOL, TraitCodegenUtils.fromClass(short.class)) + .build(); } @Override public Symbol integerShape(IntegerShape shape) { return TraitCodegenUtils.fromClass(Integer.class) - .toBuilder() - .putProperty(SymbolProperties.UNBOXED_SYMBOL, TraitCodegenUtils.fromClass(int.class)) - .build(); + .toBuilder() + .putProperty(SymbolProperties.UNBOXED_SYMBOL, TraitCodegenUtils.fromClass(int.class)) + .build(); } @Override @@ -97,25 +97,25 @@ public Symbol intEnumShape(IntEnumShape shape) { @Override public Symbol longShape(LongShape shape) { return TraitCodegenUtils.fromClass(Long.class) - .toBuilder() - .putProperty(SymbolProperties.UNBOXED_SYMBOL, TraitCodegenUtils.fromClass(long.class)) - .build(); + .toBuilder() + .putProperty(SymbolProperties.UNBOXED_SYMBOL, TraitCodegenUtils.fromClass(long.class)) + .build(); } @Override public Symbol floatShape(FloatShape shape) { return TraitCodegenUtils.fromClass(Float.class) - .toBuilder() - .putProperty(SymbolProperties.UNBOXED_SYMBOL, TraitCodegenUtils.fromClass(float.class)) - .build(); + .toBuilder() + .putProperty(SymbolProperties.UNBOXED_SYMBOL, TraitCodegenUtils.fromClass(float.class)) + .build(); } @Override public Symbol doubleShape(DoubleShape shape) { return TraitCodegenUtils.fromClass(Double.class) - .toBuilder() - .putProperty(SymbolProperties.UNBOXED_SYMBOL, TraitCodegenUtils.fromClass(double.class)) - .build(); + .toBuilder() + .putProperty(SymbolProperties.UNBOXED_SYMBOL, TraitCodegenUtils.fromClass(double.class)) + .build(); } @Override @@ -132,26 +132,26 @@ public Symbol bigDecimalShape(BigDecimalShape shape) { public Symbol listShape(ListShape shape) { if (shape.hasTrait(UniqueItemsTrait.class)) { return TraitCodegenUtils.fromClass(Set.class) + .toBuilder() + .addReference(toSymbol(shape.getMember())) + .putProperty(SymbolProperties.BUILDER_REF_INITIALIZER, "forOrderedSet()") + .build(); + } + return TraitCodegenUtils.fromClass(List.class) .toBuilder() .addReference(toSymbol(shape.getMember())) - .putProperty(SymbolProperties.BUILDER_REF_INITIALIZER, "forOrderedSet()") + .putProperty(SymbolProperties.BUILDER_REF_INITIALIZER, "forList()") .build(); - } - return TraitCodegenUtils.fromClass(List.class) - .toBuilder() - .addReference(toSymbol(shape.getMember())) - .putProperty(SymbolProperties.BUILDER_REF_INITIALIZER, "forList()") - .build(); } @Override public Symbol mapShape(MapShape shape) { return TraitCodegenUtils.fromClass(Map.class) - .toBuilder() - .addReference(shape.getKey().accept(this)) - .addReference(shape.getValue().accept(this)) - .putProperty(SymbolProperties.BUILDER_REF_INITIALIZER, "forOrderedMap()") - .build(); + .toBuilder() + .addReference(shape.getKey().accept(this)) + .addReference(shape.getValue().accept(this)) + .putProperty(SymbolProperties.BUILDER_REF_INITIALIZER, "forOrderedMap()") + .build(); } @Override @@ -203,7 +203,7 @@ public String toMemberName(MemberShape member) { // Enum shapes should have upper snake case members } else if (containerShape.isEnumShape() || containerShape.isIntEnumShape()) { return CaseUtils.toSnakeCase(TraitCodegenUtils.MEMBER_ESCAPER.escape(member.getMemberName())) - .toUpperCase(Locale.ROOT); + .toUpperCase(Locale.ROOT); } if (member.getMemberName().contains("_")) { @@ -216,14 +216,14 @@ public String toMemberName(MemberShape member) { private Symbol getJavaClassSymbol(Shape shape) { String name = TraitCodegenUtils.getDefaultName(shape); String namespace = TraitCodegenUtils.mapNamespace( - smithyNamespace, - shape.getId().getNamespace(), - packageNamespace + smithyNamespace, + shape.getId().getNamespace(), + packageNamespace ); return Symbol.builder() - .name(name) - .namespace(namespace, ".") - .declarationFile("./" + namespace.replace(".", "/") + "/" + name + ".java") - .build(); + .name(name) + .namespace(namespace, ".") + .declarationFile("./" + namespace.replace(".", "/") + "/" + name + ".java") + .build(); } } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenUtils.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenUtils.java index 475cb544745..1814003b3d0 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenUtils.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/TraitCodegenUtils.java @@ -24,11 +24,11 @@ public final class TraitCodegenUtils { public static final Symbol JAVA_STRING_SYMBOL = TraitCodegenUtils.fromClass(String.class); public static final URL RESERVED_WORDS_FILE = TraitCodegenUtils.class.getResource("reserved-words.txt"); public static final ReservedWords SHAPE_ESCAPER = new ReservedWordsBuilder() - .loadCaseInsensitiveWords(RESERVED_WORDS_FILE, word -> word + "Shape") - .build(); + .loadCaseInsensitiveWords(RESERVED_WORDS_FILE, word -> word + "Shape") + .build(); public static final ReservedWords MEMBER_ESCAPER = new ReservedWordsBuilder() - .loadCaseInsensitiveWords(RESERVED_WORDS_FILE, word -> word + "Member") - .build(); + .loadCaseInsensitiveWords(RESERVED_WORDS_FILE, word -> word + "Member") + .build(); private TraitCodegenUtils() {} @@ -40,8 +40,8 @@ private TraitCodegenUtils() {} */ public static Symbol fromClass(Class clazz) { Symbol.Builder builder = Symbol.builder() - .name(clazz.getSimpleName()) - .namespace(clazz.getCanonicalName().replace("." + clazz.getSimpleName(), ""), "."); + .name(clazz.getSimpleName()) + .namespace(clazz.getCanonicalName().replace("." + clazz.getSimpleName(), ""), "."); if (clazz.isPrimitive()) { builder.putProperty(SymbolProperties.IS_PRIMITIVE, true); @@ -100,7 +100,7 @@ public static String getDefaultTraitName(Shape shape) { public static boolean isJavaString(Symbol symbol) { Symbol baseSymbol = symbol.getProperty(SymbolProperties.BASE_SYMBOL).orElse(symbol); return JAVA_STRING_SYMBOL.getName().equals(baseSymbol.getName()) - && JAVA_STRING_SYMBOL.getNamespace().equals(baseSymbol.getNamespace()); + && JAVA_STRING_SYMBOL.getNamespace().equals(baseSymbol.getNamespace()); } /** @@ -112,12 +112,12 @@ public static boolean isJavaString(Symbol symbol) { */ public static boolean isJavaStringList(Shape shape, SymbolProvider symbolProvider) { return shape.isListShape() - && !shape.hasTrait(UniqueItemsTrait.class) - && TraitCodegenUtils.isJavaString( - symbolProvider.toSymbol( - shape.asListShape().get().getMember() - ) - ); + && !shape.hasTrait(UniqueItemsTrait.class) + && TraitCodegenUtils.isJavaString( + symbolProvider.toSymbol( + shape.asListShape().get().getMember() + ) + ); } /** @@ -128,14 +128,14 @@ public static boolean isJavaStringList(Shape shape, SymbolProvider symbolProvide * @param packageNamespace Java package namespace for trait codegen. */ public static String mapNamespace( - String rootSmithyNamespace, - String shapeNamespace, - String packageNamespace + String rootSmithyNamespace, + String shapeNamespace, + String packageNamespace ) { if (!shapeNamespace.startsWith(rootSmithyNamespace)) { throw new IllegalArgumentException( - "Cannot relativize non-nested namespaces " - + "Root: " + rootSmithyNamespace + " Nested: " + shapeNamespace + "." + "Cannot relativize non-nested namespaces " + + "Root: " + rootSmithyNamespace + " Nested: " + shapeNamespace + "." ); } return shapeNamespace.replace(rootSmithyNamespace, packageNamespace); diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/BuilderGenerator.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/BuilderGenerator.java index f5b7e0659d5..880ac4e35fc 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/BuilderGenerator.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/BuilderGenerator.java @@ -61,11 +61,11 @@ final class BuilderGenerator implements Runnable { private final Model model; BuilderGenerator( - TraitCodegenWriter writer, - Symbol symbol, - SymbolProvider symbolProvider, - Shape baseShape, - Model model + TraitCodegenWriter writer, + Symbol symbol, + SymbolProvider symbolProvider, + Shape baseShape, + Model model ) { this.writer = writer; this.symbol = symbol; @@ -94,10 +94,10 @@ private void writeBuilderClass() { baseShape.accept(new BuilderSetterGenerator()); writer.override(); writer.openBlock( - "public $T build() {", - "}", - symbol, - () -> writer.write("return new $C;", (Runnable) this::writeBuilderReturn) + "public $T build() {", + "}", + symbol, + () -> writer.write("return new $C;", (Runnable) this::writeBuilderReturn) ); writer.dedent().write("}"); writer.newLine(); @@ -127,47 +127,47 @@ private void writeBuilderReturn() { private void writeToBuilderMethod() { writer.writeDocString(writer.format("Creates a builder used to build a {@link $T}.", symbol)); writer.openBlock( - "public $T<$T> toBuilder() {", - "}", - SmithyBuilder.class, - symbol, - () -> { - writer.writeInlineWithNoFormatting("return builder()"); - writer.indent(); - if (baseShape.hasTrait(TraitDefinition.class)) { - writer.writeInlineWithNoFormatting(".sourceLocation(getSourceLocation())"); - } - if (baseShape.members().isEmpty()) { - writer.writeInlineWithNoFormatting(";"); - } - writer.newLine(); - - // Set all builder properties for any members in the shape - if (baseShape.isListShape()) { - writer.writeWithNoFormatting(".values(getValues());"); - } else { - Iterator memberIterator = baseShape.members().iterator(); - while (memberIterator.hasNext()) { - MemberShape member = memberIterator.next(); - writer.writeInline(".$1L($1L)", symbolProvider.toMemberName(member)); - if (memberIterator.hasNext()) { - writer.writeInlineWithNoFormatting("\n"); - } else { - writer.writeInlineWithNoFormatting(";\n"); + "public $T<$T> toBuilder() {", + "}", + SmithyBuilder.class, + symbol, + () -> { + writer.writeInlineWithNoFormatting("return builder()"); + writer.indent(); + if (baseShape.hasTrait(TraitDefinition.class)) { + writer.writeInlineWithNoFormatting(".sourceLocation(getSourceLocation())"); + } + if (baseShape.members().isEmpty()) { + writer.writeInlineWithNoFormatting(";"); + } + writer.newLine(); + + // Set all builder properties for any members in the shape + if (baseShape.isListShape()) { + writer.writeWithNoFormatting(".values(getValues());"); + } else { + Iterator memberIterator = baseShape.members().iterator(); + while (memberIterator.hasNext()) { + MemberShape member = memberIterator.next(); + writer.writeInline(".$1L($1L)", symbolProvider.toMemberName(member)); + if (memberIterator.hasNext()) { + writer.writeInlineWithNoFormatting("\n"); + } else { + writer.writeInlineWithNoFormatting(";\n"); + } } } + writer.dedent(); } - writer.dedent(); - } ); writer.newLine(); } private void writeBuilderMethod() { writer.openBlock( - "public static Builder builder() {", - "}", - () -> writer.write("return new Builder();") + "public static Builder builder() {", + "}", + () -> writer.write("return new Builder();") ).newLine(); } @@ -202,30 +202,30 @@ public Void structureShape(StructureShape shape) { private void writeProperty(MemberShape shape) { Optional builderRefOptional = symbolProvider.toSymbol(shape) - .getProperty(SymbolProperties.BUILDER_REF_INITIALIZER); + .getProperty(SymbolProperties.BUILDER_REF_INITIALIZER); if (builderRefOptional.isPresent()) { writer.write( - "private final $1T<$2B> $3L = $1T.$4L;", - BuilderRef.class, - symbolProvider.toSymbol(shape), - symbolProvider.toMemberName(shape), - builderRefOptional.orElseThrow(RuntimeException::new) + "private final $1T<$2B> $3L = $1T.$4L;", + BuilderRef.class, + symbolProvider.toSymbol(shape), + symbolProvider.toMemberName(shape), + builderRefOptional.orElseThrow(RuntimeException::new) ); return; } if (shape.hasNonNullDefault()) { writer.write( - "private $B $L = $C;", - symbolProvider.toSymbol(shape), - symbolProvider.toMemberName(shape), - new DefaultInitializerGenerator(writer, model, symbolProvider, shape) + "private $B $L = $C;", + symbolProvider.toSymbol(shape), + symbolProvider.toMemberName(shape), + new DefaultInitializerGenerator(writer, model, symbolProvider, shape) ); } else { writer.write( - "private $B $L;", - symbolProvider.toSymbol(shape), - symbolProvider.toMemberName(shape) + "private $B $L;", + symbolProvider.toSymbol(shape), + symbolProvider.toMemberName(shape) ); } } @@ -233,11 +233,11 @@ private void writeProperty(MemberShape shape) { private void writeValuesProperty(Shape shape) { Symbol collectionSymbol = symbolProvider.toSymbol(shape); writer.write( - "private final $1T<$2B> $3L = $1T.$4L;", - BuilderRef.class, - collectionSymbol, - "values", - collectionSymbol.expectProperty(SymbolProperties.BUILDER_REF_INITIALIZER) + "private final $1T<$2B> $3L = $1T.$4L;", + BuilderRef.class, + collectionSymbol, + "values", + collectionSymbol.expectProperty(SymbolProperties.BUILDER_REF_INITIALIZER) ); } } @@ -267,9 +267,11 @@ public Void mapShape(MapShape shape) { @Override public Void structureShape(StructureShape shape) { shape.members() - .forEach( - memberShape -> memberShape.accept(new SetterVisitor(symbolProvider.toMemberName(memberShape))) - ); + .forEach( + memberShape -> memberShape.accept( + new SetterVisitor(symbolProvider.toMemberName(memberShape)) + ) + ); return null; } } @@ -284,14 +286,14 @@ private SetterVisitor(String memberName) { @Override protected Void getDefault(Shape shape) { writer.openBlock( - "public Builder $1L($2B $1L) {", - "}", - memberName, - symbolProvider.toSymbol(shape), - () -> { - writer.write("this.$1L = $1L;", memberName); - writer.writeWithNoFormatting("return this;"); - } + "public Builder $1L($2B $1L) {", + "}", + memberName, + symbolProvider.toSymbol(shape), + () -> { + writer.write("this.$1L = $1L;", memberName); + writer.writeWithNoFormatting("return this;"); + } ).newLine(); return null; } @@ -299,15 +301,15 @@ protected Void getDefault(Shape shape) { @Override public Void listShape(ListShape shape) { writer.openBlock( - "public Builder $1L($2B $1L) {", - "}", - memberName, - symbolProvider.toSymbol(shape), - () -> { - writer.write("clear$U();", memberName); - writer.write("this.$1L.get().addAll($1L);", memberName); - writer.writeWithNoFormatting("return this;"); - } + "public Builder $1L($2B $1L) {", + "}", + memberName, + symbolProvider.toSymbol(shape), + () -> { + writer.write("clear$U();", memberName); + writer.write("this.$1L.get().addAll($1L);", memberName); + writer.writeWithNoFormatting("return this;"); + } ).newLine(); // Clear all @@ -318,26 +320,26 @@ public Void listShape(ListShape shape) { // Set one writer.openBlock( - "public Builder add$U($T value) {", - "}", - memberName, - symbolProvider.toSymbol(shape.getMember()), - () -> { - writer.write("this.$L.get().add(value);", memberName); - writer.write("return this;"); - } + "public Builder add$U($T value) {", + "}", + memberName, + symbolProvider.toSymbol(shape.getMember()), + () -> { + writer.write("this.$L.get().add(value);", memberName); + writer.write("return this;"); + } ).newLine(); // Remove one writer.openBlock( - "public Builder remove$U($T value) {", - "}", - memberName, - symbolProvider.toSymbol(shape.getMember()), - () -> { - writer.write("this.$L.get().remove(value);", memberName); - writer.write("return this;"); - } + "public Builder remove$U($T value) {", + "}", + memberName, + symbolProvider.toSymbol(shape.getMember()), + () -> { + writer.write("this.$L.get().remove(value);", memberName); + writer.write("return this;"); + } ).newLine(); return null; } @@ -346,15 +348,15 @@ public Void listShape(ListShape shape) { public Void mapShape(MapShape shape) { // Set all writer.openBlock( - "public Builder $1L($2B $1L) {", - "}", - memberName, - symbolProvider.toSymbol(shape), - () -> { - writer.write("clear$U();", memberName); - writer.write("this.$1L.get().putAll($1L);", memberName); - writer.write("return this;"); - } + "public Builder $1L($2B $1L) {", + "}", + memberName, + symbolProvider.toSymbol(shape), + () -> { + writer.write("clear$U();", memberName); + writer.write("this.$1L.get().putAll($1L);", memberName); + writer.write("return this;"); + } ); writer.newLine(); @@ -368,28 +370,28 @@ public Void mapShape(MapShape shape) { MemberShape keyShape = shape.getKey(); MemberShape valueShape = shape.getValue(); writer.openBlock( - "public Builder put$U($T key, $T value) {", - "}", - memberName, - symbolProvider.toSymbol(keyShape), - symbolProvider.toSymbol(valueShape), - () -> { - writer.write("this.$L.get().put(key, value);", memberName); - writer.write("return this;"); - } + "public Builder put$U($T key, $T value) {", + "}", + memberName, + symbolProvider.toSymbol(keyShape), + symbolProvider.toSymbol(valueShape), + () -> { + writer.write("this.$L.get().put(key, value);", memberName); + writer.write("return this;"); + } ).newLine(); // Remove one writer.openBlock( - "public Builder remove$U($T $L) {", - "}", - memberName, - symbolProvider.toSymbol(keyShape), - memberName, - () -> { - writer.write("this.$1L.get().remove($1L);", memberName); - writer.write("return this;"); - } + "public Builder remove$U($T $L) {", + "}", + memberName, + symbolProvider.toSymbol(keyShape), + memberName, + () -> { + writer.write("this.$1L.get().remove($1L);", memberName); + writer.write("return this;"); + } ).newLine(); return null; } @@ -404,7 +406,7 @@ public Void memberShape(MemberShape shape) { * Adds default values to builder properties. */ private static final class DefaultInitializerGenerator extends ShapeVisitor.DataShapeVisitor implements - Runnable { + Runnable { private final TraitCodegenWriter writer; private final Model model; private final SymbolProvider symbolProvider; @@ -412,10 +414,10 @@ private static final class DefaultInitializerGenerator extends ShapeVisitor.Data private Node defaultValue; DefaultInitializerGenerator( - TraitCodegenWriter writer, - Model model, - SymbolProvider symbolProvider, - MemberShape member + TraitCodegenWriter writer, + Model model, + SymbolProvider symbolProvider, + MemberShape member ) { this.writer = writer; this.model = model; @@ -535,17 +537,17 @@ public Void timestampShape(TimestampShape timestampShape) { switch (member.expectTrait(TimestampFormatTrait.class).getFormat()) { case EPOCH_SECONDS: writer.writeInline( - "$T.ofEpochSecond($LL)", - Instant.class, - defaultValue.expectNumberNode().getValue().longValue() + "$T.ofEpochSecond($LL)", + Instant.class, + defaultValue.expectNumberNode().getValue().longValue() ); return null; case HTTP_DATE: writer.writeInline( - "$T.from($T.RFC_1123_DATE_TIME.parse($S))", - Instant.class, - DateTimeFormatter.class, - defaultValue.expectStringNode().getValue() + "$T.from($T.RFC_1123_DATE_TIME.parse($S))", + Instant.class, + DateTimeFormatter.class, + defaultValue.expectStringNode().getValue() ); return null; default: diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ConstructorGenerator.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ConstructorGenerator.java index e496601db67..6e108f49cd9 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ConstructorGenerator.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ConstructorGenerator.java @@ -49,10 +49,10 @@ final class ConstructorGenerator extends TraitVisitor implements Runnable private final SymbolProvider symbolProvider; ConstructorGenerator( - TraitCodegenWriter writer, - Symbol symbol, - Shape shape, - SymbolProvider symbolProvider + TraitCodegenWriter writer, + Symbol symbol, + Shape shape, + SymbolProvider symbolProvider ) { this.writer = writer; this.symbol = symbol; @@ -68,22 +68,22 @@ public void run() { @Override public Void listShape(ListShape shape) { if (!shape.hasTrait(UniqueItemsTrait.class) - && TraitCodegenUtils.isJavaString(symbolProvider.toSymbol(shape.getMember())) + && TraitCodegenUtils.isJavaString(symbolProvider.toSymbol(shape.getMember())) ) { writer.openBlock( - "public $1T($1B values, $2T sourceLocation) {", - "}", - symbol, - FromSourceLocation.class, - () -> writer.write("super(ID, values, sourceLocation);") + "public $1T($1B values, $2T sourceLocation) {", + "}", + symbol, + FromSourceLocation.class, + () -> writer.write("super(ID, values, sourceLocation);") ); writer.newLine(); writer.openBlock( - "public $1T($1B values) {", - "}", - symbol, - () -> writer.write("super(ID, values, $T.NONE);", SourceLocation.class) + "public $1T($1B values) {", + "}", + symbol, + () -> writer.write("super(ID, values, $T.NONE);", SourceLocation.class) ); writer.newLine(); } else { @@ -104,28 +104,28 @@ public Void intEnumShape(IntEnumShape shape) { Symbol integerSymbol = TraitCodegenUtils.fromClass(Integer.class); // Constructor with no source location writer.openBlock( - "public $T($T value) {", - "}", - symbol, - integerSymbol, - () -> { - writer.write("super(ID, $T.NONE);", SourceLocation.class); - writer.writeWithNoFormatting("this.value = value;"); - } + "public $T($T value) {", + "}", + symbol, + integerSymbol, + () -> { + writer.write("super(ID, $T.NONE);", SourceLocation.class); + writer.writeWithNoFormatting("this.value = value;"); + } ); writer.newLine(); // Constructor with source location writer.openBlock( - "public $T($T value, $T sourceLocation) {", - "}", - symbol, - integerSymbol, - FromSourceLocation.class, - () -> { - writer.writeWithNoFormatting("super(ID, sourceLocation);"); - writer.writeWithNoFormatting("this.value = value;"); - } + "public $T($T value, $T sourceLocation) {", + "}", + symbol, + integerSymbol, + FromSourceLocation.class, + () -> { + writer.writeWithNoFormatting("super(ID, sourceLocation);"); + writer.writeWithNoFormatting("this.value = value;"); + } ); writer.newLine(); return null; @@ -134,11 +134,11 @@ public Void intEnumShape(IntEnumShape shape) { @Override public Void documentShape(DocumentShape shape) { writer.openBlock( - "public $T($T value) {", - "}", - symbol, - Node.class, - () -> writer.writeWithNoFormatting("super(ID, value);") + "public $T($T value) {", + "}", + symbol, + Node.class, + () -> writer.writeWithNoFormatting("super(ID, value);") ); writer.newLine(); return null; @@ -199,14 +199,14 @@ private void writeValueShapeConstructors() { // Constructor with source location writer.openBlock( - "public $1T($1B value, $2T sourceLocation) {", - "}", - symbol, - FromSourceLocation.class, - () -> { - writer.writeWithNoFormatting("super(ID, sourceLocation);"); - writer.writeWithNoFormatting("this.value = value;"); - } + "public $1T($1B value, $2T sourceLocation) {", + "}", + symbol, + FromSourceLocation.class, + () -> { + writer.writeWithNoFormatting("super(ID, sourceLocation);"); + writer.writeWithNoFormatting("this.value = value;"); + } ); writer.newLine(); } @@ -214,21 +214,21 @@ private void writeValueShapeConstructors() { private void writeStringTraitConstructors() { // Without source location writer.openBlock( - "public $T(String value) {", - "}", - symbol, - () -> writer.write("super(ID, value, $T.NONE);", SourceLocation.class) + "public $T(String value) {", + "}", + symbol, + () -> writer.write("super(ID, value, $T.NONE);", SourceLocation.class) ); writer.newLine(); // With source location writer.openBlock( - "public $T($T value, $T sourceLocation) {", - "}", - symbol, - String.class, - FromSourceLocation.class, - () -> writer.writeWithNoFormatting("super(ID, value, sourceLocation);") + "public $T($T value, $T sourceLocation) {", + "}", + symbol, + String.class, + FromSourceLocation.class, + () -> writer.writeWithNoFormatting("super(ID, value, sourceLocation);") ); writer.newLine(); } @@ -312,10 +312,10 @@ public Void structureShape(StructureShape shape) { writer.write("this.$L = $L;", symbolProvider.toMemberName(member), getBuilderValue(member)); } else { writer.write( - "this.$1L = $2T.requiredState($1S, $3L);", - symbolProvider.toMemberName(member), - SmithyBuilder.class, - getBuilderValue(member) + "this.$1L = $2T.requiredState($1S, $3L);", + symbolProvider.toMemberName(member), + SmithyBuilder.class, + getBuilderValue(member) ); } } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/EnumShapeGenerator.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/EnumShapeGenerator.java index 4c279ae2662..5e85957036a 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/EnumShapeGenerator.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/EnumShapeGenerator.java @@ -38,18 +38,18 @@ private EnumShapeGenerator() {} @Override public void accept(GenerateTraitDirective directive) { directive.context() - .writerDelegator() - .useShapeWriter( - directive.shape(), - writer -> writeEnum(directive.shape(), directive.symbolProvider(), writer, directive.model()) - ); + .writerDelegator() + .useShapeWriter( + directive.shape(), + writer -> writeEnum(directive.shape(), directive.symbolProvider(), writer, directive.model()) + ); } public void writeEnum( - Shape enumShape, - SymbolProvider provider, - TraitCodegenWriter writer, - Model model + Shape enumShape, + SymbolProvider provider, + TraitCodegenWriter writer, + Model model ) { writeEnum(enumShape, provider, writer, model, true); } @@ -64,42 +64,42 @@ public void writeEnum( * @param isStandaloneClass flag indicating if enum is a standalone class (i.e. defined in its own class file). */ public void writeEnum( - Shape enumShape, - SymbolProvider provider, - TraitCodegenWriter writer, - Model model, - boolean isStandaloneClass + Shape enumShape, + SymbolProvider provider, + TraitCodegenWriter writer, + Model model, + boolean isStandaloneClass ) { Symbol enumSymbol = provider.toSymbol(enumShape); writer.pushState(new ClassSection(enumShape)) - .putContext("standalone", isStandaloneClass) - .openBlock( - "public enum $B ${?standalone}implements $T ${/standalone}{", - "}", - enumSymbol, - ToNode.class, - () -> { - writeVariants(enumShape, provider, writer); - writer.newLine(); - - writeValueField(writer); - writer.newLine(); - - writeConstructor(enumSymbol, writer); - - writeValueGetter(writer); - writer.newLine(); - - writeFromMethod(enumSymbol, writer); - - // Only generate From and To Node when we are in a standalone class. - if (isStandaloneClass) { - writeToNode(writer); - new FromNodeGenerator(writer, enumSymbol, enumShape, provider, model).run(); - } - } - ) - .popState(); + .putContext("standalone", isStandaloneClass) + .openBlock( + "public enum $B ${?standalone}implements $T ${/standalone}{", + "}", + enumSymbol, + ToNode.class, + () -> { + writeVariants(enumShape, provider, writer); + writer.newLine(); + + writeValueField(writer); + writer.newLine(); + + writeConstructor(enumSymbol, writer); + + writeValueGetter(writer); + writer.newLine(); + + writeFromMethod(enumSymbol, writer); + + // Only generate From and To Node when we are in a standalone class. + if (isStandaloneClass) { + writeToNode(writer); + new FromNodeGenerator(writer, enumSymbol, enumShape, provider, model).run(); + } + } + ) + .popState(); } abstract String getVariantTemplate(); @@ -123,65 +123,65 @@ private void writeValueField(TraitCodegenWriter writer) { private void writeValueGetter(TraitCodegenWriter writer) { writer.openBlock( - "public $T getValue() {", - "}", - getValueType(), - () -> writer.writeWithNoFormatting("return value;") + "public $T getValue() {", + "}", + getValueType(), + () -> writer.writeWithNoFormatting("return value;") ); } private void writeToNode(TraitCodegenWriter writer) { writer.override(); writer.openBlock( - "public $T toNode() {", - "}", - Node.class, - () -> writer.write("return $T.from(value);", Node.class) + "public $T toNode() {", + "}", + Node.class, + () -> writer.write("return $T.from(value);", Node.class) ); writer.newLine(); } private void writeConstructor(Symbol enumSymbol, TraitCodegenWriter writer) { writer.openBlock( - "$B($T value) {", - "}", - enumSymbol, - getValueType(), - () -> writer.write("this.value = value;") + "$B($T value) {", + "}", + enumSymbol, + getValueType(), + () -> writer.write("this.value = value;") ); writer.newLine(); } private void writeFromMethod(Symbol enumSymbol, TraitCodegenWriter writer) { writer.writeDocString( - writer.format( - "Create a {@code $1B} from a value in a model.\n\n" - + "

Any unknown value is returned as {@code UNKNOWN}.\n" - + "@param value Value to create enum from.\n" - + "@return Returns the {@link $1B} enum value.", - enumSymbol - ) + writer.format( + "Create a {@code $1B} from a value in a model.\n\n" + + "

Any unknown value is returned as {@code UNKNOWN}.\n" + + "@param value Value to create enum from.\n" + + "@return Returns the {@link $1B} enum value.", + enumSymbol + ) ); writer.openBlock( - "public static $B from($T value) {", - "}", - enumSymbol, - getValueType(), - () -> { - writer.write("$T.requireNonNull(value, \"Enum value should not be null.\");", Objects.class); - writer.openBlock( - "for ($B val: values()) {", - "}", - enumSymbol, - () -> writer.openBlock( - "if ($T.equals(val.getValue(), value)) {", - "}", - Objects.class, - () -> writer.writeWithNoFormatting("return val;") - ) - ); - writer.writeWithNoFormatting("return UNKNOWN;"); - } + "public static $B from($T value) {", + "}", + enumSymbol, + getValueType(), + () -> { + writer.write("$T.requireNonNull(value, \"Enum value should not be null.\");", Objects.class); + writer.openBlock( + "for ($B val: values()) {", + "}", + enumSymbol, + () -> writer.openBlock( + "if ($T.equals(val.getValue(), value)) {", + "}", + Objects.class, + () -> writer.writeWithNoFormatting("return val;") + ) + ); + writer.writeWithNoFormatting("return UNKNOWN;"); + } ); writer.newLine(); } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/FromNodeGenerator.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/FromNodeGenerator.java index 8136adc8ac0..81386227e0a 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/FromNodeGenerator.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/FromNodeGenerator.java @@ -51,11 +51,11 @@ final class FromNodeGenerator extends TraitVisitor implements Runnable { private final Model model; FromNodeGenerator( - TraitCodegenWriter writer, - Symbol symbol, - Shape shape, - SymbolProvider symbolProvider, - Model model + TraitCodegenWriter writer, + Symbol symbol, + Shape shape, + SymbolProvider symbolProvider, + Model model ) { this.writer = writer; this.symbol = symbol; @@ -77,15 +77,15 @@ public Void listShape(ListShape shape) { writeFromNodeJavaDoc(); writer.openBlock( - "public static $T fromNode($T node) {", - "}", - symbol, - Node.class, - () -> { - writer.writeWithNoFormatting("Builder builder = builder();"); - shape.accept(new FromNodeMapperVisitor(writer, model, "node")); - writer.writeWithNoFormatting("return builder.build();"); - } + "public static $T fromNode($T node) {", + "}", + symbol, + Node.class, + () -> { + writer.writeWithNoFormatting("Builder builder = builder();"); + shape.accept(new FromNodeMapperVisitor(writer, model, "node")); + writer.writeWithNoFormatting("return builder.build();"); + } ); writer.newLine(); @@ -96,15 +96,15 @@ public Void listShape(ListShape shape) { public Void mapShape(MapShape shape) { writeFromNodeJavaDoc(); writer.openBlock( - "public static $T fromNode($T node) {", - "}", - symbol, - Node.class, - () -> { - writer.writeWithNoFormatting("Builder builder = builder();"); - shape.accept(new FromNodeMapperVisitor(writer, model, "node")); - writer.writeWithNoFormatting("return builder.build();"); - } + "public static $T fromNode($T node) {", + "}", + symbol, + Node.class, + () -> { + writer.writeWithNoFormatting("Builder builder = builder();"); + shape.accept(new FromNodeMapperVisitor(writer, model, "node")); + writer.writeWithNoFormatting("return builder.build();"); + } ); writer.newLine(); @@ -188,11 +188,11 @@ public Void structureShape(StructureShape shape) { public Void timestampShape(TimestampShape shape) { writeFromNodeJavaDoc(); writer.openBlock( - "public static $T fromNode($T node) {", - "}", - symbol, - Node.class, - this::writeTimestampDeser + "public static $T fromNode($T node) {", + "}", + symbol, + Node.class, + this::writeTimestampDeser ); writer.newLine(); @@ -205,23 +205,23 @@ private void writeTimestampDeser() { // timestamp should be able to handle both epoch seconds and date time formats. if (shape.hasTrait(TimestampFormatTrait.class)) { writer.write( - "return new $T($C, node.getSourceLocation());", - symbol, - (Runnable) () -> shape.accept(new FromNodeMapperVisitor(writer, model, "node")) + "return new $T($C, node.getSourceLocation());", + symbol, + (Runnable) () -> shape.accept(new FromNodeMapperVisitor(writer, model, "node")) ); } else { writer.openBlock("if (node.isNumberNode()) {", "}", () -> { writer.write( - "return new $T($T.ofEpochSecond(node.expectNumberNode().getValue().longValue()),", - symbol, - Instant.class + "return new $T($T.ofEpochSecond(node.expectNumberNode().getValue().longValue()),", + symbol, + Instant.class ).indent(); writer.writeWithNoFormatting("node.getSourceLocation());").dedent(); }); writer.write( - "return new $T($T.parse(node.expectStringNode().getValue()), node.getSourceLocation());", - symbol, - Instant.class + "return new $T($T.parse(node.expectStringNode().getValue()), node.getSourceLocation());", + symbol, + Instant.class ); } writer.newLine(); @@ -229,14 +229,14 @@ private void writeTimestampDeser() { private void writeFromNodeJavaDoc() { writer.writeDocString( - writer.format( - "Creates a {@link $1T} from a {@link Node}.\n\n" - + "@param node Node to create the $1T from.\n" - + "@return Returns the created $1T.\n" - + "@throws $2T if the given Node is invalid.\n", - symbol, - ExpectationNotMetException.class - ) + writer.format( + "Creates a {@link $1T} from a {@link Node}.\n\n" + + "@param node Node to create the $1T from.\n" + + "@return Returns the created $1T.\n" + + "@throws $2T if the given Node is invalid.\n", + symbol, + ExpectationNotMetException.class + ) ); } @@ -268,10 +268,10 @@ public Void booleanShape(BooleanShape shape) { @Override public Void listShape(ListShape shape) { writer.writeInline( - memberPrefix + "ArrayMember($1S, n -> $3C, builder::$2L)", - fieldName, - memberName, - (Runnable) () -> shape.getMember().accept(new FromNodeMapperVisitor(writer, model, "n")) + memberPrefix + "ArrayMember($1S, n -> $3C, builder::$2L)", + fieldName, + memberName, + (Runnable) () -> shape.getMember().accept(new FromNodeMapperVisitor(writer, model, "n")) ); return null; } @@ -279,9 +279,9 @@ public Void listShape(ListShape shape) { @Override public Void byteShape(ByteShape shape) { writer.writeInline( - memberPrefix + "NumberMember($S, n -> builder.$L(n.byteValue()))", - fieldName, - memberName + memberPrefix + "NumberMember($S, n -> builder.$L(n.byteValue()))", + fieldName, + memberName ); return null; } @@ -289,9 +289,9 @@ public Void byteShape(ByteShape shape) { @Override public Void shortShape(ShortShape shape) { writer.writeInline( - memberPrefix + "NumberMember($S, n -> builder.$L(n.shortValue()))", - fieldName, - memberName + memberPrefix + "NumberMember($S, n -> builder.$L(n.shortValue()))", + fieldName, + memberName ); return null; } @@ -299,9 +299,9 @@ public Void shortShape(ShortShape shape) { @Override public Void integerShape(IntegerShape shape) { writer.writeInline( - memberPrefix + "NumberMember($S, n -> builder.$L(n.intValue()))", - fieldName, - memberName + memberPrefix + "NumberMember($S, n -> builder.$L(n.intValue()))", + fieldName, + memberName ); return null; } @@ -309,9 +309,9 @@ public Void integerShape(IntegerShape shape) { @Override public Void longShape(LongShape shape) { writer.writeInline( - memberPrefix + "NumberMember($S, n -> builder.$L(n.longValue()))", - fieldName, - memberName + memberPrefix + "NumberMember($S, n -> builder.$L(n.longValue()))", + fieldName, + memberName ); return null; } @@ -319,9 +319,9 @@ public Void longShape(LongShape shape) { @Override public Void floatShape(FloatShape shape) { writer.writeInline( - memberPrefix + "NumberMember($S, n -> builder.$L(n.floatValue()))", - fieldName, - memberName + memberPrefix + "NumberMember($S, n -> builder.$L(n.floatValue()))", + fieldName, + memberName ); return null; } @@ -329,10 +329,10 @@ public Void floatShape(FloatShape shape) { @Override public Void documentShape(DocumentShape shape) { writer.writeInline( - memberPrefix + "Member($1S, $3T::expectObjectNode, builder::$2L)", - fieldName, - memberName, - Node.class + memberPrefix + "Member($1S, $3T::expectObjectNode, builder::$2L)", + fieldName, + memberName, + Node.class ); return null; } @@ -340,9 +340,9 @@ public Void documentShape(DocumentShape shape) { @Override public Void doubleShape(DoubleShape shape) { writer.writeInline( - memberPrefix + "NumberMember($S, n -> builder.$L(n.doubleValue()))", - fieldName, - memberName + memberPrefix + "NumberMember($S, n -> builder.$L(n.doubleValue()))", + fieldName, + memberName ); return null; } @@ -350,10 +350,10 @@ public Void doubleShape(DoubleShape shape) { @Override public Void bigIntegerShape(BigIntegerShape shape) { writer.writeInline( - memberPrefix - + "Member($S, n -> n.expectNumberNode().asBigDecimal().get().toBigInteger(), builder::$L)", - fieldName, - memberName + memberPrefix + + "Member($S, n -> n.expectNumberNode().asBigDecimal().get().toBigInteger(), builder::$L)", + fieldName, + memberName ); return null; } @@ -361,10 +361,10 @@ public Void bigIntegerShape(BigIntegerShape shape) { @Override public Void bigDecimalShape(BigDecimalShape shape) { writer.writeInline( - memberPrefix - + "Member($S, n -> n.expectNumberNode().asBigDecimal().get(), builder::$L)", - fieldName, - memberName + memberPrefix + + "Member($S, n -> n.expectNumberNode().asBigDecimal().get(), builder::$L)", + fieldName, + memberName ); return null; } @@ -373,16 +373,16 @@ public Void bigDecimalShape(BigDecimalShape shape) { public Void mapShape(MapShape shape) { writer.disableNewlines(); writer.openBlock( - memberPrefix - + "ObjectMember($S, o -> o.getMembers().forEach((k, v) -> {\n", - "}))", - fieldName, - () -> writer.write( - "builder.put$L($C, $C);\n", - StringUtils.capitalize(memberName), - (Runnable) () -> shape.getKey().accept(new FromNodeMapperVisitor(writer, model, "k")), - (Runnable) () -> shape.getValue().accept(new FromNodeMapperVisitor(writer, model, "v")) - ) + memberPrefix + + "ObjectMember($S, o -> o.getMembers().forEach((k, v) -> {\n", + "}))", + fieldName, + () -> writer.write( + "builder.put$L($C, $C);\n", + StringUtils.capitalize(memberName), + (Runnable) () -> shape.getKey().accept(new FromNodeMapperVisitor(writer, model, "k")), + (Runnable) () -> shape.getValue().accept(new FromNodeMapperVisitor(writer, model, "v")) + ) ); writer.enableNewlines(); return null; @@ -391,10 +391,10 @@ public Void mapShape(MapShape shape) { @Override public Void intEnumShape(IntEnumShape shape) { writer.writeInline( - memberPrefix + "NumberMember($S, n -> builder.$L($T.from(n.intValue())))", - fieldName, - memberName, - symbolProvider.toSymbol(shape) + memberPrefix + "NumberMember($S, n -> builder.$L($T.from(n.intValue())))", + fieldName, + memberName, + symbolProvider.toSymbol(shape) ); return null; } @@ -405,10 +405,10 @@ public Void stringShape(StringShape shape) { writer.writeInline(memberPrefix + "StringMember($S, builder::$L)", fieldName, memberName); } else { writer.writeInline( - memberPrefix + "Member($1S, n -> $3C, builder::$2L)", - fieldName, - memberName, - (Runnable) () -> shape.accept(new FromNodeMapperVisitor(writer, model, "n")) + memberPrefix + "Member($1S, n -> $3C, builder::$2L)", + fieldName, + memberName, + (Runnable) () -> shape.accept(new FromNodeMapperVisitor(writer, model, "n")) ); } return null; @@ -417,10 +417,10 @@ public Void stringShape(StringShape shape) { @Override public Void enumShape(EnumShape shape) { writer.writeInline( - memberPrefix + "StringMember($S, n -> builder.$L($T.from(n)))", - fieldName, - memberName, - symbolProvider.toSymbol(shape) + memberPrefix + "StringMember($S, n -> builder.$L($T.from(n)))", + fieldName, + memberName, + symbolProvider.toSymbol(shape) ); return null; } @@ -428,10 +428,10 @@ public Void enumShape(EnumShape shape) { @Override public Void structureShape(StructureShape shape) { writer.writeInline( - memberPrefix + "Member($1S, n -> $3C, builder::$2L)", - fieldName, - memberName, - (Runnable) () -> shape.accept(new FromNodeMapperVisitor(writer, model, "n")) + memberPrefix + "Member($1S, n -> $3C, builder::$2L)", + fieldName, + memberName, + (Runnable) () -> shape.accept(new FromNodeMapperVisitor(writer, model, "n")) ); return null; } @@ -439,10 +439,10 @@ public Void structureShape(StructureShape shape) { @Override public Void timestampShape(TimestampShape shape) { writer.writeInline( - memberPrefix + "Member($1S, n -> $3C, builder::$2L)", - fieldName, - memberName, - (Runnable) () -> shape.accept(new FromNodeMapperVisitor(writer, model, "n")) + memberPrefix + "Member($1S, n -> $3C, builder::$2L)", + fieldName, + memberName, + (Runnable) () -> shape.accept(new FromNodeMapperVisitor(writer, model, "n")) ); return null; } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/FromNodeMapperVisitor.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/FromNodeMapperVisitor.java index ca406a85945..4a231861df5 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/FromNodeMapperVisitor.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/FromNodeMapperVisitor.java @@ -61,8 +61,8 @@ public Void listShape(ListShape shape) { writer.indent(); writer.writeWithNoFormatting(".getElements().stream()"); writer.write( - ".map(n -> $C)", - (Runnable) () -> shape.getMember().accept(new FromNodeMapperVisitor(writer, model, "n")) + ".map(n -> $C)", + (Runnable) () -> shape.getMember().accept(new FromNodeMapperVisitor(writer, model, "n")) ); writer.writeWithNoFormatting(".forEach(builder::addValues);"); writer.dedent(); @@ -72,14 +72,14 @@ public Void listShape(ListShape shape) { @Override public Void mapShape(MapShape shape) { writer.openBlock( - "$L.expectObjectNode().getMembers().forEach((k, v) -> {", - "});", - varName, - () -> writer.write( - "builder.putValues($C, $C);", - (Runnable) () -> shape.getKey().accept(new FromNodeMapperVisitor(writer, model, "k")), - (Runnable) () -> shape.getValue().accept(new FromNodeMapperVisitor(writer, model, "v")) - ) + "$L.expectObjectNode().getMembers().forEach((k, v) -> {", + "});", + varName, + () -> writer.write( + "builder.putValues($C, $C);", + (Runnable) () -> shape.getKey().accept(new FromNodeMapperVisitor(writer, model, "k")), + (Runnable) () -> shape.getValue().accept(new FromNodeMapperVisitor(writer, model, "v")) + ) ); return null; } @@ -160,17 +160,17 @@ public Void timestampShape(TimestampShape shape) { switch (shape.expectTrait(TimestampFormatTrait.class).getFormat()) { case EPOCH_SECONDS: writer.writeInline( - "$2T.ofEpochSecond($1L.expectNumberNode().getValue().longValue())", - varName, - Instant.class + "$2T.ofEpochSecond($1L.expectNumberNode().getValue().longValue())", + varName, + Instant.class ); return null; case HTTP_DATE: writer.writeInline( - "$2T.from($3T.RFC_1123_DATE_TIME.parse($1L.expectStringNode().getValue()))", - varName, - Instant.class, - DateTimeFormatter.class + "$2T.from($3T.RFC_1123_DATE_TIME.parse($1L.expectStringNode().getValue()))", + varName, + Instant.class, + DateTimeFormatter.class ); return null; default: diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/GetterGenerator.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/GetterGenerator.java index 511f66ddc37..8451b4f991d 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/GetterGenerator.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/GetterGenerator.java @@ -52,10 +52,10 @@ public final class GetterVisitor extends TraitVisitor { @Override public Void documentShape(DocumentShape shape) { writer.openBlock( - "public $T getValue() {", - "}", - Node.class, - () -> writer.writeWithNoFormatting("return toNode();") + "public $T getValue() {", + "}", + Node.class, + () -> writer.writeWithNoFormatting("return toNode();") ); writer.newLine(); return null; @@ -90,10 +90,10 @@ public Void enumShape(EnumShape shape) { Symbol shapeSymbol = symbolProvider.toSymbol(shape); generateEnumValueGetterDocstring(shapeSymbol); writer.openBlock( - "public $B getEnumValue() {", - "}", - shapeSymbol, - () -> writer.write("return $B.from(getValue());", shapeSymbol) + "public $B getEnumValue() {", + "}", + shapeSymbol, + () -> writer.write("return $B.from(getValue());", shapeSymbol) ); writer.newLine(); return null; @@ -103,10 +103,10 @@ public Void enumShape(EnumShape shape) { public Void intEnumShape(IntEnumShape shape) { writer.pushState(new GetterSection(shape)); writer.openBlock( - "public $T getValue() {", - "}", - Integer.class, - () -> writer.write("return value;") + "public $T getValue() {", + "}", + Integer.class, + () -> writer.write("return value;") ); writer.popState(); writer.newLine(); @@ -114,10 +114,10 @@ public Void intEnumShape(IntEnumShape shape) { Symbol shapeSymbol = symbolProvider.toSymbol(shape); generateEnumValueGetterDocstring(shapeSymbol); writer.openBlock( - "public $B getEnumValue() {", - "}", - shapeSymbol, - () -> writer.write("return $B.from(value);", shapeSymbol) + "public $B getEnumValue() {", + "}", + shapeSymbol, + () -> writer.write("return $B.from(value);", shapeSymbol) ); writer.newLine(); return null; @@ -131,16 +131,16 @@ public Void structureShape(StructureShape shape) { writer.pushState(new GetterSection(member)); if (TraitCodegenUtils.isNullableMember(member)) { writer.openBlock( - "public $T<$T> get$U() {", - "}", - Optional.class, - symbolProvider.toSymbol(member), - symbolProvider.toMemberName(member), - () -> writer.write( - "return $T.ofNullable($L);", + "public $T<$T> get$U() {", + "}", Optional.class, - symbolProvider.toMemberName(member) - ) + symbolProvider.toSymbol(member), + symbolProvider.toMemberName(member), + () -> writer.write( + "return $T.ofNullable($L);", + Optional.class, + symbolProvider.toMemberName(member) + ) ); writer.popState(); writer.newLine(); @@ -150,20 +150,20 @@ public Void structureShape(StructureShape shape) { Shape target = model.expectShape(member.getTarget()); if (target.isListShape() || target.isMapShape()) { writer.openBlock( - "public $T get$UOrEmpty() {", - "}", - symbolProvider.toSymbol(member), - symbolProvider.toMemberName(member), - () -> writer.write("return $L;", symbolProvider.toMemberName(member)) + "public $T get$UOrEmpty() {", + "}", + symbolProvider.toSymbol(member), + symbolProvider.toMemberName(member), + () -> writer.write("return $L;", symbolProvider.toMemberName(member)) ); } } else { writer.openBlock( - "public $T get$U() {", - "}", - symbolProvider.toSymbol(member), - symbolProvider.toMemberName(member), - () -> writer.write("return $L;", symbolProvider.toMemberName(member)) + "public $T get$U() {", + "}", + symbolProvider.toSymbol(member), + symbolProvider.toMemberName(member), + () -> writer.write("return $L;", symbolProvider.toMemberName(member)) ); writer.popState(); } @@ -186,21 +186,21 @@ protected Void numberShape(NumberShape shape) { private void generateEnumValueGetterDocstring(Symbol symbol) { writer.writeDocString( - writer.format( - "Gets the {@code $1T} value as a {@code $1B} enum.\n\n" - + "@return Returns the {@code $1B} enum.", - symbol - ) + writer.format( + "Gets the {@code $1T} value as a {@code $1B} enum.\n\n" + + "@return Returns the {@code $1B} enum.", + symbol + ) ); } private void generateValuesGetter(Shape shape) { writer.pushState(new GetterSection(shape)); writer.openBlock( - "public $B getValues() {", - "}", - symbolProvider.toSymbol(shape), - () -> writer.write("return values;") + "public $B getValues() {", + "}", + symbolProvider.toSymbol(shape), + () -> writer.write("return values;") ); writer.popState(); writer.newLine(); @@ -209,10 +209,10 @@ private void generateValuesGetter(Shape shape) { private void generateValueGetter(Shape shape) { writer.pushState(new GetterSection(shape)); writer.openBlock( - "public $B getValue() {", - "}", - symbolProvider.toSymbol(shape), - () -> writer.write("return value;") + "public $B getValue() {", + "}", + symbolProvider.toSymbol(shape), + () -> writer.write("return value;") ); writer.popState(); writer.newLine(); diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/PropertiesGenerator.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/PropertiesGenerator.java index 47bfcd0ca03..d8f82317361 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/PropertiesGenerator.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/PropertiesGenerator.java @@ -99,9 +99,9 @@ public Void enumShape(EnumShape shape) { public Void structureShape(StructureShape shape) { for (MemberShape member : shape.members()) { writer.write( - "private final $T $L;", - symbolProvider.toSymbol(member), - symbolProvider.toMemberName(member) + "private final $T $L;", + symbolProvider.toSymbol(member), + symbolProvider.toMemberName(member) ); } return null; diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ProviderGenerator.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ProviderGenerator.java index 7ee76441b0f..91db52df75b 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ProviderGenerator.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ProviderGenerator.java @@ -43,11 +43,11 @@ final class ProviderGenerator implements Runnable { private final Symbol traitSymbol; ProviderGenerator( - TraitCodegenWriter writer, - Model model, - Shape shape, - SymbolProvider provider, - Symbol traitSymbol + TraitCodegenWriter writer, + Model model, + Shape shape, + SymbolProvider provider, + Symbol traitSymbol ) { this.writer = writer; this.model = model; @@ -66,22 +66,22 @@ private final class ProviderMethodVisitor extends TraitVisitor { @Override public Void documentShape(DocumentShape shape) { writer.openBlock( - "public static final class Provider extends $T.Provider {", - "}", - AbstractTrait.class, - () -> { - generateProviderConstructor(); - writer.newLine(); - writer.override(); - writer.openBlock( - "public $T createTrait($T target, $T value) {", - "}", - Trait.class, - ShapeId.class, - Node.class, - () -> writer.write("return new $T(value);", traitSymbol) - ); - } + "public static final class Provider extends $T.Provider {", + "}", + AbstractTrait.class, + () -> { + generateProviderConstructor(); + writer.newLine(); + writer.override(); + writer.openBlock( + "public $T createTrait($T target, $T value) {", + "}", + Trait.class, + ShapeId.class, + Node.class, + () -> writer.write("return new $T(value);", traitSymbol) + ); + } ); return null; } @@ -109,15 +109,15 @@ public Void listShape(ListShape shape) { // If the trait is a string-only list we can use a simpler provider from the StringListTrait base class if (TraitCodegenUtils.isJavaStringList(shape, provider)) { writer.openBlock( - "public static final class Provider extends $T.Provider<$T> {", - "}", - StringListTrait.class, - traitSymbol, - () -> writer.openBlock( - "public Provider() {", + "public static final class Provider extends $T.Provider<$T> {", "}", - () -> writer.write("super(ID, $T::new);", traitSymbol) - ) + StringListTrait.class, + traitSymbol, + () -> writer.openBlock( + "public Provider() {", + "}", + () -> writer.write("super(ID, $T::new);", traitSymbol) + ) ); } else { generateAbstractTraitProvider(); @@ -151,25 +151,25 @@ protected Void numberShape(NumberShape shape) { private void generateAbstractTraitProvider() { writer.openBlock( - "public static final class Provider extends $T.Provider {", - "}", - AbstractTrait.class, - () -> { - generateProviderConstructor(); - writer.override(); - writer.openBlock( - "public $T createTrait($T target, $T value) {", - "}", - Trait.class, - ShapeId.class, - Node.class, - () -> { - writer.write("$1T result = $1T.fromNode(value);", traitSymbol); - writer.writeWithNoFormatting("result.setNodeCache(value);"); - writer.writeWithNoFormatting("return result;"); - } - ); - } + "public static final class Provider extends $T.Provider {", + "}", + AbstractTrait.class, + () -> { + generateProviderConstructor(); + writer.override(); + writer.openBlock( + "public $T createTrait($T target, $T value) {", + "}", + Trait.class, + ShapeId.class, + Node.class, + () -> { + writer.write("$1T result = $1T.fromNode(value);", traitSymbol); + writer.writeWithNoFormatting("result.setNodeCache(value);"); + writer.writeWithNoFormatting("return result;"); + } + ); + } ); } @@ -179,39 +179,39 @@ private void generateProviderConstructor() { private void generateValueShapeProvider() { writer.openBlock( - "public static final class Provider extends $T.Provider {", - "}", - AbstractTrait.class, - () -> { - generateProviderConstructor(); - writer.override(); - writer.openBlock( - "public $T createTrait($T target, $T value) {", - "}", - Trait.class, - ShapeId.class, - Node.class, - () -> writer.write( - "return new $1T($2C, value.getSourceLocation());", - traitSymbol, - (Runnable) () -> shape.accept(new FromNodeMapperVisitor(writer, model, "value")) - ) - ); - } + "public static final class Provider extends $T.Provider {", + "}", + AbstractTrait.class, + () -> { + generateProviderConstructor(); + writer.override(); + writer.openBlock( + "public $T createTrait($T target, $T value) {", + "}", + Trait.class, + ShapeId.class, + Node.class, + () -> writer.write( + "return new $1T($2C, value.getSourceLocation());", + traitSymbol, + (Runnable) () -> shape.accept(new FromNodeMapperVisitor(writer, model, "value")) + ) + ); + } ); } private void generateStringShapeProvider() { writer.openBlock( - "public static final class Provider extends $T.Provider<$T> {", - "}", - StringTrait.class, - traitSymbol, - () -> writer.openBlock( - "public Provider() {", + "public static final class Provider extends $T.Provider<$T> {", "}", - () -> writer.write("super(ID, $T::new);", traitSymbol) - ) + StringTrait.class, + traitSymbol, + () -> writer.openBlock( + "public Provider() {", + "}", + () -> writer.write("super(ID, $T::new);", traitSymbol) + ) ); } } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ShapeGenerator.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ShapeGenerator.java index 600618ca3a0..8bfd9995896 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ShapeGenerator.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ShapeGenerator.java @@ -68,16 +68,16 @@ public Void intEnumShape(IntEnumShape shape) { @Override public Void unionShape(UnionShape shape) { throw new UnsupportedOperationException( - "Generation of nested types for Union shapes " - + " is not supported at this time." + "Generation of nested types for Union shapes " + + " is not supported at this time." ); } @Override public Void memberShape(MemberShape shape) { throw new IllegalArgumentException( - "NestedShapeGenerator should not visit member shapes. " - + " Attempted to visit " + shape + "NestedShapeGenerator should not visit member shapes. " + + " Attempted to visit " + shape ); } } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/StructureShapeGenerator.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/StructureShapeGenerator.java index 4099827f998..3ab0435a28f 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/StructureShapeGenerator.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/StructureShapeGenerator.java @@ -20,51 +20,51 @@ final class StructureShapeGenerator implements Consumer public void accept(GenerateTraitDirective directive) { directive.context().writerDelegator().useShapeWriter(directive.shape(), writer -> { writer.pushState(new ClassSection(directive.shape())) - .openBlock( - "public final class $1T implements $2T, $3T<$1T> {", - "}", - directive.symbol(), - ToNode.class, - ToSmithyBuilder.class, - () -> { - new PropertiesGenerator(writer, directive.shape(), directive.symbolProvider()).run(); - new ConstructorGenerator( - writer, - directive.symbol(), - directive.shape(), - directive.symbolProvider() - ).run(); - new ToNodeGenerator( - writer, - directive.shape(), - directive.symbolProvider(), - directive.model() - ).run(); - new FromNodeGenerator( - writer, + .openBlock( + "public final class $1T implements $2T, $3T<$1T> {", + "}", directive.symbol(), - directive.shape(), - directive.symbolProvider(), - directive.model() - ).run(); - new GetterGenerator( - writer, - directive.symbolProvider(), - directive.model(), - directive.shape() - ).run(); - new BuilderGenerator( - writer, - directive.symbol(), - directive.symbolProvider(), - directive.shape(), - directive.model() - ).run(); - writeEquals(writer, directive.symbol()); - writeHashCode(writer); - } - ) - .popState(); + ToNode.class, + ToSmithyBuilder.class, + () -> { + new PropertiesGenerator(writer, directive.shape(), directive.symbolProvider()).run(); + new ConstructorGenerator( + writer, + directive.symbol(), + directive.shape(), + directive.symbolProvider() + ).run(); + new ToNodeGenerator( + writer, + directive.shape(), + directive.symbolProvider(), + directive.model() + ).run(); + new FromNodeGenerator( + writer, + directive.symbol(), + directive.shape(), + directive.symbolProvider(), + directive.model() + ).run(); + new GetterGenerator( + writer, + directive.symbolProvider(), + directive.model(), + directive.shape() + ).run(); + new BuilderGenerator( + writer, + directive.symbol(), + directive.symbolProvider(), + directive.shape(), + directive.model() + ).run(); + writeEquals(writer, directive.symbol()); + writeHashCode(writer); + } + ) + .popState(); writer.newLine(); }); } @@ -74,15 +74,15 @@ private void writeEquals(TraitCodegenWriter writer, Symbol symbol) { writer.openBlock("public boolean equals(Object other) {", "}", () -> { writer.disableNewlines(); writer.openBlock( - "if (other == this) {\n", - "}", - () -> writer.writeWithNoFormatting("return true;").newLine() + "if (other == this) {\n", + "}", + () -> writer.writeWithNoFormatting("return true;").newLine() ); writer.openBlock( - " else if (!(other instanceof $T)) {\n", - "}", - symbol, - () -> writer.writeWithNoFormatting("return false;").newLine() + " else if (!(other instanceof $T)) {\n", + "}", + symbol, + () -> writer.writeWithNoFormatting("return false;").newLine() ); writer.openBlock(" else {\n", "}", () -> { writer.write("$1T b = ($1T) other;", symbol).newLine(); @@ -96,9 +96,9 @@ private void writeEquals(TraitCodegenWriter writer, Symbol symbol) { private void writeHashCode(TraitCodegenWriter writer) { writer.override(); writer.openBlock( - "public int hashCode() {", - "}", - () -> writer.writeWithNoFormatting("return toNode().hashCode();") + "public int hashCode() {", + "}", + () -> writer.writeWithNoFormatting("return toNode().hashCode();") ); } } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ToNodeGenerator.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ToNodeGenerator.java index 7f9c85a2d98..6f2e12e66a1 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ToNodeGenerator.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/ToNodeGenerator.java @@ -60,10 +60,10 @@ final class ToNodeGenerator implements Runnable { public void run() { writer.override(); writer.openBlock( - shape.hasTrait(TraitDefinition.class) ? "protected $T createNode() {" : "public $T toNode() {", - "}", - Node.class, - () -> shape.accept(new CreateNodeBodyGenerator()) + shape.hasTrait(TraitDefinition.class) ? "protected $T createNode() {" : "public $T toNode() {", + "}", + Node.class, + () -> shape.accept(new CreateNodeBodyGenerator()) ); writer.newLine(); } @@ -73,13 +73,13 @@ private final class CreateNodeBodyGenerator extends TraitVisitor { @Override public Void listShape(ListShape shape) { writer.write("return values.stream()") - .indent() - .write( - ".map(s -> $C)", - (Runnable) () -> shape.getMember().accept(new ToNodeMapperVisitor("s")) - ) - .write(".collect($T.collect(getSourceLocation()));", ArrayNode.class) - .dedent(); + .indent() + .write( + ".map(s -> $C)", + (Runnable) () -> shape.getMember().accept(new ToNodeMapperVisitor("s")) + ) + .write(".collect($T.collect(getSourceLocation()));", ArrayNode.class) + .dedent(); return null; } @@ -93,35 +93,35 @@ public Void documentShape(DocumentShape shape) { public Void mapShape(MapShape shape) { // If it is a Map use a simpler syntax if (TraitCodegenUtils.isJavaString(symbolProvider.toSymbol(shape.getKey())) - && TraitCodegenUtils.isJavaString(symbolProvider.toSymbol(shape.getValue())) + && TraitCodegenUtils.isJavaString(symbolProvider.toSymbol(shape.getValue())) ) { writer.write("return $T.fromStringMap(values).toBuilder()", ObjectNode.class) - .writeWithNoFormatting(".sourceLocation(getSourceLocation()).build();"); + .writeWithNoFormatting(".sourceLocation(getSourceLocation()).build();"); return null; } writer.writeWithNoFormatting("return values.entrySet().stream()") - .indent() - .write(".map(entry -> new $T<>(", AbstractMap.SimpleImmutableEntry.class) - .indent() - .write( - "$C, $C))", - (Runnable) () -> shape.getKey() - .accept( - new ToNodeMapperVisitor("entry.getKey()") - ), - (Runnable) () -> shape.getValue() - .accept( - new ToNodeMapperVisitor("entry.getValue()") - ) - ) - .dedent() - .write( - ".collect($1T.collect($2T::getKey, $2T::getValue))", - ObjectNode.class, - Map.Entry.class - ) - .writeWithNoFormatting(".toBuilder().sourceLocation(getSourceLocation()).build();") - .dedent(); + .indent() + .write(".map(entry -> new $T<>(", AbstractMap.SimpleImmutableEntry.class) + .indent() + .write( + "$C, $C))", + (Runnable) () -> shape.getKey() + .accept( + new ToNodeMapperVisitor("entry.getKey()") + ), + (Runnable) () -> shape.getValue() + .accept( + new ToNodeMapperVisitor("entry.getValue()") + ) + ) + .dedent() + .write( + ".collect($1T.collect($2T::getKey, $2T::getValue))", + ObjectNode.class, + Map.Entry.class + ) + .writeWithNoFormatting(".toBuilder().sourceLocation(getSourceLocation()).build();") + .dedent(); return null; } @@ -155,16 +155,16 @@ public Void structureShape(StructureShape shape) { for (MemberShape mem : shape.members()) { if (TraitCodegenUtils.isNullableMember(mem)) { writer.write( - ".withOptionalMember($S, get$U().map(m -> $C))", - mem.getMemberName(), - symbolProvider.toMemberName(mem), - (Runnable) () -> mem.accept(new ToNodeMapperVisitor("m")) + ".withOptionalMember($S, get$U().map(m -> $C))", + mem.getMemberName(), + symbolProvider.toMemberName(mem), + (Runnable) () -> mem.accept(new ToNodeMapperVisitor("m")) ); } else { writer.write( - ".withMember($S, $C)", - mem.getMemberName(), - (Runnable) () -> mem.accept(new ToNodeMapperVisitor(symbolProvider.toMemberName(mem))) + ".withMember($S, $C)", + mem.getMemberName(), + (Runnable) () -> mem.accept(new ToNodeMapperVisitor(symbolProvider.toMemberName(mem))) ); } } @@ -185,21 +185,21 @@ public Void timestampShape(TimestampShape shape) { switch (shape.expectTrait(TimestampFormatTrait.class).getFormat()) { case EPOCH_SECONDS: writer.write( - "return new $T(value.getEpochSecond(), getSourceLocation());", - NumberNode.class + "return new $T(value.getEpochSecond(), getSourceLocation());", + NumberNode.class ); break; case HTTP_DATE: writer.write( - "return new $T($T.RFC_1123_DATE_TIME.format(", - StringNode.class, - DateTimeFormatter.class + "return new $T($T.RFC_1123_DATE_TIME.format(", + StringNode.class, + DateTimeFormatter.class ); writer.indent(); writer.write( - "$T.ofInstant(value, $T.UTC)), getSourceLocation());", - ZonedDateTime.class, - ZoneOffset.class + "$T.ofInstant(value, $T.UTC)), getSourceLocation());", + ZonedDateTime.class, + ZoneOffset.class ); writer.dedent(); break; @@ -248,10 +248,10 @@ public Void booleanShape(BooleanShape shape) { @Override public Void listShape(ListShape shape) { writer.write( - "$L.stream().map(s -> $C).collect($T.collect())", - varName, - (Runnable) () -> shape.getMember().accept(new ToNodeMapperVisitor("s")), - ArrayNode.class + "$L.stream().map(s -> $C).collect($T.collect())", + varName, + (Runnable) () -> shape.getMember().accept(new ToNodeMapperVisitor("s")), + ArrayNode.class ); return null; } @@ -259,28 +259,28 @@ public Void listShape(ListShape shape) { @Override public Void mapShape(MapShape shape) { writer.openBlock( - "$L.entrySet().stream()", - "", - varName, - () -> writer.write(".map(entry -> new $T<>(", AbstractMap.SimpleImmutableEntry.class) - .indent() - .write( - "$C, $C))", - (Runnable) () -> shape.getKey() - .accept( - new ToNodeMapperVisitor("entry.getKey()") - ), - (Runnable) () -> shape.getValue() - .accept( - new ToNodeMapperVisitor("entry.getValue()") + "$L.entrySet().stream()", + "", + varName, + () -> writer.write(".map(entry -> new $T<>(", AbstractMap.SimpleImmutableEntry.class) + .indent() + .write( + "$C, $C))", + (Runnable) () -> shape.getKey() + .accept( + new ToNodeMapperVisitor("entry.getKey()") + ), + (Runnable) () -> shape.getValue() + .accept( + new ToNodeMapperVisitor("entry.getValue()") + ) + ) + .dedent() + .write( + ".collect($1T.collect($2T::getKey, $2T::getValue))", + ObjectNode.class, + Map.Entry.class ) - ) - .dedent() - .write( - ".collect($1T.collect($2T::getKey, $2T::getValue))", - ObjectNode.class, - Map.Entry.class - ) ); return null; } @@ -334,10 +334,10 @@ public Void timestampShape(TimestampShape shape) { return null; case HTTP_DATE: writer.write( - "$T.from($T.RFC_1123_DATE_TIME.format($L))", - Node.class, - DateTimeFormatter.class, - varName + "$T.from($T.RFC_1123_DATE_TIME.format($L))", + Node.class, + DateTimeFormatter.class, + varName ); return null; default: diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/TraitGenerator.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/TraitGenerator.java index e10acac7271..64498b706ce 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/TraitGenerator.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/TraitGenerator.java @@ -51,59 +51,65 @@ public void accept(GenerateTraitDirective directive) { boolean isAggregateType = directive.shape().getType().getCategory().equals(ShapeType.Category.AGGREGATE); writer.putContext("isAggregateType", isAggregateType); writer.openBlock( - "public final class $2T extends $baseClass:T" - + "${?isAggregateType} implements $1T<$2T>${/isAggregateType} {", - "}", - ToSmithyBuilder.class, - directive.symbol(), - () -> { - // All traits include a static ID property - writer.write( - "public static final $1T ID = $1T.from($2S);", - ShapeId.class, - directive.shape().getId() - ); - writer.newLine(); - new PropertiesGenerator(writer, directive.shape(), directive.symbolProvider()).run(); - new ConstructorGenerator( - writer, - directive.symbol(), - directive.shape(), - directive.symbolProvider() - ).run(); - // Abstract Traits need to define serde methods - if (AbstractTrait.class.equals( - directive.shape().accept(new BaseClassVisitor(directive.symbolProvider())) - ) - ) { - new ToNodeGenerator(writer, directive.shape(), directive.symbolProvider(), directive.model()) - .run(); + "public final class $2T extends $baseClass:T" + + "${?isAggregateType} implements $1T<$2T>${/isAggregateType} {", + "}", + ToSmithyBuilder.class, + directive.symbol(), + () -> { + // All traits include a static ID property + writer.write( + "public static final $1T ID = $1T.from($2S);", + ShapeId.class, + directive.shape().getId() + ); + writer.newLine(); + new PropertiesGenerator(writer, directive.shape(), directive.symbolProvider()).run(); + new ConstructorGenerator( + writer, + directive.symbol(), + directive.shape(), + directive.symbolProvider() + ).run(); + // Abstract Traits need to define serde methods + if (AbstractTrait.class.equals( + directive.shape().accept(new BaseClassVisitor(directive.symbolProvider())) + ) + ) { + new ToNodeGenerator( + writer, + directive.shape(), + directive.symbolProvider(), + directive.model() + ) + .run(); + } + new FromNodeGenerator( + writer, + directive.symbol(), + directive.shape(), + directive.symbolProvider(), + directive.model() + ).run(); + new GetterGenerator(writer, directive.symbolProvider(), directive.model(), directive.shape()) + .run(); + directive.shape() + .accept(new NestedClassVisitor(writer, directive.symbolProvider(), directive.model())); + new BuilderGenerator( + writer, + directive.symbol(), + directive.symbolProvider(), + directive.shape(), + directive.model() + ).run(); + new ProviderGenerator( + writer, + directive.model(), + directive.shape(), + directive.symbolProvider(), + directive.symbol() + ).run(); } - new FromNodeGenerator( - writer, - directive.symbol(), - directive.shape(), - directive.symbolProvider(), - directive.model() - ).run(); - new GetterGenerator(writer, directive.symbolProvider(), directive.model(), directive.shape()).run(); - directive.shape() - .accept(new NestedClassVisitor(writer, directive.symbolProvider(), directive.model())); - new BuilderGenerator( - writer, - directive.symbol(), - directive.symbolProvider(), - directive.shape(), - directive.model() - ).run(); - new ProviderGenerator( - writer, - directive.model(), - directive.shape(), - directive.symbolProvider(), - directive.symbol() - ).run(); - } ); writer.popState(); }); @@ -119,10 +125,10 @@ public void accept(GenerateTraitDirective directive) { */ private static void addSpiTraitProvider(TraitCodegenContext context, Symbol symbol) { context.writerDelegator() - .useFileWriter( - PROVIDER_FILE, - writer -> writer.writeInline("$L$$Provider", symbol.getFullName()) - ); + .useFileWriter( + PROVIDER_FILE, + writer -> writer.writeInline("$L$$Provider", symbol.getFullName()) + ); } /** diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/TraitVisitor.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/TraitVisitor.java index 03e7f1eda17..9b0ea7ccf1c 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/TraitVisitor.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/TraitVisitor.java @@ -38,8 +38,8 @@ abstract class TraitVisitor extends ShapeVisitor.DataShapeVisitor { @Override public R booleanShape(BooleanShape shape) { throw new UnsupportedOperationException( - "Boolean traits not supported. Consider using an " - + " Annotation Trait." + "Boolean traits not supported. Consider using an " + + " Annotation Trait." ); } @@ -86,24 +86,24 @@ public R bigDecimalShape(BigDecimalShape shape) { @Override public R unionShape(UnionShape shape) { throw new UnsupportedOperationException( - "Property generator does not support shape " - + shape + " of type " + shape.getType() + "Property generator does not support shape " + + shape + " of type " + shape.getType() ); } @Override public R blobShape(BlobShape shape) { throw new UnsupportedOperationException( - "Property generator does not support shape " - + shape + " of type " + shape.getType() + "Property generator does not support shape " + + shape + " of type " + shape.getType() ); } @Override public R memberShape(MemberShape shape) { throw new IllegalArgumentException( - "Property generator cannot visit member shapes. Attempted " - + "to visit " + shape + "Property generator cannot visit member shapes. Attempted " + + "to visit " + shape ); } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/TraitCodegenIntegration.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/TraitCodegenIntegration.java index 9bcda19d81a..1d3af82a15a 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/TraitCodegenIntegration.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/TraitCodegenIntegration.java @@ -19,5 +19,5 @@ * {@code AutoService}, can do this for you. */ public interface TraitCodegenIntegration extends - SmithyIntegration { + SmithyIntegration { } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/annotations/AnnotationIntegration.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/annotations/AnnotationIntegration.java index a3c54afaa3e..6a8ecc61bbf 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/annotations/AnnotationIntegration.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/annotations/AnnotationIntegration.java @@ -29,12 +29,12 @@ public List runBefore() { @Override public List> interceptors( - TraitCodegenContext codegenContext + TraitCodegenContext codegenContext ) { return ListUtils.of( - new SmithyGeneratedAnnotationInterceptor(), - new DeprecatedAnnotationInterceptor(), - new UnstableAnnotationInterceptor() + new SmithyGeneratedAnnotationInterceptor(), + new DeprecatedAnnotationInterceptor(), + new UnstableAnnotationInterceptor() ); } } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/annotations/SmithyGeneratedAnnotationInterceptor.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/annotations/SmithyGeneratedAnnotationInterceptor.java index 16098b6253f..653afc4af05 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/annotations/SmithyGeneratedAnnotationInterceptor.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/annotations/SmithyGeneratedAnnotationInterceptor.java @@ -13,7 +13,7 @@ * Adds the {@link software.amazon.smithy.utils.SmithyGenerated} annotation to all generated classes. */ final class SmithyGeneratedAnnotationInterceptor - implements CodeInterceptor.Prepender { + implements CodeInterceptor.Prepender { @Override public Class sectionType() { return ClassSection.class; diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/core/CoreIntegration.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/core/CoreIntegration.java index 623fcd04029..eb7325c2331 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/core/CoreIntegration.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/core/CoreIntegration.java @@ -50,9 +50,9 @@ public byte priority() { @Override public SymbolProvider decorateSymbolProvider( - Model model, - TraitCodegenSettings settings, - SymbolProvider symbolProvider + Model model, + TraitCodegenSettings settings, + SymbolProvider symbolProvider ) { return new SymbolProvider() { @Override @@ -73,16 +73,16 @@ public String toMemberName(MemberShape shape) { @Override public List> interceptors( - TraitCodegenContext codegenContext + TraitCodegenContext codegenContext ) { return ListUtils.of(new JavadocFormatterInterceptor()); } private Symbol getTraitSymbol(TraitCodegenSettings settings, Shape shape, Symbol baseSymbol) { String relativeNamespace = TraitCodegenUtils.mapNamespace( - settings.smithyNamespace(), - shape.getId().getNamespace(), - settings.packageName() + settings.smithyNamespace(), + shape.getId().getNamespace(), + settings.packageName() ); String name = TraitCodegenUtils.getDefaultTraitName(shape); @@ -96,11 +96,11 @@ private Symbol getTraitSymbol(TraitCodegenSettings settings, Shape shape, Symbol // and add the base symbol as a property. The references need to be set to empty list // to prevent writing as parameterized classes. return baseSymbol.toBuilder() - .name(name) - .references(ListUtils.of()) - .namespace(relativeNamespace, ".") - .putProperty(SymbolProperties.BASE_SYMBOL, baseSymbol) - .definitionFile("./" + relativeNamespace.replace(".", "/") + "/" + name + ".java") - .build(); + .name(name) + .references(ListUtils.of()) + .namespace(relativeNamespace, ".") + .putProperty(SymbolProperties.BASE_SYMBOL, baseSymbol) + .definitionFile("./" + relativeNamespace.replace(".", "/") + "/" + name + ".java") + .build(); } } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/idref/IdRefDecoratorIntegration.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/idref/IdRefDecoratorIntegration.java index e94c54bedc7..cd057a75828 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/idref/IdRefDecoratorIntegration.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/idref/IdRefDecoratorIntegration.java @@ -43,9 +43,9 @@ public byte priority() { @Override public SymbolProvider decorateSymbolProvider( - Model model, - TraitCodegenSettings settings, - SymbolProvider symbolProvider + Model model, + TraitCodegenSettings settings, + SymbolProvider symbolProvider ) { return new SymbolProvider() { @Override @@ -72,21 +72,21 @@ private Symbol provideSymbol(Shape shape, SymbolProvider symbolProvider, Model m // toSymbol(member) MemberShape member = shape.asListShape().orElseThrow(RuntimeException::new).getMember(); return symbolProvider.toSymbol(shape) - .toBuilder() - .references(ListUtils.of(new SymbolReference(provideSymbol(member, symbolProvider, model)))) - .build(); + .toBuilder() + .references(ListUtils.of(new SymbolReference(provideSymbol(member, symbolProvider, model)))) + .build(); } else if (shape.isMapShape()) { // Same as list replacement but for map shapes MapShape mapShape = shape.asMapShape().orElseThrow(RuntimeException::new); return symbolProvider.toSymbol(shape) - .toBuilder() - .references( - ListUtils.of( - new SymbolReference(provideSymbol(mapShape.getKey(), symbolProvider, model)), - new SymbolReference(provideSymbol(mapShape.getValue(), symbolProvider, model)) + .toBuilder() + .references( + ListUtils.of( + new SymbolReference(provideSymbol(mapShape.getKey(), symbolProvider, model)), + new SymbolReference(provideSymbol(mapShape.getValue(), symbolProvider, model)) + ) ) - ) - .build(); + .build(); } return symbolProvider.toSymbol(shape); } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/javadoc/JavaDocInjectorInterceptor.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/javadoc/JavaDocInjectorInterceptor.java index b767e9a8314..bf8a7b6204a 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/javadoc/JavaDocInjectorInterceptor.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/javadoc/JavaDocInjectorInterceptor.java @@ -29,8 +29,8 @@ public Class sectionType() { @Override public boolean isIntercepted(CodeSection section) { return section instanceof ClassSection - || section instanceof GetterSection - || section instanceof EnumVariantSection; + || section instanceof GetterSection + || section instanceof EnumVariantSection; } @Override diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/javadoc/JavaDocIntegration.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/javadoc/JavaDocIntegration.java index 8d7e8ba421f..f138c78a699 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/javadoc/JavaDocIntegration.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/integrations/javadoc/JavaDocIntegration.java @@ -30,14 +30,14 @@ public String name() { @Override public List> interceptors( - TraitCodegenContext codegenContext + TraitCodegenContext codegenContext ) { return ListUtils.of( - new JavaDocInjectorInterceptor(), - new ExternalDocumentationInterceptor(), - new SinceInterceptor(), - new DeprecatedInterceptor(), - new DocumentationTraitInterceptor() + new JavaDocInjectorInterceptor(), + new ExternalDocumentationInterceptor(), + new SinceInterceptor(), + new DeprecatedInterceptor(), + new DocumentationTraitInterceptor() ); } } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/writer/TraitCodegenImportContainer.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/writer/TraitCodegenImportContainer.java index 009f2edb8dc..d6b77f4ebdc 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/writer/TraitCodegenImportContainer.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/writer/TraitCodegenImportContainer.java @@ -53,12 +53,12 @@ public String toString() { */ private Set getSortedAndFilteredImports() { return imports.values() - .stream() - .filter(s -> s.size() == 1) - .map(s -> s.iterator().next()) - .filter(s -> !s.getNamespace().startsWith("java.lang")) - .filter(s -> !s.getNamespace().equals(namespace)) - .map(Symbol::getFullName) - .collect(Collectors.toCollection(TreeSet::new)); + .stream() + .filter(s -> s.size() == 1) + .map(s -> s.iterator().next()) + .filter(s -> !s.getNamespace().startsWith("java.lang")) + .filter(s -> !s.getNamespace().equals(namespace)) + .map(Symbol::getFullName) + .collect(Collectors.toCollection(TreeSet::new)); } } diff --git a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/writer/TraitCodegenWriter.java b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/writer/TraitCodegenWriter.java index 4a70af0f5c9..d48e1a5c592 100644 --- a/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/writer/TraitCodegenWriter.java +++ b/smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/writer/TraitCodegenWriter.java @@ -52,9 +52,9 @@ public class TraitCodegenWriter extends SymbolWriter> symbolNames = new HashMap<>(); public TraitCodegenWriter( - String fileName, - String namespace, - TraitCodegenSettings settings + String fileName, + String namespace, + TraitCodegenSettings settings ) { super(new TraitCodegenImportContainer(namespace)); this.namespace = namespace; @@ -206,8 +206,8 @@ public String apply(Object type, String indent) { typeSymbol = TraitCodegenUtils.fromClass((Class) type); } else { throw new IllegalArgumentException( - "Invalid type provided for $T. Expected a Symbol or Class " - + "but found: `" + type + "`." + "Invalid type provided for $T. Expected a Symbol or Class " + + "but found: `" + type + "`." ); } @@ -256,8 +256,8 @@ private final class BaseTypeFormatter implements BiFunction fileList = manifest.getFiles().stream().map(Path::toString).collect(Collectors.toList()); assertThat( - fileList, - hasItem( - Paths.get("/META-INF/services/software.amazon.smithy.model.traits.TraitService").toString() - ) + fileList, + hasItem( + Paths.get("/META-INF/services/software.amazon.smithy.model.traits.TraitService").toString() + ) ); assertThat( - fileList, - hasItem( - Paths.get("/com/example/traits/nested/NestedNamespaceTrait.java").toString() - ) + fileList, + hasItem( + Paths.get("/com/example/traits/nested/NestedNamespaceTrait.java").toString() + ) ); assertThat( - fileList, - hasItem( - Paths.get("/com/example/traits/nested/NestedNamespaceStruct.java").toString() - ) + fileList, + hasItem( + Paths.get("/com/example/traits/nested/NestedNamespaceStruct.java").toString() + ) ); } @Test public void filtersTags() { PluginContext context = PluginContext.builder() - .fileManifest(manifest) - .settings( - ObjectNode.builder() - .withMember("package", "com.example.traits") - .withMember("namespace", "test.smithy.traitcodegen") - .withMember("header", ArrayNode.fromStrings("Header line One")) - .withMember("excludeTags", ArrayNode.fromStrings("filterOut")) - .build() - ) - .model(model) - .build(); + .fileManifest(manifest) + .settings( + ObjectNode.builder() + .withMember("package", "com.example.traits") + .withMember("namespace", "test.smithy.traitcodegen") + .withMember("header", ArrayNode.fromStrings("Header line One")) + .withMember("excludeTags", ArrayNode.fromStrings("filterOut")) + .build() + ) + .model(model) + .build(); SmithyBuildPlugin plugin = new TraitCodegenPlugin(); plugin.execute(context); @@ -105,16 +105,16 @@ public void filtersTags() { @Test public void addsHeaderLines() { PluginContext context = PluginContext.builder() - .fileManifest(manifest) - .settings( - ObjectNode.builder() - .withMember("package", "com.example.traits") - .withMember("namespace", "test.smithy.traitcodegen") - .withMember("header", ArrayNode.fromStrings("Header line one", "Header line two")) - .build() - ) - .model(model) - .build(); + .fileManifest(manifest) + .settings( + ObjectNode.builder() + .withMember("package", "com.example.traits") + .withMember("namespace", "test.smithy.traitcodegen") + .withMember("header", ArrayNode.fromStrings("Header line one", "Header line two")) + .build() + ) + .model(model) + .build(); SmithyBuildPlugin plugin = new TraitCodegenPlugin(); plugin.execute(context); @@ -122,17 +122,17 @@ public void addsHeaderLines() { assertFalse(manifest.getFiles().isEmpty()); assertEquals(EXPECTED_NUMBER_OF_FILES, manifest.getFiles().size()); Optional fileStringOptional = manifest.getFileString( - Paths.get("com/example/traits/idref/IdRefStructTrait.java").toString() + Paths.get("com/example/traits/idref/IdRefStructTrait.java").toString() ); assertTrue(fileStringOptional.isPresent()); assertThat( - fileStringOptional.get(), - startsWith( - "/**\n" + - " * Header line one\n" + - " * Header line two\n" + - " */" - ) + fileStringOptional.get(), + startsWith( + "/**\n" + + " * Header line one\n" + + " * Header line two\n" + + " */" + ) ); } } diff --git a/smithy-trait-codegen/src/test/java/software/amazon/smithy/traitcodegen/integrations/annotations/AnnotationsTest.java b/smithy-trait-codegen/src/test/java/software/amazon/smithy/traitcodegen/integrations/annotations/AnnotationsTest.java index 87cf47c4dea..a742b7f87f4 100644 --- a/smithy-trait-codegen/src/test/java/software/amazon/smithy/traitcodegen/integrations/annotations/AnnotationsTest.java +++ b/smithy-trait-codegen/src/test/java/software/amazon/smithy/traitcodegen/integrations/annotations/AnnotationsTest.java @@ -24,27 +24,27 @@ public class AnnotationsTest { private static final URL TEST_FILE = Objects.requireNonNull( - AnnotationsTest.class.getResource("annotations-test.smithy") + AnnotationsTest.class.getResource("annotations-test.smithy") ); private final MockManifest manifest = new MockManifest(); @BeforeEach void setup() { Model model = Model.assembler() - .addImport(TEST_FILE) - .assemble() - .unwrap(); + .addImport(TEST_FILE) + .assemble() + .unwrap(); PluginContext context = PluginContext.builder() - .fileManifest(manifest) - .settings( - ObjectNode.builder() - .withMember("package", "com.example.traits") - .withMember("namespace", "com.example.annotations") - .withMember("header", ArrayNode.fromStrings("Header line One")) - .build() - ) - .model(model) - .build(); + .fileManifest(manifest) + .settings( + ObjectNode.builder() + .withMember("package", "com.example.traits") + .withMember("namespace", "com.example.annotations") + .withMember("header", ArrayNode.fromStrings("Header line One")) + .build() + ) + .model(model) + .build(); SmithyBuildPlugin plugin = new TraitCodegenPlugin(); plugin.execute(context); @@ -64,8 +64,8 @@ void hasSmithyGeneratedAnnotationEvenIfNoDocstring() { void deprecatedAnnotationOnClass() { String fileContents = getFileContentsFromShapeName("DeprecatedStructure", true); String expected = "@Deprecated\n" + - "@SmithyGenerated\n" + - "public final class DeprecatedStructureTrait"; + "@SmithyGenerated\n" + + "public final class DeprecatedStructureTrait"; assertTrue(fileContents.contains(expected)); } @@ -73,7 +73,7 @@ void deprecatedAnnotationOnClass() { void deprecatedAnnotationOnMember() { String fileContents = getFileContentsFromShapeName("DeprecatedStructure", true); String expected = " @Deprecated\n" + - " public Optional getDeprecatedMember() {"; + " public Optional getDeprecatedMember() {"; assertTrue(fileContents.contains(expected)); } @@ -81,10 +81,10 @@ void deprecatedAnnotationOnMember() { void deprecatedAnnotationWithDocsOnMember() { String fileContents = getFileContentsFromShapeName("DeprecatedStructure", true); String expected = " /**\n" + - " * Has docs in addition to deprecated\n" + - " */\n" + - " @Deprecated\n" + - " public Optional getDeprecatedWithDocs() {"; + " * Has docs in addition to deprecated\n" + + " */\n" + + " @Deprecated\n" + + " public Optional getDeprecatedWithDocs() {"; assertTrue(fileContents.contains(expected)); } @@ -92,8 +92,8 @@ void deprecatedAnnotationWithDocsOnMember() { void unstableAnnotationOnClass() { String fileContents = getFileContentsFromShapeName("UnstableStructure", true); String expected = "@SmithyUnstableApi\n" + - "@SmithyGenerated\n" + - "public final class UnstableStructureTrait extends AbstractTrait"; + "@SmithyGenerated\n" + + "public final class UnstableStructureTrait extends AbstractTrait"; assertTrue(fileContents.contains(expected)); } @@ -101,7 +101,7 @@ void unstableAnnotationOnClass() { void unstableAnnotationOnMember() { String fileContents = getFileContentsFromShapeName("UnstableStructure", true); String expected = " @SmithyUnstableApi\n" + - " public Optional getUnstableMember() {"; + " public Optional getUnstableMember() {"; assertTrue(fileContents.contains(expected)); } @@ -109,10 +109,10 @@ void unstableAnnotationOnMember() { void unstableAnnotationWithDocsOnMember() { String fileContents = getFileContentsFromShapeName("UnstableStructure", true); String expected = " /**\n" + - " * Has docs in addition to unstable\n" + - " */\n" + - " @SmithyUnstableApi\n" + - " public Optional getUnstableWithDocs() {"; + " * Has docs in addition to unstable\n" + + " */\n" + + " @SmithyUnstableApi\n" + + " public Optional getUnstableWithDocs() {"; assertTrue(fileContents.contains(expected)); } @@ -120,7 +120,7 @@ void unstableAnnotationWithDocsOnMember() { void deprecatedAnnotationOnEnumVariant() { String fileContents = getFileContentsFromShapeName("EnumWithAnnotations", true); String expected = " @Deprecated\n" + - " DEPRECATED(\"DEPRECATED\"),"; + " DEPRECATED(\"DEPRECATED\"),"; assertTrue(fileContents.contains(expected)); } @@ -128,7 +128,7 @@ void deprecatedAnnotationOnEnumVariant() { void unstableAnnotationOnEnumVariant() { String fileContents = getFileContentsFromShapeName("EnumWithAnnotations", true); String expected = " @SmithyUnstableApi\n" + - " UNSTABLE(\"UNSTABLE\"),"; + " UNSTABLE(\"UNSTABLE\"),"; assertTrue(fileContents.contains(expected)); } diff --git a/smithy-trait-codegen/src/test/java/software/amazon/smithy/traitcodegen/integrations/javadoc/JavadocTest.java b/smithy-trait-codegen/src/test/java/software/amazon/smithy/traitcodegen/integrations/javadoc/JavadocTest.java index dc5b8d08beb..ef2ed99fff9 100644 --- a/smithy-trait-codegen/src/test/java/software/amazon/smithy/traitcodegen/integrations/javadoc/JavadocTest.java +++ b/smithy-trait-codegen/src/test/java/software/amazon/smithy/traitcodegen/integrations/javadoc/JavadocTest.java @@ -29,20 +29,20 @@ public class JavadocTest { @BeforeEach void setup() { Model model = Model.assembler() - .addImport(TEST_FILE) - .assemble() - .unwrap(); + .addImport(TEST_FILE) + .assemble() + .unwrap(); PluginContext context = PluginContext.builder() - .fileManifest(manifest) - .settings( - ObjectNode.builder() - .withMember("package", "com.example.traits") - .withMember("namespace", "com.example.javadoc") - .withMember("header", ArrayNode.fromStrings("Header line One")) - .build() - ) - .model(model) - .build(); + .fileManifest(manifest) + .settings( + ObjectNode.builder() + .withMember("package", "com.example.traits") + .withMember("namespace", "com.example.javadoc") + .withMember("header", ArrayNode.fromStrings("Header line One")) + .build() + ) + .model(model) + .build(); SmithyBuildPlugin plugin = new TraitCodegenPlugin(); plugin.execute(context); @@ -53,10 +53,10 @@ void setup() { void hasClassLevelDocstring() { String fileContents = getFileContentsFromShapeName("DocumentationWrapping", true); String expected = "/**\n" + - " * Basic class-level documentation\n" + - " */\n" + - "@SmithyGenerated\n" + - "public final class DocumentationWrappingTrait extends AbstractTrait implements ToSmithyBuilder {"; + " * Basic class-level documentation\n" + + " */\n" + + "@SmithyGenerated\n" + + "public final class DocumentationWrappingTrait extends AbstractTrait implements ToSmithyBuilder {"; assertTrue(fileContents.contains(expected)); } @@ -64,13 +64,13 @@ void hasClassLevelDocstring() { void wrapsBasicTextString() { String fileContents = getFileContentsFromShapeName("DocumentationWrapping", true); String expected = " /**\n" + - " * This is a long long docstring that should be wrapped. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do\n" - + - " * eiusmod tempor incididunt ut labore et dolore magna aliqua.\n" + - " */\n" + - " public Optional getShouldBeWrapped() {\n" + - " return Optional.ofNullable(shouldBeWrapped);\n" + - " }"; + " * This is a long long docstring that should be wrapped. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do\n" + + + " * eiusmod tempor incididunt ut labore et dolore magna aliqua.\n" + + " */\n" + + " public Optional getShouldBeWrapped() {\n" + + " return Optional.ofNullable(shouldBeWrapped);\n" + + " }"; assertTrue(fileContents.contains(expected)); } @@ -78,24 +78,24 @@ void wrapsBasicTextString() { void doesNotFormatContentInsideHtmlTags() { String fileContents = getFileContentsFromShapeName("DocumentationWrapping", true); String expected = " /**\n" + - " * Documentation includes preformatted text that should not be messed with. This sentence should still be partially\n" - + - " * wrapped.\n" + - " * For example:\n" + - " *

\n" +
-            "     * Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n"
-            +
-            "     * 
\n" + - " *
    \n" + - " *
  • Lorem ipsum dolor sit amet, consectetur adipiscing elit Lorem ipsum dolor sit amet, consectetur adipiscing elit consectetur adipiscing
  • \n" - + - " *
  • Lorem ipsum dolor sit amet, consectetur adipiscing elit Lorem ipsum dolor sit amet, consectetur adipiscing elit consectetur adipiscing
  • \n" - + - " *
\n" + - " */\n" + - " public Optional getPreformattedText() {\n" + - " return Optional.ofNullable(preformattedText);\n" + - " }"; + " * Documentation includes preformatted text that should not be messed with. This sentence should still be partially\n" + + + " * wrapped.\n" + + " * For example:\n" + + " *
\n" +
+                "     * Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n"
+                +
+                "     * 
\n" + + " *
    \n" + + " *
  • Lorem ipsum dolor sit amet, consectetur adipiscing elit Lorem ipsum dolor sit amet, consectetur adipiscing elit consectetur adipiscing
  • \n" + + + " *
  • Lorem ipsum dolor sit amet, consectetur adipiscing elit Lorem ipsum dolor sit amet, consectetur adipiscing elit consectetur adipiscing
  • \n" + + + " *
\n" + + " */\n" + + " public Optional getPreformattedText() {\n" + + " return Optional.ofNullable(preformattedText);\n" + + " }"; assertTrue(fileContents.contains(expected)); } @@ -103,11 +103,11 @@ void doesNotFormatContentInsideHtmlTags() { void deprecatedAnnotationAndNoteOnClass() { String fileContents = getFileContentsFromShapeName("DeprecatedStructure", true); String expected = "/**\n" + - " * @deprecated As of yesterday. A message\n" + - " */\n" + - "@Deprecated\n" + - "@SmithyGenerated\n" + - "public final class DeprecatedStructureTrait"; + " * @deprecated As of yesterday. A message\n" + + " */\n" + + "@Deprecated\n" + + "@SmithyGenerated\n" + + "public final class DeprecatedStructureTrait"; assertTrue(fileContents.contains(expected)); } @@ -115,10 +115,10 @@ void deprecatedAnnotationAndNoteOnClass() { void deprecatedAnnotationAndNoteOnMember() { String fileContents = getFileContentsFromShapeName("DeprecatedStructure", true); String expected = " /**\n" + - " * @deprecated As of yesterday. A message\n" + - " */\n" + - " @Deprecated\n" + - " public Optional getDeprecatedMember() {"; + " * @deprecated As of yesterday. A message\n" + + " */\n" + + " @Deprecated\n" + + " public Optional getDeprecatedMember() {"; assertTrue(fileContents.contains(expected)); } @@ -126,12 +126,12 @@ void deprecatedAnnotationAndNoteOnMember() { void deprecatedAnnotationAndNoteWithDocsOnMember() { String fileContents = getFileContentsFromShapeName("DeprecatedStructure", true); String expected = " /**\n" + - " * Has docs in addition to deprecated\n" + - " *\n" + - " * @deprecated As of yesterday. A message\n" + - " */\n" + - " @Deprecated\n" + - " public Optional getDeprecatedWithDocs() {"; + " * Has docs in addition to deprecated\n" + + " *\n" + + " * @deprecated As of yesterday. A message\n" + + " */\n" + + " @Deprecated\n" + + " public Optional getDeprecatedWithDocs() {"; assertTrue(fileContents.contains(expected)); } @@ -139,10 +139,10 @@ void deprecatedAnnotationAndNoteWithDocsOnMember() { void sinceJavadocTagAddedToClass() { String fileContents = getFileContentsFromShapeName("SinceStructure", true); String expected = "/**\n" + - " * @since 1.2\n" + - " */\n" + - "@SmithyGenerated\n" + - "public final class SinceStructureTrait"; + " * @since 1.2\n" + + " */\n" + + "@SmithyGenerated\n" + + "public final class SinceStructureTrait"; assertTrue(fileContents.contains(expected)); } @@ -150,9 +150,9 @@ void sinceJavadocTagAddedToClass() { void sinceJavaDocOnMember() { String fileContents = getFileContentsFromShapeName("SinceStructure", true); String expected = " /**\n" + - " * @since 1.2\n" + - " */\n" + - " public Optional getSinceMember() {"; + " * @since 1.2\n" + + " */\n" + + " public Optional getSinceMember() {"; assertTrue(fileContents.contains(expected)); } @@ -160,11 +160,11 @@ void sinceJavaDocOnMember() { void externalDocumentationOnClass() { String fileContents = getFileContentsFromShapeName("ExternalDocumentation", true); String expected = "/**\n" + - " * @see
Example\n" + - " * @see Example2\n" + - " */\n" + - "@SmithyGenerated\n" + - "public final class ExternalDocumentationTrait extends AbstractTrait"; + " * @see Example\n" + + " * @see Example2\n" + + " */\n" + + "@SmithyGenerated\n" + + "public final class ExternalDocumentationTrait extends AbstractTrait"; assertTrue(fileContents.contains(expected)); } @@ -173,9 +173,9 @@ void externalDocumentationOnClass() { void externalDocumentationOnMember() { String fileContents = getFileContentsFromShapeName("ExternalDocumentation", true); String expected = " /**\n" + - " * @see Example\n" + - " */\n" + - " public Optional getMemberWithExternalDocumentation() {"; + " * @see Example\n" + + " */\n" + + " public Optional getMemberWithExternalDocumentation() {"; assertTrue(fileContents.contains(expected)); } @@ -183,16 +183,16 @@ void externalDocumentationOnMember() { void allDocumentationIncludedTogetherOnClass() { String fileContents = getFileContentsFromShapeName("Rollup", true); String expected = "/**\n" + - " * This structure applies all documentation traits\n" + - " *\n" + - " * @see Example\n" + - " * @since 4.5\n" + - " * @deprecated As of sometime.\n" + - " */\n" + - "@SmithyUnstableApi\n" + - "@Deprecated\n" + - "@SmithyGenerated\n" + - "public final class RollupTrait extends AbstractTrait"; + " * This structure applies all documentation traits\n" + + " *\n" + + " * @see Example\n" + + " * @since 4.5\n" + + " * @deprecated As of sometime.\n" + + " */\n" + + "@SmithyUnstableApi\n" + + "@Deprecated\n" + + "@SmithyGenerated\n" + + "public final class RollupTrait extends AbstractTrait"; assertTrue(fileContents.contains(expected)); } @@ -200,15 +200,15 @@ void allDocumentationIncludedTogetherOnClass() { void allDocumentationIncludedTogetherOnMember() { String fileContents = getFileContentsFromShapeName("Rollup", true); String expected = " /**\n" + - " * This member applies all documentation traits\n" + - " *\n" + - " * @see Example\n" + - " * @since 4.5\n" + - " * @deprecated As of sometime.\n" + - " */\n" + - " @SmithyUnstableApi\n" + - " @Deprecated\n" + - " public Optional getRollupMember() {"; + " * This member applies all documentation traits\n" + + " *\n" + + " * @see Example\n" + + " * @since 4.5\n" + + " * @deprecated As of sometime.\n" + + " */\n" + + " @SmithyUnstableApi\n" + + " @Deprecated\n" + + " public Optional getRollupMember() {"; assertTrue(fileContents.contains(expected)); } @@ -216,15 +216,15 @@ void allDocumentationIncludedTogetherOnMember() { void allDocumentationIncludedTogetherEnumVariant() { String fileContents = getFileContentsFromShapeName("EnumVariantsTest", true); String expected = " /**\n" + - " * Just a documented variant\n" + - " *\n" + - " * @see Example\n" + - " * @since 4.5\n" + - " * @deprecated Really. Dont use this.\n" + - " */\n" + - " @SmithyUnstableApi\n" + - " @Deprecated\n" + - " A(\"A\"),"; + " * Just a documented variant\n" + + " *\n" + + " * @see Example\n" + + " * @since 4.5\n" + + " * @deprecated Really. Dont use this.\n" + + " */\n" + + " @SmithyUnstableApi\n" + + " @Deprecated\n" + + " A(\"A\"),"; assertTrue(fileContents.contains(expected)); } diff --git a/smithy-utils/src/main/java/software/amazon/smithy/utils/AbstractCodeWriter.java b/smithy-utils/src/main/java/software/amazon/smithy/utils/AbstractCodeWriter.java index 170c589858e..1f100472a97 100644 --- a/smithy-utils/src/main/java/software/amazon/smithy/utils/AbstractCodeWriter.java +++ b/smithy-utils/src/main/java/software/amazon/smithy/utils/AbstractCodeWriter.java @@ -568,52 +568,52 @@ public abstract class AbstractCodeWriter> { // Valid formatter characters that can be registered. Must be sorted for binary search to work. static final char[] VALID_FORMATTER_CHARS = { - '!', - '%', - '&', - '*', - '+', - ',', - '-', - '.', - ';', - '=', - '@', - 'A', - 'B', - 'C', - 'D', - 'E', - 'F', - 'G', - 'H', - 'I', - 'J', - 'K', - 'L', - 'M', - 'N', - 'O', - 'P', - 'Q', - 'R', - 'S', - 'T', - 'U', - 'V', - 'W', - 'X', - 'Y', - 'Z', - '_', - '`'}; + '!', + '%', + '&', + '*', + '+', + ',', + '-', + '.', + ';', + '=', + '@', + 'A', + 'B', + 'C', + 'D', + 'E', + 'F', + 'G', + 'H', + 'I', + 'J', + 'K', + 'L', + 'M', + 'N', + 'O', + 'P', + 'Q', + 'R', + 'S', + 'T', + 'U', + 'V', + 'W', + 'X', + 'Y', + 'Z', + '_', + '`'}; private static final Pattern LINES = Pattern.compile("\\r?\\n"); private static final Map> DEFAULT_FORMATTERS = MapUtils.of( - 'L', - (s, i) -> formatLiteral(s), - 'S', - (s, i) -> StringUtils.escapeJavaString(formatLiteral(s), i) + 'L', + (s, i) -> formatLiteral(s), + 'S', + (s, i) -> StringUtils.escapeJavaString(formatLiteral(s), i) ); private final Deque states = new ArrayDeque<>(); @@ -1509,11 +1509,11 @@ public T openBlock(String textBeforeNewline, String textAfterNewline, Object arg * @return Returns this. */ public T openBlock( - String textBeforeNewline, - String textAfterNewline, - Object arg1, - Object arg2, - Runnable f + String textBeforeNewline, + String textAfterNewline, + Object arg1, + Object arg2, + Runnable f ) { return openBlock(textBeforeNewline, textAfterNewline, new Object[]{arg1, arg2}, f); } @@ -1532,12 +1532,12 @@ public T openBlock( * @return Returns this. */ public T openBlock( - String textBeforeNewline, - String textAfterNewline, - Object arg1, - Object arg2, - Object arg3, - Runnable f + String textBeforeNewline, + String textAfterNewline, + Object arg1, + Object arg2, + Object arg3, + Runnable f ) { return openBlock(textBeforeNewline, textAfterNewline, new Object[]{arg1, arg2, arg3}, f); } @@ -1557,13 +1557,13 @@ public T openBlock( * @return Returns this. */ public T openBlock( - String textBeforeNewline, - String textAfterNewline, - Object arg1, - Object arg2, - Object arg3, - Object arg4, - Runnable f + String textBeforeNewline, + String textAfterNewline, + Object arg1, + Object arg2, + Object arg3, + Object arg4, + Runnable f ) { return openBlock(textBeforeNewline, textAfterNewline, new Object[]{arg1, arg2, arg3, arg4}, f); } @@ -1584,14 +1584,14 @@ public T openBlock( * @return Returns this. */ public T openBlock( - String textBeforeNewline, - String textAfterNewline, - Object arg1, - Object arg2, - Object arg3, - Object arg4, - Object arg5, - Runnable f + String textBeforeNewline, + String textAfterNewline, + Object arg1, + Object arg2, + Object arg3, + Object arg4, + Object arg5, + Runnable f ) { return openBlock(textBeforeNewline, textAfterNewline, new Object[]{arg1, arg2, arg3, arg4, arg5}, f); } @@ -1674,14 +1674,14 @@ private String findAndFormatStackTraceElement(String content, boolean inline) { protected boolean isStackTraceRelevant(StackTraceElement e) { String normalized = e.getClassName().replace("$", "."); return !normalized.startsWith("java.") - // Ignore writes made by AbstractCodeWriter or AbstractCodeWriter$State. - && !normalized.startsWith(AbstractCodeWriter.class.getCanonicalName()) - // Ignore writes made by subclasses of this class. - && !normalized.startsWith(getClass().getCanonicalName()) - // Ignore writes made by SimpleCodeWriter. - && !normalized.equals(SimpleCodeWriter.class.getCanonicalName()) - // Ignore any writes made by the well-known SymbolWriter from smithy-codegen-core. - && !normalized.equals("software.amazon.smithy.utils.SymbolWriter"); + // Ignore writes made by AbstractCodeWriter or AbstractCodeWriter$State. + && !normalized.startsWith(AbstractCodeWriter.class.getCanonicalName()) + // Ignore writes made by subclasses of this class. + && !normalized.startsWith(getClass().getCanonicalName()) + // Ignore writes made by SimpleCodeWriter. + && !normalized.equals(SimpleCodeWriter.class.getCanonicalName()) + // Ignore any writes made by the well-known SymbolWriter from smithy-codegen-core. + && !normalized.equals("software.amazon.smithy.utils.SymbolWriter"); } /** @@ -1854,7 +1854,7 @@ public T ensureNewline() { private boolean builderEndsWith(StringBuilder builder, String check) { return builder.length() > check.length() - && builder.substring(builder.length() - check.length(), builder.length()).equals(check); + && builder.substring(builder.length() - check.length(), builder.length()).equals(check); } /** @@ -1995,10 +1995,10 @@ public Object getContext(String key) { return method.invoke(state.sectionValue); } catch (ReflectiveOperationException e) { String message = String.format( - "Unable to get context '%s' from a matching method of the current CodeSection: %s %s", - key, - e.getCause() != null ? e.getCause().getMessage() : e.getMessage(), - getDebugInfo() + "Unable to get context '%s' from a matching method of the current CodeSection: %s %s", + key, + e.getCause() != null ? e.getCause().getMessage() : e.getMessage(), + getDebugInfo() ); throw new RuntimeException(message, e); } @@ -2037,13 +2037,13 @@ public C getContext(String key, Class type) { return (C) value; } else { throw new ClassCastException( - String.format( - "Expected context value '%s' to be an instance of %s, but found %s %s", - key, - type.getName(), - value.getClass().getName(), - getDebugInfo() - ) + String.format( + "Expected context value '%s' to be an instance of %s, but found %s %s", + key, + type.getName(), + value.getClass().getName(), + getDebugInfo() + ) ); } } @@ -2102,13 +2102,13 @@ String applyFormatter(char identifier, Object value) { return removeTrailingNewline(expandSection(section, "", ignore -> consumer.accept((T) this))); } else { throw new ClassCastException( - String.format( - "Expected value for 'C' formatter to be an instance of %s or %s, but found %s %s", - Runnable.class.getName(), - Consumer.class.getName(), - value == null ? "null" : value.getClass().getName(), - getDebugInfo() - ) + String.format( + "Expected value for 'C' formatter to be an instance of %s or %s, but found %s %s", + Runnable.class.getName(), + Consumer.class.getName(), + value == null ? "null" : value.getClass().getName(), + getDebugInfo() + ) ); } } else { diff --git a/smithy-utils/src/main/java/software/amazon/smithy/utils/BuilderRef.java b/smithy-utils/src/main/java/software/amazon/smithy/utils/BuilderRef.java index c0ca6e8f7cf..f20b3a0c111 100644 --- a/smithy-utils/src/main/java/software/amazon/smithy/utils/BuilderRef.java +++ b/smithy-utils/src/main/java/software/amazon/smithy/utils/BuilderRef.java @@ -86,10 +86,10 @@ public interface BuilderRef extends CopyOnWriteRef { */ static BuilderRef> forUnorderedMap() { return new DefaultBuilderRef<>( - HashMap::new, - HashMap::new, - Collections::unmodifiableMap, - Collections::emptyMap + HashMap::new, + HashMap::new, + Collections::unmodifiableMap, + Collections::emptyMap ); } @@ -102,10 +102,10 @@ static BuilderRef> forUnorderedMap() { */ static BuilderRef> forOrderedMap() { return new DefaultBuilderRef<>( - LinkedHashMap::new, - LinkedHashMap::new, - Collections::unmodifiableMap, - Collections::emptyMap + LinkedHashMap::new, + LinkedHashMap::new, + Collections::unmodifiableMap, + Collections::emptyMap ); } @@ -117,10 +117,10 @@ static BuilderRef> forOrderedMap() { */ static BuilderRef> forList() { return new DefaultBuilderRef<>( - ArrayList::new, - ArrayList::new, - Collections::unmodifiableList, - Collections::emptyList + ArrayList::new, + ArrayList::new, + Collections::unmodifiableList, + Collections::emptyList ); } @@ -132,10 +132,10 @@ static BuilderRef> forList() { */ static BuilderRef> forUnorderedSet() { return new DefaultBuilderRef<>( - HashSet::new, - HashSet::new, - Collections::unmodifiableSet, - Collections::emptySet + HashSet::new, + HashSet::new, + Collections::unmodifiableSet, + Collections::emptySet ); } @@ -147,10 +147,10 @@ static BuilderRef> forUnorderedSet() { */ static BuilderRef> forOrderedSet() { return new DefaultBuilderRef<>( - LinkedHashSet::new, - LinkedHashSet::new, - Collections::unmodifiableSet, - Collections::emptySet + LinkedHashSet::new, + LinkedHashSet::new, + Collections::unmodifiableSet, + Collections::emptySet ); } } diff --git a/smithy-utils/src/main/java/software/amazon/smithy/utils/CodeFormatter.java b/smithy-utils/src/main/java/software/amazon/smithy/utils/CodeFormatter.java index 25c6af2d26c..1dfafce82fd 100644 --- a/smithy-utils/src/main/java/software/amazon/smithy/utils/CodeFormatter.java +++ b/smithy-utils/src/main/java/software/amazon/smithy/utils/CodeFormatter.java @@ -88,9 +88,9 @@ static Operation stringSlice(CharSequence source, int start, int end) { // should only be evaluated inside conditions that evaluate to true. This ensures that formatters // with side effects don't have their side effects enacted when a condition is not evaluated. static Operation formatted( - Function, Object> valueGetter, - char formatter, - Supplier errorMessage + Function, Object> valueGetter, + char formatter, + Supplier errorMessage ) { return (sink, writer) -> { Object value = valueGetter.apply(writer); @@ -394,13 +394,13 @@ private Operation parse() { } throw new IllegalArgumentException( - "Unclosed parse conditional blocks: [" - + blocks.stream() - // Don't include the root block. - .filter(b -> !b.variable().isEmpty()) - .map(BlockOperation::variable) - .collect(Collectors.joining(", ")) - + "]" + "Unclosed parse conditional blocks: [" + + blocks.stream() + // Don't include the root block. + .filter(b -> !b.variable().isEmpty()) + .map(BlockOperation::variable) + .collect(Collectors.joining(", ")) + + "]" ); } @@ -446,7 +446,7 @@ private void parseBracedArgument(int pendingTextStart) { parser.skip(); if (pendingTextStart > -1) { while (startPosition > pendingTextStart - && Character.isWhitespace(parser.input().charAt(startPosition - 1))) { + && Character.isWhitespace(parser.input().charAt(startPosition - 1))) { startPosition--; } } @@ -484,8 +484,8 @@ private void parseBracedArgument(int pendingTextStart) { throw error("Cannot strip leading whitespace with '~' when using inline block alignment '|'"); } String staticWhitespace = isAllLeadingWhitespaceOnLine(startPosition, startColumn) - ? template.substring(startPosition - startColumn, startPosition) - : null; + ? template.substring(startPosition - startColumn, startPosition) + : null; parser.expect('|'); operation = Operation.block(operation, staticWhitespace); } @@ -578,11 +578,11 @@ private void handleConditionalOnLine(int pendingTextStart, int startPosition, in } else if (isAllLeadingWhitespaceOnLine(startPosition, startColumn)) { if (pendingTextStart > -1) { pushOperation( - Operation.stringSlice( - parser.input(), - pendingTextStart, - startPosition - startColumn - ) + Operation.stringSlice( + parser.input(), + pendingTextStart, + startPosition - startColumn + ) ); } parser.skip(); @@ -605,8 +605,8 @@ private void popBlock(int pendingTextStart, int startPosition, int startColumn) BlockOperation block = blocks.pop(); if (!block.variable().equals(name)) { throw new IllegalArgumentException( - "Invalid closing tag: '" + name + "'. Expected: '" - + block.variable() + "'" + "Invalid closing tag: '" + name + "'. Expected: '" + + block.variable() + "'" ); } @@ -637,16 +637,16 @@ private Operation parseNormalArgument() { // The error message needs to be created here and given to the operation in way that it can // throw with an appropriate message. return Operation.formatted( - getter, - identifier, - () -> createErrorMessage( - String.format( - "Syntax error at line %d column %d: Unknown formatter `%c` found in format string", - line, - column, - identifier + getter, + identifier, + () -> createErrorMessage( + String.format( + "Syntax error at line %d column %d: Unknown formatter `%c` found in format string", + line, + column, + identifier + ) ) - ) ); } @@ -684,11 +684,11 @@ private Function, Object> parseRelativeArgumentGetter() { private Object getPositionalArgument(int index) { if (index >= arguments.length) { throw error( - String.format( - "Given %d arguments but attempted to format index %d", - arguments.length, - index - ) + String.format( + "Given %d arguments but attempted to format index %d", + arguments.length, + index + ) ); } else { // Track the usage of the positional argument. @@ -710,11 +710,11 @@ private Function, Object> parsePositionalArgumentGetter() if (index < 0 || index >= arguments.length) { throw error( - String.format( - "Positional argument index %d out of range of provided %d arguments in format string", - index, - arguments.length - ) + String.format( + "Positional argument index %d out of range of provided %d arguments in format string", + index, + arguments.length + ) ); } @@ -730,12 +730,12 @@ private void ensureNameIsValid(String name) { private boolean isNameCharacter(int c) { return (c >= 'a' && c <= 'z') - || (c >= 'A' && c <= 'Z') - || (c >= '0' && c <= '9') - || c == '_' - || c == '.' - || c == '#' - || c == '$'; + || (c >= 'A' && c <= 'Z') + || (c >= '0' && c <= '9') + || c == '_' + || c == '.' + || c == '#' + || c == '$'; } } } diff --git a/smithy-utils/src/main/java/software/amazon/smithy/utils/CodeInterceptor.java b/smithy-utils/src/main/java/software/amazon/smithy/utils/CodeInterceptor.java index fa3760a2167..c747d89f773 100644 --- a/smithy-utils/src/main/java/software/amazon/smithy/utils/CodeInterceptor.java +++ b/smithy-utils/src/main/java/software/amazon/smithy/utils/CodeInterceptor.java @@ -77,8 +77,8 @@ default boolean isIntercepted(S section) { * @return Returns the created Appender. */ static > CodeInterceptor appender( - Class type, - BiConsumer appender + Class type, + BiConsumer appender ) { return new Appender() { @Override @@ -156,8 +156,8 @@ default void write(W writer, String previousText, S section) { * @return Returns the created interceptor. */ static > CodeInterceptor forName( - String sectionName, - BiConsumer consumer + String sectionName, + BiConsumer consumer ) { return new CodeInterceptor() { @Override diff --git a/smithy-utils/src/main/java/software/amazon/smithy/utils/CodeWriter.java b/smithy-utils/src/main/java/software/amazon/smithy/utils/CodeWriter.java index 9e0dca8a354..9e8a3d0e08e 100644 --- a/smithy-utils/src/main/java/software/amazon/smithy/utils/CodeWriter.java +++ b/smithy-utils/src/main/java/software/amazon/smithy/utils/CodeWriter.java @@ -238,11 +238,11 @@ public CodeWriter openBlock(String textBeforeNewline, String textAfterNewline, O @Override public CodeWriter openBlock( - String textBeforeNewline, - String textAfterNewline, - Object arg1, - Object arg2, - Runnable f + String textBeforeNewline, + String textAfterNewline, + Object arg1, + Object arg2, + Runnable f ) { super.openBlock(textBeforeNewline, textAfterNewline, arg1, arg2, f); return this; @@ -250,12 +250,12 @@ public CodeWriter openBlock( @Override public CodeWriter openBlock( - String textBeforeNewline, - String textAfterNewline, - Object arg1, - Object arg2, - Object arg3, - Runnable f + String textBeforeNewline, + String textAfterNewline, + Object arg1, + Object arg2, + Object arg3, + Runnable f ) { super.openBlock(textBeforeNewline, textAfterNewline, arg1, arg2, arg3, f); return this; @@ -263,13 +263,13 @@ public CodeWriter openBlock( @Override public CodeWriter openBlock( - String textBeforeNewline, - String textAfterNewline, - Object arg1, - Object arg2, - Object arg3, - Object arg4, - Runnable f + String textBeforeNewline, + String textAfterNewline, + Object arg1, + Object arg2, + Object arg3, + Object arg4, + Runnable f ) { super.openBlock(textBeforeNewline, textAfterNewline, arg1, arg2, arg3, arg4, f); return this; @@ -277,14 +277,14 @@ public CodeWriter openBlock( @Override public CodeWriter openBlock( - String textBeforeNewline, - String textAfterNewline, - Object arg1, - Object arg2, - Object arg3, - Object arg4, - Object arg5, - Runnable f + String textBeforeNewline, + String textAfterNewline, + Object arg1, + Object arg2, + Object arg3, + Object arg4, + Object arg5, + Runnable f ) { super.openBlock(textBeforeNewline, textAfterNewline, arg1, arg2, arg3, arg4, arg5, f); return this; diff --git a/smithy-utils/src/main/java/software/amazon/smithy/utils/DefaultBuilderRef.java b/smithy-utils/src/main/java/software/amazon/smithy/utils/DefaultBuilderRef.java index ea29e5656e5..6efbf7429e5 100644 --- a/smithy-utils/src/main/java/software/amazon/smithy/utils/DefaultBuilderRef.java +++ b/smithy-utils/src/main/java/software/amazon/smithy/utils/DefaultBuilderRef.java @@ -27,10 +27,10 @@ final class DefaultBuilderRef implements BuilderRef { private T borrowed; DefaultBuilderRef( - Supplier ctor, - Function copyCtor, - Function immutableWrapper, - Supplier emptyCtorOptimization + Supplier ctor, + Function copyCtor, + Function immutableWrapper, + Supplier emptyCtorOptimization ) { this.ctor = ctor; this.copyCtor = copyCtor; @@ -120,15 +120,15 @@ private T applyCopyCtor(T value) { private T applyImmutableWrapper(T value) { return Objects.requireNonNull( - immutableWrapper.apply(value), - "BuilderRef 'immutableWrapper' must not return null" + immutableWrapper.apply(value), + "BuilderRef 'immutableWrapper' must not return null" ); } private T applyEmptyCtorOptimization() { return Objects.requireNonNull( - emptyCtorOptimization.get(), - "BuilderRef 'emptyCtorOptimization' must not return null" + emptyCtorOptimization.get(), + "BuilderRef 'emptyCtorOptimization' must not return null" ); } } diff --git a/smithy-utils/src/main/java/software/amazon/smithy/utils/IoUtils.java b/smithy-utils/src/main/java/software/amazon/smithy/utils/IoUtils.java index ae03ecaacd4..3bfc77a0dd1 100644 --- a/smithy-utils/src/main/java/software/amazon/smithy/utils/IoUtils.java +++ b/smithy-utils/src/main/java/software/amazon/smithy/utils/IoUtils.java @@ -170,12 +170,12 @@ public static String runCommand(String command, Path directory) { if (exitValue != 0) { throw new RuntimeException( - String.format( - "Command `%s` failed with exit code %d and output:%n%n%s", - command, - exitValue, - sb - ) + String.format( + "Command `%s` failed with exit code %d and output:%n%n%s", + command, + exitValue, + sb + ) ); } @@ -255,15 +255,15 @@ public static int runCommand(List args, Path directory, Appendable outpu * @return Returns the exit code of the process. */ public static int runCommand( - List args, - Path directory, - InputStream input, - Appendable output, - Map env + List args, + Path directory, + InputStream input, + Appendable output, + Map env ) { ProcessBuilder processBuilder = new ProcessBuilder(args) - .directory(Objects.requireNonNull(directory.toFile(), "Process directory cannot be null")) - .redirectErrorStream(true); + .directory(Objects.requireNonNull(directory.toFile(), "Process directory cannot be null")) + .redirectErrorStream(true); processBuilder.environment().putAll(env); try { @@ -276,9 +276,9 @@ public static int runCommand( } try ( - BufferedReader bufferedStdoutReader = new BufferedReader( - new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8) - ) + BufferedReader bufferedStdoutReader = new BufferedReader( + new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8) + ) ) { String line; while ((line = bufferedStdoutReader.readLine()) != null) { @@ -342,9 +342,9 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { return Files.isSymbolicLink(dir) - // Don't delete symlink files, just delete the symlink. - ? FileVisitResult.SKIP_SUBTREE - : FileVisitResult.CONTINUE; + // Don't delete symlink files, just delete the symlink. + ? FileVisitResult.SKIP_SUBTREE + : FileVisitResult.CONTINUE; } @Override @@ -368,13 +368,13 @@ public static void copyDir(Path src, Path dest) { Files.walkFileTree(src, new CopyFileVisitor(src, dest)); } catch (IOException e) { throw new RuntimeException( - String.format( - "Error copying directory from \"%s\" to \"%s\": %s", - src, - dest, - e.getMessage() - ), - e + String.format( + "Error copying directory from \"%s\" to \"%s\": %s", + src, + dest, + e.getMessage() + ), + e ); } } diff --git a/smithy-utils/src/main/java/software/amazon/smithy/utils/MapUtils.java b/smithy-utils/src/main/java/software/amazon/smithy/utils/MapUtils.java index e6e23b589e4..c266da370c5 100644 --- a/smithy-utils/src/main/java/software/amazon/smithy/utils/MapUtils.java +++ b/smithy-utils/src/main/java/software/amazon/smithy/utils/MapUtils.java @@ -188,18 +188,18 @@ public static Map of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4 * @throws NullPointerException if any key or value is {@code null} */ public static Map of( - K k1, - V v1, - K k2, - V v2, - K k3, - V v3, - K k4, - V v4, - K k5, - V v5, - K k6, - V v6 + K k1, + V v1, + K k2, + V v2, + K k3, + V v3, + K k4, + V v4, + K k5, + V v5, + K k6, + V v6 ) { Map result = new HashMap<>(6); result.put(k1, v1); @@ -235,20 +235,20 @@ public static Map of( * @throws NullPointerException if any key or value is {@code null} */ public static Map of( - K k1, - V v1, - K k2, - V v2, - K k3, - V v3, - K k4, - V v4, - K k5, - V v5, - K k6, - V v6, - K k7, - V v7 + K k1, + V v1, + K k2, + V v2, + K k3, + V v3, + K k4, + V v4, + K k5, + V v5, + K k6, + V v6, + K k7, + V v7 ) { Map result = new HashMap<>(7); result.put(k1, v1); @@ -287,22 +287,22 @@ public static Map of( * @throws NullPointerException if any key or value is {@code null} */ public static Map of( - K k1, - V v1, - K k2, - V v2, - K k3, - V v3, - K k4, - V v4, - K k5, - V v5, - K k6, - V v6, - K k7, - V v7, - K k8, - V v8 + K k1, + V v1, + K k2, + V v2, + K k3, + V v3, + K k4, + V v4, + K k5, + V v5, + K k6, + V v6, + K k7, + V v7, + K k8, + V v8 ) { Map result = new HashMap<>(8); result.put(k1, v1); @@ -344,24 +344,24 @@ public static Map of( * @throws NullPointerException if any key or value is {@code null} */ public static Map of( - K k1, - V v1, - K k2, - V v2, - K k3, - V v3, - K k4, - V v4, - K k5, - V v5, - K k6, - V v6, - K k7, - V v7, - K k8, - V v8, - K k9, - V v9 + K k1, + V v1, + K k2, + V v2, + K k3, + V v3, + K k4, + V v4, + K k5, + V v5, + K k6, + V v6, + K k7, + V v7, + K k8, + V v8, + K k9, + V v9 ) { Map result = new HashMap<>(9); result.put(k1, v1); @@ -406,26 +406,26 @@ public static Map of( * @throws NullPointerException if any key or value is {@code null} */ public static Map of( - K k1, - V v1, - K k2, - V v2, - K k3, - V v3, - K k4, - V v4, - K k5, - V v5, - K k6, - V v6, - K k7, - V v7, - K k8, - V v8, - K k9, - V v9, - K k10, - V v10 + K k1, + V v1, + K k2, + V v2, + K k3, + V v3, + K k4, + V v4, + K k5, + V v5, + K k6, + V v6, + K k7, + V v7, + K k8, + V v8, + K k9, + V v9, + K k10, + V v10 ) { Map result = new HashMap<>(10); result.put(k1, v1); @@ -494,15 +494,15 @@ public static Map ofEntries(Map.Entry... */ @SuppressWarnings("unchecked") public static Collector> toUnmodifiableMap( - Function keyMapper, - Function valueMapper + Function keyMapper, + Function valueMapper ) { return Collectors.collectingAndThen( - Collectors.toMap( - Objects.requireNonNull(keyMapper, "keyMapper"), - Objects.requireNonNull(valueMapper, "valueMapper") - ), - Collections::unmodifiableMap + Collectors.toMap( + Objects.requireNonNull(keyMapper, "keyMapper"), + Objects.requireNonNull(valueMapper, "valueMapper") + ), + Collections::unmodifiableMap ); } } diff --git a/smithy-utils/src/main/java/software/amazon/smithy/utils/MediaType.java b/smithy-utils/src/main/java/software/amazon/smithy/utils/MediaType.java index 60fbdd34d6b..d82789ae829 100644 --- a/smithy-utils/src/main/java/software/amazon/smithy/utils/MediaType.java +++ b/smithy-utils/src/main/java/software/amazon/smithy/utils/MediaType.java @@ -58,7 +58,7 @@ public static MediaType from(String value) { public static boolean isJson(String mediaType) { MediaType type = from(mediaType); return (type.getType().equals("application") && type.getSubtypeWithoutSuffix().equals("json")) - || type.getSuffix().filter(s -> s.equals("json")).isPresent(); + || type.getSuffix().filter(s -> s.equals("json")).isPresent(); } /** @@ -115,8 +115,8 @@ public Map getParameters() { public Optional getSuffix() { int position = subtype.lastIndexOf('+'); return position == -1 || position == subtype.length() - 1 - ? Optional.empty() - : Optional.of(subtype.substring(position + 1)); + ? Optional.empty() + : Optional.of(subtype.substring(position + 1)); } @Override @@ -133,8 +133,8 @@ public boolean equals(Object o) { } MediaType mediaType = (MediaType) o; return mediaType.type.equals(type) - && mediaType.subtype.equals(subtype) - && mediaType.parameters.equals(parameters); + && mediaType.subtype.equals(subtype) + && mediaType.parameters.equals(parameters); } @Override @@ -205,8 +205,8 @@ private void parse() { String name = parseToken().toLowerCase(Locale.US); expect('='); String value = peek() == '"' - ? parseQuotedString() - : parseToken(); + ? parseQuotedString() + : parseToken(); parameters.put(name, value); ws(); } diff --git a/smithy-utils/src/main/java/software/amazon/smithy/utils/SimpleParser.java b/smithy-utils/src/main/java/software/amazon/smithy/utils/SimpleParser.java index b64b28e7d24..548391c2e92 100644 --- a/smithy-utils/src/main/java/software/amazon/smithy/utils/SimpleParser.java +++ b/smithy-utils/src/main/java/software/amazon/smithy/utils/SimpleParser.java @@ -184,8 +184,8 @@ public final char expect(char... tokens) { } StringBuilder message = new StringBuilder("Found '") - .append(peekSingleCharForMessage()) - .append("', but expected one of the following tokens:"); + .append(peekSingleCharForMessage()) + .append("', but expected one of the following tokens:"); for (char c : tokens) { message.append(' ').append('\'').append(c).append('\''); } diff --git a/smithy-utils/src/main/java/software/amazon/smithy/utils/StringUtils.java b/smithy-utils/src/main/java/software/amazon/smithy/utils/StringUtils.java index ff5f2c5c56a..5d3c4457327 100644 --- a/smithy-utils/src/main/java/software/amazon/smithy/utils/StringUtils.java +++ b/smithy-utils/src/main/java/software/amazon/smithy/utils/StringUtils.java @@ -1179,10 +1179,10 @@ public static String wrap(final String str, final int wrapLength) { * @see Source */ public static String wrap( - final String str, - final int wrapLength, - final String newLineStr, - final boolean wrapLongWords + final String str, + final int wrapLength, + final String newLineStr, + final boolean wrapLongWords ) { return wrap(str, wrapLength, newLineStr, wrapLongWords, " "); } @@ -1281,11 +1281,11 @@ public static String wrap( * @see Source */ public static String wrap( - final String str, - int wrapLength, - String newLineStr, - final boolean wrapLongWords, - String wrapOn + final String str, + int wrapLength, + String newLineStr, + final boolean wrapLongWords, + String wrapOn ) { if (str == null) { return null; @@ -1308,10 +1308,10 @@ public static String wrap( while (offset < inputLineLength) { int spaceToWrapAt = -1; Matcher matcher = patternToWrapOn.matcher( - str.substring( - offset, - Math.min((int) Math.min(Integer.MAX_VALUE, offset + wrapLength + 1L), inputLineLength) - ) + str.substring( + offset, + Math.min((int) Math.min(Integer.MAX_VALUE, offset + wrapLength + 1L), inputLineLength) + ) ); if (matcher.find()) { if (matcher.start() == 0) { @@ -1568,11 +1568,11 @@ public static int levenshteinDistance(CharSequence left, CharSequence right, fin // compute stripe indices, constrain to array size final int min = Math.max(1, j - threshold); final int max = j > Integer.MAX_VALUE - threshold - ? n - : Math.min( - n, - j + threshold - ); + ? n + : Math.min( + n, + j + threshold + ); // ignore entry left of leftmost if (min > 1) { diff --git a/smithy-utils/src/test/java/software/amazon/smithy/utils/CodeFormatterTest.java b/smithy-utils/src/test/java/software/amazon/smithy/utils/CodeFormatterTest.java index 71bb52a17fc..37e0f89a680 100644 --- a/smithy-utils/src/test/java/software/amazon/smithy/utils/CodeFormatterTest.java +++ b/smithy-utils/src/test/java/software/amazon/smithy/utils/CodeFormatterTest.java @@ -164,18 +164,18 @@ public void formatsMultipleDigitPositionalLiterals() { SimpleCodeWriter writer = createWriter(); writer.putFormatter('L', CodeFormatterTest::valueOf); String result = writer.format( - "$1L $2L $3L $4L $5L $6L $7L $8L $9L $10L $11L", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - "10", - "11" + "$1L $2L $3L $4L $5L $6L $7L $8L $9L $10L $11L", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "10", + "11" ); assertThat(result, equalTo("1 2 3 4 5 6 7 8 9 10 11")); @@ -191,11 +191,11 @@ public void performsPositionalBoundsChecking() { }); assertThat( - e.getMessage(), - containsString( - "Positional argument index 0 out of range of provided 0 arguments " - + "in format string" - ) + e.getMessage(), + containsString( + "Positional argument index 0 out of range of provided 0 arguments " + + "in format string" + ) ); } @@ -444,11 +444,11 @@ public void expandsAlignedRelativeFormattersWithCarriageReturns() { public void expandsAlignedBlocksWithNewlines() { SimpleCodeWriter writer = new SimpleCodeWriter(); writer.write( - "$1L() {\n" + - " ${2L|}\n" + - "}", - "method", - "// this\n// is a test." + "$1L() {\n" + + " ${2L|}\n" + + "}", + "method", + "// this\n// is a test." ); assertThat(writer.toString(), equalTo("method() {\n // this\n // is a test.\n}\n")); @@ -459,11 +459,11 @@ public void alignedBlocksComposeWithPrefixes() { SimpleCodeWriter writer = new SimpleCodeWriter(); writer.setNewlinePrefix("| "); writer.write( - "$1L() {\n" + - " ${2L|}\n" + - "}", - "method", - "// this\n// is a test." + "$1L() {\n" + + " ${2L|}\n" + + "}", + "method", + "// this\n// is a test." ); assertThat(writer.toString(), equalTo("| method() {\n| // this\n| // is a test.\n| }\n")); @@ -474,11 +474,11 @@ public void defaultCFormatterRequiresRunnableOrFunction() { RuntimeException e = Assertions.assertThrows(RuntimeException.class, () -> new CodeWriter().write("$C", "hi")); assertThat( - e.getMessage(), - containsString( - "Expected value for 'C' formatter to be an instance of " + Runnable.class.getName() - + " or " + Consumer.class.getName() + ", but found " + String.class.getName() - ) + e.getMessage(), + containsString( + "Expected value for 'C' formatter to be an instance of " + Runnable.class.getName() + + " or " + Consumer.class.getName() + ", but found " + String.class.getName() + ) ); } @@ -510,11 +510,11 @@ void write2(String text) { public void alignsBlocksWithStaticWhitespace() { SimpleCodeWriter writer = new SimpleCodeWriter(); writer.write( - "$1L() {\n" + - "\t\t${2L|}\n" + - "}", - "method", - "hi\nthere" + "$1L() {\n" + + "\t\t${2L|}\n" + + "}", + "method", + "hi\nthere" ); assertThat(writer.toString(), equalTo("method() {\n\t\thi\n\t\tthere\n}\n")); @@ -524,11 +524,11 @@ public void alignsBlocksWithStaticWhitespace() { public void alignsBlocksWithStaticAndSpecificWhitespace() { SimpleCodeWriter writer = new SimpleCodeWriter(); writer.write( - "$1L() {\n" + - "\t\t ${2L|}\n" + - "}", - "method", - "hi\nthere" + "$1L() {\n" + + "\t\t ${2L|}\n" + + "}", + "method", + "hi\nthere" ); assertThat(writer.toString(), equalTo("method() {\n\t\t hi\n\t\t there\n}\n")); @@ -546,16 +546,16 @@ public void canAlignNestedBlocks() { }); assertThat( - writer.toString(), - equalTo( - "a() {\n" - + "\t\tb() {\n" - + "\t\t\t\tc() {\n" - + "\t\t\t\t\t\t d\n" - + "\t\t\t\t}\n" - + "\t\t}\n" - + "}\n" - ) + writer.toString(), + equalTo( + "a() {\n" + + "\t\tb() {\n" + + "\t\t\t\tc() {\n" + + "\t\t\t\t\t\t d\n" + + "\t\t\t\t}\n" + + "\t\t}\n" + + "}\n" + ) ); } @@ -564,18 +564,18 @@ public void canProvideCustomLoopPrefixes() { SimpleCodeWriter writer = new SimpleCodeWriter().insertTrailingNewline(false); writer.putContext("foo", Arrays.asList("a", "b", "c")); writer.write( - "${#foo as k, v}\n" - + "${k:L} ${v:L} ${k.first:L} ${k.last:L}\n" - + "${/foo}" + "${#foo as k, v}\n" + + "${k:L} ${v:L} ${k.first:L} ${k.last:L}\n" + + "${/foo}" ); assertThat( - writer.toString(), - equalTo( - "0 a true false\n" - + "1 b false false\n" - + "2 c false true\n" - ) + writer.toString(), + equalTo( + "0 a true false\n" + + "1 b false false\n" + + "2 c false true\n" + ) ); } @@ -583,8 +583,8 @@ public void canProvideCustomLoopPrefixes() { public void validatesKeyBindingName() { SimpleCodeWriter writer = new SimpleCodeWriter().insertTrailingNewline(false); RuntimeException e = Assertions.assertThrows( - RuntimeException.class, - () -> writer.write("${#foo as 0a, v}${/foo}") + RuntimeException.class, + () -> writer.write("${#foo as 0a, v}${/foo}") ); assertThat(e.getMessage(), containsString("Invalid format expression name `0a`")); @@ -594,8 +594,8 @@ public void validatesKeyBindingName() { public void validatesValueBindingName() { SimpleCodeWriter writer = new SimpleCodeWriter().insertTrailingNewline(false); RuntimeException e = Assertions.assertThrows( - RuntimeException.class, - () -> writer.write("${#foo as k, 0v}${/foo}") + RuntimeException.class, + () -> writer.write("${#foo as k, 0v}${/foo}") ); assertThat(e.getMessage(), containsString("Invalid format expression name `0v`")); @@ -605,8 +605,8 @@ public void validatesValueBindingName() { public void requiresBothKeyAndValueBindingNamesWhenAnySet() { SimpleCodeWriter writer = new SimpleCodeWriter().insertTrailingNewline(false); RuntimeException e = Assertions.assertThrows( - RuntimeException.class, - () -> writer.write("${#foo as k}${/foo}") + RuntimeException.class, + () -> writer.write("${#foo as k}${/foo}") ); assertThat(e.getMessage(), containsString("Expected: ',', but found '}'")); @@ -617,26 +617,26 @@ public void canNestForLoops() { SimpleCodeWriter writer = new SimpleCodeWriter().insertTrailingNewline(false); writer.putContext("foo", Arrays.asList("a", "b", "c")); writer.write( - "${#foo as k1, v1}\n" - + "${#foo as k2, v2}\n" - + "${k1:L} ${v1:L}; ${k2:L} ${v2:L}\n" - + "${/foo}\n" - + "${/foo}" + "${#foo as k1, v1}\n" + + "${#foo as k2, v2}\n" + + "${k1:L} ${v1:L}; ${k2:L} ${v2:L}\n" + + "${/foo}\n" + + "${/foo}" ); assertThat( - writer.toString(), - equalTo( - "0 a; 0 a\n" - + "0 a; 1 b\n" - + "0 a; 2 c\n" - + "1 b; 0 a\n" - + "1 b; 1 b\n" - + "1 b; 2 c\n" - + "2 c; 0 a\n" - + "2 c; 1 b\n" - + "2 c; 2 c\n" - ) + writer.toString(), + equalTo( + "0 a; 0 a\n" + + "0 a; 1 b\n" + + "0 a; 2 c\n" + + "1 b; 0 a\n" + + "1 b; 1 b\n" + + "1 b; 2 c\n" + + "2 c; 0 a\n" + + "2 c; 1 b\n" + + "2 c; 2 c\n" + ) ); } @@ -672,26 +672,26 @@ public void controlsLeadingWhitespaceWithConditionals() { SimpleCodeWriter writer = new SimpleCodeWriter().insertTrailingNewline(false); writer.putContext("foo", Arrays.asList("a", "b", "c")); writer.write( - "${#foo as k1, v1}\n" // elided because it's standalone - + " ${#foo as k2, v2}\n" // elided because it's standalone - + " ${~k1:L} ${v1:L}; ${k2:L} ${v2:L}\n" // removes leading ws - + " ${/foo}\n" // elided - + "${/foo}" + "${#foo as k1, v1}\n" // elided because it's standalone + + " ${#foo as k2, v2}\n" // elided because it's standalone + + " ${~k1:L} ${v1:L}; ${k2:L} ${v2:L}\n" // removes leading ws + + " ${/foo}\n" // elided + + "${/foo}" ); // elided assertThat( - writer.toString(), - equalTo( - "0 a; 0 a\n" - + "0 a; 1 b\n" - + "0 a; 2 c\n" - + "1 b; 0 a\n" - + "1 b; 1 b\n" - + "1 b; 2 c\n" - + "2 c; 0 a\n" - + "2 c; 1 b\n" - + "2 c; 2 c\n" - ) + writer.toString(), + equalTo( + "0 a; 0 a\n" + + "0 a; 1 b\n" + + "0 a; 2 c\n" + + "1 b; 0 a\n" + + "1 b; 1 b\n" + + "1 b; 2 c\n" + + "2 c; 0 a\n" + + "2 c; 1 b\n" + + "2 c; 2 c\n" + ) ); } @@ -700,18 +700,18 @@ public void controlsLeadingWhitespaceWithConditionalsAndBlocks() { SimpleCodeWriter writer = new SimpleCodeWriter().insertTrailingNewline(false); writer.putContext("foo", "text"); writer.write( - "${?foo}\n" // elided because it's standalone - + " ${~foo:L} ${C|}\n" // removes leading ws before v, and C is properly formatted. - + "${/foo}", // elided - writer.consumer(w -> w.writeInlineWithNoFormatting("hi1\nhi2")) + "${?foo}\n" // elided because it's standalone + + " ${~foo:L} ${C|}\n" // removes leading ws before v, and C is properly formatted. + + "${/foo}", // elided + writer.consumer(w -> w.writeInlineWithNoFormatting("hi1\nhi2")) ); assertThat( - writer.toString(), - equalTo( - "text hi1\n" - + " hi2\n" - ) + writer.toString(), + equalTo( + "text hi1\n" + + " hi2\n" + ) ); } @@ -720,8 +720,8 @@ public void cannotUseInlineBlockAlignmentWithTrimmedWhitespace() { SimpleCodeWriter writer = new SimpleCodeWriter(); Assertions.assertThrows( - RuntimeException.class, - () -> writer.write("${~C|}", writer.consumer(w -> w.write("x"))) + RuntimeException.class, + () -> writer.write("${~C|}", writer.consumer(w -> w.write("x"))) ); } @@ -739,9 +739,9 @@ public void canSkipTrailingWhitespaceInConditionals() { SimpleCodeWriter writer = new SimpleCodeWriter().insertTrailingNewline(false); writer.putContext("nav", "http://example.com"); writer.write( - "${?nav~}\n" - + " ${nav:L}\n" - + "${~/nav}" + "${?nav~}\n" + + " ${nav:L}\n" + + "${~/nav}" ); assertThat(writer.toString(), equalTo("http://example.com")); diff --git a/smithy-utils/src/test/java/software/amazon/smithy/utils/CodeWriterTest.java b/smithy-utils/src/test/java/software/amazon/smithy/utils/CodeWriterTest.java index 274f23c2c44..188eefeab3f 100644 --- a/smithy-utils/src/test/java/software/amazon/smithy/utils/CodeWriterTest.java +++ b/smithy-utils/src/test/java/software/amazon/smithy/utils/CodeWriterTest.java @@ -28,10 +28,10 @@ public class CodeWriterTest { public void limitsBlankLines() { CodeWriter writer = new CodeWriter().trimBlankLines().trimTrailingSpaces(); writer.write("if ($L == \"foo\") {\n\n\n\n", "BAZ") - .indent() - .write("print($L)", "BAZ") - .dedent() - .write("}"); + .indent() + .write("print($L)", "BAZ") + .dedent() + .write("}"); assertThat(writer.toString(), equalTo("if (BAZ == \"foo\") {\n\n print(BAZ)\n}\n")); } @@ -40,10 +40,10 @@ public void limitsBlankLines() { public void doesNotLimitBlankLines() { CodeWriter writer = new CodeWriter().trimTrailingSpaces(); writer.write("if ($L == \"foo\") {\n\n\n\n", "BAZ") - .indent() - .write("print($L)", "BAZ") - .dedent() - .write("}"); + .indent() + .write("print($L)", "BAZ") + .dedent() + .write("}"); assertThat(writer.toString(), equalTo("if (BAZ == \"foo\") {\n\n\n\n\n print(BAZ)\n}\n")); } @@ -67,9 +67,9 @@ public void trimsTrailingSpaces() { @Test public void toStringCanDisableTrimmingTrailingSpaces() { CodeWriter writer = new CodeWriter() - .insertTrailingNewline(false) - .trimTrailingSpaces(false) - .writeInline("hi "); + .insertTrailingNewline(false) + .trimTrailingSpaces(false) + .writeInline("hi "); assertThat(writer.toString(), equalTo("hi ")); } @@ -101,13 +101,13 @@ public void trailingNewlineIsAddedToEmptyText() { public void canWriteTextWithNewlinePrefixAndBlankLineTrimming() { CodeWriter writer = CodeWriter.createDefault(); writer - .write("/**") - .setNewlinePrefix(" * ") - .write("This is some docs.") - .write("And more docs.\n") - .write("Foo.") - .setNewlinePrefix("") - .write(" */"); + .write("/**") + .setNewlinePrefix(" * ") + .write("This is some docs.") + .write("And more docs.\n") + .write("Foo.") + .setNewlinePrefix("") + .write(" */"); /* Becomes: * @@ -122,8 +122,8 @@ public void canWriteTextWithNewlinePrefixAndBlankLineTrimming() { * ^ Minus this character. */ assertThat( - writer.toString(), - equalTo("/**\n * This is some docs.\n * And more docs.\n *\n * Foo.\n */\n") + writer.toString(), + equalTo("/**\n * This is some docs.\n * And more docs.\n *\n * Foo.\n */\n") ); } @@ -131,19 +131,19 @@ public void canWriteTextWithNewlinePrefixAndBlankLineTrimming() { public void handlesIndentation() { CodeWriter writer = CodeWriter.createDefault(); writer - .write("Hi") - .indent() - .write("A") - .indent() - .write("B") - .dedent() - .write("C") - .dedent() - .write("Fin."); + .write("Hi") + .indent() + .write("A") + .indent() + .write("B") + .dedent() + .write("C") + .dedent() + .write("Fin."); assertThat( - writer.toString(), - equalTo("Hi\n A\n B\n C\nFin.\n") + writer.toString(), + equalTo("Hi\n A\n B\n C\nFin.\n") ); } @@ -166,14 +166,14 @@ public void canDedentToRoot() { public void canIndentDocBlocks() { CodeWriter writer = CodeWriter.createDefault(); writer.indent() - .write("/**") - .setNewlinePrefix(" * ") - .write("This is some docs.") - .write("And more docs.\n") - .write("Foo.") - .setNewlinePrefix("") - .write(" */") - .dedent(); + .write("/**") + .setNewlinePrefix(" * ") + .write("This is some docs.") + .write("And more docs.\n") + .write("Foo.") + .setNewlinePrefix("") + .write(" */") + .dedent(); /* Becomes: * @@ -188,8 +188,8 @@ public void canIndentDocBlocks() { * ^ Minus this character. */ assertThat( - writer.toString(), - equalTo(" /**\n * This is some docs.\n * And more docs.\n *\n * Foo.\n */\n") + writer.toString(), + equalTo(" /**\n * This is some docs.\n * And more docs.\n *\n * Foo.\n */\n") ); } @@ -213,9 +213,9 @@ public void doesNotInjectNewlineWhenNotNeeded() { public void cannotPopMoreStatesThanExist() { Assertions.assertThrows(IllegalStateException.class, () -> { CodeWriter.createDefault() - .pushState() - .popState() - .popState(); + .pushState() + .popState() + .popState(); }); } @@ -223,42 +223,42 @@ public void cannotPopMoreStatesThanExist() { public void canPushAndPopState() { CodeWriter writer = CodeWriter.createDefault(); writer - .setNewlinePrefix("0: ") - .write("Hi") - .pushState() - .indent(2) - .setNewlinePrefix("2: ") - .write("there,") - .pushState() - .indent(2) - .setNewlinePrefix("4: ") - .write("guy") - .popState() - .write("Foo") - .popState() - .write("baz"); + .setNewlinePrefix("0: ") + .write("Hi") + .pushState() + .indent(2) + .setNewlinePrefix("2: ") + .write("there,") + .pushState() + .indent(2) + .setNewlinePrefix("4: ") + .write("guy") + .popState() + .write("Foo") + .popState() + .write("baz"); assertThat( - writer.toString(), - equalTo("0: Hi\n 2: there,\n 4: guy\n 2: Foo\n0: baz\n") + writer.toString(), + equalTo("0: Hi\n 2: there,\n 4: guy\n 2: Foo\n0: baz\n") ); } @Test public void writesBlocks() { String result = CodeWriter.createDefault() - .openBlock("public final class $L {", "Foo") - .openBlock("public void main(String[] args) {") - .write("System.out.println(args[0]);") - .closeBlock("}") - .closeBlock("}") - .toString(); + .openBlock("public final class $L {", "Foo") + .openBlock("public void main(String[] args) {") + .write("System.out.println(args[0]);") + .closeBlock("}") + .closeBlock("}") + .toString(); assertThat( - result, - equalTo( - "public final class Foo {\n public void main(String[] args) {\n System.out.println(args[0]);\n }\n}\n" - ) + result, + equalTo( + "public final class Foo {\n public void main(String[] args) {\n System.out.println(args[0]);\n }\n}\n" + ) ); } @@ -325,12 +325,12 @@ public void formatsNullAsEmptyString() { @Test public void writesWithNamedContext() { CodeWriter w = CodeWriter.createDefault() - .putContext("foo", "Hello!") - .pushState() - .putContext("foo", "Hola!") - .write("Hi. $foo:L") - .popState() - .write("Hi. $foo:L"); + .putContext("foo", "Hello!") + .pushState() + .putContext("foo", "Hola!") + .write("Hi. $foo:L") + .popState() + .write("Hi. $foo:L"); assertThat(w.toString(), equalTo("Hi. Hola!\nHi. Hello!\n")); } @@ -356,11 +356,11 @@ public void failsWhenTypedContextDoesNotMatch() { }); assertThat( - e.getMessage(), - equalTo( - "Expected context value 'foo' to be an instance of java.lang.Integer, but " - + "found java.lang.String (Debug Info {path=ROOT/a, near=Hello {\\n})" - ) + e.getMessage(), + equalTo( + "Expected context value 'foo' to be an instance of java.lang.Integer, but " + + "found java.lang.String (Debug Info {path=ROOT/a, near=Hello {\\n})" + ) ); } @@ -459,20 +459,20 @@ public void canIntegrateSectionsWithComplexStates() { writer.write(" */"); assertThat( - writer.toString(), - equalTo( - "/**\n" - + " * Hi!\n" - + " *\n" - + " * Intercepted: baz!\n" - + " * Yap!\n" - + " * This is indented, in flow of parent.\n" - + " * Yap!\n" - + " * Yap?\n" - + " * # Has a prefix\n" - + " * # Yes\n" - + " */\n" - ) + writer.toString(), + equalTo( + "/**\n" + + " * Hi!\n" + + " *\n" + + " * Intercepted: baz!\n" + + " * Yap!\n" + + " * This is indented, in flow of parent.\n" + + " * Yap!\n" + + " * Yap?\n" + + " * # Has a prefix\n" + + " * # Yes\n" + + " */\n" + ) ); } @@ -501,20 +501,20 @@ public void canIntegrateInlineSectionsWithComplexStates() { writer.write(" */"); assertThat( - writer.toString(), - equalTo( - "/**\n" - + " * Foo \"foo!\"\n" - + " *\n" - + " * \"baz\"!\n" - + " * Yap!\n" - + " * This is indented, in flow of parent.\n" - + " * Yap!\n" - + " * Yap?\n" - + " * # Has a prefix\n" - + " * # Yes\n" - + " */\n" - ) + writer.toString(), + equalTo( + "/**\n" + + " * Foo \"foo!\"\n" + + " *\n" + + " * \"baz\"!\n" + + " * Yap!\n" + + " * This is indented, in flow of parent.\n" + + " * Yap!\n" + + " * Yap?\n" + + " * # Has a prefix\n" + + " * # Yes\n" + + " */\n" + ) ); } @@ -524,7 +524,7 @@ public void hasOpenBlockRunnable0() { String result = writer.openBlock("public {", "}", () -> { writer.write("hi();"); }) - .toString(); + .toString(); assertThat(result, equalTo("public {\n hi();\n}\n")); } @@ -537,13 +537,13 @@ public void hasOpenBlockRunnable1() { writer.write("System.out.println(args[0]);"); }); }) - .toString(); + .toString(); assertThat( - result, - equalTo( - "public final class Foo {\n public void main(String[] args) {\n System.out.println(args[0]);\n }\n}\n" - ) + result, + equalTo( + "public final class Foo {\n public void main(String[] args) {\n System.out.println(args[0]);\n }\n}\n" + ) ); } @@ -553,7 +553,7 @@ public void hasOpenBlockRunnable2() { String result = writer.openBlock("public $L $L {", "}", "1", "2", () -> { writer.write("hi();"); }) - .toString(); + .toString(); assertThat(result, equalTo("public 1 2 {\n hi();\n}\n")); } @@ -564,7 +564,7 @@ public void hasOpenBlockRunnable3() { String result = writer.openBlock("public $L $L $L {", "}", "1", "2", "3", () -> { writer.write("hi();"); }) - .toString(); + .toString(); assertThat(result, equalTo("public 1 2 3 {\n hi();\n}\n")); } @@ -575,7 +575,7 @@ public void hasOpenBlockRunnable4() { String result = writer.openBlock("public $L $L $L $L {", "}", "1", "2", "3", "4", () -> { writer.write("hi();"); }) - .toString(); + .toString(); assertThat(result, equalTo("public 1 2 3 4 {\n hi();\n}\n")); } @@ -586,7 +586,7 @@ public void hasOpenBlockRunnable5() { String result = writer.openBlock("public $L $L $L $L $L {", "}", "1", "2", "3", "4", "5", () -> { writer.write("hi();"); }) - .toString(); + .toString(); assertThat(result, equalTo("public 1 2 3 4 5 {\n hi();\n}\n")); } @@ -603,13 +603,13 @@ public void poppedSectionsEscapeDollars() { public void poppedSectionsEscapeCustomExpressionStarts() { CodeWriter writer = CodeWriter.createDefault(); String result = writer - .setExpressionStart('#') - .pushState("foo") - .write("##Hello") - .write("$Hello") - .write("$$Hello") - .popState() - .toString(); + .setExpressionStart('#') + .pushState("foo") + .write("##Hello") + .write("$Hello") + .write("$$Hello") + .popState() + .toString(); assertThat(result, equalTo("#Hello\n$Hello\n$$Hello\n")); } @@ -617,10 +617,10 @@ public void poppedSectionsEscapeCustomExpressionStarts() { @Test public void canWriteInline() { String result = CodeWriter.createDefault() - .insertTrailingNewline(false) - .writeInline("foo") - .writeInline(", bar") - .toString(); + .insertTrailingNewline(false) + .writeInline("foo") + .writeInline(", bar") + .toString(); assertThat(result, equalTo("foo, bar")); } @@ -628,11 +628,11 @@ public void canWriteInline() { @Test public void writeInlineHandlesSingleNewline() { String result = CodeWriter.createDefault() - .insertTrailingNewline(false) - .writeInline("foo") - .indent() - .writeInline(":\nbar") - .toString(); + .insertTrailingNewline(false) + .writeInline("foo") + .indent() + .writeInline(":\nbar") + .toString(); assertThat(result, equalTo("foo:\n bar")); } @@ -640,14 +640,14 @@ public void writeInlineHandlesSingleNewline() { @Test public void writeInlineHandlesMultipleNewlines() { String result = CodeWriter.createDefault() - .insertTrailingNewline(false) - .writeInline("foo:") - .writeInline(" [") - .indent() - .writeInline("\nbar,\nbaz,\nbam,") - .dedent() - .writeInline("\n]") - .toString(); + .insertTrailingNewline(false) + .writeInline("foo:") + .writeInline(" [") + .indent() + .writeInline("\nbar,\nbaz,\nbam,") + .dedent() + .writeInline("\n]") + .toString(); assertThat(result, equalTo("foo: [\n bar,\n baz,\n bam,\n]")); } @@ -655,10 +655,10 @@ public void writeInlineHandlesMultipleNewlines() { @Test public void writeInlineStripsSpaces() { String result = CodeWriter.createDefault() - .insertTrailingNewline(false) - .trimTrailingSpaces() - .writeInline("foo ") - .toString(); + .insertTrailingNewline(false) + .trimTrailingSpaces() + .writeInline("foo ") + .toString(); assertThat(result, equalTo("foo")); } @@ -666,19 +666,19 @@ public void writeInlineStripsSpaces() { @Test public void writeInlineDoesNotAllowIndentationToBeEscaped() { String result = CodeWriter.createDefault() - .setIndentText("\t") - .insertTrailingNewline(false) - .indent() - .indent() - .writeInline("{foo:") - .writeInline(" [\n") - .indent() - .writeInline("hi,\nbye") - .dedent() - .writeInline("\n]\n") - .dedent() - .writeInline("}") - .toString(); + .setIndentText("\t") + .insertTrailingNewline(false) + .indent() + .indent() + .writeInline("{foo:") + .writeInline(" [\n") + .indent() + .writeInline("hi,\nbye") + .dedent() + .writeInline("\n]\n") + .dedent() + .writeInline("}") + .toString(); assertThat(result, equalTo("\t\t{foo: [\n\t\t\thi,\n\t\t\tbye\n\t\t]\n\t}")); } @@ -686,12 +686,12 @@ public void writeInlineDoesNotAllowIndentationToBeEscaped() { @Test public void newlineCanBeDisabled() { CodeWriter writer = CodeWriter - .createDefault() - .insertTrailingNewline(); + .createDefault() + .insertTrailingNewline(); String result = writer - .disableNewlines() - .openBlock("[", "]", () -> writer.write("hi")) - .toString(); + .disableNewlines() + .openBlock("[", "]", () -> writer.write("hi")) + .toString(); assertThat(result, equalTo("[hi]\n")); } @@ -699,13 +699,13 @@ public void newlineCanBeDisabled() { @Test public void newlineCanBeDisabledWithEmptyString() { CodeWriter writer = CodeWriter - .createDefault() - .insertTrailingNewline(); + .createDefault() + .insertTrailingNewline(); String result = writer - .setNewline("") - .openBlock("[", "]", () -> writer.write("hi")) - .enableNewlines() - .toString(); + .setNewline("") + .openBlock("[", "]", () -> writer.write("hi")) + .enableNewlines() + .toString(); assertThat(result, equalTo("[hi]\n")); } @@ -713,13 +713,13 @@ public void newlineCanBeDisabledWithEmptyString() { @Test public void newlineCanBeMultipleCharacters() { CodeWriter writer = CodeWriter - .createDefault() - .insertTrailingNewline() - .setNewline("\r\n"); + .createDefault() + .insertTrailingNewline() + .setNewline("\r\n"); String result = writer - .openBlock("[", "]", () -> writer.write("hi")) - .enableNewlines() - .toString(); + .openBlock("[", "]", () -> writer.write("hi")) + .enableNewlines() + .toString(); assertThat(result, equalTo("[\r\n hi\r\n]\r\n")); } @@ -727,13 +727,13 @@ public void newlineCanBeMultipleCharacters() { @Test public void newlineCanBeLotsOfCharacters() { CodeWriter writer = CodeWriter - .createDefault() - .insertTrailingNewline() - .setNewline("HELLO_THIS_IS_A_NEWLINE!!!"); + .createDefault() + .insertTrailingNewline() + .setNewline("HELLO_THIS_IS_A_NEWLINE!!!"); String result = writer - .write("Hi.") - .write("There.") - .toString(); + .write("Hi.") + .write("There.") + .toString(); assertThat(result, equalTo("Hi.HELLO_THIS_IS_A_NEWLINE!!!There.HELLO_THIS_IS_A_NEWLINE!!!")); } @@ -742,10 +742,10 @@ public void newlineCanBeLotsOfCharacters() { public void settingNewlineEnablesNewlines() { CodeWriter writer = CodeWriter.createDefault(); String result = writer - .disableNewlines() - .setNewline("\n") - .openBlock("[", "]", () -> writer.write("hi")) - .toString(); + .disableNewlines() + .setNewline("\n") + .openBlock("[", "]", () -> writer.write("hi")) + .toString(); assertThat(result, equalTo("[\n hi\n]\n")); } @@ -767,17 +767,17 @@ public void canSetCustomExpressionStartChar() { String result = writer.toString(); assertThat( - result, - equalTo( - "Hi, 1\n" - + "Hi, #L\n" - + "Hi, $L\n" - + "Hi, $$L\n" - + "Hi, #L\n" - + "Hi, ##L\n" - + "Hi, 2\n" - + "Hi, $L\n" - ) + result, + equalTo( + "Hi, 1\n" + + "Hi, #L\n" + + "Hi, $L\n" + + "Hi, $$L\n" + + "Hi, #L\n" + + "Hi, ##L\n" + + "Hi, 2\n" + + "Hi, $L\n" + ) ); } @@ -1120,17 +1120,17 @@ public void alwaysWritesToParentBuilders() { @Test public void skipsConditionalsWithAllWhitespaceLines1() { SimpleCodeWriter writer = new SimpleCodeWriter() - .trimTrailingSpaces(false) - .insertTrailingNewline(false); + .trimTrailingSpaces(false) + .insertTrailingNewline(false); writer.putContext("foo", true); writer.write( - " ${?foo}\n" // " " is skipped. - + " ${foo:L} foo ${foo:L}\n" // " " is kept, so is the newline. - + " ${/foo}\n" // whole line is skipped. - + " ${^foo}\n" // whole line is skipped. - + " not ${foo:L}\n" // skipped. - + " ${/foo}\n" // Whole line is skipped. - + "Who?" + " ${?foo}\n" // " " is skipped. + + " ${foo:L} foo ${foo:L}\n" // " " is kept, so is the newline. + + " ${/foo}\n" // whole line is skipped. + + " ${^foo}\n" // whole line is skipped. + + " not ${foo:L}\n" // skipped. + + " ${/foo}\n" // Whole line is skipped. + + "Who?" ); // Includes only "Who?" assertThat(writer.toString(), equalTo(" true foo true\nWho?")); @@ -1139,17 +1139,17 @@ public void skipsConditionalsWithAllWhitespaceLines1() { @Test public void skipsConditionalsWithAllWhitespaceLines2() { SimpleCodeWriter writer = new SimpleCodeWriter() - .trimTrailingSpaces(false) - .insertTrailingNewline(false); + .trimTrailingSpaces(false) + .insertTrailingNewline(false); writer.putContext("foo", true); writer.write( - "${?foo}\n" // " " is skipped. - + " ${foo:L}\n" // " " is kept, so is the newline. - + "${/foo}\n" // whole line is skipped. - + "${^foo}\n" // whole line is skipped. - + " not ${foo:L}\n" // skipped. - + "${/foo}\n" // Whole line is skipped. - + "Who?" + "${?foo}\n" // " " is skipped. + + " ${foo:L}\n" // " " is kept, so is the newline. + + "${/foo}\n" // whole line is skipped. + + "${^foo}\n" // whole line is skipped. + + " not ${foo:L}\n" // skipped. + + "${/foo}\n" // Whole line is skipped. + + "Who?" ); // Includes only "Who?" assertThat(writer.toString(), equalTo(" true\nWho?")); @@ -1158,16 +1158,16 @@ public void skipsConditionalsWithAllWhitespaceLines2() { @Test public void skipsConditionalsWithAllWhitespaceLines3() { SimpleCodeWriter writer = new SimpleCodeWriter() - .trimTrailingSpaces(false) - .insertTrailingNewline(false); + .trimTrailingSpaces(false) + .insertTrailingNewline(false); writer.write( - " ${?foo}\n" // Whole line is skipped. - + " ${foo:L} foo ${foo:L}\n" // Whole line is skipped. - + " ${/foo}\n" // whole line is skipped. - + " ${^foo}\n" // whole line is skipped. - + " not ${foo:L}\n" // Includes " not \n" - + " ${/foo}\n" // Whole line is skipped. - + "Who?" + " ${?foo}\n" // Whole line is skipped. + + " ${foo:L} foo ${foo:L}\n" // Whole line is skipped. + + " ${/foo}\n" // whole line is skipped. + + " ${^foo}\n" // whole line is skipped. + + " not ${foo:L}\n" // Includes " not \n" + + " ${/foo}\n" // Whole line is skipped. + + "Who?" ); // Includes only "Who?" assertThat(writer.toString(), equalTo(" not \nWho?")); @@ -1176,12 +1176,12 @@ public void skipsConditionalsWithAllWhitespaceLines3() { @Test public void expandsEmptyConditionalSections() { SimpleCodeWriter writer = new SimpleCodeWriter() - .trimTrailingSpaces(false) - .insertTrailingNewline(false); + .trimTrailingSpaces(false) + .insertTrailingNewline(false); writer.write( - "Hi\n" - + "${^foo}\n" - + "${/foo}" + "Hi\n" + + "${^foo}\n" + + "${/foo}" ); assertThat(writer.toString(), equalTo("Hi\n")); @@ -1193,20 +1193,20 @@ public void expandsEmptyConditionalSections() { @Test public void failsWhenFormatterIsUnknownInsideConditional() { SimpleCodeWriter writer = new SimpleCodeWriter() - .trimTrailingSpaces(false) - .insertTrailingNewline(false); + .trimTrailingSpaces(false) + .insertTrailingNewline(false); RuntimeException e = Assertions.assertThrows(RuntimeException.class, () -> { writer.write("${^foo}$P${/foo}", 10); }); assertThat( - e.getMessage(), - equalTo( - "Syntax error at line 1 column 9: Unknown formatter `P` " - + "found in format string (template: ${^foo}$P${/foo}) " - + "(Debug Info {path=ROOT, near=})" - ) + e.getMessage(), + equalTo( + "Syntax error at line 1 column 9: Unknown formatter `P` " + + "found in format string (template: ${^foo}$P${/foo}) " + + "(Debug Info {path=ROOT, near=})" + ) ); } @@ -1216,8 +1216,8 @@ public void failsWhenFormatterIsUnknownInsideConditional() { @Test public void ignoresInvalidFormattersInUnevaluatedConditions() { SimpleCodeWriter writer = new SimpleCodeWriter() - .trimTrailingSpaces(false) - .insertTrailingNewline(false); + .trimTrailingSpaces(false) + .insertTrailingNewline(false); writer.write("${?foo}$P${/foo}", 10); assertThat(writer.toString(), equalTo("")); @@ -1227,14 +1227,14 @@ public void ignoresInvalidFormattersInUnevaluatedConditions() { @MethodSource("nestedBlocksProvider") public void evaluatesNestedBlocks(String line) { SimpleCodeWriter writer = new SimpleCodeWriter() - .trimTrailingSpaces(false) - .insertTrailingNewline(false); + .trimTrailingSpaces(false) + .insertTrailingNewline(false); writer.write( - "${^foo}" + line - + " ${^foo}Hi1${/foo}" + line - + " ${^foo}${^foo}Hi2${?foo}No${/foo}${/foo}${/foo}" + line - + " ${^foo}Hi3${/foo}" + line - + "${/foo}" + "${^foo}" + line + + " ${^foo}Hi1${/foo}" + line + + " ${^foo}${^foo}Hi2${?foo}No${/foo}${/foo}${/foo}" + line + + " ${^foo}Hi3${/foo}" + line + + "${/foo}" ); assertThat(writer.toString(), equalTo(" Hi1" + line + " Hi2" + line + " Hi3" + line)); @@ -1247,13 +1247,13 @@ public static Stream nestedBlocksProvider() { @Test public void canIterateOverVariable() { SimpleCodeWriter writer = new SimpleCodeWriter() - .trimTrailingSpaces(false) - .insertTrailingNewline(false); + .trimTrailingSpaces(false) + .insertTrailingNewline(false); writer.putContext("foo", Arrays.asList("a", "b", "c")); writer.write( - "${#foo}\n" - + " - ${key:L}: ${value:L}\n" - + "${/foo}" + "${#foo}\n" + + " - ${key:L}: ${value:L}\n" + + "${/foo}" ); assertThat(writer.toString(), equalTo(" - 0: a\n - 1: b\n - 2: c\n")); @@ -1262,15 +1262,15 @@ public void canIterateOverVariable() { @Test public void canIterateOverVariableAndDelayConditionals() { SimpleCodeWriter writer = new SimpleCodeWriter() - .trimTrailingSpaces(false) - .insertTrailingNewline(false); + .trimTrailingSpaces(false) + .insertTrailingNewline(false); writer.putContext("foo", Arrays.asList("a", "", "b")); writer.write( - "${#foo}\n" - + " ${?value}\n" - + " - ${key:L}: ${value:L}\n" - + " ${/value}\n" - + "${/foo}\n" + "${#foo}\n" + + " ${?value}\n" + + " - ${key:L}: ${value:L}\n" + + " ${/value}\n" + + "${/foo}\n" ); assertThat(writer.toString(), equalTo(" - 0: a\n - 2: b\n")); @@ -1279,19 +1279,19 @@ public void canIterateOverVariableAndDelayConditionals() { @Test public void canGetFirstAndLastFromIterator() { SimpleCodeWriter writer = new SimpleCodeWriter() - .trimTrailingSpaces(false) - .insertTrailingNewline(false); + .trimTrailingSpaces(false) + .insertTrailingNewline(false); writer.putContext("foo", Arrays.asList("a", "b", "c")); writer.write( - "${#foo}\n" - + "${?key.first}\n" - + "[\n" - + "${/key.first}\n" - + " ${value:L}${^key.last},${/key.last}\n" - + "${?key.last}\n" - + "]\n" - + "${/key.last}\n" - + "${/foo}\n" + "${#foo}\n" + + "${?key.first}\n" + + "[\n" + + "${/key.first}\n" + + " ${value:L}${^key.last},${/key.last}\n" + + "${?key.last}\n" + + "]\n" + + "${/key.last}\n" + + "${/foo}\n" ); assertThat(writer.toString(), equalTo("[\n a,\n b,\n c\n]\n")); @@ -1300,19 +1300,19 @@ public void canGetFirstAndLastFromIterator() { @Test public void canGetFirstAndLastFromIteratorWithCustomName() { SimpleCodeWriter writer = new SimpleCodeWriter() - .trimTrailingSpaces(false) - .insertTrailingNewline(false); + .trimTrailingSpaces(false) + .insertTrailingNewline(false); writer.putContext("foo", Arrays.asList("a", "b", "c")); writer.write( - "${#foo as i, value}\n" - + "${?i.first}\n" - + "[\n" - + "${/i.first}\n" - + " ${value:L}${^i.last},${/i.last}\n" - + "${?i.last}\n" - + "]\n" - + "${/i.last}\n" - + "${/foo}\n" + "${#foo as i, value}\n" + + "${?i.first}\n" + + "[\n" + + "${/i.first}\n" + + " ${value:L}${^i.last},${/i.last}\n" + + "${?i.last}\n" + + "]\n" + + "${/i.last}\n" + + "${/foo}\n" ); assertThat(writer.toString(), equalTo("[\n a,\n b,\n c\n]\n")); @@ -1323,32 +1323,32 @@ public void canGetFirstAndLastFromIteratorWithCustomName() { public void truthyAndFalsey(Object fooValue, String expected) { String template = "${?foo}A${/foo}${^foo}B${/foo}"; String actual = new SimpleCodeWriter() - .trimTrailingSpaces(false) - .insertTrailingNewline(false) - .putContext("foo", fooValue) - .write(template) - .toString(); + .trimTrailingSpaces(false) + .insertTrailingNewline(false) + .putContext("foo", fooValue) + .write(template) + .toString(); assertThat(actual, equalTo(expected)); } public static Stream truthyAndFalseyTestCases() { return Stream.of( - Arguments.of(null, "B"), - Arguments.of(false, "B"), - Arguments.of("", "B"), - Arguments.of(Collections.emptyList(), "B"), - Arguments.of(Collections.emptySet(), "B"), - Arguments.of(Collections.emptyMap(), "B"), - Arguments.of(Optional.empty(), "B"), - Arguments.of(0, "A"), - Arguments.of(1, "A"), - Arguments.of("a", "A"), - Arguments.of(ListUtils.of("a"), "A"), - Arguments.of(SetUtils.of("a"), "A"), - Arguments.of(MapUtils.of("a", "a"), "A"), - Arguments.of(Optional.of(0), "A"), - Arguments.of(Optional.of(Collections.emptyList()), "A") + Arguments.of(null, "B"), + Arguments.of(false, "B"), + Arguments.of("", "B"), + Arguments.of(Collections.emptyList(), "B"), + Arguments.of(Collections.emptySet(), "B"), + Arguments.of(Collections.emptyMap(), "B"), + Arguments.of(Optional.empty(), "B"), + Arguments.of(0, "A"), + Arguments.of(1, "A"), + Arguments.of("a", "A"), + Arguments.of(ListUtils.of("a"), "A"), + Arguments.of(SetUtils.of("a"), "A"), + Arguments.of(MapUtils.of("a", "a"), "A"), + Arguments.of(Optional.of(0), "A"), + Arguments.of(Optional.of(Collections.emptyList()), "A") ); } @@ -1356,36 +1356,36 @@ public static Stream truthyAndFalseyTestCases() { @MethodSource("iterationTestCases") public void handlesIteration(Object fooValue, String expected) { String template = "${#foo}\n" - + "k: ${key:L}, v: ${value:L}, f: ${key.first:L}, l: ${key.last:L}\n" - + "${/foo}"; + + "k: ${key:L}, v: ${value:L}, f: ${key.first:L}, l: ${key.last:L}\n" + + "${/foo}"; String actual = new SimpleCodeWriter() - .trimTrailingSpaces(false) - .insertTrailingNewline(false) - .putContext("foo", fooValue) - .write(template) - .toString(); + .trimTrailingSpaces(false) + .insertTrailingNewline(false) + .putContext("foo", fooValue) + .write(template) + .toString(); assertThat(actual, equalTo(expected)); } public static Stream iterationTestCases() { return Stream.of( - Arguments.of(null, ""), - Arguments.of(false, ""), - Arguments.of("", ""), - Arguments.of(Collections.emptyList(), ""), - Arguments.of(Collections.emptySet(), ""), - Arguments.of(Collections.emptyMap(), ""), - Arguments.of(Optional.empty(), ""), - Arguments.of(Optional.of(0), ""), - Arguments.of(Optional.of(Collections.emptyList()), ""), - Arguments.of(ListUtils.of("a"), "k: 0, v: a, f: true, l: true\n"), - Arguments.of(SetUtils.of("a"), "k: 0, v: a, f: true, l: true\n"), - Arguments.of(MapUtils.of("ak", "av"), "k: ak, v: av, f: true, l: true\n"), - Arguments.of( - Arrays.asList("a", "b"), - "k: 0, v: a, f: true, l: false\nk: 1, v: b, f: false, l: true\n" - ) + Arguments.of(null, ""), + Arguments.of(false, ""), + Arguments.of("", ""), + Arguments.of(Collections.emptyList(), ""), + Arguments.of(Collections.emptySet(), ""), + Arguments.of(Collections.emptyMap(), ""), + Arguments.of(Optional.empty(), ""), + Arguments.of(Optional.of(0), ""), + Arguments.of(Optional.of(Collections.emptyList()), ""), + Arguments.of(ListUtils.of("a"), "k: 0, v: a, f: true, l: true\n"), + Arguments.of(SetUtils.of("a"), "k: 0, v: a, f: true, l: true\n"), + Arguments.of(MapUtils.of("ak", "av"), "k: ak, v: av, f: true, l: true\n"), + Arguments.of( + Arrays.asList("a", "b"), + "k: 0, v: a, f: true, l: false\nk: 1, v: b, f: false, l: true\n" + ) ); } @@ -1419,26 +1419,26 @@ public void detectsUnclosedBlocks() { @Test public void handlesNestedBlockAlignment() { SimpleCodeWriter writer = new SimpleCodeWriter() - .trimTrailingSpaces(false) - .insertTrailingNewline(false); + .trimTrailingSpaces(false) + .insertTrailingNewline(false); writer.onSection("nested", writer::writeInlineWithNoFormatting); writer.write( - "Hello: ${C@nested|}", - writer.consumer( - w -> w.write( - ". ${C|}", - w.consumer(w2 -> w2.write("* Hi\n* There")) + "Hello: ${C@nested|}", + writer.consumer( + w -> w.write( + ". ${C|}", + w.consumer(w2 -> w2.write("* Hi\n* There")) + ) ) - ) ); String actual = writer.toString(); assertThat( - actual, - equalTo( - "Hello: . * Hi\n" - + " * There" - ) + actual, + equalTo( + "Hello: . * Hi\n" + + " * There" + ) ); } @@ -1516,11 +1516,11 @@ public void providesContextWhenBadGetterIsCalled() { }); assertThat( - e.getMessage(), - containsString( - "Unable to get context 'bad' from a matching method of the current " - + "CodeSection: This was bad! " - ) + e.getMessage(), + containsString( + "Unable to get context 'bad' from a matching method of the current " + + "CodeSection: This was bad! " + ) ); // The debug info contains the class name of the section. assertThat(e.getMessage(), containsString(MySection.class.getCanonicalName())); diff --git a/smithy-utils/src/test/java/software/amazon/smithy/utils/IoUtilsTest.java b/smithy-utils/src/test/java/software/amazon/smithy/utils/IoUtilsTest.java index c08a90e674b..284a3338571 100644 --- a/smithy-utils/src/test/java/software/amazon/smithy/utils/IoUtilsTest.java +++ b/smithy-utils/src/test/java/software/amazon/smithy/utils/IoUtilsTest.java @@ -64,35 +64,35 @@ public void readsFromStringPath() throws Exception { // we create a Path from the URI, convert that to a string, then pass // it to the helper method which uses Paths.get again. assertEquals( - "This is a test." + System.lineSeparator(), - IoUtils.readUtf8File(Paths.get(getClass().getResource("test.txt").toURI()).toString()) + "This is a test." + System.lineSeparator(), + IoUtils.readUtf8File(Paths.get(getClass().getResource("test.txt").toURI()).toString()) ); } @Test public void readsFromPath() throws URISyntaxException { assertEquals( - "This is a test." + System.lineSeparator(), - IoUtils.readUtf8File(Paths.get(getClass().getResource("test.txt").toURI())) + "This is a test." + System.lineSeparator(), + IoUtils.readUtf8File(Paths.get(getClass().getResource("test.txt").toURI())) ); } @Test public void readsFromClass() { assertEquals( - "This is a test." + System.lineSeparator(), - IoUtils.readUtf8Resource(getClass(), "test.txt") + "This is a test." + System.lineSeparator(), + IoUtils.readUtf8Resource(getClass(), "test.txt") ); } @Test public void readsFromClassLoader() { assertEquals( - "This is a test." + System.lineSeparator(), - IoUtils.readUtf8Resource( - getClass().getClassLoader(), - "software/amazon/smithy/utils/test.txt" - ) + "This is a test." + System.lineSeparator(), + IoUtils.readUtf8Resource( + getClass().getClassLoader(), + "software/amazon/smithy/utils/test.txt" + ) ); } diff --git a/smithy-utils/src/test/java/software/amazon/smithy/utils/ListUtilsTest.java b/smithy-utils/src/test/java/software/amazon/smithy/utils/ListUtilsTest.java index ceeac348cc8..e6bfeee93b3 100644 --- a/smithy-utils/src/test/java/software/amazon/smithy/utils/ListUtilsTest.java +++ b/smithy-utils/src/test/java/software/amazon/smithy/utils/ListUtilsTest.java @@ -42,8 +42,8 @@ public void ofManyIsMany() { @Test public void collectsToList() { assertThat( - Stream.of("Jason", "Michael", "Kevin").collect(ListUtils.toUnmodifiableList()), - containsInAnyOrder("Jason", "Michael", "Kevin") + Stream.of("Jason", "Michael", "Kevin").collect(ListUtils.toUnmodifiableList()), + containsInAnyOrder("Jason", "Michael", "Kevin") ); } } diff --git a/smithy-utils/src/test/java/software/amazon/smithy/utils/MapUtilsTest.java b/smithy-utils/src/test/java/software/amazon/smithy/utils/MapUtilsTest.java index 30e8f2381d2..97935b553d8 100644 --- a/smithy-utils/src/test/java/software/amazon/smithy/utils/MapUtilsTest.java +++ b/smithy-utils/src/test/java/software/amazon/smithy/utils/MapUtilsTest.java @@ -74,14 +74,14 @@ public void ofThreeIsThree() { @Test public void ofFourIsFour() { Map map = MapUtils.of( - "1", - "A", - "2", - "B", - "3", - "C", - "4", - "D" + "1", + "A", + "2", + "B", + "3", + "C", + "4", + "D" ); assertThat(map, hasEntry("1", "A")); assertThat(map, hasEntry("2", "B")); @@ -92,16 +92,16 @@ public void ofFourIsFour() { @Test public void ofFiveIsFive() { Map map = MapUtils.of( - "1", - "A", - "2", - "B", - "3", - "C", - "4", - "D", - "5", - "E" + "1", + "A", + "2", + "B", + "3", + "C", + "4", + "D", + "5", + "E" ); assertThat(map, hasEntry("1", "A")); assertThat(map, hasEntry("2", "B")); @@ -113,18 +113,18 @@ public void ofFiveIsFive() { @Test public void ofSixIsSix() { Map map = MapUtils.of( - "1", - "A", - "2", - "B", - "3", - "C", - "4", - "D", - "5", - "E", - "6", - "F" + "1", + "A", + "2", + "B", + "3", + "C", + "4", + "D", + "5", + "E", + "6", + "F" ); assertThat(map, hasEntry("1", "A")); assertThat(map, hasEntry("2", "B")); @@ -137,20 +137,20 @@ public void ofSixIsSix() { @Test public void ofSevenIsSeven() { Map map = MapUtils.of( - "1", - "A", - "2", - "B", - "3", - "C", - "4", - "D", - "5", - "E", - "6", - "F", - "7", - "G" + "1", + "A", + "2", + "B", + "3", + "C", + "4", + "D", + "5", + "E", + "6", + "F", + "7", + "G" ); assertThat(map, hasEntry("1", "A")); assertThat(map, hasEntry("2", "B")); @@ -164,22 +164,22 @@ public void ofSevenIsSeven() { @Test public void ofEightIsEight() { Map map = MapUtils.of( - "1", - "A", - "2", - "B", - "3", - "C", - "4", - "D", - "5", - "E", - "6", - "F", - "7", - "G", - "8", - "H" + "1", + "A", + "2", + "B", + "3", + "C", + "4", + "D", + "5", + "E", + "6", + "F", + "7", + "G", + "8", + "H" ); assertThat(map, hasEntry("1", "A")); assertThat(map, hasEntry("2", "B")); @@ -194,24 +194,24 @@ public void ofEightIsEight() { @Test public void ofNineIsNine() { Map map = MapUtils.of( - "1", - "A", - "2", - "B", - "3", - "C", - "4", - "D", - "5", - "E", - "6", - "F", - "7", - "G", - "8", - "H", - "9", - "I" + "1", + "A", + "2", + "B", + "3", + "C", + "4", + "D", + "5", + "E", + "6", + "F", + "7", + "G", + "8", + "H", + "9", + "I" ); assertThat(map, hasEntry("1", "A")); assertThat(map, hasEntry("2", "B")); @@ -227,26 +227,26 @@ public void ofNineIsNine() { @Test public void ofTenIsTen() { Map map = MapUtils.of( - "1", - "A", - "2", - "B", - "3", - "C", - "4", - "D", - "5", - "E", - "6", - "F", - "7", - "G", - "8", - "H", - "9", - "I", - "10", - "J" + "1", + "A", + "2", + "B", + "3", + "C", + "4", + "D", + "5", + "E", + "6", + "F", + "7", + "G", + "8", + "H", + "9", + "I", + "10", + "J" ); assertThat(map, hasEntry("1", "A")); assertThat(map, hasEntry("2", "B")); @@ -270,8 +270,8 @@ public void suppliesEntry() { @Test public void buildsFromTwoEntries() { Map map = MapUtils.ofEntries( - MapUtils.entry("1", "A"), - MapUtils.entry("2", "B") + MapUtils.entry("1", "A"), + MapUtils.entry("2", "B") ); assertThat(map, hasEntry("1", "A")); @@ -297,7 +297,7 @@ public void buildsFromEntriesEmpty() { @Test public void collectsToMap() { Map map = Stream.of("Jason", "Michael", "Kevin") - .collect(MapUtils.toUnmodifiableMap(i -> i.substring(0, 1), identity())); + .collect(MapUtils.toUnmodifiableMap(i -> i.substring(0, 1), identity())); assertThat(map, hasEntry("J", "Jason")); assertThat(map, hasEntry("K", "Kevin")); assertThat(map, hasEntry("M", "Michael")); diff --git a/smithy-utils/src/test/java/software/amazon/smithy/utils/MediaTypeTest.java b/smithy-utils/src/test/java/software/amazon/smithy/utils/MediaTypeTest.java index 8c07c50b589..bc33ce93f44 100644 --- a/smithy-utils/src/test/java/software/amazon/smithy/utils/MediaTypeTest.java +++ b/smithy-utils/src/test/java/software/amazon/smithy/utils/MediaTypeTest.java @@ -51,8 +51,8 @@ public void requiresValidParameterName() { @Test public void requiresEqualsAfterParameterName() { RuntimeException e = Assertions.assertThrows( - RuntimeException.class, - () -> MediaType.from("application/json; foo") + RuntimeException.class, + () -> MediaType.from("application/json; foo") ); assertThat(e.getMessage(), containsString("Expected: '='")); @@ -76,8 +76,8 @@ public void requiresParameterValueAfterOtherParamsAndSemicolon() { @Test public void detectsInvalidQuotedEscapes() { RuntimeException e = Assertions.assertThrows( - RuntimeException.class, - () -> MediaType.from("application/json; foo=\"bar\\") + RuntimeException.class, + () -> MediaType.from("application/json; foo=\"bar\\") ); assertThat(e.getMessage(), containsString("Expected character after escape")); diff --git a/smithy-utils/src/test/java/software/amazon/smithy/utils/OptionalUtilsTest.java b/smithy-utils/src/test/java/software/amazon/smithy/utils/OptionalUtilsTest.java index c8b861d2452..073cea78368 100644 --- a/smithy-utils/src/test/java/software/amazon/smithy/utils/OptionalUtilsTest.java +++ b/smithy-utils/src/test/java/software/amazon/smithy/utils/OptionalUtilsTest.java @@ -34,18 +34,18 @@ public void streamIsEmpty() { @Test public void invokesPresentAction() { OptionalUtils.ifPresentOrElse( - Optional.of("Kevin"), - (i) -> {}, - () -> new RuntimeException("Failure") + Optional.of("Kevin"), + (i) -> {}, + () -> new RuntimeException("Failure") ); } @Test public void invokesEmptyAction() { OptionalUtils.ifPresentOrElse( - Optional.empty(), - (i) -> new RuntimeException("Failure"), - () -> {} + Optional.empty(), + (i) -> new RuntimeException("Failure"), + () -> {} ); } } diff --git a/smithy-utils/src/test/java/software/amazon/smithy/utils/SetUtilsTest.java b/smithy-utils/src/test/java/software/amazon/smithy/utils/SetUtilsTest.java index 57085bd7754..942275a88f1 100644 --- a/smithy-utils/src/test/java/software/amazon/smithy/utils/SetUtilsTest.java +++ b/smithy-utils/src/test/java/software/amazon/smithy/utils/SetUtilsTest.java @@ -60,8 +60,8 @@ public void ofManyIsMany() { @Test public void collectsToSet() { assertThat( - Stream.of("Jason", "Michael", "Kevin").collect(SetUtils.toUnmodifiableSet()), - containsInAnyOrder("Jason", "Michael", "Kevin") + Stream.of("Jason", "Michael", "Kevin").collect(SetUtils.toUnmodifiableSet()), + containsInAnyOrder("Jason", "Michael", "Kevin") ); } } diff --git a/smithy-utils/src/test/java/software/amazon/smithy/utils/SimpleCodeWriterTest.java b/smithy-utils/src/test/java/software/amazon/smithy/utils/SimpleCodeWriterTest.java index 9d914783f19..6fa9631d7f2 100644 --- a/smithy-utils/src/test/java/software/amazon/smithy/utils/SimpleCodeWriterTest.java +++ b/smithy-utils/src/test/java/software/amazon/smithy/utils/SimpleCodeWriterTest.java @@ -17,10 +17,10 @@ public class SimpleCodeWriterTest { public void limitsBlankLines() { SimpleCodeWriter writer = new SimpleCodeWriter().trimBlankLines().trimTrailingSpaces(); writer.write("if ($L == \"foo\") {\n\n\n\n", "BAZ") - .indent() - .write("print($L)", "BAZ") - .dedent() - .write("}"); + .indent() + .write("print($L)", "BAZ") + .dedent() + .write("}"); assertThat(writer.toString(), equalTo("if (BAZ == \"foo\") {\n\n print(BAZ)\n}\n")); } @@ -29,10 +29,10 @@ public void limitsBlankLines() { public void doesNotLimitBlankLines() { SimpleCodeWriter writer = new SimpleCodeWriter().trimTrailingSpaces(); writer.write("if ($L == \"foo\") {\n\n\n\n", "BAZ") - .indent() - .write("print($L)", "BAZ") - .dedent() - .write("}"); + .indent() + .write("print($L)", "BAZ") + .dedent() + .write("}"); assertThat(writer.toString(), equalTo("if (BAZ == \"foo\") {\n\n\n\n\n print(BAZ)\n}\n")); } @@ -56,9 +56,9 @@ public void trimsTrailingSpaces() { @Test public void toStringCanDisableTrimmingTrailingSpaces() { SimpleCodeWriter writer = new SimpleCodeWriter() - .insertTrailingNewline(false) - .trimTrailingSpaces(false) - .writeInline("hi "); + .insertTrailingNewline(false) + .trimTrailingSpaces(false) + .writeInline("hi "); assertThat(writer.toString(), equalTo("hi ")); } @@ -90,13 +90,13 @@ public void trailingNewlineIsAddedToEmptyText() { public void canWriteTextWithNewlinePrefixAndBlankLineTrimming() { SimpleCodeWriter writer = new SimpleCodeWriter(); writer - .write("/**") - .setNewlinePrefix(" * ") - .write("This is some docs.") - .write("And more docs.\n") - .write("Foo.") - .setNewlinePrefix("") - .write(" */"); + .write("/**") + .setNewlinePrefix(" * ") + .write("This is some docs.") + .write("And more docs.\n") + .write("Foo.") + .setNewlinePrefix("") + .write(" */"); /* Becomes: * @@ -111,8 +111,8 @@ public void canWriteTextWithNewlinePrefixAndBlankLineTrimming() { * ^ Minus this character. */ assertThat( - writer.toString(), - equalTo("/**\n * This is some docs.\n * And more docs.\n *\n * Foo.\n */\n") + writer.toString(), + equalTo("/**\n * This is some docs.\n * And more docs.\n *\n * Foo.\n */\n") ); } @@ -120,19 +120,19 @@ public void canWriteTextWithNewlinePrefixAndBlankLineTrimming() { public void handlesIndentation() { SimpleCodeWriter writer = new SimpleCodeWriter(); writer - .write("Hi") - .indent() - .write("A") - .indent() - .write("B") - .dedent() - .write("C") - .dedent() - .write("Fin."); + .write("Hi") + .indent() + .write("A") + .indent() + .write("B") + .dedent() + .write("C") + .dedent() + .write("Fin."); assertThat( - writer.toString(), - equalTo("Hi\n A\n B\n C\nFin.\n") + writer.toString(), + equalTo("Hi\n A\n B\n C\nFin.\n") ); } @@ -155,14 +155,14 @@ public void canDedentToRoot() { public void canIndentDocBlocks() { SimpleCodeWriter writer = new SimpleCodeWriter(); writer.indent() - .write("/**") - .setNewlinePrefix(" * ") - .write("This is some docs.") - .write("And more docs.\n") - .write("Foo.") - .setNewlinePrefix("") - .write(" */") - .dedent(); + .write("/**") + .setNewlinePrefix(" * ") + .write("This is some docs.") + .write("And more docs.\n") + .write("Foo.") + .setNewlinePrefix("") + .write(" */") + .dedent(); /* Becomes: * @@ -177,8 +177,8 @@ public void canIndentDocBlocks() { * ^ Minus this character. */ assertThat( - writer.toString(), - equalTo(" /**\n * This is some docs.\n * And more docs.\n *\n * Foo.\n */\n") + writer.toString(), + equalTo(" /**\n * This is some docs.\n * And more docs.\n *\n * Foo.\n */\n") ); } @@ -202,9 +202,9 @@ public void doesNotInjectNewlineWhenNotNeeded() { public void cannotPopMoreStatesThanExist() { Assertions.assertThrows(IllegalStateException.class, () -> { new SimpleCodeWriter() - .pushState() - .popState() - .popState(); + .pushState() + .popState() + .popState(); }); } @@ -212,42 +212,42 @@ public void cannotPopMoreStatesThanExist() { public void canPushAndPopState() { SimpleCodeWriter writer = new SimpleCodeWriter(); writer - .setNewlinePrefix("0: ") - .write("Hi") - .pushState() - .indent(2) - .setNewlinePrefix("2: ") - .write("there,") - .pushState() - .indent(2) - .setNewlinePrefix("4: ") - .write("guy") - .popState() - .write("Foo") - .popState() - .write("baz"); + .setNewlinePrefix("0: ") + .write("Hi") + .pushState() + .indent(2) + .setNewlinePrefix("2: ") + .write("there,") + .pushState() + .indent(2) + .setNewlinePrefix("4: ") + .write("guy") + .popState() + .write("Foo") + .popState() + .write("baz"); assertThat( - writer.toString(), - equalTo("0: Hi\n 2: there,\n 4: guy\n 2: Foo\n0: baz\n") + writer.toString(), + equalTo("0: Hi\n 2: there,\n 4: guy\n 2: Foo\n0: baz\n") ); } @Test public void writesBlocks() { String result = new SimpleCodeWriter() - .openBlock("public final class $L {", "Foo") - .openBlock("public void main(String[] args) {") - .write("System.out.println(args[0]);") - .closeBlock("}") - .closeBlock("}") - .toString(); + .openBlock("public final class $L {", "Foo") + .openBlock("public void main(String[] args) {") + .write("System.out.println(args[0]);") + .closeBlock("}") + .closeBlock("}") + .toString(); assertThat( - result, - equalTo( - "public final class Foo {\n public void main(String[] args) {\n System.out.println(args[0]);\n }\n}\n" - ) + result, + equalTo( + "public final class Foo {\n public void main(String[] args) {\n System.out.println(args[0]);\n }\n}\n" + ) ); } @@ -314,12 +314,12 @@ public void formatsNullAsEmptyString() { @Test public void writesWithNamedContext() { SimpleCodeWriter w = new SimpleCodeWriter() - .putContext("foo", "Hello!") - .pushState() - .putContext("foo", "Hola!") - .write("Hi. $foo:L") - .popState() - .write("Hi. $foo:L"); + .putContext("foo", "Hello!") + .pushState() + .putContext("foo", "Hola!") + .write("Hi. $foo:L") + .popState() + .write("Hi. $foo:L"); assertThat(w.toString(), equalTo("Hi. Hola!\nHi. Hello!\n")); } @@ -345,11 +345,11 @@ public void failsWhenTypedContextDoesNotMatch() { }); assertThat( - e.getMessage(), - equalTo( - "Expected context value 'foo' to be an instance of java.lang.Integer, but " - + "found java.lang.String (Debug Info {path=ROOT/a, near=Hello {\\n})" - ) + e.getMessage(), + equalTo( + "Expected context value 'foo' to be an instance of java.lang.Integer, but " + + "found java.lang.String (Debug Info {path=ROOT/a, near=Hello {\\n})" + ) ); } @@ -451,20 +451,20 @@ public void canIntegrateSectionsWithComplexStates() { writer.write(" */"); assertThat( - writer.toString(), - equalTo( - "/**\n" - + " * Hi!\n" - + " *\n" - + " * Intercepted: baz!\n" - + " * Yap!\n" - + " * This is indented, in flow of parent.\n" - + " * Yap!\n" - + " * Yap?\n" - + " * # Has a prefix\n" - + " * # Yes\n" - + " */\n" - ) + writer.toString(), + equalTo( + "/**\n" + + " * Hi!\n" + + " *\n" + + " * Intercepted: baz!\n" + + " * Yap!\n" + + " * This is indented, in flow of parent.\n" + + " * Yap!\n" + + " * Yap?\n" + + " * # Has a prefix\n" + + " * # Yes\n" + + " */\n" + ) ); } @@ -493,20 +493,20 @@ public void canIntegrateInlineSectionsWithComplexStates() { writer.write(" */"); assertThat( - writer.toString(), - equalTo( - "/**\n" - + " * Foo \"foo!\"\n" - + " *\n" - + " * \"baz\"!\n" - + " * Yap!\n" - + " * This is indented, in flow of parent.\n" - + " * Yap!\n" - + " * Yap?\n" - + " * # Has a prefix\n" - + " * # Yes\n" - + " */\n" - ) + writer.toString(), + equalTo( + "/**\n" + + " * Foo \"foo!\"\n" + + " *\n" + + " * \"baz\"!\n" + + " * Yap!\n" + + " * This is indented, in flow of parent.\n" + + " * Yap!\n" + + " * Yap?\n" + + " * # Has a prefix\n" + + " * # Yes\n" + + " */\n" + ) ); } @@ -516,7 +516,7 @@ public void hasOpenBlockRunnable0() { String result = writer.openBlock("public {", "}", () -> { writer.write("hi();"); }) - .toString(); + .toString(); assertThat(result, equalTo("public {\n hi();\n}\n")); } @@ -529,13 +529,13 @@ public void hasOpenBlockRunnable1() { writer.write("System.out.println(args[0]);"); }); }) - .toString(); + .toString(); assertThat( - result, - equalTo( - "public final class Foo {\n public void main(String[] args) {\n System.out.println(args[0]);\n }\n}\n" - ) + result, + equalTo( + "public final class Foo {\n public void main(String[] args) {\n System.out.println(args[0]);\n }\n}\n" + ) ); } @@ -545,7 +545,7 @@ public void hasOpenBlockRunnable2() { String result = writer.openBlock("public $L $L {", "}", "1", "2", () -> { writer.write("hi();"); }) - .toString(); + .toString(); assertThat(result, equalTo("public 1 2 {\n hi();\n}\n")); } @@ -556,7 +556,7 @@ public void hasOpenBlockRunnable3() { String result = writer.openBlock("public $L $L $L {", "}", "1", "2", "3", () -> { writer.write("hi();"); }) - .toString(); + .toString(); assertThat(result, equalTo("public 1 2 3 {\n hi();\n}\n")); } @@ -567,7 +567,7 @@ public void hasOpenBlockRunnable4() { String result = writer.openBlock("public $L $L $L $L {", "}", "1", "2", "3", "4", () -> { writer.write("hi();"); }) - .toString(); + .toString(); assertThat(result, equalTo("public 1 2 3 4 {\n hi();\n}\n")); } @@ -578,7 +578,7 @@ public void hasOpenBlockRunnable5() { String result = writer.openBlock("public $L $L $L $L $L {", "}", "1", "2", "3", "4", "5", () -> { writer.write("hi();"); }) - .toString(); + .toString(); assertThat(result, equalTo("public 1 2 3 4 5 {\n hi();\n}\n")); } @@ -595,13 +595,13 @@ public void poppedSectionsEscapeDollars() { public void poppedSectionsEscapeCustomExpressionStarts() { SimpleCodeWriter writer = new SimpleCodeWriter(); String result = writer - .setExpressionStart('#') - .pushState("foo") - .write("##Hello") - .write("$Hello") - .write("$$Hello") - .popState() - .toString(); + .setExpressionStart('#') + .pushState("foo") + .write("##Hello") + .write("$Hello") + .write("$$Hello") + .popState() + .toString(); assertThat(result, equalTo("#Hello\n$Hello\n$$Hello\n")); } @@ -609,10 +609,10 @@ public void poppedSectionsEscapeCustomExpressionStarts() { @Test public void canWriteInline() { String result = new SimpleCodeWriter() - .insertTrailingNewline(false) - .writeInline("foo") - .writeInline(", bar") - .toString(); + .insertTrailingNewline(false) + .writeInline("foo") + .writeInline(", bar") + .toString(); assertThat(result, equalTo("foo, bar")); } @@ -620,11 +620,11 @@ public void canWriteInline() { @Test public void writeInlineHandlesSingleNewline() { String result = new SimpleCodeWriter() - .insertTrailingNewline(false) - .writeInline("foo") - .indent() - .writeInline(":\nbar") - .toString(); + .insertTrailingNewline(false) + .writeInline("foo") + .indent() + .writeInline(":\nbar") + .toString(); assertThat(result, equalTo("foo:\n bar")); } @@ -632,14 +632,14 @@ public void writeInlineHandlesSingleNewline() { @Test public void writeInlineHandlesMultipleNewlines() { String result = new SimpleCodeWriter() - .insertTrailingNewline(false) - .writeInline("foo:") - .writeInline(" [") - .indent() - .writeInline("\nbar,\nbaz,\nbam,") - .dedent() - .writeInline("\n]") - .toString(); + .insertTrailingNewline(false) + .writeInline("foo:") + .writeInline(" [") + .indent() + .writeInline("\nbar,\nbaz,\nbam,") + .dedent() + .writeInline("\n]") + .toString(); assertThat(result, equalTo("foo: [\n bar,\n baz,\n bam,\n]")); } @@ -647,10 +647,10 @@ public void writeInlineHandlesMultipleNewlines() { @Test public void writeInlineStripsSpaces() { String result = new SimpleCodeWriter() - .insertTrailingNewline(false) - .trimTrailingSpaces() - .writeInline("foo ") - .toString(); + .insertTrailingNewline(false) + .trimTrailingSpaces() + .writeInline("foo ") + .toString(); assertThat(result, equalTo("foo")); } @@ -658,19 +658,19 @@ public void writeInlineStripsSpaces() { @Test public void writeInlineDoesNotAllowIndentationToBeEscaped() { String result = new SimpleCodeWriter() - .setIndentText("\t") - .insertTrailingNewline(false) - .indent() - .indent() - .writeInline("{foo:") - .writeInline(" [\n") - .indent() - .writeInline("hi,\nbye") - .dedent() - .writeInline("\n]\n") - .dedent() - .writeInline("}") - .toString(); + .setIndentText("\t") + .insertTrailingNewline(false) + .indent() + .indent() + .writeInline("{foo:") + .writeInline(" [\n") + .indent() + .writeInline("hi,\nbye") + .dedent() + .writeInline("\n]\n") + .dedent() + .writeInline("}") + .toString(); assertThat(result, equalTo("\t\t{foo: [\n\t\t\thi,\n\t\t\tbye\n\t\t]\n\t}")); } @@ -678,11 +678,11 @@ public void writeInlineDoesNotAllowIndentationToBeEscaped() { @Test public void newlineCanBeDisabled() { SimpleCodeWriter writer = new SimpleCodeWriter() - .insertTrailingNewline(); + .insertTrailingNewline(); String result = writer - .disableNewlines() - .openBlock("[", "]", () -> writer.write("hi")) - .toString(); + .disableNewlines() + .openBlock("[", "]", () -> writer.write("hi")) + .toString(); assertThat(result, equalTo("[hi]\n")); } @@ -690,12 +690,12 @@ public void newlineCanBeDisabled() { @Test public void newlineCanBeDisabledWithEmptyString() { SimpleCodeWriter writer = new SimpleCodeWriter() - .insertTrailingNewline(); + .insertTrailingNewline(); String result = writer - .setNewline("") - .openBlock("[", "]", () -> writer.write("hi")) - .enableNewlines() - .toString(); + .setNewline("") + .openBlock("[", "]", () -> writer.write("hi")) + .enableNewlines() + .toString(); assertThat(result, equalTo("[hi]\n")); } @@ -703,12 +703,12 @@ public void newlineCanBeDisabledWithEmptyString() { @Test public void newlineCanBeMultipleCharacters() { SimpleCodeWriter writer = new SimpleCodeWriter() - .insertTrailingNewline() - .setNewline("\r\n"); + .insertTrailingNewline() + .setNewline("\r\n"); String result = writer - .openBlock("[", "]", () -> writer.write("hi")) - .enableNewlines() - .toString(); + .openBlock("[", "]", () -> writer.write("hi")) + .enableNewlines() + .toString(); assertThat(result, equalTo("[\r\n hi\r\n]\r\n")); } @@ -716,12 +716,12 @@ public void newlineCanBeMultipleCharacters() { @Test public void newlineCanBeLotsOfCharacters() { SimpleCodeWriter writer = new SimpleCodeWriter() - .insertTrailingNewline() - .setNewline("HELLO_THIS_IS_A_NEWLINE!!!"); + .insertTrailingNewline() + .setNewline("HELLO_THIS_IS_A_NEWLINE!!!"); String result = writer - .write("Hi.") - .write("There.") - .toString(); + .write("Hi.") + .write("There.") + .toString(); assertThat(result, equalTo("Hi.HELLO_THIS_IS_A_NEWLINE!!!There.HELLO_THIS_IS_A_NEWLINE!!!")); } @@ -730,10 +730,10 @@ public void newlineCanBeLotsOfCharacters() { public void settingNewlineEnablesNewlines() { SimpleCodeWriter writer = new SimpleCodeWriter(); String result = writer - .disableNewlines() - .setNewline("\n") - .openBlock("[", "]", () -> writer.write("hi")) - .toString(); + .disableNewlines() + .setNewline("\n") + .openBlock("[", "]", () -> writer.write("hi")) + .toString(); assertThat(result, equalTo("[\n hi\n]\n")); } @@ -755,17 +755,17 @@ public void canSetCustomExpressionStartChar() { String result = writer.toString(); assertThat( - result, - equalTo( - "Hi, 1\n" - + "Hi, #L\n" - + "Hi, $L\n" - + "Hi, $$L\n" - + "Hi, #L\n" - + "Hi, ##L\n" - + "Hi, 2\n" - + "Hi, $L\n" - ) + result, + equalTo( + "Hi, 1\n" + + "Hi, #L\n" + + "Hi, $L\n" + + "Hi, $$L\n" + + "Hi, #L\n" + + "Hi, ##L\n" + + "Hi, 2\n" + + "Hi, $L\n" + ) ); } @@ -1183,12 +1183,12 @@ public void injectsInlineSectionsThatWriteInlineWithoutInfiniteRecursion() { writer.write("Name: ${L@foo|}", ""); assertThat( - writer.toString(), - equalTo( - "Name: DROP_TABLE1,\n" - + " DROP_TABLE2,\n" - + " DROP_TABLE3,\n" - ) + writer.toString(), + equalTo( + "Name: DROP_TABLE1,\n" + + " DROP_TABLE2,\n" + + " DROP_TABLE3,\n" + ) ); } diff --git a/smithy-utils/src/test/java/software/amazon/smithy/utils/SimpleParserTest.java b/smithy-utils/src/test/java/software/amazon/smithy/utils/SimpleParserTest.java index 3b7017d66ec..e160cf2d2f4 100644 --- a/smithy-utils/src/test/java/software/amazon/smithy/utils/SimpleParserTest.java +++ b/smithy-utils/src/test/java/software/amazon/smithy/utils/SimpleParserTest.java @@ -45,10 +45,10 @@ public void expectThrowsWhenNotMatchingOneOfMany() { }); assertThat( - e.getMessage(), - equalTo( - "Syntax error at line 1, column 1: Found 'f', but expected one of the following tokens: '!' '?'" - ) + e.getMessage(), + equalTo( + "Syntax error at line 1, column 1: Found 'f', but expected one of the following tokens: '!' '?'" + ) ); } @@ -59,10 +59,10 @@ public void expectThrowsWhenNotMatchingOneOfManyAndDueToEof() { }); assertThat( - e.getMessage(), - equalTo( - "Syntax error at line 1, column 1: Found '[EOF]', but expected one of the following tokens: '!' '?'" - ) + e.getMessage(), + equalTo( + "Syntax error at line 1, column 1: Found '[EOF]', but expected one of the following tokens: '!' '?'" + ) ); } diff --git a/smithy-utils/src/test/java/software/amazon/smithy/utils/SmithyBuilderTest.java b/smithy-utils/src/test/java/software/amazon/smithy/utils/SmithyBuilderTest.java index c2a6ecd2486..7fd266c61ff 100644 --- a/smithy-utils/src/test/java/software/amazon/smithy/utils/SmithyBuilderTest.java +++ b/smithy-utils/src/test/java/software/amazon/smithy/utils/SmithyBuilderTest.java @@ -16,11 +16,11 @@ public void includesCallingClassName() { IllegalStateException e = Assertions.assertThrows(IllegalStateException.class, () -> new Foo().test()); assertThat( - e.getMessage(), - equalTo( - "foo was not set on the builder (builder class is probably " - + "software.amazon.smithy.utils.SmithyBuilderTest$Foo)" - ) + e.getMessage(), + equalTo( + "foo was not set on the builder (builder class is probably " + + "software.amazon.smithy.utils.SmithyBuilderTest$Foo)" + ) ); } diff --git a/smithy-utils/src/test/java/software/amazon/smithy/utils/TriConsumerTest.java b/smithy-utils/src/test/java/software/amazon/smithy/utils/TriConsumerTest.java index 36580b16311..c696027b26b 100644 --- a/smithy-utils/src/test/java/software/amazon/smithy/utils/TriConsumerTest.java +++ b/smithy-utils/src/test/java/software/amazon/smithy/utils/TriConsumerTest.java @@ -21,8 +21,8 @@ public void composes() { TriConsumer second = (d, e, f) -> { result.append(d.toUpperCase(Locale.ENGLISH)) - .append(e.toUpperCase(Locale.ENGLISH)) - .append(f.toUpperCase(Locale.ENGLISH)); + .append(e.toUpperCase(Locale.ENGLISH)) + .append(f.toUpperCase(Locale.ENGLISH)); }; TriConsumer composed = first.andThen(second); diff --git a/smithy-waiters/src/main/java/software/amazon/smithy/waiters/Acceptor.java b/smithy-waiters/src/main/java/software/amazon/smithy/waiters/Acceptor.java index 07eb832773a..310164c1f8f 100644 --- a/smithy-waiters/src/main/java/software/amazon/smithy/waiters/Acceptor.java +++ b/smithy-waiters/src/main/java/software/amazon/smithy/waiters/Acceptor.java @@ -61,16 +61,16 @@ public Matcher getMatcher() { public static Acceptor fromNode(Node node) { ObjectNode value = node.expectObjectNode().warnIfAdditionalProperties(KEYS); return new Acceptor( - AcceptorState.fromNode(value.expectStringMember(STATE)), - Matcher.fromNode(value.expectMember(MATCHER)) + AcceptorState.fromNode(value.expectStringMember(STATE)), + Matcher.fromNode(value.expectMember(MATCHER)) ); } @Override public Node toNode() { return Node.objectNode() - .withMember("state", Node.from(state.toString())) - .withMember("matcher", matcher.toNode()); + .withMember("state", Node.from(state.toString())) + .withMember("matcher", matcher.toNode()); } @Override diff --git a/smithy-waiters/src/main/java/software/amazon/smithy/waiters/ModelRuntimeTypeGenerator.java b/smithy-waiters/src/main/java/software/amazon/smithy/waiters/ModelRuntimeTypeGenerator.java index 3970ba30caa..6587ee19894 100644 --- a/smithy-waiters/src/main/java/software/amazon/smithy/waiters/ModelRuntimeTypeGenerator.java +++ b/smithy-waiters/src/main/java/software/amazon/smithy/waiters/ModelRuntimeTypeGenerator.java @@ -187,10 +187,10 @@ public Object memberShape(MemberShape shape) { } return model.getShape(shape.getTarget()) - .map(target -> target.accept(this)) - // Rather than fail on broken models during waiter validation, - // return an ANY to get *some* validation. - .orElse(LiteralExpression.ANY); + .map(target -> target.accept(this)) + // Rather than fail on broken models during waiter validation, + // return an ANY to get *some* validation. + .orElse(LiteralExpression.ANY); } @Override diff --git a/smithy-waiters/src/main/java/software/amazon/smithy/waiters/PathMatcher.java b/smithy-waiters/src/main/java/software/amazon/smithy/waiters/PathMatcher.java index 9cbc3447daf..d56e097b848 100644 --- a/smithy-waiters/src/main/java/software/amazon/smithy/waiters/PathMatcher.java +++ b/smithy-waiters/src/main/java/software/amazon/smithy/waiters/PathMatcher.java @@ -76,18 +76,18 @@ public PathComparator getComparator() { public static PathMatcher fromNode(Node node) { ObjectNode value = node.expectObjectNode().warnIfAdditionalProperties(KEYS); return new PathMatcher( - value.expectStringMember(PATH).getValue(), - value.expectStringMember(EXPECTED).getValue(), - PathComparator.fromNode(value.expectStringMember(COMPARATOR)) + value.expectStringMember(PATH).getValue(), + value.expectStringMember(EXPECTED).getValue(), + PathComparator.fromNode(value.expectStringMember(COMPARATOR)) ); } @Override public Node toNode() { return Node.objectNode() - .withMember(PATH, Node.from(path)) - .withMember(EXPECTED, Node.from(expected)) - .withMember(COMPARATOR, comparator.toNode()); + .withMember(PATH, Node.from(path)) + .withMember(EXPECTED, Node.from(expected)) + .withMember(COMPARATOR, comparator.toNode()); } @Override @@ -100,8 +100,8 @@ public boolean equals(Object o) { PathMatcher that = (PathMatcher) o; return getPath().equals(that.getPath()) - && getComparator().equals(that.getComparator()) - && getExpected().equals(that.getExpected()); + && getComparator().equals(that.getComparator()) + && getExpected().equals(that.getExpected()); } @Override diff --git a/smithy-waiters/src/main/java/software/amazon/smithy/waiters/UniqueWaiterNamesValidator.java b/smithy-waiters/src/main/java/software/amazon/smithy/waiters/UniqueWaiterNamesValidator.java index 852fdd75203..001302ee62c 100644 --- a/smithy-waiters/src/main/java/software/amazon/smithy/waiters/UniqueWaiterNamesValidator.java +++ b/smithy-waiters/src/main/java/software/amazon/smithy/waiters/UniqueWaiterNamesValidator.java @@ -32,8 +32,8 @@ public final class UniqueWaiterNamesValidator extends AbstractValidator { @Override public List validate(Model model) { return model.shapes(ServiceShape.class) - .flatMap(service -> validateService(model, service).stream()) - .collect(Collectors.toList()); + .flatMap(service -> validateService(model, service).stream()) + .collect(Collectors.toList()); } private List validateService(Model model, ServiceShape service) { @@ -44,23 +44,23 @@ private List validateService(Model model, ServiceShape service) if (entry.getValue().size() > 1) { for (OperationShape operation : entry.getValue()) { Set conflicts = entry.getValue() - .stream() - .filter(o -> !o.equals(operation)) - .map(Shape::getId) - .collect(Collectors.toCollection(TreeSet::new)); + .stream() + .filter(o -> !o.equals(operation)) + .map(Shape::getId) + .collect(Collectors.toCollection(TreeSet::new)); events.add( - error( - operation, - operation.expectTrait(WaitableTrait.class), - String.format( - "`%s` trait waiter name `%s` case-insensitively conflicts with waiters on other " - + "operations in the closure of service, `%s`: %s", - WaitableTrait.ID, - entry.getKey(), - service.getId(), - conflicts + error( + operation, + operation.expectTrait(WaitableTrait.class), + String.format( + "`%s` trait waiter name `%s` case-insensitively conflicts with waiters on other " + + "operations in the closure of service, `%s`: %s", + WaitableTrait.ID, + entry.getKey(), + service.getId(), + conflicts + ) ) - ) ); } } @@ -77,8 +77,8 @@ private Map> computeWaiterNamesToOperations(Model mo operation.getTrait(WaitableTrait.class).ifPresent(trait -> { for (String name : trait.getWaiters().keySet()) { Set operations = waiterNamesToOperations.computeIfAbsent( - name.toLowerCase(Locale.ENGLISH), - n -> new HashSet<>() + name.toLowerCase(Locale.ENGLISH), + n -> new HashSet<>() ); operations.add(operation); } diff --git a/smithy-waiters/src/main/java/software/amazon/smithy/waiters/WaitableTraitValidator.java b/smithy-waiters/src/main/java/software/amazon/smithy/waiters/WaitableTraitValidator.java index b44db0d2c8b..41c68209934 100644 --- a/smithy-waiters/src/main/java/software/amazon/smithy/waiters/WaitableTraitValidator.java +++ b/smithy-waiters/src/main/java/software/amazon/smithy/waiters/WaitableTraitValidator.java @@ -19,9 +19,9 @@ public final class WaitableTraitValidator extends AbstractValidator { @Override public List validate(Model model) { return model.shapes(OperationShape.class) - .filter(operation -> operation.hasTrait(WaitableTrait.class)) - .flatMap(operation -> validateOperation(model, operation).stream()) - .collect(Collectors.toList()); + .filter(operation -> operation.hasTrait(WaitableTrait.class)) + .flatMap(operation -> validateOperation(model, operation).stream()) + .collect(Collectors.toList()); } private List validateOperation(Model model, OperationShape operation) { @@ -34,18 +34,18 @@ private List validateOperation(Model model, OperationShape oper if (waiter.getMinDelay() > waiter.getMaxDelay()) { events.add( - error( - operation, - trait, - String.format( - "`%s` trait waiter named `%s` has a `minDelay` value of %d that is greater than its " - + "`maxDelay` value of %d", - WaitableTrait.ID, - waiterName, - waiter.getMinDelay(), - waiter.getMaxDelay() + error( + operation, + trait, + String.format( + "`%s` trait waiter named `%s` has a `minDelay` value of %d that is greater than its " + + "`maxDelay` value of %d", + WaitableTrait.ID, + waiterName, + waiter.getMinDelay(), + waiter.getMaxDelay() + ) ) - ) ); } @@ -62,15 +62,15 @@ private List validateOperation(Model model, OperationShape oper if (!foundSuccess) { // Emitted as unsuppressable "WaitableTrait". events.add( - error( - operation, - trait, - String.format( - "No success state matcher found for `%s` trait waiter named `%s`", - WaitableTrait.ID, - waiterName + error( + operation, + trait, + String.format( + "No success state matcher found for `%s` trait waiter named `%s`", + WaitableTrait.ID, + waiterName + ) ) - ) ); } } diff --git a/smithy-waiters/src/main/java/software/amazon/smithy/waiters/Waiter.java b/smithy-waiters/src/main/java/software/amazon/smithy/waiters/Waiter.java index f167e1011fd..1c165ad8c9f 100644 --- a/smithy-waiters/src/main/java/software/amazon/smithy/waiters/Waiter.java +++ b/smithy-waiters/src/main/java/software/amazon/smithy/waiters/Waiter.java @@ -35,12 +35,12 @@ public final class Waiter implements Tagged, ToNode, ToSmithyBuilder { private static final int DEFAULT_MIN_DELAY = 2; private static final int DEFAULT_MAX_DELAY = 120; private static final Set KEYS = SetUtils.of( - DOCUMENTATION, - ACCEPTORS, - MIN_DELAY, - MAX_DELAY, - TAGS, - DEPRECATED + DOCUMENTATION, + ACCEPTORS, + MIN_DELAY, + MAX_DELAY, + TAGS, + DEPRECATED ); private final String documentation; @@ -66,12 +66,12 @@ public static Builder builder() { @Override public Builder toBuilder() { return builder() - .documentation(getDocumentation().orElse(null)) - .acceptors(getAcceptors()) - .minDelay(getMinDelay()) - .maxDelay(getMaxDelay()) - .tags(tags) - .deprecated(deprecated); + .documentation(getDocumentation().orElse(null)) + .acceptors(getAcceptors()) + .minDelay(getMinDelay()) + .maxDelay(getMaxDelay()) + .tags(tags) + .deprecated(deprecated); } /** @@ -154,8 +154,8 @@ public boolean isDeprecated() { @Override public Node toNode() { ObjectNode.Builder builder = Node.objectNodeBuilder() - .withOptionalMember(DOCUMENTATION, getDocumentation().map(Node::from)) - .withMember(ACCEPTORS, getAcceptors().stream().map(Acceptor::toNode).collect(ArrayNode.collect())); + .withOptionalMember(DOCUMENTATION, getDocumentation().map(Node::from)) + .withMember(ACCEPTORS, getAcceptors().stream().map(Acceptor::toNode).collect(ArrayNode.collect())); // Don't serialize default values for minDelay and maxDelay. if (minDelay != DEFAULT_MIN_DELAY) { @@ -186,11 +186,11 @@ public boolean equals(Object o) { Waiter waiter = (Waiter) o; return minDelay == waiter.minDelay - && maxDelay == waiter.maxDelay - && Objects.equals(documentation, waiter.documentation) - && acceptors.equals(waiter.acceptors) - && tags.equals(waiter.tags) - && deprecated == waiter.deprecated; + && maxDelay == waiter.maxDelay + && Objects.equals(documentation, waiter.documentation) + && acceptors.equals(waiter.acceptors) + && tags.equals(waiter.tags) + && deprecated == waiter.deprecated; } @Override diff --git a/smithy-waiters/src/main/java/software/amazon/smithy/waiters/WaiterMatcherValidator.java b/smithy-waiters/src/main/java/software/amazon/smithy/waiters/WaiterMatcherValidator.java index e68204e67fb..6c3e984a583 100644 --- a/smithy-waiters/src/main/java/software/amazon/smithy/waiters/WaiterMatcherValidator.java +++ b/smithy-waiters/src/main/java/software/amazon/smithy/waiters/WaiterMatcherValidator.java @@ -87,15 +87,15 @@ public List visitErrorType(Matcher.ErrorTypeMember errorType) { } addEvent( - Severity.WARNING, - String.format( - "errorType '%s' not found on operation. This operation defines the following errors: %s", - error, - operation.getErrors() - ), - INVALID_ERROR_TYPE, - waiterName, - String.valueOf(acceptorIndex) + Severity.WARNING, + String.format( + "errorType '%s' not found on operation. This operation defines the following errors: %s", + error, + operation.getErrors() + ), + INVALID_ERROR_TYPE, + waiterName, + String.valueOf(acceptorIndex) ); return events; @@ -115,14 +115,14 @@ private void validatePathMatcher(LiteralExpression input, PathMatcher pathMatche // A booleanEquals comparator requires an `expected` value of "true" or "false". if (!pathMatcher.getExpected().equals("true") && !pathMatcher.getExpected().equals("false")) { addEvent( - Severity.ERROR, - String.format( - "Waiter acceptors with a %s comparator must set their `expected` value to 'true' or " - + "'false', but found '%s'.", - PathComparator.BOOLEAN_EQUALS, - pathMatcher.getExpected() - ), - NON_SUPPRESSABLE_ERROR + Severity.ERROR, + String.format( + "Waiter acceptors with a %s comparator must set their `expected` value to 'true' or " + + "'false', but found '%s'.", + PathComparator.BOOLEAN_EQUALS, + pathMatcher.getExpected() + ), + NON_SUPPRESSABLE_ERROR ); } validateReturnType(pathMatcher.getComparator(), RuntimeType.BOOLEAN, returnType); @@ -145,13 +145,13 @@ private RuntimeType validatePath(LiteralExpression input, String path) { return result.getReturnType(); } catch (JmespathException e) { addEvent( - Severity.ERROR, - String.format( - "Invalid JMESPath expression (%s): %s", - path, - e.getMessage() - ), - NON_SUPPRESSABLE_ERROR + Severity.ERROR, + String.format( + "Invalid JMESPath expression (%s): %s", + path, + e.getMessage() + ), + NON_SUPPRESSABLE_ERROR ); return RuntimeType.ANY; } @@ -160,18 +160,18 @@ private RuntimeType validatePath(LiteralExpression input, String path) { private void validateReturnType(PathComparator comparator, RuntimeType expected, RuntimeType actual) { if (actual != RuntimeType.ANY && actual != expected) { addEvent( - Severity.DANGER, - String.format( - "Waiter acceptors with a %s comparator must return a `%s` type, but this acceptor was " - + "statically determined to return a `%s` type.", - comparator, - expected, - actual - ), - JMESPATH_PROBLEM, - RETURN_TYPE_MISMATCH, - waiterName, - String.valueOf(acceptorIndex) + Severity.DANGER, + String.format( + "Waiter acceptors with a %s comparator must return a `%s` type, but this acceptor was " + + "statically determined to return a `%s` type.", + comparator, + expected, + actual + ), + JMESPATH_PROBLEM, + RETURN_TYPE_MISMATCH, + waiterName, + String.valueOf(acceptorIndex) ); } } @@ -179,8 +179,8 @@ private void validateReturnType(PathComparator comparator, RuntimeType expected, // Lint using an ANY type or using the modeled shape as the starting data. private LiteralExpression createCurrentNodeFromShape(Shape shape) { return shape == null - ? LiteralExpression.ANY - : new LiteralExpression(shape.accept(new ModelRuntimeTypeGenerator(model))); + ? LiteralExpression.ANY + : new LiteralExpression(shape.accept(new ModelRuntimeTypeGenerator(model))); } private void addJmespathEvent(String path, ExpressionProblem problem) { @@ -203,21 +203,21 @@ private void addJmespathEvent(String path, ExpressionProblem problem) { String problemMessage = problem.message + " (" + problem.line + ":" + problem.column + ")"; addEvent( - severity, - String.format("Problem found in JMESPath expression (%s): %s", path, problemMessage), - eventId + severity, + String.format("Problem found in JMESPath expression (%s): %s", path, problemMessage), + eventId ); } private void addEvent(Severity severity, String message, String... eventIdParts) { events.add( - ValidationEvent.builder() - .id(String.join(".", eventIdParts)) - .shape(operation) - .sourceLocation(waitable) - .severity(severity) - .message(String.format("Waiter `%s`, acceptor %d: %s", waiterName, acceptorIndex, message)) - .build() + ValidationEvent.builder() + .id(String.join(".", eventIdParts)) + .shape(operation) + .sourceLocation(waitable) + .severity(severity) + .message(String.format("Waiter `%s`, acceptor %d: %s", waiterName, acceptorIndex, message)) + .build() ); } } diff --git a/smithy-waiters/src/test/java/software/amazon/smithy/waiters/ModelRuntimeTypeGeneratorTest.java b/smithy-waiters/src/test/java/software/amazon/smithy/waiters/ModelRuntimeTypeGeneratorTest.java index c27de612688..af339c0c622 100644 --- a/smithy-waiters/src/test/java/software/amazon/smithy/waiters/ModelRuntimeTypeGeneratorTest.java +++ b/smithy-waiters/src/test/java/software/amazon/smithy/waiters/ModelRuntimeTypeGeneratorTest.java @@ -27,9 +27,9 @@ public class ModelRuntimeTypeGeneratorTest { @BeforeAll static void before() { model = Model.assembler() - .addImport(ModelRuntimeTypeGenerator.class.getResource("model-runtime-types.smithy")) - .assemble() - .unwrap(); + .addImport(ModelRuntimeTypeGenerator.class.getResource("model-runtime-types.smithy")) + .assemble() + .unwrap(); } @ParameterizedTest @@ -65,33 +65,33 @@ public static Collection shapeSource() { recursiveStruct.put("bar", Collections.singletonList(recursiveStructAny)); return Arrays.asList( - new Object[][]{ - {"StringList", Arrays.asList("aa", "aa")}, - {"SizedStringList", Arrays.asList("aa", "aa", "aa", "aa", "aa")}, - {"StringListMap", stringListMap}, - {"SizedStringListMap", sizedStringListMap}, - {"SizedString1", "aaaa"}, - {"SizedString2", "a"}, - {"SizedString3", "aaaaaaaa"}, - {"SizedInteger1", 100.0}, - {"SizedInteger2", 2.0}, - {"SizedInteger3", 8.0}, - {"MyUnion", myUnionOrStruct}, - {"MyStruct", myUnionOrStruct}, - {"smithy.api#Blob", "blob"}, - {"smithy.api#Document", LiteralExpression.ANY}, - {"smithy.api#Boolean", true}, - {"smithy.api#Byte", 8.0}, - {"smithy.api#Short", 8.0}, - {"smithy.api#Integer", 8.0}, - {"smithy.api#Long", 8.0}, - {"smithy.api#Float", 8.0}, - {"smithy.api#Double", 8.0}, - {"smithy.api#BigInteger", 8.0}, - {"smithy.api#BigDecimal", 8.0}, - {"smithy.api#Timestamp", LiteralExpression.NUMBER}, - {"RecursiveStruct", recursiveStruct} - } + new Object[][]{ + {"StringList", Arrays.asList("aa", "aa")}, + {"SizedStringList", Arrays.asList("aa", "aa", "aa", "aa", "aa")}, + {"StringListMap", stringListMap}, + {"SizedStringListMap", sizedStringListMap}, + {"SizedString1", "aaaa"}, + {"SizedString2", "a"}, + {"SizedString3", "aaaaaaaa"}, + {"SizedInteger1", 100.0}, + {"SizedInteger2", 2.0}, + {"SizedInteger3", 8.0}, + {"MyUnion", myUnionOrStruct}, + {"MyStruct", myUnionOrStruct}, + {"smithy.api#Blob", "blob"}, + {"smithy.api#Document", LiteralExpression.ANY}, + {"smithy.api#Boolean", true}, + {"smithy.api#Byte", 8.0}, + {"smithy.api#Short", 8.0}, + {"smithy.api#Integer", 8.0}, + {"smithy.api#Long", 8.0}, + {"smithy.api#Float", 8.0}, + {"smithy.api#Double", 8.0}, + {"smithy.api#BigInteger", 8.0}, + {"smithy.api#BigDecimal", 8.0}, + {"smithy.api#Timestamp", LiteralExpression.NUMBER}, + {"RecursiveStruct", recursiveStruct} + } ); } } diff --git a/smithy-waiters/src/test/java/software/amazon/smithy/waiters/WaiterTest.java b/smithy-waiters/src/test/java/software/amazon/smithy/waiters/WaiterTest.java index 62495becee3..fbc5fb594f8 100644 --- a/smithy-waiters/src/test/java/software/amazon/smithy/waiters/WaiterTest.java +++ b/smithy-waiters/src/test/java/software/amazon/smithy/waiters/WaiterTest.java @@ -48,10 +48,10 @@ public void includesMinDelayAndMaxDelayInNodeIfNotDefaults() { Matcher matcher = new Matcher.SuccessMember(true); Acceptor a1 = new Acceptor(AcceptorState.SUCCESS, matcher); Waiter waiter = Waiter.builder() - .minDelay(10) - .maxDelay(100) - .addAcceptor(a1) - .build(); + .minDelay(10) + .maxDelay(100) + .addAcceptor(a1) + .build(); ObjectNode node = waiter.toNode().expectObjectNode(); assertThat(waiter.getMinDelay(), is(10)); @@ -66,10 +66,10 @@ public void includesMinDelayAndMaxDelayInNodeIfNotDefaults() { @Test public void loadsAndPersistsWaiters() { Model model = Model.assembler() - .discoverModels() - .addImport(getClass().getResource("errorfiles/valid-waiters.smithy")) - .assemble() - .unwrap(); + .discoverModels() + .addImport(getClass().getResource("errorfiles/valid-waiters.smithy")) + .assemble() + .unwrap(); Shape shape = model.expectShape(ShapeId.from("smithy.example#A")); WaitableTrait trait = shape.expectTrait(WaitableTrait.class);