Java Code Examples for io.swagger.v3.oas.models.responses.ApiResponse#content()

The following examples show how to use io.swagger.v3.oas.models.responses.ApiResponse#content() . 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: OASErrors.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
public static Map<String, ApiResponse> generateStandardApiErrorResponses() {
  Map<String, ApiResponse> responses = new LinkedHashMap<>();

  List<Integer> responseCodes = getStandardHttpStatusCodes();
  for (Integer responseCode : responseCodes) {
    if (responseCode >= 400 && responseCode <= 599) {
      ApiResponse apiResponse = new ApiResponse();
      apiResponse.description(HttpStatus.toMessage(responseCode));
      apiResponse.content(new Content()
          .addMediaType("application/vnd.api+json",
              new MediaType().schema(new Failure().$ref()))
      );
      responses.put(responseCode.toString(), apiResponse);
    }
  }

  return responses;
}
 
Example 2
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
private ApiResponse createApiSuccessfulResponse(
        MethodDeclaration methodDeclaration) {
    Content successfulContent = new Content();
    // "description" is a REQUIRED property of Response
    ApiResponse successfulResponse = new ApiResponse().description("");
    methodDeclaration.getJavadoc().ifPresent(javadoc -> {
        for (JavadocBlockTag blockTag : javadoc.getBlockTags()) {
            if (blockTag.getType() == JavadocBlockTag.Type.RETURN) {
                successfulResponse.setDescription(
                        "Return " + blockTag.getContent().toText());
            }
        }
    });
    if (!methodDeclaration.getType().isVoidType()) {
        MediaType mediaItem = createReturnMediaType(methodDeclaration);
        successfulContent.addMediaType("application/json", mediaItem);
        successfulResponse.content(successfulContent);
    }
    return successfulResponse;
}
 
Example 3
Source File: GenericResponseBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Build content from doc.
 *
 * @param components the components
 * @param apiResponsesOp the api responses op
 * @param methodAttributes the method attributes
 * @param apiResponseAnnotations the api response annotations
 * @param apiResponse the api response
 */
public static void buildContentFromDoc(Components components, ApiResponses apiResponsesOp,
		MethodAttributes methodAttributes,
		io.swagger.v3.oas.annotations.responses.ApiResponse apiResponseAnnotations,
		ApiResponse apiResponse) {

	io.swagger.v3.oas.annotations.media.Content[] contentdoc = apiResponseAnnotations.content();
	Optional<Content> optionalContent = getContent(contentdoc, new String[0],
			methodAttributes.getMethodProduces(), null, components, methodAttributes.getJsonViewAnnotation());
	if (apiResponsesOp.containsKey(apiResponseAnnotations.responseCode())) {
		// Merge with the existing content
		Content existingContent = apiResponsesOp.get(apiResponseAnnotations.responseCode()).getContent();
		if (optionalContent.isPresent()) {
			Content newContent = optionalContent.get();
			if (methodAttributes.isMethodOverloaded() && existingContent != null) {
				Arrays.stream(methodAttributes.getMethodProduces()).filter(mediaTypeStr -> (newContent.get(mediaTypeStr) != null)).forEach(mediaTypeStr -> {
					if (newContent.get(mediaTypeStr).getSchema() != null)
						mergeSchema(existingContent, newContent.get(mediaTypeStr).getSchema(), mediaTypeStr);
				});
				apiResponse.content(existingContent);
			}
			else
				apiResponse.content(newContent);
		}
		else {
			apiResponse.content(existingContent);
		}
	}
	else {
		optionalContent.ifPresent(apiResponse::content);
	}
}
 
Example 4
Source File: SwaggerConverter.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#responseObject
 *
 * @return
 */


protected ApiResponse getSuccessApiResponse(Rpc rpc) {
    ApiResponse apiResponse = new ApiResponse();

    apiResponse.content(getContent(rpc.responseType()));
    Type type = this.schmea.getType(rpc.responseType());
    apiResponse.description(type.documentation());
    return apiResponse;
}
 
Example 5
Source File: SchemaGenerator.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
private static void resolveAPIResponse(String status, Type resolvedType, ApiResponses responses, Path modelsDir) {
    final Schema<?> responseSchema = processType(resolvedType, modelsDir);
    final ApiResponse response = new ApiResponse();
    final Content content = new Content();
    final MediaType mediaType = new MediaType();
    mediaType.schema(responseSchema);
    content.addMediaType("application/json", mediaType);
    response.content(content);
    response.description("Some random thing");
    responses.addApiResponse(status, response);
}
 
Example 6
Source File: SwaggerConverter.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
public ApiResponse convert(io.swagger.models.Response v2Response, List<String> produces) {
    ApiResponse response = new ApiResponse();
    Content content = new Content();

    if (v2Response instanceof RefResponse) {

        RefResponse ref = (RefResponse) v2Response;
        if (ref.get$ref().indexOf("#/responses") == 0) {
            String updatedRef = "#/components/responses" + ref.get$ref().substring("#/responses".length());
            ref.set$ref(updatedRef);
        }

        response.set$ref(ref.get$ref());
    } else {

        List<String> mediaTypes = new ArrayList<>(globalProduces);
        if (produces != null) {
            // use this for media type
            mediaTypes.clear();
            mediaTypes.addAll(produces);
        }

        if (mediaTypes.size() == 0) {
            mediaTypes.add("*/*");
        }

        response.setDescription(v2Response.getDescription());

        if (v2Response.getSchema() != null) {
            Schema schema = convertFileSchema(convert(v2Response.getSchema()));
            for (String type : mediaTypes) {
                // TODO: examples
                MediaType mediaType = new MediaType();
                content.addMediaType(type, mediaType.schema(schema));
            }
            response.content(content);
        }

        response.content(convertExamples(v2Response.getExamples(), content));
        response.setExtensions(convert(v2Response.getVendorExtensions()));

        if (v2Response.getHeaders() != null && v2Response.getHeaders().size() > 0) {
            response.setHeaders(convertHeaders(v2Response.getHeaders()));
        }
    }

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

    ObjectSchema items = new ObjectSchema();
    items.addExtension("x-ext", "ext-items");
    items.addProperties("name", new StringSchema());


    ArraySchema schema = new ArraySchema()
            .items(items);
    schema.addExtension("x-ext", "ext-prop");

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

    openAPI.path("/foo/baz", new PathItem()
            .get(new Operation()
                    .responses(new ApiResponses().addApiResponse("200",response))));

    new InlineModelResolver().flatten(openAPI);

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

    assertNotNull(apiResponse.getContent().get("*/*").getSchema());
    Schema responseProperty = apiResponse.getContent().get("*/*").getSchema();

    // no need to flatten more
    assertTrue(responseProperty instanceof ArraySchema);

    ArraySchema ap = (ArraySchema) responseProperty;
    assertEquals(1, ap.getExtensions().size());
    assertEquals("ext-prop", ap.getExtensions().get("x-ext"));

    Schema p = ap.getItems();

    assertNotNull(p);

    assertEquals("#/components/schemas/inline_response_200", p.get$ref());

    assertEquals(1, p.getExtensions().size());
    assertEquals("ext-items", p.getExtensions().get("x-ext"));

    Schema inline = openAPI.getComponents().getSchemas().get("inline_response_200");
    assertNotNull(inline);
    assertTrue(inline instanceof Schema);

    assertNotNull(inline.getProperties().get("name"));
    assertTrue(inline.getProperties().get("name") instanceof StringSchema);
}
 
Example 8
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void resolveInlineArrayResponseWithTitle() throws Exception {
    OpenAPI openAPI = new OpenAPI();

    ApiResponse apiResponse  = new ApiResponse();
    apiResponse.addExtension("x-foo", "bar");
    apiResponse.description("it works!");

    Map<String,Schema> properties = new HashMap<>();
    properties.put("name", new StringSchema());

    apiResponse.content(new Content().addMediaType("*/*", new MediaType().schema(new ArraySchema()
                    .items(new ObjectSchema()
                            .title("FooBar")
                            .properties(properties)))));

    openAPI.path("/foo/baz", new PathItem()
            .get(new Operation()
                    .responses(new ApiResponses().addApiResponse("200",apiResponse))));

    new InlineModelResolver().flatten(openAPI);

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

    assertNotNull(response.getContent().get("*/*").getSchema());
    Schema responseProperty = response.getContent().get("*/*").getSchema();

    // no need to flatten more
    assertTrue(responseProperty instanceof ArraySchema);

    ArraySchema ap = (ArraySchema) responseProperty;
    Schema p = ap.getItems();

    assertNotNull(p);

    assertEquals(p.get$ref(), "#/components/schemas/"+ "FooBar");


    Schema inline = openAPI.getComponents().getSchemas().get("FooBar");
    assertNotNull(inline);
    assertTrue(inline instanceof Schema);
    assertNotNull(inline.getProperties().get("name"));
    assertTrue(inline.getProperties().get("name") instanceof StringSchema);
}
 
Example 9
Source File: ResponseProcessorTest.java    From swagger-parser with Apache License 2.0 3 votes vote down vote up
@Test
public void testProcessResponse(@Injectable final Schema responseSchema,
                                @Injectable final Header responseHeader) throws Exception {

    new StrictExpectations(){{
        new SchemaProcessor(cache, swagger);
        times=1;
        result = propertyProcessor;

        new HeaderProcessor(cache,swagger);
        times = 1;
        result = headerProcessor;

        new LinkProcessor(cache,swagger);
        times = 1;
        result = linkProcessor;


        propertyProcessor.processSchema(responseSchema);
        times=1;

        headerProcessor.processHeader(responseHeader);
        times = 1;


    }};

    ApiResponse response = new ApiResponse();
    response.content(new Content().addMediaType("*/*", new MediaType().schema(responseSchema)));
    response.addHeaderObject("foo", responseHeader);

    new ResponseProcessor(cache, swagger).processResponse(response);


    new FullVerifications(){{}};
}