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

The following examples show how to use io.swagger.v3.oas.models.Operation#setRequestBody() . 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: DataRestRequestBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Add parameters.
 *
 * @param openAPI the open api
 * @param requestMethod the request method
 * @param methodAttributes the method attributes
 * @param operation the operation
 * @param methodParameter the method parameter
 * @param parameterInfo the parameter info
 * @param parameter the parameter
 */
private void addParameters(OpenAPI openAPI, RequestMethod requestMethod, MethodAttributes methodAttributes, Operation operation, MethodParameter methodParameter, ParameterInfo parameterInfo, Parameter parameter) {
	List<Annotation> parameterAnnotations = Arrays.asList(methodParameter.getParameterAnnotations());
	if (requestBuilder.isValidParameter(parameter)) {
		requestBuilder.applyBeanValidatorAnnotations(parameter, parameterAnnotations);
		operation.addParametersItem(parameter);
	}
	else if (!RequestMethod.GET.equals(requestMethod)) {
		RequestBodyInfo requestBodyInfo = new RequestBodyInfo();
		if (operation.getRequestBody() != null)
			requestBodyInfo.setRequestBody(operation.getRequestBody());
		requestBodyBuilder.calculateRequestBodyInfo(openAPI.getComponents(), methodAttributes,
				parameterInfo, requestBodyInfo);
		requestBuilder.applyBeanValidatorAnnotations(requestBodyInfo.getRequestBody(), parameterAnnotations, methodParameter.isOptional());
		operation.setRequestBody(requestBodyInfo.getRequestBody());
	}
}
 
Example 3
Source File: OpenApiOperationValidationsTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "getOrHeadWithBodyExpectations")
public void testGetOrHeadWithBodyWithDisabledRecommendations(PathItem.HttpMethod method, String operationId, String ref, Content content, boolean shouldTriggerFailure) {
    RuleConfiguration config = new RuleConfiguration();
    config.setEnableRecommendations(false);
    OpenApiOperationValidations validator = new OpenApiOperationValidations(config);

    Operation op = new Operation().operationId(operationId);
    RequestBody body = new RequestBody();
    if (StringUtils.isNotEmpty(ref) || content != null) {
        body.$ref(ref);
        body.content(content);

        op.setRequestBody(body);
    }

    ValidationResult result = validator.validate(new OperationWrapper(null, op, method));
    Assert.assertNotNull(result.getWarnings());

    List<Invalid> warnings = result.getWarnings().stream()
            .filter(invalid -> "API GET/HEAD defined with request body".equals(invalid.getRule().getDescription()))
            .collect(Collectors.toList());

    Assert.assertNotNull(warnings);
    Assert.assertEquals(warnings.size(), 0, "Expected warnings not to include recommendation.");
}
 
Example 4
Source File: OpenApiOperationValidationsTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "getOrHeadWithBodyExpectations")
public void testGetOrHeadWithBodyWithDisabledRule(PathItem.HttpMethod method, String operationId, String ref, Content content, boolean shouldTriggerFailure) {
    RuleConfiguration config = new RuleConfiguration();
    config.setEnableApiRequestUriWithBodyRecommendation(false);
    OpenApiOperationValidations validator = new OpenApiOperationValidations(config);

    Operation op = new Operation().operationId(operationId);
    RequestBody body = new RequestBody();
    if (StringUtils.isNotEmpty(ref) || content != null) {
        body.$ref(ref);
        body.content(content);

        op.setRequestBody(body);
    }

    ValidationResult result = validator.validate(new OperationWrapper(null, op, method));
    Assert.assertNotNull(result.getWarnings());

    List<Invalid> warnings = result.getWarnings().stream()
            .filter(invalid -> "API GET/HEAD defined with request body".equals(invalid.getRule().getDescription()))
            .collect(Collectors.toList());

    Assert.assertNotNull(warnings);
    Assert.assertEquals(warnings.size(), 0, "Expected warnings not to include recommendation.");
}
 
Example 5
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 6
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 7
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 8
Source File: OpenApiOperationValidationsTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "getOrHeadWithBodyExpectations")
public void testGetOrHeadWithBody(PathItem.HttpMethod method, String operationId, String ref, Content content, boolean shouldTriggerFailure) {
    RuleConfiguration config = new RuleConfiguration();
    config.setEnableRecommendations(true);
    OpenApiOperationValidations validator = new OpenApiOperationValidations(config);

    Operation op = new Operation().operationId(operationId);
    RequestBody body = new RequestBody();
    if (StringUtils.isNotEmpty(ref) || content != null) {
        body.$ref(ref);
        body.content(content);

        op.setRequestBody(body);
    }

    ValidationResult result = validator.validate(new OperationWrapper(null, op, method));
    Assert.assertNotNull(result.getWarnings());

    List<Invalid> warnings = result.getWarnings().stream()
            .filter(invalid -> "API GET/HEAD defined with request body".equals(invalid.getRule().getDescription()))
            .collect(Collectors.toList());

    Assert.assertNotNull(warnings);
    if (shouldTriggerFailure) {
        Assert.assertEquals(warnings.size(), 1, "Expected warnings to include recommendation.");
    } else {
        Assert.assertEquals(warnings.size(), 0, "Expected warnings not to include recommendation.");
    }
}
 
Example 9
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 10
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveInlineRequestBody() throws Exception {
    OpenAPI openAPI = new OpenAPI();


    ObjectSchema objectSchema = new ObjectSchema();
    objectSchema.addProperties("street", new StringSchema());

    Schema schema = new Schema();
    schema.addProperties("address", objectSchema);
    schema.addProperties("name", new StringSchema());

    MediaType mediaType = new MediaType();
    mediaType.setSchema(schema);

    Content content = new Content();
    content.addMediaType("*/*", mediaType );

    RequestBody requestBody = new RequestBody();
    requestBody.setContent(content);

    Operation operation = new Operation();
    operation.setRequestBody(requestBody);

    PathItem pathItem = new PathItem();
    pathItem.setGet(operation);
    openAPI.path("/hello",pathItem);

    new InlineModelResolver().flatten(openAPI);

    Operation getOperation = openAPI.getPaths().get("/hello").getGet();
    RequestBody body = getOperation.getRequestBody();
    assertTrue(body.getContent().get("*/*").getSchema().get$ref() != null);

    Schema bodySchema = openAPI.getComponents().getSchemas().get("body");
    assertTrue(bodySchema instanceof Schema);

    assertNotNull(bodySchema.getProperties().get("address"));
}
 
Example 11
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Construct openAPI definition for graphQL. Add get and post operations
 *
 * @param openAPI OpenAPI
 * @return modified openAPI for GraphQL
 */
private void modifyGraphQLSwagger(OpenAPI openAPI) {
    SwaggerData.Resource resource = new SwaggerData.Resource();
    resource.setAuthType(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN);
    resource.setPolicy(APIConstants.DEFAULT_SUB_POLICY_UNLIMITED);
    resource.setPath("/");
    resource.setVerb(APIConstants.HTTP_POST);
    Operation postOperation = createOperation(resource);

    //post operation
    RequestBody requestBody = new RequestBody();
    requestBody.setDescription("Query or mutation to be passed to graphQL API");
    requestBody.setRequired(true);

    JSONObject typeOfPayload = new JSONObject();
    JSONObject payload = new JSONObject();
    typeOfPayload.put(APIConstants.TYPE, APIConstants.STRING);
    payload.put(APIConstants.OperationParameter.PAYLOAD_PARAM_NAME, typeOfPayload);

    Schema postSchema = new Schema();
    postSchema.setType(APIConstants.OBJECT);
    postSchema.setProperties(payload);

    MediaType mediaType = new MediaType();
    mediaType.setSchema(postSchema);

    Content content = new Content();
    content.addMediaType(APPLICATION_JSON_MEDIA_TYPE, mediaType);
    requestBody.setContent(content);
    postOperation.setRequestBody(requestBody);

    //add post and get operations to path /*
    PathItem pathItem = new PathItem();
    pathItem.setPost(postOperation);
    Paths paths = new Paths();
    paths.put("/", pathItem);

    openAPI.setPaths(paths);
}
 
Example 12
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 13
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 14
Source File: AbstractRequestBuilder.java    From springdoc-openapi with Apache License 2.0 3 votes vote down vote up
/**
 * Sets params.
 *
 * @param operation the operation
 * @param operationParameters the operation parameters
 * @param requestBodyInfo the request body info
 */
private void setParams(Operation operation, List<Parameter> operationParameters, RequestBodyInfo requestBodyInfo) {
	if (!CollectionUtils.isEmpty(operationParameters))
		operation.setParameters(operationParameters);
	if (requestBodyInfo.getRequestBody() != null)
		operation.setRequestBody(requestBodyInfo.getRequestBody());
}