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

The following examples show how to use io.swagger.v3.oas.models.responses.ApiResponse#setContent() . 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: OperationContext.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
private void processProduces() {

    if (getProduces() == null) {
      return;
    }

    List<String> produceList = Arrays.stream(produces).filter(s -> !StringUtils.isEmpty(s))
        .collect(Collectors.toList());

    if (!produceList.isEmpty()) {
      ApiResponse apiResponse = new ApiResponse();
      Content content = new Content();
      MediaType mediaType = new MediaType();
      Schema schema = ModelConverter
          .getSchema(getMethod().getReturnType(), getComponents(), RequestResponse.RESPONSE);
      mediaType.schema(schema);
      for (String produce : produceList) {
        content.addMediaType(produce, mediaType);
      }
      apiResponse.description("OK");
      apiResponse.setContent(content);
      addResponse(HttpStatuses.OK, apiResponse);
    }
  }
 
Example 2
Source File: OperationContext.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
public void correctResponse(ApiResponses apiResponses) {

    if (apiResponses == null) {
      return;
    }

    // no annotations are processed
    // generate a default response based on the method return value
    if (apiResponses.get(HttpStatuses.OK) == null) {
      ApiResponse apiResponse = new ApiResponse();

      Class<?> returnType = method.getReturnType();
      if (returnType == Void.TYPE || returnType == Void.class) {
        return;
      }

      MediaType mediaType = new MediaType();

      Schema refSchema = ModelConverter.getSchema(returnType, getComponents(), RequestResponse.RESPONSE);
      mediaType.schema(refSchema);

      Content content = new Content();
      content.addMediaType(MediaTypes.APPLICATION_JSON, mediaType);
      apiResponse.description("OK");
      apiResponse.setContent(content);
      apiResponses.addApiResponse(HttpStatuses.OK, apiResponse);
    }
  }
 
Example 3
Source File: GenericResponseBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Build api responses.
 *
 * @param components the components
 * @param methodParameter the method parameter
 * @param apiResponsesOp the api responses op
 * @param methodAttributes the method attributes
 * @param httpCode the http code
 * @param apiResponse the api response
 * @param isGeneric the is generic
 */
private void buildApiResponses(Components components, MethodParameter methodParameter, ApiResponses apiResponsesOp,
		MethodAttributes methodAttributes, String httpCode, ApiResponse apiResponse, boolean isGeneric) {
	// No documentation
	if (StringUtils.isBlank(apiResponse.get$ref())) {
		if (apiResponse.getContent() == null) {
			Content content = buildContent(components, methodParameter, methodAttributes.getMethodProduces(),
					methodAttributes.getJsonViewAnnotation());
			apiResponse.setContent(content);
		}
		else if (CollectionUtils.isEmpty(apiResponse.getContent()))
			apiResponse.setContent(null);
		if (StringUtils.isBlank(apiResponse.getDescription())) {
			setDescription(httpCode, apiResponse);
		}
	}
	if (apiResponse.getContent() != null
			&& ((isGeneric || methodAttributes.isMethodOverloaded()) && methodAttributes.isNoApiResponseDoc())) {
		// Merge with existing schema
		Content existingContent = apiResponse.getContent();
		Type type = ReturnTypeParser.getType(methodParameter);
		Schema<?> schemaN = calculateSchema(components, type,
				methodAttributes.getJsonViewAnnotation(), methodParameter.getParameterAnnotations());
		if (schemaN != null && ArrayUtils.isNotEmpty(methodAttributes.getMethodProduces()))
			Arrays.stream(methodAttributes.getMethodProduces()).forEach(mediaTypeStr -> mergeSchema(existingContent, schemaN, mediaTypeStr));
	}
	apiResponsesOp.addApiResponse(httpCode, apiResponse);
}
 
Example 4
Source File: DataRestResponseBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Build search response.
 *
 * @param operation the operation
 * @param handlerMethod the handler method
 * @param openAPI the open api
 * @param methodResourceMapping the method resource mapping
 * @param domainType the domain type
 * @param methodAttributes the method attributes
 */
public void buildSearchResponse(Operation operation, HandlerMethod handlerMethod, OpenAPI openAPI,
		MethodResourceMapping methodResourceMapping, Class<?> domainType, MethodAttributes methodAttributes) {
	MethodParameter methodParameterReturn = handlerMethod.getReturnType();
	ApiResponses apiResponses = new ApiResponses();
	ApiResponse apiResponse = new ApiResponse();
	Type returnType = findSearchReturnType(handlerMethod, methodResourceMapping, domainType);
	Content content = genericResponseBuilder.buildContent(openAPI.getComponents(), methodParameterReturn.getParameterAnnotations(), methodAttributes.getMethodProduces(), null, returnType);
	apiResponse.setContent(content);
	addResponse200(apiResponses, apiResponse);
	addResponse404(apiResponses);
	operation.setResponses(apiResponses);
}
 
Example 5
Source File: DataRestResponseBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Build entity response.
 *
 * @param operation the operation
 * @param handlerMethod the handler method
 * @param openAPI the open api
 * @param requestMethod the request method
 * @param operationPath the operation path
 * @param domainType the domain type
 * @param methodAttributes the method attributes
 */
public void buildEntityResponse(Operation operation, HandlerMethod handlerMethod, OpenAPI openAPI, RequestMethod requestMethod,
		String operationPath, Class<?> domainType, MethodAttributes methodAttributes) {
	MethodParameter methodParameterReturn = handlerMethod.getReturnType();
	Type returnType = ReturnTypeParser.resolveType(methodParameterReturn.getGenericParameterType(), methodParameterReturn.getContainingClass());
	returnType = getType(returnType, domainType);
	ApiResponses apiResponses = new ApiResponses();
	ApiResponse apiResponse = new ApiResponse();
	Content content = genericResponseBuilder.buildContent(openAPI.getComponents(), methodParameterReturn.getParameterAnnotations(), methodAttributes.getMethodProduces(), null, returnType);
	apiResponse.setContent(content);
	addResponse(requestMethod, operationPath, apiResponses, apiResponse);
	operation.setResponses(apiResponses);
}
 
Example 6
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 7
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testArrayResponse() {
    OpenAPI openAPI = new OpenAPI();


    ObjectSchema objectSchema = new ObjectSchema();
    objectSchema.addProperties("name", new StringSchema());
    ArraySchema schema = new ArraySchema();
    schema.setItems(objectSchema);

    ApiResponse apiResponse = new ApiResponse();
    apiResponse.addExtension("x-foo", "bar");
    apiResponse.setDescription("it works!");
    apiResponse.setContent(new Content().addMediaType("*/*", new MediaType().schema(schema)));

    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");
    assertTrue(response.getContent().get("*/*").getSchema() instanceof ArraySchema);

    ArraySchema am = (ArraySchema) response.getContent().get("*/*").getSchema();
    Schema items = am.getItems();
    assertTrue(items.get$ref() != null);

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


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

    assertNotNull(inline.getProperties().get("name"));
    assertTrue(inline.getProperties().get("name") instanceof StringSchema);
}
 
Example 8
Source File: OpenAPIDeserializer.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
public ApiResponse getResponse(ObjectNode node, String location, ParseResult result) {
    if (node == null) {
        return null;
    }

    ApiResponse apiResponse = new ApiResponse();
    JsonNode ref = node.get("$ref");
    if (ref != null) {
        if (ref.getNodeType().equals(JsonNodeType.STRING)) {
            String mungedRef = mungedRef(ref.textValue());
            if (mungedRef != null) {
                apiResponse.set$ref(mungedRef);
            }else{
                apiResponse.set$ref(ref.textValue());
            }
             return apiResponse;
        } else {
            result.invalidType(location, "$ref", "string", node);
            return null;
        }
    }

    String value = getString("description", node, true, location, result);
    if (StringUtils.isNotBlank(value)) {
        apiResponse.description(value);
    }


    ObjectNode headerObject = getObject("headers", node, false, location, result);
    if (headerObject != null) {
        Map<String, Header> headers = getHeaders(headerObject, location, result, false);
        if (headers != null &&  headers.size() > 0) {
            apiResponse.setHeaders(headers);
        }
    }

    ObjectNode linksObj = getObject("links", node, false, location, result);
    if (linksObj != null) {
         Map<String,Link> links = getLinks(linksObj, location, result, false);
         if(links != null && links.size() > 0) {
             apiResponse.setLinks(links);
         }
    }

    ObjectNode contentObject = getObject("content", node, false, location, result);
    if (contentObject != null) {
        apiResponse.setContent(getContent(contentObject, String.format("%s.%s", location, "content"), result));
    }

    Map <String,Object> extensions = getExtensions(node);
    if(extensions != null && extensions.size() > 0) {
        apiResponse.setExtensions(extensions);
    }

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


    return apiResponse;
}
 
Example 9
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 10
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);
}