Search in sources :

Example 21 with Content

use of io.swagger.v3.oas.annotations.media.Content in project swagger-parser by swagger-api.

the class OpenAPIDeserializerTest method testStyleInvalid.

@Test
public void testStyleInvalid() {
    String json = "{" + "    \"openapi\": \"3.0.0\"," + "    \"info\": {" + "        \"title\": \"realize\"," + "        \"version\": \"0.0.0\"" + "    }," + "    \"paths\": {" + "        \"/realize/{param}\": {" + "            \"post\": {" + "                \"parameters\": [" + "                    {" + "                        \"name\": \"param\"," + "                        \"in\": \"path\"," + "" + "                        \"style\": \"DERP\"," + "                        \"required\": true," + "" + "                        \"schema\": {" + "                            \"type\": \"string\"," + "                            \"nullable\": false," + "                            \"minLength\": 1" + "                        }" + "                    }" + "                ]," + "                \"responses\": {" + "                    \"200\": {" + "                        \"description\": \"Success\"," + "                        \"content\": {" + "                            \"application/json\": {" + "                                \"schema\": {" + "                                    \"type\": \"object\"" + "                                }" + "                            }" + "                        }" + "                    }" + "                }" + "            }" + "        }" + "    }" + "}";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(json, null, null);
    assertTrue(result.getMessages().size() == 1);
    assertEquals(result.getMessages().get(0), "attribute paths.'/realize/{param}'(post).parameters.[param].style is not of type `StyleEnum`");
}
Also used : SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) Test(org.testng.annotations.Test)

Example 22 with Content

use of io.swagger.v3.oas.annotations.media.Content in project swagger-parser by swagger-api.

the class OpenAPIDeserializerTest method testBodyContent.

@Test
public void testBodyContent() {
    String json = "{" + "  \"openapi\": \"3.0.0\"," + "  \"info\": {" + "    \"title\": \"Operations\"," + "    \"version\": \"0.0.0\"" + "  }," + "  \"paths\": {" + "    \"/operations\": {" + "      \"post\": {" + "        \"requestBody\": {" + "            \"description\": \"Content empty\"," + "            \"content\": {" + "            }" + "        }," + "        \"responses\": {" + "          \"default\": {" + "            \"description\": \"None\"" + "          }" + "        }" + "      }," + "      \"put\": {" + "        \"requestBody\": {" + "            \"description\": \"Content undefined\"" + "        }," + "        \"responses\": {" + "          \"default\": {" + "            \"description\": \"None\"" + "          }" + "        }" + "      }" + "    }" + "  }" + "}";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(json, null, null);
    Operation post = result.getOpenAPI().getPaths().get("/operations").getPost();
    assertEquals(post.getRequestBody().getContent(), null, "Empty content");
    assertEquals(result.getMessages().contains("attribute paths.'/operations'(post).requestBody.content with no media type is unsupported"), true, "Empty content error reported");
    Operation put = result.getOpenAPI().getPaths().get("/operations").getPut();
    assertEquals(put.getRequestBody().getContent(), null, "Empty content");
    assertEquals(result.getMessages().contains("attribute paths.'/operations'(put).requestBody.content is missing"), true, "Missing content error reported");
    assertEquals(result.getMessages().size(), 2, "Messages");
}
Also used : SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Operation(io.swagger.v3.oas.models.Operation) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) Test(org.testng.annotations.Test)

Example 23 with Content

use of io.swagger.v3.oas.annotations.media.Content in project swagger-parser by swagger-api.

the class SwaggerConverter method convert.

public Operation convert(io.swagger.models.Operation v2Operation) {
    Operation operation = new Operation();
    if (StringUtils.isNotBlank(v2Operation.getDescription())) {
        operation.setDescription(v2Operation.getDescription());
    }
    if (StringUtils.isNotBlank(v2Operation.getSummary())) {
        operation.setSummary(v2Operation.getSummary());
    }
    operation.setDeprecated(v2Operation.isDeprecated());
    operation.setOperationId(v2Operation.getOperationId());
    operation.setExtensions(convert(v2Operation.getVendorExtensions()));
    operation.setTags(v2Operation.getTags());
    if (v2Operation.getParameters() != null) {
        List<io.swagger.models.parameters.Parameter> formParams = new ArrayList<>();
        for (io.swagger.models.parameters.Parameter param : v2Operation.getParameters()) {
            if ("formData".equals(param.getIn())) {
                formParams.add(param);
            } else if ("body".equals(param.getIn())) {
                operation.setRequestBody(convertParameterToRequestBody(param, v2Operation.getConsumes()));
                operation.addExtension("x-codegen-request-body-name", param.getName());
            } else {
                Parameter convert = convert(param);
                String $ref = convert.get$ref();
                if ($ref != null && $ref.startsWith("#/components/requestBodies/") && isRefABodyParam(param)) {
                    operation.setRequestBody(new RequestBody().$ref($ref));
                } else if ($ref != null && $ref.startsWith("#/components/schemas/") && isRefAFormParam(param)) {
                    formParams.add(param);
                } else {
                    operation.addParametersItem(convert);
                }
            }
        }
        if (formParams.size() > 0) {
            RequestBody body = convertFormDataToRequestBody(formParams, v2Operation.getConsumes());
            body.getContent().forEach((key, content) -> {
                Schema schema = content.getSchema();
                if (schema != null && schema.getRequired() != null && schema.getRequired().size() > 0) {
                    body.setRequired(Boolean.TRUE);
                }
            });
            operation.requestBody(body);
        }
    }
    if (v2Operation.getResponses() != null) {
        for (String responseCode : v2Operation.getResponses().keySet()) {
            io.swagger.models.Response v2Response = v2Operation.getResponses().get(responseCode);
            ApiResponse response = convert(v2Response, v2Operation.getProduces());
            ApiResponses responses = operation.getResponses();
            if (responses == null) {
                responses = new ApiResponses();
            }
            operation.responses(responses.addApiResponse(responseCode, response));
        }
    }
    if (v2Operation.getExternalDocs() != null) {
        operation.setExternalDocs(convert(v2Operation.getExternalDocs()));
    }
    if (v2Operation.getSecurity() != null && v2Operation.getSecurity().size() > 0) {
        operation.setSecurity(convertSecurityRequirementsMap(v2Operation.getSecurity()));
    }
    return operation;
}
Also used : ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Schema(io.swagger.v3.oas.models.media.Schema) FileSchema(io.swagger.v3.oas.models.media.FileSchema) ArrayList(java.util.ArrayList) Operation(io.swagger.v3.oas.models.Operation) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) Response(io.swagger.models.Response) Parameter(io.swagger.v3.oas.models.parameters.Parameter) SerializableParameter(io.swagger.models.parameters.SerializableParameter) AbstractSerializableParameter(io.swagger.models.parameters.AbstractSerializableParameter) RefParameter(io.swagger.models.parameters.RefParameter) BodyParameter(io.swagger.models.parameters.BodyParameter) ApiResponses(io.swagger.v3.oas.models.responses.ApiResponses) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody)

Example 24 with Content

use of io.swagger.v3.oas.annotations.media.Content in project swagger-parser by swagger-api.

the class SwaggerConverter method convertParameterToRequestBody.

private RequestBody convertParameterToRequestBody(io.swagger.models.parameters.Parameter param, List<String> consumes) {
    RequestBody body = new RequestBody();
    BodyParameter bp = (BodyParameter) param;
    List<String> mediaTypes = new ArrayList<>(globalConsumes);
    if (consumes != null && consumes.size() > 0) {
        mediaTypes.clear();
        mediaTypes.addAll(consumes);
    }
    if (mediaTypes.size() == 0) {
        mediaTypes.add("*/*");
    }
    if (StringUtils.isNotBlank(param.getDescription())) {
        body.description(param.getDescription());
    }
    body.required(param.getRequired());
    Content content = new Content();
    for (String type : mediaTypes) {
        content.addMediaType(type, new MediaType().schema(convert(bp.getSchema())));
        if (StringUtils.isNotBlank(bp.getDescription())) {
            body.setDescription(bp.getDescription());
        }
    }
    convertExamples(((BodyParameter) param).getExamples(), content);
    body.content(content);
    return body;
}
Also used : Content(io.swagger.v3.oas.models.media.Content) ArrayList(java.util.ArrayList) MediaType(io.swagger.v3.oas.models.media.MediaType) BodyParameter(io.swagger.models.parameters.BodyParameter) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody)

Example 25 with Content

use of io.swagger.v3.oas.annotations.media.Content in project swagger-parser by swagger-api.

the class OpenAPIResolverTest method componentsResolver.

@Test
public void componentsResolver() throws Exception {
    final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    String pathFile = FileUtils.readFileToString(new File("src/test/resources/oas3.yaml.template"));
    pathFile = pathFile.replace("${dynamicPort}", String.valueOf(this.serverPort));
    final JsonNode rootNode = mapper.readTree(pathFile.getBytes());
    final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
    final SwaggerParseResult result = deserializer.deserialize(rootNode);
    Assert.assertNotNull(result);
    final OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);
    assertEquals(new OpenAPIResolver(openAPI, new ArrayList<>(), null).resolve(), openAPI);
    Map<String, Schema> schemas = openAPI.getComponents().getSchemas();
    // internal url schema
    Schema pet = schemas.get("Pet");
    Schema category = (Schema) pet.getProperties().get("category");
    assertEquals(category.get$ref(), "#/components/schemas/Category");
    // remote url schema
    Schema user = (Schema) pet.getProperties().get("user");
    assertEquals(user.get$ref(), "#/components/schemas/User");
    // ArraySchema items
    ArraySchema tagsProperty = (ArraySchema) pet.getProperties().get("tags");
    assertEquals(tagsProperty.getItems().get$ref(), "#/components/schemas/ExampleSchema");
    assertEquals(tagsProperty.getType(), "array");
    Assert.assertNotNull(openAPI.getComponents().getSchemas().get("ExampleSchema"));
    // Schema not
    assertEquals(schemas.get("OrderRef").getNot().get$ref(), "#/components/schemas/Category");
    // Schema additionalProperties
    assertTrue(schemas.get("OrderRef").getAdditionalProperties() instanceof Schema);
    Schema additionalProperties = (Schema) schemas.get("OrderRef").getAdditionalProperties();
    assertEquals(additionalProperties.get$ref(), "#/components/schemas/User");
    // AllOfSchema
    ComposedSchema extended = (ComposedSchema) schemas.get("ExtendedErrorModel");
    Schema root = (Schema) extended.getAllOf().get(0).getProperties().get("rootCause");
    assertEquals(root.get$ref(), "#/components/schemas/Category");
    Map<String, ApiResponse> responses = openAPI.getComponents().getResponses();
    // internal response headers
    ApiResponse illegalInput = responses.get("IllegalInput");
    assertEquals(illegalInput.getHeaders().get("X-Ref-Limit-Limit").get$ref(), "#/components/headers/X-Rate-Limit-Reset");
    // internal response links
    assertEquals(illegalInput.getLinks().get("address").get$ref(), "#/components/links/unsubscribe");
    // internal url response schema
    MediaType generalError = responses.get("GeneralError").getContent().get("application/json");
    assertEquals(generalError.getSchema().get$ref(), "#/components/schemas/ExtendedErrorModel");
    Map<String, RequestBody> requestBodies = openAPI.getComponents().getRequestBodies();
    // internal url requestBody schema
    RequestBody requestBody1 = requestBodies.get("requestBody1");
    MediaType xmlMedia = requestBody1.getContent().get("application/json");
    assertEquals(xmlMedia.getSchema().get$ref(), "#/components/schemas/Pet");
    // internal url requestBody ArraySchema
    RequestBody requestBody2 = requestBodies.get("requestBody2");
    MediaType jsonMedia = requestBody2.getContent().get("application/json");
    ArraySchema items = (ArraySchema) jsonMedia.getSchema();
    assertEquals(items.getItems().get$ref(), "#/components/schemas/User");
    // internal request body
    assertEquals("#/components/requestBodies/requestBody2", requestBodies.get("requestBody3").get$ref());
    // remote request body url
    assertEquals(requestBodies.get("reference").get$ref(), "#/components/requestBodies/remote_requestBody");
    Map<String, Parameter> parameters = openAPI.getComponents().getParameters();
    // remote url parameter
    assertEquals(parameters.get("remoteParameter").get$ref(), "#/components/parameters/parameter");
    // internal Schema Parameter
    assertEquals(parameters.get("newParam").getSchema().get$ref(), "#/components/schemas/Tag");
    // parameter examples
    assertEquals(parameters.get("contentParameter").getExamples().get("cat"), openAPI.getComponents().getExamples().get("cat"));
    // parameter content schema
    assertEquals(parameters.get("contentParameter").getContent().get("application/json").getSchema().get$ref(), "#/components/schemas/ExtendedErrorModel");
    // internal Schema header
    Map<String, Header> headers = openAPI.getComponents().getHeaders();
    // header remote schema ref
    assertEquals(headers.get("X-Rate-Limit-Remaining").getSchema().get$ref(), "#/components/schemas/User");
    // header examples
    assertEquals(headers.get("X-Rate-Limit-Reset").getExamples().get("headerExample").get$ref(), "#/components/examples/dog");
    // remote header ref
    assertEquals(headers.get("X-Ref-Limit-Limit").get$ref(), "#/components/headers/X-Rate-Limit-Reset");
    // header content
    assertEquals(headers.get("X-Rate-Limit-Reset").getContent().get("application/json").getSchema().get$ref(), "#/components/schemas/ExtendedErrorModel");
    Map<String, Example> examples = openAPI.getComponents().getExamples();
    // internal url example
    Example frogExample = examples.get("frog");
    assertEquals(frogExample.get$ref(), "#/components/examples/cat");
    // remote example url
    assertEquals(examples.get("referenceCat").get$ref(), "#/components/examples/example");
    // internal url securityScheme
    SecurityScheme scheme = openAPI.getComponents().getSecuritySchemes().get("reference");
    assertEquals(scheme.getType(), SecurityScheme.Type.APIKEY);
    SecurityScheme remoteScheme = openAPI.getComponents().getSecuritySchemes().get("remote_reference");
    assertEquals(remoteScheme.getType(), SecurityScheme.Type.OAUTH2);
    Map<String, Link> links = openAPI.getComponents().getLinks();
    // internal link
    assertEquals(openAPI.getComponents().getLinks().get("referenced").get$ref(), "#/components/links/unsubscribe");
    // remote ref link
    assertEquals(openAPI.getComponents().getLinks().get("subscribe").get$ref(), "#/components/links/link");
    Map<String, Callback> callbacks = openAPI.getComponents().getCallbacks();
    // internal callback reference
    assertEquals(callbacks.get("referenced").get$ref(), "#/components/callbacks/failed");
    // callback pathItem -> operation ->requestBody
    assertEquals(callbacks.get("heartbeat").get("$request.query.heartbeat-url").getPost().getRequestBody().get$ref(), "#/components/requestBodies/requestBody3");
    // remote callback ref
    assertEquals(callbacks.get("remoteCallback").get$ref(), "#/components/callbacks/callback");
}
Also used : OpenAPIDeserializer(io.swagger.v3.parser.util.OpenAPIDeserializer) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) StringSchema(io.swagger.v3.oas.models.media.StringSchema) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Schema(io.swagger.v3.oas.models.media.Schema) JsonNode(com.fasterxml.jackson.databind.JsonNode) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Example(io.swagger.v3.oas.models.examples.Example) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) MediaType(io.swagger.v3.oas.models.media.MediaType) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Callback(io.swagger.v3.oas.models.callbacks.Callback) Header(io.swagger.v3.oas.models.headers.Header) OpenAPIResolver(io.swagger.v3.parser.OpenAPIResolver) Parameter(io.swagger.v3.oas.models.parameters.Parameter) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) File(java.io.File) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Link(io.swagger.v3.oas.models.links.Link) Test(org.testng.annotations.Test)

Aggregations

OpenAPI (io.swagger.v3.oas.models.OpenAPI)121 Test (org.testng.annotations.Test)120 MediaType (io.swagger.v3.oas.models.media.MediaType)70 Schema (io.swagger.v3.oas.models.media.Schema)70 Operation (io.swagger.v3.oas.annotations.Operation)65 Content (io.swagger.v3.oas.models.media.Content)64 ApiResponses (io.swagger.v3.oas.annotations.responses.ApiResponses)62 OpenAPIV3Parser (io.swagger.v3.parser.OpenAPIV3Parser)59 ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)57 IntegerSchema (io.swagger.v3.oas.models.media.IntegerSchema)53 Operation (io.swagger.v3.oas.models.Operation)52 ObjectSchema (io.swagger.v3.oas.models.media.ObjectSchema)51 StringSchema (io.swagger.v3.oas.models.media.StringSchema)50 ProtectedApi (org.gluu.oxtrust.service.filter.ProtectedApi)42 PathItem (io.swagger.v3.oas.models.PathItem)41 ArrayList (java.util.ArrayList)41 RequestBody (io.swagger.v3.oas.models.parameters.RequestBody)40 ApiResponse (io.swagger.v3.oas.models.responses.ApiResponse)37 SwaggerParseResult (io.swagger.v3.parser.core.models.SwaggerParseResult)37 ParseOptions (io.swagger.v3.parser.core.models.ParseOptions)33