Java Code Examples for io.swagger.v3.oas.models.Operation#getResponses()
The following examples show how to use
io.swagger.v3.oas.models.Operation#getResponses() .
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: CppRestSdkClientCodegen.java From openapi-generator with Apache License 2.0 | 6 votes |
@Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List<Server> servers) { CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { ApiResponse methodResponse = findMethodResponse(operation.getResponses()); if (methodResponse != null) { Schema response = ModelUtils.getSchemaFromResponse(methodResponse); response = ModelUtils.unaliasSchema(this.openAPI, response, importMapping); if (response != null) { CodegenProperty cm = fromProperty("response", response); op.vendorExtensions.put("x-codegen-response", cm); if ("std::shared_ptr<HttpContent>".equals(cm.dataType)) { op.vendorExtensions.put("x-codegen-response-ishttpcontent", true); } } } } return op; }
Example 2
Source File: OperationBuilder.java From springdoc-openapi with Apache License 2.0 | 6 votes |
/** * Merge operation operation. * * @param operation the operation * @param operationModel the operation model * @return the operation */ public Operation mergeOperation(Operation operation, Operation operationModel) { if (operationModel.getOperationId().length() < operation.getOperationId().length()) { operation.setOperationId(operationModel.getOperationId()); } ApiResponses apiResponses = operation.getResponses(); for (Entry<String, ApiResponse> apiResponseEntry : operationModel.getResponses().entrySet()) { if (apiResponses.containsKey(apiResponseEntry.getKey())) { Content existingContent = apiResponses.get(apiResponseEntry.getKey()).getContent(); Content newContent = apiResponseEntry.getValue().getContent(); if (newContent != null) newContent.forEach((mediaTypeStr, mediaType) -> SpringDocAnnotationsUtils.mergeSchema(existingContent, mediaType.getSchema(), mediaTypeStr)); } else apiResponses.addApiResponse(apiResponseEntry.getKey(), apiResponseEntry.getValue()); } return operation; }
Example 3
Source File: CppPistacheServerCodegen.java From openapi-generator with Apache License 2.0 | 6 votes |
@Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List<Server> servers) { CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { ApiResponse apiResponse = findMethodResponse(operation.getResponses()); if (apiResponse != null) { Schema response = ModelUtils.getSchemaFromResponse(apiResponse); if (response != null) { CodegenProperty cm = fromProperty("response", response); op.vendorExtensions.put("x-codegen-response", cm); if ("HttpContent".equals(cm.dataType)) { op.vendorExtensions.put("x-codegen-response-ishttpcontent", true); } } } } String pathForPistache = path.replaceAll("\\{(.*?)}", ":$1"); op.vendorExtensions.put("x-codegen-pistache-path", pathForPistache); return op; }
Example 4
Source File: OpenApiCustomizer.java From cxf with Apache License 2.0 | 5 votes |
/** * Allows to customize the responses of the given {@link Operation} instance; the method is invoked * for all instances available. * * @param operation operation instance * @param ori CXF data about the given operation instance */ protected void customizeResponses(final Operation operation, final OperationResourceInfo ori) { if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { ApiResponse response = operation.getResponses().entrySet().iterator().next().getValue(); if (StringUtils.isBlank(response.getDescription()) || (StringUtils.isNotBlank(javadocProvider.getMethodResponseDoc(ori)) && Reader.DEFAULT_DESCRIPTION.equals(response.getDescription()))) { response.setDescription(javadocProvider.getMethodResponseDoc(ori)); } } }
Example 5
Source File: OpenAPIGeneratorTestBase.java From crnk-framework with Apache License 2.0 | 5 votes |
private static void assertOperationResponseCodes(Operation operation, List<String> codes) { // Some operations will be null in cases where a JsonApiResource has postable, patchable, // readable, deleteable set to false. In that case, do not perform any response checks if(operation == null) { return; } ApiResponses responses = operation.getResponses(); for (String code : codes) { Assert.assertTrue("Operation missing response code " + code, responses.containsKey(code)); } }
Example 6
Source File: AbstractAdaCodegen.java From openapi-generator with Apache License 2.0 | 5 votes |
@Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List<Server> servers) { CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { ApiResponse methodResponse = findMethodResponse(operation.getResponses()); if (methodResponse != null && ModelUtils.getSchemaFromResponse(methodResponse) != null) { CodegenProperty cm = fromProperty("response", ModelUtils.getSchemaFromResponse(methodResponse)); op.vendorExtensions.put("x-codegen-response", cm); if ("HttpContent".equals(cm.dataType)) { op.vendorExtensions.put("x-codegen-response-ishttpcontent", true); } } } // Add a vendor extension attribute that provides a map of auth methods and the scopes // which are expected by the operation. This map is then used by postProcessOperationsWithModels // to build another vendor extension that provides a subset of the auth methods with only // the scopes required by the operation. final List<SecurityRequirement> securities = operation.getSecurity(); if (securities != null && securities.size() > 0) { final Map<String, SecurityScheme> securitySchemes = this.openAPI.getComponents() != null ? this.openAPI.getComponents().getSecuritySchemes() : null; final List<SecurityRequirement> globalSecurities = this.openAPI.getSecurity(); Map<String, List<String>> scopes = getAuthScopes(securities, securitySchemes); if (scopes.isEmpty() && globalSecurities != null) { scopes = getAuthScopes(globalSecurities, securitySchemes); } op.vendorExtensions.put("x-scopes", scopes); } return op; }
Example 7
Source File: GenericResponseBuilder.java From springdoc-openapi with Apache License 2.0 | 5 votes |
/** * Build api responses. * * @param components the components * @param handlerMethod the handler method * @param operation the operation * @param methodAttributes the method attributes * @return the api responses */ public ApiResponses build(Components components, HandlerMethod handlerMethod, Operation operation, MethodAttributes methodAttributes) { ApiResponses apiResponses = methodAttributes.calculateGenericMapResponse(getGenericMapResponse(handlerMethod.getBeanType())); //Then use the apiResponses from documentation ApiResponses apiResponsesFromDoc = operation.getResponses(); if (!CollectionUtils.isEmpty(apiResponsesFromDoc)) apiResponsesFromDoc.forEach(apiResponses::addApiResponse); // for each one build ApiResponse and add it to existing responses // Fill api Responses computeResponseFromDoc(components, handlerMethod.getReturnType(), apiResponses, methodAttributes); buildApiResponses(components, handlerMethod.getReturnType(), apiResponses, methodAttributes); return apiResponses; }
Example 8
Source File: OperationBuilder.java From springdoc-openapi with Apache License 2.0 | 5 votes |
/** * Gets api responses. * * @param responses the responses * @param methodAttributes the method attributes * @param operation the operation * @param components the components * @return the api responses */ private Optional<ApiResponses> getApiResponses( final io.swagger.v3.oas.annotations.responses.ApiResponse[] responses, MethodAttributes methodAttributes, Operation operation, Components components) { ApiResponses apiResponsesObject = new ApiResponses(); String[] classProduces = methodAttributes.getClassProduces(); String[] methodProduces = methodAttributes.getMethodProduces(); ApiResponses apiResponsesOp = operation.getResponses(); for (io.swagger.v3.oas.annotations.responses.ApiResponse response : responses) { ApiResponse apiResponseObject = new ApiResponse(); if (StringUtils.isNotBlank(response.ref())) { setRef(apiResponsesObject, response, apiResponseObject); continue; } setDescription(response, apiResponseObject); setExtensions(response, apiResponseObject); buildResponseContent(methodAttributes, components, classProduces, methodProduces, apiResponsesOp, response, apiResponseObject); AnnotationsUtils.getHeaders(response.headers(), null).ifPresent(apiResponseObject::headers); // Make schema as string if empty calculateHeader(apiResponseObject); if (isResponseObject(apiResponseObject)) { setLinks(response, apiResponseObject); if (StringUtils.isNotBlank(response.responseCode())) { apiResponsesObject.addApiResponse(response.responseCode(), apiResponseObject); } else { apiResponsesObject._default(apiResponseObject); } } } return Optional.of(apiResponsesObject); }
Example 9
Source File: ResourceInterfaceGenerator.java From spring-openapi with MIT License | 5 votes |
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 10
Source File: ModelUtils.java From openapi-generator with Apache License 2.0 | 4 votes |
private static void visitPathItem(PathItem pathItem, OpenAPI openAPI, OpenAPISchemaVisitor visitor, List<String> visitedSchemas) { List<Operation> allOperations = pathItem.readOperations(); if (allOperations != null) { for (Operation operation : allOperations) { //Params: visitParameters(openAPI, operation.getParameters(), visitor, visitedSchemas); //RequestBody: RequestBody requestBody = getReferencedRequestBody(openAPI, operation.getRequestBody()); if (requestBody != null) { visitContent(openAPI, requestBody.getContent(), visitor, visitedSchemas); } //Responses: if (operation.getResponses() != null) { for (ApiResponse r : operation.getResponses().values()) { ApiResponse apiResponse = getReferencedApiResponse(openAPI, r); if (apiResponse != null) { visitContent(openAPI, apiResponse.getContent(), visitor, visitedSchemas); if (apiResponse.getHeaders() != null) { for (Entry<String, Header> e : apiResponse.getHeaders().entrySet()) { Header header = getReferencedHeader(openAPI, e.getValue()); if (header.getSchema() != null) { visitSchema(openAPI, header.getSchema(), e.getKey(), visitedSchemas, visitor); } visitContent(openAPI, header.getContent(), visitor, visitedSchemas); } } } } } //Callbacks: if (operation.getCallbacks() != null) { for (Callback c : operation.getCallbacks().values()) { Callback callback = getReferencedCallback(openAPI, c); if (callback != null) { for (PathItem p : callback.values()) { visitPathItem(p, openAPI, visitor, visitedSchemas); } } } } } } //Params: visitParameters(openAPI, pathItem.getParameters(), visitor, visitedSchemas); }
Example 11
Source File: OASMergeUtil.java From crnk-framework with Apache License 2.0 | 4 votes |
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 12
Source File: OperationResponsesDiffValidator.java From servicecomb-toolkit with Apache License 2.0 | 4 votes |
@Override protected ApiResponses getPropertyObject(Operation oasObject) { return oasObject.getResponses(); }
Example 13
Source File: OperationDiff.java From openapi-diff with Apache License 2.0 | 4 votes |
public Optional<ChangedOperation> diff( Operation oldOperation, Operation newOperation, DiffContext context) { ChangedOperation changedOperation = new ChangedOperation(context.getUrl(), context.getMethod(), oldOperation, newOperation); openApiDiff .getMetadataDiff() .diff(oldOperation.getSummary(), newOperation.getSummary(), context) .ifPresent(changedOperation::setSummary); openApiDiff .getMetadataDiff() .diff(oldOperation.getDescription(), newOperation.getDescription(), context) .ifPresent(changedOperation::setDescription); changedOperation.setDeprecated( !Boolean.TRUE.equals(oldOperation.getDeprecated()) && Boolean.TRUE.equals(newOperation.getDeprecated())); if (oldOperation.getRequestBody() != null || newOperation.getRequestBody() != null) { openApiDiff .getRequestBodyDiff() .diff( oldOperation.getRequestBody(), newOperation.getRequestBody(), context.copyAsRequest()) .ifPresent(changedOperation::setRequestBody); } openApiDiff .getParametersDiff() .diff(oldOperation.getParameters(), newOperation.getParameters(), context) .ifPresent( params -> { removePathParameters(context.getParameters(), params); changedOperation.setParameters(params); }); if (oldOperation.getResponses() != null || newOperation.getResponses() != null) { openApiDiff .getApiResponseDiff() .diff(oldOperation.getResponses(), newOperation.getResponses(), context.copyAsResponse()) .ifPresent(changedOperation::setApiResponses); } if (oldOperation.getSecurity() != null || newOperation.getSecurity() != null) { openApiDiff .getSecurityRequirementsDiff() .diff(oldOperation.getSecurity(), newOperation.getSecurity(), context) .ifPresent(changedOperation::setSecurityRequirements); } openApiDiff .getExtensionsDiff() .diff(oldOperation.getExtensions(), newOperation.getExtensions(), context) .ifPresent(extensions -> changedOperation.setExtensions(extensions)); return isChanged(changedOperation); }
Example 14
Source File: AbstractEndpointGenerationTest.java From flow with Apache License 2.0 | 4 votes |
private void assertPath(Class<?> testEndpointClass, Method expectedEndpointMethod, PathItem actualPath) { Operation actualOperation = actualPath.getPost(); assertEquals("Unexpected tag in the OpenAPI spec", actualOperation.getTags(), Collections.singletonList(testEndpointClass.getSimpleName())); assertTrue(String.format( "Unexpected OpenAPI operation id: does not contain the endpoint name of the class '%s'", testEndpointClass.getSimpleName()), actualOperation.getOperationId() .contains(getEndpointName(testEndpointClass))); assertTrue(String.format( "Unexpected OpenAPI operation id: does not contain the name of the endpoint method '%s'", expectedEndpointMethod.getName()), actualOperation.getOperationId() .contains(expectedEndpointMethod.getName())); if (expectedEndpointMethod.getParameterCount() > 0) { Schema requestSchema = extractSchema( actualOperation.getRequestBody().getContent()); assertRequestSchema(requestSchema, expectedEndpointMethod.getParameterTypes(), expectedEndpointMethod.getParameters()); } else { assertNull(String.format( "No request body should be present in path schema for endpoint method with no parameters, method: '%s'", expectedEndpointMethod), actualOperation.getRequestBody()); } ApiResponses responses = actualOperation.getResponses(); assertEquals( "Every operation is expected to have a single '200' response", 1, responses.size()); ApiResponse apiResponse = responses.get("200"); assertNotNull( "Every operation is expected to have a single '200' response", apiResponse); if (expectedEndpointMethod.getReturnType() != void.class) { assertSchema(extractSchema(apiResponse.getContent()), expectedEndpointMethod.getReturnType()); } else { assertNull(String.format( "No response is expected to be present for void method '%s'", expectedEndpointMethod), apiResponse.getContent()); } assertNotNull( "Non-anonymous endpoint method should have a security data defined for it in the schema", actualOperation.getSecurity()); }
Example 15
Source File: OpenAPIDeserializerTest.java From swagger-parser with Apache License 2.0 | 4 votes |
@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 16
Source File: OpenAPIV3ParserTest.java From swagger-parser with Apache License 2.0 | 4 votes |
private OpenAPI doRelativeFileTest(String location) { OpenAPIV3Parser parser = new OpenAPIV3Parser(); ParseOptions options = new ParseOptions(); options.setResolve(true); SwaggerParseResult readResult = parser.readLocation(location, null, options); if (readResult.getMessages().size() > 0) { Json.prettyPrint(readResult.getMessages()); } final OpenAPI openAPI = readResult.getOpenAPI(); final PathItem path = openAPI.getPaths().get("/health"); assertEquals(path.getClass(), PathItem.class); //we successfully converted the RefPath to a Path final List<Parameter> parameters = path.getParameters(); assertParamDetails(parameters, 0, QueryParameter.class, "param1", "query"); assertParamDetails(parameters, 1, HeaderParameter.class, "param2", "header"); final Operation operation = path.getGet(); final List<Parameter> operationParams = operation.getParameters(); assertParamDetails(operationParams, 0, PathParameter.class, "param3", "path"); assertParamDetails(operationParams, 1, HeaderParameter.class, "param4", "header"); final Map<String, ApiResponse> responsesMap = operation.getResponses(); assertResponse(openAPI, responsesMap, "200","application/json", "Health information from the server", "#/components/schemas/health"); assertResponse(openAPI, responsesMap, "400","*/*", "Your request was not valid", "#/components/schemas/error"); assertResponse(openAPI, responsesMap, "500","*/*", "An unexpected error occur during processing", "#/components/schemas/error"); final Map<String, Schema> definitions = openAPI.getComponents().getSchemas(); final Schema refInDefinitions = definitions.get("refInDefinitions"); assertEquals(refInDefinitions.getDescription(), "The example model"); expectedPropertiesInModel(refInDefinitions, "foo", "bar"); final ArraySchema arrayModel = (ArraySchema) definitions.get("arrayModel"); final Schema arrayModelItems = arrayModel.getItems(); assertEquals(arrayModelItems.get$ref(), "#/components/schemas/foo"); final Schema fooModel = definitions.get("foo"); assertEquals(fooModel.getDescription(), "Just another model"); expectedPropertiesInModel(fooModel, "hello", "world"); final ComposedSchema composedCat = (ComposedSchema) definitions.get("composedCat"); final Schema child = composedCat.getAllOf().get(2); expectedPropertiesInModel(child, "huntingSkill", "prop2", "reflexes", "reflexMap"); final ArraySchema reflexes = (ArraySchema) child.getProperties().get("reflexes"); final Schema reflexItems = reflexes.getItems(); assertEquals(reflexItems.get$ref(), "#/components/schemas/reflex"); assertTrue(definitions.containsKey(reflexItems.get$ref().substring(reflexItems.get$ref().lastIndexOf("/")+1))); final Schema reflexMap = (Schema) child.getProperties().get("reflexMap"); final Schema reflexMapAdditionalProperties = (Schema) reflexMap.getAdditionalProperties(); assertEquals(reflexMapAdditionalProperties.get$ref(), "#/components/schemas/reflex"); assertEquals(composedCat.getAllOf().size(), 3); assertEquals(composedCat.getAllOf().get(0).get$ref(), "#/components/schemas/pet"); assertEquals(composedCat.getAllOf().get(1).get$ref(), "#/components/schemas/foo_2"); return openAPI; }
Example 17
Source File: OperationResponsesValidator.java From servicecomb-toolkit with Apache License 2.0 | 4 votes |
@Override protected ApiResponses getPropertyObject(Operation oasObject) { return oasObject.getResponses(); }