From 2ad31f27a9d5150c38bcd562120c937aa86796bc Mon Sep 17 00:00:00 2001 From: Filipp Akinfiev Date: Thu, 5 Jul 2018 12:58:27 +0200 Subject: [PATCH 1/2] + new swagger plugin based on OpenAPI Specification 3.0.0 --- swagger/README.md | 274 ++++------- swagger/pom.xml | 9 +- .../plugin/swagger/ModelResolver.java | 440 ------------------ .../plugin/swagger/SwaggerController.java | 194 ++++---- .../plugin/swagger/SwaggerPlugin.java | 83 ++-- .../swagger/annotations/ApiModelProperty.java | 25 - .../swagger/annotations/ApiModelRequest.java | 15 - .../plugin/swagger/domain/ApiDeclaration.java | 106 ----- .../swagger/domain/ApiDeclarations.java | 195 -------- .../plugin/swagger/domain/ApiKeys.java | 25 - .../plugin/swagger/domain/ApiModel.java | 91 ---- .../plugin/swagger/domain/ApiOperation.java | 213 --------- .../domain/ApiOperationParameters.java | 60 --- .../plugin/swagger/domain/ApiResource.java | 53 --- .../plugin/swagger/domain/ApiResources.java | 65 --- .../plugin/swagger/domain/ApiResponse.java | 33 -- .../plugin/swagger/domain/Authorization.java | 75 --- .../swagger/domain/AuthorizationTypes.java | 25 - .../plugin/swagger/domain/Authorizations.java | 28 -- .../plugin/swagger/domain/DataType.java | 191 -------- .../plugin/swagger/domain/GrantTypes.java | 25 - .../swagger/domain/ImplicitGrantType.java | 63 --- .../plugin/swagger/domain/Info.java | 87 ---- .../plugin/swagger/domain/Items.java | 70 --- .../plugin/swagger/domain/Primitives.java | 53 --- .../plugin/swagger/domain/Scope.java | 25 - .../utilities/SwaggerObjectConverter.java | 118 ----- .../plugin/swagger/wrapper/Callback.java | 11 + .../plugin/swagger/wrapper/Components.java | 119 +++++ .../plugin/swagger/wrapper/Contact.java | 40 ++ .../plugin/swagger/wrapper/Discriminator.java | 31 ++ .../plugin/swagger/wrapper/Encoding.java | 68 +++ .../plugin/swagger/wrapper/Example.java | 54 +++ .../wrapper/ExternalDocumentation.java | 38 ++ .../plugin/swagger/wrapper/Header.java | 89 ++++ .../plugin/swagger/wrapper/Info.java | 67 +++ .../plugin/swagger/wrapper/License.java | 34 ++ .../plugin/swagger/wrapper/Link.java | 83 ++++ .../plugin/swagger/wrapper/LinkParameter.java | 27 ++ .../plugin/swagger/wrapper/MediaType.java | 69 +++ .../plugin/swagger/wrapper/OAuthFlow.java | 49 ++ .../plugin/swagger/wrapper/OAuthFlows.java | 43 ++ .../plugin/swagger/wrapper/OpenApi.java | 107 +++++ .../plugin/swagger/wrapper/Operation.java | 184 ++++++++ .../plugin/swagger/wrapper/Parameter.java | 158 +++++++ .../plugin/swagger/wrapper/PathItem.java | 179 +++++++ .../plugin/swagger/wrapper/Reference.java | 25 + .../plugin/swagger/wrapper/RequestBody.java | 58 +++ .../plugin/swagger/wrapper/Response.java | 84 ++++ .../plugin/swagger/wrapper/Schema.java | 290 ++++++++++++ .../swagger/wrapper/SecurityRequirement.java | 15 + .../swagger/wrapper/SecurityScheme.java | 79 ++++ .../plugin/swagger/wrapper/Server.java | 69 +++ .../swagger/wrapper/ServerVariable.java | 64 +++ .../plugin/swagger/wrapper/Tag.java | 34 ++ .../plugin/swagger/wrapper/XmlObject.java | 52 +++ .../io/swagger/oas/annotations/Hidden.java | 13 + .../io/swagger/oas/annotations/Operation.java | 118 +++++ .../restexpress/plugin/swagger/Another.java | 35 -- .../plugin/swagger/AnotherReturnType.java | 27 -- .../restexpress/plugin/swagger/DummyBase.java | 6 - .../plugin/swagger/DummyController.java | 117 ----- .../plugin/swagger/DummyModel.java | 56 --- .../plugin/swagger/ModelResolverTest.java | 97 ---- .../plugin/swagger/SwaggerAssert.java | 37 -- .../plugin/swagger/SwaggerPluginTest.java | 430 ----------------- 66 files changed, 2577 insertions(+), 3220 deletions(-) delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/ModelResolver.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/annotations/ApiModelProperty.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/annotations/ApiModelRequest.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiDeclaration.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiDeclarations.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiKeys.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiModel.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiOperation.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiOperationParameters.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiResource.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiResources.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiResponse.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Authorization.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/AuthorizationTypes.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Authorizations.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/DataType.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/GrantTypes.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ImplicitGrantType.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Info.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Items.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Primitives.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Scope.java delete mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/utilities/SwaggerObjectConverter.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Callback.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Components.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Contact.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Discriminator.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Encoding.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Example.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/ExternalDocumentation.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Header.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Info.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/License.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Link.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/LinkParameter.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/MediaType.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/OAuthFlow.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/OAuthFlows.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/OpenApi.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Operation.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Parameter.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/PathItem.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Reference.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/RequestBody.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Response.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Schema.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/SecurityRequirement.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/SecurityScheme.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Server.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/ServerVariable.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Tag.java create mode 100644 swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/XmlObject.java create mode 100644 swagger/src/main/java/io/swagger/oas/annotations/Hidden.java create mode 100644 swagger/src/main/java/io/swagger/oas/annotations/Operation.java delete mode 100644 swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/Another.java delete mode 100644 swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/AnotherReturnType.java delete mode 100644 swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/DummyBase.java delete mode 100644 swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/DummyController.java delete mode 100644 swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/DummyModel.java delete mode 100644 swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/ModelResolverTest.java delete mode 100644 swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/SwaggerAssert.java delete mode 100644 swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/SwaggerPluginTest.java diff --git a/swagger/README.md b/swagger/README.md index beba429..301ac34 100644 --- a/swagger/README.md +++ b/swagger/README.md @@ -1,193 +1,105 @@ Swagger Plugin ============== -*Help Us Out!* This plugin is not quite ready for prime time. While it honors many of the Swagger-provided annotations, when they are absent, -it provides defaults by simply introspects your object models, exposing every non-static, non-transient property. This may not be desired. Additionally, it doesn't -yet support annotations for the 'authorizations' and 'info' Swagger models. Help us get it to prime time by sending a pull request! +Based on [OpenAPI Specification 3.0.0](https://swagger.io/specification/#oasDocument) -The Swagger plugin gathers metadata about the routes in your RestExpress service suite -to render live documentation, so it's never out of date. +fixed files for swagger-annotations are in io.swagger.oas.annotations (Hidden + Operation) -Adds routes within your service suite to facilitate Swagger documentation and usage. -By default, it add a route, /api-docs, but is configurable when instantiating the plugin. +How to use in RestExpress -It is possible to set flags and parameters on the plugin, so that preprocessors and postprocessors -handle them correctly. For example, making the /api-docs route public so that it doesn't -require authentication or authorization. - -Maven Usage -=========== -Stable: -```xml - - com.strategicgains.plugin-express - SwaggerPlugin - 0.2.6 - +Example of OpenApiConfig.java for your Project : ``` -Development: -```xml - - com.strategicgains.plugin-express - SwaggerPlugin - 0.3.0-SNAPSHOT - +import com.strategicgains.restexpress.plugin.swagger.wrapper.Components; +import com.strategicgains.restexpress.plugin.swagger.wrapper.Contact; +import com.strategicgains.restexpress.plugin.swagger.wrapper.Info; +import com.strategicgains.restexpress.plugin.swagger.wrapper.License; +import com.strategicgains.restexpress.plugin.swagger.wrapper.OpenApi; +import com.strategicgains.restexpress.plugin.swagger.wrapper.SecurityScheme; +import com.strategicgains.restexpress.plugin.swagger.wrapper.Server; +import com.strategicgains.restexpress.plugin.swagger.wrapper.ServerVariable; + +public class OpenApiConfig { + public static OpenApi get() { + Info info = new Info("cellypso REST API", "This is a your app server.", "1.0.0"); + info.setLicense(new License("Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0.html")); + info.setTermsOfService("https://path.to.your/terms/"); + info.setContact(new Contact("API Support", "https://path.to.your/support", "apisupport@your.domain")); + + OpenApi api = new OpenApi(info); + + { + Server s = new Server("http://staging.your.test:{port}/{basePath}","Staging server"); + ServerVariable sv1 = new ServerVariable("80"); + sv1.addEnum("80"); +// sv1.addEnum("443"); + s.addVariable("port", sv1); + s.getVariables().put("port", sv1); + ServerVariable sv2 = new ServerVariable("v1"); + sv2.addEnum("v1"); + s.getVariables().put("basePath", sv2); + api.getServers().add(s); + } + { + Server s = new Server("https://your.server.com:{port}/{basePath}","Production server"); + ServerVariable sv1 = new ServerVariable("443"); + sv1.addEnum("443"); + s.addVariable("port", sv1); + s.getVariables().put("port", sv1); + ServerVariable sv2 = new ServerVariable("v1"); + sv2.addEnum("v1"); + s.getVariables().put("basePath", sv2); + api.getServers().add(s); + } + api.setComponents(new Components()); + + SecurityScheme securityScheme = new SecurityScheme(); + securityScheme.setDescription("Authorization header using the Bearer schema. Example: Authorization: Bearer {token}"); + securityScheme.setName("Authorization"); + securityScheme.setIn("header"); + securityScheme.setType("http"); + securityScheme.setScheme("bearer"); + securityScheme.setBearerFormat("JWT"); + + api.getComponents().getSecuritySchemes().put("Authorization", securityScheme); + + + return api; + } +} ``` -Or download the jar directly from: -http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22SwaggerPlugin%22 - -Note that to use the SNAPSHOT version, you must enable snapshots and a repository in your pom (or settings.xml) file as follows: -```xml - - - allow-snapshots - true - - - snapshots-repo - https://oss.sonatype.org/content/repositories/snapshots - false - true - - - - +in your restexpress config ``` - -Usage -===== - -Simply create a new plugin and register it with the RestExpress server, setting options -as necessary, using method chaining if desired. - -For example: -```java -RestExpress server = new RestExpress()... - -new SwaggerPlugin("/api-docs") // URL path is optional. Defaults to '/api-docs' - .setDefaultToHidden(true) // if this is set to true then only annotated apis will be shown - .flag("public-route") // optional. Set a flag on the request for this route. - .register(server); +private static void configurePlugins(Configuration config, RestExpress server) { +// .... + + new SwaggerPlugin("/api-docs", OpenApiConfig.get()) +// .setDefaultToHidden(true) + .setBasePath("/v1") + .flag(Flags.Auth.PUBLIC_ROUTE) + .register(server); + +// .... + } + ``` + + add OpenApi Annotation to your controllers ``` - -Swagger Annotations -=================== -The Swagger Plugin now supports several swagger annotations. - -### @ApiOperation -[Swagger doc for ApiOperation](https://github.com/wordnik/swagger-core/blob/master/modules/swagger-annotations/src/main/java/com/wordnik/swagger/annotations/ApiOperation.java) - -The four parameters that are supported in ApiOperation are value, notes, response, and hidden. Several of the other values are determined by inspecting the Route metadata. These include response, httpMethod, and nickname. If response is defined in the ApiOperation annotation, that will be used, if not, the response class will be set as the return object defined in the controller method. if the parameter "hidden" is set to true then the API will not appear in the swagger documentation. The default for "hidden" is set to false (unless specified differently, See Usage above). - -Example Usage: -```java -@ApiOperation(value = "Get a specific course item", // Brief description of the operation - notes = "This operation will return a specific course item as defined in the route.", // Detailed description of the operation - response = Item.class, hidden = false) // Response type returned by the method. -public Item getItem(Request request, Response response) + @Operation( + tags = {"HR :: Employees"}, + summary = "Search employee by firstname || lastname", + description = "", + security = @SecurityRequirement(name = "Authorization"), + parameters = { + @Parameter(name="filter", in="query", description="filter", required=true), + @Parameter(name="table", in="query", description="as table"), + @Parameter(name="countOnly", in="query", description="count only") + }, + responses = { + @ApiResponse(responseCode="200", content=@Content(mediaType = "application/json", schema=@Schema(implementation=TestRS.class))) + } + ) + public void searchEmployee(Request request, Response response) { + .... ``` -### @ApiParam -[Swagger doc for ApiParam](https://github.com/wordnik/swagger-core/blob/master/modules/swagger-annotations/src/main/java/com/wordnik/swagger/annotations/ApiParam.java) - -This represents a single parameter for an api operation. - -Example Usage: -```java -@ApiParam(name = "title", // Name of the parameter -required = true, // Whether the parameter is required or not -value = "(Required) Title of the item.", // Description of the parameter -defaultValue = "Title placeholder", // Default value if none is assigned. -allowableValues = "Any String") // Description of all allowable values for the parameter. - public void createWithApiParam(Request request, Response response) -``` - -### @ApiImplicitParam -[Swagger doc for ApiImplicitParam](https://github.com/wordnik/swagger-core/blob/master/modules/swagger-annotations/src/main/java/com/wordnik/swagger/annotations/ApiImplicitParam.java) - -This represents a single parameter for an api operation. - -Example Usage: -```java -@ApiImplicitParam(name = "expand", // Name of the parameter -required = false, // Whether the parameter is required or not. -value = "(Optional) Return item and all its children.", // Description of the parameter -paramType = "query", // Parameter type, i.e. body, query, path. -dataType = "String", // Type of the parameter. -allowableValues = "all, some, none") // Description of the allowable values. -public void createWithApiImplicitParams(Request request, Response response) -``` - -### @ApiImplicitParams -[Swagger doc for ApiImplicitParams](https://github.com/wordnik/swagger-core/blob/master/modules/swagger-annotations/src/main/java/com/wordnik/swagger/annotations/ApiImplicitParams.java) - -Collection of ApiImplicitParam annotations. This allows one method to define multiple ApiImplicitParam annotations. - -Example Usage: -```java -@ApiImplicitParams({ - @ApiImplicitParam(name = "expand", required = false, value = "(Optional) Return item and all its children.", paramType = "query", dataType = "String", allowableValues = "items"), - @ApiImplicitParam(name = "limit", required = false, value = "(Optional) Set the number of items returned from request.", paramType = "query", dataType = "Integer", allowableValues = "Any integer"), - @ApiImplicitParam(name = "offset", required = false, value = "(Optional) Return the collection of items starting with the offset number. The limit query param must also be set if offset is set.", paramType = "query", dataType = "Integer", allowableValues = "Any integer") -}) -public Item getItem(Request request, Response response) -``` - -### @ApiResponse -[Swagger doc for ApiResponse](https://github.com/wordnik/swagger-core/blob/master/modules/swagger-annotations/src/main/java/com/wordnik/swagger/annotations/ApiResponse.java) - -Defines a response code that can be returned from this api operation. - -Example Usage: -```java -@ApiResponse(code = 200, // Http response code -message = "Successful retrieval of item") // Description of when the code is returned. -public Item getItem(Request request, Response response) -``` - -### @ApiResponses -[Swagger doc for ApiResponses](https://github.com/wordnik/swagger-core/blob/master/modules/swagger-annotations/src/main/java/com/wordnik/swagger/annotations/ApiResponses.java) - -Collection of Api Response annotations allowing one method to define multiple ApiResponse annotations. - -Example Usage: -```java -@ApiResponses({ - @ApiResponse(code = 200, message = "Successful retrieval of item"), - @ApiResponse(code = 404, message = "Course or Item not found"), - @ApiResponse(code = 403, message = "User not authorized"), - @ApiResponse(code = 400, message = "Item id incorrect format") -}) -public Item getItem(Request request, Response response) -``` - -### @ApiModel -[Swagger doc for ApiModel](https://github.com/wordnik/swagger-core/blob/master/modules/swagger-annotations/src/main/java/com/wordnik/swagger/annotations/ApiModel.java) - -Provides information a model class, including description, as well as inheritance and subtype information. - -Example Usage: -```java -@ApiModel(value = "Course Item", // Brief synopsis of the model. -description = "Model that defines a course item that will be returned back to the user.", // Detailed description of the class. -parent = ParentItem.class, // Superclass of the model. -subtypes = [CourseItem.class, UserItem.class]) // SubClasses that inherit this model. -public class Item { -``` - -### @ApiModelProperty -[Swagger doc for ApiModelProperty](https://github.com/wordnik/swagger-core/blob/master/modules/swagger-annotations/src/main/java/com/wordnik/swagger/annotations/ApiModelProperty.java) - -Information on a particular property in the model. - -Example Usage: -```java - @ApiModelProperty(hidden = true) // This marks the property as hidden, and won't be visible in the documentation. - private UUID id; - @ApiModelProperty(value = "Item Title", // Brief description of the model property - notes = "This defines the items title that will be visible in the course UI", // Detailed description of the property - dataType = "String", // Data type of the property. - required=true, // Whether the property is required to be set - allowableValues = "Any non-empty string. '\n' is not allowed") // Allowable values for the property - private String title; -``` +that's all \ No newline at end of file diff --git a/swagger/pom.xml b/swagger/pom.xml index 7a298a9..0394c1e 100644 --- a/swagger/pom.xml +++ b/swagger/pom.xml @@ -15,10 +15,9 @@ - com.wordnik - swagger-annotations - 1.3.8 - compile - + io.swagger + swagger-annotations + 2.0.0-rc2 + diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/ModelResolver.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/ModelResolver.java deleted file mode 100644 index 7eb9ada..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/ModelResolver.java +++ /dev/null @@ -1,440 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.*; - -import com.strategicgains.restexpress.plugin.swagger.domain.ApiModel; -import com.strategicgains.restexpress.plugin.swagger.domain.DataType; -import com.strategicgains.restexpress.plugin.swagger.domain.Items; -import com.strategicgains.restexpress.plugin.swagger.domain.Primitives; -import com.strategicgains.restexpress.plugin.swagger.utilities.SwaggerObjectConverter; -import com.strategicgains.restexpress.plugin.swagger.annotations.ApiModelProperty; - -/** - * This class implements a simplified least-common denominator reflection-based - * introspector in roughly the same behavior as the serializers supported in - * RestExpress (jackson/gson) - * - * Research notes: In developing this class, it was discovered that jackson has - * facilities to generate a variant of json-schema directly from an - * ObjectMapper. However, as of this writing, it didn't support handling the - * swagger-annotations. It also produced schema that while obviously - * syntactically correct, didn't leverage the "$ref" construct and produce the - * "flat" model structure that the Swagger spec prefers. - * - * Furthermore, the serializer is overridden with something non-jackson, I - * didn't want to tie the swagger model generation to APIs that get unhooked. - * - * So, with all that said, this class, much like gson and jackson: - * - * - * @author russtrotter - */ -public class ModelResolver -{ - private Map models; - - public ModelResolver() - { - this(new HashMap()); - } - - public ModelResolver(Map models) - { - this.models = models; - } - - public DataType resolve(Type cls) - { - return resolve(cls, null); - } - - public DataType resolve(Type cls, String modelName) - { - return createNode(cls, modelName, null, null); - } - - private ApiModel resolveClass(Class target, String modelName) - { - String id = getModelId(target, modelName); - ApiModel model = models.get(id); - - if (model != null) - { - return model; - } - - if (target.isPrimitive()) - { - System.err.println("Unable to resolve primitive class: " + target); - return model; - // throw new - // IllegalArgumentException("Unable to resolve primitive class: " + - // target); - } - - if (target.isSynthetic()) - { - System.err.println("Unable to resolve synthetic class: " + target); - return model; - // throw new - // IllegalArgumentException("Unable to resolve synthetic class: " + - // target); - } - - if (target.isArray()) - { - System.err.println("Unable to use arrays for models: " + target); - return model; - // throw new - // IllegalArgumentException("Unable to use arrays for models: " + - // target); - } - - // com.wordnik.swagger.annotations.ApiModel apiModel = - // target.getAnnotation(com.wordnik.swagger.annotations.ApiModel.class); - // if (apiModel == null) { - // throw new IllegalArgumentException("Missing ApiModel annotation on: " - // + target); - // } - - model = new ApiModel().id(id); - models.put(id, model); - Map properties = new HashMap(); - - for (Class cls = target; !Object.class.equals(cls) && cls != null; cls = cls - .getSuperclass()) - { - processFields(properties, cls, modelName); - } - - List sorted = new ArrayList(properties.values()); - - // sort the properties based on property "position" attribute of - // annotation - Collections.sort(sorted, new Comparator() - { - @Override - public int compare(DataType o1, DataType o2) - { - return o1.getPosition() - o2.getPosition(); - } - }); - - for (DataType property : sorted) - { - model.property(property); - - if (property.isRequired()) - { - model.required(property.getProperty()); - } - } - - return model; - } - - private DataType createNode(Type target, String modelName, String dataType, String format) - { - DataType node = new DataType(); - - if (dataType != null && !dataType.isEmpty()) - { - node.setType(dataType); - - if(format != null && !format.isEmpty()) - { - node.setFormat(format); - } - } - else if (target instanceof Class) - { - Class targetClass = (Class) target; - - if (String.class.equals(target)) - { - node.setType(Primitives.STRING); - } - else if (Integer.class.equals(target) - || Integer.TYPE.equals(target)) - { - node.setType(Primitives.INTEGER); - } - else if (Short.class.equals(target) - || Short.TYPE.equals(target)) - { - node.setType(Primitives.INTEGER); - } - else if (Long.class.equals(target) - || Long.TYPE.equals(target)) - { - node.setType(Primitives.LONG); - } - else if (Boolean.class.equals(target) - || Boolean.TYPE.equals(target)) - { - node.setType(Primitives.BOOLEAN); - } - else if (Float.class.equals(target) - || Float.TYPE.equals(target)) - { - node.setType(Primitives.FLOAT); - } - else if (Double.class.equals(target) - || Double.TYPE.equals(target)) - { - node.setType(Primitives.DOUBLE); - } - else if (Byte.class.equals(target) - || Byte.TYPE.equals(target)) - { - node.setType(Primitives.BYTE); - } - else if (Date.class.equals(target)) - { - node.setType(Primitives.DATE_TIME); - } - else if (targetClass.isArray()) - { - node.setType("array"); - DataType componentModel = createNode(targetClass - .getComponentType(), null, null, null); - node.setItems(new Items(componentModel)); - } - else if (Map.class.isAssignableFrom(targetClass)) { - node.setType("object"); - } - else if (targetClass.isEnum()) - { - node.setType(Primitives.STRING); - - for (Object obj : targetClass.getEnumConstants()) - { - node.addEnum(obj.toString()); - } - } - else if (Void.class.equals(target) - || Void.TYPE.equals(target)) - { - node.setType(Primitives.VOID); - } - else if (targetClass.getSimpleName().equals("ObjectId") ) - { - node.setType(Primitives.STRING); - } - else - { - ApiModel subModel = resolveClass(targetClass, modelName); - node.setRef(subModel.getId()); - } - } - else if (target instanceof ParameterizedType) - { - ParameterizedType parameterizedType = (ParameterizedType) target; - Class rawType = (Class) parameterizedType.getRawType(); - - if (Map.class.isAssignableFrom(rawType)) { - node.setType("object"); - } - - if (Collection.class.isAssignableFrom(rawType)) - { - node.setType("array"); - - if (Set.class.isAssignableFrom(rawType)) - { - node.setUniqueItems(true); - } - - DataType componentModel = createNode(parameterizedType - .getActualTypeArguments()[0], null, null, null); - node.setItems(new Items(componentModel)); - } - else - { - System.err.println("Unhandled generic type: " + target); - return node; - // throw new IllegalArgumentException("Unhandled generic type: " - // + target); - } - } - else - { - System.err.println("Unhandled type: " + target); - return node; - // throw new UnsupportedOperationException("Unhandled type: " + - // target); - } - - return node; - } - - private void processFields(Map properties, Class target, String modelName) - { - for (Field field : target.getDeclaredFields()) - { - if ((field.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) == 0) - { - PropertyMetadata propertyMetadata = getPropertyMetadataFromField(field); - - // Ignore all properties that are marked as hidden - if (propertyMetadata != null && propertyMetadata.hidden) - { - continue; - } - - //Ignore properties that are marked to be excluded from this model - if(propertyMetadata != null && propertyMetadata.excludeFromModels != null) - { - String modelId = getModelId(target, modelName); - if(Arrays.asList(propertyMetadata.excludeFromModels).contains(modelId)) - { - continue; - } - } - - if (propertyMetadata == null) { - DataType property = createNode(field.getGenericType(), null, null, null) - .setProperty(field.getName()); - properties.put(field.getName(), property); - } - else if(!properties.containsKey(field.getName())) - { - DataType property = createNode(field.getGenericType(), null, propertyMetadata.dataType, propertyMetadata.format) - .setDescription(propertyMetadata.notes) - .setRequired(propertyMetadata.required) - .setPosition(propertyMetadata.position) - .setDefaultValue(propertyMetadata.defaultValue) - .setProperty(field.getName()); - properties.put(field.getName(), property); - } - else - { - DataType property = createNode(field.getGenericType(), null, propertyMetadata.dataType, propertyMetadata.format) - .setProperty(field.getName()); - properties.put(field.getName(), property); - } - } - } - } - - private String getModelId(Class target, String modelName) - { - String id = null; - if(modelName != null && !modelName.isEmpty()) - { - id = modelName; - } - else - { - id = target.getSimpleName(); - } - - return id; - } - - //The logic of pulling the data out of the field annotation is encapsulated here to stay backward compatible - //with consumers using the com.wordnik.swagger.annotations.ApiModelProperty annotation. - private PropertyMetadata getPropertyMetadataFromField(Field field) - { - PropertyMetadata propertyMetadata = null; - if(field != null) { - for(Annotation a : field.getAnnotations()) - { - if (a instanceof ApiModelProperty) - { - ApiModelProperty model = (ApiModelProperty) a; - propertyMetadata = new PropertyMetadata(); - propertyMetadata.allowableValues = model.allowableValues(); - propertyMetadata.access = model.access(); - propertyMetadata.notes = model.notes(); - propertyMetadata.dataType = model.dataType(); - propertyMetadata.format = model.format(); - propertyMetadata.required = model.required(); - propertyMetadata.position = model.position(); - propertyMetadata.hidden = model.hidden(); - propertyMetadata.excludeFromModels = model.excludeFromModels(); - if(model.defaultValue() != null && model.defaultValue() != "") - { - try - { - if(field.getType().isArray()) { - propertyMetadata.defaultValue = SwaggerObjectConverter.convertObjectTo(model.defaultValue(), field.getType().getComponentType()); - } - else { - propertyMetadata.defaultValue = SwaggerObjectConverter.convertObjectTo(model.defaultValue(), field.getType()); - } - } - catch(Exception ex) - { - - } - } - break; - } - else if (a instanceof com.wordnik.swagger.annotations.ApiModelProperty) - { - com.wordnik.swagger.annotations.ApiModelProperty model = (com.wordnik.swagger.annotations.ApiModelProperty) a; - propertyMetadata = new PropertyMetadata(); - propertyMetadata.value = model.value(); - propertyMetadata.allowableValues = model.allowableValues(); - propertyMetadata.access = model.access(); - propertyMetadata.notes = model.notes(); - propertyMetadata.dataType = model.dataType(); - propertyMetadata.required = model.required(); - propertyMetadata.position = model.position(); - propertyMetadata.hidden = model.hidden(); - break; - } - } - } - - return propertyMetadata; - } - - private class PropertyMetadata - { - String value = ""; - String allowableValues = ""; - String access = ""; - String notes = ""; - String dataType = ""; - String format = ""; - boolean required = false; - int position = 0; - boolean hidden = false; - String[] excludeFromModels = {}; - Object defaultValue = null; - } -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/SwaggerController.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/SwaggerController.java index 33a05b8..c97760a 100644 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/SwaggerController.java +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/SwaggerController.java @@ -1,5 +1,6 @@ /* Copyright 2013, Strategic Gains, Inc. + Copyright 2017, pulsIT UG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,114 +17,91 @@ package com.strategicgains.restexpress.plugin.swagger; import java.lang.reflect.Method; +import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.List; -import java.util.Map; +import java.util.regex.Pattern; import org.restexpress.Request; import org.restexpress.Response; import org.restexpress.RestExpress; -import org.restexpress.exception.NotFoundException; import org.restexpress.route.Route; import org.restexpress.route.RouteBuilder; import org.restexpress.util.Callback; -import com.strategicgains.restexpress.plugin.swagger.domain.ApiDeclarations; -import com.strategicgains.restexpress.plugin.swagger.domain.ApiOperation; -import com.strategicgains.restexpress.plugin.swagger.domain.ApiResources; +import com.strategicgains.restexpress.plugin.swagger.wrapper.OpenApi; +import com.strategicgains.restexpress.plugin.swagger.wrapper.Operation; +import com.strategicgains.restexpress.plugin.swagger.wrapper.PathItem; -/** - * @author toddf - * @since Nov 21, 2013 - */ -public class SwaggerController -implements Callback -{ - public static final List VALID_METHODS = new ArrayList( - Arrays.asList(new String[] - { - "GET", "PUT", "POST", "DELETE", "HEAD", "PATCH" - })); +public class SwaggerController implements Callback { + public static final List VALID_METHODS = new ArrayList(Arrays.asList(new String[] { "GET", "PUT", "POST", "DELETE", "HEAD", "PATCH" })); - // Determines if the route will show in swagger output if it is not annotated - // if set to true then route must be explicitly annotated with ApiOperation to show in swagger - // if false then all routes will show in swagger unless ApiOperation.hidden is set to true - //(backward compatiblility means this should be false unless explicitly set) + // if set to true then route must be explicitly annotated with ApiOperation to + // show in swagger + // if false then all routes will show in swagger unless ApiOperation.hidden is + // set to true + // (backward compatiblility means this should be false unless explicitly set) private boolean shouldShowAnnotatedOnly = false; - private RestExpress server; - private ApiResources resources; - private Map apisByPath = new HashMap(); + protected RestExpress server; + private OpenApi openApi; + private String basePath; private String swaggerRoot; - - public SwaggerController(RestExpress server, String apiVersion, String swaggerVersion, boolean shouldShowAnnotatedOnly) - { - this(server,apiVersion,swaggerVersion); - this.shouldShowAnnotatedOnly = shouldShowAnnotatedOnly; - } - public SwaggerController(RestExpress server, String apiVersion, String swaggerVersion) - { + private String filterByTag = ""; + private List routes = new ArrayList(); + + public SwaggerController(RestExpress server, OpenApi openApi, String basePath, String swaggerVersion, boolean shouldShowAnnotatedOnly) { + this(server, swaggerVersion, openApi, basePath); + this.shouldShowAnnotatedOnly = shouldShowAnnotatedOnly; + } + + public SwaggerController(RestExpress server, String swaggerVersion, OpenApi openApi, String basePath) { super(); - this.resources = new ApiResources(apiVersion, swaggerVersion); + this.openApi = openApi; + this.basePath = basePath; this.server = server; } - public void initialize(String urlPath, RestExpress server) - { + public void initialize(String urlPath, RestExpress server) { swaggerRoot = getPathSegment(urlPath); server.iterateRouteBuilders(this); } - public ApiResources readAll(Request request, Response response) - { - return resources; - } - - public ApiDeclarations read(Request request, Response response) - { - String path = request.getHeader("path"); - ApiDeclarations api = apisByPath.get("/" + path); - - if (api == null) throw new NotFoundException(path); - - if (!api.hasBasePath()) - { - ApiDeclarations apid = new ApiDeclarations(api); - apid.setBasePath(request.getBaseUrl()); - return apid; - } - - return api; + public OpenApi readAll(Request request, Response response) { + try { + String filter = URLDecoder.decode(request.getQueryStringMap().getOrDefault("byTag", ""), "UTF-8"); + if(!filterByTag.equals(filter)) { + filterByTag = filter; + openApi.getPaths().clear(); + for(RouteBuilder r : routes) { + process(r); + } + } + } catch (Exception e) { } + + return openApi; } /** - * Returns the first part of the URL path. Either the leading slash to the - * first period ('.') or the first slash to the second slash. + * Returns the first part of the URL path. Either the leading slash to the first + * period ('.') or the first slash to the second slash. * - * @param pattern - * a URL pattern. + * @param pattern a URL pattern. * @return */ - private String getPathSegment(String pattern) - { + private String getPathSegment(String pattern) { int slash = pattern.indexOf('/', 1); int dot = pattern.indexOf('.', 1); String path; - if (slash > 0) - { + if (slash > 0) { path = pattern.substring(0, slash); - } - else if (dot > 0) - { + } else if (dot > 0) { path = pattern.substring(0, dot); - } - else - { + } else { path = pattern; } @@ -131,45 +109,65 @@ else if (dot > 0) } @Override - public void process(RouteBuilder routeBuilder) - { - for (Route route : routeBuilder.build()) - { - if (!VALID_METHODS.contains(route.getMethod().name())) continue; - - String path = getPathSegment(route.getPattern()); + public void process(RouteBuilder routeBuilder) { + if(!routes.contains(routeBuilder)) { + routes.add(routeBuilder); + } + for (Route route : routeBuilder.build()) { + if (!VALID_METHODS.contains(route.getMethod().name())) + continue; + + String routePath = route.getPattern(); + String path = ""; + if(routePath.startsWith(basePath)){ + routePath = routePath.substring(basePath.length()); + path = getPathSegment(routePath); + } else { + path = getPathSegment(routePath); + } + path = routePath; // Don't report the Swagger routes... - if (swaggerRoot.equals(path)) continue; + if (swaggerRoot.equals(path)) + continue; // Don't report the / route. It will not be resolved. - if ("/".equals(path)) continue; + if ("/".equals(path)) + continue; + + if (isRouteHidden(route)) + continue; - if(isRouteHidden(route)) continue; - ApiDeclarations apis = apisByPath.get(path); - - if (apis == null) // new path to document - { - apis = new ApiDeclarations(resources, server, path); - apisByPath.put(path, apis); - // TODO: pull the description from the route metadata (not - // currently available). - resources.addApi(path, null); + Operation operation; + Method m = route.getAction(); + + if (m.isAnnotationPresent(io.swagger.oas.annotations.Operation.class)) { + operation = new Operation(m.getAnnotation(io.swagger.oas.annotations.Operation.class)); + } else { + operation = new Operation(); + } + + operation.setOperationId(route.getController().getClass().getName() + "::" + route.getAction().getName()); + if(filterByTag != null && filterByTag.length() > 0 && operation != null && operation.getTags() != null && (operation.getTags().stream().filter(Pattern.compile(filterByTag).asPredicate()).findFirst().orElse(null) == null)) { + continue; + } + + PathItem p = openApi.getPaths().get(path); + if(p != null) { + p.add(route.getMethod().name(), operation); + } else { + p = new PathItem(); + p.add(route.getMethod().name(), operation); + openApi.getPaths().put(path, p); } - - ApiOperation operation = apis.addOperation(route); - apis.addModels(operation, route); } } - private boolean isRouteHidden(Route route) - { + private boolean isRouteHidden(Route route) { Method method = route.getAction(); - if (method.isAnnotationPresent(com.wordnik.swagger.annotations.ApiOperation.class)) - { - com.wordnik.swagger.annotations.ApiOperation annotation = method.getAnnotation(com.wordnik.swagger.annotations.ApiOperation.class); - return annotation.hidden(); + if (method.isAnnotationPresent(io.swagger.oas.annotations.Operation.class)) { + return (method.isAnnotationPresent(io.swagger.oas.annotations.Hidden.class)); } return shouldShowAnnotatedOnly; diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/SwaggerPlugin.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/SwaggerPlugin.java index 339ba98..30e7b34 100644 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/SwaggerPlugin.java +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/SwaggerPlugin.java @@ -1,5 +1,6 @@ /* Copyright 2013, Strategic Gains, Inc. + Copyright 2017, pulsIT UG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,105 +18,87 @@ import java.util.Map.Entry; -import io.netty.handler.codec.http.HttpMethod; -import org.restexpress.Format; import org.restexpress.RestExpress; import org.restexpress.plugin.RoutePlugin; import org.restexpress.route.RouteBuilder; -/** - * @author toddf - * @since Nov 21, 2013 - */ -public class SwaggerPlugin -extends RoutePlugin -{ - private static final String SWAGGER_VERSION = "1.2"; +import com.strategicgains.restexpress.plugin.swagger.wrapper.OpenApi; + +import io.netty.handler.codec.http.HttpMethod; + +public class SwaggerPlugin extends RoutePlugin { + private static final String SWAGGER_VERSION = "3.5.0"; private SwaggerController controller; private String urlPath; - private String apiVersion; + private String swaggerVersion = SWAGGER_VERSION; private boolean defaultToHidden = false; - + private OpenApi openApi; + private String basePath = ""; - public SwaggerPlugin() - { - this("/api-docs"); + public SwaggerPlugin(OpenApi openApi) { + this("/api-docs", openApi); } - public SwaggerPlugin(String urlPath) - { + public SwaggerPlugin(String urlPath, OpenApi openApi) { super(); this.urlPath = urlPath; + this.openApi = openApi; } - public SwaggerPlugin apiVersion(String version) - { - this.apiVersion = version; - return this; - } - - public SwaggerPlugin swaggerVersion(String version) - { + public SwaggerPlugin swaggerVersion(String version) { this.swaggerVersion = version; return this; } @Override - public SwaggerPlugin register(RestExpress server) - { - if (isRegistered()) return this; + public SwaggerPlugin register(RestExpress server) { + if (isRegistered()) + return this; super.register(server); - controller = new SwaggerController(server, apiVersion, swaggerVersion, isDefaultToHidden()); + controller = new SwaggerController(server, openApi, basePath, swaggerVersion, isDefaultToHidden()); - RouteBuilder resources = server.uri(urlPath, controller) - .action("readAll", HttpMethod.GET).name("swagger.resources") - .format(Format.JSON); + RouteBuilder resources = server.uri(urlPath , controller).action("readAll", HttpMethod.GET).name("swagger.resources"); - RouteBuilder apis = server.uri(urlPath + "/{path}", controller) - .method(HttpMethod.GET).name("swagger.apis").format(Format.JSON); - - for (String flag : flags()) - { + for (String flag : flags()) { resources.flag(flag); - apis.flag(flag); } - for (Entry entry : parameters().entrySet()) - { + for (Entry entry : parameters().entrySet()) { resources.parameter(entry.getKey(), entry.getValue()); - apis.parameter(entry.getKey(), entry.getValue()); } return this; } @Override - public void bind(RestExpress server) - { + public void bind(RestExpress server) { controller.initialize(urlPath, server); } - public boolean isDefaultToHidden() - { + public boolean isDefaultToHidden() { return defaultToHidden; } /** * When set to true the swagger documentation is not visible unless an - * ApiOperation annotation exists for the controller method. This allows - * control over which apis are advertised and which are not visible to the - * public + * ApiOperation annotation exists for the controller method. This allows control + * over which apis are advertised and which are not visible to the public * * @param defaultToHidden * @return returns this (in order to chain commands) */ - public SwaggerPlugin setDefaultToHidden(boolean defaultToHidden) - { + public SwaggerPlugin setDefaultToHidden(boolean defaultToHidden) { this.defaultToHidden = defaultToHidden; return this; } + + public SwaggerPlugin setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + } diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/annotations/ApiModelProperty.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/annotations/ApiModelProperty.java deleted file mode 100644 index b3743af..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/annotations/ApiModelProperty.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.strategicgains.restexpress.plugin.swagger.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target( -{ - ElementType.METHOD, ElementType.FIELD -}) -@Retention(RetentionPolicy.RUNTIME) -public @interface ApiModelProperty -{ - String defaultValue() default ""; - String allowableValues() default ""; - String access() default ""; - String notes() default ""; - String dataType() default ""; - String format() default ""; - boolean required() default false; - int position() default 0; - boolean hidden() default false; - String[] excludeFromModels() default {}; -} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/annotations/ApiModelRequest.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/annotations/ApiModelRequest.java deleted file mode 100644 index 6fd43a7..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/annotations/ApiModelRequest.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.strategicgains.restexpress.plugin.swagger.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -public @interface ApiModelRequest -{ - Class model(); - boolean required() default false; - String modelName() default ""; -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiDeclaration.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiDeclaration.java deleted file mode 100644 index 6dbc5b7..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiDeclaration.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - Copyright 2013, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -import java.util.ArrayList; -import java.util.List; - -import org.restexpress.route.Route; - -/** - * @author toddf - * @since Nov 21, 2013 - * @see https://github.com/wordnik/swagger-core/wiki/Api-Declaration - */ -public class ApiDeclaration -{ - private String path; - private String description; - private List consumes; - private List produces; - private Authorizations authorizations; - private List operations = new ArrayList(); - - public ApiDeclaration(Route route) - { - super(); - this.path = route.getPattern(); - this.description = route.getName(); - } - - public ApiDeclaration(String path, String description) - { - this.path = path; - this.description = description; - } - - public ApiDeclaration operation(ApiOperation operation) - { - operations.add(operation); - return this; - } - - public ApiDeclaration authorization(String key, Authorization authn) - { - if (authorizations == null) - { - authorizations = new Authorizations(); - } - - authorizations.put(key, authn); - return this; - } - - public ApiDeclaration consumes(String contentType) - { - if (consumes == null) - { - consumes = new ArrayList(); - } - - if (!consumes.contains(contentType)) - { - consumes.add(contentType); - } - - return this; - } - - public ApiDeclaration produces(String contentType) - { - if (produces == null) - { - produces = new ArrayList(); - } - - if (!produces.contains(contentType)) - { - produces.add(contentType); - } - - return this; - } - - public String getPath() - { - return path; - } - - public String getDescription() - { - return description; - } -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiDeclarations.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiDeclarations.java deleted file mode 100644 index 91c0a04..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiDeclarations.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - Copyright 2013, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.restexpress.RestExpress; -import org.restexpress.route.Route; - -import com.strategicgains.restexpress.plugin.swagger.ModelResolver; -import com.strategicgains.restexpress.plugin.swagger.annotations.ApiModelRequest; - -/** - * @author toddf - * @since Nov 21, 2013 - * @see https://github.com/wordnik/swagger-core/wiki/Api-Declaration - */ -public class ApiDeclarations -{ - private String apiVersion; - private String swaggerVersion; - private String basePath; - private String resourcePath; - private List consumes; - private List produces; - private List apis = new ArrayList(); - private transient Map apisByPath = new LinkedHashMap(); - private Map models = new HashMap(); - - public ApiDeclarations(ApiDeclarations that) - { - this.apiVersion = that.apiVersion; - this.swaggerVersion = that.swaggerVersion; - this.basePath = that.basePath; - this.resourcePath = that.resourcePath; - this.consumes = that.consumes; - this.produces = that.produces; - this.apis = that.apis; - this.apisByPath = that.apisByPath; - this.models = that.models; - } - - public ApiDeclarations(ApiResources api, RestExpress server, String path) - { - this.apiVersion = api.getApiVersion(); - this.swaggerVersion = api.getSwaggerVersion(); - this.basePath = computeBasePath(server.getBaseUrl()); - this.resourcePath = path; - } - - private String computeBasePath(String baseUrl) - { - return ((baseUrl == null || (baseUrl.startsWith("{") && baseUrl.endsWith("}"))) ? null : baseUrl); - } - - public String getBasePath() - { - return basePath; - } - - public boolean hasBasePath() - { - return (basePath != null); - } - - public void setBasePath(String basePath) - { - this.basePath = basePath; - } - - public void addApi(ApiDeclaration api) - { - apis.add(api); - apisByPath.put(api.getPath(), api); - } - - public ApiDeclarations consumes(String contentType) - { - if (consumes == null) - { - consumes = new ArrayList(); - } - - if (!consumes.contains(contentType)) - { - consumes.add(contentType); - } - - return this; - } - - public ApiDeclarations produces(String contentType) - { - if (produces == null) - { - produces = new ArrayList(); - } - - if (!produces.contains(contentType)) - { - produces.add(contentType); - } - - return this; - } - - public ApiDeclarations addModel(ApiModel model) - { - if (!models.containsKey(model.getId())) - { - models.put(model.getId(), model); - } - - return this; - } - - public Map getModels() - { - return models; - } - - public ApiOperation addOperation(Route route) - { - ApiDeclaration apiDeclaration = apisByPath.get(route.getPattern()); - - if (apiDeclaration == null) - { - apiDeclaration = new ApiDeclaration(route); - addApi(apiDeclaration); - } - - ApiOperation operation = new ApiOperation(route); - apiDeclaration.operation(operation); - return operation; - } - - public void addModels(ApiOperation operation, Route route) - { - ModelResolver resolver = new ModelResolver(models); - // Swagger defaults response to Void.class, so if response was not set in the annotation and - // the method has a valid response type this will get set to Void. Do we want to default to - // Reflection if response is Void? Only issue with this is if the method returns an object, - // but the response is explicitly set to Void. - DataType returnType = null; - if(operation.getResponse() != null && operation.getResponse() != Void.class) { - //operation.setType(operation.getResponse().getSimpleName()); - returnType = resolver.resolve(operation.getResponse()); - } else { - returnType = resolver.resolve(route.getAction().getGenericReturnType()); - } - if (returnType.getRef() != null) - { - operation.setType(returnType.getRef()); - } - else - { - operation.setType(returnType.getType()); - operation.setItems(returnType.getItems()); - } - - ApiModelRequest apiModelRequest = route.getAction().getAnnotation( - ApiModelRequest.class); - - if (apiModelRequest != null) - { - DataType bodyType = resolver.resolve(apiModelRequest.model(), apiModelRequest.modelName()); - String type =bodyType.getRef() != null ? bodyType.getRef() : bodyType.getType(); - ApiOperationParameters bodyParam = new ApiOperationParameters("body", "body", - type, apiModelRequest.required()); - // if the body is an array then we need to set items - if("array".equals(bodyParam .getType())) { - bodyParam.setItems(bodyType.getItems()); - } - operation.addParameter(bodyParam); - - } - } -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiKeys.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiKeys.java deleted file mode 100644 index ad3b79a..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiKeys.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -/** - * @author toddf - * @since Apr 1, 2014 - */ -public enum ApiKeys -{ - header, query -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiModel.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiModel.java deleted file mode 100644 index a5b6b6f..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiModel.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - Copyright 2013, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -/** - * @author toddf - * @since Nov 21, 2013 - */ -public class ApiModel -{ - private String id; - private Set required; - private Map properties; - private String description; - private Object defaultValue; - - public String getId() - { - return id; - } - - public String getDescription() - { - return description; - } - - public ApiModel id(String id) - { - this.id = id; - return this; - } - - public ApiModel description(String description) - { - this.description = description; - return this; - } - - public ApiModel required(String property) - { - if (required == null) - { - required = new HashSet(); - } - - required.add(property); - return this; - } - - public ApiModel property(DataType property) - { - if (properties == null) - { - properties = new LinkedHashMap(); - } - - if (!properties.containsKey(property.getProperty())) - { - properties.put(property.getProperty(), property); - } - - return this; - } - - public Object getDefaultValue() { - return defaultValue; - } - - public ApiModel setDefaultValue(Object defaultValue) { - this.defaultValue = defaultValue; - return this; - } -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiOperation.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiOperation.java deleted file mode 100644 index 9669827..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiOperation.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - Copyright 2013, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -import org.restexpress.route.Route; - -/** - * @author toddf - * @since Nov 21, 2013 - */ -public class ApiOperation -extends DataType -{ - private String method; - private String nickname = ""; - private List parameters; - private String summary = ""; - private String notes; - private List responseMessages; - private Class response; - - public ApiOperation(Route route) - { - this.parameters = new ArrayList(); - - // TODO: use Swagger annotation on controller method, if present. - // Get the method from the route - Method m = route.getAction(); - if (m - .isAnnotationPresent(com.wordnik.swagger.annotations.ApiOperation.class)) - { - com.wordnik.swagger.annotations.ApiOperation ao = m - .getAnnotation(com.wordnik.swagger.annotations.ApiOperation.class); - // Both value and notes are used as descriptions in ApiOperation - // annotation. - // value is a brief description, notes a more detailed description. - if (ao.value() != null) summary = ao.value(); - if (ao.notes() != null) notes = ao.notes(); - if (ao.response() != null) { - response = ao.response(); - } - } - - this.method = route.getMethod().name(); - String name = route.getName(); - this.nickname = method + (name == null ? "" : name); - this.nickname = nickname.replaceAll("[^a-zA-Z0-9_]",""); - - if (route.getUrlParameters() == null) return; - - for (String param : route.getUrlParameters()) - { - if (param.equals("format")) continue; - - addParameter(new ApiOperationParameters("path", param, "string", true)); - } - - // TODO: determine body/input parameters. - // For now depend on the swagger annotation for body/input specific - // parameters. - determineBodyInputParameters(m); - - // Check for any swagger responseMessages - checkForSwaggerResponseAnnotations(m); - - } - - /** - * Add operation parameter - * - * @param param - */ - public void addParameter(ApiOperationParameters param) - { - parameters.add(param); - } - - /** - * Add response to the errorResponse list - * - * @param response - */ - public void addResponse(ApiResponse response) - { - if (responseMessages == null) - { - responseMessages = new ArrayList(); - } - - responseMessages.add(response); - } - - /** - * Process any swagger annotations relating to parameters passed in the - * body. - * - * Swagger annotations are @ApiParam, @ApiImplicitParam and - * @ApiImplicitParams, a collection of @ApiImplicitParam annotations. - * - * @param method - * - Controller method - */ - public void determineBodyInputParameters(Method method) - { - if (method - .isAnnotationPresent(com.wordnik.swagger.annotations.ApiParam.class)) - { - com.wordnik.swagger.annotations.ApiParam ap = method - .getAnnotation(com.wordnik.swagger.annotations.ApiParam.class); - ApiOperationParameters inputParam = new ApiOperationParameters( - "body", ap.name(), "string", ap.required()); - if (ap.allowableValues() != null - && !ap.allowableValues().equals("")) - inputParam.setAllowableValues(ap.allowableValues()); - if (ap.value() != null && !ap.value().equals("")) - inputParam.setDescription(ap.value()); - if (ap.defaultValue() != null && !ap.defaultValue().equals("")) - inputParam.setDefaultValue(ap.defaultValue()); - - addParameter(inputParam); - } - if (method - .isAnnotationPresent(com.wordnik.swagger.annotations.ApiImplicitParam.class)) - { - com.wordnik.swagger.annotations.ApiImplicitParam aip = method - .getAnnotation(com.wordnik.swagger.annotations.ApiImplicitParam.class); - ApiOperationParameters inputParam = new ApiOperationParameters( - aip.paramType(), aip.name(), aip.dataType(), aip.required()); - if (aip.allowableValues() != null - && !aip.allowableValues().equals("")) - inputParam.setAllowableValues(aip.allowableValues()); - if (aip.value() != null && !aip.value().equals("")) - inputParam.setDescription(aip.value()); - addParameter(inputParam); - } - if (method - .isAnnotationPresent(com.wordnik.swagger.annotations.ApiImplicitParams.class)) - { - com.wordnik.swagger.annotations.ApiImplicitParams aip = method - .getAnnotation(com.wordnik.swagger.annotations.ApiImplicitParams.class); - for (com.wordnik.swagger.annotations.ApiImplicitParam ip : aip - .value()) - { - ApiOperationParameters inputParam = new ApiOperationParameters( - ip.paramType(), ip.name(), ip.dataType(), ip.required()); - if (ip.allowableValues() != null - && !ip.allowableValues().equals("")) - inputParam.setAllowableValues(ip.allowableValues()); - if (ip.value() != null && !ip.value().equals("")) - inputParam.setDescription(ip.value()); - addParameter(inputParam); - } - } - } - - /** - * Process any swagger ApiResponse annotations - * - * Swagger response annotations are @ApiResponse and @ApiResponses, a - * collection of @ApiResponse annotations. - * - * @param m - */ - public void checkForSwaggerResponseAnnotations(Method m) - { - if (m - .isAnnotationPresent(com.wordnik.swagger.annotations.ApiResponse.class)) - { - com.wordnik.swagger.annotations.ApiResponse ar = m - .getAnnotation(com.wordnik.swagger.annotations.ApiResponse.class); - ApiResponse apiResponse = new ApiResponse(ar.code(), ar.message()); - addResponse(apiResponse); - } - else if (m - .isAnnotationPresent(com.wordnik.swagger.annotations.ApiResponses.class)) - { - com.wordnik.swagger.annotations.ApiResponses ar = m - .getAnnotation(com.wordnik.swagger.annotations.ApiResponses.class); - for (com.wordnik.swagger.annotations.ApiResponse r : ar.value()) - { - ApiResponse apiResponse = new ApiResponse(r.code(), r.message()); - addResponse(apiResponse); - } - } - - } - - /** - * Return the response class - * @return - */ - public Class getResponse() { - return response; - } - -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiOperationParameters.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiOperationParameters.java deleted file mode 100644 index 3bad9c8..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiOperationParameters.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - Copyright 2013, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -/** - * @author toddf - * @since Nov 22, 2013 - */ -public class ApiOperationParameters -extends DataType -{ - private String paramType; // path, query, body, header, form - private String name; - private String format; - private boolean required; // must be true for query paramType - private Boolean allowMultiple; - private String allowableValues; // values allowed for the parameter, matches - // Swagger annotation value in - // @ApiImplicitParam - private String defaultValue; - - public ApiOperationParameters(String paramType, String name, String type, - boolean isRequired) - { - super(); - this.paramType = paramType; - this.name = name; - this.required = isRequired; - setType(type); - } - - /** - * Allowable values for the operation parameter. - * - * @param value - */ - public void setAllowableValues(String value) - { - allowableValues = value; - } - - public void setDefaultValue(String defaultValue) - { - this.defaultValue = defaultValue; - } - -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiResource.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiResource.java deleted file mode 100644 index ebcbf1d..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiResource.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright 2013, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -/** - * @author toddf - * @since Nov 21, 2013 - */ -public class ApiResource -{ - private String path; - private String description; - - public ApiResource(String path) - { - this(path, null); - } - - public ApiResource(String path, String description) - { - super(); - this.path = path; - this.description = description; - } - - @Override - public int hashCode() - { - return path.hashCode() - + (description == null ? 0 : description.hashCode()); - } - - @Override - public boolean equals(Object o) - { - ApiResource that = (ApiResource) o; - return (path.equals(that.path) && ((description == null && that.description == null) || (description != null && description - .equals(that.description)))); - } -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiResources.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiResources.java deleted file mode 100644 index 328580e..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiResources.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright 2013, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * @author toddf - * @since Nov 21, 2013 - */ -public class ApiResources -{ - private String apiVersion; - private String swaggerVersion; - private Info info; - private Authorizations authorizations; - private List apis = new ArrayList(); - - public ApiResources(String apiVersion, String swaggerVersion) - { - super(); - this.apiVersion = apiVersion; - this.swaggerVersion = swaggerVersion; - } - - public String getApiVersion() - { - return apiVersion; - } - - public String getSwaggerVersion() - { - return swaggerVersion; - } - - public List getApis() - { - return Collections.unmodifiableList(apis); - } - - public void addApi(String path, String description) - { - addApi(new ApiResource(path, description)); - } - - public void addApi(ApiResource api) - { - apis.add(api); - } -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiResponse.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiResponse.java deleted file mode 100644 index e618c2a..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ApiResponse.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.strategicgains.restexpress.plugin.swagger.domain; - -/** - * ApiResponse object to match Swagger annotation @ApiResponse - * - * @author uritzry Since May 1, 2014 - * @since May 1, 2014 - */ -public class ApiResponse -extends DataType -{ - // HTTP Response Code - private int code; - - // Reason for the response code used. - private String message; - - public ApiResponse(int code, String message) - { - this.code = code; - this.message = message; - } - - public int getCode() - { - return code; - } - - public String getMessage() - { - return message; - } -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Authorization.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Authorization.java deleted file mode 100644 index e9996f4..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Authorization.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -import java.util.List; - -/** - * @author toddf - * @since Apr 1, 2014 - */ -public class Authorization -{ - private AuthorizationTypes type; // 'basicAuth' | 'apiKey' | 'oauth2' - private ApiKeys passAs; // 'header' | 'query' - private ApiKeys keyname; // 'header' | 'query' - private List scopes; - private GrantTypes grantTypes; - - public Authorization(AuthorizationTypes type, ApiKeys passAs, - ApiKeys keyname) - { - super(); - this.type = type; - this.passAs = passAs; - this.keyname = keyname; - } - - public List getScopes() - { - return scopes; - } - - public void setScopes(List scopes) - { - this.scopes = scopes; - } - - public GrantTypes getGrantTypes() - { - return grantTypes; - } - - public void setGrantTypes(GrantTypes grantTypes) - { - this.grantTypes = grantTypes; - } - - public AuthorizationTypes getType() - { - return type; - } - - public ApiKeys getPassAs() - { - return passAs; - } - - public ApiKeys getKeyname() - { - return keyname; - } -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/AuthorizationTypes.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/AuthorizationTypes.java deleted file mode 100644 index 8e8a857..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/AuthorizationTypes.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -/** - * @author toddf - * @since Apr 1, 2014 - */ -public enum AuthorizationTypes -{ - basicAuth, apiKey, oauth2 -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Authorizations.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Authorizations.java deleted file mode 100644 index db76beb..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Authorizations.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -import java.util.HashMap; - -/** - * @author toddf - * @since Apr 1, 2014 - */ -public class Authorizations -extends HashMap -{ - private static final long serialVersionUID = -970523650140785684L; -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/DataType.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/DataType.java deleted file mode 100644 index e5f6305..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/DataType.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.HashSet; -import java.util.Set; - -/** - * @author russtrotter - */ -public class DataType -{ - private String type; - private String format; - private String $ref; - private Boolean uniqueItems; - private String description; - private Items items; - private Object defaultValue; - - // Note, since "enum" is a java reserved word, we have to override the - // serialized name - @JsonProperty("enum") - private Set enumeration; - - // The transient fields disable gson/jackson serialization. We only use it - // during model building - private transient boolean primitive = false; - private transient String property; - private transient boolean required; - private transient int position = 0; - - public String getType() - { - return type; - } - - public DataType setType(Primitives primitive) - { - setType(primitive.type()); - setFormat(primitive.format()); - setPrimitive(true); - return this; - } - - public DataType setType(String type) - { - this.type = type; - return this; - } - - public String getFormat() - { - return format; - } - - public DataType setFormat(String format) - { - this.format = format; - return this; - } - - public String getRef() - { - return $ref; - } - - public DataType setRef(String ref) - { - this.$ref = ref; - return this; - } - - public Boolean getUniqueItems() - { - return uniqueItems; - } - - public DataType setUniqueItems(Boolean uniqueItems) - { - this.uniqueItems = uniqueItems; - return this; - } - - public boolean isRequired() - { - return required; - } - - public DataType setRequired(boolean required) - { - this.required = required; - return this; - } - - public String getDescription() - { - return description; - } - - public DataType setDescription(String description) - { - // treat empty strings as nulls so we don't get JSON - // generated for this field in those cases - if (description != null && description.length() > 0) - { - this.description = description; - } - - return this; - } - - public Items getItems() - { - return items; - } - - public DataType setItems(Items items) - { - this.items = items; - return this; - } - - public int getPosition() - { - return position; - } - - public DataType setPosition(int position) - { - this.position = position; - return this; - } - - public String getProperty() - { - return property; - } - - public DataType setProperty(String property) - { - this.property = property; - return this; - } - - public DataType addEnum(String value) - { - if (enumeration == null) - { - enumeration = new HashSet(); - } - - enumeration.add(value); - return this; - } - - public boolean isPrimitive() - { - return primitive; - } - - public DataType setPrimitive(boolean primitive) - { - this.primitive = primitive; - return this; - } - - public Object getDefaultValue() { - return defaultValue; - } - - public DataType setDefaultValue(Object defaultValue) { - this.defaultValue = defaultValue; - return this; - } -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/GrantTypes.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/GrantTypes.java deleted file mode 100644 index ee9a861..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/GrantTypes.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -/** - * @author toddf - * @since Apr 1, 2014 - */ -public class GrantTypes -{ - -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ImplicitGrantType.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ImplicitGrantType.java deleted file mode 100644 index 07a772d..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/ImplicitGrantType.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -/** - * @author toddf - * @since Apr 1, 2014 - */ -public class ImplicitGrantType -{ - private String tokenName; - private LoginEndpoint loginEndpoint; - - public ImplicitGrantType(String loginEndpoint) - { - super(); - this.loginEndpoint = new LoginEndpoint(loginEndpoint); - } - - public String getTokenName() - { - return tokenName; - } - - public void setTokenName(String tokenName) - { - this.tokenName = tokenName; - } - - public String getLoginEndpoint() - { - return (loginEndpoint == null ? null : loginEndpoint.getUrl()); - } - - public class LoginEndpoint - { - private String url; - - public LoginEndpoint(String url) - { - super(); - this.url = url; - } - - public String getUrl() - { - return url; - } - } -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Info.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Info.java deleted file mode 100644 index 07cc429..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Info.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -/** - * @author toddf - * @since Apr 1, 2014 - */ -public class Info -{ - private String title; - private String description; - private String termsOfServiceUrl; - private String contact; - private String license; - private String licenseUrl; - - public Info(String title, String description) - { - super(); - this.title = title; - this.description = description; - } - - public String getTermsOfServiceUrl() - { - return termsOfServiceUrl; - } - - public void setTermsOfServiceUrl(String termsOfServiceUrl) - { - this.termsOfServiceUrl = termsOfServiceUrl; - } - - public String getContact() - { - return contact; - } - - public void setContact(String contact) - { - this.contact = contact; - } - - public String getLicense() - { - return license; - } - - public void setLicense(String license) - { - this.license = license; - } - - public String getLicenseUrl() - { - return licenseUrl; - } - - public void setLicenseUrl(String licenseUrl) - { - this.licenseUrl = licenseUrl; - } - - public String getTitle() - { - return title; - } - - public String getDescription() - { - return description; - } -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Items.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Items.java deleted file mode 100644 index 82a907e..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Items.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -/** - * @author toddf - * @since Apr 4, 2014 - */ -public class Items -{ - private String type; - private String format; - private String $ref; - - public Items() - { - super(); - } - - public Items(DataType dataType) - { - this(); - this.type = dataType.getType(); - this.format = dataType.getFormat(); - this.$ref = dataType.getRef(); - } - - public String getType() - { - return type; - } - - public void setType(String type) - { - this.type = type; - } - - public String getFormat() - { - return format; - } - - public void setFormat(String format) - { - this.format = format; - } - - public String getRef() - { - return $ref; - } - - public void setRef(String ref) - { - this.$ref = ref; - } -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Primitives.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Primitives.java deleted file mode 100644 index 22a0790..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Primitives.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -/** - * @author toddf - * @since Apr 4, 2014 - */ -public enum Primitives -{ - INTEGER("integer", "int32"), - LONG("integer", "int64"), - FLOAT("number", "float"), - DOUBLE("number", "double"), - STRING("string", null), - BYTE("string", "byte"), - BOOLEAN("boolean", null), - DATE("string", "date"), - DATE_TIME("string", "date-time"), - VOID("void", null); - - private String type; - private String format; - - private Primitives(String type, String format) - { - this.type = type; - this.format = format; - } - - public String type() - { - return type; - } - - public String format() - { - return format; - } -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Scope.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Scope.java deleted file mode 100644 index 1ea7548..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/domain/Scope.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger.domain; - -/** - * @author toddf - * @since Apr 1, 2014 - */ -public class Scope -{ - -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/utilities/SwaggerObjectConverter.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/utilities/SwaggerObjectConverter.java deleted file mode 100644 index 8055ea0..0000000 --- a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/utilities/SwaggerObjectConverter.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.strategicgains.restexpress.plugin.swagger.utilities; - -import java.math.BigDecimal; -import java.util.Date; - -public class SwaggerObjectConverter -{ - public static T convertObjectTo(Object object, Class explicitType) - { - Object returnObject; - if (object == null) - { - returnObject = null; - } - else if (!object.getClass().isAssignableFrom(explicitType)) - { - final String toString = object.toString(); - if (explicitType.isAssignableFrom(Integer.class) - || explicitType.isAssignableFrom(int.class)) - { - returnObject = Integer.parseInt(toString); - } - else if (explicitType.isAssignableFrom(Boolean.class) - || explicitType.isAssignableFrom(boolean.class)) - { - returnObject = Boolean.parseBoolean(toString); - } - else if (explicitType.isAssignableFrom(Character.class) - || explicitType.isAssignableFrom(char.class)) - { - returnObject = toString.charAt(0); - } - else if (explicitType.isAssignableFrom(Byte.class) - || explicitType.isAssignableFrom(byte.class)) - { - returnObject = Byte.parseByte(toString); - } - else if (explicitType.isAssignableFrom(Short.class) - || explicitType.isAssignableFrom(short.class)) - { - returnObject = Short.parseShort(toString); - } - else if (explicitType.isAssignableFrom(Float.class) - || explicitType.isAssignableFrom(float.class)) - { - returnObject = Float.parseFloat(toString); - } - else if (explicitType.isAssignableFrom(Double.class) - || explicitType.isAssignableFrom(double.class)) - { - returnObject = Double.parseDouble(toString); - } - else if (explicitType.isAssignableFrom(Long.class) - || explicitType.isAssignableFrom(long.class)) - { - returnObject = Long.parseLong(toString); - } - else if (explicitType.isAssignableFrom(BigDecimal.class)) - { - returnObject = new BigDecimal(toString); - } - else if (explicitType.isAssignableFrom(Date.class)) - { - returnObject = new Date(toString); - } - else if (explicitType.isAssignableFrom(String.class)) - { - returnObject = toString; - } - else - { - try - { - returnObject = explicitType.cast(object); - } - catch (ClassCastException e) - { - throw new ClassCastException("Cannot convert " - + object.getClass() + " to $explicitType."); - } - } - } - else - { - returnObject = explicitType.cast(object); - } - return (T) returnObject; - } - - public static boolean canConvert(Object object, Class type) - { - try - { - convertObjectTo(object, type); - return true; - } - catch (Exception e) - { - return false; - } - } -} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Callback.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Callback.java new file mode 100644 index 0000000..15f5378 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Callback.java @@ -0,0 +1,11 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +/** + * @see https://swagger.io/specification/#callbackObject + */ +public class Callback extends Reference{ + //TODO: Callback is not implemented yet + public Callback(String ref) { + super(ref); + } +} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Components.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Components.java new file mode 100644 index 0000000..25adfa1 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Components.java @@ -0,0 +1,119 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import java.util.HashMap; +import java.util.Map; + +/** + * @see https://swagger.io/specification/#componentsObject + */ +public class Components { + private Map schemas; + private Map responses; + private Map parameters; + private Map examples; + private Map requestBodies; + private Map headers; + private Map securitySchemes; + private Map links; + private Map callbacks; + + public Map getSchemas() { + if(schemas == null) { + schemas = new HashMap(); + } + return schemas; + } + + public void setSchemas(Map schemas) { + this.schemas = schemas; + } + + public Map getResponses() { + if(responses == null) { + responses = new HashMap(); + } + return responses; + } + + public void setResponses(Map responses) { + this.responses = responses; + } + + public Map getParameters() { + if(parameters == null) { + parameters = new HashMap(); + } + return parameters; + } + + public void setParameters(Map parameters) { + this.parameters = parameters; + } + + public Map getExamples() { + if(examples == null) { + examples = new HashMap(); + } + return examples; + } + + public void setExamples(Map examples) { + this.examples = examples; + } + + public Map getRequestBodies() { + if(requestBodies == null) { + requestBodies = new HashMap(); + } + return requestBodies; + } + + public void setRequestBodies(Map requestBodies) { + this.requestBodies = requestBodies; + } + + public Map getHeaders() { + if(headers == null) { + headers = new HashMap(); + } + return headers; + } + + public void setHeaders(Map headers) { + this.headers = headers; + } + + public Map getSecuritySchemes() { + if(securitySchemes == null) { + securitySchemes = new HashMap(); + } + return securitySchemes; + } + + public void setSecuritySchemes(Map securitySchemes) { + this.securitySchemes = securitySchemes; + } + + public Map getLinks() { + if(links == null) { + links = new HashMap(); + } + return links; + } + + public void setLinks(Map links) { + this.links = links; + } + + public Map getCallbacks() { + if(callbacks == null) { + callbacks = new HashMap(); + } + return callbacks; + } + + public void setCallbacks(Map callbacks) { + this.callbacks = callbacks; + } + +} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Contact.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Contact.java new file mode 100644 index 0000000..6c9742d --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Contact.java @@ -0,0 +1,40 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +/** + * @see https://swagger.io/specification/#contactObject + */ +public class Contact { + private String name; + private String url; + private String email; + + public Contact(String name, String url, String email) { + setName(name); + setUrl(url); + setEmail(email); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Discriminator.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Discriminator.java new file mode 100644 index 0000000..9b7ac9d --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Discriminator.java @@ -0,0 +1,31 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import java.util.HashMap; +import java.util.Map; + +/** + * @see https://swagger.io/specification/#discriminatorObject + */ +public class Discriminator { + private String propertyName; + private Map mapping; + + public String getPropertyName() { + return propertyName; + } + + public void setPropertyName(String propertyName) { + this.propertyName = propertyName; + } + + public Map getMapping() { + if(mapping == null) { + mapping = new HashMap(); + } + return mapping; + } + + public void setMapping(Map mapping) { + this.mapping = mapping; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Encoding.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Encoding.java new file mode 100644 index 0000000..fd1f3bf --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Encoding.java @@ -0,0 +1,68 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import java.util.HashMap; +import java.util.Map; + +/** + * @see https://swagger.io/specification/#encodingObject + */ +public class Encoding { + private String contentType; + private Map headers; + private String style; + private Boolean explode; + private Boolean allowReserved; + + public Encoding(io.swagger.oas.annotations.media.Encoding e) { + setContentType(OpenApi.nullIfEmpty(e.contentType())); + for(io.swagger.oas.annotations.headers.Header h : e.headers()) { + getHeaders().put(e.name(), new Header(h)); + } + setStyle(OpenApi.nullIfEmpty(e.style())); + setExplode(e.explode()); + setAllowReserved(e.allowReserved()); + } + + public String getContentType() { + return contentType; + } + + public void setContentType(String contentType) { + this.contentType = contentType; + } + + public Map getHeaders() { + if(headers == null) { + headers = new HashMap(); + } + return headers; + } + + public void setHeaders(Map headers) { + this.headers = headers; + } + + public String getStyle() { + return style; + } + + public void setStyle(String style) { + this.style = style; + } + + public Boolean getExplode() { + return explode; + } + + public void setExplode(Boolean explode) { + this.explode = explode; + } + + public Boolean getAllowReserved() { + return allowReserved; + } + + public void setAllowReserved(Boolean allowReserved) { + this.allowReserved = allowReserved; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Example.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Example.java new file mode 100644 index 0000000..3fe4eb2 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Example.java @@ -0,0 +1,54 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +/** + * @see https://swagger.io/specification/#exampleObject + */ +public class Example extends Reference{ + private String summary; + private String description; + private String value; + private String externalValue; + + public Example(String ref) { + super(ref); + } + + public Example(io.swagger.oas.annotations.media.ExampleObject e) { + setSummary(OpenApi.nullIfEmpty(e.summary())); + //TODO: description in annotation missing setDescription(OpenApi.nullIfEmpty(e.description())); + setValue(OpenApi.nullIfEmpty(e.value())); + setExternalValue(OpenApi.nullIfEmpty(e.externalValue())); + } + + public String getSummary() { + return summary; + } + + public void setSummary(String summary) { + this.summary = summary; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getExternalValue() { + return externalValue; + } + + public void setExternalValue(String externalValue) { + this.externalValue = externalValue; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/ExternalDocumentation.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/ExternalDocumentation.java new file mode 100644 index 0000000..5761e8b --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/ExternalDocumentation.java @@ -0,0 +1,38 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +/** + * @see https://swagger.io/specification/#externalDocumentationObject + */ +public class ExternalDocumentation { + private String description; + private String url; + + public ExternalDocumentation(String url) { + setUrl(url); + } + + public ExternalDocumentation(io.swagger.oas.annotations.ExternalDocumentation externalDocs) { + setDescription(OpenApi.nullIfEmpty(externalDocs.description())); + setUrl(OpenApi.nullIfEmpty(externalDocs.url())); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public boolean isValid() { + return description != null && url != null; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Header.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Header.java new file mode 100644 index 0000000..2ed0ae8 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Header.java @@ -0,0 +1,89 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +/** + * @see https://swagger.io/specification/#headerObject + */ +public class Header extends Reference{ + private String name; + private String description; + private Boolean required; + private Boolean deprecated; + private Boolean allowEmptyValue; + + private Schema schema; + private String example; + + public Header(String ref) { + super(ref); + } + + public Header(io.swagger.oas.annotations.headers.Header h) { + setName(OpenApi.nullIfEmpty(h.name())); + setDescription(OpenApi.nullIfEmpty(h.description())); + setRequired(h.required()); + setDeprecated(h.deprecated()); + setAllowEmptyValue(h.allowEmptyValue()); + + setSchema(new Schema(h.schema())); + if(!getSchema().isValid()){ + setSchema(null); + } + //TODO annotation.example is missing setExample(OpenApi.nullIfEmpty(p.example())); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Boolean getRequired() { + return required; + } + + public void setRequired(Boolean required) { + this.required = required; + } + + public Boolean getDeprecated() { + return deprecated; + } + + public void setDeprecated(Boolean deprecated) { + this.deprecated = deprecated; + } + + public Boolean getAllowEmptyValue() { + return allowEmptyValue; + } + + public void setAllowEmptyValue(Boolean allowEmptyValue) { + this.allowEmptyValue = allowEmptyValue; + } + + public Schema getSchema() { + return schema; + } + + public void setSchema(Schema schema) { + this.schema = schema; + } + + public String getExample() { + return example; + } + + public void setExample(String example) { + this.example = example; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Info.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Info.java new file mode 100644 index 0000000..1b02e84 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Info.java @@ -0,0 +1,67 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +/** + * @see https://swagger.io/specification/#infoObject + */ +public class Info { + private String title; + private String description; + private String termsOfService; + private Contact contact; + private License license; + private String version; + + public Info(String title, String description, String version) { + setTitle(title); + setDescription(description); + setVersion(version); + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getTermsOfService() { + return termsOfService; + } + + public void setTermsOfService(String termsOfService) { + this.termsOfService = termsOfService; + } + + public Contact getContact() { + return contact; + } + + public void setContact(Contact contact) { + this.contact = contact; + } + + public License getLicense() { + return license; + } + + public void setLicense(License license) { + this.license = license; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/License.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/License.java new file mode 100644 index 0000000..21d31ff --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/License.java @@ -0,0 +1,34 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +/** + * @see https://swagger.io/specification/#licenseObject + */ +public class License { + private String name; + private String url; + + public License(String name) { + setName(name); + } + + public License(String name, String url) { + setName(name); + setUrl(url); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Link.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Link.java new file mode 100644 index 0000000..c074ede --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Link.java @@ -0,0 +1,83 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import java.util.Map; + +/** + * @see https://swagger.io/specification/#linkObject + */ +public class Link extends Reference{ + private String operationRef; + private String operationId; + private Map parameters; + private String requestBody; + private String description; + private Server server; + + public Link(String ref) { + super(ref); + } + + public Link(io.swagger.oas.annotations.links.Link l) { + setOperationRef(OpenApi.nullIfEmpty(l.operationRef())); + setOperationId(OpenApi.nullIfEmpty(l.operationId())); + + for(io.swagger.oas.annotations.links.LinkParameter lp: l.parameters()) { + String name = OpenApi.nullIfEmpty(lp.name()); + if(name != null) { + getParameters().put(name, new LinkParameter(lp)); + } + } + + setRequestBody(OpenApi.nullIfEmpty(l.requestBody())); + setDescription(OpenApi.nullIfEmpty(l.description())); + setServer(new Server(l.server())); + } + + public String getOperationRef() { + return operationRef; + } + + public void setOperationRef(String operationRef) { + this.operationRef = operationRef; + } + + public String getOperationId() { + return operationId; + } + + public void setOperationId(String operationId) { + this.operationId = operationId; + } + + public Map getParameters() { + return parameters; + } + + public void setParameters(Map parameters) { + this.parameters = parameters; + } + + public String getRequestBody() { + return requestBody; + } + + public void setRequestBody(String requestBody) { + this.requestBody = requestBody; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Server getServer() { + return server; + } + + public void setServer(Server server) { + this.server = server; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/LinkParameter.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/LinkParameter.java new file mode 100644 index 0000000..1ea8ab1 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/LinkParameter.java @@ -0,0 +1,27 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +public class LinkParameter { + private String name; + private String expression; + + public LinkParameter(io.swagger.oas.annotations.links.LinkParameter lp) { + setName(OpenApi.nullIfEmpty(lp.name())); + setExpression(OpenApi.nullIfEmpty(lp.expression())); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getExpression() { + return expression; + } + + public void setExpression(String expression) { + this.expression = expression; + } +} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/MediaType.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/MediaType.java new file mode 100644 index 0000000..85e9373 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/MediaType.java @@ -0,0 +1,69 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import java.util.HashMap; +import java.util.Map; + +/** + * @see https://swagger.io/specification/#mediaTypeObject + */ +public class MediaType { + private Schema schema; + private String example; + private Map examples; + private Map encoding; + + public MediaType(io.swagger.oas.annotations.media.Content c) { + setSchema(new Schema(c.schema())); + if(!getSchema().isValid()){ + setSchema(null); + } + + //TODO: setExample(); ?? + + for(io.swagger.oas.annotations.media.ExampleObject e : c.examples()) { + getExamples().put(e.name(), new Example(e)); + } + + for(io.swagger.oas.annotations.media.Encoding e : c.encoding()) { + getEncoding().put(e.name(), new Encoding(e)); + } + } + + public Schema getSchema() { + return schema; + } + + public void setSchema(Schema schema) { + this.schema = schema; + } + + public String getExample() { + return example; + } + + public void setExample(String example) { + this.example = example; + } + + public Map getExamples() { + if(examples == null) { + examples = new HashMap(); + } + return examples; + } + + public void setExamples(Map examples) { + this.examples = examples; + } + + public Map getEncoding() { + if(encoding == null) { + encoding = new HashMap(); + } + return encoding; + } + + public void setEncoding(Map encoding) { + this.encoding = encoding; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/OAuthFlow.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/OAuthFlow.java new file mode 100644 index 0000000..ae15948 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/OAuthFlow.java @@ -0,0 +1,49 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import java.util.HashMap; +import java.util.Map; + +/** + * @see https://swagger.io/specification/#oauthFlowObject + */ +public class OAuthFlow { + private String authorizationUrl; + private String tokenUrl; + private String refreshUrl; + private Map scopes; + + public String getAuthorizationUrl() { + return authorizationUrl; + } + + public void setAuthorizationUrl(String authorizationUrl) { + this.authorizationUrl = authorizationUrl; + } + + public String getTokenUrl() { + return tokenUrl; + } + + public void setTokenUrl(String tokenUrl) { + this.tokenUrl = tokenUrl; + } + + public String getRefreshUrl() { + return refreshUrl; + } + + public void setRefreshUrl(String refreshUrl) { + this.refreshUrl = refreshUrl; + } + + public Map getScopes() { + if(scopes == null) { + scopes = new HashMap(); + } + return scopes; + } + + public void setScopes(Map scopes) { + this.scopes = scopes; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/OAuthFlows.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/OAuthFlows.java new file mode 100644 index 0000000..5c2846e --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/OAuthFlows.java @@ -0,0 +1,43 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +/** + * @see https://swagger.io/specification/#oauthFlowsObject + */ +public class OAuthFlows { + private OAuthFlow implicit; + private OAuthFlow password; + private OAuthFlow clientCredentials; + private OAuthFlow authorizationCode; + + public OAuthFlow getImplicit() { + return implicit; + } + + public void setImplicit(OAuthFlow implicit) { + this.implicit = implicit; + } + + public OAuthFlow getPassword() { + return password; + } + + public void setPassword(OAuthFlow password) { + this.password = password; + } + + public OAuthFlow getClientCredentials() { + return clientCredentials; + } + + public void setClientCredentials(OAuthFlow clientCredentials) { + this.clientCredentials = clientCredentials; + } + + public OAuthFlow getAuthorizationCode() { + return authorizationCode; + } + + public void setAuthorizationCode(OAuthFlow authorizationCode) { + this.authorizationCode = authorizationCode; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/OpenApi.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/OpenApi.java new file mode 100644 index 0000000..95f213d --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/OpenApi.java @@ -0,0 +1,107 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * https://swagger.io/specification/#oasObject + * + */ +public class OpenApi { + private String openapi; + private Info info; + private List servers; + private Map paths; + private Components components; + private SecurityRequirement security; + private List tags; + private ExternalDocumentation externalDocs; + + public OpenApi(Info info) { + setOpenapi("3.0.0"); + setInfo(info); + servers = new ArrayList(); + paths = new TreeMap(); + } + + public String getOpenapi() { + return openapi; + } + + public void setOpenapi(String openapi) { + this.openapi = openapi; + } + + public Info getInfo() { + return info; + } + + public void setInfo(Info info) { + this.info = info; + } + + public List getServers() { + return servers; + } + + public void setServers(List servers) { + this.servers = servers; + } + + public Map getPaths() { + return paths; + } + + public void setPaths(Map paths) { + this.paths = paths; + } + + public void addPath(String path, PathItem value) { + getPaths().put(path, value); + } + + public Components getComponents() { + return components; + } + + public void setComponents(Components components) { + this.components = components; + } + + public SecurityRequirement getSecurity() { + return security; + } + + public void setSecurity(SecurityRequirement security) { + this.security = security; + } + + public List getTags() { + if(tags == null) { + tags = new ArrayList(); + } + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public ExternalDocumentation getExternalDocs() { + return externalDocs; + } + + public void setExternalDocs(ExternalDocumentation externalDocs) { + this.externalDocs = externalDocs; + } + + public static String nullIfEmpty(String str) { + if(str != null && !str.isEmpty()){ + return str; + }else { + return null; + } + } +} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Operation.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Operation.java new file mode 100644 index 0000000..ac14a10 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Operation.java @@ -0,0 +1,184 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @see https://swagger.io/specification/#operationObject + */ +public class Operation { + private List tags; + private String summary; + private String description; + private ExternalDocumentation externalDocs; + private String operationId; + private List parameters; + private RequestBody requestBody; + private Map responses; + private Mapcallbacks; + private Boolean deprecated; + private List> security; + private List servers; + + public Operation() { + + } + + public Operation(io.swagger.oas.annotations.Operation op) { + setTags(Arrays.asList(op.tags())); + setSummary(OpenApi.nullIfEmpty(op.summary())); + setDescription(OpenApi.nullIfEmpty(op.description())); + setExternalDocs(new ExternalDocumentation(op.externalDocs())); + if(!getExternalDocs().isValid()){ + setExternalDocs(null); + } + setOperationId(OpenApi.nullIfEmpty(op.operationId())); + + for(io.swagger.oas.annotations.Parameter p : op.parameters()) { + getParameters().add(new Parameter(p)); + } + + setRequestBody(new RequestBody(op.requestBody())); + if(!getRequestBody().isValid()) { + setRequestBody(null); + } + + for(io.swagger.oas.annotations.responses.ApiResponse r : op.responses()) { + if(OpenApi.nullIfEmpty(r.responseCode()) != null) { + getResponses().put(r.responseCode(), new Response(r)); + } + } + + //TODO: callbacks ???? == Extension[] extensions() + + setDeprecated(op.deprecated()); + + for(io.swagger.oas.annotations.security.SecurityRequirement sr : op.security()) { + if(OpenApi.nullIfEmpty(sr.name()) != null) { + Map sec = new HashMap(); + sec.put(sr.name(), sr.scopes()); + getSecurity().add(sec); + } + } + + for(io.swagger.oas.annotations.servers.Server s : op.servers()) { + getServers().add(new Server(s)); + } + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public String getSummary() { + return summary; + } + + public void setSummary(String summary) { + this.summary = summary; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + + public ExternalDocumentation getExternalDocs() { + return externalDocs; + } + + public void setExternalDocs(ExternalDocumentation externalDocs) { + this.externalDocs = externalDocs; + } + + public String getOperationId() { + return operationId; + } + + public void setOperationId(String operationId) { + this.operationId = operationId; + } + + public List getParameters() { + if(parameters == null) { + parameters = new ArrayList(); + } + return parameters; + } + + public void setParameters(List parameters) { + this.parameters = parameters; + } + + public RequestBody getRequestBody() { + return requestBody; + } + + public void setRequestBody(RequestBody requestBody) { + this.requestBody = requestBody; + } + + public Map getResponses() { + if(responses == null) { + responses = new HashMap(); + } + return responses; + } + + public void setResponses(Map responses) { + this.responses = responses; + } + + public Map getCallbacks() { + if(callbacks == null) { + callbacks = new HashMap(); + } + return callbacks; + } + + public void setCallbacks(Map callbacks) { + this.callbacks = callbacks; + } + + public Boolean getDeprecated() { + return deprecated; + } + + public void setDeprecated(Boolean deprecated) { + this.deprecated = deprecated; + } + + public List> getSecurity() { + if(security == null) { + security = new ArrayList>(); + } + return security; + } + + public void setSecurity(List> security) { + this.security = security; + } + + public List getServers() { + if(servers == null) { + servers = new ArrayList(); + } + return servers; + } + + public void setServers(List servers) { + this.servers = servers; + } + +} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Parameter.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Parameter.java new file mode 100644 index 0000000..78d9f11 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Parameter.java @@ -0,0 +1,158 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import java.util.HashMap; +import java.util.Map; + +import io.swagger.oas.annotations.enums.Explode; + +/** + * @see https://swagger.io/specification/#parameterObject + */ +public class Parameter extends Reference{ + private String name; + private String in; + private String description; + private Boolean required; + private Boolean deprecated; + private Boolean allowEmptyValue; + + private String style; + private Boolean explode; + private Boolean allowReserved; + private Schema schema; + private String example; + private Map examples; + + public Parameter(String ref) { + super(ref); + } + + public Parameter(io.swagger.oas.annotations.Parameter p) { + setName(OpenApi.nullIfEmpty(p.name())); + setIn(OpenApi.nullIfEmpty(p.in())); + setDescription(OpenApi.nullIfEmpty(p.description())); + setRequired(p.required()); + setDeprecated(p.deprecated()); + setAllowEmptyValue(p.allowEmptyValue()); + + setStyle(OpenApi.nullIfEmpty(p.style())); + setExplode(p.explode() == Explode.TRUE); + setAllowReserved(p.allowReserved()); + setSchema(new Schema(p.schema())); + if(!getSchema().isValid()){ + setSchema(null); + } + setExample(OpenApi.nullIfEmpty(p.example())); + for(io.swagger.oas.annotations.media.ExampleObject e : p.examples()) { + if(e.name().length() > 0) { + getExamples().put(e.name(), new Example(e)); + } + } + // TODO: check unmapped annatation vars + /* + * ArraySchema array() default @ArraySchema(); + * Content[] content() default {}; + * boolean hidden() default false; + */ + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getIn() { + return in; + } + + public void setIn(String in) { + this.in = in; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Boolean getRequired() { + return required; + } + + public void setRequired(Boolean required) { + this.required = required; + } + + public Boolean getDeprecated() { + return deprecated; + } + + public void setDeprecated(Boolean deprecated) { + this.deprecated = deprecated; + } + + public Boolean getAllowEmptyValue() { + return allowEmptyValue; + } + + public void setAllowEmptyValue(Boolean allowEmptyValue) { + this.allowEmptyValue = allowEmptyValue; + } + + public String getStyle() { + return style; + } + + public void setStyle(String style) { + this.style = style; + } + + public Boolean getExplode() { + return explode; + } + + public void setExplode(Boolean explode) { + this.explode = explode; + } + + public Boolean getAllowReserved() { + return allowReserved; + } + + public void setAllowReserved(Boolean allowReserved) { + this.allowReserved = allowReserved; + } + + public Schema getSchema() { + return schema; + } + + public void setSchema(Schema schema) { + this.schema = schema; + } + + public String getExample() { + return example; + } + + public void setExample(String example) { + this.example = example; + } + + public Map getExamples() { + if(examples == null) { + examples = new HashMap(); + } + return examples; + } + + public void setExamples(Map examples) { + this.examples = examples; + } + +} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/PathItem.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/PathItem.java new file mode 100644 index 0000000..7290911 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/PathItem.java @@ -0,0 +1,179 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import java.util.List; + +/** + * @see https://swagger.io/specification/#pathObject + * @see https://swagger.io/specification/#pathItemObject + */ +public class PathItem extends Reference{ + private String summary; + private String description; + + private Operation get; + private Operation put; + private Operation post; + private Operation delete; + private Operation options; + private Operation head; + private Operation patch; + private Operation trace; + + private List servers; + private List parameters; + + public PathItem() { + super(); + } + + public PathItem(String ref) { + super(ref); + } + + public String getSummary() { + return summary; + } + + public void setSummary(String summary) { + this.summary = summary; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Operation getGet() { + return get; + } + + public void setGet(Operation get) { + this.get = get; + } + + public Operation getPut() { + return put; + } + + public void setPut(Operation put) { + this.put = put; + } + + public Operation getPost() { + return post; + } + + public void setPost(Operation post) { + this.post = post; + } + + public Operation getDelete() { + return delete; + } + + public void setDelete(Operation delete) { + this.delete = delete; + } + + public Operation getOptions() { + return options; + } + + public void setOptions(Operation options) { + this.options = options; + } + + public Operation getHead() { + return head; + } + + public void setHead(Operation head) { + this.head = head; + } + + public Operation getPatch() { + return patch; + } + + public void setPatch(Operation patch) { + this.patch = patch; + } + + public Operation getTrace() { + return trace; + } + + public void setTrace(Operation trace) { + this.trace = trace; + } + + public List getServers() { + return servers; + } + + public void setServers(List servers) { + this.servers = servers; + } + + public List getParameters() { + return parameters; + } + + public void setParameters(List parameters) { + this.parameters = parameters; + } + + public void add(String method, Operation operation) { + switch(method.toUpperCase()) { + case "OPTIONS": + setOptions(operation); + break; + case "GET": + setGet(operation); + break; + case "HEAD": + setHead(operation); + break; + case "POST": + setPost(operation); + break; + case "PUT": + setPut(operation); + break; + case "PATCH": + setPatch(operation); + break; + case "DELETE": + setDelete(operation); + break; + case "TRACE": + setTrace(operation); + break; + } + } + + public Operation get(String method) { + switch(method.toUpperCase()) { + case "OPTIONS": + return getOptions(); + case "GET": + return getGet(); + case "HEAD": + return getHead(); + case "POST": + return getPost(); + case "PUT": + return getPut(); + case "PATCH": + return getPatch(); + case "DELETE": + return getDelete(); + case "TRACE": + return getTrace(); + } + return null; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Reference.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Reference.java new file mode 100644 index 0000000..dce36e7 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Reference.java @@ -0,0 +1,25 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @see https://swagger.io/specification/#referenceObject + */ +public class Reference { + @JsonProperty("$ref") + private String ref; + + public Reference() {} + + public Reference(String ref) { + setRef(ref); + } + + public String getRef() { + return ref; + } + + public void setRef(String ref) { + this.ref = ref; + } +} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/RequestBody.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/RequestBody.java new file mode 100644 index 0000000..e072828 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/RequestBody.java @@ -0,0 +1,58 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import java.util.HashMap; +import java.util.Map; + +/** + * @see https://swagger.io/specification/#requestBodyObject + */ +public class RequestBody extends Reference{ + private String description; + private Map content; + private Boolean required; + + public RequestBody(String ref) { + super(ref); + } + + public RequestBody(io.swagger.oas.annotations.parameters.RequestBody rb) { + setDescription(OpenApi.nullIfEmpty(rb.description())); + for(io.swagger.oas.annotations.media.Content c : rb.content()) { + if(OpenApi.nullIfEmpty(c.mediaType()) != null) { + getContent().put(c.mediaType(), new MediaType(c)); + } + } + setRequired(rb.required()); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Map getContent() { + if(content == null) { + content = new HashMap(); + } + return content; + } + + public void setContent(Map content) { + this.content = content; + } + + public Boolean getRequired() { + return required; + } + + public void setRequired(Boolean required) { + this.required = (required) ? true : null; + } + + public boolean isValid() { + return description != null && required != null && content != null && !content.isEmpty(); + } +} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Response.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Response.java new file mode 100644 index 0000000..7336b13 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Response.java @@ -0,0 +1,84 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import java.util.HashMap; +import java.util.Map; + +import io.swagger.oas.annotations.responses.ApiResponse; + +/** + * @see https://swagger.io/specification/#responsesObject + * @see https://swagger.io/specification/#responseObject + * + */ +public class Response { + private String description; + private Map headers; + private Map content; + private Map links; + + public Response(ApiResponse r) { + setDescription(OpenApi.nullIfEmpty(r.description())); + + for(io.swagger.oas.annotations.headers.Header h : r.headers()) { + String name = OpenApi.nullIfEmpty(h.name()); + if(name != null) { + getHeaders().put(name, new Header(h)); + } + } + + for(io.swagger.oas.annotations.media.Content c : r.content()) { + String name = OpenApi.nullIfEmpty(c.mediaType()); + if(name != null) { + getContent().put(c.mediaType(), new MediaType(c)); + } + } + + for(io.swagger.oas.annotations.links.Link l : r.links()) { + String name = OpenApi.nullIfEmpty(l.name()); + if(name != null) { + getLinks().put(name, new Link(l)); + } + } + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Map getHeaders() { + if(headers == null) { + headers = new HashMap(); + } + return headers; + } + + public void setHeaders(Map headers) { + this.headers = headers; + } + + public Map getContent() { + if(content == null) { + content = new HashMap(); + } + return content; + } + + public void setContent(Map content) { + this.content = content; + } + + public Map getLinks() { + if(links == null) { + links = new HashMap(); + } + return links; + } + + public void setLinks(Map links) { + this.links = links; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Schema.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Schema.java new file mode 100644 index 0000000..1fbdb96 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Schema.java @@ -0,0 +1,290 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * https://swagger.io/specification/#schemaObject + */ +public class Schema extends Reference{ + private String title; + private Double multipleOf; + private String maximum; + private Boolean exclusiveMaximum; + private String minimum; + private Boolean exclusiveMinimum; + private Integer maxLength; + private Integer minLength; + private String pattern; +// maxItems +// minItems +// uniqueItems + private Integer maxProperties; + private Integer minProperties; + private Boolean required; + @JsonProperty("enum") + private String[] enumVal; + + private String type; + private Class[] allOf; + private Class[] oneOf; + private Class[] anyOf; + private Class not; +// items +// properties +// additionalProperties + private String description; + private String format; + @JsonProperty("default") + private String defaultValue; + + private Class implementation; + private String example; + + public Schema(String ref) { + super(ref); + } + + public Schema(io.swagger.oas.annotations.media.Schema schema) { + setRef(OpenApi.nullIfEmpty(schema.ref())); + setTitle(OpenApi.nullIfEmpty(schema.title())); + setMultipleOf(schema.multipleOf()); + setMaximum(OpenApi.nullIfEmpty(schema.maximum())); + setExclusiveMaximum(schema.exclusiveMaximum()); + setMinimum(schema.minimum()); + setExclusiveMinimum(schema.exclusiveMinimum()); + setMaxLength(schema.maxLength()); + setMinLength(schema.minLength()); + setPattern(OpenApi.nullIfEmpty(schema.pattern())); + //TODO: maxItems + //TODO: minItems + //TODO: uniqueItems + setMaxProperties(schema.maxProperties()); + setMinProperties(schema.minProperties()); + setRequired(schema.required()); + if(schema.allowableValues().length > 0) { + setEnumVal(schema.allowableValues()); + } + + setType(OpenApi.nullIfEmpty(schema.type())); + if(schema.allOf().length > 0) { + setAllOf(schema.allOf()); + } + if(schema.oneOf().length > 0) { + setOneOf(schema.oneOf()); + } + if(schema.anyOf().length > 0) { + setAnyOf(schema.anyOf()); + } + setNot(schema.not()); + //TODO: items + //TODO: properties + //TODO: additionalProperties + setDescription(OpenApi.nullIfEmpty(schema.description())); + setFormat(OpenApi.nullIfEmpty(schema.format())); + setDefaultValue(schema.defaultValue()); + + + setImplementation(schema.implementation()); + setExample(OpenApi.nullIfEmpty(schema.example())); + + //TODO: check unmapped vars +// String name() default ""; +// String[] requiredProperties() default {}; +// boolean nullable() default false; +// boolean readOnly() default false; +// boolean writeOnly() default false; +// ExternalDocumentation externalDocs() default @ExternalDocumentation(); +// boolean deprecated() default false; +// String discriminatorProperty() default ""; +// DiscriminatorMapping[] discriminatorMapping() default {}; +// boolean hidden() default false; + } + + public Class getImplementation() { + return implementation; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Double getMultipleOf() { + return multipleOf; + } + + public void setMultipleOf(Double multipleOf) { + this.multipleOf = multipleOf; + } + + public String getMaximum() { + return maximum; + } + + public void setMaximum(String maximum) { + this.maximum = maximum; + } + + public Boolean getExclusiveMaximum() { + return exclusiveMaximum; + } + + public void setExclusiveMaximum(Boolean exclusiveMaximum) { + this.exclusiveMaximum = exclusiveMaximum; + } + + public String getMinimum() { + return minimum; + } + + public void setMinimum(String minimum) { + this.minimum = minimum; + } + + public Boolean getExclusiveMinimum() { + return exclusiveMinimum; + } + + public void setExclusiveMinimum(Boolean exclusiveMinimum) { + this.exclusiveMinimum = exclusiveMinimum; + } + + public Integer getMaxLength() { + return maxLength; + } + + public void setMaxLength(Integer maxLength) { + this.maxLength = maxLength; + } + + public Integer getMinLength() { + return minLength; + } + + public void setMinLength(Integer minLength) { + this.minLength = minLength; + } + + public String getPattern() { + return pattern; + } + + public void setPattern(String pattern) { + this.pattern = pattern; + } + + public Integer getMaxProperties() { + return maxProperties; + } + + public void setMaxProperties(Integer maxProperties) { + this.maxProperties = maxProperties; + } + + public Integer getMinProperties() { + return minProperties; + } + + public void setMinProperties(Integer minProperties) { + this.minProperties = minProperties; + } + + public Boolean getRequired() { + return required; + } + + public void setRequired(Boolean required) { + this.required = required; + } + + public String[] getEnumVal() { + return enumVal; + } + + public void setEnumVal(String[] enumVal) { + this.enumVal = enumVal; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Class[] getAllOf() { + return allOf; + } + + public void setAllOf(Class[] allOf) { + this.allOf = allOf; + } + + public Class[] getOneOf() { + return oneOf; + } + + public void setOneOf(Class[] oneOf) { + this.oneOf = oneOf; + } + + public Class[] getAnyOf() { + return anyOf; + } + + public void setAnyOf(Class[] anyOf) { + this.anyOf = anyOf; + } + + public Class getNot() { + return not; + } + + public void setNot(Class not) { + this.not = not; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getFormat() { + return format; + } + + public void setFormat(String format) { + this.format = format; + } + + public String getDefaultValue() { + return defaultValue; + } + + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + public void setImplementation(Class implementation) { + this.implementation = implementation; + } + + public String getExample() { + return example; + } + + public void setExample(String example) { + this.example = example; + } + + public boolean isValid() { + return getRef() != null || implementation != null; + } +} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/SecurityRequirement.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/SecurityRequirement.java new file mode 100644 index 0000000..78277bb --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/SecurityRequirement.java @@ -0,0 +1,15 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +/** + * @see https://swagger.io/specification/#securityRequirementObject + */ +public class SecurityRequirement extends Reference{ + + public SecurityRequirement() { + super(); + } + + public SecurityRequirement(String ref) { + super(ref); + } +} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/SecurityScheme.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/SecurityScheme.java new file mode 100644 index 0000000..7a8cc07 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/SecurityScheme.java @@ -0,0 +1,79 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +/** + * @see https://swagger.io/specification/#securitySchemeObject + */ +public class SecurityScheme { + private String type; + private String description; + private String name; + private String in; + private String scheme; + private String bearerFormat; + private OAuthFlows flows; + private String openIdConnectUrl; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getIn() { + return in; + } + + public void setIn(String in) { + this.in = in; + } + + public String getScheme() { + return scheme; + } + + public void setScheme(String scheme) { + this.scheme = scheme; + } + + public String getBearerFormat() { + return bearerFormat; + } + + public void setBearerFormat(String bearerFormat) { + this.bearerFormat = bearerFormat; + } + + public OAuthFlows getFlows() { + return flows; + } + + public void setFlows(OAuthFlows flows) { + this.flows = flows; + } + + public String getOpenIdConnectUrl() { + return openIdConnectUrl; + } + + public void setOpenIdConnectUrl(String openIdConnectUrl) { + this.openIdConnectUrl = openIdConnectUrl; + } +} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Server.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Server.java new file mode 100644 index 0000000..b9cff66 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Server.java @@ -0,0 +1,69 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import java.util.HashMap; +import java.util.Map; + +/** + * @see https://swagger.io/specification/#serverObject + */ +public class Server { + private String url; + private String description; + private Map variables; + + public Server(String url, String description) { + setUrl(url); + setDescription(description); + } + + public Server(io.swagger.oas.annotations.servers.Server s) { + setUrl(OpenApi.nullIfEmpty(s.url())); + setDescription(OpenApi.nullIfEmpty(s.description())); + + for(io.swagger.oas.annotations.servers.ServerVariable sv : s.variables()) { + String name = OpenApi.nullIfEmpty(sv.name()); + if(name != null) { + getVariables().put(name, new ServerVariable(sv)); + } + } + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Map getVariables() { + if(variables == null) { + variables = new HashMap(); + } + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + + public void addVariable(String key, ServerVariable value) { + if(variables == null) { + variables = new HashMap(); + } + variables.put(key, value); + } + + public boolean isValid() { + return url != null && description != null && (variables != null && !variables.isEmpty()); + } + +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/ServerVariable.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/ServerVariable.java new file mode 100644 index 0000000..c88ac78 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/ServerVariable.java @@ -0,0 +1,64 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @see https://swagger.io/specification/#serverVariableObject + */ +public class ServerVariable { + @JsonProperty("enum") + private List enumVar; + @JsonProperty("default") + private String defaultValue; + private String description; + + public ServerVariable(String defaultValue) { + setDefault(defaultValue); + } + + public ServerVariable(io.swagger.oas.annotations.servers.ServerVariable sv) { + if(sv.allowableValues() != null && sv.allowableValues().length > 0) { + setEnumVar(Arrays.asList(sv.allowableValues())); + } + setDefault(sv.defaultValue()); + setDescription(OpenApi.nullIfEmpty(sv.description())); + } + + public List getEnumVar() { + if(enumVar == null) { + enumVar = new ArrayList(); + } + return enumVar; + } + + public void setEnumVar(List enumVar) { + this.enumVar = enumVar; + } + + public void addEnum(String string) { + if(enumVar == null) { + enumVar = new ArrayList(); + } + enumVar.add(string); + } + + public String getDefault() { + return defaultValue; + } + + public void setDefault(String defaultValue) { + this.defaultValue = defaultValue; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Tag.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Tag.java new file mode 100644 index 0000000..01530f7 --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/Tag.java @@ -0,0 +1,34 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +/** + * @see https://swagger.io/specification/#tagObject + */ +public class Tag { + private String name; + private String description; + private ExternalDocumentation externalDocs; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public ExternalDocumentation getExternalDocs() { + return externalDocs; + } + + public void setExternalDocs(ExternalDocumentation externalDocs) { + this.externalDocs = externalDocs; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/XmlObject.java b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/XmlObject.java new file mode 100644 index 0000000..690069b --- /dev/null +++ b/swagger/src/main/java/com/strategicgains/restexpress/plugin/swagger/wrapper/XmlObject.java @@ -0,0 +1,52 @@ +package com.strategicgains.restexpress.plugin.swagger.wrapper; + +/** + * @see https://swagger.io/specification/#xmlObject + */ +public class XmlObject { + private String name; + private String namespace; + private String prefix; + private Boolean attribute; + private Boolean wrapped; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNamespace() { + return namespace; + } + + public void setNamespace(String namespace) { + this.namespace = namespace; + } + + public String getPrefix() { + return prefix; + } + + public void setPrefix(String prefix) { + this.prefix = prefix; + } + + public Boolean getAttribute() { + return attribute; + } + + public void setAttribute(Boolean attribute) { + this.attribute = attribute; + } + + public Boolean getWrapped() { + return wrapped; + } + + public void setWrapped(Boolean wrapped) { + this.wrapped = wrapped; + } +} \ No newline at end of file diff --git a/swagger/src/main/java/io/swagger/oas/annotations/Hidden.java b/swagger/src/main/java/io/swagger/oas/annotations/Hidden.java new file mode 100644 index 0000000..f02a0a0 --- /dev/null +++ b/swagger/src/main/java/io/swagger/oas/annotations/Hidden.java @@ -0,0 +1,13 @@ +package io.swagger.oas.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@Target(value={ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(value=RetentionPolicy.RUNTIME) +public @interface Hidden { + +} diff --git a/swagger/src/main/java/io/swagger/oas/annotations/Operation.java b/swagger/src/main/java/io/swagger/oas/annotations/Operation.java new file mode 100644 index 0000000..6454282 --- /dev/null +++ b/swagger/src/main/java/io/swagger/oas/annotations/Operation.java @@ -0,0 +1,118 @@ +/** + * Copyright 2017 SmartBear Software + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * + * https://raw.githubusercontent.com/swagger-api/swagger-core/bugfix/requestBody-Annotation/modules/swagger-annotations/src/main/java/io/swagger/oas/annotations/Operation.java + */ + +package io.swagger.oas.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import io.swagger.oas.annotations.extensions.Extension; +import io.swagger.oas.annotations.parameters.RequestBody; +import io.swagger.oas.annotations.responses.ApiResponse; +import io.swagger.oas.annotations.security.SecurityRequirement; +import io.swagger.oas.annotations.servers.Server; + +/** + * Describes a single API operation on a path. + **/ +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Inherited +public @interface Operation { + /** + * The HTTP method for this operation. + * @return the HTTP method of this operation + **/ + String method() default ""; + + /** + * Tags can be used for logical grouping of operations by resources or any other qualifier. + * @return the list of tags associated with this operation + **/ + String[] tags() default {}; + + /** + * Provides a brief description of this operation. Should be 120 characters or less for proper visibility in Swagger-UI. + * @return a summary of this operation + **/ + String summary() default ""; + + /** + * A verbose description of the operation. + * @return a description of this operation + **/ + String description() default ""; + + /** + * Additional external documentation for this operation. + * @return additional documentation about this operation + **/ + ExternalDocumentation externalDocs() default @ExternalDocumentation(); + + /** + * The operationId is used by third-party tools to uniquely identify this operation. + * @return the ID of this operation + **/ + String operationId() default ""; + + /** + * An optional array of parameters which will be added to any automatically detected parameters in the method itself. + * @return the list of parameters for this operation + **/ + Parameter[] parameters() default {}; + + /** + * The request body applicable for this operation. + * @return the requesty body of this operation + **/ + RequestBody requestBody() default @RequestBody(); + + /** + * A declaration of which security mechanisms can be used for this operation. + * @return the array of security requirements for this Operation + */ + SecurityRequirement[] security() default {}; + + /** + * The list of possible responses as they are returned from executing this operation. + * @return the list of responses for this operation + **/ + ApiResponse[] responses() default {}; + + /** + * Allows an operation to be marked as deprecated. Alternatively use the @Deprecated annotation + * @return whether or not this operation is deprecated + **/ + boolean deprecated() default false; + + /** + * An alternative server array to service this operation. + * @return the list of servers hosting this operation + **/ + Server[] servers() default {}; + + /** + * The list of optional extensions + * @return an optional array of extensions + */ + Extension[] extensions() default {}; +} \ No newline at end of file diff --git a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/Another.java b/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/Another.java deleted file mode 100644 index 439c6fc..0000000 --- a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/Another.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ -package com.strategicgains.restexpress.plugin.swagger; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - -/** - * @author toddf - * @since Apr 1, 2014 - */ -public class Another -{ - private String aString; - private int anInt; - private Integer[] intArray; - private Map mapStringString; - private Map mapObjectObject; - private List listDummyModel; - Collection anothers; -} diff --git a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/AnotherReturnType.java b/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/AnotherReturnType.java deleted file mode 100644 index bd82e0f..0000000 --- a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/AnotherReturnType.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ -package com.strategicgains.restexpress.plugin.swagger; - -/** - * - * @author uritzry - * @since Aug 20, 2014 - */ -public class AnotherReturnType { - - private String someValue; - -} diff --git a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/DummyBase.java b/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/DummyBase.java deleted file mode 100644 index fe7a523..0000000 --- a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/DummyBase.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.strategicgains.restexpress.plugin.swagger; - -public abstract class DummyBase { - private String base1; - private int base2; -} diff --git a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/DummyController.java b/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/DummyController.java deleted file mode 100644 index c03ea39..0000000 --- a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/DummyController.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - Copyright 2013, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ -package com.strategicgains.restexpress.plugin.swagger; - -import java.util.List; - -import org.restexpress.Request; -import org.restexpress.Response; - -import com.strategicgains.restexpress.plugin.swagger.annotations.ApiModelRequest; -import com.wordnik.swagger.annotations.ApiImplicitParam; -import com.wordnik.swagger.annotations.ApiImplicitParams; -import com.wordnik.swagger.annotations.ApiOperation; -import com.wordnik.swagger.annotations.ApiParam; -import com.wordnik.swagger.annotations.ApiResponse; -import com.wordnik.swagger.annotations.ApiResponses; - -/** - * @author toddf - * @since Nov 22, 2013 - */ -public class DummyController -{ - public DummyModel read(Request request, Response response) - { - return null; - } - - public List readAll(Request request, Response response) - { - return null; - } - - @ApiModelRequest(model=DummyModel.class, required=true) - public void create(Request request, Response response) - { - response.setResponseCreated(); - } - - public void update(Request request, Response response) - { - } - - public void delete(Request request, Response response) - { - response.setResponseNoContent(); - } - - public void health(Request request, Response response) - { - } - - public void options(Request request, Response response) - { - } - - public Another readAnother(Request request, Response response) - { - return null; - } - - @ApiOperation(value = "hidden.", hidden = true, - notes = "More detailed description here. hidden", - response = Another.class) - public AnotherReturnType thisIsAHiddenAPI(Request request, Response response) - { - return null; - } - - @ApiOperation(value = "Read with Annotations.", - notes = "More detailed description here.", - response = Another.class) - public AnotherReturnType readWithApiOperationAnnotation(Request request, Response response) - { - return null; - } - - @ApiResponses({ - @ApiResponse(code = 204, message = "Successful update"), - @ApiResponse(code = 404, message = "Item not found"), - @ApiResponse(code = 400, message = "Item id incorrect format")}) - public void updateWithApiResponse(Request request, Response response) - { - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "expand", required = false, value = "(Optional) Return item and all its children.", paramType = "query", dataType = "String", allowableValues = "all, some, none"), - @ApiImplicitParam(name = "title", required = true, value = "(Required) Title of the item.", paramType = "body", dataType = "String", allowableValues = "Any string"), - }) - public void createWithApiImplicitParams(Request request, Response response) - { - } - - @ApiParam(name = "title", required = true, value = "(Required) Title of the item.", defaultValue = "Title placeholder", allowableValues = "Any String") - public void createWithApiParam(Request request, Response response) - { - } - - @ApiModelRequest(model=DummyModel.class, modelName="AlternativeDummyModel") - public void createWithApiModelRequest(Request request, Response response) - { - } - -} diff --git a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/DummyModel.java b/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/DummyModel.java deleted file mode 100644 index f5f0966..0000000 --- a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/DummyModel.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.strategicgains.restexpress.plugin.swagger; - -import com.wordnik.swagger.annotations.ApiModel; -import com.strategicgains.restexpress.plugin.swagger.annotations.ApiModelProperty; - -import java.math.BigDecimal; -import java.util.List; - -@com.wordnik.swagger.annotations.ApiModel -public class DummyModel extends DummyBase { - @ApiModel - public static class One extends Base { - private String prop1; - private String prop2; - } - - public static class Base { - @ApiModelProperty(position = -1) - private String base1; - @ApiModelProperty(position = -2) - private String base2; - } - - public enum ColorEnum { - RED, - GREEN, - BLUE - } - - @ApiModelProperty - private List ones; - @ApiModelProperty - private String dummy1; - @ApiModelProperty - private int dummy2; - private transient String transient1; - private static int static1; - @ApiModelProperty - private float dummy3; - @ApiModelProperty - private boolean dummy4; - @ApiModelProperty - private One[] dummy5; - @ApiModelProperty - private int[] dummy6; - @ApiModelProperty - private Integer dummy7; - @ApiModelProperty - private Double dummy8; - @ApiModelProperty - private ColorEnum color; - @ApiModelProperty(dataType = "number") - private BigDecimal dummy9; - @ApiModelProperty(dataType = "number", format = "double", excludeFromModels = {"AlternativeDummyModel"}) - private BigDecimal dummy10; -} diff --git a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/ModelResolverTest.java b/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/ModelResolverTest.java deleted file mode 100644 index 0b8871c..0000000 --- a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/ModelResolverTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package com.strategicgains.restexpress.plugin.swagger; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import org.junit.Test; - -import com.strategicgains.restexpress.plugin.swagger.domain.DataType; - -/** - * @author russtrotter - */ -public class ModelResolverTest -{ - private ModelResolver builder = new ModelResolver(); - - @Test - public void shouldResolveDummyModel() - { - DataType n = builder.resolve(DummyModel.class); - assertNotNull(n); - assertEquals(DummyModel.class.getSimpleName(), n.getRef()); - } - - @Test - public void shouldResolveDummyModelArray() - { - DataType n = builder.resolve(DummyModel[].class); - assertNotNull(n); - assertEquals("array", n.getType()); - assertEquals(DummyModel.class.getSimpleName(), n.getItems().getRef()); - } - -// @Test -// public void shouldResolveDummyModelArrayList() -// { -// List list = new ArrayList(); -// DataType n = builder.resolve(list.getClass()); -// assertNotNull(n); -// assertEquals("array", n.getType()); -// assertEquals(DummyModel.class.getSimpleName(), n.getItems().getRef()); -// } - - @Test - public void shouldResolveAnother() - { - DataType n = builder.resolve(Another.class); - assertNotNull(n); - assertEquals(Another.class.getSimpleName(), n.getRef()); - } - - @Test - public void shouldResolveAnotherArray() - { - DataType n = builder.resolve(Another[].class); - assertNotNull(n); - assertEquals("array", n.getType()); - assertEquals(Another.class.getSimpleName(), n.getItems().getRef()); - } - -// @Test -// public void shouldResolveAnotherArrayList() -// { -// DataType n = builder.resolve(new ArrayList().getClass()); -// assertNotNull(n); -// assertEquals("array", n.getType()); -// assertEquals(Another.class.getSimpleName(), n.getItems().getRef()); -// } - - @Test - public void shouldResolveAnotherMap() - { - DataType n = builder.resolve(new HashMap().getClass()); - assertNotNull(n); - assertEquals("object", n.getType()); - } -} diff --git a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/SwaggerAssert.java b/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/SwaggerAssert.java deleted file mode 100644 index 548ec0c..0000000 --- a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/SwaggerAssert.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright 2014, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ -package com.strategicgains.restexpress.plugin.swagger; - -import static org.hamcrest.Matchers.equalTo; - -import com.jayway.restassured.http.ContentType; -import com.jayway.restassured.response.Response; - -/** - * @author toddf - * @since Apr 4, 2014 - */ -public class SwaggerAssert -{ - public static void common(Response response) - { - response - .then() - .contentType(ContentType.JSON) - .body("apiVersion", equalTo("1.0")) - .body("swaggerVersion", equalTo("1.2")); - } -} diff --git a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/SwaggerPluginTest.java b/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/SwaggerPluginTest.java deleted file mode 100644 index 7dcd4c0..0000000 --- a/swagger/src/test/java/com/strategicgains/restexpress/plugin/swagger/SwaggerPluginTest.java +++ /dev/null @@ -1,430 +0,0 @@ -/* - Copyright 2013, Strategic Gains, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ -package com.strategicgains.restexpress.plugin.swagger; - -import static com.jayway.restassured.RestAssured.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.List; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.util.EntityUtils; -import io.netty.handler.codec.http.HttpMethod; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.restexpress.RestExpress; - -import com.jayway.restassured.RestAssured; -import com.jayway.restassured.response.Response; - -/** - * @author toddf - * @since Nov 22, 2013 - */ -public class SwaggerPluginTest -{ - private static final RestExpress SERVER = new RestExpress(); - private static final int PORT = 9001; - private static final String BASE_URL = "http://localhost:" + PORT; - private HttpClient http = new DefaultHttpClient(); - - @BeforeClass - public static void intialize() - { - RestAssured.port = PORT; - - DummyController controller = new DummyController(); - SERVER.setBaseUrl(BASE_URL); - - SERVER.uri("/", controller) - .action("health", HttpMethod.GET) - .name("root"); - - SERVER.uri("/anothers/{userId}", controller) - .action("readAnother", HttpMethod.GET); - - SERVER.uri("/users.{format}", controller) - .action("readAll", HttpMethod.GET) - .action("options", HttpMethod.OPTIONS) - .method(HttpMethod.POST) - .name("Users Collection"); - - SERVER.uri("/users/{userId}.{format}", controller) - .method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE) - .action("options", HttpMethod.OPTIONS) - .name("Individual User"); - - SERVER.uri("/users/{userId}/orders.{format}", controller) - .action("readAll", HttpMethod.GET) - .method(HttpMethod.POST) - .name("User Orders Collection"); - - SERVER.uri("/orders.{format}", controller) - .action("readAll", HttpMethod.GET) - .method(HttpMethod.POST) - .name("Orders Collection"); - - SERVER.uri("/orders/{orderId}.{format}", controller) - .method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE) - .name("Individual Order"); - - SERVER.uri("/orders/{orderId}/items.{format}", controller) - .action("readAll", HttpMethod.GET) - .method(HttpMethod.POST) - .name("Order Line-Items Collection"); - - SERVER.uri("/orders/{orderId}/items/{itemId}.{format}", controller) - .method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE) - .name("Individual Order Line-Item"); - - SERVER.uri("/products.{format}", controller) - .action("readAll", HttpMethod.GET) - .method(HttpMethod.POST) - .name("Orders Collection"); - - SERVER.uri("/products/{orderId}.{format}", controller) - .method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE) - .name("Individual Order"); - - SERVER.uri("/health", controller) - .flag("somevalue") - .action("health", HttpMethod.GET) - .name("health"); - - SERVER.uri("/nicknametest", controller) - .method(HttpMethod.GET) - .name(" |nickName sh0uld_str1p-CHARS$. "); - - SERVER.uri("/annotations/{userId}/users", controller) - .action("readWithApiOperationAnnotation", HttpMethod.GET) - .method(HttpMethod.GET) - .name("Read with Annotations"); - - SERVER.uri("/annotations/hidden", controller) - .action("thisIsAHiddenAPI", HttpMethod.GET) - .method(HttpMethod.GET) - .name("thisIsAHiddenAPI"); - - SERVER.uri("/annotations/{userId}", controller) - .action("updateWithApiResponse", HttpMethod.PUT) - .method(HttpMethod.PUT) - .name("Update with Annotations"); - - SERVER.uri("/annotations/{userId}/users/list", controller) - .action("createWithApiImplicitParams", HttpMethod.POST) - .method(HttpMethod.POST) - .name("Create with Implicit Params"); - - SERVER.uri("/annotations/{userId}/users/newlist", controller) - .action("createWithApiParam", HttpMethod.POST) - .method(HttpMethod.POST) - .name("Create with Api Param"); - - SERVER.uri("/annotations/{userId}/users/list2", controller) - .action("createWithApiModelRequest", HttpMethod.POST) - .method(HttpMethod.POST) - .name("Create with Implicit Params"); - - new SwaggerPlugin() - .apiVersion("1.0") - .swaggerVersion("1.2") - .flag("flag1") - .flag("flag2") - .parameter("parm1", "value1") - .parameter("parm2", "value2") - .register(SERVER); - - SERVER.bind(PORT); - } - - @AfterClass - public static void shutdown() - { - SERVER.shutdown(); - } - - @Test - public void shouldReturnApiResources() - throws Exception - { - Response r = get("/api-docs"); - SwaggerAssert.common(r); - r.then() - .body("apis", not(hasItem(hasEntry("path", "/")))) - .body("apis", hasItem(hasEntry("path", "/anothers"))) - .body("apis", hasItem(hasEntry("path", "/users"))) - .body("apis", hasItem(hasEntry("path", "/orders"))) - .body("apis", hasItem(hasEntry("path", "/products"))) - .body("apis", hasItem(hasEntry("path", "/health"))) - .body("apis", hasItem(hasEntry("path", "/annotations"))) - .body("apis", not(hasItem(hasEntry("path", "/api-docs")))); - } - - @Test - public void shouldReturnUsersApi() - { - Response r = get("/api-docs/users"); - SwaggerAssert.common(r); - r.then() - .body("basePath", equalTo(BASE_URL)) - .body("resourcePath", is("/users")); - - r.then() - .root("apis[%s].%s") - .body(withArgs(0, "path"), is("/users")) - .body(withArgs(0, "description"), is("Users Collection")) - .body(withArgs(0, "operations"), hasItem(hasEntry("method", "GET"))) - .body(withArgs(0, "operations"), hasItem(hasEntry("method", "POST"))) - .body(withArgs(0, "operations"), not(hasItem(hasEntry("method", "PUT")))) - .body(withArgs(0, "operations"), not(hasItem(hasEntry("method", "DELETE")))) - -// .body(withArgs(1, "path"), is("/users/{userId}.{format}")) - .body(withArgs(1, "path"), is("/users/{userId}")) - .body(withArgs(1, "description"), is("Individual User")) - .body(withArgs(1, "operations"), hasItem(hasEntry("method", "GET"))) - .body(withArgs(1, "operations"), hasItem(hasEntry("method", "PUT"))) - .body(withArgs(1, "operations"), hasItem(hasEntry("method", "DELETE"))) - .body(withArgs(1, "operations"), not(hasItem(hasEntry("method", "POST")))) - -// .body(withArgs(2, "path"), is("/users/{userId}/orders.{format}")) - .body(withArgs(2, "path"), is("/users/{userId}/orders")) - .body(withArgs(2, "description"), is("User Orders Collection")) - .body(withArgs(2, "operations"), hasItem(hasEntry("method", "GET"))) - .body(withArgs(2, "operations"), hasItem(hasEntry("method", "POST"))) - .body(withArgs(2, "operations"), not(hasItem(hasEntry("method", "PUT")))) - .body(withArgs(2, "operations"), not(hasItem(hasEntry("method", "DELETE")))); - } - - @Test - public void testApiUsersRoute() - throws ClientProtocolException, IOException - { - HttpGet request = new HttpGet("http://localhost:9001/api-docs/users"); - HttpResponse response = (HttpResponse) http.execute(request); - HttpEntity entity = response.getEntity(); - String json = EntityUtils.toString(entity); - assertTrue(json.contains("\"apiVersion\":\"1.0\"")); - assertTrue(json.contains("\"swaggerVersion\":\"1.2\"")); - assertTrue(json.contains("\"basePath\":\"http://localhost:9001\"")); - assertTrue(json.contains("\"resourcePath\":\"/users\"")); - assertTrue(json.contains("\"nickname\":\"GETUsersCollection\"")); - assertTrue(json.contains("\"nickname\":\"POSTUsersCollection\"")); - assertFalse(json.contains("\"nickname\":\"OPTIONSUsersCollection\"")); - assertTrue(json.contains("\"nickname\":\"GETIndividualUser\"")); - assertTrue(json.contains("\"nickname\":\"PUTIndividualUser\"")); - assertTrue(json.contains("\"nickname\":\"DELETEIndividualUser\"")); - assertFalse(json.contains("\"nickname\":\"OPTIONSIndividualUser\"")); - assertTrue(json.contains("\"summary\":\"\"")); - request.releaseConnection(); - } - - @Test - public void testApiOrdersRoute() - throws ClientProtocolException, IOException - { - HttpGet request = new HttpGet("http://localhost:9001/api-docs/orders"); - HttpResponse response = (HttpResponse) http.execute(request); - HttpEntity entity = response.getEntity(); - String json = EntityUtils.toString(entity); - assertTrue(json.contains("\"apiVersion\":\"1.0\"")); - assertTrue(json.contains("\"swaggerVersion\":\"1.2\"")); - assertTrue(json.contains("\"basePath\":\"http://localhost:9001\"")); - assertTrue(json.contains("\"resourcePath\":\"/orders\"")); - request.releaseConnection(); - } - - @Test - public void testApiProductsRoute() - throws ClientProtocolException, IOException - { - HttpGet request = new HttpGet("http://localhost:9001/api-docs/products"); - HttpResponse response = (HttpResponse) http.execute(request); - HttpEntity entity = response.getEntity(); - String json = EntityUtils.toString(entity); - assertTrue(json.contains("\"apiVersion\":\"1.0\"")); - assertTrue(json.contains("\"swaggerVersion\":\"1.2\"")); - assertTrue(json.contains("\"basePath\":\"http://localhost:9001\"")); - assertTrue(json.contains("\"resourcePath\":\"/products\"")); - request.releaseConnection(); - } - - @Test - public void testApiHealthRoute() - throws ClientProtocolException, IOException - { - HttpGet request = new HttpGet("http://localhost:9001/api-docs/health"); - HttpResponse response = (HttpResponse) http.execute(request); - HttpEntity entity = response.getEntity(); - String json = EntityUtils.toString(entity); - assertTrue(json.contains("\"apiVersion\":\"1.0\"")); - assertTrue(json.contains("\"swaggerVersion\":\"1.2\"")); - assertTrue(json.contains("\"basePath\":\"http://localhost:9001\"")); - assertTrue(json.contains("\"resourcePath\":\"/health\"")); - request.releaseConnection(); - } - - @Test - public void testNickname() - throws ClientProtocolException, IOException - { - HttpGet request = new HttpGet("http://localhost:9001/api-docs/nicknametest"); - HttpResponse response = (HttpResponse) http.execute(request); - HttpEntity entity = response.getEntity(); - String json = EntityUtils.toString(entity); - assertTrue(json.contains("\"apiVersion\":\"1.0\"")); - assertTrue(json.contains("\"swaggerVersion\":\"1.2\"")); - assertTrue(json.contains("\"basePath\":\"http://localhost:9001\"")); - assertTrue(json.contains("\"nickname\":\"GETnickNamesh0uld_str1pCHARS\"")); - request.releaseConnection(); - } - - @Test - public void testParametersArrayAlwaysExist() - throws ClientProtocolException, IOException - { - HttpGet request = new HttpGet("http://localhost:9001/api-docs/health"); - HttpResponse response = (HttpResponse) http.execute(request); - HttpEntity entity = response.getEntity(); - String json = EntityUtils.toString(entity); - assertTrue(json.contains("\"parameters\":[]")); - request.releaseConnection(); - } - - /** - * Test controller methods with Swagger annotations return the - * expected json values. - */ - @Test - public void shouldNotShowHiddenApi() - { - Response r = get("/api-docs/annotations"); - String json = r.asString(); - assertFalse(json.contains("hidden")); - } - /** - * Test controller methods with Swagger annotations return the - * expected json values. - */ - @Test - public void shouldReturnAnnotationsApi() - { - Response r = get("/api-docs/annotations"); - String json = r.asString(); - SwaggerAssert.common(r); - r.then() - .body("basePath", equalTo(BASE_URL)) - .body("resourcePath", is("/annotations")); - - // For first api verify that summary and notes are populated successfully. - r.then() - .root("apis[%s].%s") - .body(withArgs(0, "path"), is("/annotations/{userId}/users")) - .body(withArgs(0, "description"), is("Read with Annotations")) - .body(withArgs(0, "operations"), hasItem(hasEntry("method", "GET"))) - .body(withArgs(0, "operations"), hasItem(hasEntry("type", "Another"))) - .body(withArgs(0, "operations"), hasItem(hasEntry("nickname", "GETReadwithAnnotations"))) - .body(withArgs(0, "operations"), hasItem(hasEntry("summary", "Read with Annotations."))) - .body(withArgs(0, "operations"), hasItem(hasEntry("notes", "More detailed description here."))); - - // For second api verify the three response codes are being returned correctly. - r.then() - .root("apis[1].operations[0].responseMessages[%s].%s") - .body(withArgs(0, "code"), is(204)) - .body(withArgs(0, "message"), is("Successful update")) - .body(withArgs(1, "code"), is(404)) - .body(withArgs(1, "message"), is("Item not found")) - .body(withArgs(2, "code"), is(400)) - .body(withArgs(2, "message"), is("Item id incorrect format")); - - // For third api verify the parameters are being returned correctly. - r.then() - .root("apis[2].operations[0].parameters[%s].%s") - .body(withArgs(0, "type"), is("string")) - .body(withArgs(0, "paramType"), is("path")) - .body(withArgs(0, "name"), is("userId")) - .body(withArgs(0, "required"), is(true)) - .body(withArgs(1, "type"), is("String")) - .body(withArgs(1, "description"), is("(Optional) Return item and all its children.")) - .body(withArgs(1, "paramType"), is("query")) - .body(withArgs(1, "name"), is("expand")) - .body(withArgs(1, "allowableValues"), is("all, some, none")) - .body(withArgs(1, "required"), is(false)) - .body(withArgs(2, "type"), is("String")) - .body(withArgs(2, "description"), is("(Required) Title of the item.")) - .body(withArgs(2, "paramType"), is("body")) - .body(withArgs(2, "name"), is("title")) - .body(withArgs(2, "allowableValues"), is("Any string")) - .body(withArgs(2, "required"), is(true)); - - // For fourth api verify parameters are being returned correctly. - r.then() - .root("apis[3].operations[0].parameters[%s].%s") - .body(withArgs(0, "type"), is("string")) - .body(withArgs(0, "paramType"), is("path")) - .body(withArgs(0, "name"), is("userId")) - .body(withArgs(0, "required"), is(true)) - .body(withArgs(1, "type"), is("string")) - .body(withArgs(1, "description"), is("(Required) Title of the item.")) - .body(withArgs(1, "defaultValue"), is("Title placeholder")) - .body(withArgs(1, "paramType"), is("body")) - .body(withArgs(1, "name"), is("title")) - .body(withArgs(1, "allowableValues"), is("Any String")) - .body(withArgs(1, "required"), is(true)); - - // Verify the models - r.then() - .root("models.%s.properties.%s.%s") - .body(withArgs("DummyModel", "dummy1", "type"), is("string")) - .body(withArgs("DummyModel", "dummy2", "type"), is("integer")) - .body(withArgs("DummyModel", "dummy2", "format"), is("int32")) - .body(withArgs("DummyModel", "dummy3", "type"), is("number")) - .body(withArgs("DummyModel", "dummy3", "format"), is("float")) - .body(withArgs("DummyModel", "dummy4", "type"), is("boolean")) - .body(withArgs("DummyModel", "dummy5", "type"), is("array")) - .body(withArgs("DummyModel", "dummy6", "type"), is("array")) - .body(withArgs("DummyModel", "dummy7", "type"), is("integer")) - .body(withArgs("DummyModel", "dummy7", "format"), is("int32")) - .body(withArgs("DummyModel", "dummy8", "type"), is("number")) - .body(withArgs("DummyModel", "dummy8", "format"), is("double")) - .body(withArgs("DummyModel", "dummy9", "type"), is("number")) - .body(withArgs("DummyModel", "dummy10", "type"), is("number")) - .body(withArgs("DummyModel", "dummy10", "format"), is("double")); - - // Make sure that the dummy10 property is not part of the AlternativeDummyModel model - r.then() - .root("models.%s.properties.%s") - .body(withArgs("AlternativeDummyModel", "dummy1"), notNullValue()) - .body(withArgs("AlternativeDummyModel", "dummy2"), notNullValue()) - .body(withArgs("AlternativeDummyModel", "dummy3"), notNullValue()) - .body(withArgs("AlternativeDummyModel", "dummy4"), notNullValue()) - .body(withArgs("AlternativeDummyModel", "dummy5"), notNullValue()) - .body(withArgs("AlternativeDummyModel", "dummy6"), notNullValue()) - .body(withArgs("AlternativeDummyModel", "dummy7"), notNullValue()) - .body(withArgs("AlternativeDummyModel", "dummy8"), notNullValue()) - .body(withArgs("AlternativeDummyModel", "dummy9"), notNullValue()) - .body(withArgs("AlternativeDummyModel", "dummy10"), nullValue()); - - } - -} From 95fd3b51569bf1da19b2585908505eca628adc3a Mon Sep 17 00:00:00 2001 From: Filipp Akinfiev Date: Thu, 5 Jul 2018 13:00:22 +0200 Subject: [PATCH 2/2] readme fix --- swagger/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swagger/README.md b/swagger/README.md index 301ac34..a69f84d 100644 --- a/swagger/README.md +++ b/swagger/README.md @@ -80,7 +80,7 @@ private static void configurePlugins(Configuration config, RestExpress server) { // .... } - ``` +``` add OpenApi Annotation to your controllers ```