Java Code Examples for io.swagger.v3.oas.models.PathItem#readOperations()

The following examples show how to use io.swagger.v3.oas.models.PathItem#readOperations() . 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: OpenAPIResolver.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public OpenAPI resolve() {
    if (openApi == null) {
        return null;
    }

    pathProcessor.processPaths();
    componentsProcessor.processComponents();


    if(openApi.getPaths() != null) {
        for(String pathname : openApi.getPaths().keySet()) {
            PathItem pathItem = openApi.getPaths().get(pathname);
            if(pathItem.readOperations() != null) {
                for(Operation operation : pathItem.readOperations()) {
                    operationsProcessor.processOperation(operation);
                }
            }
        }
    }

    return openApi;
}
 
Example 2
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 3
Source File: JMeterClientCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    if (openAPI != null && openAPI.getPaths() != null) {
        for (String pathname : openAPI.getPaths().keySet()) {
            PathItem path = openAPI.getPaths().get(pathname);
            if (path.readOperations() != null) {
                for (Operation operation : path.readOperations()) {
                    String pathWithDollars = pathname.replaceAll("\\{", "\\$\\{");
                    operation.addExtension("x-path", pathWithDollars);
                }
            }
        }
    }
}
 
Example 4
Source File: PathsProcessor.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
private void addParametersToEachOperation(PathItem pathItem) {
    if (settings.addParametersToEachOperation()) {
        List<Parameter> parameters = pathItem.getParameters();

        if (parameters != null) {
            // add parameters to each operation
            List<Operation> operations = pathItem.readOperations();
            if (operations != null) {
                for (Operation operation : operations) {
                    List<Parameter> parametersToAdd = new ArrayList<>();
                    List<Parameter> existingParameters = operation.getParameters();
                    if (existingParameters == null) {
                        existingParameters = new ArrayList<>();
                        operation.setParameters(existingParameters);
                    }
                    for (Parameter parameterToAdd : parameters) {
                        boolean matched = false;
                        for (Parameter existingParameter : existingParameters) {
                            if (parameterToAdd.getIn() != null && parameterToAdd.getIn().equals(existingParameter.getIn()) &&
                                    parameterToAdd.getName().equals(existingParameter.getName())) {
                                matched = true;
                            }
                        }
                        if (!matched) {
                            parametersToAdd.add(parameterToAdd);
                        }
                    }
                    if (parametersToAdd.size() > 0) {
                        operation.getParameters().addAll(0, parametersToAdd);
                    }
                }
            }
        }
        // remove the shared parameters
        pathItem.setParameters(null);
    }
}
 
Example 5
Source File: OAS3ParserTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateAPIDefinitionWithExtensions() throws Exception {
    String relativePath = "definitions" + File.separator + "oas3" + File.separator + "oas3Resources.json";
    String oas3Resources = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath), "UTF-8");
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();

    // check remove vendor extensions
    String definition = testGenerateAPIDefinitionWithExtension(oas3Parser, oas3Resources);
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(definition, null, null);
    OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
    boolean isExtensionNotFound = openAPI.getExtensions() == null || !openAPI.getExtensions()
            .containsKey(APIConstants.SWAGGER_X_WSO2_SECURITY);
    Assert.assertTrue(isExtensionNotFound);
    Assert.assertEquals(2, openAPI.getPaths().size());

    Iterator<Map.Entry<String, PathItem>> itr = openAPI.getPaths().entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String, PathItem> pathEntry = itr.next();
        PathItem path = pathEntry.getValue();
        for (Operation operation : path.readOperations()) {
            Assert.assertFalse(operation.getExtensions().containsKey(APIConstants.SWAGGER_X_SCOPE));
        }
    }

    // check updated scopes in security definition
    Operation itemGet = openAPI.getPaths().get("/items").getGet();
    Assert.assertTrue(itemGet.getSecurity().get(0).get("default").contains("newScope"));

    // check available scopes in security definition
    SecurityScheme securityScheme = openAPI.getComponents().getSecuritySchemes().get("default");
    OAuthFlow implicityOauth = securityScheme.getFlows().getImplicit();
    Assert.assertTrue(implicityOauth.getScopes().containsKey("newScope"));
    Assert.assertEquals("newScopeDescription", implicityOauth.getScopes().get("newScope"));

    Assert.assertTrue(implicityOauth.getExtensions().containsKey(APIConstants.SWAGGER_X_SCOPES_BINDINGS));
    Map<String, String> scopeBinding =
            (Map<String, String>) implicityOauth.getExtensions().get(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
    Assert.assertTrue(scopeBinding.containsKey("newScope"));
    Assert.assertEquals("admin", scopeBinding.get("newScope"));
}
 
Example 6
Source File: AbstractJavaCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    super.preprocessOpenAPI(openAPI);
    if (openAPI == null) {
        return;
    }
    if (openAPI.getPaths() != null) {
        for (String pathname : openAPI.getPaths().keySet()) {
            PathItem path = openAPI.getPaths().get(pathname);
            if (path.readOperations() == null) {
                continue;
            }
            for (Operation operation : path.readOperations()) {
                LOGGER.info("Processing operation " + operation.getOperationId());
                if (hasBodyParameter(openAPI, operation) || hasFormParameter(openAPI, operation)) {
                    String defaultContentType = hasFormParameter(openAPI, operation) ? "application/x-www-form-urlencoded" : "application/json";
                    List<String> consumes = new ArrayList<>(getConsumesInfo(openAPI, operation));
                    String contentType = consumes == null || consumes.isEmpty() ? defaultContentType : consumes.get(0);
                    operation.addExtension("x-contentType", contentType);
                }
                String accepts = getAccept(openAPI, operation);
                operation.addExtension("x-accepts", accepts);

            }
        }
    }

    // TODO: Setting additionalProperties is not the responsibility of this method. These side-effects should be moved elsewhere to prevent unexpected behaviors.
    if (artifactVersion == null) {
        // If no artifactVersion is provided in additional properties, version from API specification is used.
        // If none of them is provided then fallbacks to default version
        if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION) && additionalProperties.get(CodegenConstants.ARTIFACT_VERSION) != null) {
            this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION));
        } else if (openAPI.getInfo() != null && openAPI.getInfo().getVersion() != null) {
            this.setArtifactVersion(openAPI.getInfo().getVersion());
        } else {
            this.setArtifactVersion(ARTIFACT_VERSION_DEFAULT_VALUE);
        }
    }
    additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);

    if (additionalProperties.containsKey(CodegenConstants.SNAPSHOT_VERSION)) {
        if (convertPropertyToBooleanAndWriteBack(CodegenConstants.SNAPSHOT_VERSION)) {
            this.setArtifactVersion(this.buildSnapshotVersion(this.getArtifactVersion()));
        }
    }
    additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);

}
 
Example 7
Source File: ScalaGatlingCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
/**
 * Modifies the openapi doc to make mustache easier to use
 *
 * @param openAPI input openapi document
 */
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    for (String pathname : openAPI.getPaths().keySet()) {
        PathItem path = openAPI.getPaths().get(pathname);
        if (path.readOperations() == null) {
            continue;
        }
        for (Operation operation : path.readOperations()) {

            if (operation.getExtensions() == null) {
                operation.setExtensions(new HashMap());
            }

            if (!operation.getExtensions().keySet().contains("x-gatling-path")) {
                if (pathname.contains("{")) {
                    String gatlingPath = pathname.replaceAll("\\{", "\\$\\{");
                    operation.addExtension("x-gatling-path", gatlingPath);
                } else {
                    operation.addExtension("x-gatling-path", pathname);
                }
            }

            Set<Parameter> headerParameters = new HashSet<>();
            Set<Parameter> formParameters = new HashSet<>();
            Set<Parameter> queryParameters = new HashSet<>();
            Set<Parameter> pathParameters = new HashSet<>();

            if (operation.getParameters() != null) {

                for (Parameter parameter : operation.getParameters()) {
                    if (parameter.getIn().equalsIgnoreCase("header")) {
                        headerParameters.add(parameter);
                    }
                /* need to revise below as form parameter is no longer in the parameter list
                if (parameter.getIn().equalsIgnoreCase("formData")) {
                    formParameters.add(parameter);
                }
                */
                    if (parameter.getIn().equalsIgnoreCase("query")) {
                        queryParameters.add(parameter);
                    }
                    if (parameter.getIn().equalsIgnoreCase("path")) {
                        pathParameters.add(parameter);
                    }
                /* TODO need to revise below as body is no longer in the parameter
                if (parameter.getIn().equalsIgnoreCase("body")) {
                    BodyParameter bodyParameter = (BodyParameter) parameter;
                    Model model = bodyParameter.getSchema();
                    if (model instanceof RefModel) {
                        String[] refArray = model.getReference().split("\\/");
                        operation.setVendorExtension("x-gatling-body-object", refArray[refArray.length - 1] + ".toStringBody");
                        Set<String> bodyFeederParams = new HashSet<>();
                        Set<String> sessionBodyVars = new HashSet<>();
                        for (Map.Entry<String, Model> modelEntry : swagger.getDefinitions().entrySet()) {
                            if (refArray[refArray.length - 1].equalsIgnoreCase(modelEntry.getKey())) {
                                for (Map.Entry<String, Property> propertyEntry : modelEntry.getValue().getProperties().entrySet()) {
                                    bodyFeederParams.add(propertyEntry.getKey());
                                    sessionBodyVars.add("\"${" + propertyEntry.getKey() + "}\"");
                                }
                            }
                        }
                        operation.setVendorExtension("x-gatling-body-feeder", operation.getOperationId() + "BodyFeeder");
                        operation.setVendorExtension("x-gatling-body-feeder-params", StringUtils.join(sessionBodyVars, ","));
                        try {
                            FileUtils.writeStringToFile(
                                new File(outputFolder + File.separator + dataFolder + File.separator + operation.getOperationId() + "-" + "bodyParams.csv"),
                                StringUtils.join(bodyFeederParams, ","),
                                StandardCharsets.UTF_8
                            );
                        } catch (IOException ioe) {
                            LOGGER.error("Could not create feeder file for operationId" + operation.getOperationId(), ioe);
                        }

                    } else if (model instanceof ArrayModel) {
                        operation.setVendorExtension("x-gatling-body-object", "StringBody(\"[]\")");
                    } else {
                        operation.setVendorExtension("x-gatling-body-object", "StringBody(\"{}\")");
                    }

                }
                */
                }
            }

            prepareGatlingData(operation, headerParameters, "header");
            prepareGatlingData(operation, formParameters, "form");
            prepareGatlingData(operation, queryParameters, "query");
            prepareGatlingData(operation, pathParameters, "path");
        }
    }

}
 
Example 8
Source File: ModelUtils.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
private static void visitPathItem(PathItem pathItem, OpenAPI openAPI, OpenAPISchemaVisitor visitor, List<String> visitedSchemas) {
    List<Operation> allOperations = pathItem.readOperations();
    if (allOperations != null) {
        for (Operation operation : allOperations) {
            //Params:
            visitParameters(openAPI, operation.getParameters(), visitor, visitedSchemas);

            //RequestBody:
            RequestBody requestBody = getReferencedRequestBody(openAPI, operation.getRequestBody());
            if (requestBody != null) {
                visitContent(openAPI, requestBody.getContent(), visitor, visitedSchemas);
            }

            //Responses:
            if (operation.getResponses() != null) {
                for (ApiResponse r : operation.getResponses().values()) {
                    ApiResponse apiResponse = getReferencedApiResponse(openAPI, r);
                    if (apiResponse != null) {
                        visitContent(openAPI, apiResponse.getContent(), visitor, visitedSchemas);
                        if (apiResponse.getHeaders() != null) {
                            for (Entry<String, Header> e : apiResponse.getHeaders().entrySet()) {
                                Header header = getReferencedHeader(openAPI, e.getValue());
                                if (header.getSchema() != null) {
                                    visitSchema(openAPI, header.getSchema(), e.getKey(), visitedSchemas, visitor);
                                }
                                visitContent(openAPI, header.getContent(), visitor, visitedSchemas);
                            }
                        }
                    }
                }
            }

            //Callbacks:
            if (operation.getCallbacks() != null) {
                for (Callback c : operation.getCallbacks().values()) {
                    Callback callback = getReferencedCallback(openAPI, c);
                    if (callback != null) {
                        for (PathItem p : callback.values()) {
                            visitPathItem(p, openAPI, visitor, visitedSchemas);
                        }
                    }
                }
            }
        }
    }
    //Params:
    visitParameters(openAPI, pathItem.getParameters(), visitor, visitedSchemas);
}