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

The following examples show how to use io.swagger.v3.oas.models.Operation#getRequestBody() . 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: 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 2
Source File: ExtensionsUtilTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void testArrayParam(@Injectable final List<AuthorizationValue> auths) throws IOException{
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);

    String pathFile = FileUtils.readFileToString(new File("./src/test/swagger/oas3.yaml"),"UTF-8");
    SwaggerParseResult result = new OpenAPIV3Parser().readContents(pathFile, auths, options);
    OpenAPI openAPI = result.getOpenAPI();

    new ExtensionsUtil().addExtensions(openAPI);

    Operation operation = openAPI.getPaths().get("/pet").getPost();
    RequestBody body = operation.getRequestBody();

    assertNotNull(body);
    Schema model = body.getContent().get("application/json").getSchema();
    assertEquals("object", model.getType());
}
 
Example 3
Source File: ExtensionsUtilTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolveRequestBody(@Injectable final List<AuthorizationValue> auths) throws Exception {
    ReflectionUtils utils = new ReflectionUtils();
    utils.setConfiguration( Configuration.read("src/test/config/config1.yaml"));

    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);


    String pathFile = FileUtils.readFileToString(new File("./src/test/swagger/oas3.yaml"),"UTF-8");
    SwaggerParseResult result = new OpenAPIV3Parser().readContents(pathFile, auths, options);
    OpenAPI openAPI = result.getOpenAPI();

    new ExtensionsUtil().addExtensions(openAPI);

    Operation operation = openAPI.getPaths().get("/mappedWithDefinedModel/{id}").getPost();
    RequestBody body = operation.getRequestBody();

    for (String mediaType: body.getContent().keySet()) {
        JavaType jt = utils.getTypeFromRequestBody(body, mediaType , openAPI.getComponents().getSchemas())[0];
        assertEquals(jt.getRawClass(), Dog.class);
    }
}
 
Example 4
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 5
Source File: PathItemTransformer.java    From swagger-brake with Apache License 2.0 5 votes vote down vote up
private Request getRequestBody(Operation operation) {
    Request result = null;
    RequestBody requestBody = operation.getRequestBody();
    if (requestBody != null) {
        result = requestBodyTransformer.transform(requestBody);
    }
    return result;
}
 
Example 6
Source File: HeadersGenerator.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private void generateContentTypeHeaders(Operation operation, List<HttpHeaderField> headers) {
    if (operation.getRequestBody() == null || operation.getRequestBody().getContent() == null) {
        return;
    }

    for (String type : operation.getRequestBody().getContent().keySet()) {
        if (type.toLowerCase().contains("json")
                || type.toLowerCase().contains("x-www-form-urlencoded")) {
            headers.add(new HttpHeaderField(HttpHeader.CONTENT_TYPE, type));
            break;
        }
    }
}
 
Example 7
Source File: ReflectionUtils.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
public JavaType[] getOperationParameterClasses(Operation operation, String mediaType, Map<String, Schema> definitions) {
    TypeFactory tf = Json.mapper().getTypeFactory();

    if (operation.getParameters() == null){
        operation.setParameters(new ArrayList<>());
    }
    int body = 0;
    JavaType[] bodyArgumentClasses = null;
    if (operation.getRequestBody() != null){
        bodyArgumentClasses = getTypeFromRequestBody(operation.getRequestBody(), mediaType, definitions);
        if (bodyArgumentClasses != null) {
            body = bodyArgumentClasses.length;
        }
    }

    JavaType[] jt = new JavaType[operation.getParameters().size() + 1 + body];
    int i = 0;
    jt[i] = tf.constructType(RequestContext.class);

    i += 1;

    for (Parameter parameter : operation.getParameters()) {
        JavaType argumentClasses = getTypeFromParameter(parameter, definitions);
        jt[i] = argumentClasses;
        i += 1;
    }
    if (operation.getRequestBody() != null && bodyArgumentClasses != null) {
        for (JavaType argument :bodyArgumentClasses) {
            jt[i] = argument;
            i += 1;
        }

    }
    return jt;
}
 
Example 8
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 9
Source File: OperationRequestBodyValidator.java    From servicecomb-toolkit with Apache License 2.0 4 votes vote down vote up
@Override
protected RequestBody getPropertyObject(Operation oasObject) {
  return oasObject.getRequestBody();
}
 
Example 10
Source File: OperationRequestBodyDiffValidator.java    From servicecomb-toolkit with Apache License 2.0 4 votes vote down vote up
@Override
protected RequestBody getPropertyObject(Operation oasObject) {
  return oasObject.getRequestBody();
}
 
Example 11
Source File: DefaultGeneratorTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Test
public void testRefModelValidationProperties() {
    OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/refAliasedPrimitiveWithValidation.yml");
    ClientOptInput opts = new ClientOptInput();
    opts.setOpenAPI(openAPI);
    DefaultCodegen config = new DefaultCodegen();
    config.setStrictSpecBehavior(false);
    opts.setConfig(config);

    DefaultGenerator generator = new DefaultGenerator();
    generator.opts(opts);

    String expectedPattern = "^\\d{3}-\\d{2}-\\d{4}$";
    // NOTE: double-escaped regex for when the value is intended to be dumped in template into a String location.
    String escapedPattern = config.toRegularExpression(expectedPattern);

    Schema stringRegex = openAPI.getComponents().getSchemas().get("StringRegex");
    // Sanity check.
    Assert.assertEquals(stringRegex.getPattern(), expectedPattern);

    // Validate when we alias/unalias
    Schema unaliasedStringRegex = ModelUtils.unaliasSchema(openAPI, stringRegex);
    Assert.assertEquals(unaliasedStringRegex.getPattern(), expectedPattern);

    // Validate when converting to property
    CodegenProperty stringRegexProperty = config.fromProperty("stringRegex", stringRegex);
    Assert.assertEquals(stringRegexProperty.pattern, escapedPattern);

    // Validate when converting to parameter
    Operation operation = openAPI.getPaths().get("/fake/StringRegex").getPost();
    RequestBody body = operation.getRequestBody();
    CodegenParameter codegenParameter = config.fromRequestBody(body, new HashSet<>(), "body");

    Assert.assertEquals(codegenParameter.pattern, escapedPattern);

    // Validate when converting to response
    ApiResponse response = operation.getResponses().get("200");
    CodegenResponse codegenResponse = config.fromResponse("200", response);

    Assert.assertEquals(((Schema) codegenResponse.schema).getPattern(), expectedPattern);
    Assert.assertEquals(codegenResponse.pattern, escapedPattern);
}
 
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: OperationDiff.java    From openapi-diff with Apache License 2.0 4 votes vote down vote up
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);
}