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

The following examples show how to use io.swagger.v3.oas.models.PathItem. 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: OperationsTransformer.java    From spring-openapi with MIT License 6 votes vote down vote up
public Map<String, PathItem> transformOperations(List<Class<?>> restControllerClasses) {
	final Map<String, PathItem> operationsMap = new HashMap<>();

	for (Class<?> clazz : restControllerClasses) {
		if (shouldBeIgnored(clazz)) {
			logger.info("Ignoring class {}", clazz.getName());
			continue;
		}

		logger.debug("Transforming {} controller class", clazz.getName());
		String baseControllerPath = getBaseControllerPath(clazz);
		ReflectionUtils.doWithMethods(clazz, method -> createOperation(method, baseControllerPath, operationsMap, clazz.getSimpleName()),
				this::isOperationMethod);
	}
	fixDuplicateOperationIds(operationsMap);
	return operationsMap;
}
 
Example #2
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testArbitraryObjectResponseMapInline() {
    OpenAPI openAPI = new OpenAPI();

    Schema schema = new Schema();
    schema.setAdditionalProperties(new ObjectSchema());

    openAPI.path("/foo/baz", new PathItem()
            .get(new Operation()
                    .responses(new ApiResponses().addApiResponse("200", new ApiResponse()
                            .description("it works!")
                            .content(new Content().addMediaType("*/*", new MediaType().schema(schema)))))));

    new InlineModelResolver().flatten(openAPI);

    ApiResponse response = openAPI.getPaths().get("/foo/baz").getGet().getResponses().get("200");

    Schema property = response.getContent().get("*/*").getSchema();
    assertTrue(property.getAdditionalProperties() != null);
    assertTrue(property.getAdditionalProperties() instanceof  Schema);
    assertTrue(openAPI.getComponents().getSchemas() == null);
    Schema inlineProp = (Schema)property.getAdditionalProperties();
    assertTrue(inlineProp instanceof ObjectSchema);
    ObjectSchema op = (ObjectSchema) inlineProp;
    assertNull(op.getProperties());
}
 
Example #3
Source File: ResponseTest.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Check the consistency for all POST and GET endpoints defined in OpenAPI spec.
 */
@Test
public void checkOpenAPISpec() {
  ParseOptions options = new ParseOptions();
  options.setResolve(true);
  options.setFlatten(true);
  _openAPI = new OpenAPIV3Parser().read(OPENAPI_SPEC_PATH, null, options);
  for (PathItem path : _openAPI.getPaths().values()) {
    if (path.getGet() != null) {
      checkOperation(path.getGet());
    }
    if (path.getPost() != null) {
      checkOperation(path.getPost());
    }
  }
}
 
Example #4
Source File: ExtensionsUtil.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
public void addExtensions(OpenAPI openAPI) {
    if (openAPI.getComponents() == null || openAPI.getComponents().getSchemas() == null) {
        schemas = new HashMap<>();
    } else {
        schemas = openAPI.getComponents().getSchemas();
        for (String name : schemas.keySet()) {
            Schema schema = schemas.get(name);
            if (schema.getExtensions() != null) {
                if (!schema.getExtensions().containsKey(Constants.X_SWAGGER_ROUTER_MODEL)) {
                    schema.addExtension(Constants.X_SWAGGER_ROUTER_MODEL, name);
                }
            } else {
                schema.addExtension(Constants.X_SWAGGER_ROUTER_MODEL, name);
            }
        }
    }
    if (openAPI.getPaths() != null) {
        for (String pathname : openAPI.getPaths().keySet()) {
            PathItem pathItem = openAPI.getPaths().get(pathname);
            resolvePath(pathItem, true);
        }
    }

}
 
Example #5
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testOperationBodyParameterRemoteRefs() {
    final Schema schema = new Schema();

    final OpenAPI swagger = new OpenAPI();
    swagger.path("/fun", new PathItem()
            .get(new Operation()
                    .parameters(Arrays.asList(new Parameter().$ref("#/components/parameters/SampleParameter")))));

    swagger.path("/times", new PathItem()
            .get(new Operation()
                    .parameters(Arrays.asList(new Parameter().$ref("#/components/parameters/SampleParameter")))));

    swagger.components(new Components().addParameters("SampleParameter", new Parameter()
            .name("skip")
            .schema(schema)));

    final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve();
    final List<Parameter> params = swagger.getPaths().get("/fun").getGet().getParameters();
    assertEquals(params.size(), 1);
    final Parameter param =  params.get(0);
    assertEquals(param.getName(), "skip");
}
 
Example #6
Source File: RequestParameterTest.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Return the list of parameters given the path item (an endpoint)
 *
 * @param pathItem Endpoint defined as a PathItem object
 * @return set of parameters for the specified endpoint
 */
public static Set<String> parseEndpoint(PathItem pathItem) throws IllegalArgumentException {
  List<Parameter> parameterList;
  Set<String> parameterSet = new TreeSet<>();
  if (pathItem.getGet() != null) {
    parameterList = pathItem.getGet().getParameters();
  } else if (pathItem.getPost() != null) {
    parameterList = pathItem.getPost().getParameters();
  } else {
    throw new IllegalArgumentException("Schema Parser does not support HTTP methods other than GET/POST");
  }

  for (Parameter parameter : parameterList) {
    Assert.assertFalse(parameterSet.contains(parameter.getName()));
    parameterSet.add(parameter.getName());
  }
  return parameterSet;
}
 
Example #7
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 #8
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(description = "resolve top-level responses")
public void testSharedResponses() {
    final OpenAPI swagger = new OpenAPI();
    List<Parameter> parameters = new ArrayList<>();
    parameters.add(0,new Parameter().$ref("username"));
    swagger.path("/fun", new PathItem()
            .get(new Operation()
                    .parameters(parameters)
                    .responses(new ApiResponses().addApiResponse("200", new ApiResponse().$ref("#/components/responses/foo")))));

    swagger.components(new Components().addResponses("foo", new ApiResponse().description("ok!")));

    final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve();
    ApiResponse response = resolved.getPaths().get("/fun").getGet().getResponses().get("200");
    assertTrue(response.getDescription().equals("ok!"));
    assertTrue(response instanceof ApiResponse);
}
 
Example #9
Source File: OperationsTransformer.java    From spring-openapi with MIT License 6 votes vote down vote up
private void mapRequestMapping(RequestMapping requestMapping, Method method, Map<String, PathItem> operationsMap, String controllerClassName,
							   String baseControllerPath) {
	Operation operation = new Operation();
	operation.setOperationId(getOperationId(requestMapping.name(), method, getSpringMethod(requestMapping.method())));
	operation.setSummary(StringUtils.isBlank(requestMapping.name()) ? requestMapping.name() : method.getName());
	operation.setTags(singletonList(classNameToTag(controllerClassName)));

	if (isHttpMethodWithRequestBody(requestMapping.method())) {
		operation.setRequestBody(createRequestBody(method, getFirstFromArray(requestMapping.consumes())));
	}
	operation.setParameters(transformParameters(method));
	operation.setResponses(createApiResponses(method, getFirstFromArray(requestMapping.produces())));

	operationInterceptors.forEach(interceptor -> interceptor.intercept(method, operation));

	String path = ObjectUtils.defaultIfNull(getFirstFromArray(requestMapping.value()), getFirstFromArray(requestMapping.path()));
	updateOperationsMap(prepareUrl(baseControllerPath, "/", path), operationsMap,
			pathItem -> setContentBasedOnHttpMethod(pathItem, requestMapping.method(), operation)
	);
}
 
Example #10
Source File: OpenApiOperationValidationsTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "getOrHeadWithBodyExpectations")
public void testGetOrHeadWithBodyWithDisabledRule(PathItem.HttpMethod method, String operationId, String ref, Content content, boolean shouldTriggerFailure) {
    RuleConfiguration config = new RuleConfiguration();
    config.setEnableApiRequestUriWithBodyRecommendation(false);
    OpenApiOperationValidations validator = new OpenApiOperationValidations(config);

    Operation op = new Operation().operationId(operationId);
    RequestBody body = new RequestBody();
    if (StringUtils.isNotEmpty(ref) || content != null) {
        body.$ref(ref);
        body.content(content);

        op.setRequestBody(body);
    }

    ValidationResult result = validator.validate(new OperationWrapper(null, op, method));
    Assert.assertNotNull(result.getWarnings());

    List<Invalid> warnings = result.getWarnings().stream()
            .filter(invalid -> "API GET/HEAD defined with request body".equals(invalid.getRule().getDescription()))
            .collect(Collectors.toList());

    Assert.assertNotNull(warnings);
    Assert.assertEquals(warnings.size(), 0, "Expected warnings not to include recommendation.");
}
 
Example #11
Source File: ExtensionsUtil.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
public  void removeExtensions(OpenAPI openAPI) {

        if (openAPI.getComponents() == null || openAPI.getComponents().getSchemas() == null) {
            schemas = new HashMap<>();
        } else {
            schemas = openAPI.getComponents().getSchemas();
            for (String name : schemas.keySet()) {
                Schema schema = schemas.get(name);
                if (schema.getExtensions() != null) {
                    if (schema.getExtensions().containsKey(Constants.X_SWAGGER_ROUTER_MODEL)) {
                        Map<String,Schema> extensions = schema.getExtensions();
                        Object value = extensions.get(Constants.X_SWAGGER_ROUTER_MODEL);
                        extensions.remove(Constants.X_SWAGGER_ROUTER_MODEL,value);
                    }
                }
            }
        }
        if (openAPI.getPaths() != null) {
            for (String pathname : openAPI.getPaths().keySet()) {
                PathItem pathItem = openAPI.getPaths().get(pathname);
                resolvePath(pathItem,false);
            }
        }

    }
 
Example #12
Source File: ResourceInterfaceGenerator.java    From spring-openapi with MIT License 6 votes vote down vote up
private void addToResourceMap(Map.Entry<String, PathItem> pathItemEntry, Map<String, List<OperationData>> resourceMap) {
	String url = pathItemEntry.getKey();
	String resourceName = getResourceName(pathItemEntry.getValue());
	PathItem pathItem = pathItemEntry.getValue();
	Stream.of(pathItem.getPost(), pathItem.getPatch(), pathItem.getPut(), pathItem.getHead(), pathItem.getOptions(), pathItem.getGet(), pathItem.getDelete())
			.filter(Objects::nonNull)
			.forEach(operation -> {
				if (resourceMap.containsKey(resourceName)) {
					resourceMap.get(resourceName).add(new OperationData(operation, url));
				} else {
					List<OperationData> operations = new ArrayList<>();
					operations.add(new OperationData(operation, url));
					resourceMap.put(resourceName, operations);
				}
			});
}
 
Example #13
Source File: CallbackProcessor.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public void processCallback(Callback callback) {
    if (callback.get$ref() != null){
        processReferenceCallback(callback);
    }
    //Resolver PathItem
    for(String name : callback.keySet()){
        PathItem pathItem = callback.get(name);
        final Map<PathItem.HttpMethod, Operation> operationMap = pathItem.readOperationsMap();

        for (PathItem.HttpMethod httpMethod : operationMap.keySet()) {
            Operation operation = operationMap.get(httpMethod);
            operationProcessor.processOperation(operation);
        }

        List<Parameter> parameters = pathItem.getParameters();
        if (parameters != null) {
            for (Parameter parameter: parameters){
                parameterProcessor.processParameter(parameter);
            }
        }
    }
}
 
Example #14
Source File: OperationBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Extract operation id from path item set.
 *
 * @param path the path
 * @return the set
 */
private Set<String> extractOperationIdFromPathItem(PathItem path) {
	Set<String> ids = new HashSet<>();
	if (path.getGet() != null && StringUtils.isNotBlank(path.getGet().getOperationId())) {
		ids.add(path.getGet().getOperationId());
	}
	if (path.getPost() != null && StringUtils.isNotBlank(path.getPost().getOperationId())) {
		ids.add(path.getPost().getOperationId());
	}
	if (path.getPut() != null && StringUtils.isNotBlank(path.getPut().getOperationId())) {
		ids.add(path.getPut().getOperationId());
	}
	if (path.getDelete() != null && StringUtils.isNotBlank(path.getDelete().getOperationId())) {
		ids.add(path.getDelete().getOperationId());
	}
	if (path.getOptions() != null && StringUtils.isNotBlank(path.getOptions().getOperationId())) {
		ids.add(path.getOptions().getOperationId());
	}
	if (path.getHead() != null && StringUtils.isNotBlank(path.getHead().getOperationId())) {
		ids.add(path.getHead().getOperationId());
	}
	if (path.getPatch() != null && StringUtils.isNotBlank(path.getPatch().getOperationId())) {
		ids.add(path.getPatch().getOperationId());
	}
	return ids;
}
 
Example #15
Source File: PathItemOperationsValidator.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@Override
public List<OasViolation> validate(OasValidationContext context, OasObjectPropertyLocation location,
  PathItem oasObject) {
  if (StringUtils.isNotBlank(oasObject.get$ref())) {
    return emptyList();
  }

  List<OasViolation> violations = new ArrayList<>();

  Map<PathItem.HttpMethod, Operation> operationMap = oasObject.readOperationsMap();

  for (Map.Entry<PathItem.HttpMethod, Operation> entry : operationMap.entrySet()) {
    PathItem.HttpMethod method = entry.getKey();
    Operation operation = entry.getValue();
    OasObjectPropertyLocation operationLocation = location.property(method.toString().toLowerCase(), OasObjectType.OPERATION);
    violations.addAll(
      OasObjectValidatorUtils.doValidateProperty(context, operationLocation, operation, operationValidators));
  }
  return violations;
}
 
Example #16
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 #17
Source File: ChangedPath.java    From openapi-diff with Apache License 2.0 5 votes vote down vote up
public ChangedPath(String pathUrl, PathItem oldPath, PathItem newPath, DiffContext context) {
  this.pathUrl = pathUrl;
  this.oldPath = oldPath;
  this.newPath = newPath;
  this.context = context;
  this.increased = new LinkedHashMap<>();
  this.missing = new LinkedHashMap<>();
  this.changed = new ArrayList<>();
}
 
Example #18
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 #19
Source File: OpenAPIGeneratorTestBase.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
private static void assertJsonAPICompliantNestedPath(PathItem pathItem) {
  // Ensure GET response json:api compliance
  assertOperationResponseCodes(pathItem.getGet(), Arrays.asList("200", "400"));

  // Ensure POST response json:api compliance
  assertOperationResponseCodes(pathItem.getPost(), Arrays.asList("200", "202", "204", "403", "404", "409"));

  // Ensure PATCH response json:api compliance
  assertOperationResponseCodes(pathItem.getPatch(), Arrays.asList("200", "202", "204", "403", "404", "409"));

  // Ensure DELETE response json:api compliance
  assertOperationResponseCodes(pathItem.getDelete(), Arrays.asList("200", "202", "204", "404"));
}
 
Example #20
Source File: OperationHelper.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
public List<OperationModel> getAllOperations(PathItem path, String url) {
    List<OperationModel> operations = new LinkedList<OperationModel>();

    if (path.getGet() != null) {
        operations.add(new OperationModel(url, path.getGet(), RequestMethod.GET));
    }
    if (path.getPost() != null) {
        operations.add(new OperationModel(url, path.getPost(), RequestMethod.POST));
    }
    if (path.getPut() != null) {
        operations.add(new OperationModel(url, path.getPut(), RequestMethod.PUT));
    }
    if (path.getHead() != null) {
        operations.add(new OperationModel(url, path.getHead(), RequestMethod.HEAD));
    }
    if (path.getOptions() != null) {
        operations.add(new OperationModel(url, path.getOptions(), RequestMethod.OPTION));
    }
    if (path.getDelete() != null) {
        operations.add(new OperationModel(url, path.getDelete(), RequestMethod.DELETE));
    }
    if (path.getPatch() != null) {
        operations.add(new OperationModel(url, path.getPatch(), RequestMethod.PATCH));
    }
    if (operations.isEmpty()) {
        log.debug("Failed to find any operations for url=" + url + " path=" + path);
    }

    return operations;
}
 
Example #21
Source File: EndpointUtils.java    From openapi-diff with Apache License 2.0 5 votes vote down vote up
public static Endpoint convert2Endpoint(
    String pathUrl, PathItem.HttpMethod httpMethod, Operation operation) {
  Endpoint endpoint = new Endpoint();
  endpoint.setPathUrl(pathUrl);
  endpoint.setMethod(httpMethod);
  endpoint.setSummary(operation.getSummary());
  endpoint.setOperation(operation);
  return endpoint;
}
 
Example #22
Source File: TypeScriptAngularClientCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testOperationIdParser() {
    OpenAPI openAPI = TestUtils.createOpenAPI();
    Operation operation1 = new Operation().operationId("123_test_@#$%_special_tags").responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")));
    openAPI.path("another-fake/dummy/", new PathItem().get(operation1));
    final TypeScriptAngularClientCodegen codegen = new TypeScriptAngularClientCodegen();
    codegen.setOpenAPI(openAPI);

    CodegenOperation co1 = codegen.fromOperation("/another-fake/dummy/", "get", operation1, null);
    org.testng.Assert.assertEquals(co1.operationId, "_123testSpecialTags");

}
 
Example #23
Source File: ModelUtils.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Private method used by several methods ({@link #getAllUsedSchemas(OpenAPI)},
 * {@link #getUnusedSchemas(OpenAPI)},
 * {@link #getSchemasUsedOnlyInFormParam(OpenAPI)}, ...) to traverse all paths of an
 * OpenAPI instance and call the visitor functional interface when a schema is found.
 *
 * @param openAPI specification
 * @param visitor functional interface (can be defined as a lambda) called each time a schema is found.
 */
private static void visitOpenAPI(OpenAPI openAPI, OpenAPISchemaVisitor visitor) {
    Map<String, PathItem> paths = openAPI.getPaths();
    List<String> visitedSchemas = new ArrayList<>();

    if (paths != null) {
        for (PathItem path : paths.values()) {
            visitPathItem(path, openAPI, visitor, visitedSchemas);
        }
    }
}
 
Example #24
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Update OAS operations for Store
 *
 * @param openAPI OpenAPI to be updated
 */
private void updateOperations(OpenAPI openAPI) {
    for (String pathKey : openAPI.getPaths().keySet()) {
        PathItem pathItem = openAPI.getPaths().get(pathKey);
        for (Map.Entry<PathItem.HttpMethod, Operation> entry : pathItem.readOperationsMap().entrySet()) {
            Operation operation = entry.getValue();
            Map<String, Object> extensions = operation.getExtensions();
            if (extensions != null) {
                // remove mediation extension
                if (extensions.containsKey(APIConstants.SWAGGER_X_MEDIATION_SCRIPT)) {
                    extensions.remove(APIConstants.SWAGGER_X_MEDIATION_SCRIPT);
                }
                // set x-scope value to security definition if it not there.
                if (extensions.containsKey(APIConstants.SWAGGER_X_WSO2_SCOPES)) {
                    String scope = (String) extensions.get(APIConstants.SWAGGER_X_WSO2_SCOPES);
                    List<SecurityRequirement> security = operation.getSecurity();
                    if (security == null) {
                        security = new ArrayList<>();
                        operation.setSecurity(security);
                    }
                    for (Map<String, List<String>> requirement : security) {
                        if (requirement.get(OPENAPI_SECURITY_SCHEMA_KEY) == null || !requirement
                                .get(OPENAPI_SECURITY_SCHEMA_KEY).contains(scope)) {
                            requirement.put(OPENAPI_SECURITY_SCHEMA_KEY, Collections.singletonList(scope));
                        }
                    }
                }
            }
        }
    }
}
 
Example #25
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 #26
Source File: OpenAPIParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue749() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult result = new OpenAPIParser().readLocation("issue749-main.yaml", null, options);
    assertNotNull(result);

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

    Components components = openAPI.getComponents();
    assertNotNull(components);

    PathItem pathItem = openAPI.getPaths().get("/some/ping");
    assertNotNull(pathItem);
    List<Parameter> parameters = pathItem.getGet().getParameters();
    assertNotNull(parameters);
    assertEquals(parameters.size(), 1);
    assertEquals(parameters.get(0).getName(), "i");
    assertNotNull(parameters.get(0).getSchema());
    assertEquals(parameters.get(0).getSchema().get$ref(), "#/components/schemas/SomeId");

    Map<String, Schema> schemas = components.getSchemas();
    assertNotNull(schemas);
    assertEquals(schemas.size(), 1);
    assertNotNull(schemas.get("SomeId"));
}
 
Example #27
Source File: V2ConverterTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue455() throws Exception {
    OpenAPI oas = getConvertedOpenAPIFromJsonFile(ISSUE_455_JSON);

    assertNotNull(oas);
    assertEquals(PARAMETERS_SIZE, oas.getPaths().size());

    PathItem pathItem = oas.getPaths().get(API_BATCH_PATH);
    assertNotNull(pathItem);

    assertEquals(PARAMETERS_SIZE, pathItem.getGet().getParameters().size());
}
 
Example #28
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testInlineMapResponseWithObjectSchema() throws Exception {
    OpenAPI openAPI = new OpenAPI();

    Schema schema = new Schema();
    schema.setAdditionalProperties(new ObjectSchema()
            .addProperties("name", new StringSchema()));
    schema.addExtension("x-ext", "ext-prop");

    ApiResponse apiResponse = new ApiResponse()
            .description("it works!")
            .content(new Content().addMediaType("*/*",new MediaType().schema(schema)));
    apiResponse.addExtension("x-foo", "bar");

    ApiResponses apiResponses = new ApiResponses().addApiResponse("200",apiResponse);

    openAPI.path("/foo/baz", new PathItem()
            .get(new Operation()
                    .responses(apiResponses)));

    new InlineModelResolver().flatten(openAPI);

    ApiResponse response = openAPI.getPaths().get("/foo/baz").getGet().getResponses().get("200");
    Schema property = response.getContent().get("*/*").getSchema();
    assertTrue(property.getAdditionalProperties() != null);
    assertEquals(1, property.getExtensions().size());
    assertEquals("ext-prop", property.getExtensions().get("x-ext"));
    assertTrue(openAPI.getComponents().getSchemas().size() == 1);

    Schema inline = openAPI.getComponents().getSchemas().get("inline_response_map200");
    assertTrue(inline instanceof Schema);
    assertNotNull(inline.getProperties().get("name"));
    assertTrue(inline.getProperties().get("name") instanceof StringSchema);
}
 
Example #29
Source File: OpenApiOperationValidationsTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@DataProvider(name = "getOrHeadWithBodyExpectations")
public Object[][] getOrHeadWithBodyExpectations() {
    return new Object[][]{
            /* method */ /* operationId */ /* ref */ /* content */ /* triggers warning */
            {PathItem.HttpMethod.GET, "opWithRef", "#/components/schemas/Animal", null, true},
            {PathItem.HttpMethod.GET, "opWithContent", null, new Content().addMediaType("a", new MediaType()), true},
            {PathItem.HttpMethod.GET, "opWithoutRefOrContent", null, null, false},
            {PathItem.HttpMethod.HEAD, "opWithRef", "#/components/schemas/Animal", null, true},
            {PathItem.HttpMethod.HEAD, "opWithContent", null, new Content().addMediaType("a", new MediaType()), true},
            {PathItem.HttpMethod.HEAD, "opWithoutRefOrContent", null, null, false},
            {PathItem.HttpMethod.POST, "opWithRef", "#/components/schemas/Animal", null, false},
            {PathItem.HttpMethod.POST, "opWithContent", null, new Content().addMediaType("a", new MediaType()), false},
            {PathItem.HttpMethod.POST, "opWithoutRefOrContent", null, null, false}
    };
}
 
Example #30
Source File: OpenApiOperationValidations.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether a GET or HEAD operation is configured to expect a body.
 * <p>
 * RFC7231 describes this behavior as:
 * <p>
 * A payload within a GET request message has no defined semantics;
 * sending a payload body on a GET request might cause some existing
 * implementations to reject the request.
 * <p>
 * See https://tools.ietf.org/html/rfc7231#section-4.3.1
 * <p>
 * Because there are no defined semantics, and because some client and server implementations
 * may silently ignore the entire body (see https://xhr.spec.whatwg.org/#the-send()-method) or
 * throw an error (see https://fetch.spec.whatwg.org/#ref-for-dfn-throw%E2%91%A1%E2%91%A1),
 * we maintain that the existence of a body for this operation is most likely programmer error and raise awareness.
 *
 * @param wrapper Wraps an operation with accompanying HTTP Method
 * @return {@link ValidationRule.Pass} if the check succeeds, otherwise {@link ValidationRule.Fail}
 */
private static ValidationRule.Result checkAntipatternGetOrHeadWithBody(OperationWrapper wrapper) {
    if (wrapper == null) {
        return ValidationRule.Pass.empty();
    }

    ValidationRule.Result result = ValidationRule.Pass.empty();

    if (wrapper.getHttpMethod() == PathItem.HttpMethod.GET || wrapper.getHttpMethod() == PathItem.HttpMethod.HEAD) {
        RequestBody body = wrapper.getOperation().getRequestBody();

        if (body != null) {
            if (StringUtils.isNotEmpty(body.get$ref()) || (body.getContent() != null && body.getContent().size() > 0)) {
                result = new ValidationRule.Fail();
                result.setDetails(String.format(
                        Locale.ROOT,
                        "%s %s contains a request body and is considered an anti-pattern.",
                        wrapper.getHttpMethod().name(),
                        wrapper.getOperation().getOperationId())
                );
            }
        }

    }

    return result;
}