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

The following examples show how to use io.swagger.v3.oas.models.OpenAPI#getPaths() . 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: 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 2
Source File: BearerOpenAPIFilter.java    From RestDoc with Apache License 2.0 6 votes vote down vote up
@Override
public OpenAPI handle(OpenAPI openApi) {
    var components = openApi.getComponents();
    // security 添加 token
    var scheme = new SecurityScheme();
    scheme.setType(SecurityScheme.Type.HTTP);
    scheme.setScheme("bearer");
    scheme.setBearerFormat("JWT");
    components.addSecuritySchemes("bearerAuth", scheme);
    // path 添加 token
    var paths = openApi.getPaths();
    var securityRequirement = new SecurityRequirement().addList("bearerAuth");
    paths.forEach((s, pathItem) -> {
        handelPathItem(pathItem.getGet(), securityRequirement);
        handelPathItem(pathItem.getPost(), securityRequirement);
        handelPathItem(pathItem.getPut(), securityRequirement);
        handelPathItem(pathItem.getDelete(), securityRequirement);
        handelPathItem(pathItem.getPatch(), securityRequirement);
        handelPathItem(pathItem.getHead(), securityRequirement);
        handelPathItem(pathItem.getOptions(), securityRequirement);
        handelPathItem(pathItem.getTrace(), securityRequirement);
    });
    return openApi;
}
 
Example 3
Source File: HideEmptyControllerOpenAPIFilter.java    From RestDoc with Apache License 2.0 6 votes vote down vote up
@Override
public OpenAPI handle(OpenAPI openApi) {
    if (openApi.getPaths() == null) return openApi;

    Set<String> tags = new HashSet<>();
    for (var path : openApi.getPaths().values()) {
        if (path.getGet() != null) tags.addAll(path.getGet().getTags());
        if (path.getPost() != null) tags.addAll(path.getPost().getTags());
        if (path.getPut() != null) tags.addAll(path.getPut().getTags());
        if (path.getDelete() != null) tags.addAll(path.getDelete().getTags());
        if (path.getOptions() != null) tags.addAll(path.getOptions().getTags());
        if (path.getHead() != null) tags.addAll(path.getHead().getTags());
        if (path.getPatch() != null) tags.addAll(path.getPatch().getTags());
    }

    openApi.getTags().removeIf(tag -> tags.stream().noneMatch(o -> o.equals(tag.getName())));
    return openApi;
}
 
Example 4
Source File: ObjcModelTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "create proper imports per #316")
public void issue316Test() {
    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/postBodyTest.json");
    final DefaultCodegen codegen = new ObjcClientCodegen();
    codegen.setOpenAPI(openAPI);

    final Map<String, PathItem> animalPaths = openAPI.getPaths();

    final PathItem animalOps = animalPaths.get("/animals");
    Assert.assertNotNull(animalOps.getPost());

    final CodegenOperation animalCo = codegen.fromOperation("/animals", "POST", animalOps.getPost(), null);
    Assert.assertEquals(animalCo.imports.size(), 1);
    Assert.assertTrue(animalCo.imports.contains("OAIAnimal"));

    final Map<String, PathItem> insectPaths = openAPI.getPaths();
    final PathItem insectOps = insectPaths.get("/insects");
    Assert.assertNotNull(insectOps.getPost());

    final CodegenOperation insectCo = codegen.fromOperation("/insects", "POST", insectOps.getPost(), null);
    Assert.assertEquals(insectCo.imports.size(), 1);
    Assert.assertTrue(insectCo.imports.contains("OAIInsect"));
}
 
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 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 6
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 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: OpenApiDiff.java    From openapi-diff with Apache License 2.0 5 votes vote down vote up
private void preProcess(OpenAPI openApi) {
  List<SecurityRequirement> securityRequirements = openApi.getSecurity();

  if (securityRequirements != null) {
    List<SecurityRequirement> distinctSecurityRequirements =
        securityRequirements.stream().distinct().collect(Collectors.toList());
    Map<String, PathItem> paths = openApi.getPaths();
    if (paths != null) {
      paths
          .values()
          .forEach(
              pathItem ->
                  pathItem
                      .readOperationsMap()
                      .values()
                      .stream()
                      .filter(operation -> operation.getSecurity() != null)
                      .forEach(
                          operation ->
                              operation.setSecurity(
                                  operation
                                      .getSecurity()
                                      .stream()
                                      .distinct()
                                      .collect(Collectors.toList()))));
      paths
          .values()
          .forEach(
              pathItem ->
                  pathItem
                      .readOperationsMap()
                      .values()
                      .stream()
                      .filter(operation -> operation.getSecurity() == null)
                      .forEach(operation -> operation.setSecurity(distinctSecurityRequirements)));
    }
    openApi.setSecurity(null);
  }
}
 
Example 9
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 10
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 11
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 12
Source File: PhpZendExpressivePathHandlerServerCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
/**
 * Generate additional model definitions from query parameters
 *
 * @param openAPI OpenAPI object
 */
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    super.preprocessOpenAPI(openAPI);

    Map<String, PathItem> 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);
                    Map<String, Schema> schemas = new HashMap<>();
                    if (operation == null || operation.getParameters() == null) {
                        continue;
                    }

                    List<String> requiredProperties = new ArrayList<>();
                    for (Parameter parameter : operation.getParameters()) {
                        Schema schema = convertParameterToSchema(parameter);
                        if (schema != null) {
                            schemas.put(schema.getName(), schema);
                            if (Boolean.TRUE.equals(parameter.getRequired())) {
                                requiredProperties.add(schema.getName());
                            }
                        }
                    }

                    if (!schemas.isEmpty()) {
                        ObjectSchema model = new ObjectSchema();
                        String operationId = getOrGenerateOperationId(operation, pathname, method.name());
                        model.setDescription("Query parameters for " + operationId);
                        model.setProperties(schemas);
                        model.setRequired(requiredProperties);
                        //Add internal extension directly, because addExtension filters extension names
                        addInternalExtensionToSchema(model, VEN_FROM_QUERY, Boolean.TRUE);
                        String definitionName = generateUniqueDefinitionName(operationId + "QueryData", openAPI);
                        openAPI.getComponents().addSchemas(definitionName, model);
                        String definitionModel = "\\" + modelPackage + "\\" + toModelName(definitionName);
                        addInternalExtensionToOperation(operation, VEN_QUERY_DATA_TYPE, definitionModel);
                        addInternalExtensionToOperation(operation, VEN_HAS_QUERY_DATA, Boolean.TRUE);
                    }
                }
            }
        }
    }
}
 
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: PythonAbstractConnexionServerCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
    // XXX - Revert the original parameter (and path) names to make sure we have
    //       a consistent REST interface across other server/client languages:
    //
    // XXX - Reverts `x-python-connexion-openapi-name` back to the original (query/path) parameter name.
    //       We do not want to have our REST API itself being converted to pythonic params.
    //       This would be incompatible with other server implementations.
    OpenAPI openAPI = (OpenAPI) objs.get("openAPI");
    Map<String, PathItem> paths = openAPI.getPaths();
    if (paths != null) {
        List<String> pathnames = new ArrayList(paths.keySet());
        for (String pythonPathname : pathnames) {
            PathItem path = paths.get(pythonPathname);

            // Fix path parameters back to original casing
            Map<String, Object> pathExtensions = path.getExtensions();
            if (pathExtensions != null) {
                // Get and remove the (temporary) vendor extension
                String openapiPathname = (String) pathExtensions.remove("x-python-connexion-openapi-name");
                if (openapiPathname != null && !openapiPathname.equals(pythonPathname)) {
                    LOGGER.info("Path '" + pythonPathname + "' is not consistant with the original OpenAPI definition. It will be replaced back by '" + openapiPathname + "'");
                    paths.remove(pythonPathname);
                    paths.put(openapiPathname, path);
                }
            }

            Map<HttpMethod, Operation> operationMap = path.readOperationsMap();
            if (operationMap != null) {
                for (HttpMethod method : operationMap.keySet()) {
                    Operation operation = operationMap.get(method);
                    if (operation.getParameters() != null) {
                        for (Parameter parameter : operation.getParameters()) {
                            Map<String, Object> parameterExtensions = parameter.getExtensions();
                            if (parameterExtensions != null) {
                                // Get and remove the (temporary) vendor extension
                                String swaggerParameterName = (String) parameterExtensions.remove("x-python-connexion-openapi-name");
                                if (swaggerParameterName != null) {
                                    String pythonParameterName = parameter.getName();
                                    if (!swaggerParameterName.equals(pythonParameterName)) {
                                        LOGGER.info("Reverting name of parameter '" + pythonParameterName + "' of operation '" + operation.getOperationId() + "' back to '" + swaggerParameterName + "'");
                                        parameter.setName(swaggerParameterName);
                                    } else {
                                        LOGGER.debug("Name of parameter '" + pythonParameterName + "' of operation '" + operation.getOperationId() + "' was unchanged.");
                                    }
                                } else {
                                    LOGGER.debug("x-python-connexion-openapi-name was not set on parameter '" + parameter.getName() + "' of operation '" + operation.getOperationId() + "'");
                                }
                            }
                        }
                    }
                }
            }
        }

        // Sort path names after variable name fix
        List<String> recoveredPathnames = new ArrayList(paths.keySet());
        Collections.sort(recoveredPathnames);
        for (String pathname : recoveredPathnames) {
            PathItem pathItem = paths.remove(pathname);
            paths.put(pathname, pathItem);
        }
    }

    generateJSONSpecFile(objs);
    generateYAMLSpecFile(objs);

    for (Map<String, Object> operations : getOperations(objs)) {
        @SuppressWarnings("unchecked")
        List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");

        List<Map<String, Object>> opsByPathList = sortOperationsByPath(ops);
        operations.put("operationsByPath", opsByPathList);
    }
    return super.postProcessSupportingFileData(objs);
}
 
Example 15
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 16
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 17
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method generates API definition to the given api
 *
 * @param swaggerData api
 * @return API definition in string format
 * @throws APIManagementException
 */
@Override
public String generateAPIDefinition(SwaggerData swaggerData) throws APIManagementException {
    OpenAPI openAPI = new OpenAPI();

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

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

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

    info.setVersion(swaggerData.getVersion());
    openAPI.setInfo(info);
    updateSwaggerSecurityDefinition(openAPI, swaggerData, "https://test.com");
    updateLegacyScopesFromSwagger(openAPI, swaggerData);
    if (APIConstants.GRAPHQL_API.equals(swaggerData.getTransportType())) {
        modifyGraphQLSwagger(openAPI);
    } else {
        for (SwaggerData.Resource resource : swaggerData.getResources()) {
            addOrUpdatePathToSwagger(openAPI, resource);
        }
    }
    return Json.pretty(openAPI);
}
 
Example 18
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 19
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;
}
 
Example 20
Source File: OpenApiPathsValidator.java    From servicecomb-toolkit with Apache License 2.0 4 votes vote down vote up
@Override
protected Paths getPropertyObject(OpenAPI oasObject) {
  return oasObject.getPaths();
}