Search in sources :

Example 6 with ApiResponse

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

the class ServletReaderExtension method applyResponses.

@Override
public void applyResponses(ReaderContext context, Operation operation, Method method) {
    final Map<Integer, Response> result = new HashMap<Integer, Response>();
    final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
    if (apiOperation != null && StringUtils.isNotBlank(apiOperation.responseReference())) {
        final Response response = new Response().description(SUCCESSFUL_OPERATION);
        response.schema(new RefProperty(apiOperation.responseReference()));
        result.put(apiOperation.code(), response);
    }
    final Type responseType = getResponseType(method);
    if (isValidResponse(responseType)) {
        final Property property = ModelConverters.getInstance().readAsProperty(responseType);
        if (property != null) {
            final Property responseProperty = ContainerWrapper.wrapContainer(getResponseContainer(apiOperation), property);
            final int responseCode = apiOperation == null ? 200 : apiOperation.code();
            final Map<String, Property> defaultResponseHeaders = apiOperation == null ? Collections.<String, Property>emptyMap() : parseResponseHeaders(context, apiOperation.responseHeaders());
            final Response response = new Response().description(SUCCESSFUL_OPERATION).schema(responseProperty).headers(defaultResponseHeaders);
            result.put(responseCode, response);
            appendModels(context.getSwagger(), responseType);
        }
    }
    final ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class);
    if (responseAnnotation != null) {
        for (ApiResponse apiResponse : responseAnnotation.value()) {
            final Map<String, Property> responseHeaders = parseResponseHeaders(context, apiResponse.responseHeaders());
            final Response response = new Response().description(apiResponse.message()).headers(responseHeaders);
            if (StringUtils.isNotEmpty(apiResponse.reference())) {
                response.schema(new RefProperty(apiResponse.reference()));
            } else if (!ReflectionUtils.isVoid(apiResponse.response())) {
                final Type type = apiResponse.response();
                final Property property = ModelConverters.getInstance().readAsProperty(type);
                if (property != null) {
                    response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property));
                    appendModels(context.getSwagger(), type);
                }
            }
            result.put(apiResponse.code(), response);
        }
    }
    for (Map.Entry<Integer, Response> responseEntry : result.entrySet()) {
        if (responseEntry.getKey() == 0) {
            operation.defaultResponse(responseEntry.getValue());
        } else {
            operation.response(responseEntry.getKey(), responseEntry.getValue());
        }
    }
}
Also used : HashMap(java.util.HashMap) ApiResponse(io.swagger.annotations.ApiResponse) RefProperty(io.swagger.models.properties.RefProperty) Response(io.swagger.models.Response) ApiResponse(io.swagger.annotations.ApiResponse) Type(java.lang.reflect.Type) JavaType(com.fasterxml.jackson.databind.JavaType) ApiOperation(io.swagger.annotations.ApiOperation) ArrayProperty(io.swagger.models.properties.ArrayProperty) Property(io.swagger.models.properties.Property) MapProperty(io.swagger.models.properties.MapProperty) RefProperty(io.swagger.models.properties.RefProperty) Map(java.util.Map) HashMap(java.util.HashMap) ApiResponses(io.swagger.annotations.ApiResponses)

Example 7 with ApiResponse

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

the class Reader method parseMethod.

private Operation parseMethod(Class<?> cls, Method method, AnnotatedMethod annotatedMethod, List<Parameter> globalParameters, List<ApiResponse> 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<String, Property> defaultResponseHeaders = new LinkedHashMap<String, Property>();
    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<SecurityRequirement> securities = new ArrayList<SecurityRequirement>();
        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<ApiResponse> apiResponses = new ArrayList<ApiResponse>();
    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<Parameter> 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<Parameter> 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;
}
Also used : AnnotatedParameter(com.fasterxml.jackson.databind.introspect.AnnotatedParameter) ArrayList(java.util.ArrayList) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.models.Operation) ApiResponse(io.swagger.annotations.ApiResponse) LinkedHashMap(java.util.LinkedHashMap) RefProperty(io.swagger.models.properties.RefProperty) Authorization(io.swagger.annotations.Authorization) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ArrayProperty(io.swagger.models.properties.ArrayProperty) Property(io.swagger.models.properties.Property) MapProperty(io.swagger.models.properties.MapProperty) RefProperty(io.swagger.models.properties.RefProperty) ApiResponses(io.swagger.annotations.ApiResponses) Response(io.swagger.models.Response) ApiResponse(io.swagger.annotations.ApiResponse) Type(java.lang.reflect.Type) JavaType(com.fasterxml.jackson.databind.JavaType) ParameterizedType(java.lang.reflect.ParameterizedType) 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) AuthorizationScope(io.swagger.annotations.AuthorizationScope) SecurityRequirement(io.swagger.models.SecurityRequirement)

Example 8 with ApiResponse

use of io.swagger.annotations.ApiResponse in project java-chassis by ServiceComb.

the class CodeFirstJaxrs method cseResponse.

//    public Response getUserResponse() {
//
//    }
@ApiResponse(code = 200, response = User.class, message = "")
@ResponseHeaders({ @ResponseHeader(name = "h1", response = String.class), @ResponseHeader(name = "h2", response = String.class) })
@Path("/cseResponse")
@GET
public Response cseResponse() {
    Response response = Response.createSuccess(Status.ACCEPTED, new User());
    response.getHeaders().addHeader("h1", "h1v").addHeader("h2", "h2v");
    return response;
}
Also used : ApiResponse(io.swagger.annotations.ApiResponse) Response(io.servicecomb.core.Response) User(io.servicecomb.demo.server.User) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) ResponseHeaders(io.servicecomb.swagger.extend.annotations.ResponseHeaders) ApiResponse(io.swagger.annotations.ApiResponse)

Example 9 with ApiResponse

use of io.swagger.annotations.ApiResponse in project java-chassis by ServiceComb.

the class ApiResponseMethodProcessor method process.

@Override
public void process(Object annotation, OperationGenerator operationGenerator) {
    // swagger号称不允许独立使用这个标注,不过支持独立使用,也没什么后果
    ApiResponse apiResponse = (ApiResponse) annotation;
    AnnotationUtils.addResponse(operationGenerator.getSwagger(), operationGenerator.getOperation(), apiResponse);
}
Also used : ApiResponse(io.swagger.annotations.ApiResponse)

Example 10 with ApiResponse

use of io.swagger.annotations.ApiResponse in project java-chassis by ServiceComb.

the class ApiResponsesMethodProcessor method process.

@Override
public void process(Object annotation, OperationGenerator operationGenerator) {
    ApiResponses apiResponses = (ApiResponses) annotation;
    MethodAnnotationProcessor processor = operationGenerator.getContext().findMethodAnnotationProcessor(ApiResponse.class);
    for (ApiResponse apiResponse : apiResponses.value()) {
        processor.process(apiResponse, operationGenerator);
    }
}
Also used : MethodAnnotationProcessor(io.servicecomb.swagger.generator.core.MethodAnnotationProcessor) ApiResponses(io.swagger.annotations.ApiResponses) ApiResponse(io.swagger.annotations.ApiResponse)

Aggregations

ApiResponse (io.swagger.annotations.ApiResponse)76 ApiOperation (io.swagger.annotations.ApiOperation)68 Response (javax.ws.rs.core.Response)63 Path (javax.ws.rs.Path)60 ApiResponses (io.swagger.annotations.ApiResponses)53 GET (javax.ws.rs.GET)46 ResponseUtils.formatResponse (org.commonjava.indy.bind.jaxrs.util.ResponseUtils.formatResponse)42 Produces (javax.ws.rs.Produces)33 IndyWorkflowException (org.commonjava.indy.IndyWorkflowException)31 Consumes (javax.ws.rs.Consumes)25 ApiParam (io.swagger.annotations.ApiParam)23 Api (io.swagger.annotations.Api)22 DELETE (javax.ws.rs.DELETE)22 POST (javax.ws.rs.POST)22 Inject (javax.inject.Inject)21 PUT (javax.ws.rs.PUT)21 PathParam (javax.ws.rs.PathParam)21 StoreKey (org.commonjava.indy.model.core.StoreKey)19 StoreType (org.commonjava.indy.model.core.StoreType)19 URI (java.net.URI)18