Java Code Examples for io.swagger.v3.oas.models.Operation#setResponses()

The following examples show how to use io.swagger.v3.oas.models.Operation#setResponses() . 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: OperationsTransformer.java    From spring-openapi with MIT License 6 votes vote down vote up
private void mapRequestMapping(RequestMapping requestMapping, Method method, Map<String, PathItem> operationsMap, String controllerClassName,
							   String baseControllerPath) {
	Operation operation = new Operation();
	operation.setOperationId(getOperationId(requestMapping.name(), method, getSpringMethod(requestMapping.method())));
	operation.setSummary(StringUtils.isBlank(requestMapping.name()) ? requestMapping.name() : method.getName());
	operation.setTags(singletonList(classNameToTag(controllerClassName)));

	if (isHttpMethodWithRequestBody(requestMapping.method())) {
		operation.setRequestBody(createRequestBody(method, getFirstFromArray(requestMapping.consumes())));
	}
	operation.setParameters(transformParameters(method));
	operation.setResponses(createApiResponses(method, getFirstFromArray(requestMapping.produces())));

	operationInterceptors.forEach(interceptor -> interceptor.intercept(method, operation));

	String path = ObjectUtils.defaultIfNull(getFirstFromArray(requestMapping.value()), getFirstFromArray(requestMapping.path()));
	updateOperationsMap(prepareUrl(baseControllerPath, "/", path), operationsMap,
			pathItem -> setContentBasedOnHttpMethod(pathItem, requestMapping.method(), operation)
	);
}
 
Example 2
Source File: OperationsTransformer.java    From spring-openapi with MIT License 5 votes vote down vote up
private void mapDelete(DeleteMapping deleteMapping, Method method, Map<String, PathItem> operationsMap, String controllerClassName,
					   String baseControllerPath) {
	Operation operation = new Operation();
	operation.setOperationId(getOperationId(deleteMapping.name(), method, HttpMethod.DELETE));
	operation.setSummary(StringUtils.isBlank(deleteMapping.name()) ? deleteMapping.name() : method.getName());
	operation.setTags(singletonList(classNameToTag(controllerClassName)));

	operation.setParameters(transformParameters(method));
	operation.setResponses(createApiResponses(method, getFirstFromArray(deleteMapping.produces())));
	String path = ObjectUtils.defaultIfNull(getFirstFromArray(deleteMapping.value()), getFirstFromArray(deleteMapping.path()));

	operationInterceptors.forEach(interceptor -> interceptor.intercept(method, operation));
	updateOperationsMap(prepareUrl(baseControllerPath, "/", path), operationsMap, pathItem -> pathItem.setDelete(operation));
}
 
Example 3
Source File: OperationsTransformer.java    From spring-openapi with MIT License 5 votes vote down vote up
private void mapGet(GetMapping getMapping, Method method, Map<String, PathItem> operationsMap, String controllerClassName, String baseControllerPath) {
	Operation operation = new Operation();
	operation.setOperationId(getOperationId(getMapping.name(), method, HttpMethod.GET));
	operation.setSummary(StringUtils.isBlank(getMapping.name()) ? getMapping.name() : method.getName());
	operation.setTags(singletonList(classNameToTag(controllerClassName)));

	operation.setParameters(transformParameters(method));
	operation.setResponses(createApiResponses(method, getFirstFromArray(getMapping.produces())));

	String path = ObjectUtils.defaultIfNull(getFirstFromArray(getMapping.value()), getFirstFromArray(getMapping.path()));

	operationInterceptors.forEach(interceptor -> interceptor.intercept(method, operation));
	updateOperationsMap(prepareUrl(baseControllerPath, "/", path), operationsMap, pathItem -> pathItem.setGet(operation));
}
 
Example 4
Source File: OperationsTransformer.java    From spring-openapi with MIT License 5 votes vote down vote up
private void mapPatch(PatchMapping patchMapping, Method method, Map<String, PathItem> operationsMap, String controllerClassName, String baseControllerPath) {
	Operation operation = new Operation();
	operation.setOperationId(getOperationId(patchMapping.name(), method, HttpMethod.PATCH));
	operation.setSummary(StringUtils.isBlank(patchMapping.name()) ? patchMapping.name() : method.getName());
	operation.setTags(singletonList(classNameToTag(controllerClassName)));

	operation.setRequestBody(createRequestBody(method, getFirstFromArray(patchMapping.consumes())));
	operation.setResponses(createApiResponses(method, getFirstFromArray(patchMapping.produces())));
	operation.setParameters(transformParameters(method));

	String path = ObjectUtils.defaultIfNull(getFirstFromArray(patchMapping.value()), getFirstFromArray(patchMapping.path()));

	operationInterceptors.forEach(interceptor -> interceptor.intercept(method, operation));
	updateOperationsMap(prepareUrl(baseControllerPath, "/", path), operationsMap, pathItem -> pathItem.setPatch(operation));
}
 
Example 5
Source File: OperationsTransformer.java    From spring-openapi with MIT License 5 votes vote down vote up
private void mapPut(PutMapping putMapping, Method method, Map<String, PathItem> operationsMap, String controllerClassName, String baseControllerPath) {
	Operation operation = new Operation();
	operation.setOperationId(getOperationId(putMapping.name(), method, HttpMethod.PUT));
	operation.setSummary(StringUtils.isBlank(putMapping.name()) ? putMapping.name() : method.getName());
	operation.setTags(singletonList(classNameToTag(controllerClassName)));

	operation.setRequestBody(createRequestBody(method, getFirstFromArray(putMapping.consumes())));
	operation.setResponses(createApiResponses(method, getFirstFromArray(putMapping.produces())));
	operation.setParameters(transformParameters(method));

	String path = ObjectUtils.defaultIfNull(getFirstFromArray(putMapping.value()), getFirstFromArray(putMapping.path()));

	operationInterceptors.forEach(interceptor -> interceptor.intercept(method, operation));
	updateOperationsMap(prepareUrl(baseControllerPath, "/", path), operationsMap, pathItem -> pathItem.setPut(operation));
}
 
Example 6
Source File: OperationsTransformer.java    From spring-openapi with MIT License 5 votes vote down vote up
private void mapPost(PostMapping postMapping, Method method, Map<String, PathItem> operationsMap, String controllerClassName, String baseControllerPath) {
	Operation operation = new Operation();
	operation.setOperationId(getOperationId(postMapping.name(), method, HttpMethod.POST));
	operation.setSummary(StringUtils.isBlank(postMapping.name()) ? postMapping.name() : method.getName());
	operation.setTags(singletonList(classNameToTag(controllerClassName)));

	operation.setRequestBody(createRequestBody(method, getFirstFromArray(postMapping.consumes())));
	operation.setResponses(createApiResponses(method, getFirstFromArray(postMapping.produces())));
	operation.setParameters(transformParameters(method));

	String path = ObjectUtils.defaultIfNull(getFirstFromArray(postMapping.value()), getFirstFromArray(postMapping.path()));

	operationInterceptors.forEach(interceptor -> interceptor.intercept(method, operation));
	updateOperationsMap(prepareUrl(baseControllerPath, "/", path), operationsMap, pathItem -> pathItem.setPost(operation));
}
 
Example 7
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 8
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 9
Source File: ProtoOpenAPI.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
/**
 * Add openAPI path item to the the openAPI object.
 *
 * @param path            name of the pathItem
 * @param scopes          array of operation scopes
 * @param throttlingTier throttling tier
 */
void addOpenAPIPath(String path, String[] scopes, String throttlingTier) {
    PathItem pathItem = new PathItem();
    Operation operation = new Operation();
    operation.setOperationId(UUID.randomUUID().toString());
    addOauth2SecurityRequirement(operation, scopes);
    if (StringUtils.isNotEmpty(throttlingTier)) {
        operation.addExtension(OpenAPIConstants.THROTTLING_TIER, throttlingTier);
    }
    //needs to add the basic Auth Requirement to the operation level because if scopes are mentioned,
    // there would be oauth2 security requirement in method level.
    if (isBasicAuthEnabled) {
        addBasicAuthSecurityRequirement(operation);
    }
    if (isAPIKeyEnabled) {
        addAPIKeySecurityRequirement(operation);
    }
    //For each path, the only available http method is "post" according to the grpc mapping.
    pathItem.setPost(operation);
    if (openAPI.getPaths() == null) {
        openAPI.setPaths(new Paths());
    }
    //as Responses object is mandatory
    ApiResponse apiResponse = new ApiResponse();
    apiResponse.setDescription(ProtoToOpenAPIConstants.RESPONSE_DESCRIPTION);
    ApiResponses apiResponses = new ApiResponses();
    apiResponses.addApiResponse(ProtoToOpenAPIConstants.SUCCESS_RESPONSE_CODE, apiResponse);
    operation.setResponses(apiResponses);
    //append forward slash to preserve openAPI syntax
    openAPI.getPaths().addPathItem(ProtoToOpenAPIConstants.PATH_SEPARATOR + path, pathItem);
}
 
Example 10
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private Map<String, PathItem> createPathItems(String endpointName,
        ClassOrInterfaceDeclaration typeDeclaration) {
    Map<String, PathItem> newPathItems = new HashMap<>();
    for (MethodDeclaration methodDeclaration : typeDeclaration
            .getMethods()) {
        if (isAccessForbidden(typeDeclaration, methodDeclaration)) {
            continue;
        }
        String methodName = methodDeclaration.getNameAsString();

        Operation post = createPostOperation(methodDeclaration);
        if (methodDeclaration.getParameters().isNonEmpty()) {
            post.setRequestBody(createRequestBody(methodDeclaration));
        }

        ApiResponses responses = createApiResponses(methodDeclaration);
        post.setResponses(responses);
        post.tags(Collections
                .singletonList(typeDeclaration.getNameAsString()));
        PathItem pathItem = new PathItem().post(post);

        String pathName = "/" + endpointName + "/" + methodName;
        pathItem.readOperationsMap()
                .forEach((httpMethod, operation) -> operation
                        .setOperationId(String.join("_", endpointName,
                                methodName, httpMethod.name())));
        newPathItems.put(pathName, pathItem);
    }
    return newPathItems;
}
 
Example 11
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new operation object using the URI template object
 *
 * @param resource API resource data
 * @return a new operation object using the URI template object
 */
private Operation createOperation(SwaggerData.Resource resource) {
    Operation operation = new Operation();
    populatePathParameters(operation, resource.getPath());
    updateOperationManagedInfo(resource, operation);

    ApiResponses apiResponses = new ApiResponses();
    ApiResponse apiResponse = new ApiResponse();
    apiResponse.description("OK");
    apiResponses.addApiResponse(APIConstants.SWAGGER_RESPONSE_200, apiResponse);
    operation.setResponses(apiResponses);
    return operation;
}
 
Example 12
Source File: AbstractOpenApiResource.java    From springdoc-openapi with Apache License 2.0 4 votes vote down vote up
/**
 * Calculate path.
 *
 * @param handlerMethod the handler method
 * @param routerOperation the router operation
 */
protected void calculatePath(HandlerMethod handlerMethod, RouterOperation routerOperation) {
	String operationPath = routerOperation.getPath();
	Set<RequestMethod> requestMethods = new HashSet<>(Arrays.asList(routerOperation.getMethods()));
	io.swagger.v3.oas.annotations.Operation apiOperation = routerOperation.getOperation();
	String[] methodConsumes = routerOperation.getConsumes();
	String[] methodProduces = routerOperation.getProduces();
	String[] headers = routerOperation.getHeaders();
	Map<String, String> queryParams = routerOperation.getQueryParams();

	OpenAPI openAPI = openAPIBuilder.getCalculatedOpenAPI();
	Components components = openAPI.getComponents();
	Paths paths = openAPI.getPaths();

	Map<HttpMethod, Operation> operationMap = null;
	if (paths.containsKey(operationPath)) {
		PathItem pathItem = paths.get(operationPath);
		operationMap = pathItem.readOperationsMap();
	}

	for (RequestMethod requestMethod : requestMethods) {
		Operation existingOperation = getExistingOperation(operationMap, requestMethod);
		Method method = handlerMethod.getMethod();
		// skip hidden operations
		if (operationParser.isHidden(method))
			continue;

		RequestMapping reqMappingClass = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getBeanType(),
				RequestMapping.class);

		MethodAttributes methodAttributes = new MethodAttributes(springDocConfigProperties.getDefaultConsumesMediaType(), springDocConfigProperties.getDefaultProducesMediaType(), methodConsumes, methodProduces, headers);
		methodAttributes.setMethodOverloaded(existingOperation != null);

		if (reqMappingClass != null) {
			methodAttributes.setClassConsumes(reqMappingClass.consumes());
			methodAttributes.setClassProduces(reqMappingClass.produces());
		}

		methodAttributes.calculateConsumesProduces(method);

		Operation operation = (existingOperation != null) ? existingOperation : new Operation();

		if (isDeprecated(method))
			operation.setDeprecated(true);

		// Add documentation from operation annotation
		if (apiOperation == null || StringUtils.isBlank(apiOperation.operationId()))
			apiOperation = AnnotatedElementUtils.findMergedAnnotation(method,
					io.swagger.v3.oas.annotations.Operation.class);

		calculateJsonView(apiOperation, methodAttributes, method);
		if (apiOperation != null)
			openAPI = operationParser.parse(apiOperation, operation, openAPI, methodAttributes);
		fillParametersList(operation, queryParams, methodAttributes);

		// compute tags
		operation = openAPIBuilder.buildTags(handlerMethod, operation, openAPI);

		io.swagger.v3.oas.annotations.parameters.RequestBody requestBodyDoc = AnnotatedElementUtils.findMergedAnnotation(method,
				io.swagger.v3.oas.annotations.parameters.RequestBody.class);

		// RequestBody in Operation
		requestBuilder.getRequestBodyBuilder()
				.buildRequestBodyFromDoc(requestBodyDoc, methodAttributes, components,
						methodAttributes.getJsonViewAnnotationForRequestBody())
				.ifPresent(operation::setRequestBody);
		// requests
		operation = requestBuilder.build(handlerMethod, requestMethod, operation, methodAttributes, openAPI);

		// responses
		ApiResponses apiResponses = responseBuilder.build(components, handlerMethod, operation, methodAttributes);
		operation.setResponses(apiResponses);

		Set<io.swagger.v3.oas.annotations.callbacks.Callback> apiCallbacks = AnnotatedElementUtils.findMergedRepeatableAnnotations(method, io.swagger.v3.oas.annotations.callbacks.Callback.class);

		// callbacks
		buildCallbacks(openAPI, methodAttributes, operation, apiCallbacks);

		// allow for customisation
		customiseOperation(operation, handlerMethod);

		PathItem pathItemObject = buildPathItem(requestMethod, operation, operationPath, paths);
		paths.addPathItem(operationPath, pathItemObject);
	}
}
 
Example 13
Source File: OASMergeUtil.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
public static Operation mergeOperations(Operation thisOperation, Operation thatOperation) {
  if (thatOperation == null) {
    return thisOperation;
  }

  if (thatOperation.getTags() != null) {
    thisOperation.setTags(
        mergeTags(thisOperation.getTags(), thatOperation.getTags())
    );
  }
  if (thatOperation.getExternalDocs() != null) {
    thisOperation.setExternalDocs(
      mergeExternalDocumentation(thisOperation.getExternalDocs(), thatOperation.getExternalDocs())
    );
  }
  if (thatOperation.getParameters() != null) {
    thisOperation.setParameters(
        mergeParameters(thisOperation.getParameters(), thatOperation.getParameters())
    );
  }
  if (thatOperation.getRequestBody() != null) {
    thisOperation.setRequestBody(thatOperation.getRequestBody());
  }
  if (thatOperation.getResponses() != null) {
    thisOperation.setResponses(thatOperation.getResponses());
  }
  if (thatOperation.getCallbacks() != null) {
    thisOperation.setCallbacks(thatOperation.getCallbacks());
  }
  if (thatOperation.getDeprecated() != null) {
    thisOperation.setDeprecated(thatOperation.getDeprecated());
  }
  if (thatOperation.getSecurity() != null) {
    thisOperation.setSecurity(thatOperation.getSecurity());
  }
  if (thatOperation.getServers() != null) {
    thisOperation.setServers(thatOperation.getServers());
  }
  if (thatOperation.getExtensions() != null) {
    thisOperation.setExtensions(thatOperation.getExtensions());
  }
  if (thatOperation.getOperationId() != null) {
    thisOperation.setOperationId(thatOperation.getOperationId());
  }
  if (thatOperation.getSummary() != null) {
    thisOperation.setSummary(thatOperation.getSummary());
  }
  if (thatOperation.getDescription() != null) {
    thisOperation.setDescription(thatOperation.getDescription());
  }
  if (thatOperation.getExtensions() != null) {
    thisOperation.setExtensions(thatOperation.getExtensions());
  }
  return thisOperation;
}
 
Example 14
Source File: OpenAPIDeserializer.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
public Operation getOperation(ObjectNode obj, String location, ParseResult result) {
    if (obj == null) {
        return null;
    }
    Operation operation = new Operation();

    ArrayNode array = getArray("tags", obj, false, location, result);
    List<String> tags = getTagsStrings(array, String.format("%s.%s", location, "tags"), result);
    if (tags != null) {
        operation.setTags(tags);
    }
    String value = getString("summary", obj, false, location, result);
    if (StringUtils.isNotBlank(value)) {
        operation.setSummary(value);
    }

    value = getString("description", obj, false, location, result);
    if (StringUtils.isNotBlank(value)) {
        operation.setDescription(value);
    }

    ObjectNode externalDocs = getObject("externalDocs", obj, false, location, result);
    ExternalDocumentation docs = getExternalDocs(externalDocs, String.format("%s.%s", location, "externalDocs"), result);
    if(docs != null) {
        operation.setExternalDocs(docs);
    }
    value = getString("operationId", obj, false, location, result, operationIDs);
    if (StringUtils.isNotBlank(value)) {
        operation.operationId(value);
    }

    ArrayNode parameters = getArray("parameters", obj, false, location, result);
    if (parameters != null){
        operation.setParameters(getParameterList(parameters, String.format("%s.%s", location, "parameters"), result));
    }

    final ObjectNode requestObjectNode = getObject("requestBody", obj, false, location, result);
    if (requestObjectNode != null){
        operation.setRequestBody(getRequestBody(requestObjectNode, String.format("%s.%s", location, "requestBody"), result));
    }

    ObjectNode responsesNode = getObject("responses", obj, true, location, result);
    ApiResponses responses = getResponses(responsesNode, String.format("%s.%s", location, "responses"), result, false);
    if(responses != null) {
        operation.setResponses(responses);
    }

    ObjectNode callbacksNode = getObject("callbacks", obj, false, location, result);
    Map<String,Callback> callbacks = getCallbacks(callbacksNode, String.format("%s.%s", location, "callbacks"), result, false);
    if(callbacks != null){
        operation.setCallbacks(callbacks);
    }

    Boolean deprecated = getBoolean("deprecated", obj, false, location, result);
    if (deprecated != null) {
        operation.setDeprecated(deprecated);
    }

    array = getArray("servers", obj, false, location, result);
    if (array != null && array.size() > 0) {
        operation.setServers(getServersList(array, String.format("%s.%s", location, "servers"), result));
    }


    array = getArray("security", obj, false, location, result);
    if (array != null) {
        operation.setSecurity(getSecurityRequirementsList(array, String.format("%s.%s", location, "security"), result));
    }


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

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


    return operation;
}
 
Example 15
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 16
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);
}