Java Code Examples for io.swagger.v3.oas.models.Paths#get()

The following examples show how to use io.swagger.v3.oas.models.Paths#get() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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;
}
 
Example 10
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test(dataProvider = "data")
public void readContentObject(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());
    Assert.assertNotNull(petByStatusEndpoint.getGet().getParameters());
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().size(), 1);
    Assert.assertNotNull(petByStatusEndpoint.getGet().getParameters().get(0).getContent());
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getContent().size(),3);
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getContent().get("application/json").getSchema().getType(),"array");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getContent().get("application/json").getExample(),"example string");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getContent().get("application/json").getExamples().get("list").getSummary(),"List of Names");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getContent().get("application/json").getSchema().getType(),"array");

    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getContent().get("application/xml").getExamples().get("list").getSummary(),"List of names");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getContent().get("application/xml").getExamples().get("list").getValue(),"<Users><User name='Bob'/><User name='Diane'/><User name='Mary'/><User name='Bill'/></Users>");

    Assert.assertNotNull(petByStatusEndpoint.getGet().getParameters().get(0).getContent().get("application/xml").getExamples().get("empty").getSummary());
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getContent().get("application/xml").getExamples().get("empty").getSummary(),"Empty list");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getContent().get("application/xml").getExamples().get("empty").getValue(),"<Users/>");


    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getContent().get("text/plain").getExamples().get("list").getSummary(),"List of names");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getContent().get("text/plain").getExamples().get("list").getValue(),"Bob,Diane,Mary,Bill");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getContent().get("text/plain").getExamples().get("empty").getSummary(),"Empty");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getContent().get("text/plain").getExamples().get("empty").getValue(),"");

    PathItem petEndpoint = paths.get("/pet");
    Assert.assertNotNull(petEndpoint.getPut());
    Assert.assertNotNull(petEndpoint.getPut().getResponses().get("400").getContent().get("application/json"));
    Assert.assertEquals(petEndpoint.getPut().getResponses().get("400").getContent().size(),1);
    Assert.assertEquals(petEndpoint.getPut().getResponses().get("400").getContent().get("application/json").getSchema().getType(), "array");
}
 
Example 11
Source File: ResolverFully.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
public void resolveFully(OpenAPI openAPI) {
    Components components = openAPI.getComponents();
    if (components != null && components.getRequestBodies() != null) {
        requestBodies = components.getRequestBodies();
        if (requestBodies == null) {
            requestBodies = new HashMap<>();
        }
    }

    if (components != null && components.getSchemas() != null) {
        schemas = components.getSchemas();
        if (schemas == null) {
            schemas = new HashMap<>();
        }
    }

    if (components != null && components.getExamples() != null) {
        examples = components.getExamples();
        if (examples == null) {
            examples = new HashMap<>();
        }
    }

    if (components != null && components.getHeaders() != null) {
        headers = components.getHeaders();
        if (headers == null) {
            headers = new HashMap<>();
        }
    }  

    if (components != null && components.getParameters() != null) {
        parameters = components.getParameters();
        if (parameters == null) {
            parameters = new HashMap<>();
        }
    }
    if (components != null && components.getLinks() != null) {
        links = components.getLinks();
        if (links == null) {
            links = new HashMap<>();
        }
    }
    Paths paths = openAPI.getPaths();
    if(paths != null) {
        for (String pathname : paths.keySet()) {
            PathItem pathItem = paths.get(pathname);
            resolvePath(pathItem);
        }
    }
}
 
Example 12
Source File: NodeJSExpressServerCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
    public void preprocessOpenAPI(OpenAPI openAPI) {
        URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
        String host = URLPathUtils.getProtocolAndHost(url);
        String port = URLPathUtils.getPort(url, defaultServerPort);
        String basePath = url.getPath();

        if (additionalProperties.containsKey(SERVER_PORT)) {
            port = additionalProperties.get(SERVER_PORT).toString();
        }
        this.additionalProperties.put(SERVER_PORT, port);

        if (openAPI.getInfo() != null) {
            Info info = openAPI.getInfo();
            if (info.getTitle() != null) {
                // when info.title is defined, use it for projectName
                // used in package.json
                projectName = info.getTitle()
                        .replaceAll("[^a-zA-Z0-9]", "-")
                        .replaceAll("^[-]*", "")
                        .replaceAll("[-]*$", "")
                        .replaceAll("[-]{2,}", "-")
                        .toLowerCase(Locale.ROOT);
                this.additionalProperties.put("projectName", projectName);
            }
        }

        // need vendor extensions
        Paths paths = openAPI.getPaths();
        if (paths != null) {
            for (String pathname : paths.keySet()) {
                PathItem path = paths.get(pathname);
                Map<HttpMethod, Operation> operationMap = path.readOperationsMap();
                if (operationMap != null) {
                    for (HttpMethod method : operationMap.keySet()) {
                        Operation operation = operationMap.get(method);
                        String tag = "default";
                        if (operation.getTags() != null && operation.getTags().size() > 0) {
                            tag = toApiName(operation.getTags().get(0));
                        }
                        if (operation.getOperationId() == null) {
                            operation.setOperationId(getOrGenerateOperationId(operation, pathname, method.toString()));
                        }
                        // add x-openapi-router-controller
//                        if (operation.getExtensions() == null ||
//                                operation.getExtensions().get("x-openapi-router-controller") == null) {
//                            operation.addExtension("x-openapi-router-controller", sanitizeTag(tag) + "Controller");
//                        }
//                        // add x-openapi-router-service
//                        if (operation.getExtensions() == null ||
//                                operation.getExtensions().get("x-openapi-router-service") == null) {
//                            operation.addExtension("x-openapi-router-service", sanitizeTag(tag) + "Service");
//                        }
                        if (operation.getExtensions() == null ||
                                operation.getExtensions().get("x-eov-operation-handler") == null) {
                            operation.addExtension("x-eov-operation-handler", "controllers/" + sanitizeTag(tag) + "Controller");
                        }
                    }
                }
            }
        }

    }
 
Example 13
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test(dataProvider = "data")
public void readProducesTestEndpoint(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 producesTestEndpoint = paths.get("/producesTest");
    Assert.assertNotNull(producesTestEndpoint.getGet());
    Assert.assertNotNull(producesTestEndpoint.getGet().getParameters());
    Assert.assertTrue(producesTestEndpoint.getGet().getParameters().isEmpty());

    Operation operation = producesTestEndpoint.getGet();
    ApiResponses responses = operation.getResponses();
    Assert.assertNotNull(responses);
    Assert.assertFalse(responses.isEmpty());

    ApiResponse response = responses.get("200");
    Assert.assertNotNull(response);
    Assert.assertEquals("it works", response.getDescription());

    Content content = response.getContent();
    Assert.assertNotNull(content);
    MediaType mediaType = content.get("application/json");
    Assert.assertNotNull(mediaType);

    Schema schema = mediaType.getSchema();
    Assert.assertNotNull(schema);
    Assert.assertTrue(schema instanceof ObjectSchema);

    ObjectSchema objectSchema = (ObjectSchema) schema;
    schema = objectSchema.getProperties().get("name");
    Assert.assertNotNull(schema);

    Assert.assertTrue(schema instanceof StringSchema);
}
 
Example 14
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test(dataProvider = "data")
public void readPathsObject(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);
    //System.out.println(openAPI);

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


    PathItem petRef = paths.get("/pathItemRef");

    PathItem petEndpoint = paths.get("/pet");
    Assert.assertNotNull(petEndpoint);
    Assert.assertEquals(petEndpoint.getSummary(),"summary");
    Assert.assertEquals(petEndpoint.getDescription(),"description");
    Assert.assertNotNull(petEndpoint.getPost().getExternalDocs());
    Assert.assertEquals(petEndpoint.getPost().getExternalDocs().getUrl(),"http://swagger.io");
    Assert.assertEquals(petEndpoint.getPost().getExternalDocs().getDescription(),"Find out more");

    //Operation trace
    Assert.assertNotNull(petEndpoint.getTrace());
    Assert.assertNotNull(petEndpoint.getDescription());

    //Operation post
    Assert.assertNotNull(petEndpoint.getPost());
    Assert.assertNotNull(petEndpoint.getPost().getTags());
    Assert.assertEquals(petEndpoint.getPost().getTags().size(), 1);
    Assert.assertEquals(petEndpoint.getPost().getSummary(), "Add a new pet to the store");
    Assert.assertNull(petEndpoint.getPost().getDescription());
    Assert.assertEquals(petEndpoint.getPost().getOperationId(), "addPet");
    Assert.assertNotNull(petEndpoint.getServers());
    Assert.assertEquals(petEndpoint.getServers().size(), 1);
    Assert.assertNotNull(petEndpoint.getParameters());
    Assert.assertEquals(petEndpoint.getParameters().size(), 2);
    Assert.assertNotNull(petEndpoint.getPost().getParameters());
    Assert.assertEquals(petEndpoint.getPost().getSecurity().get(0).get("petstore_auth").get(0), "write:pets");
    Assert.assertEquals(petEndpoint.getPost().getSecurity().get(0).get("petstore_auth").get(1), "read:pets");

    ApiResponses responses = petEndpoint.getPost().getResponses();
    Assert.assertNotNull(responses);
    assertTrue(responses.containsKey("405"));
    ApiResponse response = responses.get("405");
    Assert.assertEquals(response.getDescription(), "Invalid input");
    Assert.assertEquals(response.getHeaders().get("X-Rate-Limit").getDescription(), "calls per hour allowed by the user");


    //parameters operation get

    PathItem petByStatusEndpoint = paths.get("/pet/findByStatus");
    Assert.assertNotNull(petByStatusEndpoint.getGet());
    Assert.assertNotNull(petByStatusEndpoint.getGet().getTags());
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().size(), 1);
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getIn(),"query");
    Assert.assertEquals(petByStatusEndpoint.getGet().getCallbacks().get("mainHook").get("$request.body#/url").getPost().getResponses().get("200").getDescription(),"webhook successfully processed operation");

}
 
Example 15
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void readOAS(/*JsonNode rootNode*/) throws Exception {
    final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    final JsonNode rootNode = mapper.readTree(Files.readAllBytes(java.nio.file.Paths.get(getClass().getResource("/oas4.yaml").toURI())));
    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.assertNotNull(paths);
    Assert.assertEquals(paths.size(), 114);



    PathItem stripe = paths.get("/v1/3d_secure");

    Assert.assertNotNull(stripe);


    Assert.assertNotNull(stripe.getPost());
    Assert.assertNull(stripe.getPost().getDescription());
    Assert.assertEquals(stripe.getPost().getOperationId(), "Create3DSecure");
    Assert.assertNotNull(stripe.getPost().getParameters());

    ApiResponses responses = stripe.getPost().getResponses();
    Assert.assertNotNull(responses);
    assertTrue(responses.containsKey("200"));
    ApiResponse response = responses.get("200");
    Assert.assertEquals(response.getDescription(), "Successful response.");
    Assert.assertEquals(response.getContent().get("application/json").getSchema().get$ref(),"#/components/schemas/three_d_secure");



    PathItem stripeGet = paths.get("/v1/account/external_accounts");

    Assert.assertNotNull(stripeGet);


    Assert.assertNotNull(stripeGet.getGet());
    Assert.assertNull(stripeGet.getGet().getDescription());
    Assert.assertEquals(stripeGet.getGet().getOperationId(), "AllAccountExternalAccounts");
    Assert.assertNotNull(stripeGet.getGet().getParameters());

    ApiResponses responsesGet = stripeGet.getGet().getResponses();
    Assert.assertNotNull(responsesGet);
    assertTrue(responsesGet.containsKey("200"));
    ApiResponse responseGet = responsesGet.get("200");
    Assert.assertEquals(responseGet.getDescription(), "Successful response.");
    Map<String, Schema> properties = (Map<String, Schema>) responseGet.getContent().get("application/json").getSchema().getProperties();

    Assert.assertNotNull(properties);
    Assert.assertNull(properties.get("data").getType());
    Assert.assertEquals(properties.get("has_more").getDescription(), "True if this list has another page of items after this one that can be fetched.");
    assertTrue(properties.get("data") instanceof ComposedSchema );


    ComposedSchema data =  (ComposedSchema) properties.get("data");
    assertTrue(data.getOneOf().get(0) instanceof ArraySchema );
    ArraySchema items = (ArraySchema)data.getOneOf().get(0);
    Assert.assertEquals(items.getItems().get$ref(),"#/components/schemas/bank_account");

}
 
Example 16
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldParseApiWithParametersUsingContentvsSchema() {
    // Tests that the content method of specifying the format of a parameter
    // gets resolved.
    // Test checks if an API's single parameter of array type gets fully resolved to 
    // referenced definitions.
    String location = "src/test/resources/issue-1078/api.yaml";
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    // This test uses an Array in the parameters, test if it get's fully resolved.
    options.setResolveFully(true);
    OpenAPIV3Parser tested = new OpenAPIV3Parser();
    
    // Parse yaml
    SwaggerParseResult result = tested.readLocation(location, emptyList(), options);

    OpenAPI api = result.getOpenAPI();
    Paths paths = api.getPaths();

    // First ensure all schemas were resolved, this is important when this library 
    // is used to generate code
    Components components = api.getComponents();
    assertNotNull(components);
    assertThat(components.getSchemas().size(), equalTo(4));
    assertNotNull(components.getSchemas().get("LocationType"));
    assertNotNull(components.getSchemas().get("Lat"));
    assertNotNull(components.getSchemas().get("Long"));
    assertNotNull(components.getSchemas().get("SearchResult"));
    
    PathItem apiEndpoint = paths.get("/api-endpoint-1");
    List<Parameter> parameters = apiEndpoint.getGet().getParameters();
    
    // Ensure there's only one parameter in this test
    assertThat(parameters.size(), equalTo(1));
    
    // We are testing content for a parameter so make sure its there.
    Content content = parameters.get(0).getContent();
    assertNotNull(content);
    // spec says only one content is permitted in 3.x
    assertThat( content.size(), equalTo(1));

    // Ensure there's a media type
    MediaType mediaType = content.entrySet().iterator().next().getValue();
    assertNotNull(mediaType);

    // This test has a single parameter of type array
    Schema parameterSchema = mediaType.getSchema();
    Assert.assertTrue(parameterSchema instanceof ArraySchema);
    ArraySchema arraySchema = (ArraySchema)parameterSchema;

    // Test if the item schema was resolved properly
    Schema itemSchema = arraySchema.getItems();
    assertNotNull(itemSchema);
    Assert.assertTrue(itemSchema instanceof ObjectSchema);

    // Ensure the referenced item's schema has been resolved.
    ObjectSchema objSchema = (ObjectSchema)itemSchema;
    Map<String, Schema> objectItemSchemas = objSchema.getProperties();
    assertThat( objectItemSchemas.size(), equalTo(2));
    Assert.assertTrue(objectItemSchemas.get("lat") instanceof IntegerSchema);
    Assert.assertTrue(objectItemSchemas.get("long") instanceof IntegerSchema);
}
 
Example 17
Source File: AbstractOpenApiResource.java    From springdoc-openapi with Apache License 2.0 4 votes vote down vote up
/**
 * Calculate path.
 *
 * @param handlerMethod the handler method
 * @param routerOperation the router operation
 */
protected void calculatePath(HandlerMethod handlerMethod, RouterOperation routerOperation) {
	String operationPath = routerOperation.getPath();
	Set<RequestMethod> requestMethods = new HashSet<>(Arrays.asList(routerOperation.getMethods()));
	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();
	Components components = openAPI.getComponents();
	Paths paths = openAPI.getPaths();

	Map<HttpMethod, Operation> operationMap = null;
	if (paths.containsKey(operationPath)) {
		PathItem pathItem = paths.get(operationPath);
		operationMap = pathItem.readOperationsMap();
	}

	for (RequestMethod requestMethod : requestMethods) {
		Operation existingOperation = getExistingOperation(operationMap, requestMethod);
		Method method = handlerMethod.getMethod();
		// skip hidden operations
		if (operationParser.isHidden(method))
			continue;

		RequestMapping reqMappingClass = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getBeanType(),
				RequestMapping.class);

		MethodAttributes methodAttributes = new MethodAttributes(springDocConfigProperties.getDefaultConsumesMediaType(), springDocConfigProperties.getDefaultProducesMediaType(), methodConsumes, methodProduces, headers);
		methodAttributes.setMethodOverloaded(existingOperation != null);

		if (reqMappingClass != null) {
			methodAttributes.setClassConsumes(reqMappingClass.consumes());
			methodAttributes.setClassProduces(reqMappingClass.produces());
		}

		methodAttributes.calculateConsumesProduces(method);

		Operation operation = (existingOperation != null) ? existingOperation : new Operation();

		if (isDeprecated(method))
			operation.setDeprecated(true);

		// Add documentation from operation annotation
		if (apiOperation == null || StringUtils.isBlank(apiOperation.operationId()))
			apiOperation = AnnotatedElementUtils.findMergedAnnotation(method,
					io.swagger.v3.oas.annotations.Operation.class);

		calculateJsonView(apiOperation, methodAttributes, method);
		if (apiOperation != null)
			openAPI = operationParser.parse(apiOperation, operation, openAPI, methodAttributes);
		fillParametersList(operation, queryParams, methodAttributes);

		// compute tags
		operation = openAPIBuilder.buildTags(handlerMethod, operation, openAPI);

		io.swagger.v3.oas.annotations.parameters.RequestBody requestBodyDoc = AnnotatedElementUtils.findMergedAnnotation(method,
				io.swagger.v3.oas.annotations.parameters.RequestBody.class);

		// RequestBody in Operation
		requestBuilder.getRequestBodyBuilder()
				.buildRequestBodyFromDoc(requestBodyDoc, methodAttributes, components,
						methodAttributes.getJsonViewAnnotationForRequestBody())
				.ifPresent(operation::setRequestBody);
		// requests
		operation = requestBuilder.build(handlerMethod, requestMethod, operation, methodAttributes, openAPI);

		// responses
		ApiResponses apiResponses = responseBuilder.build(components, handlerMethod, operation, methodAttributes);
		operation.setResponses(apiResponses);

		Set<io.swagger.v3.oas.annotations.callbacks.Callback> apiCallbacks = AnnotatedElementUtils.findMergedRepeatableAnnotations(method, io.swagger.v3.oas.annotations.callbacks.Callback.class);

		// callbacks
		buildCallbacks(openAPI, methodAttributes, operation, apiCallbacks);

		// allow for customisation
		customiseOperation(operation, handlerMethod);

		PathItem pathItemObject = buildPathItem(requestMethod, operation, operationPath, paths);
		paths.addPathItem(operationPath, pathItemObject);
	}
}
 
Example 18
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;
}