io.swagger.v3.oas.models.Paths Java Examples

The following examples show how to use io.swagger.v3.oas.models.Paths. 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: 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 #2
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 #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: 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 #5
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 #6
Source File: DefaultGenerator.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a file at .openapi-generator/VERSION to track the version of user's latest run.
 *
 * @param files The list tracking generated files
 */
private void generateVersionMetadata(List<File> files) {
    String versionMetadata = config.outputFolder() + File.separator + METADATA_DIR + File.separator + "VERSION";
    if (generateMetadata) {
        File versionMetadataFile = new File(versionMetadata);
        try {
            File written = this.templateProcessor.writeToFile(versionMetadata, ImplementationVersion.read().getBytes(StandardCharsets.UTF_8));
            if (written != null) {
                files.add(versionMetadataFile);
                if (config.isEnablePostProcessFile() && !dryRun) {
                    config.postProcessFile(written, "openapi-generator-version");
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Could not generate supporting file '" + versionMetadata + "'", e);
        }
    } else {
        Path metadata = java.nio.file.Paths.get(versionMetadata);
        this.templateProcessor.skip(metadata, "Skipped by generateMetadata option supplied by user.");
    }
}
 
Example #7
Source File: DefaultGenerator.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public Map<String, List<CodegenOperation>> processPaths(Paths paths) {
    Map<String, List<CodegenOperation>> ops = new TreeMap<>();
    // when input file is not valid and doesn't contain any paths
    if(paths == null) {
        return ops;
    }
    for (String resourcePath : paths.keySet()) {
        PathItem path = paths.get(resourcePath);
        processOperation(resourcePath, "get", path.getGet(), ops, path);
        processOperation(resourcePath, "head", path.getHead(), ops, path);
        processOperation(resourcePath, "put", path.getPut(), ops, path);
        processOperation(resourcePath, "post", path.getPost(), ops, path);
        processOperation(resourcePath, "delete", path.getDelete(), ops, path);
        processOperation(resourcePath, "patch", path.getPatch(), ops, path);
        processOperation(resourcePath, "options", path.getOptions(), ops, path);
        processOperation(resourcePath, "trace", path.getTrace(), ops, path);
    }
    return ops;
}
 
Example #8
Source File: DefaultGenerator.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private void generateModelTests(List<File> files, Map<String, Object> models, String modelName) throws IOException {
    // to generate model test files
    for (String templateName : config.modelTestTemplateFiles().keySet()) {
        String suffix = config.modelTestTemplateFiles().get(templateName);
        String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(modelName) + suffix;

        if (generateModelTests) {
            // do not overwrite test file that already exists (regardless of config's skipOverwrite setting)
            File modelTestFile = new File(filename);
            if (modelTestFile.exists()) {
                this.templateProcessor.skip(modelTestFile.toPath(), "Test files never overwrite an existing file of the same name.");
            } else {
                File written = processTemplateToFile(models, templateName, filename, generateModelTests, CodegenConstants.MODEL_TESTS);
                if (written != null) {
                    files.add(written);
                    if (config.isEnablePostProcessFile() && !dryRun) {
                        config.postProcessFile(written, "model-test");
                    }
                }
            }
        } else if (dryRun) {
            Path skippedPath = java.nio.file.Paths.get(filename);
            this.templateProcessor.skip(skippedPath, "Skipped by modelTests option supplied by user.");
        }
    }
}
 
Example #9
Source File: PathsDocument.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Override
public Document apply(Document document, Parameters parameters) {
    Paths apiPaths = parameters.schema.getPaths();

    if (null == apiPaths || apiPaths.isEmpty()) return document;

    SectionImpl allPathsSection = new SectionImpl(document);
    allPathsSection.setTitle(labels.getLabel(SECTION_TITLE_PATHS));

    apiPaths.forEach((name, pathItem) ->
            pathItem.readOperationsMap().forEach(((httpMethod, operation) -> {
                SectionImpl operationSection = new SectionImpl(allPathsSection);
                String summary = Optional.ofNullable(operation.getSummary()).orElse("");
                operationSection.setTitle((italicUnconstrained(httpMethod.name().toUpperCase()) + " " + monospaced(name) + " " + summary).trim());
                appendDescription(operationSection, operation.getDescription());
                externalDocumentationComponent.apply(operationSection, operation.getExternalDocs());
                parametersComponent.apply(operationSection, operation.getParameters());
                responseComponent.apply(operationSection, operation.getResponses());
                appendServersSection(operationSection, operation.getServers());
                securityRequirementTableComponent.apply(operationSection, operation.getSecurity(), false);
                allPathsSection.append(operationSection);
            })));

    document.append(allPathsSection);
    return document;
}
 
Example #10
Source File: OpenAPIBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiates a new Open api builder.
 *
 * @param openAPI the open api
 * @param context the context
 * @param securityParser the security parser
 * @param springDocConfigProperties the spring doc config properties
 * @param openApiBuilderCustomisers the open api builder customisers
 */
OpenAPIBuilder(Optional<OpenAPI> openAPI, ApplicationContext context, SecurityParser securityParser,
		SpringDocConfigProperties springDocConfigProperties,
		Optional<List<OpenApiBuilderCustomiser>> openApiBuilderCustomisers) {
	if (openAPI.isPresent()) {
		this.openAPI = openAPI.get();
		if (this.openAPI.getComponents() == null)
			this.openAPI.setComponents(new Components());
		if (this.openAPI.getPaths() == null)
			this.openAPI.setPaths(new Paths());
		if (!CollectionUtils.isEmpty(this.openAPI.getServers()))
			this.isServersPresent = true;
	}
	this.context = context;
	this.securityParser = securityParser;
	this.springDocConfigProperties = springDocConfigProperties;
	this.openApiBuilderCustomisers = openApiBuilderCustomisers;
}
 
Example #11
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void readEmptySecurityRequirement() throws Exception {
    final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    final JsonNode rootNode = mapper.readTree(Files.readAllBytes(java.nio.file.Paths.get(getClass().getResource("/oas.yaml").toURI())));

    final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
    final SwaggerParseResult result = deserializer.deserialize(rootNode);

    Assert.assertNotNull(result);

    final OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);

    SecurityRequirement securityRequirement = openAPI.getSecurity().get(0);

    assertTrue(securityRequirement.isEmpty());
    assertEquals(openAPI.getSecurity().size(), 4);
}
 
Example #12
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "data")
public void readRequestBodyObject(JsonNode rootNode) throws Exception {
    final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
    final SwaggerParseResult result = deserializer.deserialize(rootNode);

    Assert.assertNotNull(result);

    final OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);

    final Paths paths = openAPI.getPaths();
    Assert.assertNotNull(paths);

    PathItem petByStatusEndpoint = paths.get("/pet/findByStatus");
    Assert.assertNotNull(petByStatusEndpoint.getGet().getRequestBody());
    Assert.assertEquals(petByStatusEndpoint.getGet().getRequestBody().getDescription(),"pet store to add to the system");
    assertTrue(petByStatusEndpoint.getGet().getRequestBody().getRequired(),"true");
    Assert.assertNotNull(petByStatusEndpoint.getGet().getRequestBody().getContent().get("multipart/mixed"));
    Assert.assertEquals(petByStatusEndpoint.getGet().getRequestBody().getContent().get("multipart/mixed").getSchema().getType(),"object");
    Assert.assertNotNull(petByStatusEndpoint.getGet().getRequestBody().getContent().get("multipart/mixed").getSchema().getProperties());


    Assert.assertEquals(petByStatusEndpoint.getGet().getRequestBody().getContent().get("multipart/mixed").getEncoding().get("historyMetadata").getContentType(),"application/xml; charset=utf-8");
    Assert.assertNotNull(petByStatusEndpoint.getGet().getRequestBody().getContent().get("multipart/mixed").getEncoding().get("profileImage").getHeaders());
    Assert.assertNotNull(petByStatusEndpoint.getGet().getRequestBody().getContent().get("multipart/mixed").getEncoding().get("profileImage").getHeaders().get("X-Rate-Limit"));
}
 
Example #13
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "data")
public void readExamplesObject(JsonNode rootNode) throws Exception {
    final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
    final SwaggerParseResult result = deserializer.deserialize(rootNode);

    Assert.assertNotNull(result);

    final OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);

    final Paths paths = openAPI.getPaths();
    Assert.assertNotNull(paths);
    Assert.assertEquals(paths.size(), 18);

    //parameters operation get
    PathItem petByStatusEndpoint = paths.get("/pet/findByStatus");
    Assert.assertNotNull(petByStatusEndpoint.getGet());
    Assert.assertNotNull(petByStatusEndpoint.getGet().getParameters());
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().size(), 1);
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getName(), "status");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getIn(),"query");

}
 
Example #14
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "data")
public void readSchemaObject(JsonNode rootNode) throws Exception {
    final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
    final SwaggerParseResult result = deserializer.deserialize(rootNode);

    Assert.assertNotNull(result);

    final OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);

    final Paths paths = openAPI.getPaths();
    Assert.assertNotNull(paths);
    Assert.assertEquals(paths.size(), 18);

    //parameters operation get
    PathItem petByStatusEndpoint = paths.get("/pet/findByStatus");
    Assert.assertNotNull(petByStatusEndpoint.getGet());
    Assert.assertNotNull(petByStatusEndpoint.getGet().getParameters());
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().size(), 1);
    Assert.assertNotNull(petByStatusEndpoint.getGet().getParameters().get(0).getSchema());
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getSchema().getFormat(), "int64");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getSchema().getXml().getNamespace(), "http://example.com/schema/sample");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getSchema().getXml().getPrefix(), "sample");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getIn(),"query");
}
 
Example #15
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "data")
public void readSchemaArray(JsonNode rootNode) throws Exception {
    final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
    final SwaggerParseResult result = deserializer.deserialize(rootNode);

    Assert.assertNotNull(result);

    final OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);

    final Paths paths = openAPI.getPaths();
    Assert.assertNotNull(paths);
    Assert.assertEquals(paths.size(), 18);

    //parameters operation get
    PathItem petByStatusEndpoint = paths.get("/pet/findByTags");
    Assert.assertNotNull(petByStatusEndpoint.getGet());
    Assert.assertNotNull(petByStatusEndpoint.getGet().getParameters());
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().size(), 1);
    Assert.assertNotNull(petByStatusEndpoint.getGet().getParameters().get(0).getSchema());
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getSchema().getType(), "array");
    Assert.assertEquals(((ArraySchema)(petByStatusEndpoint.getGet().getParameters().get(0).getSchema())).getItems().getType(), "string");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getName(),"tags");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getExplode(), Boolean.TRUE);
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getStyle(), StyleEnum.FORM);
}
 
Example #16
Source File: AbstractEndpointGenerationTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private void assertPaths(Paths actualPaths,
        List<Class<?>> testEndpointClasses) {
    int pathCount = 0;
    for (Class<?> testEndpointClass : testEndpointClasses) {
        for (Method expectedEndpointMethod : testEndpointClass
                .getDeclaredMethods()) {
            if (!Modifier.isPublic(expectedEndpointMethod.getModifiers())
                    || accessChecker
                            .getSecurityTarget(expectedEndpointMethod)
                            .isAnnotationPresent(DenyAll.class)) {
                continue;
            }
            pathCount++;
            String expectedEndpointUrl = String.format("/%s/%s",
                    getEndpointName(testEndpointClass),
                    expectedEndpointMethod.getName());
            PathItem actualPath = actualPaths.get(expectedEndpointUrl);
            assertNotNull(String.format(
                    "Expected to find a path '%s' for the endpoint method '%s' in the class '%s'",
                    expectedEndpointUrl, expectedEndpointMethod,
                    testEndpointClass), actualPath);
            assertPath(testEndpointClass, expectedEndpointMethod, actualPath);
        }
    }
    assertEquals("Unexpected number of OpenAPI paths found", pathCount,
            actualPaths.size());
}
 
Example #17
Source File: TagMustBeReferencedValidator.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
private Set<String> getAllOperationsTags(OasValidationContext context) {

    Set<String> allTags = context.getAttribute(CACHE_KEY);
    if (allTags != null) {
      return allTags;
    }

    allTags = new HashSet<>();

    OpenAPI openAPI = context.getOpenAPI();
    Paths paths = openAPI.getPaths();
    if (paths == null) {
      return emptySet();
    }

    for (Map.Entry<String, PathItem> entry : paths.entrySet()) {
      PathItem pathItem = entry.getValue();
      List<Operation> operations = pathItem.readOperations();
      for (Operation operation : operations) {
        List<String> tags = operation.getTags();
        if (CollectionUtils.isEmpty(tags)) {
          continue;
        }
        allTags.addAll(tags);
      }
    }

    context.setAttribute(CACHE_KEY, allTags);
    return allTags;
  }
 
Example #18
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void readEmptyServerObject() throws Exception {
    final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    final JsonNode rootNode = mapper.readTree(Files.readAllBytes(java.nio.file.Paths.get(getClass().getResource("/oas2.yaml.template").toURI())));

    final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
    final SwaggerParseResult result = deserializer.deserialize(rootNode);

    Assert.assertNotNull(result);

    final OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);

    assertEquals(openAPI.getServers().get(0).getUrl(),"/");
}
 
Example #19
Source File: RequestParameterTest.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * parse the entire schema defined in yaml file and return a map
 *
 * @return a map of endpoints to its corresponding set of parameters
 */
public Map<String, Set<String>> parseSchema() {
  Map<String, Set<String>> parsedSchema = new HashMap<>();
  Paths paths = _openAPI.getPaths();
  for (Map.Entry<String, PathItem> endpoint : paths.entrySet()) {
    parsedSchema.put(endpoint.getKey(), parseEndpoint(endpoint.getValue()));
  }
  return parsedSchema;
}
 
Example #20
Source File: PathTransformer.java    From swagger-brake with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<Path> transform(Paths from) {
    if (from == null) {
        throw new IllegalArgumentException("input must not be null");
    }
    return from.entrySet().stream().map(e -> transform(e.getKey(), e.getValue())).flatMap(Collection::stream).collect(toList());
}
 
Example #21
Source File: ProtoOpenAPI.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
/**
 * Add openAPI path item to the the openAPI object.
 *
 * @param path            name of the pathItem
 * @param scopes          array of operation scopes
 * @param throttlingTier throttling tier
 */
void addOpenAPIPath(String path, String[] scopes, String throttlingTier) {
    PathItem pathItem = new PathItem();
    Operation operation = new Operation();
    operation.setOperationId(UUID.randomUUID().toString());
    addOauth2SecurityRequirement(operation, scopes);
    if (StringUtils.isNotEmpty(throttlingTier)) {
        operation.addExtension(OpenAPIConstants.THROTTLING_TIER, throttlingTier);
    }
    //needs to add the basic Auth Requirement to the operation level because if scopes are mentioned,
    // there would be oauth2 security requirement in method level.
    if (isBasicAuthEnabled) {
        addBasicAuthSecurityRequirement(operation);
    }
    if (isAPIKeyEnabled) {
        addAPIKeySecurityRequirement(operation);
    }
    //For each path, the only available http method is "post" according to the grpc mapping.
    pathItem.setPost(operation);
    if (openAPI.getPaths() == null) {
        openAPI.setPaths(new Paths());
    }
    //as Responses object is mandatory
    ApiResponse apiResponse = new ApiResponse();
    apiResponse.setDescription(ProtoToOpenAPIConstants.RESPONSE_DESCRIPTION);
    ApiResponses apiResponses = new ApiResponses();
    apiResponses.addApiResponse(ProtoToOpenAPIConstants.SUCCESS_RESPONSE_CODE, apiResponse);
    operation.setResponses(apiResponses);
    //append forward slash to preserve openAPI syntax
    openAPI.getPaths().addPathItem(ProtoToOpenAPIConstants.PATH_SEPARATOR + path, pathItem);
}
 
Example #22
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static void readPathsAndScopes(PathItem srcPathItem, URITemplate uriTemplate,
                                       final Set<Scope> allScopes, SwaggerUpdateContext context) {
    Map<PathItem.HttpMethod, Operation> srcOperations = srcPathItem.readOperationsMap();

    PathItem.HttpMethod httpMethod = PathItem.HttpMethod.valueOf(uriTemplate.getHTTPVerb().toUpperCase());
    Operation srcOperation = srcOperations.get(httpMethod);

    Paths paths = context.getPaths();
    Set<Scope> aggregatedScopes = context.getAggregatedScopes();

    if (!paths.containsKey(uriTemplate.getUriTemplate())) {
        paths.put(uriTemplate.getUriTemplate(), new PathItem());
    }

    PathItem pathItem = paths.get(uriTemplate.getUriTemplate());
    pathItem.operation(httpMethod, srcOperation);

    readReferenceObjects(srcOperation, context);

    List<SecurityRequirement> srcOperationSecurity = srcOperation.getSecurity();
    if (srcOperationSecurity != null) {
        for (SecurityRequirement requirement : srcOperationSecurity) {
            List<String> scopes = requirement.get(OAS3Parser.OPENAPI_SECURITY_SCHEMA_KEY);
            if (scopes != null) {
                for (String scopeKey : scopes) {
                    for (Scope scope : allScopes) {
                        if (scope.getKey().equals(scopeKey)) {
                            aggregatedScopes.add(scope);
                        }
                    }
                }
            }
        }
    }
}
 
Example #23
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 #24
Source File: PathsKeyCaseValidator.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
@Override
public List<OasViolation> validate(OasValidationContext context, OasObjectPropertyLocation location, Paths oasObject) {
  List<OasViolation> violations = new ArrayList<>();

  Set<String> paths = oasObject.keySet();

  for (String path : paths) {
    if (!matchCamelCase(path)) {
      OasObjectPropertyLocation pathLoc = location.property(path, OasObjectType.PATH_ITEM);
      violations.add(new OasViolation(pathLoc, ERROR + expectedCase));
    }
  }

  return violations;
}
 
Example #25
Source File: PathsPathItemsValidator.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
@Override
public List<OasViolation> validate(OasValidationContext context, OasObjectPropertyLocation location, Paths oasObject) {
  List<OasViolation> violations = new ArrayList<>();

  for (Map.Entry<String, PathItem> entry : oasObject.entrySet()) {
    String path = entry.getKey();
    PathItem pathItem = entry.getValue();
    OasObjectPropertyLocation pathItemLocation = location.property(path, OasObjectType.PATH_ITEM);
    violations.addAll(doValidateProperty(context, pathItemLocation, pathItem, pathItemValidators));
  }

  return violations;
}
 
Example #26
Source File: AbstractOpenApiResource.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate path.
 *
 * @param routerOperation the router operation
 */
protected void calculatePath(RouterOperation routerOperation) {
	String operationPath = routerOperation.getPath();
	io.swagger.v3.oas.annotations.Operation apiOperation = routerOperation.getOperation();
	String[] methodConsumes = routerOperation.getConsumes();
	String[] methodProduces = routerOperation.getProduces();
	String[] headers = routerOperation.getHeaders();
	Map<String, String> queryParams = routerOperation.getQueryParams();

	OpenAPI openAPI = openAPIBuilder.getCalculatedOpenAPI();
	Paths paths = openAPI.getPaths();
	Map<HttpMethod, Operation> operationMap = null;
	if (paths.containsKey(operationPath)) {
		PathItem pathItem = paths.get(operationPath);
		operationMap = pathItem.readOperationsMap();
	}
	for (RequestMethod requestMethod : routerOperation.getMethods()) {
		Operation existingOperation = getExistingOperation(operationMap, requestMethod);
		MethodAttributes methodAttributes = new MethodAttributes(springDocConfigProperties.getDefaultConsumesMediaType(), springDocConfigProperties.getDefaultProducesMediaType(), methodConsumes, methodProduces, headers);
		methodAttributes.setMethodOverloaded(existingOperation != null);
		Operation operation = getOperation(routerOperation, existingOperation);
		if (apiOperation != null)
			openAPI = operationParser.parse(apiOperation, operation, openAPI, methodAttributes);

		String operationId = operationParser.getOperationId(operation.getOperationId(), openAPI);
		operation.setOperationId(operationId);

		fillParametersList(operation, queryParams, methodAttributes);
		if (!CollectionUtils.isEmpty(operation.getParameters()))
			operation.getParameters().forEach(parameter -> {
						if (parameter.getSchema() == null)
							parameter.setSchema(new StringSchema());
						if (parameter.getIn() == null)
							parameter.setIn(ParameterIn.QUERY.toString());
					}
			);
		PathItem pathItemObject = buildPathItem(requestMethod, operation, operationPath, paths);
		paths.addPathItem(operationPath, pathItemObject);
	}
}
 
Example #27
Source File: OpenAPIBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Build.
 */
public void build() {
	Optional<OpenAPIDefinition> apiDef = getOpenAPIDefinition();

	if (openAPI == null) {
		this.calculatedOpenAPI = new OpenAPI();
		this.calculatedOpenAPI.setComponents(new Components());
		this.calculatedOpenAPI.setPaths(new Paths());
	}
	else
		this.calculatedOpenAPI = openAPI;

	if (apiDef.isPresent()) {
		buildOpenAPIWithOpenAPIDefinition(calculatedOpenAPI, apiDef.get());
	}
	// Set default info
	else if (calculatedOpenAPI.getInfo() == null) {
		Info infos = new Info().title(DEFAULT_TITLE).version(DEFAULT_VERSION);
		calculatedOpenAPI.setInfo(infos);
	}
	// Set default mappings
	this.mappingsMap.putAll(context.getBeansWithAnnotation(RestController.class));
	this.mappingsMap.putAll(context.getBeansWithAnnotation(RequestMapping.class));
	this.mappingsMap.putAll(context.getBeansWithAnnotation(Controller.class));

	// add security schemes
	this.calculateSecuritySchemes(calculatedOpenAPI.getComponents());
	openApiBuilderCustomisers.ifPresent(customisers -> customisers.forEach(customiser -> customiser.customise(this)));
}
 
Example #28
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 #29
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 #30
Source File: RaptorSwaggerConverter.java    From raptor with Apache License 2.0 5 votes vote down vote up
/**
 * https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#paths-object
 *
 * @param protoFile
 * @param service
 * @return
 */
@Override
protected Paths getPath(ProtoFile protoFile, Service service) {
    Paths paths = new Paths();
    String basePath = protoFile.packageName();

    InterfaceMetaInfo interfaceMetaInfo = InterfaceMetaInfo.readFrom(protoFile, service);
    String servicePath = interfaceMetaInfo.getServicePath();

    for (Rpc rpc : service.rpcs()) {
        String defaultName = PathUtils.collectPath(basePath , rpc.name());

        MethodMetaInfo methodMetaInfo = MethodMetaInfo.readFrom(rpc);

        String path = methodMetaInfo.getPath();
        path = StringUtils.isBlank(path) && StringUtils.isBlank(servicePath) ? defaultName : PathUtils.collectPath(servicePath, path);

        // TODO: 2018/5/23 处理path 相同,方法不同的问题,
        PathItem pathItem = paths.get(path);
        if(Objects.isNull(pathItem)){
            paths.addPathItem(path, getPathItem(rpc));
        }else{
            addOperation(rpc,pathItem);
        }

    }
    return paths;
}