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

The following examples show how to use io.swagger.v3.oas.models.responses.ApiResponse#getContent() . 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: PathsProcessor.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
protected void updateLocalRefs(ApiResponse response, String pathRef) {
    if (response.get$ref() != null){
        if(isLocalRef(response.get$ref())) {
            response.set$ref(computeLocalRef(response.get$ref(), pathRef));
        }
    }
    if(response.getContent() != null) {
        Map<String, MediaType> content = response.getContent();
        for (String key: content.keySet()) {
            MediaType mediaType = content.get(key);
            if (mediaType.getSchema() != null) {
                updateLocalRefs(mediaType.getSchema(), pathRef);
            }
            Map<String, Example> examples = content.get(key).getExamples();
            if (examples != null) {
                for( Example example:examples.values()){
                    updateLocalRefs(example, pathRef);
                }
            }
        }
    }
}
 
Example 2
Source File: ResourceInterfaceGenerator.java    From spring-openapi with MIT License 5 votes vote down vote up
private MethodSpec createMethod(OperationData operationData) {
	Operation operation = operationData.getOperation();
	MethodSpec.Builder methodSpecBuilder = MethodSpec.methodBuilder(getMethodName(operation))
			.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT);
	if (operation.getDescription() != null) {
		methodSpecBuilder.addJavadoc(operation.getDescription());
	}
	if (operation.getParameters() != null) {
		operation.getParameters()
				.forEach(parameter -> methodSpecBuilder.addParameter(
						parseProperties(formatParameterName(parameter.getName()), parameter.getSchema()).build()
				));
	}
	if (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null) {
		LinkedHashMap<String, MediaType> mediaTypes = operation.getRequestBody().getContent();
		methodSpecBuilder.addParameter(parseProperties("requestBody", mediaTypes.entrySet().iterator().next().getValue().getSchema()).build());
	}
	if (operation.getResponses() == null || CollectionUtils.isEmpty(operation.getResponses().entrySet())) {
		methodSpecBuilder.returns(TypeName.VOID);
	} else {
		ApiResponse apiResponse = operation.getResponses().entrySet().stream()
				.filter(responseEntry -> StringUtils.startsWith(responseEntry.getKey(), "2")) // HTTP 20x
				.findFirst()
				.map(Map.Entry::getValue)
				.orElse(null);
		if (apiResponse != null && apiResponse.getContent() != null && !apiResponse.getContent().isEmpty()) {
			MediaType mediaType = apiResponse.getContent().entrySet().iterator().next().getValue();
			if (mediaType.getSchema() != null) {
				methodSpecBuilder.returns(determineTypeName(mediaType.getSchema()));
				return methodSpecBuilder.build();
			}
		}
		methodSpecBuilder.returns(TypeName.VOID);
	}

	return methodSpecBuilder.build();
}
 
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: ResourceReferenceResponseTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
void response() {
  ApiResponse apiResponse = new ResourceReferenceResponse(metaResource).response();
  Assert.assertNotNull(apiResponse);
  Assert.assertEquals("OK", apiResponse.getDescription());
  Content content = apiResponse.getContent();
  Assert.assertEquals(1, content.size());
  Schema schema = content.get("application/vnd.api+json").getSchema();
  Assert.assertEquals(
      "#/components/schemas/ResourceTypeResourceReferenceResponseSchema",
      schema.get$ref()
  );
}
 
Example 5
Source File: ResourceResponseTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
void response() {
  ApiResponse apiResponse = new ResourceResponse(metaResource).response();
  Assert.assertNotNull(apiResponse);
  Assert.assertEquals("OK", apiResponse.getDescription());
  Content content = apiResponse.getContent();
  Assert.assertEquals(1, content.size());
  Schema schema = content.get("application/vnd.api+json").getSchema();
  Assert.assertEquals(
      "#/components/schemas/ResourceTypeResourceResponseSchema",
      schema.get$ref()
  );
}
 
Example 6
Source File: ResourcesResponseTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
void response() {
  ApiResponse apiResponse = new ResourcesResponse(metaResource).response();
  Assert.assertNotNull(apiResponse);
  Assert.assertEquals("OK", apiResponse.getDescription());
  Content content = apiResponse.getContent();
  Assert.assertEquals(1, content.size());
  Schema schema = content.get("application/vnd.api+json").getSchema();
  Assert.assertEquals(
      "#/components/schemas/ResourceTypeResourcesResponseSchema",
      schema.get$ref()
  );
}
 
Example 7
Source File: ResourceReferencesResponseTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
void response() {
  ApiResponse apiResponse = new ResourceReferencesResponse(metaResource).response();
  Assert.assertNotNull(apiResponse);
  Assert.assertEquals("OK", apiResponse.getDescription());
  Content content = apiResponse.getContent();
  Assert.assertEquals(1, content.size());
  Schema schema = content.get("application/vnd.api+json").getSchema();
  Assert.assertEquals(
      "#/components/schemas/ResourceTypeResourceReferencesResponseSchema",
      schema.get$ref()
  );
}
 
Example 8
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static void setRefOfApiResponses(ApiResponses responses, SwaggerUpdateContext context) {
    if (responses != null) {
        for (ApiResponse response : responses.values()) {
            Content content = response.getContent();

            extractReferenceFromContent(content, context);
        }
    }
}
 
Example 9
Source File: ResponseContentValidator.java    From servicecomb-toolkit with Apache License 2.0 4 votes vote down vote up
@Override
protected Map<String, MediaType> getMapProperty(ApiResponse oasObject) {
  return oasObject.getContent();
}
 
Example 10
Source File: ResponseContentDiffValidator.java    From servicecomb-toolkit with Apache License 2.0 4 votes vote down vote up
@Override
protected Map<String, MediaType> getMapProperty(ApiResponse oasObject) {
  return oasObject.getContent();
}
 
Example 11
Source File: ExternalRefProcessor.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
public String processRefToExternalResponse(String $ref, RefFormat refFormat) {
    String renamedRef = cache.getRenamedRef($ref);
    if(renamedRef != null) {
        return renamedRef;
    }
    final ApiResponse response = cache.loadRef($ref, refFormat, ApiResponse.class);

    String newRef;

    if (openAPI.getComponents() == null) {
        openAPI.setComponents(new Components());
    }
    Map<String, ApiResponse> responses = openAPI.getComponents().getResponses();

    if (responses == null) {
        responses = new LinkedHashMap<>();
    }

    final String possiblyConflictingDefinitionName = computeDefinitionName($ref);

    ApiResponse existingResponse = responses.get(possiblyConflictingDefinitionName);

    if (existingResponse != null) {
        LOGGER.debug("A model for " + existingResponse + " already exists");
        if(existingResponse.get$ref() != null) {
            // use the new model
            existingResponse = null;
        }
    }
    newRef = possiblyConflictingDefinitionName;
    cache.putRenamedRef($ref, newRef);

    if(response != null) {
        if(response.getContent() != null){
            processRefContent(response.getContent(), $ref);
        }
        if(response.getHeaders() != null){
            processRefHeaders(response.getHeaders(), $ref);
        }
        if(response.getLinks() != null){
            processRefLinks(response.getLinks(), $ref);
        }
    }

    return newRef;
}
 
Example 12
Source File: ResponseProcessor.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
public void processResponse(ApiResponse response) {

        if (response.get$ref() != null){
            processReferenceResponse(response);
        }

        Schema schema = null;
        if(response.getContent() != null){
            Map<String,MediaType> content = response.getContent();
            for( String mediaName : content.keySet()) {
                MediaType mediaType = content.get(mediaName);
                if(mediaType.getSchema()!= null) {
                    schema = mediaType.getSchema();
                    if (schema != null) {
                        schemaProcessor.processSchema(schema);
                    }
                }
                if(mediaType.getExamples() != null) {
                    for(Example ex: mediaType.getExamples().values()){
                        exampleProcessor.processExample(ex);
                    }
                }
            }
        }
        if (response.getHeaders() != null){
            Map<String,Header> headers = response.getHeaders();
            for(String headerName : headers.keySet()){
                Header header = headers.get(headerName);
                headerProcessor.processHeader(header);
            }


        }
        if (response.getLinks() != null){
            Map<String,Link> links = response.getLinks();
            for(String linkName : links.keySet()){
                Link link = links.get(linkName);
                linkProcessor.processLink(link);
            }
        }
    }
 
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: OperationBuilder.java    From springdoc-openapi with Apache License 2.0 2 votes vote down vote up
/**
 * Is response object boolean.
 *
 * @param apiResponseObject the api response object
 * @return the boolean
 */
private boolean isResponseObject(ApiResponse apiResponseObject) {
	return StringUtils.isNotBlank(apiResponseObject.getDescription()) || apiResponseObject.getContent() != null
			|| apiResponseObject.getHeaders() != null;
}