Search in sources :

Example 31 with Info

use of io.swagger.models.Info in project incubator-servicecomb-java-chassis by apache.

the class SwaggerDefinitionProcessor method convertInfo.

private void convertInfo(io.swagger.annotations.Info infoAnnotation, Swagger swagger) {
    if (infoAnnotation == null) {
        return;
    }
    Info info = new Info();
    info.setTitle(infoAnnotation.title());
    info.setVersion(infoAnnotation.version());
    info.setDescription(infoAnnotation.description());
    info.setTermsOfService(infoAnnotation.termsOfService());
    info.setContact(convertContact(infoAnnotation.contact()));
    info.setLicense(convertLicense(infoAnnotation.license()));
    info.getVendorExtensions().putAll(BaseReaderUtils.parseExtensions(infoAnnotation.extensions()));
    swagger.setInfo(info);
}
Also used : Info(io.swagger.models.Info)

Example 32 with Info

use of io.swagger.models.Info in project sql-boot by sql-boot.

the class ApiController method getSwaggerDescription.

private Swagger getSwaggerDescription(HttpServletRequest request, String connectionName) {
    FsResourceTypes fsResourceTypes = new FsResourceTypes(dbConnectionList.getConnectionByName(connectionName));
    final List<ResourceType> resourceTypes = fsResourceTypes.resourceTypes();
    Swagger swagger = new Swagger();
    swagger.consumes("application/json");
    swagger.host(request.getServerName() + ":" + request.getServerPort());
    swagger.setInfo(new Info().version("v1").title("API specification"));
    swagger.setSchemes(asList(Scheme.HTTP, Scheme.HTTPS));
    swagger.path("/connections", new Path().get(new Operation().tag("connections").response(200, new Response().description("Ok").schema(new ArrayProperty(new RefProperty("connection")))).produces("application/json")));
    swagger.model("connection", new ModelImpl().property("name", new StringProperty().description("name")).property("url", new StringProperty().description("url")).property("user", new StringProperty().description("user")).property("driverClassName", new StringProperty().description("driverClassName")).property("configurationFolder", new StringProperty().description("configurationFolder")));
    // paths
    for (ResourceType resourceType : resourceTypes) {
        PathParameter parameter = new PathParameter().required(true).type("string").name("connection_name");
        parameter.setDefaultValue(connectionName);
        swagger.path("/api/{connection_name}/headers/" + resourceType.name(), new Path().get(new Operation().description(resourceType.name()).tag("db_objects").parameter(parameter).parameter(new QueryParameter().name("select").type("string")).parameter(new QueryParameter().name("distinct").type("boolean")).parameter(new QueryParameter().name("where").type("string")).parameter(new QueryParameter().name("page").type("string").description("get page by mask [page_count:page_size]")).parameter(new QueryParameter().name("limit").type("integer")).parameter(new QueryParameter().name("orderby").type("string")).parameter(new QueryParameter().name("cache").type("boolean")).response(200, new Response().description("Ok").schema(new ArrayProperty(new RefProperty(resourceType.name())))).produces("application/json")));
        final List<String> path = resourceType.path();
        final List<String> newPath = new ArrayList<>();
        for (String s : path) {
            newPath.add(s + "_name");
            List<Parameter> parameterList = new ArrayList<>();
            PathParameter parameterConnection = new PathParameter().required(true).type("string").name("connection_name");
            parameterConnection.setDefaultValue(connectionName);
            parameterList.add(parameterConnection);
            for (String s1 : newPath) {
                final PathParameter pathParameter = new PathParameter().required(true).type("string").name(s1);
                pathParameter.setDefaultValue("*");
                parameterList.add(pathParameter);
            }
            Operation operation = new Operation();
            operation.setParameters(parameterList);
            operation.parameter(new QueryParameter().name("select").type("string"));
            operation.parameter(new QueryParameter().name("distinct").type("boolean"));
            operation.parameter(new QueryParameter().name("where").type("string"));
            operation.parameter(new QueryParameter().name("page").type("string").description("get page by mask [page_count:page_size]"));
            operation.parameter(new QueryParameter().name("limit").type("integer"));
            operation.parameter(new QueryParameter().name("orderby").type("string"));
            operation.parameter(new QueryParameter().name("cache").type("boolean"));
            swagger.path("/api/{connection_name}/headers/" + resourceType.name() + "/" + newPath.stream().map(v -> "{" + v + "}").collect(joining(".")), new Path().get(operation.description(resourceType.name()).tag("db_objects").response(200, new Response().description("Ok").schema(new ArrayProperty(new RefProperty(resourceType.name())))).produces("application/json")));
        }
    }
    // definitions
    for (ResourceType resourceType : resourceTypes) {
        ModelImpl model = new ModelImpl();
        Map<String, String> stringStringMap = resourceType.metaData();
        if (stringStringMap != null) {
            Set<Entry<String, String>> entries = stringStringMap.entrySet();
            for (Entry<String, String> stringStringEntry : entries) {
                model.property(stringStringEntry.getKey(), new StringProperty().description(stringStringEntry.getValue()));
            }
        }
        swagger.model(resourceType.name(), model);
    }
    return swagger;
}
Also used : Path(io.swagger.models.Path) Scheme(io.swagger.models.Scheme) Yaml(io.swagger.util.Yaml) PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) SqlPlaceholdersWrapper(com.github.mgramin.sqlboot.model.uri.wrappers.SqlPlaceholdersWrapper) Swagger(io.swagger.models.Swagger) StringProperty(io.swagger.models.properties.StringProperty) Json(io.swagger.util.Json) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ModelImpl(io.swagger.models.ModelImpl) ArrayProperty(io.swagger.models.properties.ArrayProperty) GET(org.springframework.web.bind.annotation.RequestMethod.GET) CrossOrigin(org.springframework.web.bind.annotation.CrossOrigin) ArrayList(java.util.ArrayList) ResourceType(com.github.mgramin.sqlboot.model.resource_type.ResourceType) HttpServletRequest(javax.servlet.http.HttpServletRequest) Path(io.swagger.models.Path) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) RefProperty(io.swagger.models.properties.RefProperty) Operation(io.swagger.models.Operation) EnableAutoConfiguration(org.springframework.boot.autoconfigure.EnableAutoConfiguration) PathParameter(io.swagger.models.parameters.PathParameter) FsResourceTypes(com.github.mgramin.sqlboot.model.resource_type.impl.composite.FsResourceTypes) DbUri(com.github.mgramin.sqlboot.model.uri.impl.DbUri) Set(java.util.Set) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Parameter(io.swagger.models.parameters.Parameter) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) BootException(com.github.mgramin.sqlboot.exceptions.BootException) Info(io.swagger.models.Info) ComponentScan(org.springframework.context.annotation.ComponentScan) Collectors.joining(java.util.stream.Collectors.joining) QueryParameter(io.swagger.models.parameters.QueryParameter) DbConnectionList(com.github.mgramin.sqlboot.model.connection.DbConnectionList) Response(io.swagger.models.Response) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Stream(java.util.stream.Stream) Uri(com.github.mgramin.sqlboot.model.uri.Uri) Entry(java.util.Map.Entry) DbResource(com.github.mgramin.sqlboot.model.resource.DbResource) ResponseEntity(org.springframework.http.ResponseEntity) ArrayProperty(io.swagger.models.properties.ArrayProperty) QueryParameter(io.swagger.models.parameters.QueryParameter) ArrayList(java.util.ArrayList) StringProperty(io.swagger.models.properties.StringProperty) ResourceType(com.github.mgramin.sqlboot.model.resource_type.ResourceType) Operation(io.swagger.models.Operation) Info(io.swagger.models.Info) PathParameter(io.swagger.models.parameters.PathParameter) RefProperty(io.swagger.models.properties.RefProperty) Response(io.swagger.models.Response) Entry(java.util.Map.Entry) FsResourceTypes(com.github.mgramin.sqlboot.model.resource_type.impl.composite.FsResourceTypes) Swagger(io.swagger.models.Swagger) PathParameter(io.swagger.models.parameters.PathParameter) Parameter(io.swagger.models.parameters.Parameter) QueryParameter(io.swagger.models.parameters.QueryParameter) ModelImpl(io.swagger.models.ModelImpl)

Example 33 with Info

use of io.swagger.models.Info in project swagger-parser by swagger-api.

the class LegacyConverterTest method convertSingleFile.

/**
 * reads a single-file swagger definition
 */
@Test
public void convertSingleFile() throws Exception {
    Swagger swagger = converter.read("src/test/resources/specs/v1_2/singleFile.json");
    assertTrue(swagger.getSecurityDefinitions().size() == 2);
    SecuritySchemeDefinition auth = swagger.getSecurityDefinitions().get("oauth2");
    assertNotNull(auth);
    assertEquals(auth.getClass(), OAuth2Definition.class);
    OAuth2Definition oauth2 = (OAuth2Definition) auth;
    assertEquals(oauth2.getFlow(), "implicit");
    assertEquals(oauth2.getAuthorizationUrl(), "http://petstore.swagger.io/oauth/dialog");
    assertTrue(oauth2.getScopes().size() == 2);
    Map<String, String> scopes = oauth2.getScopes();
    assertEquals(scopes.get("email"), "Access to your email address");
    assertEquals(scopes.get("pets"), "Access to your pets");
    auth = swagger.getSecurityDefinitions().get("apiKey");
    assertNotNull(auth);
    assertEquals(auth.getClass(), ApiKeyAuthDefinition.class);
    ApiKeyAuthDefinition apiKey = (ApiKeyAuthDefinition) auth;
    assertEquals(apiKey.getName(), "api_key");
    assertEquals(apiKey.getIn(), In.HEADER);
    assertEquals(swagger.getSwagger(), "2.0");
    assertEquals(swagger.getHost(), "petstore.swagger.io");
    assertEquals(swagger.getBasePath(), "/api");
    assertNotNull(swagger.getInfo());
    Info info = swagger.getInfo();
    assertEquals(info.getVersion(), "1.0.0");
    assertEquals(info.getTitle(), "Swagger Sample App");
    assertEquals(info.getTermsOfService(), "http://swagger.io/terms/");
    Contact contact = info.getContact();
    assertEquals(contact.getUrl(), "apiteam@swagger.io");
    License license = info.getLicense();
    assertEquals(license.getName(), "Apache 2.0");
    assertEquals(license.getUrl(), "http://www.apache.org/licenses/LICENSE-2.0.html");
    assertTrue(swagger.getDefinitions().size() == 3);
    assertTrue(swagger.getPaths().size() == 5);
    Operation patchOperation = swagger.getPaths().get("/pet/{petId}").getPatch();
    List<Map<String, List<String>>> security = patchOperation.getSecurity();
    assertTrue(security.size() == 1);
    Map<String, List<String>> securityDetail = security.get(0);
    String key = securityDetail.keySet().iterator().next();
    assertEquals(key, "oauth2");
    List<String> oauth2Scopes = securityDetail.get(key);
    assertEquals(oauth2Scopes.size(), 1);
    assertEquals(oauth2Scopes.get(0), "test:anything");
    Operation fetchOperation = swagger.getPaths().get("/pet/findByStatus").getGet();
    QueryParameter param = (QueryParameter) fetchOperation.getParameters().get(0);
    assertEquals(param.getDefaultValue(), "available");
    List<String> _enum = param.getEnum();
    assertEquals(_enum.get(0), "available");
    assertEquals(_enum.get(1), "pending");
    assertEquals(_enum.get(2), "sold");
}
Also used : QueryParameter(io.swagger.models.parameters.QueryParameter) OAuth2Definition(io.swagger.models.auth.OAuth2Definition) License(io.swagger.models.License) SecuritySchemeDefinition(io.swagger.models.auth.SecuritySchemeDefinition) Operation(io.swagger.models.Operation) Info(io.swagger.models.Info) Contact(io.swagger.models.Contact) ApiKeyAuthDefinition(io.swagger.models.auth.ApiKeyAuthDefinition) Swagger(io.swagger.models.Swagger) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) Test(org.testng.annotations.Test)

Example 34 with Info

use of io.swagger.models.Info in project swagger-parser by swagger-api.

the class ResourceListingConverterTest method convertResourceListingWithSubPath.

@Test
public void convertResourceListingWithSubPath() throws Exception {
    ResourceListing rl = new ResourceListing();
    rl.setApiVersion("2.11");
    List<ApiDeclaration> apis = new ArrayList<ApiDeclaration>();
    ApiDeclaration api = new ApiDeclaration();
    api.setBasePath("https://foo.com/baz/bar");
    apis.add(api);
    Swagger swagger = converter.convert(rl, apis);
    assertTrue(swagger.getSchemes().size() == 1);
    assertTrue(swagger.getSchemes().get(0).equals(Scheme.HTTPS));
    assertTrue(swagger.getSwagger().equals("2.0"));
    Info info = swagger.getInfo();
    assertNotNull(info);
    assertEquals(info.getVersion(), rl.getApiVersion());
    assertEquals(swagger.getBasePath(), "/baz/bar");
    assertEquals(swagger.getHost(), "foo.com");
}
Also used : ApiDeclaration(io.swagger.models.apideclaration.ApiDeclaration) ResourceListing(io.swagger.models.resourcelisting.ResourceListing) Swagger(io.swagger.models.Swagger) ArrayList(java.util.ArrayList) Info(io.swagger.models.Info) Test(org.testng.annotations.Test)

Example 35 with Info

use of io.swagger.models.Info in project swagger-parser by swagger-api.

the class SwaggerCompatConverter method convert.

public Swagger convert(ResourceListing resourceListing, List<ApiDeclaration> apiDeclarations) {
    Info info = new Info();
    if (resourceListing.getInfo() != null) {
        ApiInfo apiInfo = resourceListing.getInfo();
        Contact contact = null;
        if (apiInfo.getContact() != null) {
            contact = new Contact().url(apiInfo.getContact());
        }
        License license = null;
        if (apiInfo.getLicense() != null) {
            license = new License().name(apiInfo.getLicense()).url(apiInfo.getLicenseUrl());
        }
        info = new Info().description(apiInfo.getDescription()).version(resourceListing.getApiVersion()).title(apiInfo.getTitle()).termsOfService(apiInfo.getTermsOfServiceUrl()).contact(contact).license(license);
    } else if (resourceListing.getApiVersion() != null) {
        info = new Info().version(resourceListing.getApiVersion());
    }
    Map<String, Path> paths = new HashMap<String, Path>();
    Map<String, Model> definitions = new HashMap<String, Model>();
    String basePath = null;
    for (ApiDeclaration apiDeclaration : apiDeclarations) {
        String tag;
        if (apiDeclaration.getApiListingRef() != null) {
            String refPath = apiDeclaration.getApiListingRef().getPath();
            tag = refPath.substring(refPath.lastIndexOf("/") + 1);
        } else {
            tag = apiDeclaration.getResourcePath();
        }
        if (tag != null) {
            tag = tag.replaceAll("/", "");
        }
        if (basePath != null) {
            if (!basePath.equals(apiDeclaration.getBasePath()) && apiDeclaration.getBasePath() != null) {
                LOGGER.warn("warning!  multiple basePath values not supported!");
            }
        } else {
            basePath = apiDeclaration.getBasePath();
        }
        List<Api> apis = apiDeclaration.getApis();
        for (Api api : apis) {
            String apiPath = api.getPath();
            String description = api.getDescription();
            List<io.swagger.models.apideclaration.Operation> ops = api.getOperations();
            Path path = paths.get(apiPath);
            if (path == null) {
                path = new Path();
                paths.put(apiPath, path);
            }
            for (io.swagger.models.apideclaration.Operation op : ops) {
                Operation operation = convertOperation(tag, op, apiDeclaration);
                if (op.getMethod() != null) {
                    path.set(op.getMethod().toString().toLowerCase(), operation);
                } else {
                    LOGGER.info("skipping operation with missing method:\n" + Json.pretty(op));
                }
            }
        }
        // model definitions
        Map<String, io.swagger.models.apideclaration.Model> apiModels = apiDeclaration.getModels();
        for (String key : apiModels.keySet()) {
            Model model = convertModel(apiModels.get(key));
            definitions.put(key, model);
        }
    }
    String host = null;
    String scheme = "http";
    if (basePath != null) {
        String[] parts = basePath.split("://");
        if (parts.length == 2) {
            scheme = parts[0];
            int pos = parts[1].indexOf("/");
            if (pos != -1) {
                host = parts[1].substring(0, pos);
                basePath = parts[1].substring(pos);
            } else {
                host = parts[1];
                basePath = "/";
            }
        }
        if (!basePath.startsWith("/")) {
            basePath = "/" + basePath;
        }
    }
    Swagger swagger = new Swagger().host(host).scheme(Scheme.forValue(scheme)).basePath(basePath).info(info).paths(paths).basePath(basePath);
    swagger.setDefinitions(definitions);
    // host is read from the api declarations
    Map<String, Authorization> authorizations = resourceListing.getAuthorizations();
    if (authorizations != null) {
        for (String authNickname : authorizations.keySet()) {
            Authorization auth = authorizations.get(authNickname);
            if (auth instanceof OAuth2Authorization) {
                OAuth2Authorization o2 = (OAuth2Authorization) auth;
                List<AuthorizationScope> scopes = o2.getScopes();
                if (o2.getGrantTypes().getImplicit() != null) {
                    ImplicitGrant ig = o2.getGrantTypes().getImplicit();
                    OAuth2Definition oauth2 = new OAuth2Definition().implicit(ig.getLoginEndpoint().getUrl());
                    if (swagger.getSecurityDefinitions() != null && swagger.getSecurityDefinitions().keySet().contains(authNickname)) {
                        System.err.println("Warning!  Authorization nickname already in use!");
                    } else {
                        swagger.securityDefinition(authNickname, oauth2);
                    }
                    for (AuthorizationScope scope : scopes) {
                        oauth2.scope(scope.getScope(), scope.getDescription());
                    }
                } else if (o2.getGrantTypes().getAuthorization_code() != null) {
                    AuthorizationCodeGrant ac = (AuthorizationCodeGrant) o2.getGrantTypes().getAuthorization_code();
                    OAuth2Definition oauth2 = new OAuth2Definition().accessCode(ac.getTokenRequestEndpoint().getUrl(), ac.getTokenEndpoint().getUrl());
                    if (swagger.getSecurityDefinitions() != null && swagger.getSecurityDefinitions().keySet().contains(authNickname)) {
                        System.err.println("Warning!  Authorization nickname already in use!");
                    } else {
                        swagger.securityDefinition(authNickname, oauth2);
                    }
                    for (AuthorizationScope scope : scopes) {
                        oauth2.scope(scope.getScope(), scope.getDescription());
                    }
                }
            } else if (auth instanceof ApiKeyAuthorization) {
                ApiKeyAuthorization o2 = (ApiKeyAuthorization) auth;
                ApiKeyAuthDefinition def = new ApiKeyAuthDefinition();
                PassAs passAs = o2.getPassAs();
                if (PassAs.HEADER.equals(passAs)) {
                    def.in(In.HEADER);
                } else {
                    def.in(In.QUERY);
                }
                def.setName(o2.getKeyname());
                swagger.securityDefinition(authNickname, def);
            } else if (auth instanceof BasicAuthorization) {
                BasicAuthDefinition def = new BasicAuthDefinition();
                swagger.securityDefinition(authNickname, def);
            }
        }
    }
    return swagger;
}
Also used : HashMap(java.util.HashMap) BasicAuthorization(io.swagger.models.resourcelisting.BasicAuthorization) License(io.swagger.models.License) OAuth2Definition(io.swagger.models.auth.OAuth2Definition) Operation(io.swagger.models.Operation) BasicAuthorization(io.swagger.models.resourcelisting.BasicAuthorization) ApiKeyAuthorization(io.swagger.models.resourcelisting.ApiKeyAuthorization) Authorization(io.swagger.models.resourcelisting.Authorization) OAuth2Authorization(io.swagger.models.resourcelisting.OAuth2Authorization) PassAs(io.swagger.models.PassAs) Swagger(io.swagger.models.Swagger) ApiKeyAuthorization(io.swagger.models.resourcelisting.ApiKeyAuthorization) Path(io.swagger.models.Path) ApiDeclaration(io.swagger.models.apideclaration.ApiDeclaration) OAuth2Authorization(io.swagger.models.resourcelisting.OAuth2Authorization) Info(io.swagger.models.Info) ApiInfo(io.swagger.models.resourcelisting.ApiInfo) BasicAuthDefinition(io.swagger.models.auth.BasicAuthDefinition) Contact(io.swagger.models.Contact) ApiKeyAuthDefinition(io.swagger.models.auth.ApiKeyAuthDefinition) AuthorizationCodeGrant(io.swagger.models.resourcelisting.AuthorizationCodeGrant) ApiInfo(io.swagger.models.resourcelisting.ApiInfo) Model(io.swagger.models.Model) RefModel(io.swagger.models.RefModel) ArrayModel(io.swagger.models.ArrayModel) ImplicitGrant(io.swagger.models.resourcelisting.ImplicitGrant) Api(io.swagger.models.apideclaration.Api) AuthorizationScope(io.swagger.models.AuthorizationScope)

Aggregations

Info (io.swagger.models.Info)39 Swagger (io.swagger.models.Swagger)26 Contact (io.swagger.models.Contact)12 Operation (io.swagger.models.Operation)10 Path (io.swagger.models.Path)9 Test (org.testng.annotations.Test)8 License (io.swagger.models.License)7 QueryParameter (io.swagger.models.parameters.QueryParameter)7 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)7 ApiKeyAuthDefinition (io.swagger.models.auth.ApiKeyAuthDefinition)5 PathParameter (io.swagger.models.parameters.PathParameter)5 Model (io.swagger.models.Model)4 OAuth2Definition (io.swagger.models.auth.OAuth2Definition)4 Parameter (io.swagger.models.parameters.Parameter)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 UriTemplate (org.wso2.carbon.apimgt.core.models.UriTemplate)4 ServiceMethodInfo (org.wso2.msf4j.ServiceMethodInfo)4 Response (io.swagger.models.Response)3 Scheme (io.swagger.models.Scheme)3