Java Code Examples for io.swagger.v3.oas.models.OpenAPI#setPaths()

The following examples show how to use io.swagger.v3.oas.models.OpenAPI#setPaths() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestUtils.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public static OpenAPI createOpenAPI() {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());
    openAPI.setPaths(new Paths());

    final Info info = new Info();
    info.setDescription("API under test");
    info.setVersion("1.0.7");
    info.setTitle("My title");
    openAPI.setInfo(info);

    final Server server = new Server();
    server.setUrl("https://localhost:9999/root");
    openAPI.setServers(Collections.singletonList(server));
    return openAPI;
}
 
Example 2
Source File: DefaultGeneratorTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonStrictProcessPaths() throws Exception {
    OpenAPI openAPI = TestUtils.createOpenAPI();
    openAPI.setPaths(new Paths());
    openAPI.getPaths().addPathItem("path1/", new PathItem().get(new Operation().operationId("op1").responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")))));
    openAPI.getPaths().addPathItem("path2/", new PathItem().get(new Operation().operationId("op2").addParametersItem(new QueryParameter().name("p1").schema(new StringSchema())).responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")))));

    ClientOptInput opts = new ClientOptInput();
    opts.setOpenAPI(openAPI);
    CodegenConfig config = new DefaultCodegen();
    config.setStrictSpecBehavior(false);
    opts.setConfig(config);

    DefaultGenerator generator = new DefaultGenerator();
    generator.opts(opts);
    Map<String, List<CodegenOperation>> result = generator.processPaths(openAPI.getPaths());
    Assert.assertEquals(result.size(), 1);
    List<CodegenOperation> defaultList = result.get("Default");
    Assert.assertEquals(defaultList.size(), 2);
    Assert.assertEquals(defaultList.get(0).path, "path1/");
    Assert.assertEquals(defaultList.get(0).allParams.size(), 0);
    Assert.assertEquals(defaultList.get(1).path, "path2/");
    Assert.assertEquals(defaultList.get(1).allParams.size(), 1);
}
 
Example 3
Source File: ApiDocControllerTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
private OpenAPI getDummyOpenApiObject() {
    List<Server> servers = new ArrayList<>();
    servers.add(0, new Server().url("/api/v1/apicatalog"));
    OpenAPI openAPI = new OpenAPI();
    openAPI.setPaths(new Paths());
    openAPI.setTags(new ArrayList<>());
    openAPI.setOpenapi("3.0.0");
    openAPI.setServers(servers);

    Info info = new Info();
    info.setTitle("Service title");
    info.setDescription("Service description");
    info.setVersion("1.0.0");
    openAPI.setInfo(info);

    return openAPI;
}
 
Example 4
Source File: AbstractApiDocServiceTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
private OpenAPI getDummyOpenApiObject(List<Server> servers) {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setPaths(new Paths());
    openAPI.setTags(new ArrayList<>());
    openAPI.setOpenapi("3.0.0");
    openAPI.setServers(servers);

    Info info = new Info();
    info.setTitle("API Catalog");
    info.setDescription("REST API for the API Catalog service which is a component of the API Mediation Layer. Use this API to retrieve information regarding catalog dashboard tiles, tile contents and its status, API documentation and status for the registered services.");
    info.setVersion("1.0.0");
    openAPI.setInfo(info);

    Tag tag = new Tag();
    tag.setName("API Catalog");
    tag.setDescription("Current state information");
    openAPI.getTags().add(tag);

    openAPI.getPaths().put("/api1", new PathItem());
    openAPI.getPaths().put("/api2", new PathItem());
    return openAPI;
}
 
Example 5
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
private OpenAPI createBasicModel() {
    OpenAPI openAPI = new OpenAPI();

    Info info = new Info();
    info.setTitle(configuration.getApplicationTitle());
    info.setVersion(configuration.getApplicationApiVersion());
    openAPI.setInfo(info);

    Paths paths = new Paths();
    openAPI.setPaths(paths);

    Server server = new Server();
    server.setUrl(configuration.getServerUrl());
    server.setDescription(configuration.getServerDescription());
    openAPI.setServers(Collections.singletonList(server));
    Components components = new Components();
    SecurityScheme vaadinConnectOAuth2Scheme = new SecurityScheme()
            .type(SecurityScheme.Type.OAUTH2)
            .flows(new OAuthFlows().password(new OAuthFlow()
                    .tokenUrl(VAADIN_CONNECT_OAUTH2_TOKEN_URL)
                    .scopes(new Scopes())));
    components.addSecuritySchemes(VAADIN_CONNECT_OAUTH2_SECURITY_SCHEME,
            vaadinConnectOAuth2Scheme);
    openAPI.components(components);
    return openAPI;
}
 
Example 6
Source File: OpenAPIGenerator.java    From spring-openapi with MIT License 5 votes vote down vote up
public OpenAPI generate(OpenApiGeneratorConfig openApiGeneratorConfig) {
      logger.info("Starting OpenAPI generation");
environment = openApiGeneratorConfig.getEnvironment();
      initializeExampleInterceptor(openApiGeneratorConfig);
      OpenAPI openAPI = new OpenAPI();
      openAPI.setComponents(createComponentsWrapper());
      openAPI.setPaths(createPathsWrapper());
      openAPI.setInfo(info);
      logger.info("OpenAPI generation done!");
      return openAPI;
  }
 
Example 7
Source File: DefaultGeneratorTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessPaths() throws Exception {
    OpenAPI openAPI = TestUtils.createOpenAPI();
    openAPI.setPaths(new Paths());
    openAPI.getPaths().addPathItem("/path1", new PathItem().get(new Operation().operationId("op1").responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")))));
    openAPI.getPaths().addPathItem("/path2", new PathItem().get(new Operation().operationId("op2").addParametersItem(new QueryParameter().name("p1").schema(new StringSchema())).responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")))));
    openAPI.getPaths().addPathItem("/path3", new PathItem().addParametersItem(new QueryParameter().name("p1").schema(new StringSchema())).get(new Operation().operationId("op3").addParametersItem(new QueryParameter().name("p2").schema(new IntegerSchema())).responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")))));
    openAPI.getPaths().addPathItem("/path4", new PathItem().addParametersItem(new QueryParameter().name("p1").schema(new StringSchema())).get(new Operation().operationId("op4").responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")))));

    ClientOptInput opts = new ClientOptInput();
    opts.setOpenAPI(openAPI);
    opts.setConfig(new DefaultCodegen());

    DefaultGenerator generator = new DefaultGenerator();
    generator.opts(opts);
    Map<String, List<CodegenOperation>> result = generator.processPaths(openAPI.getPaths());
    Assert.assertEquals(result.size(), 1);
    List<CodegenOperation> defaultList = result.get("Default");
    Assert.assertEquals(defaultList.size(), 4);
    Assert.assertEquals(defaultList.get(0).path, "/path1");
    Assert.assertEquals(defaultList.get(0).allParams.size(), 0);
    Assert.assertEquals(defaultList.get(1).path, "/path2");
    Assert.assertEquals(defaultList.get(1).allParams.size(), 1);
    Assert.assertEquals(defaultList.get(2).path, "/path3");
    Assert.assertEquals(defaultList.get(2).allParams.size(), 2);
    Assert.assertEquals(defaultList.get(3).path, "/path4");
    Assert.assertEquals(defaultList.get(3).allParams.size(), 1);
}
 
Example 8
Source File: ApiDocV3Service.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Updates Servers and Paths in OpenAPI
 *
 * @param openAPI    the API doc
 * @param serviceId  the unique service id
 * @param apiDocInfo the service information
 * @param hidden     do not set Paths for automatically generated API doc
 */
protected void updatePaths(OpenAPI openAPI, String serviceId, ApiDocInfo apiDocInfo, boolean hidden) {
    ApiDocPath<PathItem> apiDocPath = new ApiDocPath<>();
    Server server = getBestMatchingServer(openAPI.getServers(), apiDocInfo);
    String basePath = server != null ? getBasePath(server.getUrl()) : "";

    if (openAPI.getPaths() != null && !openAPI.getPaths().isEmpty()) {
        openAPI.getPaths()
            .forEach((originalEndpoint, path)
                -> preparePath(path, apiDocPath, apiDocInfo, basePath, originalEndpoint, serviceId));
    }

    Map<String, PathItem> updatedPaths;
    if (apiDocPath.getPrefixes().size() == 1) {
        updateServerUrl(openAPI, server, apiDocPath.getPrefixes().iterator().next() + OpenApiUtil.SEPARATOR + serviceId);
        updatedPaths = apiDocPath.getShortPaths();
    } else {
        updateServerUrl(openAPI, server, "");
        updatedPaths = apiDocPath.getLongPaths();
    }

    if (!hidden) {
        Paths paths = new Paths();
        updatedPaths.keySet().forEach(pathName -> paths.addPathItem(pathName, updatedPaths.get(pathName)));
        openAPI.setPaths(paths);
    }
}
 
Example 9
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public static String updateAPIProductSwaggerOperations(Map<API, List<APIProductResource>> apiToProductResourceMapping,
                                                       String destinationSwagger)
        throws APIManagementException {
    SwaggerVersion destinationSwaggerVersion = getSwaggerVersion(destinationSwagger);
    OpenAPI destOpenAPI;

    if (destinationSwaggerVersion == SwaggerVersion.OPEN_API) {
        destOpenAPI = ((OAS3Parser) oas3Parser).getOpenAPI(destinationSwagger);
    } else {
        throw new APIManagementException("Cannot update destination swagger because it is not in OpenAPI format");
    }

    SwaggerUpdateContext context = new SwaggerUpdateContext();

    extractRelevantSourceData(apiToProductResourceMapping, context);

    // Update paths
    destOpenAPI.setPaths(context.getPaths());

    // Update Scopes
    setScopes(destOpenAPI, context.getAggregatedScopes());

    // Update reference definitions
    setReferenceObjectDefinitions(destOpenAPI, context);

    return Json.pretty(destOpenAPI);
}
 
Example 10
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Construct openAPI definition for graphQL. Add get and post operations
 *
 * @param openAPI OpenAPI
 * @return modified openAPI for GraphQL
 */
private void modifyGraphQLSwagger(OpenAPI openAPI) {
    SwaggerData.Resource resource = new SwaggerData.Resource();
    resource.setAuthType(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN);
    resource.setPolicy(APIConstants.DEFAULT_SUB_POLICY_UNLIMITED);
    resource.setPath("/");
    resource.setVerb(APIConstants.HTTP_POST);
    Operation postOperation = createOperation(resource);

    //post operation
    RequestBody requestBody = new RequestBody();
    requestBody.setDescription("Query or mutation to be passed to graphQL API");
    requestBody.setRequired(true);

    JSONObject typeOfPayload = new JSONObject();
    JSONObject payload = new JSONObject();
    typeOfPayload.put(APIConstants.TYPE, APIConstants.STRING);
    payload.put(APIConstants.OperationParameter.PAYLOAD_PARAM_NAME, typeOfPayload);

    Schema postSchema = new Schema();
    postSchema.setType(APIConstants.OBJECT);
    postSchema.setProperties(payload);

    MediaType mediaType = new MediaType();
    mediaType.setSchema(postSchema);

    Content content = new Content();
    content.addMediaType(APPLICATION_JSON_MEDIA_TYPE, mediaType);
    requestBody.setContent(content);
    postOperation.setRequestBody(requestBody);

    //add post and get operations to path /*
    PathItem pathItem = new PathItem();
    pathItem.setPost(postOperation);
    Paths paths = new Paths();
    paths.put("/", pathItem);

    openAPI.setPaths(paths);
}
 
Example 11
Source File: OpenAPIDeserializer.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
public OpenAPI parseRoot(JsonNode node, ParseResult result, String path) {
    String location = "";
    OpenAPI openAPI = new OpenAPI();
    if (node.getNodeType().equals(JsonNodeType.OBJECT)) {
        ObjectNode rootNode = (ObjectNode) node;

        // required
        String value = getString("openapi", rootNode, true, location, result);

        // we don't even try if the version isn't there
        if(value == null || !value.startsWith("3.0")) {
            return null;
        }
        openAPI.setOpenapi(value);

        ObjectNode obj = getObject("info", rootNode, true, location, result);
        if (obj != null) {
            Info info = getInfo(obj, "info", result);
            openAPI.setInfo(info);
        }

        obj = getObject("components", rootNode, false, location, result);
        if (obj != null) {
            Components components = getComponents(obj, "components", result);
            openAPI.setComponents(components);
            this.components=components;
        }

        obj = getObject("paths", rootNode, true, location, result);
        if (obj != null) {
            Paths paths = getPaths(obj, "paths", result);
            openAPI.setPaths(paths);
        }


        ArrayNode array = getArray("servers", rootNode, false, location, result);
        if (array != null && array.size() > 0) {
            openAPI.setServers(getServersList(array, String.format("%s.%s", location, "servers"), result, path));
        }else {
            Server defaultServer = new Server();
            defaultServer.setUrl("/");
            List<Server>  servers = new ArrayList<>();
            servers.add(defaultServer);
            openAPI.setServers(servers);
        }

        obj = getObject("externalDocs", rootNode, false, location, result);
        if (obj != null) {
            ExternalDocumentation externalDocs = getExternalDocs(obj, "externalDocs", result);
            openAPI.setExternalDocs(externalDocs);
        }

        array = getArray("tags", rootNode, false, location, result);
        if (array != null && array.size() > 0) {
            openAPI.setTags(getTagList(array, "tags", result));
        }

        array = getArray("security", rootNode, false, location, result);
        if (array != null && array.size() > 0) {
            List<SecurityRequirement> securityRequirements = getSecurityRequirementsList(array, "security", result);
            if (securityRequirements != null && securityRequirements. size() > 0) {
                openAPI.setSecurity(securityRequirements);
            }
        }

        Map <String,Object> extensions = getExtensions(rootNode);
        if(extensions != null && extensions.size() > 0) {
            openAPI.setExtensions(extensions);
        }

        Set<String> keys = getKeys(rootNode);
        for(String key : keys) {
            if(!ROOT_KEYS.contains(key) && !key.startsWith("x-")) {
                result.extra(location, key, node.get(key));
            }
        }

    } else {
        result.invalidType(location, "openapi", "object", node);
        result.invalid();
        return null;
    }

    return openAPI;
}
 
Example 12
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method generates API definition to the given api
 *
 * @param swaggerData api
 * @return API definition in string format
 * @throws APIManagementException
 */
@Override
public String generateAPIDefinition(SwaggerData swaggerData) throws APIManagementException {
    OpenAPI openAPI = new OpenAPI();

    // create path if null
    if (openAPI.getPaths() == null) {
        openAPI.setPaths(new Paths());
    }

    //Create info object
    Info info = new Info();
    info.setTitle(swaggerData.getTitle());
    if (swaggerData.getDescription() != null) {
        info.setDescription(swaggerData.getDescription());
    }

    Contact contact = new Contact();
    //Create contact object and map business owner info
    if (swaggerData.getContactName() != null) {
        contact.setName(swaggerData.getContactName());
    }
    if (swaggerData.getContactEmail() != null) {
        contact.setEmail(swaggerData.getContactEmail());
    }
    if (swaggerData.getContactName() != null || swaggerData.getContactEmail() != null) {
        //put contact object to info object
        info.setContact(contact);
    }

    info.setVersion(swaggerData.getVersion());
    openAPI.setInfo(info);
    updateSwaggerSecurityDefinition(openAPI, swaggerData, "https://test.com");
    updateLegacyScopesFromSwagger(openAPI, swaggerData);
    if (APIConstants.GRAPHQL_API.equals(swaggerData.getTransportType())) {
        modifyGraphQLSwagger(openAPI);
    } else {
        for (SwaggerData.Resource resource : swaggerData.getResources()) {
            addOrUpdatePathToSwagger(openAPI, resource);
        }
    }
    return Json.pretty(openAPI);
}
 
Example 13
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method returns URI templates according to the given swagger file(Swagger version 3)
 *
 * @param openAPI OpenAPI
 * @return OpenAPI
 * @throws APIManagementException
 */
private OpenAPI injectOtherResourceScopesToDefaultScheme(OpenAPI openAPI) throws APIManagementException {
    List<String> schemes = getOtherSchemes();

    Paths paths = openAPI.getPaths();
    for (String pathKey : paths.keySet()) {
        PathItem pathItem = paths.get(pathKey);
        Map<PathItem.HttpMethod, Operation> operationsMap = pathItem.readOperationsMap();
        SecurityRequirement updatedDefaultSecurityRequirement = new SecurityRequirement();
        for (Map.Entry<PathItem.HttpMethod, Operation> entry : operationsMap.entrySet()) {
            PathItem.HttpMethod httpMethod = entry.getKey();
            Operation operation = entry.getValue();
            List<SecurityRequirement> securityRequirements = operation.getSecurity();
            if (securityRequirements == null) {
                securityRequirements = new ArrayList<>();
            }
            if (APIConstants.SUPPORTED_METHODS.contains(httpMethod.name().toLowerCase())) {
                List<String> opScopesDefault = new ArrayList<>();
                List<String> opScopesDefaultInstance = getScopeOfOperations(OPENAPI_SECURITY_SCHEMA_KEY, operation);
                if (opScopesDefaultInstance != null) {
                    opScopesDefault.addAll(opScopesDefaultInstance);
                }
                updatedDefaultSecurityRequirement.put(OPENAPI_SECURITY_SCHEMA_KEY, opScopesDefault);
                for (Map<String, List<String>> input : securityRequirements) {
                    for (String scheme : schemes) {
                        if (!OPENAPI_SECURITY_SCHEMA_KEY.equals(scheme)) {
                            List<String> opScopesOthers = getScopeOfOperations(scheme, operation);
                            if (opScopesOthers != null) {
                                for (String scope : opScopesOthers) {
                                    if (!opScopesDefault.contains(scope)) {
                                        opScopesDefault.add(scope);
                                    }
                                }
                            }
                        }
                        updatedDefaultSecurityRequirement.put(OPENAPI_SECURITY_SCHEMA_KEY, opScopesDefault);
                    }
                }
                securityRequirements.add(updatedDefaultSecurityRequirement);
            }
            operation.setSecurity(securityRequirements);
            entry.setValue(operation);
            operationsMap.put(httpMethod, operation);
        }
        paths.put(pathKey, pathItem);
    }
    openAPI.setPaths(paths);
    return openAPI;
}