extracted =
- extensions.next().extractParameters(paramAnnotations, paramType, typesToSkip, extensions);
-
- // since downstream processors won't know how to introspect @BeanParam, process here
- for (Parameter param : extracted) {
- if (ParameterProcessor.applyAnnotations(null, param, paramType, paramAnnotations) != null) {
- parameters.add(param);
- }
- }
- }
- }
- }
-
- @Override
- protected boolean shouldIgnoreClass(Class> cls) {
- return cls.getName().startsWith("javax.ws.rs.");
- }
-
- private Property createProperty(Type type) {
- return enforcePrimitive(ModelConverters.getInstance().readAsProperty(type), 0);
- }
-
- private Property enforcePrimitive(Property in, int level) {
- if (in instanceof RefProperty) {
- return new StringProperty();
- }
- if (in instanceof ArrayProperty) {
- if (level == 0) {
- final ArrayProperty array = (ArrayProperty) in;
- array.setItems(enforcePrimitive(array.getItems(), level + 1));
- } else {
- return new StringProperty();
- }
- }
- return in;
- }
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/PATCH.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/PATCH.java
deleted file mode 100644
index 085bcbcfc6..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/PATCH.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package io.swagger.jaxrs;
-
-import javax.ws.rs.HttpMethod;
-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)
-@HttpMethod("PATCH")
-public @interface PATCH {
-}
\ No newline at end of file
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java
deleted file mode 100644
index a715d498da..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/Reader.java
+++ /dev/null
@@ -1,1238 +0,0 @@
-/**
- * Copyright 2016 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.
- */
-
-package io.swagger.jaxrs;
-
-import com.fasterxml.jackson.databind.BeanDescription;
-import com.fasterxml.jackson.databind.JavaType;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
-import com.fasterxml.jackson.databind.introspect.AnnotatedParameter;
-import com.fasterxml.jackson.databind.type.TypeFactory;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiKeyAuthDefinition;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import io.swagger.annotations.Authorization;
-import io.swagger.annotations.AuthorizationScope;
-import io.swagger.annotations.BasicAuthDefinition;
-import io.swagger.annotations.Info;
-import io.swagger.annotations.OAuth2Definition;
-import io.swagger.annotations.ResponseHeader;
-import io.swagger.annotations.Scope;
-import io.swagger.annotations.SwaggerDefinition;
-import io.swagger.converter.ModelConverters;
-import io.swagger.jaxrs.config.DefaultReaderConfig;
-import io.swagger.jaxrs.config.ReaderConfig;
-import io.swagger.jaxrs.config.ReaderListener;
-import io.swagger.jaxrs.ext.SwaggerExtension;
-import io.swagger.jaxrs.ext.SwaggerExtensions;
-import io.swagger.jaxrs.utils.ReaderUtils;
-import io.swagger.models.Contact;
-import io.swagger.models.ExternalDocs;
-import io.swagger.models.License;
-import io.swagger.models.Model;
-import io.swagger.models.Operation;
-import io.swagger.models.Path;
-import io.swagger.models.Response;
-import io.swagger.models.Scheme;
-import io.swagger.models.SecurityRequirement;
-import io.swagger.models.Swagger;
-import io.swagger.models.Tag;
-import io.swagger.models.auth.In;
-import io.swagger.models.parameters.FormParameter;
-import io.swagger.models.parameters.HeaderParameter;
-import io.swagger.models.parameters.Parameter;
-import io.swagger.models.parameters.PathParameter;
-import io.swagger.models.parameters.QueryParameter;
-import io.swagger.models.properties.ArrayProperty;
-import io.swagger.models.properties.MapProperty;
-import io.swagger.models.properties.Property;
-import io.swagger.models.properties.RefProperty;
-import io.swagger.util.BaseReaderUtils;
-import io.swagger.util.ParameterProcessor;
-import io.swagger.util.PathUtils;
-import io.swagger.util.ReflectionUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.HttpMethod;
-import javax.ws.rs.Produces;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
-public class Reader {
- private static final Logger LOGGER = LoggerFactory.getLogger(Reader.class);
- private static final String SUCCESSFUL_OPERATION = "successful operation";
- private static final String PATH_DELIMITER = "/";
-
- private final ReaderConfig config;
- private Swagger swagger;
-
- public Reader(Swagger swagger) {
- this(swagger, null);
- }
-
- public Reader(Swagger swagger, ReaderConfig config) {
- this.swagger = (swagger == null) ? new Swagger() : swagger;
- this.config = new DefaultReaderConfig(config);
- }
-
- public Swagger getSwagger() {
- return swagger;
- }
-
- /**
- * Scans a set of classes for both ReaderListeners and Swagger annotations. All found listeners will
- * be instantiated before any of the classes are scanned for Swagger annotations - so they can be invoked
- * accordingly.
- *
- * @param classes a set of classes to scan
- * @return the generated Swagger definition
- */
- public Swagger read(Set> classes) {
- Set> sortedClasses = new TreeSet>(new Comparator>() {
- @Override
- public int compare(Class> class1, Class> class2) {
- if (class1.equals(class2)) {
- return 0;
- } else if (class1.isAssignableFrom(class2)) {
- return -1;
- } else if (class2.isAssignableFrom(class1)) {
- return 1;
- }
- return class1.getName().compareTo(class2.getName());
- }
- });
- sortedClasses.addAll(classes);
-
- Map, ReaderListener> listeners = new HashMap, ReaderListener>();
-
- for (Class> cls : sortedClasses) {
- if (ReaderListener.class.isAssignableFrom(cls) && !listeners.containsKey(cls)) {
- try {
- listeners.put(cls, (ReaderListener) cls.newInstance());
- } catch (Exception e) {
- LOGGER.error("Failed to create ReaderListener", e);
- }
- }
- }
-
- for (ReaderListener listener : listeners.values()) {
- try {
- listener.beforeScan(this, swagger);
- } catch (Exception e) {
- LOGGER.error("Unexpected error invoking beforeScan listener [" + listener.getClass().getName() + "]", e);
- }
- }
-
- // process SwaggerDefinitions first - so we get tags in desired order
- for (Class> cls : sortedClasses) {
- SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);
- if (swaggerDefinition != null) {
- readSwaggerConfig(cls, swaggerDefinition);
- }
- }
-
- for (Class> cls : sortedClasses) {
- read(cls, "", null, false, new String[0], new String[0], new LinkedHashMap(), new ArrayList(), new HashSet>());
- }
-
- for (ReaderListener listener : listeners.values()) {
- try {
- listener.afterScan(this, swagger);
- } catch (Exception e) {
- LOGGER.error("Unexpected error invoking afterScan listener [" + listener.getClass().getName() + "]", e);
- }
- }
-
- return swagger;
- }
-
- /**
- * Scans a single class for Swagger annotations - does not invoke ReaderListeners
- */
- public Swagger read(Class> cls) {
- SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);
- if (swaggerDefinition != null) {
- readSwaggerConfig(cls, swaggerDefinition);
- }
-
- return read(cls, "", null, false, new String[0], new String[0], new LinkedHashMap(), new ArrayList(), new HashSet>());
- }
-
- protected Swagger read(Class> cls, String parentPath, String parentMethod, boolean isSubresource, String[] parentConsumes, String[] parentProduces, Map parentTags, List parentParameters) {
- return read(cls, parentPath, parentMethod, isSubresource, parentConsumes, parentProduces, parentTags, parentParameters, new HashSet>());
- }
-
- private Swagger read(Class> cls, String parentPath, String parentMethod, boolean isSubresource, String[] parentConsumes, String[] parentProduces, Map parentTags, List parentParameters, Set> scannedResources) {
- Map tags = new LinkedHashMap();
- List securities = new ArrayList();
-
- String[] consumes = new String[0];
- String[] produces = new String[0];
- final Set globalSchemes = EnumSet.noneOf(Scheme.class);
-
- Api api = ReflectionUtils.getAnnotation(cls, Api.class);
-
- boolean hasPathAnnotation = (ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class) != null);
- boolean hasApiAnnotation = (api != null);
- boolean isApiHidden = hasApiAnnotation && api.hidden();
-
- // class readable only if annotated with ((@Path and @Api) or isSubresource ) - and @Api not hidden
- boolean classReadable = ((hasPathAnnotation && hasApiAnnotation) || isSubresource) && !isApiHidden;
-
- // with scanAllResources true in config and @Api not hidden scan only if it has also @Path annotation or is subresource
- boolean scanAll = !isApiHidden && config.isScanAllResources() && (hasPathAnnotation || isSubresource);
-
- // readable if classReadable or scanAll
- boolean readable = classReadable || scanAll;
-
- if (!readable) {
- return swagger;
- }
-
- // api readable only if @Api present; cannot be hidden because checked in classReadable.
- boolean apiReadable = hasApiAnnotation;
-
- if (apiReadable) {
- // the value will be used as a tag for 2.0 UNLESS a Tags annotation is present
- Set tagStrings = extractTags(api);
- for (String tagString : tagStrings) {
- Tag tag = new Tag().name(tagString);
- tags.put(tagString, tag);
- }
- for (String tagName : tags.keySet()) {
- swagger.tag(tags.get(tagName));
- }
-
- if (!api.produces().isEmpty()) {
- produces = ReaderUtils.splitContentValues(new String[]{api.produces()});
- }
- if (!api.consumes().isEmpty()) {
- consumes = ReaderUtils.splitContentValues(new String[]{api.consumes()});
- }
- globalSchemes.addAll(parseSchemes(api.protocols()));
-
- for (Authorization auth : api.authorizations()) {
- if (auth.value() != null && !auth.value().isEmpty()) {
- SecurityRequirement security = new SecurityRequirement();
- security.setName(auth.value());
- for (AuthorizationScope scope : auth.scopes()) {
- if (scope.scope() != null && !scope.scope().isEmpty()) {
- security.addScope(scope.scope());
- }
- }
- securities.add(security);
- }
- }
- }
-
- if (readable) {
- if (isSubresource) {
- if (parentTags != null) {
- tags.putAll(parentTags);
- }
- }
- // merge consumes, produces
- if (consumes.length == 0 && cls.getAnnotation(Consumes.class) != null) {
- consumes = ReaderUtils.splitContentValues(cls.getAnnotation(Consumes.class).value());
- }
- if (produces.length == 0 && cls.getAnnotation(Produces.class) != null) {
- produces = ReaderUtils.splitContentValues(cls.getAnnotation(Produces.class).value());
- }
- // look for method-level annotated properties
-
- // handle sub-resources by looking at return type
-
- final List globalParameters = new ArrayList();
-
- // look for constructor-level annotated properties
- globalParameters.addAll(ReaderUtils.collectConstructorParameters(cls, swagger));
-
- // look for field-level annotated properties
- globalParameters.addAll(ReaderUtils.collectFieldParameters(cls, swagger));
-
- // build class/interface level @ApiResponse list
- ApiResponses classResponseAnnotation = ReflectionUtils.getAnnotation(cls, ApiResponses.class);
- List classApiResponses = new ArrayList();
- if (classResponseAnnotation != null) {
- classApiResponses.addAll(Arrays.asList(classResponseAnnotation.value()));
- }
-
- // parse the method
- final javax.ws.rs.Path apiPath = ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class);
- JavaType classType = TypeFactory.defaultInstance().constructType(cls);
- BeanDescription bd = new ObjectMapper().getSerializationConfig().introspect(classType);
- Method methods[] = cls.getMethods();
- for (Method method : methods) {
- AnnotatedMethod annotatedMethod = bd.findMethod(method.getName(), method.getParameterTypes());
- if (ReflectionUtils.isOverriddenMethod(method, cls)) {
- continue;
- }
- javax.ws.rs.Path methodPath = ReflectionUtils.getAnnotation(method, javax.ws.rs.Path.class);
-
- String operationPath = getPath(apiPath, methodPath, parentPath);
- Map regexMap = new LinkedHashMap();
- operationPath = PathUtils.parsePath(operationPath, regexMap);
- if (operationPath != null) {
- if (isIgnored(operationPath)) {
- continue;
- }
-
- final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
- String httpMethod = extractOperationMethod(apiOperation, method, SwaggerExtensions.chain());
-
- Operation operation = null;
- if (apiOperation != null || config.isScanAllResources() || httpMethod != null || methodPath != null) {
- operation = parseMethod(cls, method, annotatedMethod, globalParameters, classApiResponses);
- }
- if (operation == null) {
- continue;
- }
- if (parentParameters != null) {
- for (Parameter param : parentParameters) {
- operation.parameter(param);
- }
- }
- for (Parameter param : operation.getParameters()) {
- if (regexMap.get(param.getName()) != null) {
- String pattern = regexMap.get(param.getName());
- param.setPattern(pattern);
- }
- }
-
- if (apiOperation != null) {
- for (Scheme scheme : parseSchemes(apiOperation.protocols())) {
- operation.scheme(scheme);
- }
- }
-
- if (operation.getSchemes() == null || operation.getSchemes().isEmpty()) {
- for (Scheme scheme : globalSchemes) {
- operation.scheme(scheme);
- }
- }
-
- String[] apiConsumes = consumes;
- if (parentConsumes != null) {
- Set both = new LinkedHashSet(Arrays.asList(apiConsumes));
- both.addAll(new LinkedHashSet(Arrays.asList(parentConsumes)));
- if (operation.getConsumes() != null) {
- both.addAll(new LinkedHashSet(operation.getConsumes()));
- }
- apiConsumes = both.toArray(new String[both.size()]);
- }
-
- String[] apiProduces = produces;
- if (parentProduces != null) {
- Set both = new LinkedHashSet(Arrays.asList(apiProduces));
- both.addAll(new LinkedHashSet(Arrays.asList(parentProduces)));
- if (operation.getProduces() != null) {
- both.addAll(new LinkedHashSet(operation.getProduces()));
- }
- apiProduces = both.toArray(new String[both.size()]);
- }
- final Class> subResource = getSubResourceWithJaxRsSubresourceLocatorSpecs(method);
- if (subResource != null && !scannedResources.contains(subResource)) {
- scannedResources.add(subResource);
- read(subResource, operationPath, httpMethod, true, apiConsumes, apiProduces, tags, operation.getParameters(), scannedResources);
- // remove the sub resource so that it can visit it later in another path
- // but we have a room for optimization in the future to reuse the scanned result
- // by caching the scanned resources in the reader instance to avoid actual scanning
- // the the resources again
- scannedResources.remove(subResource);
- }
-
- // can't continue without a valid http method
- httpMethod = (httpMethod == null) ? parentMethod : httpMethod;
- if (httpMethod != null) {
- if (apiOperation != null) {
- for (String tag : apiOperation.tags()) {
- if (!"".equals(tag)) {
- operation.tag(tag);
- swagger.tag(new Tag().name(tag));
- }
- }
-
- operation.getVendorExtensions().putAll(BaseReaderUtils.parseExtensions(apiOperation.extensions()));
- }
-
- if (operation.getConsumes() == null) {
- for (String mediaType : apiConsumes) {
- operation.consumes(mediaType);
- }
- }
- if (operation.getProduces() == null) {
- for (String mediaType : apiProduces) {
- operation.produces(mediaType);
- }
- }
-
- if (operation.getTags() == null) {
- for (String tagString : tags.keySet()) {
- operation.tag(tagString);
- }
- }
- // Only add global @Api securities if operation doesn't already have more specific securities
- if (operation.getSecurity() == null) {
- for (SecurityRequirement security : securities) {
- operation.security(security);
- }
- }
-
- Path path = swagger.getPath(operationPath);
- if (path == null) {
- path = new Path();
- swagger.path(operationPath, path);
- }
- path.set(httpMethod, operation);
-
- readImplicitParameters(method, operation);
-
- readExternalDocs(method, operation);
- }
- }
- }
- }
-
- return swagger;
- }
-
- private void readImplicitParameters(Method method, Operation operation) {
- processImplicitParams(ReflectionUtils.getAnnotation(method, ApiImplicitParams.class), operation);
- processImplicitParams(ReflectionUtils.getAnnotation(method.getDeclaringClass(), ApiImplicitParams.class), operation);
- }
-
- private void processImplicitParams(ApiImplicitParams implicitParams, Operation operation) {
- if (implicitParams != null) {
- for (ApiImplicitParam param : implicitParams.value()) {
- Parameter p = readImplicitParam(param);
- if (p != null) {
- operation.addParameter(p);
- }
- }
- }
- }
-
- private void readExternalDocs(Method method, Operation operation) {
- io.swagger.annotations.ExternalDocs externalDocs = ReflectionUtils.getAnnotation(method, io.swagger.annotations.ExternalDocs.class);
- if(externalDocs != null) {
- operation.setExternalDocs(new ExternalDocs(externalDocs.value(), externalDocs.url()));
- }
- }
-
- protected Parameter readImplicitParam(ApiImplicitParam param) {
- final Parameter p;
- if (param.paramType().equalsIgnoreCase("path")) {
- p = new PathParameter();
- } else if (param.paramType().equalsIgnoreCase("query")) {
- p = new QueryParameter();
- } else if (param.paramType().equalsIgnoreCase("form") || param.paramType().equalsIgnoreCase("formData")) {
- p = new FormParameter();
- } else if (param.paramType().equalsIgnoreCase("body")) {
- p = null;
- } else if (param.paramType().equalsIgnoreCase("header")) {
- p = new HeaderParameter();
- } else {
- LOGGER.warn("Unknown implicit parameter type: [{}]", param.paramType());
- return null;
- }
- final Type type = param.dataTypeClass() == Void.class ? ReflectionUtils.typeFromString(param.dataType())
- : param.dataTypeClass();
- return ParameterProcessor.applyAnnotations(swagger, p, (type == null) ? String.class : type,
- Arrays.asList(param));
- }
-
- protected void readSwaggerConfig(Class> cls, SwaggerDefinition config) {
- if (!config.basePath().isEmpty()) {
- swagger.setBasePath(config.basePath());
- }
-
- if (!config.host().isEmpty()) {
- swagger.setHost(config.host());
- }
-
- readInfoConfig(config);
-
- for (String consume : config.consumes()) {
- if (StringUtils.isNotEmpty(consume)) {
- swagger.addConsumes(consume);
- }
- }
-
- for (String produce : config.produces()) {
- if (StringUtils.isNotEmpty(produce)) {
- swagger.addProduces(produce);
- }
- }
-
- for (OAuth2Definition oAuth2Config : config.securityDefinition().oAuth2Definitions()) {
- io.swagger.models.auth.OAuth2Definition oAuth2Definition = new io.swagger.models.auth.OAuth2Definition();
- OAuth2Definition.Flow flow = oAuth2Config.flow();
-
- if (flow.equals(OAuth2Definition.Flow.ACCESS_CODE)) {
- oAuth2Definition = oAuth2Definition.accessCode(oAuth2Config.authorizationUrl(), oAuth2Config.tokenUrl());
- } else if (flow.equals(OAuth2Definition.Flow.APPLICATION)) {
- oAuth2Definition = oAuth2Definition.application(oAuth2Config.tokenUrl());
- } else if (flow.equals(OAuth2Definition.Flow.IMPLICIT)) {
- oAuth2Definition = oAuth2Definition.implicit(oAuth2Config.authorizationUrl());
- } else {
- oAuth2Definition = oAuth2Definition.password(oAuth2Config.tokenUrl());
- }
-
- for (Scope scope : oAuth2Config.scopes()) {
- oAuth2Definition.addScope(scope.name(), scope.description());
- }
-
- oAuth2Definition.setDescription(oAuth2Config.description());
- swagger.addSecurityDefinition(oAuth2Config.key(), oAuth2Definition);
- }
-
- for (ApiKeyAuthDefinition[] apiKeyAuthConfigs : new ApiKeyAuthDefinition[][] {
- config.securityDefinition().apiKeyAuthDefintions(), config.securityDefinition().apiKeyAuthDefinitions() }) {
- for (ApiKeyAuthDefinition apiKeyAuthConfig : apiKeyAuthConfigs) {
- io.swagger.models.auth.ApiKeyAuthDefinition apiKeyAuthDefinition = new io.swagger.models.auth.ApiKeyAuthDefinition();
-
- apiKeyAuthDefinition.setName(apiKeyAuthConfig.name());
- apiKeyAuthDefinition.setIn(In.forValue(apiKeyAuthConfig.in().toValue()));
- apiKeyAuthDefinition.setDescription(apiKeyAuthConfig.description());
-
- swagger.addSecurityDefinition(apiKeyAuthConfig.key(), apiKeyAuthDefinition);
- }
- }
-
- for (BasicAuthDefinition[] basicAuthConfigs : new BasicAuthDefinition[][] {
- config.securityDefinition().basicAuthDefinions(), config.securityDefinition().basicAuthDefinitions() }) {
- for (BasicAuthDefinition basicAuthConfig : basicAuthConfigs) {
- io.swagger.models.auth.BasicAuthDefinition basicAuthDefinition = new io.swagger.models.auth.BasicAuthDefinition();
-
- basicAuthDefinition.setDescription(basicAuthConfig.description());
-
- swagger.addSecurityDefinition(basicAuthConfig.key(), basicAuthDefinition);
- }
- }
-
- if (!config.externalDocs().value().isEmpty()) {
- ExternalDocs externalDocs = swagger.getExternalDocs();
- if (externalDocs == null) {
- externalDocs = new ExternalDocs();
- swagger.setExternalDocs(externalDocs);
- }
-
- externalDocs.setDescription(config.externalDocs().value());
-
- if (!config.externalDocs().url().isEmpty()) {
- externalDocs.setUrl(config.externalDocs().url());
- }
- }
-
- for (io.swagger.annotations.Tag tagConfig : config.tags()) {
- if (!tagConfig.name().isEmpty()) {
- Tag tag = new Tag();
- tag.setName(tagConfig.name());
- tag.setDescription(tagConfig.description());
-
- if (!tagConfig.externalDocs().value().isEmpty()) {
- tag.setExternalDocs(new ExternalDocs(tagConfig.externalDocs().value(),
- tagConfig.externalDocs().url()));
- }
-
- tag.getVendorExtensions().putAll(BaseReaderUtils.parseExtensions(tagConfig.extensions()));
-
- swagger.addTag(tag);
- }
- }
-
- for (SwaggerDefinition.Scheme scheme : config.schemes()) {
- if (scheme != SwaggerDefinition.Scheme.DEFAULT) {
- swagger.addScheme(Scheme.forValue(scheme.name()));
- }
- }
- }
-
- protected void readInfoConfig(SwaggerDefinition config) {
- Info infoConfig = config.info();
- io.swagger.models.Info info = swagger.getInfo();
- if (info == null) {
- info = new io.swagger.models.Info();
- swagger.setInfo(info);
- }
-
- if (!infoConfig.description().isEmpty()) {
- info.setDescription(infoConfig.description());
- }
-
- if (!infoConfig.termsOfService().isEmpty()) {
- info.setTermsOfService(infoConfig.termsOfService());
- }
-
- if (!infoConfig.title().isEmpty()) {
- info.setTitle(infoConfig.title());
- }
-
- if (!infoConfig.version().isEmpty()) {
- info.setVersion(infoConfig.version());
- }
-
- if (!infoConfig.contact().name().isEmpty()) {
- Contact contact = info.getContact();
- if (contact == null) {
- contact = new Contact();
- info.setContact(contact);
- }
-
- contact.setName(infoConfig.contact().name());
- if (!infoConfig.contact().email().isEmpty()) {
- contact.setEmail(infoConfig.contact().email());
- }
-
- if (!infoConfig.contact().url().isEmpty()) {
- contact.setUrl(infoConfig.contact().url());
- }
- }
-
- if (!infoConfig.license().name().isEmpty()) {
- License license = info.getLicense();
- if (license == null) {
- license = new License();
- info.setLicense(license);
- }
-
- license.setName(infoConfig.license().name());
- if (!infoConfig.license().url().isEmpty()) {
- license.setUrl(infoConfig.license().url());
- }
- }
-
- info.getVendorExtensions().putAll(BaseReaderUtils.parseExtensions(infoConfig.extensions()));
- }
-
- protected Class> getSubResource(Method method) {
- final Class> rawType = method.getReturnType();
- final Class> type;
- if (Class.class.equals(rawType)) {
- type = getClassArgument(method.getGenericReturnType());
- if (type == null) {
- return null;
- }
- } else {
- type = rawType;
- }
-
- if (type.getAnnotation(Api.class) != null) {
- return type;
- }
-
- // For sub-resources that are not annotated with @Api, look for any HttpMethods.
- for (Method m : type.getMethods()) {
- if (extractOperationMethod(null, m, null) != null) {
- return type;
- }
- }
-
- return null;
- }
-
- protected Class> getSubResourceWithJaxRsSubresourceLocatorSpecs(Method method) {
- final Class> rawType = method.getReturnType();
- final Class> type;
- if (Class.class.equals(rawType)) {
- type = getClassArgument(method.getGenericReturnType());
- if (type == null) {
- return null;
- }
- } else {
- type = rawType;
- }
-
- if (method.getAnnotation(javax.ws.rs.Path.class) != null) {
- if (extractOperationMethod(null, method, null) == null) {
- return type;
- }
- }
- return null;
- }
-
- private static Class> getClassArgument(Type cls) {
- if (cls instanceof ParameterizedType) {
- final ParameterizedType parameterized = (ParameterizedType) cls;
- final Type[] args = parameterized.getActualTypeArguments();
- if (args.length != 1) {
- LOGGER.error("Unexpected class definition: {}", cls);
- return null;
- }
- final Type first = args[0];
- if (first instanceof Class) {
- return (Class>) first;
- } else {
- return null;
- }
- } else {
- LOGGER.error("Unknown class definition: {}", cls);
- return null;
- }
- }
-
- protected Set extractTags(Api api) {
- Set output = new LinkedHashSet();
-
- boolean hasExplicitTags = false;
- for (String tag : api.tags()) {
- if (!"".equals(tag)) {
- hasExplicitTags = true;
- output.add(tag);
- }
- }
- if (!hasExplicitTags) {
- // derive tag from api path + description
- String tagString = api.value().replace("/", "");
- if (!"".equals(tagString)) {
- output.add(tagString);
- }
- }
- return output;
- }
-
- String getPath(javax.ws.rs.Path classLevelPath, javax.ws.rs.Path methodLevelPath, String parentPath) {
- if (classLevelPath == null && methodLevelPath == null && StringUtils.isEmpty(parentPath)) {
- return null;
- }
- StringBuilder b = new StringBuilder();
- if (parentPath != null && !"".equals(parentPath) && !"/".equals(parentPath)) {
- if (!parentPath.startsWith("/")) {
- parentPath = "/" + parentPath;
- }
- if (parentPath.endsWith("/")) {
- parentPath = parentPath.substring(0, parentPath.length() - 1);
- }
-
- b.append(parentPath);
- }
- if (classLevelPath != null) {
- b.append(classLevelPath.value());
- }
- if (methodLevelPath != null && !"/".equals(methodLevelPath.value())) {
- String methodPath = methodLevelPath.value();
- if (!methodPath.startsWith("/") && !b.toString().endsWith("/")) {
- b.append("/");
- }
- if (methodPath.endsWith("/")) {
- methodPath = methodPath.substring(0, methodPath.length() - 1);
- }
- b.append(methodPath);
- }
- String output = b.toString();
- if (!output.startsWith("/")) {
- output = "/" + output;
- }
- if (output.endsWith("/") && output.length() > 1) {
- return output.substring(0, output.length() - 1);
- } else {
- return output;
- }
- }
-
- private Map parseResponseHeaders(ResponseHeader[] headers) {
- Map responseHeaders = null;
- if (headers != null) {
- for (ResponseHeader header : headers) {
- String name = header.name();
- if (!"".equals(name)) {
- if (responseHeaders == null) {
- responseHeaders = new LinkedHashMap();
- }
- String description = header.description();
- Class> cls = header.response();
-
- if (!isVoid(cls)) {
- final Property property = ModelConverters.getInstance().readAsProperty(cls);
- if (property != null) {
- Property responseProperty = ContainerWrapper.wrapContainer(header.responseContainer(), property,
- ContainerWrapper.ARRAY, ContainerWrapper.LIST, ContainerWrapper.SET);
- responseProperty.setDescription(description);
- responseHeaders.put(name, responseProperty);
- appendModels(cls);
- }
- }
- }
- }
- }
- return responseHeaders;
- }
-
- public Operation parseMethod(Method method) {
- JavaType classType = TypeFactory.defaultInstance().constructType(method.getDeclaringClass());
- BeanDescription bd = new ObjectMapper().getSerializationConfig().introspect(classType);
- return parseMethod(classType.getClass(), method, bd.findMethod(method.getName(), method.getParameterTypes()),
- Collections. emptyList(), Collections. emptyList());
- }
-
- private Operation parseMethod(Class> cls, Method method, AnnotatedMethod annotatedMethod,
- List globalParameters, List classApiResponses) {
- Operation operation = new Operation();
- if (annotatedMethod != null) {
- method = annotatedMethod.getAnnotated();
- }
- ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
- ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class);
-
- String operationId = null;
- // check if it's an inherited or implemented method.
- boolean methodInSuperType = false;
- if (!cls.isInterface()) {
- methodInSuperType = ReflectionUtils.findMethod(method, cls.getSuperclass()) != null;
- }
- if (!methodInSuperType) {
- for (Class> implementedInterface : cls.getInterfaces()) {
- methodInSuperType = ReflectionUtils.findMethod(method, implementedInterface) != null;
- if (methodInSuperType) {
- break;
- }
- }
- }
- if (!methodInSuperType) {
- operationId = method.getName();
- } else {
- operationId = this.getOperationId(method.getName());
- }
- String responseContainer = null;
-
- Type responseType = null;
- Map defaultResponseHeaders = new LinkedHashMap();
-
- if (apiOperation != null) {
- if (apiOperation.hidden()) {
- return null;
- }
- if (!apiOperation.nickname().isEmpty()) {
- operationId = apiOperation.nickname();
- }
-
- defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders());
-
- operation.summary(apiOperation.value()).description(apiOperation.notes());
-
- if (!isVoid(apiOperation.response())) {
- responseType = apiOperation.response();
- }
- if (!apiOperation.responseContainer().isEmpty()) {
- responseContainer = apiOperation.responseContainer();
- }
- List securities = new ArrayList();
- for (Authorization auth : apiOperation.authorizations()) {
- if (!auth.value().isEmpty()) {
- SecurityRequirement security = new SecurityRequirement();
- security.setName(auth.value());
- for (AuthorizationScope scope : auth.scopes()) {
- if (!scope.scope().isEmpty()) {
- security.addScope(scope.scope());
- }
- }
- securities.add(security);
- }
- }
- for (SecurityRequirement sec : securities) {
- operation.security(sec);
- }
- if (!apiOperation.consumes().isEmpty()) {
- String[] consumesAr = ReaderUtils.splitContentValues(new String[]{apiOperation.consumes()});
- for (String consume : consumesAr) {
- operation.consumes(consume);
- }
- }
- if (!apiOperation.produces().isEmpty()) {
- String[] producesAr = ReaderUtils.splitContentValues(new String[]{apiOperation.produces()});
- for (String produce : producesAr) {
- operation.produces(produce);
- }
- }
- }
-
- if (apiOperation != null && StringUtils.isNotEmpty(apiOperation.responseReference())) {
- Response response = new Response().description(SUCCESSFUL_OPERATION);
- response.schema(new RefProperty(apiOperation.responseReference()));
- operation.addResponse(String.valueOf(apiOperation.code()), response);
- } else if (responseType == null) {
- // pick out response from method declaration
- LOGGER.debug("picking up response class from method {}", method);
- responseType = method.getGenericReturnType();
- }
- if (isValidResponse(responseType)) {
- final Property property = ModelConverters.getInstance().readAsProperty(responseType);
- if (property != null) {
- final Property responseProperty = ContainerWrapper.wrapContainer(responseContainer, property);
- final int responseCode = (apiOperation == null) ? 200 : apiOperation.code();
- operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION).schema(responseProperty)
- .headers(defaultResponseHeaders));
- appendModels(responseType);
- }
- }
-
- operation.operationId(operationId);
-
- if (operation.getConsumes() == null || operation.getConsumes().isEmpty()) {
- final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class);
- if (consumes != null) {
- for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) {
- operation.consumes(mediaType);
- }
- }
- }
-
- if (operation.getProduces() == null || operation.getProduces().isEmpty()) {
- final Produces produces = ReflectionUtils.getAnnotation(method, Produces.class);
- if (produces != null) {
- for (String mediaType : ReaderUtils.splitContentValues(produces.value())) {
- operation.produces(mediaType);
- }
- }
- }
-
- List apiResponses = new ArrayList();
- if (responseAnnotation != null) {
- apiResponses.addAll(Arrays.asList(responseAnnotation.value()));
- }
-
- Class>[] exceptionTypes = method.getExceptionTypes();
- for (Class> exceptionType : exceptionTypes) {
- ApiResponses exceptionResponses = ReflectionUtils.getAnnotation(exceptionType, ApiResponses.class);
- if (exceptionResponses != null) {
- apiResponses.addAll(Arrays.asList(exceptionResponses.value()));
- }
- }
-
- for (ApiResponse apiResponse : apiResponses) {
- addResponse(operation, apiResponse);
- }
- // merge class level @ApiResponse
- for (ApiResponse apiResponse : classApiResponses) {
- String key = (apiResponse.code() == 0) ? "default" : String.valueOf(apiResponse.code());
- if (operation.getResponses() != null && operation.getResponses().containsKey(key)) {
- continue;
- }
- addResponse(operation, apiResponse);
- }
-
- if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) {
- operation.setDeprecated(true);
- }
-
- // process parameters
- for (Parameter globalParameter : globalParameters) {
- operation.parameter(globalParameter);
- }
-
- Annotation[][] paramAnnotations = ReflectionUtils.getParameterAnnotations(method);
- if (annotatedMethod == null) {
- Type[] genericParameterTypes = method.getGenericParameterTypes();
- for (int i = 0; i < genericParameterTypes.length; i++) {
- final Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls);
- List parameters = getParameters(type, Arrays.asList(paramAnnotations[i]));
-
- for (Parameter parameter : parameters) {
- operation.parameter(parameter);
- }
- }
- } else {
- for (int i = 0; i < annotatedMethod.getParameterCount(); i++) {
- AnnotatedParameter param = annotatedMethod.getParameter(i);
- final Type type = TypeFactory.defaultInstance().constructType(param.getParameterType(), cls);
- List parameters = getParameters(type, Arrays.asList(paramAnnotations[i]));
-
- for (Parameter parameter : parameters) {
- operation.parameter(parameter);
- }
- }
- }
-
- if (operation.getResponses() == null) {
- Response response = new Response().description(SUCCESSFUL_OPERATION);
- operation.defaultResponse(response);
- }
-
- processOperationDecorator(operation, method);
-
- return operation;
- }
-
- private void processOperationDecorator(Operation operation, Method method) {
- final Iterator chain = SwaggerExtensions.chain();
- if (chain.hasNext()) {
- SwaggerExtension extension = chain.next();
- LOGGER.debug("trying to decorate operation: {}", extension);
- extension.decorateOperation(operation, method, chain);
- }
- }
-
- private void addResponse(Operation operation, ApiResponse apiResponse) {
- Map responseHeaders = parseResponseHeaders(apiResponse.responseHeaders());
-
- Response response = new Response()
- .description(apiResponse.message()).headers(responseHeaders);
-
- if (apiResponse.code() == 0) {
- operation.defaultResponse(response);
- } else {
- operation.response(apiResponse.code(), response);
- }
-
- if (StringUtils.isNotEmpty(apiResponse.reference())) {
- response.schema(new RefProperty(apiResponse.reference()));
- } else if (!isVoid(apiResponse.response())) {
- Type responseType = apiResponse.response();
- final Property property = ModelConverters.getInstance().readAsProperty(responseType);
- if (property != null) {
- response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property));
- appendModels(responseType);
- }
- }
- }
-
- private List getParameters(Type type, List annotations) {
- final Iterator chain = SwaggerExtensions.chain();
- if (!chain.hasNext()) {
- return Collections.emptyList();
- }
- LOGGER.debug("getParameters for {}", type);
- Set typesToSkip = new HashSet();
- final SwaggerExtension extension = chain.next();
- LOGGER.debug("trying extension {}", extension);
-
- final List parameters = extension.extractParameters(annotations, type, typesToSkip, chain);
- if (!parameters.isEmpty()) {
- final List processed = new ArrayList(parameters.size());
- for (Parameter parameter : parameters) {
- if (ParameterProcessor.applyAnnotations(swagger, parameter, type, annotations) != null) {
- processed.add(parameter);
- }
- }
- return processed;
- } else {
- LOGGER.debug("no parameter found, looking at body params");
- final List body = new ArrayList();
- if (!typesToSkip.contains(type)) {
- Parameter param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations);
- if (param != null) {
- body.add(param);
- }
- }
- return body;
- }
- }
-
- public String extractOperationMethod(ApiOperation apiOperation, Method method, Iterator chain) {
- if (apiOperation != null && !"".equals(apiOperation.httpMethod())) {
- return apiOperation.httpMethod().toLowerCase();
- } else if (method.getAnnotation(javax.ws.rs.GET.class) != null) {
- return "get";
- } else if (method.getAnnotation(javax.ws.rs.PUT.class) != null) {
- return "put";
- } else if (method.getAnnotation(javax.ws.rs.POST.class) != null) {
- return "post";
- } else if (method.getAnnotation(javax.ws.rs.DELETE.class) != null) {
- return "delete";
- } else if (method.getAnnotation(javax.ws.rs.OPTIONS.class) != null) {
- return "options";
- } else if (method.getAnnotation(javax.ws.rs.HEAD.class) != null) {
- return "head";
- } else if (method.getAnnotation(PATCH.class) != null) {
- return "patch";
- } else if (method.getAnnotation(HttpMethod.class) != null) {
- HttpMethod httpMethod = method.getAnnotation(HttpMethod.class);
- return httpMethod.value().toLowerCase();
- } else if (!StringUtils.isEmpty(getHttpMethodFromCustomAnnotations(method))) {
- return getHttpMethodFromCustomAnnotations(method);
- } else if ((ReflectionUtils.getOverriddenMethod(method)) != null) {
- return extractOperationMethod(apiOperation, ReflectionUtils.getOverriddenMethod(method), chain);
- } else if (chain != null && chain.hasNext()) {
- return chain.next().extractOperationMethod(apiOperation, method, chain);
- } else {
- return null;
- }
- }
-
- private String getHttpMethodFromCustomAnnotations(Method method) {
- for (Annotation methodAnnotation : method.getAnnotations()) {
- HttpMethod httpMethod = methodAnnotation.annotationType().getAnnotation(HttpMethod.class);
- if (httpMethod != null) {
- return httpMethod.value().toLowerCase();
- }
- }
- return null;
- }
-
- private static Set parseSchemes(String schemes) {
- final Set result = EnumSet.noneOf(Scheme.class);
- for (String item : StringUtils.trimToEmpty(schemes).split(",")) {
- final Scheme scheme = Scheme.forValue(StringUtils.trimToNull(item));
- if (scheme != null) {
- result.add(scheme);
- }
- }
- return result;
- }
-
- private void appendModels(Type type) {
- final Map models = ModelConverters.getInstance().readAll(type);
- for (Map.Entry entry : models.entrySet()) {
- swagger.model(entry.getKey(), entry.getValue());
- }
- }
-
- private static boolean isVoid(Type type) {
- final Class> cls = TypeFactory.defaultInstance().constructType(type).getRawClass();
- return Void.class.isAssignableFrom(cls) || Void.TYPE.isAssignableFrom(cls);
- }
-
- private boolean isIgnored(String path) {
- for (String item : config.getIgnoredRoutes()) {
- final int length = item.length();
- if (path.startsWith(item) && (path.length() == length || path.startsWith(PATH_DELIMITER, length))) {
- return true;
- }
- }
- return false;
- }
-
- private static boolean isValidResponse(Type type) {
- if (type == null) {
- return false;
- }
- final JavaType javaType = TypeFactory.defaultInstance().constructType(type);
- if (isVoid(javaType)) {
- return false;
- }
- final Class> cls = javaType.getRawClass();
- return !javax.ws.rs.core.Response.class.isAssignableFrom(cls) && !isResourceClass(cls);
- }
-
- private static boolean isResourceClass(Class> cls) {
- return cls.getAnnotation(Api.class) != null;
- }
-
- public ReaderConfig getConfig() {
- return config;
- }
-
- enum ContainerWrapper {
- LIST("list") {
- @Override
- protected Property doWrap(Property property) {
- return new ArrayProperty(property);
- }
- },
- ARRAY("array") {
- @Override
- protected Property doWrap(Property property) {
- return new ArrayProperty(property);
- }
- },
- MAP("map") {
- @Override
- protected Property doWrap(Property property) {
- return new MapProperty(property);
- }
- },
- SET("set") {
- @Override
- protected Property doWrap(Property property) {
- ArrayProperty arrayProperty = new ArrayProperty(property);
- arrayProperty.setUniqueItems(true);
- return arrayProperty;
- }
- };
-
- private final String container;
-
- ContainerWrapper(String container) {
- this.container = container;
- }
-
- public static Property wrapContainer(String container, Property property, ContainerWrapper... allowed) {
- final Set tmp = (allowed.length > 0) ? EnumSet.copyOf(Arrays.asList(allowed))
- : EnumSet.allOf(ContainerWrapper.class);
- for (ContainerWrapper wrapper : tmp) {
- final Property prop = wrapper.wrap(container, property);
- if (prop != null) {
- return prop;
- }
- }
- return property;
- }
-
- public Property wrap(String container, Property property) {
- if (this.container.equalsIgnoreCase(container)) {
- return doWrap(property);
- }
- return null;
- }
-
- protected abstract Property doWrap(Property property);
- }
-
- protected String getOperationId(String operationId) {
- boolean operationIdUsed = existOperationId(operationId);
- String operationIdToFind = null;
- int counter = 0;
- while (operationIdUsed) {
- operationIdToFind = String.format("%s_%d", operationId, ++counter);
- operationIdUsed = existOperationId(operationIdToFind);
- }
- if (operationIdToFind != null) {
- operationId = operationIdToFind;
- }
- return operationId;
- }
-
- private boolean existOperationId(String operationId) {
- if (swagger == null) {
- return false;
- }
- if (swagger.getPaths() == null || swagger.getPaths().isEmpty()) {
- return false;
- }
- for (Path path : swagger.getPaths().values()) {
- for (Operation op : path.getOperations()) {
- if (operationId.equalsIgnoreCase(op.getOperationId())) {
- return true;
- }
- }
- }
- return false;
- }
-}
\ No newline at end of file
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/AbstractScanner.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/AbstractScanner.java
deleted file mode 100644
index 13b0f4492c..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/AbstractScanner.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package io.swagger.jaxrs.config;
-
-public abstract class AbstractScanner {
- protected boolean prettyPrint = false;
-
- public boolean getPrettyPrint() {
- return prettyPrint;
- }
-
- public void setPrettyPrint(boolean shouldPrettyPrint) {
- this.prettyPrint = shouldPrettyPrint;
- }
-}
\ No newline at end of file
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/BeanConfig.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/BeanConfig.java
deleted file mode 100644
index 2293a5da50..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/BeanConfig.java
+++ /dev/null
@@ -1,376 +0,0 @@
-package io.swagger.jaxrs.config;
-
-import java.lang.annotation.Annotation;
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.servlet.ServletConfig;
-import javax.ws.rs.Path;
-
-import org.apache.commons.lang3.StringUtils;
-import org.reflections.Reflections;
-import org.reflections.scanners.ResourcesScanner;
-import org.reflections.scanners.SubTypesScanner;
-import org.reflections.scanners.TypeAnnotationsScanner;
-import org.reflections.util.ClasspathHelper;
-import org.reflections.util.ConfigurationBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.reflect.TypeToken;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.SwaggerDefinition;
-import io.swagger.config.FilterFactory;
-import io.swagger.config.Scanner;
-import io.swagger.config.SwaggerConfig;
-import io.swagger.core.filter.SwaggerSpecFilter;
-import io.swagger.jaxrs.Reader;
-import io.swagger.models.Contact;
-import io.swagger.models.Info;
-import io.swagger.models.License;
-import io.swagger.models.Scheme;
-import io.swagger.models.Swagger;
-
-public class BeanConfig extends AbstractScanner implements Scanner, SwaggerConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(BeanConfig.class);
-
- Reader reader = new Reader(new Swagger());
-
- ServletConfig servletConfig;
-
- String resourcePackage;
- String[] schemes;
- String title;
- String version;
- String description;
- String termsOfServiceUrl;
- String contact;
- String license;
- String licenseUrl;
- String filterClass;
-
- Info info;
- String host;
- String basePath;
-
- String scannerId;
- String configId;
- String contextId;
-
- private boolean usePathBasedConfig = false;
-
- public boolean isUsePathBasedConfig() {
- return usePathBasedConfig;
- }
-
- public void setUsePathBasedConfig(boolean usePathBasedConfig) {
- this.usePathBasedConfig = usePathBasedConfig;
- }
-
- public String getResourcePackage() {
- return this.resourcePackage;
- }
-
- public void setResourcePackage(String resourcePackage) {
- this.resourcePackage = resourcePackage;
- }
-
- public String[] getSchemes() {
- return schemes;
- }
-
- public void setSchemes(String[] schemes) {
- this.schemes = schemes;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- 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 Info getInfo() {
- return info;
- }
-
- public void setInfo(Info info) {
- this.info = info;
- }
-
- public String getHost() {
- return host;
- }
-
- public void setHost(String host) {
- this.host = host;
- }
-
- @Override
- public String getFilterClass() {
- return filterClass;
- }
-
- public void setFilterClass(String filterClass) {
- this.filterClass = filterClass;
- }
-
- public String getContextId() {
- return contextId;
- }
-
- public void setContextId(String contextId) {
- this.contextId = contextId;
- }
-
- public String getScannerId() {
- return scannerId;
- }
-
- public void setScannerId(String scannerId) {
- this.scannerId = scannerId;
- }
-
- public String getConfigId() {
- return configId;
- }
-
- public void setServletConfig(ServletConfig servletConfig) {
- this.servletConfig = servletConfig;
- }
-
- public void setConfigId(String configId) {
- this.configId = configId;
- }
-
- public String getBasePath() {
- return basePath;
- }
-
- public void setBasePath(String basePath) {
- if (!"".equals(basePath) && basePath != null) {
- if (!basePath.startsWith("/")) {
- this.basePath = "/" + basePath;
- } else {
- this.basePath = basePath;
- }
- }
- }
-
- public void setPrettyPrint(String prettyPrint) {
- if (prettyPrint != null) {
- this.prettyPrint = Boolean.parseBoolean(prettyPrint);
- }
- }
-
- public boolean getScan() {
- return true;
- }
-
- public void setScan(boolean shouldScan) {
- scanAndRead();
- new SwaggerContextService()
- .withConfigId(configId)
- .withScannerId(scannerId)
- .withContextId(contextId)
- .withServletConfig(servletConfig)
- .withSwaggerConfig(this)
- .withScanner(this)
- .withBasePath(getBasePath())
- .withPathBasedConfig(isUsePathBasedConfig())
- .initConfig()
- .initScanner();
- }
-
- public void setScan() {
- setScan(true);
- }
-
- public void scanAndRead() {
- Set> classes = classes();
- if (classes != null) {
- Swagger swagger = reader.read(classes);
- if (StringUtils.isNotBlank(host)) {
- swagger.setHost(host);
- }
-
- if (StringUtils.isNotBlank(basePath)) {
- swagger.setBasePath(basePath);
- }
-
- updateInfoFromConfig();
- }
- }
-
- @Override
- public Set> classes() {
- ConfigurationBuilder config = new ConfigurationBuilder();
- Set acceptablePackages = new HashSet();
-
- boolean allowAllPackages = false;
-
- if (resourcePackage != null && !"".equals(resourcePackage)) {
- String[] parts = resourcePackage.split(",");
- for (String pkg : parts) {
- if (!"".equals(pkg)) {
- acceptablePackages.add(pkg);
- config.addUrls(ClasspathHelper.forPackage(pkg));
- }
- }
- } else {
- allowAllPackages = true;
- }
-
- config.setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner());
-
- final Reflections reflections = new Reflections(config);
- Set> classes = reflections.getTypesAnnotatedWith(javax.ws.rs.Path.class);
- Set> typesAnnotatedWith = reflections.getTypesAnnotatedWith(SwaggerDefinition.class);
- classes.addAll(typesAnnotatedWith);
-
- /*
- * Find concrete types annotated with @Api, but with a supertype annotated with @Path.
- * This would handle split resources where the interface has jax-rs annotations
- * and the implementing class has Swagger annotations
- */
- for (Class> cls : reflections.getTypesAnnotatedWith(Api.class)) {
- for (Class> intfc : TypeToken.of(cls).getTypes().interfaces().rawTypes()) {
- Annotation ann = intfc.getAnnotation(javax.ws.rs.Path.class);
- if (ann != null) {
- classes.add(cls);
- break;
- }
- }
- }
-
- Set> output = new HashSet>();
- for (Class> cls : classes) {
- if (allowAllPackages) {
- output.add(cls);
- } else {
- for (String pkg : acceptablePackages) {
- if (cls.getPackage().getName().startsWith(pkg)) {
- output.add(cls);
- }
- }
- }
- }
- return output;
- }
-
- private void updateInfoFromConfig() {
- info = getSwagger().getInfo();
- if (info == null) {
- info = new Info();
- }
-
- if (StringUtils.isNotBlank(description)) {
- info.description(description);
- }
-
- if (StringUtils.isNotBlank(title)) {
- info.title(title);
- }
-
- if (StringUtils.isNotBlank(version)) {
- info.version(version);
- }
-
- if (StringUtils.isNotBlank(termsOfServiceUrl)) {
- info.termsOfService(termsOfServiceUrl);
- }
-
- if (contact != null) {
- this.info.contact(new Contact()
- .name(contact));
- }
- if (license != null && licenseUrl != null) {
- this.info.license(new License()
- .name(license)
- .url(licenseUrl));
- }
- if (schemes != null) {
- for (String scheme : schemes) {
- reader.getSwagger().scheme(Scheme.forValue(scheme));
- }
- }
-
- reader.getSwagger().setInfo(info);
- }
-
- public Swagger getSwagger() {
- return reader.getSwagger();
- }
-
- @Override
- public Swagger configure(Swagger swagger) {
- if (schemes != null) {
- for (String scheme : schemes) {
- swagger.scheme(Scheme.forValue(scheme));
- }
- }
- if (filterClass != null) {
- try {
- SwaggerSpecFilter filter = (SwaggerSpecFilter) Class.forName(filterClass).newInstance();
- if (filter != null) {
- FilterFactory.setFilter(filter);
- }
- } catch (Exception e) {
- LOGGER.error("failed to load filter", e);
- }
- }
- return swagger.info(info)
- .host(host)
- .basePath(basePath);
- }
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/DefaultJaxrsConfig.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/DefaultJaxrsConfig.java
deleted file mode 100644
index a7e5c6b627..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/DefaultJaxrsConfig.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package io.swagger.jaxrs.config;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.http.HttpServlet;
-
-public class DefaultJaxrsConfig extends HttpServlet {
- @Override
- public void init(ServletConfig servletConfig) throws javax.servlet.ServletException {
- super.init(servletConfig);
- String basePath = null;
- if (SwaggerContextService.isServletConfigAvailable(servletConfig)) {
- basePath = servletConfig.getInitParameter("swagger.api.basepath");
- if (basePath != null) {
- String[] parts = basePath.split("://");
- if (parts.length > 1) {
- int pos = parts[1].indexOf("/");
- if (pos >= 0) {
- basePath = parts[1].substring(pos);
- } else {
- basePath = null;
- }
- }
- }
-
- }
-
- new SwaggerContextService().withServletConfig(servletConfig).withBasePath(basePath).initConfig().initScanner();
- ReaderConfigUtils.initReaderConfig(servletConfig);
- }
-
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/DefaultJaxrsScanner.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/DefaultJaxrsScanner.java
deleted file mode 100644
index e2ba1a2bd7..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/DefaultJaxrsScanner.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package io.swagger.jaxrs.config;
-
-import javax.servlet.ServletConfig;
-import javax.ws.rs.core.Application;
-import java.util.HashSet;
-import java.util.Set;
-
-public class DefaultJaxrsScanner extends AbstractScanner implements JaxrsScanner {
- @Override
- public Set> classesFromContext(Application app, ServletConfig sc) {
- Set> output = new HashSet>();
- if (app != null) {
- Set> clz = app.getClasses();
- if (clz != null) {
- output.addAll(clz);
- }
- Set singletons = app.getSingletons();
- if (singletons != null) {
- for (Object o : singletons) {
- output.add(o.getClass());
- }
- }
- }
- return output;
- }
-
- @Override
- public Set> classes() {
- return new HashSet>();
- }
-
- public boolean prettyPrint() {
- return getPrettyPrint();
- }
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/DefaultReaderConfig.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/DefaultReaderConfig.java
deleted file mode 100644
index fa9c92ec62..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/DefaultReaderConfig.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package io.swagger.jaxrs.config;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-
-/**
- * The {@code ReaderConfig} interface defines configuration settings for
- * JAX-RS annotations reader.
- */
-public class DefaultReaderConfig implements ReaderConfig {
- private boolean scanAllResources;
- private Collection ignoredRoutes = Collections.emptySet();
-
- /**
- * Creates default configuration.
- */
- public DefaultReaderConfig() {
- }
-
- /**
- * Creates a copy of passed configuration.
- */
- public DefaultReaderConfig(ReaderConfig src) {
- if (src == null) {
- return;
- }
- setScanAllResources(src.isScanAllResources());
- setIgnoredRoutes(src.getIgnoredRoutes());
- }
-
- @Override
- public boolean isScanAllResources() {
- return scanAllResources;
- }
-
- public void setScanAllResources(boolean scanAllResources) {
- this.scanAllResources = scanAllResources;
- }
-
- @Override
- public Collection getIgnoredRoutes() {
- return ignoredRoutes;
- }
-
- public void setIgnoredRoutes(Collection ignoredRoutes) {
- this.ignoredRoutes = ignoredRoutes == null || ignoredRoutes.isEmpty() ? Collections.emptySet()
- : Collections.unmodifiableCollection(new HashSet(ignoredRoutes));
- }
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/JaxrsScanner.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/JaxrsScanner.java
deleted file mode 100644
index b4432420ba..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/JaxrsScanner.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package io.swagger.jaxrs.config;
-
-import io.swagger.config.Scanner;
-
-import javax.servlet.ServletConfig;
-import javax.ws.rs.core.Application;
-import java.util.Set;
-
-public interface JaxrsScanner extends Scanner {
- Set> classesFromContext(Application app, ServletConfig sc);
-}
\ No newline at end of file
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/ReaderConfig.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/ReaderConfig.java
deleted file mode 100644
index f37d800fa3..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/ReaderConfig.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package io.swagger.jaxrs.config;
-
-import io.swagger.annotations.Api;
-
-import java.util.Collection;
-
-/**
- * The {@code ReaderConfig} interface defines configuration settings for
- * JAX-RS annotations reader.
- */
-public interface ReaderConfig {
-
- /**
- * Checks if all resources, but not those with the
- * {@link Api} annotation has to be processed.
- *
- * @return {@code true} if all resource has to be processed
- */
- boolean isScanAllResources();
-
- /**
- * Returns paths of resources to be ignored.
- *
- * @return collection of paths
- */
- Collection getIgnoredRoutes();
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/ReaderConfigUtils.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/ReaderConfigUtils.java
deleted file mode 100644
index bf1337497c..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/ReaderConfigUtils.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package io.swagger.jaxrs.config;
-
-import org.apache.commons.lang3.StringUtils;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-import java.util.LinkedHashSet;
-import java.util.Set;
-
-/**
- * The {@code ReaderConfigUtils} class defines helper methods for handling
- * configuration settings for JAX-RS annotations reader.
- */
-public class ReaderConfigUtils {
-
- private ReaderConfigUtils() {
- }
-
- public static void initReaderConfig(ServletConfig config) {
- if ("true".equals(config.getInitParameter("scan.all.resources"))) {
- final DefaultReaderConfig rc = new DefaultReaderConfig();
- rc.setScanAllResources(true);
- final Set ignoredRoutes = new LinkedHashSet();
- for (String item : StringUtils.trimToEmpty(config.getInitParameter("ignore.routes")).split(",")) {
- final String route = StringUtils.trimToNull(item);
- if (route != null) {
- ignoredRoutes.add(route);
- }
- }
- rc.setIgnoredRoutes(ignoredRoutes);
- config.getServletContext().setAttribute(getAttributeName(), rc);
- }
- }
-
- public static ReaderConfig getReaderConfig(ServletContext context) {
- if (context == null) return null;
- final Object attr = context.getAttribute(getAttributeName());
- if (attr instanceof ReaderConfig) {
- return (ReaderConfig) attr;
- }
- return null;
- }
-
- private static String getAttributeName() {
- return ReaderConfig.class.getName();
- }
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/ReaderListener.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/ReaderListener.java
deleted file mode 100644
index f746a72e40..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/ReaderListener.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- * Copyright 2016 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.
- */
-
-package io.swagger.jaxrs.config;
-
-import io.swagger.jaxrs.Reader;
-import io.swagger.models.Swagger;
-
-/**
- * Listener providing hooks for customizing automatically generated Swagger definitions in a JAX-RS
- * environment. Any classes picked up during the scanning process implementing this interface will
- * be instantiated via newInstance() and invoked before and after generating Swagger definitions, allowing
- * code to add additional data or change the generated definition.
- */
-
-public interface ReaderListener {
-
- /**
- * Called before the Swagger definition gets populated from scanned classes. Use this method to
- * pre-process the Swagger definition before it gets populated.
- *
- * @param reader the reader used to read annotations and build the Swagger definition
- * @param swagger the initial swagger definition
- */
-
- void beforeScan(Reader reader, Swagger swagger);
-
- /**
- * Called after a Swagger definition has been populated from scanned classes. Use this method to
- * post-process Swagger definitions.
- *
- * @param reader the reader used to read annotations and build the Swagger definition
- * @param swagger the configured Swagger definition
- */
-
- void afterScan(Reader reader, Swagger swagger);
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/ReflectiveJaxrsScanner.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/ReflectiveJaxrsScanner.java
deleted file mode 100644
index 1a40e121a7..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/ReflectiveJaxrsScanner.java
+++ /dev/null
@@ -1,108 +0,0 @@
-package io.swagger.jaxrs.config;
-
-import io.swagger.annotations.Api;
-import io.swagger.config.FilterFactory;
-import io.swagger.config.Scanner;
-import io.swagger.config.SwaggerConfig;
-import io.swagger.core.filter.SwaggerSpecFilter;
-import io.swagger.models.Swagger;
-import org.reflections.Reflections;
-import org.reflections.scanners.ResourcesScanner;
-import org.reflections.scanners.SubTypesScanner;
-import org.reflections.scanners.TypeAnnotationsScanner;
-import org.reflections.util.ClasspathHelper;
-import org.reflections.util.ConfigurationBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.HashSet;
-import java.util.Set;
-
-public class ReflectiveJaxrsScanner implements SwaggerConfig, Scanner {
- protected boolean prettyPrint = false;
- protected String resourcePackage = "";
- protected Reflections reflections;
- protected Set acceptablePackages;
- protected String filterClass;
- Logger LOGGER = LoggerFactory.getLogger(ReflectiveJaxrsScanner.class);
-
- protected Reflections getReflections() {
- if (reflections == null) {
- ConfigurationBuilder config = new ConfigurationBuilder();
- acceptablePackages = new HashSet();
-
- if (resourcePackage != "") {
- String[] parts = resourcePackage.split(",");
- for (String pkg : parts) {
- if (!"".equals(pkg)) {
- acceptablePackages.add(pkg);
- config.addUrls(ClasspathHelper.forPackage(pkg));
- }
- }
- }
-
- config.setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner());
- this.reflections = new Reflections(config);
- }
- return this.reflections;
- }
-
- public void setReflections(Reflections reflections) {
- this.reflections = reflections;
- }
-
- public String getResourcePackage() {
- return this.resourcePackage;
- }
-
- public void setResourcePackage(String resourcePackage) {
- this.resourcePackage = resourcePackage;
- }
-
- @Override
- public Swagger configure(Swagger swagger) {
- if (filterClass != null) {
- try {
- SwaggerSpecFilter filter = (SwaggerSpecFilter) Class.forName(filterClass).newInstance();
- if (filter != null) {
- FilterFactory.setFilter(filter);
- }
- } catch (Exception e) {
- LOGGER.error("failed to load filter", e);
- }
- }
-
- return swagger;
- }
-
- @Override
- public Set> classes() {
- Set> classes = getReflections().getTypesAnnotatedWith(Api.class);
- Set> output = new HashSet>();
- for (Class> cls : classes) {
- if (acceptablePackages.contains(cls.getPackage().getName())) {
- output.add(cls);
- }
- }
- return output;
- }
-
- @Override
- public String getFilterClass() {
- return filterClass;
- }
-
- public void setFilterClass(String filterClass) {
- this.filterClass = filterClass;
- }
-
- @Override
- public boolean getPrettyPrint() {
- return true;
- }
-
- @Override
- public void setPrettyPrint(boolean shouldPrettyPrint) {
- prettyPrint = shouldPrettyPrint;
- }
-}
\ No newline at end of file
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/SwaggerConfigLocator.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/SwaggerConfigLocator.java
deleted file mode 100644
index 249b0086ed..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/SwaggerConfigLocator.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package io.swagger.jaxrs.config;
-
-import io.swagger.config.SwaggerConfig;
-import io.swagger.models.Swagger;
-
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-public class SwaggerConfigLocator {
-
- private static SwaggerConfigLocator instance;
-
- private ConcurrentMap configMap = new ConcurrentHashMap();
- private ConcurrentMap swaggerMap = new ConcurrentHashMap();
-
- public static SwaggerConfigLocator getInstance() {
- if (instance == null) {
- instance = new SwaggerConfigLocator();
- }
- return instance;
- }
-
- private SwaggerConfigLocator() {
- }
-
- public SwaggerConfig getConfig(String id) {
- SwaggerConfig value = configMap.get(id);
- if (value != null) {
- return value;
- }
- return new SwaggerConfig() {
- @Override
- public Swagger configure(Swagger swagger) {
- return swagger;
- }
-
- @Override
- public String getFilterClass() {
- return null;
- }
- };
- }
-
- public void putConfig(String id, SwaggerConfig config) {
- if (! configMap.containsKey(id)) configMap.put(id, config);
- }
-
- public Swagger getSwagger(String id) {
- Swagger value = swaggerMap.get(id);
- if (value != null) {
- return value;
- }
- return null;
- }
-
- public void putSwagger(String id, Swagger swagger) {
- if (! swaggerMap.containsKey(id)) swaggerMap.put(id, swagger);
- }
-
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/SwaggerContextService.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/SwaggerContextService.java
deleted file mode 100644
index a5c998a7b3..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/SwaggerContextService.java
+++ /dev/null
@@ -1,392 +0,0 @@
-package io.swagger.jaxrs.config;
-
-import io.swagger.config.Scanner;
-import io.swagger.config.ScannerFactory;
-import io.swagger.config.SwaggerConfig;
-import io.swagger.models.Swagger;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.servlet.ServletConfig;
-
-import org.apache.commons.lang3.StringUtils;
-
-public class SwaggerContextService {
-
- private static Logger LOGGER = LoggerFactory.getLogger(SwaggerContextService.class);
-
- public static final String CONFIG_ID_KEY = "swagger.config.id";
- public static final String CONFIG_ID_PREFIX = CONFIG_ID_KEY + ".";
- public static final String CONFIG_ID_DEFAULT = CONFIG_ID_PREFIX + "default";
-
- public static final String SCANNER_ID_KEY = "swagger.scanner.id";
- public static final String SCANNER_ID_PREFIX = SCANNER_ID_KEY + ".";
- public static final String SCANNER_ID_DEFAULT = SCANNER_ID_PREFIX + "default";
-
- public static final String CONTEXT_ID_KEY = "swagger.context.id";
- public static final String USE_PATH_BASED_CONFIG = "swagger.use.path.based.config";
-
- private ServletConfig sc;
- private String configId;
- private SwaggerConfig swaggerConfig;
- private String scannerId;
- private Scanner scanner;
- private String contextId;
- private String basePath;
- private boolean usePathBasedConfig = false;
-
- public boolean isUsePathBasedConfig() {
- return usePathBasedConfig;
- }
-
- public void setUsePathBasedConfig(boolean usePathBasedConfig) {
- this.usePathBasedConfig = usePathBasedConfig;
- }
-
- public void setBasePath(String basePath) {
- this.basePath = normalizeBasePath(basePath);
- }
-
- public String getBasePath() {
- return basePath;
- }
-
- public void setScannerId(String scannerId) {
- this.scannerId = scannerId;
- }
-
- public void setScanner(Scanner scanner) {
- this.scanner = scanner;
- }
-
- public void setConfigId(String configId) {
- this.configId = configId;
- }
-
- public void setSwaggerConfig(SwaggerConfig swaggerConfig) {
- this.swaggerConfig = swaggerConfig;
- }
-
- public void setContextId(String contextId) {
- this.contextId = contextId;
- }
-
- public void setSc(ServletConfig sc) {
- this.sc = sc;
- }
-
- public SwaggerContextService withServletConfig(ServletConfig sc) {
- if (isServletConfigAvailable(sc)) this.sc = sc;
- return this;
- }
-
- public static boolean isServletConfigAvailable (ServletConfig sc) {
- if (sc == null) return false;
- // hack for quick fix for https://github.com/swagger-api/swagger-core/issues/1691
- // in v1.5.7, targeting v1.5.8; overall improved/refactored "swagger context" to be applied in later major versions
- try {
- sc.getInitParameter("test");
- } catch (Exception e) {
- LOGGER.info("Exception caught testing servletConfig. see https://github.com/swagger-api/swagger-core/issues/1691 ", e.getMessage());
- return false;
- }
- return true;
- }
-
- public SwaggerContextService withBasePath(String basePath) {
- this.basePath = normalizeBasePath(basePath);
- return this;
- }
-
- public SwaggerContextService withPathBasedConfig(boolean usePathBasedConfig) {
- this.usePathBasedConfig = usePathBasedConfig;
- return this;
- }
-
- public SwaggerContextService withConfigId(String configId) {
- this.configId = configId;
- return this;
- }
-
- public SwaggerContextService withSwaggerConfig(SwaggerConfig swaggerConfig) {
- this.swaggerConfig = swaggerConfig;
- return this;
- }
-
- public SwaggerContextService withScannerId(String scannerId) {
- this.scannerId = scannerId;
- return this;
- }
-
- public SwaggerContextService withContextId(String contextId) {
- this.contextId = contextId;
- return this;
- }
-
- public SwaggerContextService withScanner(Scanner scanner) {
- this.scanner = scanner;
- return this;
- }
-
- public SwaggerContextService initConfig() {
- return initConfig(null);
- }
-
- public SwaggerContextService initConfig(Swagger swagger) {
-
- String configIdKey;
- if (configId != null) {
- configIdKey = CONFIG_ID_PREFIX + configId;
- } else if (contextId != null) {
- configIdKey = CONFIG_ID_PREFIX + contextId;
- } else {
- if (isServletConfigAvailable(sc)) {
- configIdKey = (sc.getInitParameter(CONFIG_ID_KEY) != null) ? CONFIG_ID_PREFIX + sc.getInitParameter(CONFIG_ID_KEY) : null;
- if (configIdKey == null) {
- boolean usePathBasedConfig = Boolean.valueOf(sc.getInitParameter(USE_PATH_BASED_CONFIG));
- if (usePathBasedConfig && StringUtils.isNotBlank(basePath)) {
- configIdKey = CONFIG_ID_PREFIX + basePath;
- } else {
- configIdKey = (sc.getInitParameter(CONTEXT_ID_KEY) != null) ? CONFIG_ID_PREFIX + sc.getInitParameter(CONTEXT_ID_KEY) : CONFIG_ID_DEFAULT;
- }
- }
- } else {
- if (isUsePathBasedConfig() && StringUtils.isNotBlank(basePath)) {
- configIdKey = CONFIG_ID_PREFIX + basePath;
- } else {
- configIdKey = CONFIG_ID_DEFAULT;
- }
- }
- }
- SwaggerConfig value = (swaggerConfig != null) ? swaggerConfig : null;
- if (value == null && isServletConfigAvailable(sc)) {
- value = new WebXMLReader(sc);
- }
- if (value != null) {
- SwaggerConfigLocator.getInstance().putConfig(configIdKey, value);
- }
- if (swagger != null) {
- SwaggerConfigLocator.getInstance().putSwagger(configIdKey, swagger);
- }
- return this;
-
- }
-
- private Object getConfigOrSwagger(boolean returnSwagger) {
- String configIdKey;
- if (configId != null) {
- configIdKey = CONFIG_ID_PREFIX + configId;
- } else if (contextId != null) {
- configIdKey = CONFIG_ID_PREFIX + contextId;
- } else {
- if (isServletConfigAvailable(sc)) {
- configIdKey = (sc.getInitParameter(CONFIG_ID_KEY) != null) ? CONFIG_ID_PREFIX + sc.getInitParameter(CONFIG_ID_KEY) : null;
- if (configIdKey == null) {
- boolean usePathBasedConfig = Boolean.valueOf(sc.getInitParameter(USE_PATH_BASED_CONFIG));
- if (usePathBasedConfig && StringUtils.isNotBlank(basePath)) {
- configIdKey = CONFIG_ID_PREFIX + basePath;
- } else {
- configIdKey = (sc.getInitParameter(CONTEXT_ID_KEY) != null) ? CONFIG_ID_PREFIX + sc.getInitParameter(CONTEXT_ID_KEY) : CONFIG_ID_DEFAULT;
- }
- }
- } else {
- configIdKey = CONFIG_ID_DEFAULT;
- }
- }
- if (returnSwagger) {
- return SwaggerConfigLocator.getInstance().getSwagger(configIdKey);
- } else {
- return SwaggerConfigLocator.getInstance().getConfig(configIdKey);
- }
- }
-
- public SwaggerConfig getConfig() {
- return (SwaggerConfig)getConfigOrSwagger(false);
- }
-
- public Swagger getSwagger() {
- Swagger value = (Swagger) getConfigOrSwagger(true);
- if (value == null && isServletConfigAvailable(sc)) {
- value = (Swagger) sc.getServletContext().getAttribute("swagger");
- }
- if (value == null) value = new Swagger();
- return value;
- }
-
- public SwaggerContextService updateSwagger(Swagger swagger) {
-
- String configIdKey;
- if (configId != null) {
- configIdKey = CONFIG_ID_PREFIX + configId;
- } else if (contextId != null) {
- configIdKey = CONFIG_ID_PREFIX + contextId;
- } else {
- if (isServletConfigAvailable(sc)) {
- configIdKey = (sc.getInitParameter(CONFIG_ID_KEY) != null) ? CONFIG_ID_PREFIX + sc.getInitParameter(CONFIG_ID_KEY) : null;
- if (configIdKey == null) {
- boolean usePathBasedConfig = Boolean.valueOf(sc.getInitParameter(USE_PATH_BASED_CONFIG));
- if (usePathBasedConfig && StringUtils.isNotBlank(basePath)) {
- configIdKey = CONFIG_ID_PREFIX + basePath;
- } else {
- configIdKey = (sc.getInitParameter(CONTEXT_ID_KEY) != null) ? CONFIG_ID_PREFIX + sc.getInitParameter(CONTEXT_ID_KEY) : CONFIG_ID_DEFAULT;
- }
- }
- } else {
- if (isUsePathBasedConfig() && StringUtils.isNotBlank(basePath)) {
- configIdKey = CONFIG_ID_PREFIX + basePath;
- } else {
- configIdKey = CONFIG_ID_DEFAULT;
- }
- }
- }
- if (swagger != null) {
- SwaggerConfigLocator.getInstance().putSwagger(configIdKey, swagger);
- }
- return this;
-
- }
-
- public SwaggerContextService initScanner() {
- String scannerIdKey;
- if (scannerId != null) {
- scannerIdKey = SCANNER_ID_PREFIX + scannerId;
- } else if (contextId != null) {
- scannerIdKey = SCANNER_ID_PREFIX + contextId;
- } else {
- if (isServletConfigAvailable(sc)) {
- scannerIdKey = (sc.getInitParameter(SCANNER_ID_KEY) != null) ? SCANNER_ID_PREFIX + sc.getInitParameter(SCANNER_ID_KEY) : null;
- if (scannerIdKey == null) {
- boolean usePathBasedConfig = Boolean.valueOf(sc.getInitParameter(USE_PATH_BASED_CONFIG));
- if (usePathBasedConfig && StringUtils.isNotBlank(basePath)) {
- scannerIdKey = SCANNER_ID_PREFIX + basePath;
- } else {
- scannerIdKey = (sc.getInitParameter(CONTEXT_ID_KEY) != null) ? SCANNER_ID_PREFIX + sc.getInitParameter(CONTEXT_ID_KEY) : SCANNER_ID_DEFAULT;
- }
- }
- } else {
- if (isUsePathBasedConfig() && StringUtils.isNotBlank(basePath)) {
- scannerIdKey = SCANNER_ID_PREFIX + basePath;
- } else {
- scannerIdKey = SCANNER_ID_DEFAULT;
- }
- }
- }
- Scanner value = (scanner != null) ? scanner : new DefaultJaxrsScanner();
- ScannerFactory.setScanner(value);
- if (isServletConfigAvailable(sc)) {
- sc.getServletContext().setAttribute(scannerIdKey, value);
- String shouldPrettyPrint = sc.getInitParameter("swagger.pretty.print");
- if (shouldPrettyPrint != null) {
- value.setPrettyPrint(Boolean.parseBoolean(shouldPrettyPrint));
- }
- }
-
- SwaggerScannerLocator.getInstance().putScanner(scannerIdKey, value);
- return this;
- }
-
- public Scanner getScanner() {
- String scannerIdKey;
- Scanner value = null;
- if (scannerId != null) {
- scannerIdKey = SCANNER_ID_PREFIX + scannerId;
- } else if (contextId != null) {
- scannerIdKey = SCANNER_ID_PREFIX + contextId;
- } else {
- if (isServletConfigAvailable(sc)) {
- scannerIdKey = (sc.getInitParameter(SCANNER_ID_KEY) != null) ? SCANNER_ID_PREFIX + sc.getInitParameter(SCANNER_ID_KEY) : null;
- if (scannerIdKey == null) {
- boolean usePathBasedConfig = Boolean.valueOf(sc.getInitParameter(USE_PATH_BASED_CONFIG));
- if (usePathBasedConfig && StringUtils.isNotBlank(basePath)) {
- scannerIdKey = SCANNER_ID_PREFIX + basePath;
- } else {
- scannerIdKey = (sc.getInitParameter(CONTEXT_ID_KEY) != null) ? SCANNER_ID_PREFIX + sc.getInitParameter(CONTEXT_ID_KEY) : SCANNER_ID_DEFAULT;
- }
- }
- value = (Scanner) sc.getServletContext().getAttribute(scannerIdKey);
- } else {
- scannerIdKey = SCANNER_ID_DEFAULT;
- }
- }
- if (value != null) {
- return value;
- }
- value = SwaggerScannerLocator.getInstance().getScanner(scannerIdKey);
- if (value != null) {
- return value;
- }
- return ScannerFactory.getScanner();
- }
-
- public static boolean isUsePathBasedConfigInitParamDefined(ServletConfig sc) {
- if (!isServletConfigAvailable(sc)) return false;
- String key = sc.getInitParameter(USE_PATH_BASED_CONFIG);
- if (key != null){
- return true;
- } else {
- return (sc.getInitParameter(CONTEXT_ID_KEY) != null) ? true : false;
- }
- }
-
- public static boolean isScannerIdInitParamDefined(ServletConfig sc) {
- if (!isServletConfigAvailable(sc)) return false;
- String key = sc.getInitParameter(SCANNER_ID_KEY);
- if (key != null){
- return true;
- } else {
- return (sc.getInitParameter(CONTEXT_ID_KEY) != null);
- }
- }
-
- public static String getScannerIdFromInitParam(ServletConfig sc) {
- if (!isServletConfigAvailable(sc)) return null;
- String key = sc.getInitParameter(SCANNER_ID_KEY);
- if (key != null){
- return key;
- } else {
- return sc.getInitParameter(CONTEXT_ID_KEY);
- }
- }
-
- public static boolean isConfigIdInitParamDefined(ServletConfig sc) {
- if (!isServletConfigAvailable(sc)) return false;
- String key = sc.getInitParameter(CONFIG_ID_KEY);
- if (key != null){
- return true;
- } else {
- return (sc.getInitParameter(CONTEXT_ID_KEY) != null);
- }
- }
-
- public static String getConfigIdFromInitParam(ServletConfig sc) {
- if (!isServletConfigAvailable(sc)) return null;
- String key = sc.getInitParameter(CONFIG_ID_KEY);
- if (key != null){
- return key;
- } else {
- return sc.getInitParameter(CONTEXT_ID_KEY);
- }
- }
-
- /**
- * Normalize base path to the canonical form by adding trailing and leading slashes
- * @param basePath base path to normalize
- * @return normalized base path
- */
- private static String normalizeBasePath(final String basePath) {
- if (basePath == null) {
- return basePath;
- }
-
- String normalizedBasePath = basePath.trim();
- if (!normalizedBasePath.startsWith("/")) {
- normalizedBasePath = "/" + normalizedBasePath;
- }
-
- if (!normalizedBasePath.endsWith("/")) {
- normalizedBasePath = normalizedBasePath + "/";
- }
-
- return normalizedBasePath;
- }
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/SwaggerScannerLocator.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/SwaggerScannerLocator.java
deleted file mode 100644
index fb62a16ef1..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/SwaggerScannerLocator.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package io.swagger.jaxrs.config;
-
-import io.swagger.config.Scanner;
-
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-public class SwaggerScannerLocator {
-
- private static SwaggerScannerLocator instance;
-
- private ConcurrentMap map = new ConcurrentHashMap();
-
- public static SwaggerScannerLocator getInstance() {
- if (instance == null) {
- instance = new SwaggerScannerLocator();
- }
- return instance;
- }
-
- private SwaggerScannerLocator() {
- }
-
- public Scanner getScanner(String id) {
- Scanner value = map.get(id);
- if (value != null) {
- return value;
- }
- return new DefaultJaxrsScanner();
- }
-
- public void putScanner(String id, Scanner scanner) {
- if (!map.containsKey(id)) map.put(id, scanner);
- }
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/WebXMLReader.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/WebXMLReader.java
deleted file mode 100644
index 1efa11c418..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/config/WebXMLReader.java
+++ /dev/null
@@ -1,111 +0,0 @@
-package io.swagger.jaxrs.config;
-
-import io.swagger.config.FilterFactory;
-import io.swagger.config.SwaggerConfig;
-import io.swagger.core.filter.SwaggerSpecFilter;
-import io.swagger.models.Info;
-import io.swagger.models.Scheme;
-import io.swagger.models.Swagger;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.servlet.ServletConfig;
-import java.util.ArrayList;
-import java.util.List;
-
-public class WebXMLReader implements SwaggerConfig {
- private static final Logger LOGGER = LoggerFactory.getLogger(WebXMLReader.class);
-
- protected String basePath;
- protected String host;
- protected String filterClass;
- protected String apiVersion;
- protected String title;
- protected String[] schemes = new String[]{};
-
- public WebXMLReader(ServletConfig servletConfig) {
- apiVersion = servletConfig.getInitParameter("api.version");
- if (apiVersion == null) {
- apiVersion = "Swagger Server";
- }
-
- // we support full base path (i.e full URL to the server) or just base path
- this.host = servletConfig.getInitParameter("swagger.api.host");
- String schemesString = servletConfig.getInitParameter("swagger.api.schemes");
-
- // split the CSV string and update the `schemes` variable
- if(schemesString != null) {
- String[] parts = schemesString.split(",");
- List schemes = new ArrayList();
- for(String scheme : parts) {
- String s = scheme.trim();
- if(!s.isEmpty()) {
- schemes.add(s);
- }
- }
- this.schemes = schemes.toArray(new String[schemes.size()]);
- }
- this.title = servletConfig.getInitParameter("swagger.api.title");
-
- if (title == null) {
- title = "";
- }
-
- this.basePath = servletConfig.getInitParameter("swagger.api.basepath");
- if (basePath != null) {
- String[] parts = basePath.split("://");
- if (parts.length > 1) {
- int pos = parts[1].indexOf("/");
- if (pos >= 0) {
- this.schemes = new String[]{parts[0]};
- basePath = parts[1].substring(pos);
- host = parts[1].substring(0, pos);
- } else {
- this.schemes = new String[]{parts[0]};
- basePath = null;
- host = parts[1];
- }
- }
- else {
- // it is a proper basePath, nothing to do
- }
- }
-
- filterClass = servletConfig.getInitParameter("swagger.filter");
- if (filterClass != null) {
- try {
- SwaggerSpecFilter filter = (SwaggerSpecFilter) Class.forName(filterClass).newInstance();
- if (filter != null) {
- FilterFactory.setFilter(filter);
- }
- } catch (Exception e) {
- LOGGER.error("failed to load filter", e);
- }
- }
- }
-
- @Override
- public String getFilterClass() {
- return filterClass;
- }
-
- @Override
- public Swagger configure(Swagger swagger) {
- if (swagger != null) {
- Info info = swagger.getInfo();
- if (info == null) {
- swagger.info(new Info());
- }
-
- swagger.basePath(basePath)
- .host(host)
- .getInfo()
- .title(title)
- .version(apiVersion);
- for(String scheme : this.schemes) {
- swagger.scheme(Scheme.forValue(scheme));
- }
- }
- return swagger;
- }
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/ext/AbstractSwaggerExtension.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/ext/AbstractSwaggerExtension.java
deleted file mode 100644
index 41374cdc27..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/ext/AbstractSwaggerExtension.java
+++ /dev/null
@@ -1,64 +0,0 @@
-package io.swagger.jaxrs.ext;
-
-import com.fasterxml.jackson.databind.JavaType;
-import com.fasterxml.jackson.databind.type.TypeFactory;
-
-import io.swagger.annotations.ApiOperation;
-import io.swagger.models.Operation;
-import io.swagger.models.parameters.Parameter;
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-import java.lang.reflect.Type;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-public abstract class AbstractSwaggerExtension implements SwaggerExtension {
-
- @Override
- public String extractOperationMethod(ApiOperation apiOperation, Method method, Iterator chain) {
- if (chain.hasNext()) {
- return chain.next().extractOperationMethod(apiOperation, method, chain);
- } else {
- return null;
- }
- }
-
- @Override
- public List extractParameters(List annotations, Type type, Set typesToSkip,
- Iterator chain) {
- if (chain.hasNext()) {
- return chain.next().extractParameters(annotations, type, typesToSkip, chain);
- } else {
- return Collections.emptyList();
- }
- }
-
- @Override
- public void decorateOperation(Operation operation, Method method, Iterator chain) {
- if (chain.hasNext()) {
- chain.next().decorateOperation(operation, method, chain);
- }
- }
-
- protected boolean shouldIgnoreClass(Class> cls) {
- return false;
- }
-
- protected boolean shouldIgnoreType(Type type, Set typesToSkip) {
- if (typesToSkip.contains(type)) {
- return true;
- }
- if (shouldIgnoreClass(constructType(type).getRawClass())) {
- typesToSkip.add(type);
- return true;
- }
- return false;
- }
-
- protected JavaType constructType(Type type) {
- return TypeFactory.defaultInstance().constructType(type);
- }
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/ext/SwaggerExtension.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/ext/SwaggerExtension.java
deleted file mode 100644
index b8cf2b96bb..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/ext/SwaggerExtension.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package io.swagger.jaxrs.ext;
-
-import io.swagger.annotations.ApiOperation;
-import io.swagger.models.Operation;
-import io.swagger.models.parameters.Parameter;
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-import java.lang.reflect.Type;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-public interface SwaggerExtension {
-
- String extractOperationMethod(ApiOperation apiOperation, Method method, Iterator chain);
-
- List extractParameters(List annotations, Type type, Set typesToSkip, Iterator chain);
-
- /**
- * Decorates operation with additional vendor based extensions.
- *
- * @param operation the operation, build from swagger definition
- * @param method the method for additional scan
- * @param chain the chain with swagger extensions to process
- */
- void decorateOperation(Operation operation, Method method, Iterator chain);
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/ext/SwaggerExtensions.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/ext/SwaggerExtensions.java
deleted file mode 100644
index 3e4eccbd36..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/ext/SwaggerExtensions.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package io.swagger.jaxrs.ext;
-
-import io.swagger.jaxrs.DefaultParameterExtension;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.ServiceLoader;
-
-public class SwaggerExtensions {
- private static Logger LOGGER = LoggerFactory.getLogger(SwaggerExtensions.class);
-
- private static List extensions = null;
-
- public static List getExtensions() {
- return extensions;
- }
-
- public static void setExtensions(List ext) {
- extensions = ext;
- }
-
- public static Iterator chain() {
- return extensions.iterator();
- }
-
- static {
- extensions = new ArrayList();
- ServiceLoader loader = ServiceLoader.load(SwaggerExtension.class);
- for (SwaggerExtension ext : loader) {
- LOGGER.debug("adding extension " + ext);
- extensions.add(ext);
- }
- extensions.add(new DefaultParameterExtension());
- }
-}
\ No newline at end of file
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/listing/AcceptHeaderApiListingResource.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/listing/AcceptHeaderApiListingResource.java
deleted file mode 100644
index 951b49c96e..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/listing/AcceptHeaderApiListingResource.java
+++ /dev/null
@@ -1,43 +0,0 @@
-package io.swagger.jaxrs.listing;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import io.swagger.annotations.ApiOperation;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.*;
-
-/**
- * Created by rbolles on 2/15/16.
- */
-@Path("/swagger")
-public class AcceptHeaderApiListingResource extends BaseApiListingResource {
-
- @Context
- ServletContext context;
-
- @GET
- @Produces({MediaType.APPLICATION_JSON})
- @ApiOperation(value = "The swagger definition in JSON", hidden = true)
- public Response getListingJson(
- @Context Application app,
- @Context ServletConfig sc,
- @Context HttpHeaders headers,
- @Context UriInfo uriInfo) throws JsonProcessingException {
- return getListingJsonResponse(app, context, sc, headers, uriInfo);
- }
-
- @GET
- @Produces("application/yaml")
- @ApiOperation(value = "The swagger definition in YAML", hidden = true)
- public Response getListingYaml(
- @Context Application app,
- @Context ServletConfig sc,
- @Context HttpHeaders headers,
- @Context UriInfo uriInfo) {
- return getListingYamlResponse(app, context, sc, headers, uriInfo);
- }
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/listing/ApiListingResource.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/listing/ApiListingResource.java
deleted file mode 100644
index 96d01264a3..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/listing/ApiListingResource.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package io.swagger.jaxrs.listing;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import io.swagger.annotations.ApiOperation;
-import org.apache.commons.lang3.StringUtils;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.*;
-
-@Path("/swagger.{type:json|yaml}")
-public class ApiListingResource extends BaseApiListingResource {
-
- @Context
- ServletContext context;
-
- @GET
- @Produces({MediaType.APPLICATION_JSON, "application/yaml"})
- @ApiOperation(value = "The swagger definition in either JSON or YAML", hidden = true)
- public Response getListing(
- @Context Application app,
- @Context ServletConfig sc,
- @Context HttpHeaders headers,
- @Context UriInfo uriInfo,
- @PathParam("type") String type) throws JsonProcessingException {
- if (StringUtils.isNotBlank(type) && type.trim().equalsIgnoreCase("yaml")) {
- return getListingYamlResponse(app, context, sc, headers, uriInfo);
- } else {
- return getListingJsonResponse(app, context, sc, headers, uriInfo);
- }
- }
-
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/listing/BaseApiListingResource.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/listing/BaseApiListingResource.java
deleted file mode 100644
index 9b57aae508..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/listing/BaseApiListingResource.java
+++ /dev/null
@@ -1,217 +0,0 @@
-package io.swagger.jaxrs.listing;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import io.swagger.config.FilterFactory;
-import io.swagger.config.Scanner;
-import io.swagger.config.SwaggerConfig;
-import io.swagger.core.filter.SpecFilter;
-import io.swagger.core.filter.SwaggerSpecFilter;
-import io.swagger.jaxrs.Reader;
-import io.swagger.jaxrs.config.JaxrsScanner;
-import io.swagger.jaxrs.config.ReaderConfigUtils;
-import io.swagger.jaxrs.config.SwaggerContextService;
-import io.swagger.models.Swagger;
-import io.swagger.util.Json;
-import io.swagger.util.Yaml;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-import javax.ws.rs.core.*;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-/**
- * Created by rbolles on 2/15/16.
- */
-public abstract class BaseApiListingResource {
-
- private static volatile boolean initialized = false;
-
- private static volatile ConcurrentMap initializedScanner = new ConcurrentHashMap();
- private static volatile ConcurrentMap initializedConfig = new ConcurrentHashMap();
-
- private static Logger LOGGER = LoggerFactory.getLogger(BaseApiListingResource.class);
-
-
- private static synchronized Swagger scan(Application app, ServletContext context, ServletConfig sc, UriInfo uriInfo) {
- Swagger swagger = null;
-
- SwaggerContextService ctxService = new SwaggerContextService()
- .withServletConfig(sc)
- .withBasePath(getBasePath(uriInfo));
-
- Scanner scanner = ctxService.getScanner();
- if (scanner != null) {
- SwaggerSerializers.setPrettyPrint(scanner.getPrettyPrint());
- swagger = new SwaggerContextService()
- .withServletConfig(sc)
- .withBasePath(getBasePath(uriInfo))
- .getSwagger();
- Set> classes;
- if (scanner instanceof JaxrsScanner) {
- JaxrsScanner jaxrsScanner = (JaxrsScanner) scanner;
- classes = jaxrsScanner.classesFromContext(app, sc);
- } else {
- classes = scanner.classes();
- }
- if (classes != null) {
- Reader reader = new Reader(swagger, ReaderConfigUtils.getReaderConfig(context));
- swagger = reader.read(classes);
- if (scanner instanceof SwaggerConfig) {
- swagger = ((SwaggerConfig) scanner).configure(swagger);
- } else {
- SwaggerConfig swaggerConfig = ctxService.getConfig();
- if (swaggerConfig != null) {
- LOGGER.debug("configuring swagger with " + swaggerConfig);
- swaggerConfig.configure(swagger);
- } else {
- LOGGER.debug("no configurator");
- }
- }
- new SwaggerContextService()
- .withServletConfig(sc)
- .withBasePath(getBasePath(uriInfo))
- .updateSwagger(swagger);
- }
- }
- if (SwaggerContextService.isScannerIdInitParamDefined(sc)) {
- initializedScanner.put(sc.getServletName() + "_" + SwaggerContextService.getScannerIdFromInitParam(sc), true);
- } else if (SwaggerContextService.isConfigIdInitParamDefined(sc)) {
- initializedConfig.put(sc.getServletName() + "_" + SwaggerContextService.getConfigIdFromInitParam(sc), true);
- } else if (SwaggerContextService.isUsePathBasedConfigInitParamDefined(sc)) {
- initializedConfig.put(sc.getServletName() + "_" + ctxService.getBasePath(), true);
- } else {
- initialized = true;
- }
-
- return swagger;
- }
-
- protected Swagger process(
- Application app,
- ServletContext servletContext,
- ServletConfig sc,
- HttpHeaders headers,
- UriInfo uriInfo) {
- SwaggerContextService ctxService = new SwaggerContextService()
- .withServletConfig(sc)
- .withBasePath(getBasePath(uriInfo));
-
- Swagger swagger = ctxService.getSwagger();
- synchronized (ApiListingResource.class) {
- if (SwaggerContextService.isScannerIdInitParamDefined(sc)) {
- if (!initializedScanner.containsKey(sc.getServletName() + "_" + SwaggerContextService.getScannerIdFromInitParam(sc))) {
- swagger = scan(app, servletContext, sc, uriInfo);
- }
- } else {
- if (SwaggerContextService.isConfigIdInitParamDefined(sc)) {
- if (!initializedConfig.containsKey(sc.getServletName() + "_" + SwaggerContextService.getConfigIdFromInitParam(sc))) {
- swagger = scan(app, servletContext, sc, uriInfo);
- }
- } else if (SwaggerContextService.isUsePathBasedConfigInitParamDefined(sc)) {
- if (!initializedConfig.containsKey(sc.getServletName() + "_" + ctxService.getBasePath())) {
- swagger = scan(app, servletContext, sc, uriInfo);
- }
- } else if (!initialized) {
- swagger = scan(app, servletContext, sc, uriInfo);
- }
- }
- }
- if (swagger != null) {
- SwaggerSpecFilter filterImpl = FilterFactory.getFilter();
- if (filterImpl != null) {
- SpecFilter f = new SpecFilter();
- swagger = f.filter(swagger, filterImpl, getQueryParams(uriInfo.getQueryParameters()), getCookies(headers),
- getHeaders(headers));
- }
- }
- return swagger;
- }
-
- protected Response getListingYamlResponse(
- Application app,
- ServletContext servletContext,
- ServletConfig servletConfig,
- HttpHeaders headers,
- UriInfo uriInfo) {
- Swagger swagger = process(app, servletContext, servletConfig, headers, uriInfo);
- try {
- if (swagger != null) {
- String yaml = Yaml.mapper().writeValueAsString(swagger);
- StringBuilder b = new StringBuilder();
- String[] parts = yaml.split("\n");
- for (String part : parts) {
- b.append(part);
- b.append("\n");
- }
- return Response.ok().entity(b.toString()).type("application/yaml").build();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return Response.status(404).build();
- }
-
- protected Response getListingJsonResponse(
- Application app,
- ServletContext servletContext,
- ServletConfig servletConfig,
- HttpHeaders headers,
- UriInfo uriInfo) throws JsonProcessingException {
- Swagger swagger = process(app, servletContext, servletConfig, headers, uriInfo);
-
- if (swagger != null) {
- return Response.ok().entity(Json.mapper().writeValueAsString(swagger)).type(MediaType.APPLICATION_JSON_TYPE).build();
- } else {
- return Response.status(404).build();
- }
- }
-
- private static Map> getQueryParams(MultivaluedMap params) {
- Map> output = new HashMap>();
- if (params != null) {
- for (String key : params.keySet()) {
- List values = params.get(key);
- output.put(key, values);
- }
- }
- return output;
- }
-
- private static Map getCookies(HttpHeaders headers) {
- Map output = new HashMap();
- if (headers != null) {
- for (String key : headers.getCookies().keySet()) {
- Cookie cookie = headers.getCookies().get(key);
- output.put(key, cookie.getValue());
- }
- }
- return output;
- }
-
- private static Map> getHeaders(HttpHeaders headers) {
- Map> output = new HashMap>();
- if (headers != null) {
- for (String key : headers.getRequestHeaders().keySet()) {
- List values = headers.getRequestHeaders().get(key);
- output.put(key, values);
- }
- }
- return output;
- }
-
- private static String getBasePath(UriInfo uriInfo) {
- if (uriInfo != null) {
- return uriInfo.getBaseUri().getPath();
- } else {
- return "/";
- }
- }
-
-}
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/listing/SwaggerSerializers.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/listing/SwaggerSerializers.java
deleted file mode 100644
index 84aff573e5..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/listing/SwaggerSerializers.java
+++ /dev/null
@@ -1,73 +0,0 @@
-package io.swagger.jaxrs.listing;
-
-import io.swagger.models.Swagger;
-import io.swagger.util.Json;
-import io.swagger.util.Yaml;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.ext.MessageBodyWriter;
-import javax.ws.rs.ext.Provider;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Type;
-
-@Provider
-@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "application/yaml"})
-public class SwaggerSerializers implements MessageBodyWriter {
- static boolean prettyPrint = false;
- Logger LOGGER = LoggerFactory.getLogger(SwaggerSerializers.class);
-
- public static void setPrettyPrint(boolean shouldPrettyPrint) {
- SwaggerSerializers.prettyPrint = shouldPrettyPrint;
- }
-
- @Override
- public boolean isWriteable(Class type, Type genericType, Annotation[] annotations,
- MediaType mediaType) {
- return Swagger.class.isAssignableFrom(type);
- }
-
- @Override
- public long getSize(Swagger data, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
- return -1;
- }
-
- @Override
- public void writeTo(Swagger data,
- Class> type,
- Type genericType,
- Annotation[] annotations,
- MediaType mediaType,
- MultivaluedMap headers,
- OutputStream out) throws IOException {
- if (mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE)) {
- if (prettyPrint) {
- out.write(Json.pretty().writeValueAsBytes(data));
- } else {
- out.write(Json.mapper().writeValueAsBytes(data));
- }
- } else if (mediaType.toString().startsWith("application/yaml")) {
- headers.remove("Content-Type");
- headers.add("Content-Type", "application/yaml");
- if (prettyPrint) {
- out.write(Yaml.pretty().writeValueAsBytes(data));
- } else {
- out.write(Yaml.mapper().writeValueAsBytes(data));
- }
- } else if (mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE)) {
- headers.remove("Content-Type");
- headers.add("Content-Type", "application/json");
- if (prettyPrint) {
- out.write(Json.pretty().writeValueAsBytes(data));
- } else {
- out.write(Json.mapper().writeValueAsBytes(data));
- }
- }
- }
-}
-
diff --git a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/utils/ReaderUtils.java b/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/utils/ReaderUtils.java
deleted file mode 100644
index 213d963ff1..0000000000
--- a/modules/swagger-jaxrs/src/main/java/io/swagger/jaxrs/utils/ReaderUtils.java
+++ /dev/null
@@ -1,136 +0,0 @@
-package io.swagger.jaxrs.utils;
-
-import io.swagger.jaxrs.ext.SwaggerExtension;
-import io.swagger.jaxrs.ext.SwaggerExtensions;
-import io.swagger.models.Swagger;
-import io.swagger.models.parameters.Parameter;
-import io.swagger.util.ParameterProcessor;
-import io.swagger.util.ReflectionUtils;
-
-import com.google.common.base.Splitter;
-import com.google.common.collect.Iterables;
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-
-import javax.ws.rs.core.Context;
-
-public class ReaderUtils {
-
- /**
- * Collects constructor-level parameters from class.
- *
- * @param cls is a class for collecting
- * @param swagger is the instance of the Swagger
- * @return the collection of supported parameters
- */
- public static List collectConstructorParameters(Class> cls, Swagger swagger) {
- if (cls.isLocalClass() || (cls.isMemberClass() && !Modifier.isStatic(cls.getModifiers()))) {
- return Collections.emptyList();
- }
-
- List selected = Collections.emptyList();
- int maxParamsCount = 0;
-
- for (Constructor> constructor : cls.getDeclaredConstructors()) {
- if (!ReflectionUtils.isConstructorCompatible(constructor)
- && !ReflectionUtils.isInject(Arrays.asList(constructor.getDeclaredAnnotations()))) {
- continue;
- }
-
- final Type[] genericParameterTypes = constructor.getGenericParameterTypes();
- final Annotation[][] annotations = constructor.getParameterAnnotations();
-
- int paramsCount = 0;
- final List parameters = new ArrayList();
- for (int i = 0; i < genericParameterTypes.length; i++) {
- final List tmpAnnotations = Arrays.asList(annotations[i]);
- if (isContext(tmpAnnotations)) {
- paramsCount++;
- } else {
- final Type genericParameterType = genericParameterTypes[i];
- final List tmpParameters = collectParameters(genericParameterType, tmpAnnotations);
- if (tmpParameters.size() >= 1) {
- for (Parameter tmpParameter : tmpParameters) {
- if (ParameterProcessor.applyAnnotations(swagger, tmpParameter, genericParameterType, tmpAnnotations) != null) {
- parameters.add(tmpParameter);
- }
- }
- paramsCount++;
- }
- }
- }
-
- if (paramsCount >= maxParamsCount) {
- maxParamsCount = paramsCount;
- selected = parameters;
- }
- }
-
- return selected;
- }
-
- /**
- * Collects field-level parameters from class.
- *
- * @param cls is a class for collecting
- * @param swagger is the instance of the Swagger
- * @return the collection of supported parameters
- */
- public static List collectFieldParameters(Class> cls, Swagger swagger) {
- final List parameters = new ArrayList();
- for (Field field : ReflectionUtils.getDeclaredFields(cls)) {
- final List annotations = Arrays.asList(field.getAnnotations());
- final Type genericType = field.getGenericType();
- for (Parameter parameter : collectParameters(genericType, annotations)) {
- if (ParameterProcessor.applyAnnotations(swagger, parameter, genericType, annotations) != null) {
- parameters.add(parameter);
- }
- }
- }
- return parameters;
- }
-
- /**
- * Splits the provided array of strings into an array, using comma as the separator.
- * Also removes leading and trailing whitespace and omits empty strings from the results.
- *
- * @param strings is the provided array of strings
- * @return the resulted array of strings
- */
- public static String[] splitContentValues(String[] strings) {
- final Set result = new LinkedHashSet();
-
- for (String string : strings) {
- Iterables.addAll(result, Splitter.on(",").trimResults().omitEmptyStrings().split(string));
- }
-
- return result.toArray(new String[result.size()]);
- }
-
- private static List collectParameters(Type type, List annotations) {
- final Iterator chain = SwaggerExtensions.chain();
- return chain.hasNext() ? chain.next().extractParameters(annotations, type, new HashSet(), chain) :
- Collections.emptyList();
- }
-
- private static boolean isContext(List annotations) {
- for (Annotation annotation : annotations) {
- if (annotation instanceof Context) {
- return true;
- }
- }
- return false;
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/com/my/project/resources/ResourceInPackageA.java b/modules/swagger-jaxrs/src/test/java/com/my/project/resources/ResourceInPackageA.java
deleted file mode 100644
index 3c9c1c4fa2..0000000000
--- a/modules/swagger-jaxrs/src/test/java/com/my/project/resources/ResourceInPackageA.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.my.project.resources;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import java.util.ArrayList;
-
-@Api("/packageA")
-@Path("/packageA")
-public class ResourceInPackageA {
- @ApiOperation(value = "test.")
- @GET
- public void getTest(@ApiParam(value = "test") ArrayList tenantId) {
- return;
- }
-}
\ No newline at end of file
diff --git a/modules/swagger-jaxrs/src/test/java/com/splitresourcesTest/SplitResource.java b/modules/swagger-jaxrs/src/test/java/com/splitresourcesTest/SplitResource.java
deleted file mode 100644
index 5e8c03ea80..0000000000
--- a/modules/swagger-jaxrs/src/test/java/com/splitresourcesTest/SplitResource.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.splitresourcesTest;
-
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.core.Response;
-
-/**
- * Created by KangoV on 2016-05-22
- * #1800
- */
-@Path("/api/1.0")
-public interface SplitResource {
-
- @GET
- public Response getChildren();
-
-}
\ No newline at end of file
diff --git a/modules/swagger-jaxrs/src/test/java/com/splitresourcesTestImpl/SplitResourceImpl.java b/modules/swagger-jaxrs/src/test/java/com/splitresourcesTestImpl/SplitResourceImpl.java
deleted file mode 100644
index 5b4dcb088b..0000000000
--- a/modules/swagger-jaxrs/src/test/java/com/splitresourcesTestImpl/SplitResourceImpl.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package com.splitresourcesTestImpl;
-
-import javax.ws.rs.core.Response;
-
-import com.splitresourcesTest.SplitResource;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
-/**
- * Created by KangoV on 2016-05-22
- * #1800
- */
-@Api(tags = "children")
-public class SplitResourceImpl implements SplitResource {
-
- @ApiOperation(value = "Get Child by id")
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Success") })
- public Response getChildren() {
- return Response.ok().entity("Hello World").build();
- }
-
-}
diff --git a/modules/swagger-jaxrs/src/test/java/com/subresourcesTest/ChildResource.java b/modules/swagger-jaxrs/src/test/java/com/subresourcesTest/ChildResource.java
deleted file mode 100644
index 1d9c77d50a..0000000000
--- a/modules/swagger-jaxrs/src/test/java/com/subresourcesTest/ChildResource.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.subresourcesTest;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
-import javax.ws.rs.GET;
-import javax.ws.rs.core.Response;
-
-/**
- * Created by rbolles on 1/20/16.
- */
-@Api(tags = "children", description = "operations about children")
-public class ChildResource {
-
- @GET
- @ApiOperation(value = "Get Child by id")
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "Success")
- })
- public Response getChildren(
- ) {
- return Response.ok().entity("Hello World").build();
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/com/subresourcesTest/RootResource.java b/modules/swagger-jaxrs/src/test/java/com/subresourcesTest/RootResource.java
deleted file mode 100644
index f5b0f24892..0000000000
--- a/modules/swagger-jaxrs/src/test/java/com/subresourcesTest/RootResource.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.subresourcesTest;
-
-import io.swagger.annotations.Api;
-
-import javax.ws.rs.Path;
-
-/**
- * Created by rbolles on 1/20/16.
- */
-
-@Api(tags = "root")
-@Path("/api/1.0")
-public class RootResource {
-
- @Path("/children")
- public ChildResource getChildResource() {
- return new ChildResource();
- }
-
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/ApiListingResourceTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/ApiListingResourceTest.java
deleted file mode 100644
index 9b4f8299df..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/ApiListingResourceTest.java
+++ /dev/null
@@ -1,78 +0,0 @@
-package io.swagger;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import io.swagger.jaxrs.Reader;
-import io.swagger.jaxrs.listing.ApiListingResource;
-import io.swagger.models.Swagger;
-import org.testng.annotations.Test;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-import java.util.Enumeration;
-
-import static org.testng.Assert.assertNull;
-
-/**
- * The {@code ApiListingResourceTest} test should confirm that scanning of
- * the {@link ApiListingResource} class doesn't affect Swagger output.
- */
-public class ApiListingResourceTest {
- private final Swagger swagger = new Reader(new Swagger()).read(ApiListingResource.class);
-
- @Test
- public void shouldCheckModelsSet() {
- assertNull(swagger.getDefinitions());
- }
-
- @Test
- public void shouldHandleNullServletConfig_issue1689() throws JsonProcessingException {
- ApiListingResource a = new ApiListingResource();
- try {
- a.getListing(null, null, null, null, "json");
- } catch (RuntimeException e) {
- // test will fail before, no need to mock Response
- if(e.getCause() instanceof ClassNotFoundException) {
- return;
- }
- throw e;
- }
-
- }
- @Test
- public void shouldHandleErrorServletConfig_issue1691() throws JsonProcessingException {
-
- ServletConfig sc = new ServletConfig() {
- @Override
- public String getServletName() {
- throw new RuntimeException("test_1691");
- }
-
- @Override
- public ServletContext getServletContext() {
- throw new RuntimeException("test_1691");
- }
-
- @Override
- public String getInitParameter(String name) {
- throw new RuntimeException("test_1691");
- }
-
- @Override
- public Enumeration getInitParameterNames() {
- throw new RuntimeException("test_1691");
- }
- };
-
- ApiListingResource a = new ApiListingResource();
- try {
- a.getListing(null, sc, null, null, "json");
- } catch (RuntimeException e) {
- // test will fail before, no need to mock Response
- if(e.getCause() instanceof ClassNotFoundException) {
- return;
- }
- throw e;
- }
-
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/BeanConfigTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/BeanConfigTest.java
deleted file mode 100644
index 5ba7fcba4a..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/BeanConfigTest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-package io.swagger;
-
-import com.splitresourcesTestImpl.SplitResourceImpl;
-import com.subresourcesTest.RootResource;
-import io.swagger.jaxrs.config.BeanConfig;
-import io.swagger.models.Scheme;
-import io.swagger.models.Swagger;
-import org.testng.annotations.Test;
-
-import java.util.Arrays;
-import java.util.EnumSet;
-import java.util.HashSet;
-import java.util.Set;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
-
-public class BeanConfigTest {
-
- private final Set> expectedKeys = new HashSet(Arrays.asList("/packageA", "/packageB"));
- private final Set expectedSchemas = EnumSet.of(Scheme.HTTP, Scheme.HTTPS);
-
- private BeanConfig createBeanConfig(String rp) {
- BeanConfig bc = new BeanConfig();
- bc.setResourcePackage(rp);
- bc.setSchemes(new String[]{"http", "https"});
- bc.setHost("petstore.swagger.io");
- bc.setBasePath("/api");
- bc.setTitle("Petstore Sample API");
- bc.setDescription("A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification");
- bc.setTermsOfServiceUrl("http://swagger.io/terms/");
- bc.setContact("Swagger API Team");
- bc.setLicense("MIT");
- bc.setLicenseUrl("http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT");
- bc.setScan(true);
- return bc;
- }
-
- @Test(description = "scan a simple resource")
- public void shouldScanASimpleResource() {
- Swagger swagger = createBeanConfig("com.my.project.resources,org.my.project.resources").getSwagger();
- assertNotNull(swagger);
- assertEquals(swagger.getPaths().keySet(), expectedKeys);
- assertEquals(swagger.getSchemes(), expectedSchemas);
- }
-
- @Test(description = "deep scan packages per #1011")
- public void shouldDeepScanPakagesPer1011() {
- Swagger swagger = createBeanConfig("com.my,org.my").getSwagger();
- assertNotNull(swagger);
- assertEquals(swagger.getPaths().keySet(), expectedKeys);
- assertEquals(swagger.getSchemes(), expectedSchemas);
- }
-
- @Test
- public void testBeanConfigOnlyScansResourcesAnnoatedWithPaths() throws Exception {
- BeanConfig bc = new BeanConfig();
- bc.setResourcePackage("com.subresourcesTest");
-
- Set> classes = bc.classes();
-
- assertEquals(classes.size(), 1, "BeanConfig should only pick up the root resource because it has a @Path annotation at the class level");
- assertTrue(classes.contains(RootResource.class));
- }
-
- @Test
- public void testBeanConfigScansSplitResourcesAnnoatedWithPathAndApi() throws Exception {
- BeanConfig bc = new BeanConfig();
- bc.setResourcePackage("com.splitresourcesTestImpl");
-
- Set> classes = bc.classes();
-
- assertEquals(classes.size(), 1, "BeanConfig should pick up implementations annotated with @Api that have a superinterface with @Path");
- assertTrue(classes.contains(SplitResourceImpl.class));
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/ChildTypeTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/ChildTypeTest.java
deleted file mode 100644
index 1d1ccc9218..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/ChildTypeTest.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package io.swagger;
-
-import io.swagger.jaxrs.Reader;
-import io.swagger.models.Model;
-import io.swagger.models.Operation;
-import io.swagger.models.RefModel;
-import io.swagger.models.Swagger;
-import io.swagger.models.parameters.BodyParameter;
-import io.swagger.models.properties.Property;
-import io.swagger.models.properties.RefProperty;
-import io.swagger.resources.ResourceWithChildType;
-import org.testng.annotations.Test;
-
-import static org.testng.Assert.assertEquals;
-
-/**
- * This class test that refs are setup correctly when a child type is referenced.
- */
-public class ChildTypeTest {
- private final Swagger swagger = new Reader(new Swagger()).read(ResourceWithChildType.class);
-
- private BodyParameter getBodyParameter(Operation op, int index) {
- return (BodyParameter) op.getParameters().get(index);
- }
-
- @Test(description = "Tests child type response schema ref is correctly set up")
- public void testChildTypeResponse() {
- Operation op = swagger.getPath("/childType/testChildTypeResponse").getGet();
- Property schema = op.getResponses().get("200").getSchema();
- assertEquals(schema.getClass().getName(), RefProperty.class.getName());
- assertEquals(((RefProperty) schema).getSimpleRef(), "Sub1Bean");
- }
-
- @Test(description = "Tests child type response schema ref is correctly set up when specified on the operation")
- public void testChildTypeResponseOnOperation() {
- Operation op = swagger.getPath("/childType/testChildTypeResponseOnOperation").getGet();
- Property schema = op.getResponses().get("200").getSchema();
- assertEquals(schema.getClass().getName(), RefProperty.class.getName());
- assertEquals(((RefProperty) schema).getSimpleRef(), "Sub1Bean");
- }
-
- @Test(description = "Tests schema ref is correctly set up for child type parameter")
- public void testChildTypeParameter() {
- Operation op = swagger.getPath("/childType/testChildTypeParameter").getPost();
- BodyParameter parameter = getBodyParameter(op, 0);
- Model schema = parameter.getSchema();
- assertEquals(schema.getClass().getName(), RefModel.class.getName());
- assertEquals(((RefModel) schema).getSimpleRef(), "Sub1Bean");
- }
-
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/CollectionFormatTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/CollectionFormatTest.java
deleted file mode 100644
index b6f1abb897..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/CollectionFormatTest.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package io.swagger;
-
-import io.swagger.jaxrs.Reader;
-import io.swagger.models.Operation;
-import io.swagger.models.Swagger;
-import io.swagger.models.parameters.AbstractSerializableParameter;
-import io.swagger.resources.CollectionFormatResource;
-import org.testng.annotations.Test;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNull;
-
-public class CollectionFormatTest {
- private static final String MULTI = "multi";
- private static final String CSV = "csv";
- private final Swagger swagger = new Reader(new Swagger()).read(CollectionFormatResource.class);
-
- @Test(testName = "check collection format for QueryParam")
- public void readQueryParamTest() {
- Operation operation = getOperation("testQueryParam");
- assertEquals(getCollectionFormat(operation, 0), MULTI);
- assertNull(getCollectionFormat(operation, 1));
- assertEquals(getCollectionFormat(operation, 2), MULTI);
- }
-
- @Test(testName = "check collection format for FormParam")
- public void readFormParamTest() {
- Operation operation = getOperation("testFormParam");
- assertEquals(getCollectionFormat(operation, 0), MULTI);
- assertNull(getCollectionFormat(operation, 1));
- assertEquals(getCollectionFormat(operation, 2), MULTI);
- }
-
- @Test(testName = "check collection format for PathParam")
- public void readPathParamTest() {
- Operation operation = getOperation("testPathParam");
- assertEquals(getCollectionFormat(operation, 0), CSV);
- assertNull(getCollectionFormat(operation, 1));
- assertEquals(getCollectionFormat(operation, 2), CSV);
- }
-
- @Test(testName = "check collection format for HeaderParam")
- public void readHeaderParamTest() {
- Operation operation = getOperation("testHeaderParam");
- assertEquals(getCollectionFormat(operation, 0), CSV);
- assertNull(getCollectionFormat(operation, 1));
- assertEquals(getCollectionFormat(operation, 2), CSV);
- }
-
- @Test(testName = "check collection format for CookieParam")
- public void readCookieParamTest() {
- Operation operation = getOperation("testCookieParam");
- assertEquals(getCollectionFormat(operation, 0), CSV);
- assertNull(getCollectionFormat(operation, 1));
- assertEquals(getCollectionFormat(operation, 2), CSV);
- }
-
- @Test(testName = "check collection format for Mixed Param")
- public void readMixedParamTest() {
- Operation operation = getOperation("testMixedParam");
- assertEquals(getCollectionFormat(operation, 0), MULTI);
- assertEquals(getCollectionFormat(operation, 1), CSV);
- assertNull(getCollectionFormat(operation, 2));
- assertEquals(getCollectionFormat(operation, 3), CSV);
- }
-
- private Operation getOperation(String name) {
- return swagger.getPath("/collectionFormat/" + name).getPost();
- }
-
- private String getCollectionFormat(Operation op, int index) {
- return ((AbstractSerializableParameter) op.getParameters().get(index)).getCollectionFormat();
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/ConfigAndExtensionScannerTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/ConfigAndExtensionScannerTest.java
deleted file mode 100644
index 436d28bf12..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/ConfigAndExtensionScannerTest.java
+++ /dev/null
@@ -1,94 +0,0 @@
-package io.swagger;
-
-import io.swagger.jaxrs.Reader;
-import io.swagger.models.Info;
-import io.swagger.models.Scheme;
-import io.swagger.models.Swagger;
-import io.swagger.resources.ResourceWithConfigAndExtensions;
-import io.swagger.util.Json;
-import org.testng.annotations.Test;
-
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
-
-public class ConfigAndExtensionScannerTest {
-
- @Test(description = "scan a resource with extensions")
- public void scanResourceWithExtensions() {
- Set> classes = new HashSet>();
- classes.add(ResourceWithConfigAndExtensions.class);
- Swagger swagger = new Reader(new Swagger()).read(classes);
- assertEquals(swagger.getPaths().size(), 1);
-
- Info info = swagger.getInfo();
- assertNotNull(info);
- assertEquals(info.getDescription(), "Custom description");
- assertEquals(info.getTermsOfService(), "do-what-you-want");
- assertEquals(info.getTitle(), "TheAwesomeApi");
- assertEquals(info.getVersion(), "V1.2.3");
- assertEquals(info.getContact().getName(), "Sponge-Bob");
- assertEquals(info.getContact().getEmail(), "sponge-bob@swagger.io");
- assertEquals(info.getContact().getUrl(), "http://swagger.io");
- assertEquals(info.getLicense().getName(), "Apache 2.0");
- assertEquals(info.getLicense().getUrl(), "http://www.apache.org");
-
- assertEquals(swagger.getConsumes().size(), 2);
- assertTrue(swagger.getConsumes().contains("application/json"));
- assertTrue(swagger.getConsumes().contains("application/xml"));
-
- assertEquals(swagger.getProduces().size(), 2);
- swagger.getProduces().contains("application/json");
- swagger.getProduces().contains("application/xml");
-
- assertEquals(swagger.getExternalDocs().getDescription(), "test");
- assertEquals(swagger.getExternalDocs().getUrl(), "http://swagger.io");
-
- assertEquals(swagger.getSchemes().size(), 2);
- assertTrue(swagger.getSchemes().contains(Scheme.HTTP));
- assertTrue(swagger.getSchemes().contains(Scheme.HTTPS));
-
- assertEquals(swagger.getTags().size(), 7);
- assertEquals(swagger.getTags().get(0).getName(), "Tag-added-before-read");
-
- assertEquals(swagger.getTags().get(1).getName(), "mytag");
- assertEquals(swagger.getTags().get(1).getDescription(), "my tag");
-
- assertEquals(swagger.getTags().get(2).getName(), "anothertag");
- assertEquals(swagger.getTags().get(2).getDescription(), "another tag");
- assertEquals(swagger.getTags().get(2).getExternalDocs().getDescription(), "test");
- assertEquals(swagger.getTags().get(2).getExternalDocs().getUrl(), "http://swagger.io");
-
- assertEquals(swagger.getTags().get(3).getName(), "tagwithextensions");
- assertEquals(swagger.getTags().get(3).getDescription(), "my tag");
- Map extensions = swagger.getTags().get(3).getVendorExtensions();
- assertEquals(extensions.size(), 1);
- assertEquals(extensions.get("x-test"), "value");
-
- assertEquals(swagger.getTags().get(4).getName(), "externalinfo");
- assertEquals(swagger.getTags().get(5).getName(), "testingtag");
- assertEquals(swagger.getTags().get(6).getName(), "Tag-added-after-read");
-
- extensions = swagger.getInfo().getVendorExtensions();
- assertEquals(extensions.size(), 3);
- assertEquals(extensions.get("x-test1"), "value1");
- assertEquals(extensions.get("x-test2"), "value2");
-
- extensions = (Map) extensions.get("x-test");
- assertEquals(extensions.get("test1"), "value1");
- assertEquals(extensions.get("test2"), "value2");
-
- extensions = swagger.getPath("/who/cares").getOperations().get(0).getVendorExtensions();
- assertEquals(extensions.get("x-test"), "value");
-
- String json = Json.pretty(swagger);
- assertNotEquals(json.indexOf("\"x-test\" : {"), -1);
- assertNotEquals(json.indexOf("\"x-test1\" : \"value1\""), -1);
- assertNotEquals(json.indexOf("\"x-test2\" : \"value2\""), -1);
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/DefaultJaxrsScannerTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/DefaultJaxrsScannerTest.java
deleted file mode 100644
index 0f413bb2c8..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/DefaultJaxrsScannerTest.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package io.swagger;
-
-import com.google.common.base.Function;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Sets;
-import io.swagger.jaxrs.config.DefaultJaxrsScanner;
-import org.testng.annotations.Test;
-
-import javax.ws.rs.core.Application;
-import java.util.Set;
-
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import static org.testng.Assert.assertEquals;
-
-public class DefaultJaxrsScannerTest {
-
- @Test(description = "should return singletones")
- public void classesFromContextTest() {
- Application app = mock(Application.class);
- Set singletons = Sets.newHashSet(new io.swagger.jaxrs.listing.ApiListingResource(), new DefaultJaxrsScannerTest());
-
- when(app.getClasses()).thenReturn(null);
- when(app.getSingletons()).thenReturn(singletons);
-
- DefaultJaxrsScanner scanner = new DefaultJaxrsScanner();
- Set> output = scanner.classesFromContext(app, null);
-
- Set> classes = Sets.newHashSet(Iterables.transform(singletons, new Function>() {
- @Override
- public Class> apply(Object o) {
- return o.getClass();
- }
- }));
-
- assertEquals(output, classes);
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/GenericsTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/GenericsTest.java
deleted file mode 100644
index 4f983db87e..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/GenericsTest.java
+++ /dev/null
@@ -1,231 +0,0 @@
-package io.swagger;
-
-import com.google.common.base.Functions;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.Sets;
-import io.swagger.jaxrs.Reader;
-import io.swagger.models.ArrayModel;
-import io.swagger.models.Model;
-import io.swagger.models.Operation;
-import io.swagger.models.RefModel;
-import io.swagger.models.Swagger;
-import io.swagger.models.TestEnum;
-import io.swagger.models.parameters.BodyParameter;
-import io.swagger.models.parameters.QueryParameter;
-import io.swagger.models.properties.ArrayProperty;
-import io.swagger.models.properties.Property;
-import io.swagger.models.properties.RefProperty;
-import io.swagger.models.properties.StringProperty;
-import io.swagger.models.properties.UUIDProperty;
-import io.swagger.resources.ResourceWithGenerics;
-import io.swagger.resources.generics.UserApiRoute;
-
-import org.testng.annotations.Test;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
-
-public class GenericsTest {
- private final Swagger swagger = new Reader(new Swagger()).read(ResourceWithGenerics.class);
- private final Set enumValues = Sets.newHashSet(Collections2.transform(Arrays.asList(TestEnum.values()), Functions.toStringFunction()));
-
- private void testEnumCollection(QueryParameter p, String name) {
- testCollection(p, name, "string", null);
- StringProperty schema = (StringProperty) p.getItems();
- assertEquals(schema.getEnum(), enumValues);
- }
-
- private void testCollection(QueryParameter p, String name, String type, String format) {
- assertEquals(p.getName(), name);
- assertEquals(p.getType(), "array");
- assertEquals(p.getFormat(), null);
- assertEquals(p.getCollectionFormat(), "multi");
- assertNotEquals(p.getItems(), null);
- Property schema = p.getItems();
- assertEquals(schema.getType(), type);
- assertEquals(schema.getFormat(), format);
- }
-
- private void testScalar(QueryParameter p, String name, String type, String format) {
- assertEquals(p.getName(), name);
- assertEquals(p.getType(), type);
- assertEquals(p.getFormat(), format);
- assertEquals(p.getCollectionFormat(), null);
- assertEquals(p.getItems(), null);
- }
-
- private void testGenericType(Operation op, String type) {
- assertEquals(((RefModel) getBodyParameter(op, 0).getSchema()).getSimpleRef(), type);
- }
-
- private BodyParameter getBodyParameter(Operation op, int index) {
- return (BodyParameter) op.getParameters().get(index);
- }
-
- private Operation getOperation(String name) {
- return swagger.getPath("/generics/" + name).getPost();
- }
-
- private QueryParameter getQueryParameter(Operation op, int index) {
- return (QueryParameter) op.getParameters().get(index);
- }
-
- private Property getProperty(String type, String name) {
- return (swagger.getDefinitions().get(type)).getProperties().get(name);
- }
-
- @Test(description = "check collections of integers")
- public void checkCollectionsOfIntegers() {
- Operation op = getOperation("testIntegerContainers");
- assertEquals(op.getParameters().size(), 8);
- testCollection(getQueryParameter(op, 0), "set", "integer", "int32");
- testCollection(getQueryParameter(op, 1), "list", "integer", "int32");
- testCollection(getQueryParameter(op, 2), "list2D", "string", null);
- testCollection(getQueryParameter(op, 3), "array", "integer", "int32");
- testCollection(getQueryParameter(op, 4), "arrayP", "integer", "int32");
- testScalar(getQueryParameter(op, 5), "scalar", "integer", "int32");
- testScalar(getQueryParameter(op, 6), "scalarP", "integer", "int32");
- testCollection(getQueryParameter(op, 7), "forced", "integer", "int32");
- }
-
- @Test(description = "check collections of strings")
- public void checkCollectionsOfStrings() {
- Operation op = getOperation("testStringContainers");
- assertEquals(op.getParameters().size(), 5);
- QueryParameter set = getQueryParameter(op, 0);
- testCollection(set, "set", "string", null);
- assertEquals(((StringProperty) set.getItems()).getEnum(), Arrays.asList("1", "2", "3"));
- testCollection(getQueryParameter(op, 1), "list", "string", null);
- testCollection(getQueryParameter(op, 2), "list2D", "string", null);
- testCollection(getQueryParameter(op, 3), "array", "string", null);
- testScalar(getQueryParameter(op, 4), "scalar", "string", null);
- }
-
- @Test(description = "check collections of objects")
- public void checkCollectionsOfObjects() {
- Operation op = getOperation("testObjectContainers");
- assertEquals(op.getParameters().size(), 5);
- testCollection(getQueryParameter(op, 0), "set", "string", null);
- testCollection(getQueryParameter(op, 1), "list", "string", null);
- testCollection(getQueryParameter(op, 2), "list2D", "string", null);
- testCollection(getQueryParameter(op, 3), "array", "string", null);
- testScalar(getQueryParameter(op, 4), "scalar", "string", null);
- }
-
- @Test(description = "check collections of enumerations")
- public void checkCollectionsOfEnumerations() {
- Operation op = getOperation("testEnumContainers");
- assertEquals(op.getParameters().size(), 5);
- testEnumCollection(getQueryParameter(op, 0), "set");
- testEnumCollection(getQueryParameter(op, 1), "list");
- testCollection(getQueryParameter(op, 2), "list2D", "string", null);
- testEnumCollection(getQueryParameter(op, 3), "array");
- QueryParameter scalar = getQueryParameter(op, 4);
- testScalar(scalar, "scalar", "string", null);
- assertEquals(scalar.getEnum(), enumValues);
- }
-
- @Test(description = "check collection of strings as body parameter")
- public void checkCollectionsOfStringsAsBodyParameter() {
- Operation op = getOperation("testStringsInBody");
- assertEquals(op.getParameters().size(), 1);
- BodyParameter p = getBodyParameter(op, 0);
- ArrayModel strArray = (ArrayModel) p.getSchema();
- assertEquals(strArray.getItems().getType(), "string");
- }
-
- @Test(description = "check collection of objects as body parameter")
- public void checkCollectionsOfObjectsAsBodyParameter() {
- Operation op = getOperation("testObjectsInBody");
- assertEquals(op.getParameters().size(), 1);
- BodyParameter p = getBodyParameter(op, 0);
- ArrayModel objArray = (ArrayModel) p.getSchema();
- assertEquals(((RefProperty) objArray.getItems()).getSimpleRef(), "Tag");
- }
-
- @Test(description = "check collection of enumerations as body parameter")
- public void checkCollectionsOfEnumerationsAsBodyParameter() {
- Operation op = getOperation("testEnumsInBody");
- assertEquals(op.getParameters().size(), 1);
- BodyParameter p = getBodyParameter(op, 0);
- ArrayModel enumArray = (ArrayModel) p.getSchema();
- assertEquals(((StringProperty) enumArray.getItems()).getEnum(), enumValues);
- }
-
- @Test(description = "check 2D array as body parameter")
- public void check2DArrayAsBodyParameter() {
- Operation op = getOperation("test2DInBody");
- assertEquals(op.getParameters().size(), 1);
- BodyParameter p = getBodyParameter(op, 0);
- ArrayModel ddArray = (ArrayModel) p.getSchema();
- assertEquals(((RefProperty) ((ArrayProperty) ddArray.getItems()).getItems()).getSimpleRef(), "Tag");
- }
-
- @Test(description = "check parameters of generic types")
- public void checkParametersOfGenericTypes() {
- Set genericTypes = new HashSet(Arrays.asList("GenericTypeString", "GenericTypeUUID", "GenericTypeGenericTypeString",
- "RenamedGenericTypeString", "RenamedGenericTypeRenamedGenericTypeString"));
- assertTrue(swagger.getDefinitions().keySet().containsAll(genericTypes));
-
- Operation opString = getOperation("testGenericType");
- testGenericType(opString, "GenericTypeString");
- Property strValue = getProperty("GenericTypeString", "value");
- assertNotEquals(strValue, null);
- assertEquals(strValue.getClass().getName(), StringProperty.class.getName());
-
- Operation opUUID = getOperation("testStringBasedGenericType");
- testGenericType(opUUID, "GenericTypeUUID");
- Property uuidValue = getProperty("GenericTypeUUID", "value");
- assertNotEquals(uuidValue, null);
- assertEquals(uuidValue.getClass().getName(), UUIDProperty.class.getName());
-
- Operation opComplex = getOperation("testComplexGenericType");
- testGenericType(opComplex, "GenericTypeGenericTypeString");
- Property complexValue = getProperty("GenericTypeGenericTypeString", "value");
- assertNotEquals(complexValue, null);
- assertEquals(complexValue.getClass().getName(), RefProperty.class.getName());
- assertEquals(((RefProperty) complexValue).getSimpleRef(), "GenericTypeString");
-
- Operation opRenamed = getOperation("testRenamedGenericType");
- testGenericType(opRenamed, "RenamedGenericTypeRenamedGenericTypeString");
- Property renamedComplexValue = getProperty("RenamedGenericTypeRenamedGenericTypeString", "value");
- assertNotEquals(renamedComplexValue, null);
- assertTrue(renamedComplexValue instanceof RefProperty);
- assertEquals(((RefProperty) renamedComplexValue).getSimpleRef(), "RenamedGenericTypeString");
- }
-
- @Test(description = "check generic result")
- public void checkGenericResult() {
- Operation op = swagger.getPath("/generics/testGenericResult").getGet();
- Property schema = op.getResponses().get("200").getSchema();
- assertEquals(schema.getClass().getName(), RefProperty.class.getName());
- assertEquals(((RefProperty) schema).getSimpleRef(), "GenericListWrapperTag");
-
- Property entries = getProperty("GenericListWrapperTag", "entries");
- assertNotEquals(entries, null);
- assertEquals(entries.getClass().getName(), ArrayProperty.class.getName());
-
- Property items = ((ArrayProperty) entries).getItems();
- assertEquals(items.getClass().getName(), RefProperty.class.getName());
- assertEquals(((RefProperty) items).getSimpleRef(), "Tag");
- }
-
- @Test(description = "scan model with Generic Type")
- public void scanModelWithGenericType() {
- final Swagger swagger = new Reader(new Swagger()).read(UserApiRoute.class);
- assertNotNull(swagger);
- final Model userEntity = swagger.getDefinitions().get("UserEntity");
- assertNotNull(userEntity);
- final Map properties = userEntity.getProperties();
- assertEquals(properties.size(), 2);
- assertNotNull(properties.get("id"));
- assertNotNull(properties.get("name"));
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/HiddenParametersScannerTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/HiddenParametersScannerTest.java
deleted file mode 100644
index fca6b12067..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/HiddenParametersScannerTest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package io.swagger;
-
-import io.swagger.jaxrs.Reader;
-import io.swagger.models.Operation;
-import io.swagger.models.Swagger;
-import io.swagger.models.parameters.Parameter;
-import io.swagger.resources.HiddenParametersResource;
-import org.testng.annotations.Test;
-
-import java.util.List;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-
-public class HiddenParametersScannerTest {
- private final Swagger swagger = new Reader(new Swagger()).read(HiddenParametersResource.class);
-
- @Test
- public void shouldScanMethodWithAllParamsHidden() throws Exception {
- Operation get = getGet("/all-hidden/{id}");
-
- assertNotNull(get);
- assertEquals(0, get.getParameters().size());
- }
-
- @Test
- public void shouldScanMethodWithSomeParamsHidden() {
- Operation get = getGet("/some-hidden/{id}");
-
- assertNotNull(get);
- List parameters = get.getParameters();
- assertEquals(parameters.size(), 3);
- assertEquals(parameters.get(0).getIn(), "cookie");
- assertEquals(parameters.get(1).getIn(), "header");
- assertEquals(parameters.get(2).getIn(), "query");
- }
-
- @Test
- public void shouldScanMethodWithOtherParamsHidden() {
- Operation get = getGet("/others-hidden/{id}");
-
- assertNotNull(get);
- List parameters = get.getParameters();
- assertEquals(parameters.size(), 3);
- assertEquals(parameters.get(0).getIn(), "body");
- assertEquals(parameters.get(1).getIn(), "formData");
- assertEquals(parameters.get(2).getIn(), "path");
- }
-
- private Operation getGet(String path) {
- return swagger.getPaths().get(path).getGet();
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/IntegerValueReadingTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/IntegerValueReadingTest.java
deleted file mode 100644
index d6cdc0b810..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/IntegerValueReadingTest.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package io.swagger;
-
-/**
- * Created by tony on 2/21/17.
- */
-public class IntegerValueReadingTest {
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/JsonIdentityTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/JsonIdentityTest.java
deleted file mode 100644
index 61ae82ef1b..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/JsonIdentityTest.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package io.swagger;
-
-import io.swagger.jaxrs.Reader;
-import io.swagger.matchers.SerializationMatchers;
-import io.swagger.models.Swagger;
-import io.swagger.resources.JsonIdentityResource;
-import io.swagger.util.ResourceUtils;
-
-import org.testng.annotations.Test;
-
-import java.io.IOException;
-
-public class JsonIdentityTest {
-
- @Test(description = "Scan API with operation and response references")
- public void scan() throws IOException {
- final Swagger swagger = new Reader(new Swagger()).read(JsonIdentityResource.class);
- final String json = ResourceUtils.loadClassResource(getClass(), "ResourceWithJsonIdentity.json");
- SerializationMatchers.assertEqualsToJson(swagger, json);
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/OverriddenTypeTests.java b/modules/swagger-jaxrs/src/test/java/io/swagger/OverriddenTypeTests.java
deleted file mode 100644
index 44c8123ac0..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/OverriddenTypeTests.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package io.swagger;
-
-import io.swagger.jaxrs.Reader;
-import io.swagger.models.Swagger;
-import io.swagger.models.parameters.QueryParameter;
-import io.swagger.resources.Resource469;
-import org.testng.annotations.Test;
-
-import static org.testng.Assert.assertEquals;
-
-public class OverriddenTypeTests {
- @Test(description = "add a user-specified format")
- public void passwordParameterTest() {
- Swagger swagger = new Reader(new Swagger()).read(Resource469.class);
-
- QueryParameter qp = (QueryParameter)swagger.getPath("/test").getGet().getParameters().get(0);
- assertEquals(qp.getFormat(), "password");
- }
-
- @Test(description = "overrides a system-detected format")
- public void integerFormatOverrideTest() {
- Swagger swagger = new Reader(new Swagger()).read(Resource469.class);
-
- QueryParameter qp = (QueryParameter)swagger.getPath("/test").getPost().getParameters().get(0);
- assertEquals(qp.getFormat(), "int64");
- }
-
- @Test(description = "overrides a system-detected type")
- public void integerTypeOverrideTest() {
- Swagger swagger = new Reader(new Swagger()).read(Resource469.class);
-
- QueryParameter qp = (QueryParameter)swagger.getPath("/test").getPut().getParameters().get(0);
- assertEquals(qp.getType(), "string");
- assertEquals(qp.getFormat(), "blah");
- }
-
- @Test(description = "add a user-specified type with implicit annotation")
- public void implicitParamTest() {
- Swagger swagger = new Reader(new Swagger()).read(Resource469.class);
-
- QueryParameter qp = (QueryParameter)swagger.getPath("/test2").getGet().getParameters().get(0);
- assertEquals(qp.getType(), "string");
- assertEquals(qp.getFormat(), "password");
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/PostParamTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/PostParamTest.java
deleted file mode 100644
index 944eca421f..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/PostParamTest.java
+++ /dev/null
@@ -1,166 +0,0 @@
-package io.swagger;
-
-import io.swagger.jaxrs.Reader;
-import io.swagger.models.ArrayModel;
-import io.swagger.models.Model;
-import io.swagger.models.Operation;
-import io.swagger.models.Path;
-import io.swagger.models.Swagger;
-import io.swagger.models.parameters.BodyParameter;
-import io.swagger.models.properties.Property;
-import io.swagger.models.properties.RefProperty;
-import io.swagger.models.properties.StringProperty;
-import io.swagger.resources.PostParamResource;
-import org.testng.annotations.Test;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertNull;
-import static org.testng.Assert.assertTrue;
-
-public class PostParamTest {
- private static final String BODY = "body";
- private static final String PET = "Pet";
- private final Swagger swagger = new Reader(new Swagger()).read(PostParamResource.class);
-
- @Test(description = "find a Post operation with single object")
- public void findPostOperationWithSingleObject() {
- Path petPath = getPath("singleObject");
- assertNotNull(petPath);
- assertNull(petPath.getGet());
- Operation petPost = petPath.getPost();
- assertNotNull(petPost);
- assertEquals(petPost.getParameters().size(), 1);
- BodyParameter petPostBodyParam = (BodyParameter) petPost.getParameters().get(0);
- assertEquals(petPostBodyParam.getName(), BODY);
-
- assertTrue(petPostBodyParam.getSchema() instanceof Model);
- assertEquals(swagger.getDefinitions().get(PET).getProperties().get("status").getAccess(), "public");
- }
-
- @Test(description = "find a Post operation with list of objects")
- public void findPostOperationWithObjectsList() {
- Path petPath = getPath("listOfObjects");
- assertNotNull(petPath);
- Operation petPost = petPath.getPost();
- assertNotNull(petPost);
- assertEquals(petPost.getParameters().size(), 1);
- BodyParameter petPostBodyParam = (BodyParameter) petPost.getParameters().get(0);
- assertEquals(petPostBodyParam.getName(), BODY);
-
- Model inputModel = petPostBodyParam.getSchema();
- assertTrue(inputModel instanceof ArrayModel);
- ArrayModel ap = (ArrayModel) inputModel;
- Property inputSchema = ap.getItems();
- assertTrue(inputSchema instanceof RefProperty);
- RefProperty rm = (RefProperty) inputSchema;
- assertEquals(rm.getSimpleRef(), PET);
- }
-
- @Test(description = "find a Post operation with collection of objects")
- public void findPostOperationWithObjectsCollection() {
- Path petPath = getPath("collectionOfObjects");
- assertNotNull(petPath);
- Operation petPost = petPath.getPost();
- assertNotNull(petPost);
- assertEquals(petPost.getParameters().size(), 1);
- BodyParameter petPostBodyParam = (BodyParameter) petPost.getParameters().get(0);
- assertEquals(petPostBodyParam.getName(), BODY);
-
- Model inputModel = petPostBodyParam.getSchema();
- assertTrue(inputModel instanceof ArrayModel);
- ArrayModel ap = (ArrayModel) inputModel;
- Property inputSchema = ap.getItems();
- assertTrue(inputSchema instanceof RefProperty);
- RefProperty rm = (RefProperty) inputSchema;
- assertEquals(rm.getSimpleRef(), PET);
- }
-
- @Test(description = "find a Post operation with an array of objects")
- public void findAPostOperationWithObjectsArray() {
- Path petPath = getPath("arrayOfObjects");
- assertNotNull(petPath);
- Operation petPost = petPath.getPost();
- assertNotNull(petPost);
- assertEquals(petPost.getParameters().size(), 1);
- BodyParameter petPostBodyParam = (BodyParameter) petPost.getParameters().get(0);
- assertEquals(petPostBodyParam.getName(), BODY);
-
- Model inputModel = petPostBodyParam.getSchema();
- assertTrue(inputModel instanceof ArrayModel);
- ArrayModel ap = (ArrayModel) inputModel;
- Property inputSchema = ap.getItems();
- assertTrue(inputSchema instanceof RefProperty);
- RefProperty rm = (RefProperty) inputSchema;
- assertEquals(rm.getSimpleRef(), PET);
- }
-
- @Test(description = "find a Post operation with single string")
- public void findAPostOperationWithSingleString() {
- Path petPath = getPath("singleString");
- assertNotNull(petPath);
- assertNull(petPath.getGet());
- Operation petPost = petPath.getPost();
- assertNotNull(petPost);
- assertEquals(petPost.getParameters().size(), 1);
- BodyParameter petPostBodyParam = (BodyParameter) petPost.getParameters().get(0);
- assertEquals(petPostBodyParam.getName(), BODY);
-
- assertTrue(petPostBodyParam.getSchema() instanceof Model);
- }
-
- @Test(description = "find a Post operation with list of strings")
- public void findAPostOperationWithStringsList() {
- Path petPath = getPath("listOfStrings");
- assertNotNull(petPath);
- Operation petPost = petPath.getPost();
- assertNotNull(petPost);
- assertEquals(petPost.getParameters().size(), 1);
- BodyParameter petPostBodyParam = (BodyParameter) petPost.getParameters().get(0);
- assertEquals(petPostBodyParam.getName(), BODY);
-
- Model inputModel = petPostBodyParam.getSchema();
- assertTrue(inputModel instanceof ArrayModel);
- ArrayModel ap = (ArrayModel) inputModel;
- Property inputSchema = ap.getItems();
- assertTrue(inputSchema instanceof StringProperty);
- }
-
- @Test(description = "find a Post operation with collection of strings")
- public void findAPostOperationWithStringsCollection() {
- Path petPath = getPath("collectionOfStrings");
- assertNotNull(petPath);
- Operation petPost = petPath.getPost();
- assertNotNull(petPost);
- assertEquals(petPost.getParameters().size(), 1);
- BodyParameter petPostBodyParam = (BodyParameter) petPost.getParameters().get(0);
- assertEquals(petPostBodyParam.getName(), BODY);
-
- Model inputModel = petPostBodyParam.getSchema();
- assertTrue(inputModel instanceof ArrayModel);
- ArrayModel ap = (ArrayModel) inputModel;
- Property inputSchema = ap.getItems();
- assertTrue(inputSchema instanceof StringProperty);
- }
-
- @Test(description = "find a Post operation with an array of strings")
- public void findAPostOperationWithStringsArray() {
- Path petPath = getPath("arrayOfStrings");
- assertNotNull(petPath);
- Operation petPost = petPath.getPost();
- assertNotNull(petPost);
- assertEquals(petPost.getParameters().size(), 1);
- BodyParameter petPostBodyParam = (BodyParameter) petPost.getParameters().get(0);
- assertEquals(petPostBodyParam.getName(), BODY);
-
- Model inputModel = petPostBodyParam.getSchema();
- assertTrue(inputModel instanceof ArrayModel);
- ArrayModel ap = (ArrayModel) inputModel;
- Property inputSchema = ap.getItems();
- assertTrue(inputSchema instanceof StringProperty);
- }
-
- private Path getPath(String path) {
- return swagger.getPaths().get("/pet/".concat(path));
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/ReaderTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/ReaderTest.java
deleted file mode 100644
index d3718935b0..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/ReaderTest.java
+++ /dev/null
@@ -1,440 +0,0 @@
-package io.swagger;
-
-import io.swagger.jaxrs.Reader;
-import io.swagger.models.ExternalDocs;
-import io.swagger.models.Operation;
-import io.swagger.models.Swagger;
-import io.swagger.models.Tag;
-import io.swagger.models.parameters.BodyParameter;
-import io.swagger.models.parameters.FormParameter;
-import io.swagger.models.parameters.HeaderParameter;
-import io.swagger.models.parameters.Parameter;
-import io.swagger.models.parameters.PathParameter;
-import io.swagger.models.parameters.QueryParameter;
-import io.swagger.resources.AnnotatedInterfaceImpl;
-import io.swagger.resources.ApiConsumesProducesResource;
-import io.swagger.resources.ApiMultipleConsumesProducesResource;
-import io.swagger.resources.BookResource;
-import io.swagger.resources.BothConsumesProducesResource;
-import io.swagger.resources.DescendantResource;
-import io.swagger.resources.IndirectImplicitParamsImpl;
-import io.swagger.resources.NoConsumesProducesResource;
-import io.swagger.resources.Resource1970;
-import io.swagger.resources.ResourceWithAnnotationsOnlyInInterfaceImpl;
-import io.swagger.resources.ResourceWithClassLevelApiResourceNoMethodLevelApiResources;
-import io.swagger.resources.ResourceWithCustomException;
-import io.swagger.resources.ResourceWithCustomExceptionAndClassLevelApiResource;
-import io.swagger.resources.ResourceWithDeprecatedMethod;
-import io.swagger.resources.ResourceWithEmptyPath;
-import io.swagger.resources.ResourceWithExternalDocs;
-import io.swagger.resources.ResourceWithImplicitFileParam;
-import io.swagger.resources.ResourceWithImplicitParams;
-import io.swagger.resources.ResourceWithKnownInjections;
-import io.swagger.resources.ResourceWithValidation;
-import io.swagger.resources.RsConsumesProducesResource;
-import io.swagger.resources.RsMultipleConsumesProducesResource;
-import io.swagger.resources.SimpleMethods;
-import org.testng.annotations.Test;
-
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HEAD;
-import javax.ws.rs.OPTIONS;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.core.MediaType;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-import java.math.BigDecimal;
-import java.util.Arrays;
-import java.util.List;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertNull;
-import static org.testng.Assert.assertTrue;
-
-public class ReaderTest {
- private static final String APPLICATION_XML = "application/xml";
- private static final String TEXT_PLAIN = "text/plain";
- private static final String TEXT_HTML = "text/html";
- private static final String TEXT_XML = "text/xml";
- private static final String TEXT_JSON = "text/json";
- private static final String CHARSET8 = ";charset=UTF-8";
- private static final String TEXT_XML_CHARSET = TEXT_XML + CHARSET8;
- private static final String TEXT_HTML_CHARSET = TEXT_HTML + CHARSET8;
-
- @Test(description = "scan methods")
- public void scanMethods() {
- Method[] methods = SimpleMethods.class.getMethods();
- Reader reader = new Reader(new Swagger());
- for (Method method : methods) {
- if (isValidRestPath(method)) {
- Operation operation = reader.parseMethod(method);
- assertNotNull(operation);
- }
- }
- }
-
- @Test(description = "scan consumes and produces values with api class level annotations")
- public void scanConsumesProducesValuesWithApiClassLevelAnnotations() {
- Swagger swagger = getSwagger(ApiConsumesProducesResource.class);
- assertEquals(getGet(swagger, "/{id}").getConsumes().get(0), MediaType.APPLICATION_XHTML_XML);
- assertEquals(getGet(swagger, "/{id}").getProduces().get(0), MediaType.APPLICATION_ATOM_XML);
- assertEquals(getGet(swagger, "/{id}/value").getConsumes().get(0), APPLICATION_XML);
- assertEquals(getGet(swagger, "/{id}/value").getConsumes().get(1), TEXT_HTML_CHARSET);
- assertEquals(getGet(swagger, "/{id}/value").getProduces().get(0), TEXT_PLAIN);
- assertEquals(getGet(swagger, "/{id}/value").getProduces().get(1), TEXT_XML_CHARSET);
- assertEquals(getPut(swagger, "/{id}").getConsumes().get(0), MediaType.APPLICATION_JSON);
- assertEquals(getPut(swagger, "/{id}").getConsumes().get(1), TEXT_HTML_CHARSET);
- assertEquals(getPut(swagger, "/{id}").getProduces().get(0), TEXT_PLAIN);
- assertEquals(getPut(swagger, "/{id}").getProduces().get(1), TEXT_XML_CHARSET);
- assertEquals(getPut(swagger, "/{id}/value").getConsumes().get(0), APPLICATION_XML);
- assertEquals(getPut(swagger, "/{id}/value").getProduces().get(0), TEXT_PLAIN);
- }
-
- @Test(description = "scan consumes and produces values with api class level annotations")
- public void scanMultipleConsumesProducesValuesWithApiClassLevelAnnotations() {
- Swagger swagger = getSwagger(ApiMultipleConsumesProducesResource.class);
- assertEquals(getGet(swagger, "/{id}").getConsumes(), Arrays.asList(MediaType.APPLICATION_XHTML_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON));
- assertEquals(getGet(swagger, "/{id}").getProduces(), Arrays.asList(MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML));
-
- }
-
- @Test(description = "scan consumes and produces values with rs class level annotations")
- public void scanConsumesProducesValuesWithRsClassLevelAnnotations() {
- Swagger swagger = getSwagger(RsConsumesProducesResource.class);
- assertEquals(getGet(swagger, "/{id}").getConsumes().get(0), "application/yaml");
- assertEquals(getGet(swagger, "/{id}").getProduces().get(0), APPLICATION_XML);
- assertEquals(getGet(swagger, "/{id}/value").getConsumes().get(0), APPLICATION_XML);
- assertEquals(getGet(swagger, "/{id}/value").getProduces().get(0), TEXT_PLAIN);
- assertEquals(getPut(swagger, "/{id}").getConsumes().get(0), MediaType.APPLICATION_JSON);
- assertEquals(getPut(swagger, "/{id}").getProduces().get(0), TEXT_PLAIN);
- assertEquals(getPut(swagger, "/{id}/value").getConsumes().get(0), APPLICATION_XML);
- assertEquals(getPut(swagger, "/{id}/value").getProduces().get(0), TEXT_PLAIN);
- assertEquals(getPut(swagger, "/split").getProduces(), Arrays.asList("image/jpeg", "image/gif", "image/png"));
- assertEquals(getPut(swagger, "/split").getConsumes(), Arrays.asList("image/jpeg", "image/gif", "image/png"));
- }
-
- @Test(description = "scan multiple consumes and produces values with rs class level annotations")
- public void scanMultipleConsumesProducesValuesWithRsClassLevelAnnotations() {
- Swagger swagger = getSwagger(RsMultipleConsumesProducesResource.class);
- assertEquals(getGet(swagger, "/{id}").getConsumes(), Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML));
- assertEquals(getGet(swagger, "/{id}").getProduces(), Arrays.asList(MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON));
- }
-
- @Test(description = "scan consumes and produces values with both class level annotations")
- public void scanConsumesProducesValuesWithBothClassLevelAnnotations() {
- Swagger swagger = getSwagger(BothConsumesProducesResource.class);
- assertEquals(getGet(swagger, "/{id}").getConsumes().get(0), MediaType.APPLICATION_XHTML_XML);
- assertEquals(getGet(swagger, "/{id}").getProduces().get(0), MediaType.APPLICATION_ATOM_XML);
- assertEquals(getGet(swagger, "/{id}/value").getConsumes().get(0), APPLICATION_XML);
- assertEquals(getGet(swagger, "/{id}/value").getProduces().get(0), TEXT_PLAIN);
- assertEquals(getGet(swagger, "/{id}/{name}/value").getConsumes().get(0), MediaType.APPLICATION_JSON);
- assertEquals(getGet(swagger, "/{id}/{name}/value").getProduces().get(0), TEXT_PLAIN);
- assertEquals(getGet(swagger, "/{id}/{type}/value").getConsumes().get(0), APPLICATION_XML);
- assertEquals(getGet(swagger, "/{id}/{type}/value").getProduces().get(0), TEXT_HTML);
- assertEquals(getPut(swagger, "/{id}").getConsumes().get(0), MediaType.APPLICATION_JSON);
- assertEquals(getPut(swagger, "/{id}").getProduces().get(0), TEXT_PLAIN);
- assertEquals(getPut(swagger, "/{id}/value").getConsumes().get(0), APPLICATION_XML);
- assertEquals(getPut(swagger, "/{id}/value").getProduces().get(0), TEXT_PLAIN);
- }
-
- @Test(description = "scan consumes and produces values with no class level annotations")
- public void scanConsumesProducesValuesWithoutClassLevelAnnotations() {
- Swagger swagger = getSwagger(NoConsumesProducesResource.class);
- assertNull(getGet(swagger, "/{id}").getConsumes());
- assertNull(getGet(swagger, "/{id}").getProduces());
- assertEquals(getGet(swagger, "/{id}/value").getConsumes().get(0), APPLICATION_XML);
- assertEquals(getGet(swagger, "/{id}/value").getProduces().get(0), TEXT_PLAIN);
- assertEquals(getPut(swagger, "/{id}").getConsumes().get(0), MediaType.APPLICATION_JSON);
- assertEquals(getPut(swagger, "/{id}").getProduces().get(0), TEXT_PLAIN);
- assertEquals(getPut(swagger, "/{id}/value").getConsumes().get(0), APPLICATION_XML);
- assertEquals(getPut(swagger, "/{id}/value").getProduces().get(0), TEXT_PLAIN);
- }
-
- @Test(description = "scan class level and field level annotations")
- public void scanClassAndFieldLevelAnnotations() {
- Swagger swagger = getSwagger(ResourceWithKnownInjections.class);
-
- List resourceParameters = getGet(swagger, "/resource/{id}").getParameters();
- assertNotNull(resourceParameters);
- assertEquals(resourceParameters.size(), 3);
- assertEquals(resourceParameters.get(0).getName(), "id");
- assertEquals(resourceParameters.get(1).getName(), "fieldParam");
- assertEquals(resourceParameters.get(2).getName(), "methodParam");
-
- List subResourceParameters = getGet(swagger, "/resource/{id}/subresource1").getParameters();
- assertNotNull(subResourceParameters);
- assertEquals(subResourceParameters.size(), 3);
- assertEquals(subResourceParameters.get(0).getName(), "id");
- assertEquals(subResourceParameters.get(1).getName(), "fieldParam");
- assertEquals(subResourceParameters.get(2).getName(), "subResourceParam");
- }
-
- private Boolean isValidRestPath(Method method) {
- for (Class extends Annotation> item : Arrays.asList(GET.class, PUT.class, POST.class, DELETE.class,
- OPTIONS.class, HEAD.class)) {
- if (method.getAnnotation(item) != null) {
- return true;
- }
- }
- return false;
- }
-
- @Test(description = "scan overridden method in descendantResource")
- public void scanOverriddenMethod() {
- Swagger swagger = getSwagger(DescendantResource.class);
- Operation overriddenMethodWithTypedParam = getGet(swagger, "/pet/{petId1}");
- assertNotNull(overriddenMethodWithTypedParam);
- assertEquals(overriddenMethodWithTypedParam.getParameters().get(0).getDescription(), "ID of pet to return child");
-
- Operation methodWithoutTypedParam = getGet(swagger, "/pet/{petId2}");
- assertNotNull(methodWithoutTypedParam);
-
- Operation overriddenMethodWithoutTypedParam = getGet(swagger, "/pet/{petId3}");
- assertNotNull(overriddenMethodWithoutTypedParam);
-
- Operation methodWithoutTypedParamFromDescendant = getGet(swagger, "/pet/{petId4}");
- assertNotNull(methodWithoutTypedParamFromDescendant);
-
- Operation methodFromInterface = getGet(swagger, "/pet/{petId5}");
- assertNotNull(methodFromInterface);
- }
-
- @Test(description = "scan annotation from interface, issue#1427")
- public void scanInterfaceTest() {
- final Swagger swagger = new Reader(new Swagger()).read(AnnotatedInterfaceImpl.class);
- assertNotNull(swagger);
- assertNotNull(swagger.getPath("/v1/users/{id}").getGet());
- }
-
- @Test(description = "scan indirect implicit params from interface")
- public void scanImplicitParamInterfaceTest() {
- final Swagger swagger = new Reader(new Swagger()).read(IndirectImplicitParamsImpl.class);
- assertNotNull(swagger);
- assertEquals(swagger.getPath("/v1/users/{id}").getGet().getParameters().size(), 2);
- }
-
- @Test(description = "scan indirect implicit params from overridden method")
- public void scanImplicitParamOverriddenMethodTest() {
- final Swagger swagger = new Reader(new Swagger()).read(IndirectImplicitParamsImpl.class);
- assertNotNull(swagger);
- assertEquals(swagger.getPath("/v1/users").getPost().getParameters().size(), 2);
- }
-
- @Test(description = "scan implicit params")
- public void scanImplicitParam() {
- Swagger swagger = getSwagger(ResourceWithImplicitParams.class);
- List params = swagger.getPath("/testString").getPost().getParameters();
- assertNotNull(params);
- assertEquals(params.size(), 7);
-
- assertEquals(params.get(0).getName(), "sort");
- assertEquals(params.get(0).getIn(), "query");
-
- PathParameter pathParam = (PathParameter) params.get(1);
- assertEquals(pathParam.getName(), "type");
- assertEquals(pathParam.getIn(), "path");
- assertEquals(pathParam.getEnum().size(), 3);
- assertEquals(pathParam.getType(), "string");
-
- HeaderParameter headerParam = (HeaderParameter) params.get(2);
- assertEquals(headerParam.getName(), "size");
- assertEquals(headerParam.getIn(), "header");
- assertEquals(headerParam.getMinimum(), new BigDecimal(1.0));
-
- FormParameter formParam = (FormParameter) params.get(3);
- assertEquals(formParam.getName(), "width");
- assertEquals(formParam.getIn(), "formData");
- assertEquals(formParam.getMaximum(), new BigDecimal(1.0));
-
- assertEquals(params.get(4).getName(), "width");
- assertEquals(params.get(4).getIn(), "formData");
-
- QueryParameter queryParam = (QueryParameter) params.get(5);
- assertEquals(queryParam.getName(), "height");
- assertEquals(queryParam.getIn(), "query");
- assertEquals(queryParam.getMinimum(), new BigDecimal(3.0));
- assertEquals(queryParam.getMaximum(), new BigDecimal(4.0));
-
- BodyParameter bodyParam = (BodyParameter) params.get(6);
- assertEquals(bodyParam.getName(), "body");
- assertEquals(bodyParam.getIn(), "body");
- assertTrue(bodyParam.getRequired());
- }
-
- @Test(description = "scan implicit params with file objct")
- public void scanImplicitWithFile() {
- Swagger swagger = getSwagger(ResourceWithImplicitFileParam.class);
- Parameter param = swagger.getPath("/testString").getPost().getParameters().get(0);
- assertTrue(param instanceof FormParameter);
- FormParameter fp = (FormParameter) param;
- assertEquals("file", fp.getType());
- }
-
- @Test(description = "scan Deprecated annotation")
- public void scanDeprecatedAnnotation() {
- Swagger swagger = getSwagger(ResourceWithDeprecatedMethod.class);
- assertTrue(getGet(swagger, "/testDeprecated").isDeprecated());
- assertNull(getGet(swagger, "/testAllowed").isDeprecated());
- }
-
- @Test(description = "scan empty path annotation")
- public void scanEmptyPathAnnotation() {
- Swagger swagger = getSwagger(ResourceWithEmptyPath.class);
- assertNotNull(getGet(swagger, "/"));
- }
-
- @Test(description = "it should scan parameters from base resource class")
- public void scanParametersFromBaseResource(){
- Swagger swagger = getSwagger(BookResource.class);
- assertNotNull(swagger);
-
- List parameters = getGet(swagger, "/{id}/v1/books/{name}").getParameters();
- assertEquals(parameters.size(), 4);
-
- Parameter description = parameters.get(0);
- assertTrue(description instanceof PathParameter);
- assertEquals(description.getName(), "description");
- assertEquals(description.getDescription(), "Overridden description");
-
- Parameter id = parameters.get(1);
- assertTrue(id instanceof PathParameter);
- assertEquals(id.getName(), "id");
- assertEquals(id.getDescription(), "The Identifier of entity");
-
- Parameter test = parameters.get(2);
- assertTrue(test instanceof QueryParameter);
- assertEquals(test.getName(), "test");
- assertEquals(test.getDescription(), "Test Query Param");
-
- Parameter name = parameters.get(3);
- assertTrue(name instanceof PathParameter);
- assertEquals(name.getName(), "name");
- assertEquals(name.getDescription(), "The books name");
- }
-
- @Test(description = "it should scan parameters with Swagger and JSR-303 bean validation annotations")
- public void scanBeanValidation(){
-
- Swagger swagger = getSwagger(ResourceWithValidation.class);
- assertNotNull(swagger);
-
- QueryParameter par = (QueryParameter) swagger.getPaths().get("/303").getOperations().get(0).getParameters().get(0);
- assertTrue(par.getRequired());
- assertEquals(par.getMinimum(), new BigDecimal(10));
-
- par = (QueryParameter) swagger.getPaths().get("/swagger-and-303").getOperations().get(0).getParameters().get(0);
- assertTrue(par.getRequired());
- assertEquals(par.getMinimum(), new BigDecimal(7));
-
- par = (QueryParameter) swagger.getPaths().get("/swagger").getOperations().get(0).getParameters().get(0);
- assertTrue(par.getRequired());
- assertEquals(par.getMinimum(), new BigDecimal(7));
- }
-
- @Test(description = "scan resource with annotated exception")
- public void scanDeclaredExceptions() {
- Swagger swagger = getSwagger(ResourceWithCustomException.class);
- assertNotNull(swagger);
-
- Operation operation = getGet(swagger, "/{id}");
- assertEquals(operation.getResponses().size(), 3);
- assertTrue(operation.getResponses().containsKey("200"));
- assertTrue(operation.getResponses().containsKey("400"));
- assertTrue(operation.getResponses().containsKey("404"));
- }
-
- @Test(description = "scan resource with annotated exception")
- public void scanDeclaredExceptionsAndCombineWithMethodResponses() {
- Swagger swagger = getSwagger(ResourceWithCustomException.class);
- assertNotNull(swagger);
-
- Operation operation = getPut(swagger, "/{id}");
- assertEquals(operation.getResponses().size(), 4);
- assertTrue(operation.getResponses().containsKey("200"));
- assertTrue(operation.getResponses().containsKey("400"));
- assertTrue(operation.getResponses().containsKey("404"));
- assertTrue(operation.getResponses().containsKey("409"));
- }
-
- @Test(description = "scan resource with annotated exception")
- public void scanDeclaredExceptionsAndCombineWithMethodResponsesClassLevel() {
- Swagger swagger = getSwagger(ResourceWithCustomExceptionAndClassLevelApiResource.class);
- assertNotNull(swagger);
-
- Operation operation = getPut(swagger, "/{id}");
- assertEquals(operation.getResponses().size(), 5);
- assertTrue(operation.getResponses().containsKey("200"));
- assertTrue(operation.getResponses().containsKey("400"));
- assertTrue(operation.getResponses().containsKey("404"));
- assertTrue(operation.getResponses().containsKey("403"));
- assertTrue(operation.getResponses().containsKey("409"));
- assertEquals(operation.getResponses().get("409").getDescription(), "Conflict");
-
- swagger = getSwagger(ResourceWithClassLevelApiResourceNoMethodLevelApiResources.class);
- assertNotNull(swagger);
- operation = getPut(swagger, "/{id}");
- assertEquals(operation.getResponses().size(), 2);
- assertTrue(operation.getResponses().containsKey("403"));
- assertTrue(operation.getResponses().containsKey("409"));
-
-
- }
-
- @Test(description = "scan resource (impl) which has the Api annotations only declared in its interface")
- public void scanApiAnnotationWhichAreOnlyPresentInInterfaceAndNotInImplementation() {
- Swagger swagger = getSwagger(ResourceWithAnnotationsOnlyInInterfaceImpl.class);
- assertNotNull(swagger);
-
- final List tags = swagger.getTags();
- assertEquals(tags.size(), 1);
- assertEquals(tags.get(0).getName(), "someTag");
- }
-
- @Test(description = "scan resource (impl) which has the ApiParam annotations only declared in its interface")
- public void scanApiImplicitParamAnnotationWhichAreOnlyPresentInInterfaceAndNotInImplementation() {
- Swagger swagger = getSwagger(ResourceWithAnnotationsOnlyInInterfaceImpl.class);
- assertNotNull(swagger);
-
- List parameters = getGet(swagger, "/pet/randomPet").getParameters();
- assertNotNull(parameters);
- assertEquals(parameters.size(), 1);
- assertEquals(parameters.get(0).getName(), "petImplicitIdParam");
- }
-
- @Test(description = "scan resource per #1970")
- public void scanBigDecimal() {
- Swagger swagger = getSwagger(Resource1970.class);
- assertNotNull(swagger);
-
- PathParameter parameter = (PathParameter)swagger.getPath("/v1/{param1}").getGet().getParameters().get(0);
- assertEquals(parameter.getType(), "number");
- }
-
- @Test(description = "scan external docs on method")
- public void scanExternalDocsOnMethod() {
- Swagger swagger = getSwagger(ResourceWithExternalDocs.class);
-
- ExternalDocs externalDocsForGet = swagger.getPath("/testString").getGet().getExternalDocs();
- assertNull(externalDocsForGet);
-
- ExternalDocs externalDocsForPost = swagger.getPath("/testString").getPost().getExternalDocs();
- assertNotNull(externalDocsForPost);
- assertEquals("Test Description", externalDocsForPost.getDescription());
- assertEquals("https://swagger.io/", externalDocsForPost.getUrl());
- }
-
- private Swagger getSwagger(Class> cls) {
- return new Reader(new Swagger()).read(cls);
- }
-
- private Operation getGet(Swagger swagger, String path) {
- return swagger.getPath(path).getGet();
- }
-
- private Operation getPut(Swagger swagger, String path) {
- return swagger.getPath(path).getPut();
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/ReferenceTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/ReferenceTest.java
deleted file mode 100644
index 81506196a8..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/ReferenceTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package io.swagger;
-
-import io.swagger.converter.ModelConverters;
-import io.swagger.jaxrs.Reader;
-import io.swagger.matchers.SerializationMatchers;
-import io.swagger.models.Pet;
-import io.swagger.models.Swagger;
-import io.swagger.models.properties.Property;
-import io.swagger.models.properties.RefProperty;
-import io.swagger.resources.ResourceWithReferences;
-import io.swagger.util.ResourceUtils;
-import org.testng.annotations.Test;
-
-import java.io.IOException;
-import java.util.Map;
-
-import static org.testng.Assert.assertEquals;
-
-public class ReferenceTest {
-
- @Test(description = "Scan a model with common reference and reference with ApiModel")
- public void scanModel() {
- final Map props = ModelConverters.getInstance().readAll(Pet.class).get("Pet").getProperties();
- final RefProperty category = (RefProperty) props.get("category");
- assertEquals(category.getType(), "ref");
- assertEquals(category.get$ref(), "#/definitions/Category");
-
- final RefProperty categoryWithApiModel = (RefProperty) props.get("categoryWithApiModel");
- assertEquals(categoryWithApiModel.getType(), "ref");
- assertEquals(categoryWithApiModel.get$ref(), "#/definitions/MyCategory");
- }
-
- @Test(description = "Scan API with operation and response references")
- public void scanAPI() throws IOException {
- final Swagger swagger = new Reader(new Swagger()).read(ResourceWithReferences.class);
- final String json = ResourceUtils.loadClassResource(getClass(), "ResourceWithReferences.json");
- SerializationMatchers.assertEqualsToJson(swagger, json);
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/RegexPathParamTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/RegexPathParamTest.java
deleted file mode 100644
index a46a782ba6..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/RegexPathParamTest.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package io.swagger;
-
-import io.swagger.jaxrs.Reader;
-import io.swagger.models.Operation;
-import io.swagger.models.Swagger;
-import io.swagger.models.parameters.Parameter;
-import io.swagger.resources.RegexPathParamResource;
-import org.testng.annotations.Test;
-
-import static org.testng.Assert.assertEquals;
-
-public class RegexPathParamTest {
-
- @Test(description = "scan a simple resource")
- public void scanSimpleResource() {
- Swagger swagger = new Reader(new Swagger()).read(RegexPathParamResource.class);
- Operation get = swagger.getPaths().get("/{report_type}").getGet();
- Parameter param = get.getParameters().get(0);
- assertEquals(param.getName(), "report_type");
- assertEquals(param.getPattern(), "[aA-zZ]+");
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/ResourceTest1343.java b/modules/swagger-jaxrs/src/test/java/io/swagger/ResourceTest1343.java
deleted file mode 100644
index 0ade3985c4..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/ResourceTest1343.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package io.swagger;
-
-import io.swagger.jaxrs.Reader;
-import io.swagger.models.Swagger;
-import io.swagger.resources.Resource1343;
-import org.testng.annotations.Test;
-
-import static org.testng.Assert.assertNotNull;
-
-public class ResourceTest1343 {
- private final Reader reader = new Reader(new Swagger());
-
- private Swagger getSwagger(Class> resource) {
- return reader.read(resource);
- }
-
- @Test(description = "scan resource 1343")
- public void scanResource1343() {
- Swagger swagger = getSwagger(Resource1343.class);
- assertNotNull(swagger);
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/ResourceWithSchemeTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/ResourceWithSchemeTest.java
deleted file mode 100644
index 255a5c7aad..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/ResourceWithSchemeTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-package io.swagger;
-
-import io.swagger.jaxrs.Reader;
-import io.swagger.models.Scheme;
-import io.swagger.models.Swagger;
-import io.swagger.resources.ResourceWithScheme;
-import io.swagger.resources.ResourceWithoutScheme;
-import org.testng.annotations.Test;
-
-import java.util.Arrays;
-import java.util.List;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNull;
-
-public class ResourceWithSchemeTest {
- private final Reader reader = new Reader(new Swagger());
-
- private Swagger getSwagger(Class> resource) {
- return reader.read(resource);
- }
-
- private List loadSchemes(Swagger swagger, String path) {
- return swagger.getPaths().get(path).getGet().getSchemes();
- }
-
- @Test(description = "scan another resource with subresources")
- public void scanResourceWithSubresources() {
- Swagger swagger = getSwagger(ResourceWithScheme.class);
- assertEquals(loadSchemes(swagger, "/test/status"), Arrays.asList(Scheme.HTTPS));
- assertEquals(loadSchemes(swagger, "/test/value"), Arrays.asList(Scheme.WS, Scheme.WSS));
- assertEquals(loadSchemes(swagger, "/test/notes"), Arrays.asList(Scheme.HTTP));
- assertEquals(loadSchemes(swagger, "/test/description"), Arrays.asList(Scheme.HTTP));
- }
-
- @Test(description = "scan resource without schemes")
- public void scanResourceWithoutSchemes() {
- Swagger swagger = getSwagger(ResourceWithoutScheme.class);
- assertNull(loadSchemes(swagger, "/test/status"));
- assertNull(loadSchemes(swagger, "/test/value"));
- }
-}
-
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/SimpleReaderTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/SimpleReaderTest.java
deleted file mode 100644
index 489197ebdb..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/SimpleReaderTest.java
+++ /dev/null
@@ -1,688 +0,0 @@
-package io.swagger;
-
-import com.beust.jcommander.internal.Lists;
-import com.google.common.base.Functions;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.ImmutableMap;
-import io.swagger.jaxrs.Reader;
-import io.swagger.jaxrs.config.DefaultReaderConfig;
-import io.swagger.models.ArrayModel;
-import io.swagger.models.Model;
-import io.swagger.models.ModelImpl;
-import io.swagger.models.Operation;
-import io.swagger.models.Path;
-import io.swagger.models.RefModel;
-import io.swagger.models.Response;
-import io.swagger.models.Swagger;
-import io.swagger.models.Tag;
-import io.swagger.models.TestEnum;
-import io.swagger.models.parameters.BodyParameter;
-import io.swagger.models.parameters.Parameter;
-import io.swagger.models.parameters.PathParameter;
-import io.swagger.models.parameters.QueryParameter;
-import io.swagger.models.parameters.SerializableParameter;
-import io.swagger.models.properties.ArrayProperty;
-import io.swagger.models.properties.IntegerProperty;
-import io.swagger.models.properties.MapProperty;
-import io.swagger.models.properties.Property;
-import io.swagger.models.properties.RefProperty;
-import io.swagger.models.properties.StringProperty;
-import io.swagger.resources.ClassWithExamplePost;
-import io.swagger.resources.ClassWithExamplePostClass;
-import io.swagger.resources.HiddenResource;
-import io.swagger.resources.Issue1979Resource;
-import io.swagger.resources.NicknamedOperation;
-import io.swagger.resources.NotValidRootResource;
-import io.swagger.resources.Resource1041;
-import io.swagger.resources.Resource1073;
-import io.swagger.resources.Resource1085;
-import io.swagger.resources.Resource653;
-import io.swagger.resources.Resource841;
-import io.swagger.resources.Resource877;
-import io.swagger.resources.Resource937;
-import io.swagger.resources.ResourceWithApiOperationCode;
-import io.swagger.resources.ResourceWithApiResponseResponseContainer;
-import io.swagger.resources.ResourceWithBodyParams;
-import io.swagger.resources.ResourceWithCustomHTTPMethodAnnotations;
-import io.swagger.resources.ResourceWithEmptyModel;
-import io.swagger.resources.ResourceWithEnums;
-import io.swagger.resources.ResourceWithInnerClass;
-import io.swagger.resources.ResourceWithMapReturnValue;
-import io.swagger.resources.ResourceWithRanges;
-import io.swagger.resources.ResourceWithResponse;
-import io.swagger.resources.ResourceWithResponseHeaders;
-import io.swagger.resources.ResourceWithTypedResponses;
-import io.swagger.resources.ResourceWithVoidReturns;
-import io.swagger.resources.SimpleResource;
-import io.swagger.resources.SimpleResourceWithoutAnnotations;
-import io.swagger.resources.SimpleSelfReferencingSubResource;
-import io.swagger.resources.TaggedResource;
-import org.testng.annotations.Test;
-
-import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNotEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertNull;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
-
-public class SimpleReaderTest {
-
- private Swagger getSwagger(Class> cls) {
- return new Reader(new Swagger()).read(cls);
- }
-
- private Map getGetResponses(Swagger swagger, String path) {
- return getGet(swagger, path).getResponses();
- }
-
- private Map getPutResponses(Swagger swagger, String path) {
- return getPut(swagger, path).getResponses();
- }
-
- private List getGetParameters(Swagger swagger, String path) {
- return getGet(swagger, path).getParameters();
- }
-
- private List getPostParameters(Swagger swagger, String path) {
- return getPost(swagger, path).getParameters();
- }
-
- private List getPutParameters(Swagger swagger, String path) {
- return getPut(swagger, path).getParameters();
- }
-
- private Operation getGet(Swagger swagger, String path) {
- return swagger.getPaths().get(path).getGet();
- }
-
- private Operation getPost(Swagger swagger, String path) {
- return swagger.getPaths().get(path).getPost();
- }
-
- private Operation getPut(Swagger swagger, String path) {
- return swagger.getPaths().get(path).getPut();
- }
-
- private Operation getPatch(Swagger swagger, String path) {
- return swagger.getPaths().get(path).getPatch();
- }
-
- private Operation getDelete(Swagger swagger, String path) {
- return swagger.getPaths().get(path).getDelete();
- }
-
- @Test(description = "scan a simple resource")
- public void scanSimpleResource() {
- Swagger swagger = getSwagger(SimpleResource.class);
- assertEquals(swagger.getPaths().size(), 3);
-
- Operation get = getGet(swagger, "/{id}");
- assertNotNull(get);
- assertEquals(get.getParameters().size(), 2);
-
- PathParameter param1 = (PathParameter) get.getParameters().get(0);
- assertEquals(param1.getIn(), "path");
- assertEquals(param1.getName(), "id");
- assertTrue(param1.getRequired());
- assertEquals(param1.getDescription(), "sample param data");
- assertEquals(param1.getDefaultValue(), "5");
-
- Parameter param2 = get.getParameters().get(1);
- assertEquals(param2.getIn(), "query");
- assertEquals(param2.getName(), "limit");
- assertFalse(param2.getRequired());
- assertNull(param2.getDescription());
-
- List params = getPutParameters(swagger, "/{bodyparams}");
- BodyParameter bodyParam1 = (BodyParameter) params.get(0);
- assertEquals(bodyParam1.getIn(), "body");
- assertEquals(bodyParam1.getName(), "body");
- assertTrue(bodyParam1.getRequired());
-
- BodyParameter bodyParam2 = (BodyParameter) params.get(1);
- assertEquals(bodyParam2.getIn(), "body");
- assertEquals(bodyParam2.getName(), "body");
- assertFalse(bodyParam2.getRequired());
- }
-
- @Test(description = "scan a resource with custom http method annotations")
- public void scanResourceWithCustomHttpMethodAnnotations() {
- Swagger swagger = getSwagger(ResourceWithCustomHTTPMethodAnnotations.class);
-
- Operation get = getGet(swagger, "/");
- assertNotNull(get);
-
- Operation post = getPost(swagger, "/");
- assertNotNull(post);
-
- Operation patch = getPatch(swagger, "/");
- assertNotNull(patch);
-
- Operation put = getPut(swagger, "/");
- assertNotNull(put);
-
- Operation delete = getDelete(swagger, "/");
- assertNotNull(delete);
- }
-
- @Test(description = "scan a resource with void return type")
- public void scanResourceWithVoidReturnType() {
- Swagger swagger = getSwagger(ResourceWithVoidReturns.class);
- assertEquals(swagger.getDefinitions().size(), 1);
- assertNotNull(swagger.getDefinitions().get("NotFoundModel"));
- }
-
- @Test(description = "scan a resource with map return type")
- public void scanResourceWithMapReturnType() {
- Swagger swagger = getSwagger(ResourceWithMapReturnValue.class);
-
- Operation get = getGet(swagger, "/{id}");
- assertNotNull(get);
- assertNotNull(get.getResponses());
-
- Response response = get.getResponses().get("200");
- assertNotNull(response);
-
- Property schema = response.getSchema();
- assertEquals(schema.getClass(), MapProperty.class);
- }
-
- @Test(description = "scan a resource with generics per 653")
- public void scanResourceWithGenerics() {
- Swagger swagger = getSwagger(Resource653.class);
- Operation get = getGet(swagger, "/external/info");
- assertNotNull(get);
-
- Map responses = get.getResponses();
- assertNotNull(responses);
-
- Response response = responses.get("default");
- assertNotNull(response);
- assertNull(response.getSchema());
- }
-
- @Test(description = "scan a resource with javax.ws.core.Response ")
- public void scanResourceWithResponse() {
- assertNull(getSwagger(ResourceWithResponse.class).getDefinitions());
- }
-
- @Test(description = "scan a resource with Response.Status return type per 877")
- public void scanResourceWithResponseStatusReturnType() {
- Swagger swagger = getSwagger(Resource877.class);
-
- assertNotNull(swagger.getTags());
- assertEquals(swagger.getTags().size(), 1);
-
- Tag tag = swagger.getTags().get(0);
- assertEquals(tag.getName(), "externalinfo");
- assertNull(tag.getDescription());
- assertNull(tag.getExternalDocs());
- }
-
- @Test(description = "scan a resource with tags")
- public void scanResourceWithApiTags() {
- assertEquals(getSwagger(TaggedResource.class).getTags().size(), 2);
- }
-
- @Test(description = "scan a resource with tags in test 841")
- public void scanResourceWithApiOperationTags() {
- Swagger swagger = getSwagger(Resource841.class);
- assertEquals(swagger.getTags().size(), 3);
-
- List rootTags = getGet(swagger, "/fun").getTags();
- assertEquals(rootTags.size(), 2);
- assertEquals(rootTags, Arrays.asList("tag1", "tag2"));
-
- List thisTags = getGet(swagger, "/fun/this").getTags();
- assertEquals(thisTags.size(), 1);
- assertEquals(thisTags, Arrays.asList("tag1"));
-
- List thatTags = getGet(swagger, "/fun/that").getTags();
- assertEquals(thatTags.size(), 1);
- assertEquals(thatTags, Arrays.asList("tag2"));
- }
-
- @Test(description = "scan a resource with param enums")
- public void scanResourceWithParamEnums() {
- Swagger swagger = getSwagger(ResourceWithEnums.class);
- SerializableParameter param = (SerializableParameter) getGetParameters(swagger, "/{id}").get(2);
- List _enum = param.getEnum();
- assertEquals(_enum, Arrays.asList("a", "b", "c", "d", "e"));
-
- List checkEnumHandling = getGetParameters(swagger, "/checkEnumHandling/{v0}");
- List allEnumValues = Lists.newArrayList(Collections2.transform(Arrays.asList(TestEnum.values()), Functions.toStringFunction()));
- SerializableParameter v0 = (SerializableParameter) checkEnumHandling.get(0);
- assertEquals(v0.getEnum(), allEnumValues);
- SerializableParameter v1 = (SerializableParameter) checkEnumHandling.get(1);
- assertEquals(((StringProperty) v1.getItems()).getEnum(), allEnumValues);
- SerializableParameter v2 = (SerializableParameter) checkEnumHandling.get(2);
- assertEquals(((StringProperty) v2.getItems()).getEnum(), allEnumValues);
- SerializableParameter v3 = (SerializableParameter) checkEnumHandling.get(3);
- assertEquals(v3.getEnum(), Arrays.asList("A", "B", "C"));
- }
-
- @Test(description = "scan a resource with param range")
- public void scanResourceWithParamRange() {
- Swagger swagger = getSwagger(ResourceWithRanges.class);
- List params = getGetParameters(swagger, "/{id}");
-
- PathParameter param0 = (PathParameter) params.get(0);
- assertEquals(param0.getName(), "id");
- assertEquals(param0.getDefaultValue(), 5);
- assertEquals(param0.getMinimum(), new BigDecimal(0.0));
- assertEquals(param0.getMaximum(), new BigDecimal(10.0));
-
- PathParameter param1 = (PathParameter) params.get(1);
- assertEquals(param1.getName(), "minValue");
- assertEquals(param1.getMinimum(), new BigDecimal(0.0));
- assertNull(param1.getMaximum(), null);
-
- PathParameter param2 = (PathParameter) params.get(2);
- assertEquals(param2.getName(), "maxValue");
- assertNull(param2.getMinimum());
- assertEquals(param2.getMaximum(), new BigDecimal(100.0));
-
- PathParameter param3 = (PathParameter) params.get(3);
- assertEquals(param3.getName(), "values");
- IntegerProperty items = (IntegerProperty) param3.getItems();
- assertEquals(items.getMinimum(), new BigDecimal(0.0));
- assertEquals(items.getMaximum(), new BigDecimal(5.0));
- assertEquals(items.getExclusiveMinimum(), Boolean.TRUE);
- assertEquals(items.getExclusiveMaximum(), Boolean.TRUE);
- }
-
- @Test(description = "scan a resource with response headers")
- public void scanResourceWithResponseHeaders() {
- Swagger swagger = getSwagger(ResourceWithResponseHeaders.class);
- Map responses = getGetResponses(swagger, "/{id}");
- Map headers200 = responses.get("200").getHeaders();
- assertEquals(headers200.size(), 1);
- assertEquals(headers200.get("foo").getDescription(), "description");
- assertEquals(headers200.get("foo").getType(), "string");
-
- Map headers400 = responses.get("400").getHeaders();
- assertEquals(headers400.size(), 2);
- assertEquals(headers400.get("X-Rack-Cache").getDescription(), "Explains whether or not a cache was used");
- assertEquals(headers400.get("X-Rack-Cache").getType(), "boolean");
-
- Iterator keyItr = headers400.keySet().iterator();
- assertEquals(keyItr.next(), "X-Rack-Cache");
- assertEquals(keyItr.next(), "X-After-Rack-Cache");
- }
-
- @Test(description = "not scan a hidden resource")
- public void notScanHiddenResource() {
- assertNull(getSwagger(HiddenResource.class).getPaths());
- }
-
- @Test(description = "not scan a resource without @Api annotation")
- public void notScanNotValidRootResourcee() {
- assertNull(getSwagger(NotValidRootResource.class).getPaths());
- }
-
- @Test(description = "correctly model an empty model per 499")
- public void scanResourceWithEmptyModel() {
- Map definitions = getSwagger(ResourceWithEmptyModel.class).getDefinitions();
- assertEquals(definitions.size(), 1);
- ModelImpl empty = (ModelImpl) definitions.get("EmptyModel");
- assertEquals(empty.getType(), "object");
- assertNull(empty.getProperties());
- assertNull(empty.getAdditionalProperties(), null);
- }
-
- @Test(description = "scan a simple resource without annotations")
- public void scanSimpleResourceWithoutAnnotations() {
- DefaultReaderConfig config = new DefaultReaderConfig();
- config.setScanAllResources(true);
- Swagger swagger = new Reader(new Swagger(), config).read(SimpleResourceWithoutAnnotations.class);
- assertEquals(swagger.getPaths().size(), 2);
-
- Operation get = getGet(swagger, "/{id}");
- assertNotNull(get);
- assertEquals(get.getParameters().size(), 2);
-
- PathParameter param1 = (PathParameter) get.getParameters().get(0);
- assertEquals(param1.getIn(), "path");
- assertEquals(param1.getName(), "id");
- assertTrue(param1.getRequired());
- assertNull(param1.getDescription());
- assertEquals(param1.getDefaultValue(), "5");
-
- Parameter param2 = get.getParameters().get(1);
- assertEquals(param2.getIn(), "query");
- assertEquals(param2.getName(), "limit");
- assertFalse(param2.getRequired());
- assertNull(param2.getDescription());
- }
-
- @Test(description = "scan a simple self-referencing subresource")
- public void scanSimpleSelfReferencingSubResource() {
- DefaultReaderConfig config = new DefaultReaderConfig();
- config.setScanAllResources(true);
- Swagger swagger = new Reader(new Swagger(), config).read(SimpleSelfReferencingSubResource.class);
-
- assertEquals(swagger.getPaths().size(), 4);
-
- // these two paths are directly reachable without passing thru a recursive reference
- Operation retrieve = getGet(swagger, "/sub");
- assertNotNull(retrieve);
- assertEquals(retrieve.getParameters().size(), 0);
-
- retrieve = getGet(swagger, "/sub/leaf");
- assertNotNull(retrieve);
- assertEquals(retrieve.getParameters().size(), 0);
-
- retrieve = getGet(swagger, "/sub/recurse2");
- assertNotNull(retrieve);
- assertEquals(retrieve.getParameters().size(), 0);
-
- retrieve = getGet(swagger, "/sub/recurse2/leaf");
- assertNotNull(retrieve);
- assertEquals(retrieve.getParameters().size(), 0);
- }
-
- @Test(description = "scan resource with ApiOperation.code() value")
- public void scanResourceWithApiOperationCodeValue() {
- Swagger swagger = getSwagger(ResourceWithApiOperationCode.class);
- Map responses1 = getGetResponses(swagger, "/{id}");
- assertEquals(responses1.size(), 3);
- assertTrue(responses1.containsKey("202"));
- assertFalse(responses1.containsKey("200"));
- assertEquals(responses1.get("202").getDescription(), "successful operation");
-
- Map responses2 = getPutResponses(swagger, "/{id}");
- assertEquals(responses2.size(), 3);
- assertTrue(responses2.containsKey("200"));
- assertEquals(responses2.get("200").getDescription(), "successful operation");
- }
-
- @Test(description = "scan resource with ApiResponse.responseContainer() value")
- public void scanResourceWithApiResponseResponseContainerValue() {
- Swagger swagger = getSwagger(ResourceWithApiResponseResponseContainer.class);
- Path paths = swagger.getPaths().get("/{id}");
- Map responses1 = paths.getGet().getResponses();
- assertEquals(responses1.get("200").getSchema().getClass(), MapProperty.class);
- assertEquals(responses1.get("400").getSchema().getClass(), ArrayProperty.class);
-
- Map responses2 = paths.getPut().getResponses();
- assertEquals(responses2.get("201").getSchema().getClass(), RefProperty.class);
- assertEquals(responses2.get("401").getSchema().getClass(), ArrayProperty.class);
-
- Map responses3 = paths.getPost().getResponses();
- assertEquals(responses3.get("202").getSchema().getClass(), RefProperty.class);
- assertEquals(responses3.get("402").getSchema().getClass(), RefProperty.class);
-
- Map responses4 = paths.getDelete().getResponses();
- assertEquals(responses4.get("203").getSchema().getClass(), RefProperty.class);
- assertEquals(responses4.get("403").getSchema().getClass(), RefProperty.class);
-
- Path paths2 = swagger.getPaths().get("/{id}/name");
- Map responses5 = paths2.getGet().getResponses();
- assertEquals(responses5.get("203").getSchema().getClass(), ArrayProperty.class);
- assertNull(((ArrayProperty) responses5.get("203").getSchema()).getUniqueItems());
- assertNotEquals(responses5.get("203").getHeaders().get("foo").getClass(), MapProperty.class);
- assertEquals(responses5.get("403").getSchema().getClass(), ArrayProperty.class);
- assertEquals(((ArrayProperty) responses5.get("403").getSchema()).getUniqueItems(), Boolean.TRUE);
-
- Map responses6 = paths2.getPut().getResponses();
- assertEquals(responses6.get("203").getSchema().getClass(), ArrayProperty.class);
- assertEquals(((ArrayProperty) responses6.get("203").getSchema()).getUniqueItems(), Boolean.TRUE);
- assertEquals(responses6.get("203").getHeaders().get("foo").getClass(), ArrayProperty.class);
- assertEquals(((ArrayProperty) responses6.get("203").getHeaders().get("foo")).getUniqueItems(), Boolean.TRUE);
- assertEquals(responses6.get("403").getSchema().getClass(), ArrayProperty.class);
- }
-
- @Test(description = "scan a resource with inner class")
- public void scanResourceWithInnerClass() {
- Swagger swagger = getSwagger(ResourceWithInnerClass.class);
- assertEquals(((RefProperty) ((ArrayProperty) getGetResponses(swagger, "/description").get("200").getSchema()).
- getItems()).get$ref(), "#/definitions/Description");
- assertTrue(swagger.getDefinitions().containsKey("Description"));
- }
-
- @Test(description = "scan defaultValue and required per #937")
- public void scanDefaultValueAndRequiredOptions() {
- Swagger swagger = getSwagger(Resource937.class);
- QueryParameter param = (QueryParameter) getGetParameters(swagger, "/external/info").get(0);
- assertFalse(param.getRequired());
- assertEquals(param.getDefaultValue(), "dogs");
- }
-
- @Test(description = "scan a resource with all hidden values #1073")
- public void scanResourceWithAllHiddenValues() {
- assertNull(getSwagger(Resource1073.class).getPaths());
- }
-
- @Test(description = "scan a resource with body parameters")
- public void scanResourceWithBodyParameters() {
- Swagger swagger = getSwagger(ResourceWithBodyParams.class);
- BodyParameter param = (BodyParameter) getPostParameters(swagger, "/testShort").get(0);
- assertEquals(param.getDescription(), "a short input");
-
- ModelImpl schema = (ModelImpl) param.getSchema();
- assertEquals(schema.getType(), "integer");
- assertEquals(schema.getFormat(), "int32");
-
- assertEquals(swagger.getDefinitions().keySet(), Arrays.asList("Tag"));
-
- testString(swagger, "/testApiString", "input", "String parameter");
- testString(swagger, "/testString", "body", null);
-
- testObject(swagger, "/testApiObject", "input", "Object parameter");
- testObject(swagger, "/testObject", "body", null);
-
- List operations = new ArrayList();
- for (Path item : swagger.getPaths().values()) {
- Operation op = item.getPost();
- if (op.getOperationId().startsWith("testPrimitive")) {
- operations.add(op);
- }
- }
- assertEquals(operations.size(), 16);
- for (Operation item : operations) {
- assertEquals(item.getParameters().size(), 1);
- }
- }
-
- private Model testParam(Swagger swagger, String path, String name, String description) {
- BodyParameter param = (BodyParameter) getPostParameters(swagger, path).get(0);
- assertEquals(param.getIn(), "body");
- assertEquals(param.getName(), name);
- assertEquals(param.getDescription(), description);
- return param.getSchema();
- }
-
- private void testString(Swagger swagger, String path, String name, String description) {
- assertEquals(((ModelImpl) testParam(swagger, path, name, description)).getType(), "string");
- }
-
- private void testObject(Swagger swagger, String path, String name, String description) {
- assertEquals(((RefModel) testParam(swagger, path, name, description)).getSimpleRef(), "Tag");
- }
-
- @Test(description = "verify top-level path params per #1085")
- public void verifyTopLevelPathParams() {
- Swagger swagger = getSwagger(Resource1085.class);
- Parameter param = getGetParameters(swagger, "/external/info/{id}").get(0);
- assertEquals(param.getName(), "id");
- assertTrue(param instanceof PathParameter);
- }
-
- @Test(description = "verify top-level auth #1041")
- public void verifyTopLevelAuthorization() {
- Swagger swagger = getSwagger(Resource1041.class);
- Operation path1 = getGet(swagger, "/external/info/path1");
- List>> security1 = path1.getSecurity();
- assertEquals(security1.size(), 1);
- assertNotNull(security1.get(0).get("my_auth"));
-
- Operation path2 = getGet(swagger, "/external/info/path2");
- List>> security2 = path2.getSecurity();
- assertEquals(security2.size(), 1);
- assertNotNull(security2.get(0).get("your_auth"));
- }
-
- @Test(description = "check response models processing")
- public void checkResponseModelsProcessing() {
- Swagger swagger = getSwagger(ResourceWithTypedResponses.class);
- assertEquals(swagger.getDefinitions().keySet(), Arrays.asList("Tag"));
- for (Map.Entry entry : swagger.getPaths().entrySet()) {
- String name = entry.getKey().substring(entry.getKey().lastIndexOf("/") + 1);
- if ("testPrimitiveResponses".equals(name)) {
- Map expected = ImmutableMap.of("400", new String[]{"string", "uri"},
- "401", new String[]{"string", "url"},
- "402", new String[]{"string", "uuid"},
- "403", new String[]{"integer", "int64"},
- "404", new String[]{"string", null});
- assertEquals(entry.getValue().getGet().getResponses().size(), expected.size());
- for (Map.Entry responseEntry : entry.getValue().getGet().getResponses().entrySet()) {
- String[] expectedProp = expected.get(responseEntry.getKey());
- Property property = responseEntry.getValue().getSchema();
- assertEquals(property.getType(), expectedProp[0]);
- assertEquals(property.getFormat(), expectedProp[1]);
- }
- } else {
- Operation op = entry.getValue().getGet();
- Property response = op.getResponses().get("200").getSchema();
- Model model = ((BodyParameter) op.getParameters().get(0)).getSchema();
- assertEquals(op.getParameters().size(), 1);
-
- if ("testObjectResponse".equals(name)) {
- assertEquals(((RefProperty) response).getSimpleRef(), "Tag");
- assertEquals(((RefModel) model).getSimpleRef(), "Tag");
- } else if ("testObjectsResponse".equals(name)) {
- assertEquals(((RefProperty) ((ArrayProperty) response).getItems()).getSimpleRef(), "Tag");
- assertEquals(((RefProperty) ((ArrayModel) model).getItems()).getSimpleRef(), "Tag");
- } else if ("testStringResponse".equals(name)) {
- assertEquals(response.getClass(), StringProperty.class);
- assertEquals(((ModelImpl) model).getType(), "string");
- } else if ("testStringsResponse".equals(name)) {
- assertEquals(((ArrayProperty) response).getItems().getClass(), StringProperty.class);
- assertEquals(((ArrayModel) model).getItems().getClass(), StringProperty.class);
- } else if ("testMapResponse".equals(name)) {
- assertEquals(((RefProperty) ((MapProperty) response).getAdditionalProperties()).getSimpleRef(), "Tag");
- assertNull(model.getProperties());
- assertEquals(((RefProperty) ((ModelImpl) model).getAdditionalProperties()).getSimpleRef(), "Tag");
- } else {
- fail(String.format("Unexpected property: %s", name));
- }
- }
- }
- }
-
- @Test(description = "scan a resource with custom operation nickname")
- public void scanResourceWithApiOperationNickname() {
- Swagger swagger = getSwagger(NicknamedOperation.class);
- assertEquals(swagger.getPaths().size(), 1);
-
- assertNotNull(swagger.getPaths().get("/external/info"));
-
- Operation op = swagger.getPaths().get("/external/info").getGet();
- assertNotNull(op);
-
- assertEquals(op.getOperationId(), "getMyNicknameTest");
- }
-
- @Test(description = "scan a resource with operation post example")
- public void scanClassWithExamplePost() {
- Swagger swagger = getSwagger(ClassWithExamplePost.class);
- Parameter param = swagger.getPaths().get("/external/info").getPost().getParameters().get(0);
- BodyParameter bp = (BodyParameter) param;
- assertNotNull(bp.getExamples());
- assertTrue(bp.getExamples().size() == 1);
- String value = bp.getExamples().get("application/json");
- assertEquals("[\"a\",\"b\"]", value);
- }
-
- @Test(description = "scan a resource with operation implicit post example")
- public void scanClassWithImplicitExamplePost() {
- Swagger swagger = getSwagger(ClassWithExamplePost.class);
- Parameter param = swagger.getPaths().get("/external/info2").getPost().getParameters().get(0);
- BodyParameter bp = (BodyParameter) param;
- assertNotNull(bp.getExamples());
- assertTrue(bp.getExamples().size() == 1);
- String value = bp.getExamples().get("application/json");
- assertEquals("[\"a\",\"b\"]", value);
- }
-
- @Test(description = "scan a resource with query param example")
- public void scanClassWithExampleQuery() {
- Swagger swagger = getSwagger(ClassWithExamplePost.class);
- Parameter param = swagger.getPaths().get("/external/info").getGet().getParameters().get(0);
- QueryParameter bp = (QueryParameter) param;
- assertNotNull(bp.getExample());
- Object value = bp.getExample();
- assertEquals("a,b,c", value);
- }
-
- @Test(description = "scan a resource with implicit operation query example")
- public void scanClassWithImplicitExampleQuery() {
- Swagger swagger = getSwagger(ClassWithExamplePost.class);
- Parameter param = swagger.getPaths().get("/external/info2").getGet().getParameters().get(0);
- QueryParameter bp = (QueryParameter) param;
- assertNotNull(bp.getExample());
- Object value = bp.getExample();
- assertEquals("77", value);
- }
-
- @Test(description = "scan a resource with operation post example (dataTypeClass)")
- public void scanClassWithExamplePostClass() {
- Swagger swagger = getSwagger(ClassWithExamplePostClass.class);
- Parameter param = swagger.getPaths().get("/external/info").getPost().getParameters().get(0);
- BodyParameter bp = (BodyParameter) param;
- assertNotNull(bp.getExamples());
- assertTrue(bp.getExamples().size() == 1);
- String value = bp.getExamples().get("application/json");
- assertEquals("[\"a\",\"b\"]", value);
- }
-
- @Test(description = "scan a resource with operation implicit post example (dataTypeClass)")
- public void scanClassWithImplicitExamplePostClass() {
- Swagger swagger = getSwagger(ClassWithExamplePostClass.class);
- Parameter param = swagger.getPaths().get("/external/info2").getPost().getParameters().get(0);
- BodyParameter bp = (BodyParameter) param;
- assertNotNull(bp.getExamples());
- assertTrue(bp.getExamples().size() == 1);
- String value = bp.getExamples().get("application/json");
- assertEquals("[\"a\",\"b\"]", value);
- }
-
- @Test(description = "scan a resource with query param example (dataTypeClass)")
- public void scanClassWithExampleClassQuery() {
- Swagger swagger = getSwagger(ClassWithExamplePostClass.class);
- Parameter param = swagger.getPaths().get("/external/info").getGet().getParameters().get(0);
- QueryParameter bp = (QueryParameter) param;
- assertNotNull(bp.getExample());
- Object value = bp.getExample();
- assertEquals("a,b,c", value);
- }
-
- @Test(description = "scan a resource with implicit operation query example (dataTypeClass)")
- public void scanClassWithImplicitExampleClassQuery() {
- Swagger swagger = getSwagger(ClassWithExamplePostClass.class);
- Parameter param = swagger.getPaths().get("/external/info2").getGet().getParameters().get(0);
- QueryParameter bp = (QueryParameter) param;
- assertNotNull(bp.getExample());
- Object value = bp.getExample();
- assertEquals("77", value);
- }
-
- @Test(description = "scan a resource with read-only and empty value parameters")
- public void scanClassWithReadOnlyAndEmptyValueParams() {
- Swagger swagger = getSwagger(Issue1979Resource.class);
- Parameter readOnlyParam = swagger.getPath("/fun/readOnly").getGet().getParameters().get(0);
- assertTrue(readOnlyParam.isReadOnly());
-
- Parameter allowEmptyParam = swagger.getPath("/fun/allowEmpty").getGet().getParameters().get(0);
- assertTrue(allowEmptyParam.getAllowEmptyValue());
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/SimpleScannerWithDecoratorExtensionTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/SimpleScannerWithDecoratorExtensionTest.java
deleted file mode 100644
index 6b64cfbc40..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/SimpleScannerWithDecoratorExtensionTest.java
+++ /dev/null
@@ -1,104 +0,0 @@
-package io.swagger;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertNull;
-import io.swagger.jaxrs.Reader;
-import io.swagger.jaxrs.ext.AbstractSwaggerExtension;
-import io.swagger.jaxrs.ext.SwaggerExtension;
-import io.swagger.jaxrs.ext.SwaggerExtensions;
-import io.swagger.models.Operation;
-import io.swagger.models.Response;
-import io.swagger.models.Swagger;
-import io.swagger.resources.SimpleResourceWithVendorAnnotation;
-import io.swagger.resources.SimpleResourceWithVendorAnnotation.VendorFunnyAnnotation;
-
-import java.lang.reflect.Method;
-import java.util.Iterator;
-
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-/**
- * Scanner example for custom operation decorator extension.
- */
-public class SimpleScannerWithDecoratorExtensionTest {
-
- private static final String RESPONSE_DESCRIPTION = "Some vendor error description";
-
- private static final String RESPONSE_STATUS_401 = "401";
-
- private static final SwaggerExtension customExtension = new AbstractSwaggerExtension() {
-
- @Override
- public void decorateOperation(final Operation operation, final Method method, final Iterator chain) {
- method.getDeclaredAnnotations();
- final VendorFunnyAnnotation myFunyError = method.getAnnotation(SimpleResourceWithVendorAnnotation.VendorFunnyAnnotation.class);
- if (myFunyError != null) {
- /*
- * Extend swagger model by new error response description, with additional data received from vendor
- * based annotation. This example overwrite existing response from swagger annotation, but it is only
- * for demo.
- */
- final Response value = new Response();
- value.setDescription(RESPONSE_DESCRIPTION);
- operation.getResponses().put(RESPONSE_STATUS_401, value);
- }
- }
- };
-
- private Swagger getSwagger(final Class> cls) {
- return new Reader(new Swagger()).read(cls);
- }
-
- private Operation getGet(final Swagger swagger, final String path) {
- return swagger.getPaths().get(path).getGet();
- }
-
- @BeforeMethod()
- public void addCustomExtension() {
- SwaggerExtensions.getExtensions().add(customExtension);
- }
-
- @AfterMethod()
- public void removeCustomExtension() {
- SwaggerExtensions.getExtensions().remove(customExtension);
- }
-
- /**
- * Test for method annotated with vendor annotation which could be used for swagger documentation.
- */
- @Test(description = "scan a simple resource with custom decorator")
- public void scanSimpleResourceWithDecorator() {
- final Swagger swagger = getSwagger(SimpleResourceWithVendorAnnotation.class);
-
- assertEquals(swagger.getPaths().size(), 2);
-
- final Operation get = getGet(swagger, "/{id}");
- assertNotNull(get);
- assertEquals(get.getParameters().size(), 2);
-
- final Response response = get.getResponses().get(RESPONSE_STATUS_401);
- assertNotNull(response);
- assertEquals(response.getDescription(), RESPONSE_DESCRIPTION);
- }
-
- /**
- * Test for method annotated without vendor annotation.
- */
- @Test(description = "scan a simple resource without custom decorator")
- public void scanSimpleResourceWithoutDecorator() {
- final Swagger swagger = getSwagger(SimpleResourceWithVendorAnnotation.class);
-
- assertEquals(swagger.getPaths().size(), 2);
-
- final Operation get = getGet(swagger, "/{id}/value");
- assertNotNull(get);
- assertEquals(get.getParameters().size(), 0);
-
- final Response response = get.getResponses().get(RESPONSE_STATUS_401);
- assertNull(response);
- }
-
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/SubResourceReaderTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/SubResourceReaderTest.java
deleted file mode 100644
index d1a38b8d40..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/SubResourceReaderTest.java
+++ /dev/null
@@ -1,73 +0,0 @@
-package io.swagger;
-
-import io.swagger.jaxrs.Reader;
-import io.swagger.models.Operation;
-import io.swagger.models.Swagger;
-import io.swagger.models.parameters.BodyParameter;
-import io.swagger.models.parameters.Parameter;
-import io.swagger.resources.Resource942;
-import io.swagger.resources.ResourceWithSubResources;
-import io.swagger.resources.SubResourceHead;
-import io.swagger.resources.TestResource;
-import org.testng.annotations.Test;
-
-import java.util.Arrays;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-public class SubResourceReaderTest {
-
- @Test(description = "scan a resource with subresources")
- public void readResourceWithSubresources() {
- final Swagger swagger = getSwagger(ResourceWithSubResources.class);
- assertEquals(getOperationId(swagger, "/employees/{id}"), "getAllEmployees");
- assertEquals(getOperationId(swagger, "/employees/{id}/{id}"), "getSubresourceOperation");
- assertEquals(getOperationId(swagger, "/employees/noPath"), "getGreeting");
- }
-
- @Test(description = "scan another resource with subresources")
- public void readAnotherResourceWithSubresources() {
- final Swagger swagger = getSwagger(TestResource.class);
- final Operation get = getGet(swagger, "/test/more/otherStatus");
- assertEquals(get.getOperationId(), "otherStatus");
-
- final Parameter qp = get.getParameters().get(0);
- assertEquals(qp.getIn(), "query");
- assertEquals(qp.getName(), "qp");
-
- assertTrue(get.getProduces().containsAll(Arrays.asList("application/json", "application/xml")));
-
- assertEquals(swagger.getPaths().keySet().size(), 2);
- }
-
- @Test(description = "scan resource with class-based sub-resources")
- public void readResourceWithClassBasedSubresources() {
- final Swagger swagger = getSwagger(SubResourceHead.class);
- assertEquals(swagger.getPaths().size(), 3);
- assertEquals(getOperationId(swagger, "/head/noPath"), "getGreeting");
- assertEquals(getOperationId(swagger, "/head/tail/hello"), "getGreeting");
-
- final Operation echo = getGet(swagger, "/head/tail/{string}");
- assertEquals(echo.getOperationId(), "getEcho");
- assertEquals(echo.getParameters().size(), 1);
- }
-
- @Test(description = "find a body param")
- public void findBodyParam() {
- Swagger swagger = getSwagger(Resource942.class);
- assertTrue(swagger.getPath("/test").getPost().getParameters().get(0) instanceof BodyParameter);
- }
-
- private Swagger getSwagger(Class> cls) {
- return new Reader(new Swagger()).read(cls);
- }
-
- private Operation getGet(Swagger swagger, String path) {
- return swagger.getPaths().get(path).getGet();
- }
-
- private String getOperationId(Swagger swagger, String path) {
- return getGet(swagger, path).getOperationId();
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/SwaggerConfigLocatorTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/SwaggerConfigLocatorTest.java
deleted file mode 100644
index 2b81d197ad..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/SwaggerConfigLocatorTest.java
+++ /dev/null
@@ -1,64 +0,0 @@
-package io.swagger;
-
-import io.swagger.config.SwaggerConfig;
-import io.swagger.jaxrs.config.SwaggerConfigLocator;
-import io.swagger.models.Swagger;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import java.util.UUID;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotEquals;
-
-public class SwaggerConfigLocatorTest {
-
- String id = UUID.randomUUID().toString() + System.currentTimeMillis();
-
- @BeforeMethod
- public void setId() {
- id = UUID.randomUUID().toString() + System.currentTimeMillis();
- }
-
- @Test(description = "should add given config to map ")
- public void putConfigFirstTime() {
-
- SwaggerConfig config = new SwaggerConfig() {
- @Override
- public Swagger configure(Swagger swagger) {
- return swagger;
- }
-
- @Override
- public String getFilterClass() {
- return null;
- }
- };
-
- SwaggerConfigLocator.getInstance().putConfig(id, config);
- assertEquals(SwaggerConfigLocator.getInstance().getConfig(id), config);
-
- }
-
- @Test(description = "shouldn't add given config to map because already set")
- public void putConfigSecondTime() {
-
- putConfigFirstTime();
-
- SwaggerConfig config = new SwaggerConfig() {
- @Override
- public Swagger configure(Swagger swagger) {
- return swagger;
- }
-
- @Override
- public String getFilterClass() {
- return null;
- }
- };
-
- SwaggerConfigLocator.getInstance().putConfig(id, config);
- assertNotEquals(SwaggerConfigLocator.getInstance().getConfig(id), config);
-
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/SwaggerContextServiceTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/SwaggerContextServiceTest.java
deleted file mode 100644
index 6978d7d8e6..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/SwaggerContextServiceTest.java
+++ /dev/null
@@ -1,316 +0,0 @@
-package io.swagger;
-
-import io.swagger.config.Scanner;
-import io.swagger.config.ScannerFactory;
-import io.swagger.jaxrs.config.BeanConfig;
-import io.swagger.jaxrs.config.DefaultJaxrsScanner;
-import io.swagger.jaxrs.config.SwaggerConfigLocator;
-import io.swagger.jaxrs.config.SwaggerContextService;
-import io.swagger.jaxrs.config.SwaggerScannerLocator;
-import io.swagger.jaxrs.config.WebXMLReader;
-import io.swagger.models.Info;
-import io.swagger.models.Swagger;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-
-import static io.swagger.jaxrs.config.SwaggerContextService.*;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.*;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
-
-public class SwaggerContextServiceTest {
- private ServletContext servletContext1;
- private ServletConfig servletConfig1;
- private ServletContext servletContext2;
- private ServletConfig servletConfig2;
- private Scanner beanConfigScanner1;
- private Scanner beanConfigScanner2;
- private Scanner jaxrsScanner;
-
- @BeforeMethod
- void initMock() {
- servletContext1 = mock(ServletContext.class);
- servletConfig1 = mock(ServletConfig.class);
- servletContext2 = mock(ServletContext.class);
- servletConfig2 = mock(ServletConfig.class);
-
- jaxrsScanner = new DefaultJaxrsScanner();
-
- BeanConfig bc = new BeanConfig();
- bc.setDescription("Bean Config test 1");
- beanConfigScanner1 = bc;
-
- bc = new BeanConfig();
- bc.setDescription("Bean Config test 2");
- beanConfigScanner2 = bc;
- }
-
- void stubWithPathBasedConfigInitParam() {
-
- when(servletContext1.getAttribute(SCANNER_ID_PREFIX + "/url1")).thenReturn(beanConfigScanner1);
- when(servletContext2.getAttribute(SCANNER_ID_PREFIX + "/url2")).thenReturn(beanConfigScanner2);
-
- when(servletConfig1.getServletContext()).thenReturn(servletContext1);
- when(servletConfig2.getServletContext()).thenReturn(servletContext2);
-
- when(servletConfig1.getInitParameter(USE_PATH_BASED_CONFIG)).thenReturn("true");
- when(servletConfig2.getInitParameter(USE_PATH_BASED_CONFIG)).thenReturn("true");
- }
-
- private void stubWithInitParam() {
- when(servletContext1.getAttribute(SCANNER_ID_PREFIX + "test.1")).thenReturn(beanConfigScanner1);
- when(servletContext2.getAttribute(SCANNER_ID_PREFIX + "test.2")).thenReturn(beanConfigScanner2);
-
- when(servletConfig1.getServletContext()).thenReturn(servletContext1);
- when(servletConfig2.getServletContext()).thenReturn(servletContext2);
-
- when(servletConfig1.getInitParameter(SCANNER_ID_KEY)).thenReturn("test.1");
- when(servletConfig2.getInitParameter(SCANNER_ID_KEY)).thenReturn("test.2");
-
- when(servletConfig1.getInitParameter(CONFIG_ID_KEY)).thenReturn("test.1");
- when(servletConfig2.getInitParameter(CONFIG_ID_KEY)).thenReturn("test.2");
-
- }
-
- private void stubWithContextInitParam() {
- when(servletContext1.getAttribute(SCANNER_ID_PREFIX + "test.1")).thenReturn(beanConfigScanner1);
- when(servletContext2.getAttribute(SCANNER_ID_PREFIX + "test.2")).thenReturn(beanConfigScanner2);
-
- when(servletConfig1.getServletContext()).thenReturn(servletContext1);
- when(servletConfig2.getServletContext()).thenReturn(servletContext2);
-
- when(servletConfig1.getInitParameter(CONTEXT_ID_KEY)).thenReturn("test.1");
- when(servletConfig2.getInitParameter(CONTEXT_ID_KEY)).thenReturn("test.2");
-
- }
-
- private void stubWithoutInitParam() {
- when(servletContext1.getAttribute(SCANNER_ID_DEFAULT)).thenReturn(jaxrsScanner);
- when(servletContext2.getAttribute(SCANNER_ID_DEFAULT)).thenReturn(jaxrsScanner);
-
- when(servletConfig1.getServletContext()).thenReturn(servletContext1);
- when(servletConfig2.getServletContext()).thenReturn(servletContext2);
-
- }
-
- @Test(description = "should add servletContext attributes SCANNER_ID_PREFIX + \"test.1/2")
- public void initializeScannerWithInitParam() {
- stubWithInitParam();
-
- new SwaggerContextService().withServletConfig(servletConfig1).initScanner();
- new SwaggerContextService().withServletConfig(servletConfig2).initScanner();
-
- verify(servletConfig1, times(2)).getInitParameter(eq(SCANNER_ID_KEY));
- verify(servletContext1, times(1)).setAttribute(eq(SCANNER_ID_PREFIX + "test.1"), any(Scanner.class));
- verify(servletContext2, never()).setAttribute(eq(SCANNER_ID_PREFIX + "test.1"), any(Scanner.class));
-
- verify(servletConfig2, times(2)).getInitParameter(eq(SCANNER_ID_KEY));
- verify(servletContext2, times(1)).setAttribute(eq(SCANNER_ID_PREFIX + "test.2"), any(Scanner.class));
- verify(servletContext1, never()).setAttribute(eq(SCANNER_ID_PREFIX + "test.2"), any(Scanner.class));
-
- }
-
- @Test(description = "should call servletContext getAttribute with param SCANNER_ID_PREFIX + \"test.1/2\"")
- public void getScannerWithInitParam() {
- stubWithInitParam();
-
- Scanner scanner1 = new SwaggerContextService().withServletConfig(servletConfig1).getScanner();
- Scanner scanner2 = new SwaggerContextService().withServletConfig(servletConfig2).getScanner();
-
- assertEquals(beanConfigScanner1, scanner1);
- assertEquals(beanConfigScanner2, scanner2);
-
- verify(servletConfig1, times(2)).getInitParameter(eq(SCANNER_ID_KEY));
- verify(servletContext1, times(1)).getAttribute(eq(SCANNER_ID_PREFIX + "test.1"));
- verify(servletContext2, never()).getAttribute(eq(SCANNER_ID_PREFIX + "test.1"));
-
- verify(servletConfig2, times(2)).getInitParameter(eq(SCANNER_ID_KEY));
- verify(servletContext2, times(1)).getAttribute(eq(SCANNER_ID_PREFIX + "test.2"));
- verify(servletContext1, never()).getAttribute(eq(SCANNER_ID_PREFIX + "test.2"));
-
- }
-
- @Test(description = "should add servletContext attributes SCANNER_ID_PREFIX + \"test.1/2")
- public void initializeScannerWithContextInitParam() {
- stubWithContextInitParam();
-
- new SwaggerContextService().withServletConfig(servletConfig1).initScanner();
- new SwaggerContextService().withServletConfig(servletConfig2).initScanner();
-
- verify(servletConfig1, times(1)).getInitParameter(eq(SCANNER_ID_KEY));
- verify(servletConfig1, times(2)).getInitParameter(eq(CONTEXT_ID_KEY));
- verify(servletContext1, times(1)).setAttribute(eq(SCANNER_ID_PREFIX + "test.1"), any(Scanner.class));
- verify(servletContext2, never()).setAttribute(eq(SCANNER_ID_PREFIX + "test.1"), any(Scanner.class));
-
- verify(servletConfig2, times(1)).getInitParameter(eq(SCANNER_ID_KEY));
- verify(servletConfig2, times(2)).getInitParameter(eq(CONTEXT_ID_KEY));
- verify(servletContext2, times(1)).setAttribute(eq(SCANNER_ID_PREFIX + "test.2"), any(Scanner.class));
- verify(servletContext1, never()).setAttribute(eq(SCANNER_ID_PREFIX + "test.2"), any(Scanner.class));
-
- }
-
- @Test(description = "should call servletContext getAttribute with param SCANNER_ID_PREFIX + \"test.1/2\"")
- public void getScannerWithContextInitParam() {
- stubWithContextInitParam();
-
- Scanner scanner1 = new SwaggerContextService().withServletConfig(servletConfig1).getScanner();
- Scanner scanner2 = new SwaggerContextService().withServletConfig(servletConfig2).getScanner();
-
- assertEquals(beanConfigScanner1, scanner1);
- assertEquals(beanConfigScanner2, scanner2);
-
- verify(servletConfig1, times(1)).getInitParameter(eq(SCANNER_ID_KEY));
- verify(servletConfig1, times(2)).getInitParameter(eq(CONTEXT_ID_KEY));
- verify(servletContext1, times(1)).getAttribute(eq(SCANNER_ID_PREFIX + "test.1"));
- verify(servletContext2, never()).getAttribute(eq(SCANNER_ID_PREFIX + "test.1"));
-
- verify(servletConfig2, times(1)).getInitParameter(eq(SCANNER_ID_KEY));
- verify(servletConfig2, times(2)).getInitParameter(eq(CONTEXT_ID_KEY));
- verify(servletContext2, times(1)).getAttribute(eq(SCANNER_ID_PREFIX + "test.2"));
- verify(servletContext1, never()).getAttribute(eq(SCANNER_ID_PREFIX + "test.2"));
-
- }
-
- @Test(description = "should add servletContext attributes SCANNER_ID_DEFAULT")
- public void initializeAndGetScannerWithoutInitParam() {
- stubWithoutInitParam();
- new SwaggerContextService().withServletConfig(servletConfig1).initScanner();
- new SwaggerContextService().withServletConfig(servletConfig2).initScanner();
-
- verify(servletConfig1, times(1)).getInitParameter(eq(SCANNER_ID_KEY));
- verify(servletContext1, times(1)).setAttribute(eq(SCANNER_ID_DEFAULT), any(Scanner.class));
- verify(servletContext1, never()).setAttribute(eq(SCANNER_ID_PREFIX + "test.1"), any(Scanner.class));
- verify(servletContext2, never()).setAttribute(eq(SCANNER_ID_PREFIX + "test.2"), any(Scanner.class));
-
- verify(servletConfig2, times(1)).getInitParameter(eq(SCANNER_ID_KEY));
- verify(servletContext2, times(1)).setAttribute(eq(SCANNER_ID_DEFAULT), any(Scanner.class));
- verify(servletContext2, never()).setAttribute(eq(SCANNER_ID_PREFIX + "test.2"), any(Scanner.class));
- verify(servletContext1, never()).setAttribute(eq(SCANNER_ID_PREFIX + "test.1"), any(Scanner.class));
-
- }
-
- @Test(description = "should add scanner to ScannerFactory")
- public void initializeAndGetScannerWithoutServletConfig() {
- new SwaggerContextService().initScanner();
- new SwaggerContextService().initScanner();
-
- verify(servletConfig1, never()).getInitParameter(eq(SCANNER_ID_KEY));
- verify(servletContext1, never()).setAttribute(eq(SCANNER_ID_DEFAULT), any(Scanner.class));
- verify(servletContext1, never()).setAttribute(eq(SCANNER_ID_PREFIX + "test.1"), any(Scanner.class));
- verify(servletContext2, never()).setAttribute(eq(SCANNER_ID_PREFIX + "test.2"), any(Scanner.class));
-
- verify(servletConfig2, never()).getInitParameter(eq(SCANNER_ID_KEY));
- verify(servletContext2, never()).setAttribute(eq(SCANNER_ID_DEFAULT), any(Scanner.class));
- verify(servletContext2, never()).setAttribute(eq(SCANNER_ID_PREFIX + "test.2"), any(Scanner.class));
- verify(servletContext1, never()).setAttribute(eq(SCANNER_ID_PREFIX + "test.1"), any(Scanner.class));
-
- assertNotNull(ScannerFactory.getScanner());
- assertEquals(new SwaggerContextService().getScanner(), SwaggerScannerLocator.getInstance().getScanner(SCANNER_ID_DEFAULT));
-
- }
-
- @Test(description = "should add SwaggerConfig to SwaggerConfigLocator map with key CONFIG_ID_PREFIX + \"test.1/2\"")
- public void initializeAndGetConfigWithInitParam() {
- stubWithInitParam();
-
- new SwaggerContextService().withServletConfig(servletConfig1).initConfig();
- new SwaggerContextService().withServletConfig(servletConfig2).initConfig();
-
- assertTrue(SwaggerConfigLocator.getInstance().getConfig(CONFIG_ID_PREFIX + "test.1") instanceof WebXMLReader);
- assertTrue(SwaggerConfigLocator.getInstance().getConfig(CONFIG_ID_PREFIX + "test.2") instanceof WebXMLReader);
-
- verify(servletConfig1, times(2)).getInitParameter(eq(CONFIG_ID_KEY));
- verify(servletConfig2, times(2)).getInitParameter(eq(CONFIG_ID_KEY));
-
- }
-
- @Test(description = "should add SwaggerConfig to SwaggerConfigLocator map with key CONFIG_ID_PREFIX + \"test.1/2\"")
- public void initializeAndGetConfigWithContextInitParam() {
- stubWithContextInitParam();
-
- new SwaggerContextService().withServletConfig(servletConfig1).initConfig();
- new SwaggerContextService().withServletConfig(servletConfig2).initConfig();
-
- assertTrue(SwaggerConfigLocator.getInstance().getConfig(CONFIG_ID_PREFIX + "test.1") instanceof WebXMLReader);
- assertTrue(SwaggerConfigLocator.getInstance().getConfig(CONFIG_ID_PREFIX + "test.2") instanceof WebXMLReader);
-
- verify(servletConfig1, times(2)).getInitParameter(eq(CONTEXT_ID_KEY));
- verify(servletConfig1, times(1)).getInitParameter(eq(CONFIG_ID_KEY));
- verify(servletConfig2, times(2)).getInitParameter(eq(CONTEXT_ID_KEY));
- verify(servletConfig2, times(1)).getInitParameter(eq(CONFIG_ID_KEY));
-
- }
-
- @Test(description = "should add SwaggerConfig to SwaggerConfigLocator map with key CONFIG_ID_DEFAULT")
- public void initializeAndGetConfigWithoutInitParam() {
- stubWithoutInitParam();
-
- new SwaggerContextService().withServletConfig(servletConfig1).initConfig();
- new SwaggerContextService().withServletConfig(servletConfig2).initConfig();
-
- verify(servletConfig1, times(1)).getInitParameter(eq(CONFIG_ID_KEY));
- verify(servletConfig2, times(1)).getInitParameter(eq(CONFIG_ID_KEY));
-
- }
-
- @Test(description = "should add SwaggerConfig to SwaggerConfigLocator map with key CONFIG_ID_DEFAULT")
- public void initializeAndGetConfigWithoutServletConfig() {
- new SwaggerContextService().initConfig();
- new SwaggerContextService().initConfig();
-
- verify(servletConfig1, never()).getInitParameter(eq(CONFIG_ID_KEY));
- verify(servletConfig2, never()).getInitParameter(eq(CONFIG_ID_KEY));
-
- }
-
- private void stubWithContextSwaggerAttribute() {
- Swagger swagger = new Swagger();
- Info info = new Info().title("Test Title");
- swagger.setInfo(info);
- when(servletContext1.getAttribute("swagger")).thenReturn(swagger);
-
- when(servletConfig1.getServletContext()).thenReturn(servletContext1);
- when(servletConfig2.getServletContext()).thenReturn(servletContext2);
-
- when(servletConfig1.getInitParameter(CONTEXT_ID_KEY)).thenReturn("test.1");
- when(servletConfig2.getInitParameter(CONTEXT_ID_KEY)).thenReturn("test.2");
- }
-
- @Test(description = "should get correct swagger context set via context param \"swagger\"")
- public void initConfigViaContextParamSwagger() {
- stubWithContextSwaggerAttribute();
-
- Swagger swagger = new SwaggerContextService().withServletConfig(servletConfig1).getSwagger();
- assertEquals("Test Title",swagger.getInfo().getTitle());
- //verify(servletConfig1, times(2)).getInitParameter(eq(CONTEXT_ID_KEY));
-
-
- }
-
- @Test(description = "should add SwaggerConfig to SwaggerConfigLocator map with keys path-based keys")
- public void initializeAndGetConfigBasedOnPath() {
- stubWithPathBasedConfigInitParam();
-
- new SwaggerContextService()
- .withServletConfig(servletConfig1)
- .withBasePath("/url1")
- .initConfig();
-
- new SwaggerContextService()
- .withServletConfig(servletConfig2)
- .withBasePath("url2")
- .initConfig();
-
- assertTrue(SwaggerConfigLocator.getInstance().getConfig(CONFIG_ID_PREFIX + "/url1/") instanceof WebXMLReader);
- assertTrue(SwaggerConfigLocator.getInstance().getConfig(CONFIG_ID_PREFIX + "/url2/") instanceof WebXMLReader);
-
- verify(servletConfig1, times(1)).getInitParameter(eq(USE_PATH_BASED_CONFIG));
- verify(servletConfig2, times(1)).getInitParameter(eq(USE_PATH_BASED_CONFIG));
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/SwaggerScannerLocatorTest.java b/modules/swagger-jaxrs/src/test/java/io/swagger/SwaggerScannerLocatorTest.java
deleted file mode 100644
index 5b6172f21d..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/SwaggerScannerLocatorTest.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package io.swagger;
-
-import io.swagger.config.Scanner;
-import io.swagger.jaxrs.config.SwaggerScannerLocator;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import java.util.Set;
-import java.util.UUID;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotEquals;
-
-public class SwaggerScannerLocatorTest {
-
- String id = UUID.randomUUID().toString() + System.currentTimeMillis();
-
- @BeforeMethod
- public void setId() {
- id = UUID.randomUUID().toString() + System.currentTimeMillis();
- }
-
- @Test(description = "should add given scanner to map ")
- public void putScannerFirstTime() {
-
- Scanner scanner = new Scanner() {
- @Override
- public Set> classes() {
- return null;
- }
-
- @Override
- public boolean getPrettyPrint() {
- return false;
- }
-
- @Override
- public void setPrettyPrint(boolean shouldPrettyPrint) {
-
- }
- };
-
- SwaggerScannerLocator. getInstance().putScanner(id, scanner);
- assertEquals(SwaggerScannerLocator.getInstance().getScanner(id), scanner);
-
- }
-
- @Test(description = "shouldn't add given scanner to map because already set")
- public void putConfigSecondTime() {
-
- putScannerFirstTime();
-
- Scanner scanner = new Scanner() {
- @Override
- public Set> classes() {
- return null;
- }
-
- @Override
- public boolean getPrettyPrint() {
- return false;
- }
-
- @Override
- public void setPrettyPrint(boolean shouldPrettyPrint) {
-
- }
- };
-
- SwaggerScannerLocator. getInstance().putScanner(id, scanner);
- assertNotEquals(SwaggerScannerLocator.getInstance().getScanner(id), scanner);
-
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/functional/test/ApiListingResourceIT.java b/modules/swagger-jaxrs/src/test/java/io/swagger/functional/test/ApiListingResourceIT.java
deleted file mode 100644
index f7aef0c24d..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/functional/test/ApiListingResourceIT.java
+++ /dev/null
@@ -1,120 +0,0 @@
-package io.swagger.functional.test;
-
-import com.jayway.restassured.http.ContentType;
-import org.testng.annotations.Test;
-
-import static com.jayway.restassured.RestAssured.given;
-import static org.testng.Assert.assertEquals;
-
-/**
- * Created by rbolles on 2/16/16.
- *
- * An functional integration test that runs during maven's integration-test phase,
- * uses RestAssured to define REST API tests, and Jetty's Maven plugin to serve a simple
- * sample app just prior to the integration-test phase starting.
- */
-public class ApiListingResourceIT {
- private static final String EXPECTED_JSON = "{\"swagger\":\"2.0\",\"tags\":[{\"name\":\"widgets\"}],\"paths\":{\"/widgets/{widgetId}\":{\"get\":{\"tags\":[\"widgets\"],\"summary\":\"Find pet by ID\",\"description\":\"Returns a pet when ID <= 10. ID > 10 or nonintegers will simulate API error conditions\",\"operationId\":\"getWidget\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\"],\"parameters\":[{\"name\":\"widgetId\",\"in\":\"path\",\"required\":true,\"type\":\"string\"}],\"responses\":{\"200\":{\"description\":\"Returns widget with matching id\"}}}}},\"definitions\":{\"Widget\":{\"type\":\"object\",\"properties\":{\"a\":{\"type\":\"string\"},\"b\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"}}}}}";
- private static final String EXPECTED_YAML = "---\n" +
- "swagger: \"2.0\"\n" +
- "tags:\n" +
- "- name: \"widgets\"\n" +
- "paths:\n" +
- " /widgets/{widgetId}:\n" +
- " get:\n" +
- " tags:\n" +
- " - \"widgets\"\n" +
- " summary: \"Find pet by ID\"\n" +
- " description: \"Returns a pet when ID <= 10. ID > 10 or nonintegers will simulate\\\n" +
- " \\ API error conditions\"\n" +
- " operationId: \"getWidget\"\n" +
- " consumes:\n" +
- " - \"application/json\"\n" +
- " produces:\n" +
- " - \"application/json\"\n" +
- " parameters:\n" +
- " - name: \"widgetId\"\n" +
- " in: \"path\"\n" +
- " required: true\n" +
- " type: \"string\"\n" +
- " responses:\n" +
- " 200:\n" +
- " description: \"Returns widget with matching id\"\n" +
- "definitions:\n" +
- " Widget:\n" +
- " type: \"object\"\n" +
- " properties:\n" +
- " a:\n" +
- " type: \"string\"\n" +
- " b:\n" +
- " type: \"string\"\n" +
- " id:\n" +
- " type: \"string\"\n";
-
- @Test
- public void testSwaggerJson() throws Exception {
- String actualBody = given()
- .log().all()
- .when()
- .get("/swagger.json")
- .then()
- .log().all()
- .assertThat()
- .statusCode(200)
- .contentType(ContentType.JSON)
- .extract()
- .response().body().asString();
-
- assertEquals(actualBody, EXPECTED_JSON);
- }
-
- @Test
- public void testSwaggerJsonUsingAcceptHeader() throws Exception {
- String actualBody = given()
- .log().all()
- .accept(ContentType.JSON)
- .when()
- .get("/swagger")
- .then()
- .log().all()
- .assertThat()
- .statusCode(200)
- .contentType(ContentType.JSON)
- .extract().response().body().asString();
-
- assertEquals(actualBody, EXPECTED_JSON);
- }
-
- @Test
- public void testSwaggerYaml() throws Exception {
- String actualBody = given()
- .log().all()
- .when()
- .get("/swagger.yaml")
- .then()
- .log().all()
- .assertThat()
- .statusCode(200)
- .contentType("application/yaml")
- .extract().response().body().asString();
-
- assertEquals(actualBody, EXPECTED_YAML);
- }
-
- @Test
- public void testSwaggerYamlUsingAcceptHeader() throws Exception {
- String actualBody = given()
- .log().all()
- .accept("application/yaml")
- .when()
- .get("/swagger")
- .then()
- .log().all()
- .assertThat()
- .statusCode(200)
- .contentType("application/yaml")
- .extract().response().body().asString();
-
- assertEquals(actualBody, EXPECTED_YAML);
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/functional/test/model/Widget.java b/modules/swagger-jaxrs/src/test/java/io/swagger/functional/test/model/Widget.java
deleted file mode 100644
index 1248b65afd..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/functional/test/model/Widget.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package io.swagger.functional.test.model;
-
-/**
- * Created by rbolles on 2/16/16.
- */
-public class Widget {
-
- private String a;
- private String b;
- private String id;
-
- public String getA() {
- return a;
- }
-
- public Widget setA(String a) {
- this.a = a;
- return this;
- }
-
- public String getB() {
- return b;
- }
-
- public Widget setB(String b) {
- this.b = b;
- return this;
- }
-
- public String getId() {
- return id;
- }
-
- public Widget setId(String id) {
- this.id = id;
- return this;
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/functional/test/resources/WidgetResource.java b/modules/swagger-jaxrs/src/test/java/io/swagger/functional/test/resources/WidgetResource.java
deleted file mode 100644
index 9c19003925..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/functional/test/resources/WidgetResource.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package io.swagger.functional.test.resources;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import io.swagger.functional.test.model.Widget;
-
-import javax.ws.rs.*;
-import javax.ws.rs.core.Response;
-
-/**
- * Created by rbolles on 2/16/16.
- */
-@Path("/widgets")
-@Api(tags="widgets", description = "Widget operations")
-@Produces("application/json")
-@Consumes("application/json")
-public class WidgetResource {
-
- @Path("/{widgetId}")
- @GET
- @ApiOperation(value = "Find pet by ID",
- notes = "Returns a pet when ID <= 10. ID > 10 or nonintegers will simulate API error conditions",
- response = Widget.class
-
- )
- @ApiResponses(value = {
- @ApiResponse(code=200, message="Returns widget with matching id")
- })
- public Response getWidget(@PathParam("widgetId") String widgetId) {
- return Response.ok(new Widget().setA("foo").setB("bar")).build();
- }
-}
diff --git a/modules/swagger-jaxrs/src/test/java/io/swagger/jaxrs/ReaderFixFor1959Test.java b/modules/swagger-jaxrs/src/test/java/io/swagger/jaxrs/ReaderFixFor1959Test.java
deleted file mode 100644
index 4281f6947d..0000000000
--- a/modules/swagger-jaxrs/src/test/java/io/swagger/jaxrs/ReaderFixFor1959Test.java
+++ /dev/null
@@ -1,64 +0,0 @@
-package io.swagger.jaxrs;
-
-import io.swagger.models.Operation;
-import io.swagger.models.Path;
-import io.swagger.models.Swagger;
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * Tests whether the bug identified in pull request
- * 1959 has been resolved.
- */
-public class ReaderFixFor1959Test {
-
- @Test
- public void testParentAndChildInterface() {
-
- readAndCompare(new HashSet>(Arrays.asList(new Class>[]{Test1InterfaceParentResource.class, Test1InterfaceChildResource.class})),
- new HashSet(Arrays.asList(new String[]{"getTestValue", "getTestValue_1"})));
-
- }
-
- @Test
- public void testClassWithImplementedInterface() {
-
- readAndCompare(new HashSet>(Arrays.asList(new Class>[]{Test2InterfaceChildResource.class, Test2ClassParentResource.class})),
- new HashSet(Arrays.asList(new String[]{"getTestValue", "getTestValue_1"})));
-
- }
-
- @Test
- public void testParentAndChildClass() {
-
- readAndCompare(new HashSet>(Arrays.asList(new Class>[]{Test3ClassParentResource.class, Test3ClassChildResource.class})),
- new HashSet