Search in sources :

Example 61 with Operation

use of io.swagger.models.Operation in project carbon-apimgt by wso2.

the class DynamicHtmlGenTestCase method testPreprocessSwagger.

@Test
public void testPreprocessSwagger() throws Exception {
    DynamicHtmlGen htmlGen = new DynamicHtmlGen();
    Swagger swagger = new Swagger();
    Path path = new Path();
    Operation operation = new Operation();
    List<String> tags = new ArrayList<>();
    tags.add("tag1");
    tags.add("tag2");
    tags.add("tag3");
    tags.add("tag4");
    operation.setTags(tags);
    path.setGet(operation);
    swagger.path("get_sample", path);
    htmlGen.preprocessSwagger(swagger);
    List<String> processedTags = swagger.getPath("get_sample").getGet().getTags();
    Assert.assertEquals(processedTags.size(), 1);
    Assert.assertEquals(processedTags.get(0), "tag1");
}
Also used : Path(io.swagger.models.Path) DynamicHtmlGen(org.wso2.carbon.apimgt.rest.api.common.codegen.DynamicHtmlGen) Swagger(io.swagger.models.Swagger) ArrayList(java.util.ArrayList) CodegenOperation(io.swagger.codegen.CodegenOperation) Operation(io.swagger.models.Operation) Test(org.testng.annotations.Test)

Example 62 with Operation

use of io.swagger.models.Operation in project camel by apache.

the class SwaggerRestProducerFactory method createProducer.

@Override
public Producer createProducer(CamelContext camelContext, String host, String verb, String basePath, String uriTemplate, String queryParameters, String consumes, String produces, Map<String, Object> parameters) throws Exception {
    String apiDoc = (String) parameters.get("apiDoc");
    // load json model
    if (apiDoc == null) {
        throw new IllegalArgumentException("Swagger api-doc must be configured using the apiDoc option");
    }
    String path = uriTemplate != null ? uriTemplate : basePath;
    // path must start with a leading slash
    if (!path.startsWith("/")) {
        path = "/" + path;
    }
    Swagger swagger = loadSwaggerModel(camelContext, apiDoc);
    Operation operation = getSwaggerOperation(swagger, verb, path);
    if (operation == null) {
        throw new IllegalArgumentException("Swagger api-doc does not contain operation for " + verb + ":" + path);
    }
    // validate if we have the query parameters also
    if (queryParameters != null) {
        for (Parameter param : operation.getParameters()) {
            if ("query".equals(param.getIn()) && param.getRequired()) {
                // check if we have the required query parameter defined
                String key = param.getName();
                String token = key + "=";
                boolean hasQuery = queryParameters.contains(token);
                if (!hasQuery) {
                    throw new IllegalArgumentException("Swagger api-doc does not contain query parameter " + key + " for " + verb + ":" + path);
                }
            }
        }
    }
    String componentName = (String) parameters.get("componentName");
    Producer producer = createHttpProducer(camelContext, swagger, operation, host, verb, path, queryParameters, produces, consumes, componentName, parameters);
    return producer;
}
Also used : Producer(org.apache.camel.Producer) Swagger(io.swagger.models.Swagger) Parameter(io.swagger.models.parameters.Parameter) Operation(io.swagger.models.Operation)

Example 63 with Operation

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

the class SpecFilter method filter.

public Swagger filter(Swagger swagger, SwaggerSpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) {
    Swagger clone = new Swagger();
    clone.info(swagger.getInfo()).tags(swagger.getTags() == null ? null : new ArrayList<Tag>(swagger.getTags())).host(swagger.getHost()).basePath(swagger.getBasePath()).schemes(swagger.getSchemes()).consumes(swagger.getConsumes()).produces(swagger.getProduces()).externalDocs(swagger.getExternalDocs()).vendorExtensions(swagger.getVendorExtensions());
    final Set<String> filteredTags = new HashSet<String>();
    final Set<String> allowedTags = new HashSet<String>();
    for (String resourcePath : swagger.getPaths().keySet()) {
        Path path = swagger.getPaths().get(resourcePath);
        Map<String, Operation> ops = new HashMap<String, Operation>();
        ops.put("get", path.getGet());
        ops.put("head", path.getHead());
        ops.put("put", path.getPut());
        ops.put("post", path.getPost());
        ops.put("delete", path.getDelete());
        ops.put("patch", path.getPatch());
        ops.put("options", path.getOptions());
        Path clonedPath = new Path();
        for (String key : ops.keySet()) {
            Operation op = ops.get(key);
            if (op != null) {
                ApiDescription desc = new ApiDescription(resourcePath, key);
                final Set<String> tags;
                if (filter.isOperationAllowed(op, desc, params, cookies, headers)) {
                    clonedPath.set(key, filterOperation(filter, op, desc, params, cookies, headers));
                    tags = allowedTags;
                } else {
                    tags = filteredTags;
                }
                if (op.getTags() != null) {
                    tags.addAll(op.getTags());
                }
            }
        }
        if (!clonedPath.isEmpty()) {
            clone.path(resourcePath, clonedPath);
        }
    }
    final List<Tag> tags = clone.getTags();
    filteredTags.removeAll(allowedTags);
    if (tags != null && !filteredTags.isEmpty()) {
        for (Iterator<Tag> it = tags.iterator(); it.hasNext(); ) {
            if (filteredTags.contains(it.next().getName())) {
                it.remove();
            }
        }
        if (clone.getTags().isEmpty()) {
            clone.setTags(null);
        }
    }
    Map<String, Model> definitions = filterDefinitions(filter, swagger.getDefinitions(), params, cookies, headers);
    clone.setSecurityDefinitions(swagger.getSecurityDefinitions());
    clone.setSecurity(swagger.getSecurity());
    clone.setDefinitions(definitions);
    // existing client filters directly implementing SwaggerSpecFilter.
    if (filter instanceof AbstractSpecFilter) {
        if (((AbstractSpecFilter) filter).isRemovingUnreferencedDefinitions()) {
            clone = removeBrokenReferenceDefinitions(clone);
        }
    }
    return clone;
}
Also used : Path(io.swagger.models.Path) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Operation(io.swagger.models.Operation) Swagger(io.swagger.models.Swagger) Model(io.swagger.models.Model) RefModel(io.swagger.models.RefModel) ComposedModel(io.swagger.models.ComposedModel) ArrayModel(io.swagger.models.ArrayModel) Tag(io.swagger.models.Tag) ApiDescription(io.swagger.model.ApiDescription) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 64 with Operation

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

the class SecurityDefinitionTest method createModelWithSecurityRequirements.

@Test(description = "it should create a model with security requirements")
public void createModelWithSecurityRequirements() throws IOException {
    final Model personModel = ModelConverters.getInstance().read(Person.class).get("Person");
    final Model errorModel = ModelConverters.getInstance().read(Error.class).get("Error");
    final Info info = new Info().version("1.0.0").title("Swagger Petstore");
    final Contact contact = new Contact().name("Swagger API Team").email("foo@bar.baz").url("http://swagger.io");
    info.setContact(contact);
    final Swagger swagger = new Swagger().info(info).host("petstore.swagger.io").scheme(Scheme.HTTP).consumes("application/json").produces("application/json").model("Person", personModel).model("Error", errorModel);
    swagger.securityDefinition("githubAccessCode", new OAuth2Definition().accessCode("http://foo.com/accessCode", "http://foo.com/tokenUrl").scope("user:email", "Grants read access to a user’s email addresses."));
    final Operation get = new Operation().produces("application/json").summary("finds pets in the system").description("a longer description").tag("Pet Operations").operationId("get pet by id");
    get.parameter(new QueryParameter().name("tags").description("tags to filter by").required(false).property(new StringProperty()));
    get.parameter(new PathParameter().name("petId").description("pet to fetch").property(new LongProperty()));
    final Response response = new Response().description("pets returned").schema(new RefProperty().asDefault("Person"));
    final Response errorResponse = new Response().description("error response").schema(new RefProperty().asDefault("Error"));
    get.response(200, response).defaultResponse(errorResponse).security(new SecurityRequirement("internal_oauth2").scope("user:email")).security(new SecurityRequirement("api_key"));
    swagger.path("/pets", new Path().get(get));
    final String json = ResourceUtils.loadClassResource(getClass(), "ModelWithSecurityRequirements.json");
    SerializationMatchers.assertEqualsToJson(swagger, json);
}
Also used : Path(io.swagger.models.Path) QueryParameter(io.swagger.models.parameters.QueryParameter) OAuth2Definition(io.swagger.models.auth.OAuth2Definition) Error(io.swagger.models.Error) StringProperty(io.swagger.models.properties.StringProperty) Operation(io.swagger.models.Operation) Info(io.swagger.models.Info) PathParameter(io.swagger.models.parameters.PathParameter) Contact(io.swagger.models.Contact) RefProperty(io.swagger.models.properties.RefProperty) Response(io.swagger.models.Response) Swagger(io.swagger.models.Swagger) LongProperty(io.swagger.models.properties.LongProperty) Model(io.swagger.models.Model) Person(io.swagger.models.Person) SecurityRequirement(io.swagger.models.SecurityRequirement) Test(org.testng.annotations.Test)

Example 65 with Operation

use of io.swagger.models.Operation 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)

Aggregations

Operation (io.swagger.models.Operation)118 Test (org.testng.annotations.Test)80 Swagger (io.swagger.models.Swagger)45 Path (io.swagger.models.Path)39 BodyParameter (io.swagger.models.parameters.BodyParameter)27 Property (io.swagger.models.properties.Property)24 Response (io.swagger.models.Response)23 Parameter (io.swagger.models.parameters.Parameter)20 RefProperty (io.swagger.models.properties.RefProperty)16 ArrayModel (io.swagger.models.ArrayModel)15 Model (io.swagger.models.Model)14 QueryParameter (io.swagger.models.parameters.QueryParameter)13 StringProperty (io.swagger.models.properties.StringProperty)13 HashMap (java.util.HashMap)13 ArrayProperty (io.swagger.models.properties.ArrayProperty)12 ReaderContext (io.swagger.servlet.ReaderContext)12 PathParameter (io.swagger.models.parameters.PathParameter)11 ArrayList (java.util.ArrayList)11 MapProperty (io.swagger.models.properties.MapProperty)10 NicknamedOperation (io.swagger.resources.NicknamedOperation)10