Search in sources :

Example 11 with Api

use of io.swagger.annotations.Api in project graylog2-server by Graylog2.

the class Generator method generateOverview.

public synchronized Map<String, Object> generateOverview() {
    if (!overviewResult.isEmpty()) {
        return overviewResult;
    }
    final List<Map<String, Object>> apis = Lists.newArrayList();
    for (Class<?> clazz : getAnnotatedClasses()) {
        Api info = clazz.getAnnotation(Api.class);
        Path path = clazz.getAnnotation(Path.class);
        if (info == null || path == null) {
            LOG.debug("Skipping REST resource with no Api or Path annotation: <{}>", clazz.getCanonicalName());
            continue;
        }
        final String prefixedPath = prefixedPath(clazz, path.value());
        final Map<String, Object> apiDescription = Maps.newHashMap();
        apiDescription.put("name", prefixedPath.startsWith(pluginPathPrefix) ? "Plugins/" + info.value() : info.value());
        apiDescription.put("path", prefixedPath);
        apiDescription.put("description", info.description());
        apis.add(apiDescription);
    }
    Collections.sort(apis, (o1, o2) -> ComparisonChain.start().compare(o1.get("name").toString(), o2.get("name").toString()).result());
    Map<String, String> info = Maps.newHashMap();
    info.put("title", "Graylog REST API");
    overviewResult.put("apiVersion", ServerVersion.VERSION.toString());
    overviewResult.put("swaggerVersion", EMULATED_SWAGGER_VERSION);
    overviewResult.put("apis", apis);
    return overviewResult;
}
Also used : Path(javax.ws.rs.Path) Api(io.swagger.annotations.Api) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 12 with Api

use of io.swagger.annotations.Api 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 13 with Api

use of io.swagger.annotations.Api 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)

Example 14 with Api

use of io.swagger.annotations.Api in project swagger-core by swagger-api.

the class ServletReaderExtension method applyTags.

@Override
public void applyTags(ReaderContext context, Operation operation, Method method) {
    final List<String> tags = new ArrayList<String>();
    final Api apiAnnotation = context.getCls().getAnnotation(Api.class);
    if (apiAnnotation != null) {
        tags.addAll(Collections2.filter(Arrays.asList(apiAnnotation.tags()), new Predicate<String>() {

            @Override
            public boolean apply(String input) {
                return StringUtils.isNotBlank(input);
            }
        }));
    }
    tags.addAll(context.getParentTags());
    final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
    if (apiOperation != null) {
        tags.addAll(Collections2.filter(Arrays.asList(apiOperation.tags()), new Predicate<String>() {

            @Override
            public boolean apply(String input) {
                return StringUtils.isNotBlank(input);
            }
        }));
    }
    for (String tag : tags) {
        operation.tag(tag);
    }
}
Also used : ArrayList(java.util.ArrayList) ApiOperation(io.swagger.annotations.ApiOperation) Api(io.swagger.annotations.Api) Predicate(com.google.common.base.Predicate)

Example 15 with Api

use of io.swagger.annotations.Api in project indy by Commonjava.

the class SchedulerHandler method deprecatedGetStoreDisableTimeout.

@ApiOperation("[Deprecated] Retrieve the expiration information related to re-enablement of a repository")
@ApiResponses({ @ApiResponse(code = 200, message = "Expiration information retrieved successfully.", response = Expiration.class), @ApiResponse(code = 400, message = "Store is manually disabled (doesn't automatically re-enable), or isn't disabled.") })
@Path("store/{type: (hosted|group|remote)}/{name}/disable-timeout")
@GET
@Deprecated
public Response deprecatedGetStoreDisableTimeout(@ApiParam(allowableValues = "hosted,group,remote", required = true) @PathParam("type") String storeType, @ApiParam(required = true) @PathParam("name") String storeName) {
    StoreType type = StoreType.get(storeType);
    String altPath = Paths.get("/api/admin/schedule", MAVEN_PKG_KEY, type.singularEndpointName(), storeName).toString();
    StoreKey storeKey = new StoreKey(type, storeName);
    Expiration timeout = null;
    try {
        timeout = controller.getStoreDisableTimeout(storeKey);
        if (timeout == null) {
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }
        return formatOkResponseWithJsonEntity(timeout, objectMapper, rb -> markDeprecated(rb, altPath));
    } catch (IndyWorkflowException e) {
        throwError(e, rb -> markDeprecated(rb, altPath));
    }
    return null;
}
Also used : StoreType(org.commonjava.indy.model.core.StoreType) PathParam(javax.ws.rs.PathParam) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Path(javax.ws.rs.Path) ApiParam(io.swagger.annotations.ApiParam) ResponseUtils.throwError(org.commonjava.indy.bind.jaxrs.util.ResponseUtils.throwError) ApiResponses(io.swagger.annotations.ApiResponses) Inject(javax.inject.Inject) ApiOperation(io.swagger.annotations.ApiOperation) ResponseUtils.formatOkResponseWithJsonEntity(org.commonjava.indy.bind.jaxrs.util.ResponseUtils.formatOkResponseWithJsonEntity) IndyWorkflowException(org.commonjava.indy.IndyWorkflowException) Api(io.swagger.annotations.Api) StoreKey(org.commonjava.indy.model.core.StoreKey) MAVEN_PKG_KEY(org.commonjava.indy.pkg.maven.model.MavenPackageTypeDescriptor.MAVEN_PKG_KEY) ExpirationSet(org.commonjava.indy.core.expire.ExpirationSet) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Expiration(org.commonjava.indy.core.expire.Expiration) StoreType(org.commonjava.indy.model.core.StoreType) IndyResources(org.commonjava.indy.bind.jaxrs.IndyResources) ResponseUtils.markDeprecated(org.commonjava.indy.bind.jaxrs.util.ResponseUtils.markDeprecated) ApplicationContent(org.commonjava.indy.util.ApplicationContent) Response(javax.ws.rs.core.Response) SchedulerController(org.commonjava.indy.core.ctl.SchedulerController) Paths(java.nio.file.Paths) ApiResponse(io.swagger.annotations.ApiResponse) ResponseUtils(org.commonjava.indy.bind.jaxrs.util.ResponseUtils) WebApplicationException(javax.ws.rs.WebApplicationException) WebApplicationException(javax.ws.rs.WebApplicationException) IndyWorkflowException(org.commonjava.indy.IndyWorkflowException) Expiration(org.commonjava.indy.core.expire.Expiration) StoreKey(org.commonjava.indy.model.core.StoreKey) Path(javax.ws.rs.Path) ResponseUtils.markDeprecated(org.commonjava.indy.bind.jaxrs.util.ResponseUtils.markDeprecated) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

Api (io.swagger.annotations.Api)18 ApiOperation (io.swagger.annotations.ApiOperation)16 ApiResponse (io.swagger.annotations.ApiResponse)10 ApiResponses (io.swagger.annotations.ApiResponses)10 Path (javax.ws.rs.Path)10 ApiParam (io.swagger.annotations.ApiParam)9 Paths (java.nio.file.Paths)9 Inject (javax.inject.Inject)9 GET (javax.ws.rs.GET)9 PathParam (javax.ws.rs.PathParam)9 Response (javax.ws.rs.core.Response)9 IndyResources (org.commonjava.indy.bind.jaxrs.IndyResources)9 ResponseUtils.markDeprecated (org.commonjava.indy.bind.jaxrs.util.ResponseUtils.markDeprecated)9 URI (java.net.URI)7 Consumer (java.util.function.Consumer)7 Supplier (java.util.function.Supplier)7 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 HEAD (javax.ws.rs.HEAD)7 PUT (javax.ws.rs.PUT)7 QueryParam (javax.ws.rs.QueryParam)7