Java Code Examples for io.swagger.v3.oas.models.media.MediaType#setSchema()

The following examples show how to use io.swagger.v3.oas.models.media.MediaType#setSchema() . 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: SpringDocAnnotationsUtils.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Gets media type.
 *
 * @param schema the schema
 * @param components the components
 * @param jsonViewAnnotation the json view annotation
 * @param annotationContent the annotation content
 * @return the media type
 */
private static MediaType getMediaType(Schema schema, Components components, JsonView jsonViewAnnotation,
		io.swagger.v3.oas.annotations.media.Content annotationContent) {
	MediaType mediaType = new MediaType();
	if (!annotationContent.schema().hidden()) {
		if (components != null) {
			try {
				getSchema(annotationContent, components, jsonViewAnnotation).ifPresent(mediaType::setSchema);
			}
			catch (Exception e) {
				if (isArray(annotationContent))
					mediaType.setSchema(new ArraySchema().items(new StringSchema()));
				else
					mediaType.setSchema(new StringSchema());
			}
		}
		else {
			mediaType.setSchema(schema);
		}
	}
	return mediaType;
}
 
Example 2
Source File: SchemaGeneratorHelper.java    From spring-openapi with MIT License 5 votes vote down vote up
public MediaType createMediaType(Class<?> requestBodyParameter,
                                 String parameterName,
                                 List<Class<?>> genericParams) {
    Schema<?> rootMediaSchema = new Schema<>();
    if (isFile(requestBodyParameter)) {
        Schema<?> fileSchema = new Schema<>();
        fileSchema.setType("string");
        fileSchema.setFormat("binary");

        if (parameterName == null) {
            rootMediaSchema = fileSchema;
        } else {
            Map<String, Schema> properties = new HashMap<>();
            properties.put(parameterName, fileSchema);
            rootMediaSchema.setType("object");
            rootMediaSchema.setProperties(properties);
        }
    } else if (isList(requestBodyParameter, genericParams)) {
        rootMediaSchema = parseArraySignature(getFirstOrNull(genericParams), null, new Annotation[]{});
    } else if (!StringUtils.equalsIgnoreCase(requestBodyParameter.getSimpleName(), "void")) {
        if (isInPackagesToBeScanned(requestBodyParameter, modelPackages)) {
            rootMediaSchema.set$ref(COMPONENT_REF_PREFIX + requestBodyParameter.getSimpleName());
        } else if (requestBodyParameter.isAssignableFrom(ResponseEntity.class) && !CollectionUtils.isEmpty(genericParams)
                && !genericParams.get(0).isAssignableFrom(Void.class)) {
            rootMediaSchema.set$ref(COMPONENT_REF_PREFIX + genericParams.get(0).getSimpleName());
        } else {
            return null;
        }
    } else {
        return null;
    }

    MediaType mediaType = new MediaType();
    mediaType.setSchema(rootMediaSchema);
    return mediaType;
}
 
Example 3
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveInlineRequestBody() throws Exception {
    OpenAPI openAPI = new OpenAPI();


    ObjectSchema objectSchema = new ObjectSchema();
    objectSchema.addProperties("street", new StringSchema());

    Schema schema = new Schema();
    schema.addProperties("address", objectSchema);
    schema.addProperties("name", new StringSchema());

    MediaType mediaType = new MediaType();
    mediaType.setSchema(schema);

    Content content = new Content();
    content.addMediaType("*/*", mediaType );

    RequestBody requestBody = new RequestBody();
    requestBody.setContent(content);

    Operation operation = new Operation();
    operation.setRequestBody(requestBody);

    PathItem pathItem = new PathItem();
    pathItem.setGet(operation);
    openAPI.path("/hello",pathItem);

    new InlineModelResolver().flatten(openAPI);

    Operation getOperation = openAPI.getPaths().get("/hello").getGet();
    RequestBody body = getOperation.getRequestBody();
    assertTrue(body.getContent().get("*/*").getSchema().get$ref() != null);

    Schema bodySchema = openAPI.getComponents().getSchemas().get("body");
    assertTrue(bodySchema instanceof Schema);

    assertNotNull(bodySchema.getProperties().get("address"));
}
 
Example 4
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testInlineMapResponse() throws Exception {
    OpenAPI openAPI = new OpenAPI();

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

    ApiResponse apiResponse = new ApiResponse();
    apiResponse.description("it works!");
    MediaType mediaType = new MediaType();
    mediaType.setSchema(schema);

    Content content = new Content();
    content.addMediaType("*/*",mediaType);

    apiResponse.setContent(content);
    apiResponse.addExtension("x-foo", "bar");

    ApiResponses apiResponses = new ApiResponses();
    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);
    assertTrue(openAPI.getComponents().getSchemas() == null);
    assertEquals(1, property.getExtensions().size());
    assertEquals("ext-prop", property.getExtensions().get("x-ext"));
}
 
Example 5
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Construct openAPI definition for graphQL. Add get and post operations
 *
 * @param openAPI OpenAPI
 * @return modified openAPI for GraphQL
 */
private void modifyGraphQLSwagger(OpenAPI openAPI) {
    SwaggerData.Resource resource = new SwaggerData.Resource();
    resource.setAuthType(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN);
    resource.setPolicy(APIConstants.DEFAULT_SUB_POLICY_UNLIMITED);
    resource.setPath("/");
    resource.setVerb(APIConstants.HTTP_POST);
    Operation postOperation = createOperation(resource);

    //post operation
    RequestBody requestBody = new RequestBody();
    requestBody.setDescription("Query or mutation to be passed to graphQL API");
    requestBody.setRequired(true);

    JSONObject typeOfPayload = new JSONObject();
    JSONObject payload = new JSONObject();
    typeOfPayload.put(APIConstants.TYPE, APIConstants.STRING);
    payload.put(APIConstants.OperationParameter.PAYLOAD_PARAM_NAME, typeOfPayload);

    Schema postSchema = new Schema();
    postSchema.setType(APIConstants.OBJECT);
    postSchema.setProperties(payload);

    MediaType mediaType = new MediaType();
    mediaType.setSchema(postSchema);

    Content content = new Content();
    content.addMediaType(APPLICATION_JSON_MEDIA_TYPE, mediaType);
    requestBody.setContent(content);
    postOperation.setRequestBody(requestBody);

    //add post and get operations to path /*
    PathItem pathItem = new PathItem();
    pathItem.setPost(postOperation);
    Paths paths = new Paths();
    paths.put("/", pathItem);

    openAPI.setPaths(paths);
}
 
Example 6
Source File: Reader.java    From proteus with Apache License 2.0 4 votes vote down vote up
private void setMediaTypeToContent(Schema schema, Content content, String value)
{
	MediaType mediaTypeObject = new MediaType();
	mediaTypeObject.setSchema(schema);
	content.addMediaType(value, mediaTypeObject);
}
 
Example 7
Source File: OpenAPIDeserializer.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
public MediaType getMediaType(ObjectNode contentNode, String location, ParseResult result){
    if (contentNode == null) {
        return null;
    }
    MediaType mediaType = new MediaType();

    ObjectNode schemaObject = getObject("schema",contentNode,false,location,result);
    if(schemaObject != null){
        mediaType.setSchema(getSchema(schemaObject,String.format("%s.%s", location, "schema"),result));
    }


    ObjectNode encodingObject = getObject("encoding",contentNode,false,location,result);
    if(encodingObject!=null) {
        mediaType.setEncoding(getEncodingMap(encodingObject, String.format("%s.%s", location, "encoding"), result));
    }
    Map <String,Object> extensions = getExtensions(contentNode);
    if(extensions != null && extensions.size() > 0) {
        mediaType.setExtensions(extensions);
    }

    ObjectNode examplesObject = getObject("examples",contentNode,false,location,result);
    if(examplesObject!=null) {
        mediaType.setExamples(getExamples(examplesObject, String.format("%s.%s", location, "examples"), result, false));
    }

    Object example = getAnyExample("example",contentNode, location,result);
    if (example != null){
        mediaType.setExample(example);
    }


    Set<String> keys = getKeys(contentNode);
    for(String key : keys) {
        if(!MEDIATYPE_KEYS.contains(key) && !key.startsWith("x-")) {
            result.extra(location, key, contentNode.get(key));
        }
    }

    return mediaType;
}
 
Example 8
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testInlineResponseModel() throws Exception {
    OpenAPI openAPI = new OpenAPI();


    StringSchema stringSchema1 = new StringSchema();

    ObjectSchema objectSchema1 = new ObjectSchema();
    objectSchema1.addProperties("name", stringSchema1);
    objectSchema1.addExtension("x-ext", "ext-prop");

    MediaType mediaType1 = new MediaType();
    mediaType1.setSchema(objectSchema1);

    Content content1 = new Content();
    content1.addMediaType("*/*", mediaType1 );

    ApiResponse response1= new ApiResponse();
    response1.setDescription("it works!");
    response1.setContent(content1);

    ApiResponses responses1 = new ApiResponses();
    responses1.addApiResponse("200",response1);

    Operation operation1 = new Operation();
    operation1.setResponses(responses1);

    PathItem pathItem1 = new PathItem();
    pathItem1.setGet(operation1);
    openAPI.path("/foo/bar",pathItem1);



    StringSchema stringSchema2 = new StringSchema();

    ObjectSchema objectSchema2 = new ObjectSchema();
    objectSchema2.addProperties("name", stringSchema2);
    objectSchema2.addExtension("x-ext", "ext-prop");
    MediaType mediaType2 = new MediaType();
    mediaType2.setSchema(objectSchema2);

    Content content2 = new Content();
    content2.addMediaType("*/*", mediaType2 );

    ApiResponse response2 = new ApiResponse();
    response2.setDescription("it works!");
    response2.addExtension("x-foo","bar");
    response2.setContent(content2);

    ApiResponses responses2 = new ApiResponses();
    responses2.addApiResponse("200",response2);

    Operation operation2 = new Operation();
    operation2.setResponses(responses2);

    PathItem pathItem2 = new PathItem();
    pathItem2.setGet(operation2);
    openAPI.path("/foo/baz",pathItem2);


    new InlineModelResolver().flatten(openAPI);

    Map<String, ApiResponse> responses = openAPI.getPaths().get("/foo/bar").getGet().getResponses();

    ApiResponse response = responses.get("200");
    assertNotNull(response);

    Schema schema = response.getContent().get("*/*").getSchema();
    assertTrue(schema.get$ref() != null);
    assertEquals(1, schema.getExtensions().size());
    assertEquals("ext-prop", schema.getExtensions().get("x-ext"));

    Schema model = openAPI.getComponents().getSchemas().get("inline_response_200");
    assertTrue(model.getProperties().size() == 1);
    assertNotNull(model.getProperties().get("name"));
    assertTrue(model.getProperties().get("name") instanceof StringSchema);
}
 
Example 9
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 2 votes vote down vote up
@Test
public void testInlineResponseModelWithTitle() throws Exception {
    OpenAPI openAPI = new OpenAPI();

    String responseTitle = "GetBarResponse";

    StringSchema stringSchema1 = new StringSchema();

    ObjectSchema objectSchema1 = new ObjectSchema();
    objectSchema1.setTitle(responseTitle);
    objectSchema1.addProperties("name", stringSchema1);


    MediaType mediaType1 = new MediaType();
    mediaType1.setSchema(objectSchema1);

    Content content1 = new Content();
    content1.addMediaType("*/*", mediaType1 );

    ApiResponse response1= new ApiResponse();
    response1.setDescription("it works!");
    response1.setContent(content1);

    ApiResponses responses1 = new ApiResponses();
    responses1.addApiResponse("200",response1);

    Operation operation1 = new Operation();
    operation1.setResponses(responses1);

    PathItem pathItem1 = new PathItem();
    pathItem1.setGet(operation1);
    openAPI.path("/foo/bar",pathItem1);



    StringSchema stringSchema2 = new StringSchema();

    ObjectSchema objectSchema2 = new ObjectSchema();
    objectSchema2.addProperties("name", stringSchema2);
    objectSchema2.addExtension("x-foo", "bar");

    MediaType mediaType2 = new MediaType();
    mediaType2.setSchema(objectSchema2);

    Content content2 = new Content();
    content2.addMediaType("*/*", mediaType2 );

    ApiResponse response2 = new ApiResponse();
    response2.setDescription("it works!");

    response2.setContent(content2);

    ApiResponses responses2 = new ApiResponses();
    responses2.addApiResponse("200",response2);

    Operation operation2 = new Operation();
    operation2.setResponses(responses2);

    PathItem pathItem2 = new PathItem();
    pathItem2.setGet(operation2);
    openAPI.path("/foo/baz",pathItem2);



    new InlineModelResolver().flatten(openAPI);

    Map<String, ApiResponse> responses = openAPI.getPaths().get("/foo/bar").getGet().getResponses();

    ApiResponse response = responses.get("200");
    assertNotNull(response);
    assertTrue(response.getContent().get("*/*").getSchema().get$ref() != null );

    Schema model = openAPI.getComponents().getSchemas().get(responseTitle);
    assertTrue(model.getProperties().size() == 1);
    assertNotNull(model.getProperties().get("name"));
    assertTrue(model.getProperties().get("name") instanceof StringSchema);
}