Search in sources :

Example 1 with Scheme

use of io.swagger.models.Scheme in project herd by FINRAOS.

the class SwaggerGenMojo method getSwagger.

/**
 * Gets a new Swagger metadata.
 *
 * @return the Swagger metadata.
 * @throws MojoExecutionException if any problems were encountered.
 */
private Swagger getSwagger() throws MojoExecutionException {
    getLog().debug("Creating Swagger Metadata");
    // Set up initial Swagger metadata.
    Swagger swagger = new Swagger();
    swagger.setInfo(new Info().title(title).version(version));
    swagger.setBasePath(basePath);
    // Set the schemes.
    if (!CollectionUtils.isEmpty(schemeParameters)) {
        List<Scheme> schemes = new ArrayList<>();
        for (String schemeParameter : schemeParameters) {
            Scheme scheme = Scheme.forValue(schemeParameter);
            if (scheme == null) {
                throw new MojoExecutionException("Invalid scheme specified: " + schemeParameter);
            }
            schemes.add(scheme);
        }
        swagger.setSchemes(schemes);
    }
    // Add authorization support if specified.
    if (authType != null) {
        // Find the definition for the user specified type.
        SecuritySchemeDefinition securitySchemeDefinition = null;
        for (SecuritySchemeDefinition possibleDefinition : SECURITY_SCHEME_DEFINITIONS) {
            if (possibleDefinition.getType().equalsIgnoreCase(authType)) {
                securitySchemeDefinition = possibleDefinition;
                break;
            }
        }
        // If we found a match, set it on the swagger object.
        if (securitySchemeDefinition != null) {
            // Come up with an authentication name for easy identification (e.g. basicAuthentication, etc.).
            String securityName = securitySchemeDefinition.getType() + "Authentication";
            // Add the security definition.
            swagger.addSecurityDefinition(securityName, securitySchemeDefinition);
            // Add the security for everything based on the name of the definition.
            SecurityRequirement securityRequirement = new SecurityRequirement();
            securityRequirement.requirement(securityName);
            swagger.addSecurity(securityRequirement);
        }
    }
    // Use default paths and definitions.
    swagger.setPaths(new TreeMap<>());
    swagger.setDefinitions(new TreeMap<>());
    return swagger;
}
Also used : Scheme(io.swagger.models.Scheme) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) Swagger(io.swagger.models.Swagger) ArrayList(java.util.ArrayList) SecuritySchemeDefinition(io.swagger.models.auth.SecuritySchemeDefinition) Info(io.swagger.models.Info) SecurityRequirement(io.swagger.models.SecurityRequirement)

Example 2 with Scheme

use of io.swagger.models.Scheme in project gravitee-management-rest-api by gravitee-io.

the class SwaggerServiceImpl method prepare.

public NewApiEntity prepare(ImportSwaggerDescriptorEntity swaggerDescriptor) {
    Swagger swagger = null;
    switch(swaggerDescriptor.getVersion()) {
        case VERSION_1_0:
            try {
                logger.info("Loading an old Swagger descriptor from {}", swaggerDescriptor.getPayload());
                // For spec < 2.0, only read by url is possible
                swagger = new SwaggerCompatConverter().read(swaggerDescriptor.getPayload());
            } catch (IOException ioe) {
                logger.error("Can not read old Swagger specification", ioe);
                throw new SwaggerDescriptorException();
            }
        case VERSION_2_0:
            if (swaggerDescriptor.getType() == ImportSwaggerDescriptorEntity.Type.INLINE) {
                logger.info("Loading an inline Swagger descriptor");
                swagger = new SwaggerParser().parse(swaggerDescriptor.getPayload());
            } else if (swaggerDescriptor.getType() == ImportSwaggerDescriptorEntity.Type.URL) {
                logger.info("Loading a Swagger descriptor from URL: ", swaggerDescriptor.getPayload());
                swagger = new SwaggerParser().read(swaggerDescriptor.getPayload());
            }
    }
    if (swagger == null) {
        throw new SwaggerDescriptorException();
    }
    NewApiEntity apiEntity = new NewApiEntity();
    apiEntity.setName(swagger.getInfo().getTitle());
    apiEntity.setDescription(swagger.getInfo().getDescription());
    apiEntity.setVersion(swagger.getInfo().getVersion());
    String scheme = (swagger.getSchemes() == null || swagger.getSchemes().isEmpty()) ? defaultScheme : swagger.getSchemes().iterator().next().toValue();
    apiEntity.setEndpoint(scheme + "://" + swagger.getHost() + swagger.getBasePath());
    apiEntity.setPaths(new ArrayList<>(swagger.getPaths().keySet().stream().map(path -> path.replaceAll("\\{(.[^/]*)\\}", ":$1")).collect(Collectors.toList())));
    return apiEntity;
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) Scheme(io.swagger.models.Scheme) Yaml(io.swagger.util.Yaml) SwaggerParser(io.swagger.parser.SwaggerParser) Swagger(io.swagger.models.Swagger) URISyntaxException(java.net.URISyntaxException) Json(io.swagger.util.Json) LoggerFactory(org.slf4j.LoggerFactory) ArrayList(java.util.ArrayList) Value(org.springframework.beans.factory.annotation.Value) PageEntity(io.gravitee.management.model.PageEntity) OpenAPI(io.swagger.v3.oas.models.OpenAPI) SwaggerCompatConverter(io.swagger.parser.SwaggerCompatConverter) URI(java.net.URI) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Logger(org.slf4j.Logger) ImportSwaggerDescriptorEntity(io.gravitee.management.model.ImportSwaggerDescriptorEntity) BufferedWriter(java.io.BufferedWriter) FileWriter(java.io.FileWriter) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) NewApiEntity(io.gravitee.management.model.NewApiEntity) Collectors(java.util.stream.Collectors) File(java.io.File) Component(org.springframework.stereotype.Component) MediaType(io.gravitee.common.http.MediaType) PageConfigurationEntity(io.gravitee.management.model.PageConfigurationEntity) SwaggerDescriptorException(io.gravitee.management.service.exceptions.SwaggerDescriptorException) SwaggerService(io.gravitee.management.service.SwaggerService) Collections(java.util.Collections) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) SwaggerDescriptorException(io.gravitee.management.service.exceptions.SwaggerDescriptorException) SwaggerCompatConverter(io.swagger.parser.SwaggerCompatConverter) Swagger(io.swagger.models.Swagger) IOException(java.io.IOException) NewApiEntity(io.gravitee.management.model.NewApiEntity)

Example 3 with Scheme

use of io.swagger.models.Scheme in project ballerina by ballerina-lang.

the class SwaggerResourceMapper method parseResourceConfigAnnotationAttachment.

/**
 * Parse 'ResourceConfig' annotation attachment and build a resource operation.
 *
 * @param resource  The ballerina resource definition.
 * @param operation The swagger operation.
 */
private void parseResourceConfigAnnotationAttachment(ResourceInfo resource, Operation operation) {
    AnnAttachmentInfo resourceConfigAnnotation = resource.getAnnotationAttachmentInfo(SwaggerConstants.SWAGGER_PACKAGE_PATH, "ResourceConfig");
    if (null != resourceConfigAnnotation) {
        Map<String, AnnAttributeValue> resourceConfigAnnAttributeValueMap = SwaggerUtils.convertToAttributeMap(resourceConfigAnnotation);
        if (null != resourceConfigAnnAttributeValueMap.get("schemes")) {
            List<Scheme> schemes = new LinkedList<>();
            AnnAttributeValue[] schemesValues = resourceConfigAnnAttributeValueMap.get("schemes").getAttributeValueArray();
            for (AnnAttributeValue schemesValue : schemesValues) {
                schemes.add(Scheme.forValue(schemesValue.getStringValue()));
            }
            operation.setSchemes(schemes);
        }
    // TODO: Implement security definitions.
    // this.createSecurityDefinitions(resourceConfigAnnotation.get().getAttributeNameValuePairs()
    // .get("authorizations"), operation);
    }
}
Also used : ParamAnnAttachmentInfo(org.ballerinalang.util.codegen.ParamAnnAttachmentInfo) AnnAttachmentInfo(org.ballerinalang.util.codegen.AnnAttachmentInfo) Scheme(io.swagger.models.Scheme) AnnAttributeValue(org.ballerinalang.util.codegen.AnnAttributeValue) LinkedList(java.util.LinkedList)

Example 4 with Scheme

use of io.swagger.models.Scheme in project swagger-core by swagger-api.

the class Reader method read.

private Swagger read(Class<?> cls, String parentPath, String parentMethod, boolean isSubresource, String[] parentConsumes, String[] parentProduces, Map<String, Tag> parentTags, List<Parameter> parentParameters, Set<Class<?>> scannedResources) {
    Map<String, Tag> tags = new LinkedHashMap<String, Tag>();
    List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>();
    String[] consumes = new String[0];
    String[] produces = new String[0];
    final Set<Scheme> 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<String> 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<Parameter> globalParameters = new ArrayList<Parameter>();
        // 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<ApiResponse> classApiResponses = new ArrayList<ApiResponse>();
        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<String, String> regexMap = new LinkedHashMap<String, String>();
            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<String> both = new LinkedHashSet<String>(Arrays.asList(apiConsumes));
                    both.addAll(new LinkedHashSet<String>(Arrays.asList(parentConsumes)));
                    if (operation.getConsumes() != null) {
                        both.addAll(new LinkedHashSet<String>(operation.getConsumes()));
                    }
                    apiConsumes = both.toArray(new String[both.size()]);
                }
                String[] apiProduces = produces;
                if (parentProduces != null) {
                    Set<String> both = new LinkedHashSet<String>(Arrays.asList(apiProduces));
                    both.addAll(new LinkedHashSet<String>(Arrays.asList(parentProduces)));
                    if (operation.getProduces() != null) {
                        both.addAll(new LinkedHashSet<String>(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;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ModelConverters(io.swagger.converter.ModelConverters) Scheme(io.swagger.models.Scheme) AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) ArrayList(java.util.ArrayList) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.models.Operation) ApiResponse(io.swagger.annotations.ApiResponse) LinkedHashMap(java.util.LinkedHashMap) Authorization(io.swagger.annotations.Authorization) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Path(io.swagger.models.Path) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) Method(java.lang.reflect.Method) HttpMethod(javax.ws.rs.HttpMethod) AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) JavaType(com.fasterxml.jackson.databind.JavaType) Produces(javax.ws.rs.Produces) FormParameter(io.swagger.models.parameters.FormParameter) PathParameter(io.swagger.models.parameters.PathParameter) Parameter(io.swagger.models.parameters.Parameter) QueryParameter(io.swagger.models.parameters.QueryParameter) HeaderParameter(io.swagger.models.parameters.HeaderParameter) AnnotatedParameter(com.fasterxml.jackson.databind.introspect.AnnotatedParameter) Tag(io.swagger.models.Tag) Api(io.swagger.annotations.Api) AuthorizationScope(io.swagger.annotations.AuthorizationScope) SecurityRequirement(io.swagger.models.SecurityRequirement)

Example 5 with Scheme

use of io.swagger.models.Scheme in project swagger-core by swagger-api.

the class ServletReaderExtension method applySchemes.

@Override
public void applySchemes(ReaderContext context, Operation operation, Method method) {
    final List<Scheme> schemes = new ArrayList<Scheme>();
    final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
    final Api apiAnnotation = context.getCls().getAnnotation(Api.class);
    if (apiOperation != null) {
        schemes.addAll(parseSchemes(apiOperation.protocols()));
    }
    if (schemes.isEmpty() && apiAnnotation != null) {
        schemes.addAll(parseSchemes(apiAnnotation.protocols()));
    }
    for (Scheme scheme : schemes) {
        operation.scheme(scheme);
    }
}
Also used : Scheme(io.swagger.models.Scheme) ArrayList(java.util.ArrayList) ApiOperation(io.swagger.annotations.ApiOperation) Api(io.swagger.annotations.Api)

Aggregations

Scheme (io.swagger.models.Scheme)11 ArrayList (java.util.ArrayList)7 Swagger (io.swagger.models.Swagger)5 LinkedList (java.util.LinkedList)4 Api (io.swagger.annotations.Api)3 ApiOperation (io.swagger.annotations.ApiOperation)3 Path (io.swagger.models.Path)3 Collectors (java.util.stream.Collectors)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 Lists (com.google.common.collect.Lists)2 ExternalDocs (io.swagger.models.ExternalDocs)2 Info (io.swagger.models.Info)2 Operation (io.swagger.models.Operation)2 Tag (io.swagger.models.Tag)2 Parameter (io.swagger.models.parameters.Parameter)2 PathParameter (io.swagger.models.parameters.PathParameter)2 HashMap (java.util.HashMap)2 LinkedHashSet (java.util.LinkedHashSet)2 List (java.util.List)2