io.swagger.v3.oas.models.parameters.RequestBody Java Examples

The following examples show how to use io.swagger.v3.oas.models.parameters.RequestBody. 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: RequestBodyBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Calculate request body info.
 *
 * @param components the components
 * @param methodAttributes the method attributes
 * @param parameterInfo the parameter info
 * @param requestBodyInfo the request body info
 */
public void calculateRequestBodyInfo(Components components, MethodAttributes methodAttributes,
		ParameterInfo parameterInfo, RequestBodyInfo requestBodyInfo) {
	RequestBody requestBody = requestBodyInfo.getRequestBody();
	MethodParameter methodParameter = parameterInfo.getMethodParameter();
	// Get it from parameter level, if not present
	if (requestBody == null) {
		io.swagger.v3.oas.annotations.parameters.RequestBody requestBodyDoc = methodParameter.getParameterAnnotation(io.swagger.v3.oas.annotations.parameters.RequestBody.class);
		requestBody = this.buildRequestBodyFromDoc(requestBodyDoc, methodAttributes, components).orElse(null);
	}

	RequestPart requestPart = methodParameter.getParameterAnnotation(RequestPart.class);
	String paramName = null;
	if (requestPart != null)
		paramName = StringUtils.defaultIfEmpty(requestPart.value(), requestPart.name());
	paramName = StringUtils.defaultIfEmpty(paramName, parameterInfo.getpName());
	parameterInfo.setpName(paramName);

	requestBody = buildRequestBody(requestBody, components, methodAttributes, parameterInfo,
			requestBodyInfo);
	requestBodyInfo.setRequestBody(requestBody);
}
 
Example #2
Source File: AbstractRequestBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Apply bean validator annotations.
 *
 * @param requestBody the request body
 * @param annotations the annotations
 * @param isOptional the is optional
 */
public void applyBeanValidatorAnnotations(final RequestBody requestBody, final List<Annotation> annotations, boolean isOptional) {
	Map<String, Annotation> annos = new HashMap<>();
	boolean requestBodyRequired = false;
	if (!CollectionUtils.isEmpty(annotations)) {
		annotations.forEach(annotation -> annos.put(annotation.annotationType().getName(), annotation));
		requestBodyRequired = annotations.stream()
				.filter(annotation -> org.springframework.web.bind.annotation.RequestBody.class.equals(annotation.annotationType()))
				.anyMatch(annotation -> ((org.springframework.web.bind.annotation.RequestBody) annotation).required());
	}
	boolean validationExists = Arrays.stream(ANNOTATIONS_FOR_REQUIRED).anyMatch(annos::containsKey);

	if (validationExists || (!isOptional && requestBodyRequired))
		requestBody.setRequired(true);
	Content content = requestBody.getContent();
	for (MediaType mediaType : content.values()) {
		Schema<?> schema = mediaType.getSchema();
		applyValidationsToSchema(annos, schema);
	}
}
 
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: Swagger3RestDocGenerator.java    From RestDoc with Apache License 2.0 6 votes vote down vote up
private RequestBody convertFileParameter(ParameterModel param) {
    var requestBody = new RequestBody();

    var propSchema = new Schema();
    propSchema.setType("string");
    propSchema.format("binary");

    Schema schema = new Schema();
    schema.setType("object");
    schema.addProperties(param.getName(), propSchema);

    Content content = new Content();
    var mediaType = new MediaType();
    mediaType.setSchema(schema);
    content.addMediaType("multipart/form-data", mediaType);

    requestBody.setContent(content);
    requestBody.setDescription(param.getDescription());
    requestBody.setRequired(param.isRequired());

    return requestBody;
}
 
Example #5
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 #6
Source File: DefaultCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testHasBodyParameter() {
    final Schema refSchema = new Schema<>().$ref("#/components/schemas/Pet");
    Operation pingOperation = new Operation()
            .responses(
                    new ApiResponses().addApiResponse("204", new ApiResponse()
                            .description("Ok response")));
    Operation createOperation = new Operation()
            .requestBody(new RequestBody()
                    .content(new Content().addMediaType("application/json",
                            new MediaType().schema(refSchema))))
            .responses(
                    new ApiResponses().addApiResponse("201", new ApiResponse()
                            .description("Created response")));
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());
    openAPI.getComponents().addSchemas("Pet", new ObjectSchema());

    final DefaultCodegen codegen = new DefaultCodegen();

    Assert.assertEquals(codegen.hasBodyParameter(openAPI, pingOperation), false);
    Assert.assertEquals(codegen.hasBodyParameter(openAPI, createOperation), true);
}
 
Example #7
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 #8
Source File: DefaultCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void arrayInnerReferencedSchemaMarkedAsModel_20() {
    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/arrayRefBody.yaml");
    final DefaultCodegen codegen = new DefaultCodegen();
    codegen.setOpenAPI(openAPI);

    Set<String> imports = new HashSet<>();

    RequestBody body = openAPI.getPaths().get("/examples").getPost().getRequestBody();

    CodegenParameter codegenParameter = codegen.fromRequestBody(body, imports, "");

    Assert.assertTrue(codegenParameter.isContainer);
    Assert.assertTrue(codegenParameter.items.isModel);
    Assert.assertFalse(codegenParameter.items.isContainer);
}
 
Example #9
Source File: BodyParamExtractionTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertDoubleArrayBodyParam() throws Exception {
    Map<String, Schema> definitions = ModelConverters.getInstance().read(Person.class);

    RequestBody body = new RequestBody().
            content(new Content()
                    .addMediaType("application/json",new MediaType().schema(new ArraySchema()
                            .items(new ArraySchema().items(new StringSchema())))));


    JavaType jt = utils.getTypeFromRequestBody(body, "application/json" ,definitions)[0];
    assertNotNull(jt);

    assertEquals(jt.getRawClass(), List[].class);
    JavaType inner = jt.getContentType();
    assertEquals(inner.getRawClass(), List.class);
    assertEquals(inner.getContentType().getRawClass(), String.class);

}
 
Example #10
Source File: InputModeller.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the {@link IVarDef input variable definition} for the given request body.
 */
private Optional<IVarDef> requestBodyVarDef( OpenAPI api, RequestBody body)
  {
  return
    resultFor( "requestBody",
      () ->
      Optional.ofNullable( body)
      .map( b -> resolveRequestBody( api, b))
      .map( b -> {
        String contentVarTag = "Content";
        Map<String,MediaType> mediaTypes = expectedValueOf( b.getContent(), "Request body content");
        return
          VarSetBuilder.with( "Body")
          .type( "request")
          .members(
            instanceDefinedVar( contentVarTag, Boolean.TRUE.equals( b.getRequired())),
            mediaTypeVar( contentVarTag, mediaTypes))
          .members(
            mediaTypeContentVars( api, contentVarTag, mediaTypes))
          .build();
        }));
  }
 
Example #11
Source File: RequestModelConverter.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
private String generateBody() {
    RequestBody requestBody = operationModel.getOperation().getRequestBody();
    if (requestBody != null) {
        Content content = requestBody.getContent();
        Schema<?> schema;

        if (content.containsKey("application/json")) {
            schema = content.get("application/json").getSchema();
            return generators.getBodyGenerator().generate(schema);
        }
        if (content.containsKey("application/x-www-form-urlencoded")) {
            schema = content.get("application/x-www-form-urlencoded").getSchema();
            return generators.getBodyGenerator().generateForm(schema);
        }
        if (content.containsKey("application/octet-stream")
                || content.containsKey("multipart/form-data")) {
            return "";
        }

        if (!content.isEmpty()) {
            schema = content.entrySet().iterator().next().getValue().getSchema();
            return generators.getBodyGenerator().generate(schema);
        }
    }
    return "";
}
 
Example #12
Source File: PathsProcessor.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
protected void updateLocalRefs(RequestBody body, String pathRef) {
    if (body.get$ref() != null){
        if(isLocalRef(body.get$ref())) {
            body.set$ref(computeLocalRef(body.get$ref(), pathRef));
        }
    }
    if(body.getContent() != null) {
        Map<String, MediaType> content = body.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);
                }
            }
        }
    }else if(body.get$ref() != null){

    }
}
 
Example #13
Source File: RelativeReferenceTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue213() throws Exception {
    new Expectations() {{
        RemoteUrl.urlToString("http://foo.bar.com/swagger.json", Arrays.asList(new AuthorizationValue[]{}));
        times = 1;
        result = spec;

        RemoteUrl.urlToString("http://foo.bar.com/path/samplePath.yaml", Arrays.asList(new AuthorizationValue[]{}));
        times = 1;
        result = samplePath;
    }};


    OpenAPI swagger = new OpenAPIV3Parser().read("http://foo.bar.com/swagger.json");
    assertNotNull(swagger);
    assertNotNull(swagger.getPaths().get("/samplePath"));

    assertNotNull(swagger.getPaths().get("/samplePath").getGet());
    assertNotNull(swagger.getPaths().get("/samplePath").getGet().getRequestBody());
    RequestBody body = swagger.getPaths().get("/samplePath").getGet().getRequestBody();
    assertNotNull(body.getContent().get("application/json").getSchema());
}
 
Example #14
Source File: SchemaGenerator.java    From Poseidon with Apache License 2.0 6 votes vote down vote up
private static void handleParams(Operation operation, ParamPOJO paramPOJO, Path modelsDir, boolean isRequired) {
    if (paramPOJO.isFile()) {
        return;
    }

    if (paramPOJO.isBody()) {
        final RequestBody requestBody = new RequestBody();
        requestBody.required(isRequired);
        final Content content = new Content();
        final MediaType mediaType = new MediaType();
        mediaType.schema(createSchema(paramPOJO, modelsDir));
        content.addMediaType("application/json", mediaType);
        requestBody.content(content);
        operation.requestBody(requestBody);
        return;
    }

    operation.addParametersItem(createParameter(paramPOJO, modelsDir).required(isRequired));
}
 
Example #15
Source File: DefaultValidator.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
public void validate(Object argument, RequestBody body, Iterator<Validator> chain) throws ValidationException {
    if (Boolean.TRUE.equals(body.getRequired())) {
        if(argument == null) {
            throw new ValidationException()
                    .message(new ValidationMessage()
                            .code(ValidationError.MISSING_REQUIRED)
                            .message("missing required  parameter"));
        }
    }
    if(chain.hasNext()) {
        chain.next().validate(argument, body, chain);
        return;
    }

    return;
}
 
Example #16
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicInput() {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());

    Schema user = new Schema();
    user.addProperties("name", new StringSchema());

    openAPI.path("/foo/baz", new PathItem()
            .post(new Operation()
                    .requestBody(new RequestBody()
                            .content(new Content().addMediaType("*/*",new MediaType().schema(new Schema().$ref("User")))))));

    openAPI.getComponents().addSchemas("User", user);

    new InlineModelResolver().flatten(openAPI);
}
 
Example #17
Source File: OpenAPI3RequestValidationHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public void parseOperationSpec() {
  // Extract from path spec parameters description
  if (resolvedParameters!=null) {
    for (Parameter opParameter : resolvedParameters) {
      if (opParameter.get$ref() != null)
        opParameter = refsCache.loadRef(opParameter.get$ref(), computeRefFormat(opParameter.get$ref()), Parameter.class);
      this.parseParameter(opParameter);
    }
  }
  RequestBody body = this.pathSpec.getRequestBody();
  if (body != null) {
    if (body.get$ref() != null)
      body = refsCache.loadRef(body.get$ref(), computeRefFormat(body.get$ref()), RequestBody.class);
    this.parseRequestBody(body);
  }
}
 
Example #18
Source File: OpenApiUtils.java    From tcases with MIT License 5 votes vote down vote up
/**
 * If the given request body is defined by a reference, returns the referenced requestBody. Otherwise, returns the given request body.
 */
public static RequestBody resolveRequestBody( OpenAPI api, RequestBody requestBody)
  {
  return
    Optional.ofNullable( requestBody.get$ref())
    .map( ref -> componentRequestBodyRef( api, ref))
    .orElse( requestBody);
  }
 
Example #19
Source File: StringTypeValidator.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
public void validate(Object argument, RequestBody body, Iterator<Validator> chain) throws ValidationException {
    if (body.getContent() != null) {
        for(String media: body.getContent().keySet()) {
            if (body.getContent().get(media) != null) {
                MediaType mediaType = body.getContent().get(media);
                Set<String> allowable = validateAllowedValues(argument, mediaType.getSchema());
                if(allowable != null){
                    throw new ValidationException()
                        .message(new ValidationMessage()
                                .code(ValidationError.UNACCEPTABLE_VALUE)
                                .message(" parameter  value `" + argument + "` is not in the allowable values `" + allowable + "`"));
                }
                if (validateFormat(argument,mediaType.getSchema())){
                    throw new ValidationException()
                        .message(new ValidationMessage()
                                .code(ValidationError.INVALID_FORMAT)
                                .message( " parameter value `" + argument + "` is not a valid " + mediaType.getSchema().getFormat()));
                }


            }
        }
    }

    if(chain.hasNext()) {
        chain.next().validate(argument, body, chain);
        return;
    }

    return;
}
 
Example #20
Source File: BodyParamExtractionTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testStringBodyParam() throws Exception {
    Map<String, Schema> definitions = new HashMap<String, Schema>();

    RequestBody body = new RequestBody().
            content(new Content()
                    .addMediaType("application/json",new MediaType()
                        .schema(new Schema().type("string"))));

    JavaType jt = utils.getTypeFromRequestBody(body, "application/json" ,definitions)[0];

    assertEquals(jt.getRawClass(), String.class);
}
 
Example #21
Source File: SwaggerConverter.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
private RequestBody convertParameterToRequestBody(io.swagger.models.parameters.Parameter param, List<String> consumes) {
    RequestBody body = new RequestBody();
    BodyParameter bp = (BodyParameter) param;

    List<String> mediaTypes = new ArrayList<>(globalConsumes);
    if (consumes != null && consumes.size() > 0) {
        mediaTypes.clear();
        mediaTypes.addAll(consumes);
    }

    if (mediaTypes.size() == 0) {
        mediaTypes.add("*/*");
    }

    if (StringUtils.isNotBlank(param.getDescription())) {
        body.description(param.getDescription());
    }
    body.required(param.getRequired());

    Content content = new Content();
    for (String type : mediaTypes) {
        content.addMediaType(type,
                new MediaType().schema(
                        convert(bp.getSchema())));
        if (StringUtils.isNotBlank(bp.getDescription())) {
            body.setDescription(bp.getDescription());
        }
    }
    convertExamples(((BodyParameter) param).getExamples(), content);
    body.content(content);
    return body;
}
 
Example #22
Source File: OpenApiUtils.java    From tcases with MIT License 5 votes vote down vote up
/**
 * When the given reference is non-null, returns the component request body referenced.
 */
public static RequestBody componentRequestBodyRef( OpenAPI api, String reference)
  {
  return
    Optional.ofNullable( reference)
    .flatMap( ref -> Optional.ofNullable( componentName( COMPONENTS_REQUEST_BODIES_REF, ref)))
    .flatMap( name -> Optional.ofNullable( expectedValueOf( expectedValueOf( api.getComponents(), "Components").getRequestBodies(), "Component request bodies").get( name)))
    .orElseThrow( () -> new IllegalStateException( String.format( "Can't resolve request body reference=%s", reference)));
  }
 
Example #23
Source File: VaadinConnectTsGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private Schema getRequestBodySchema(RequestBody body) {
    Content content = body.getContent();
    if (content == null) {
        return null;
    }
    MediaType mediaType = content.get(DEFAULT_CONTENT_TYPE);
    if (mediaType != null && mediaType.getSchema() != null) {
        return mediaType.getSchema();
    }
    return null;
}
 
Example #24
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static void setRefOfRequestBody(RequestBody requestBody, SwaggerUpdateContext context) {
    if (requestBody != null) {
        Content content = requestBody.getContent();

        extractReferenceFromContent(content, context);
    }
}
 
Example #25
Source File: InlineModelResolverTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveInlineRequestBodyWithTitle() {
    OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/inline_model_resolver.yaml");
    new InlineModelResolver().flatten(openAPI);

    RequestBody requestBodyReference = openAPI.getPaths().get("/resolve_inline_request_body_with_title").getPost().getRequestBody();
    assertEquals("#/components/requestBodies/resolve_inline_request_body_with_title", requestBodyReference.get$ref());
}
 
Example #26
Source File: InlineModelResolverTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveInlineRequestBodyWithRequired() {
    OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/inline_model_resolver.yaml");
    new InlineModelResolver().flatten(openAPI);

    RequestBody requestBodyReference = openAPI.getPaths().get("/resolve_inline_request_body_with_required").getPost().getRequestBody();
    assertTrue(requestBodyReference.getRequired());

    RequestBody referencedRequestBody = ModelUtils.getReferencedRequestBody(openAPI, requestBodyReference);
    assertTrue(referencedRequestBody.getRequired());
}
 
Example #27
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
private void testOperationBodyparamRemoteRefs(String remoteRef) {
    final OpenAPI swagger = new OpenAPI();
    swagger.path("/fun", new PathItem()
            .get(new Operation()
                    .requestBody(new RequestBody()
                            .content(new Content().addMediaType("*/*",new MediaType()
                                    .schema(new Schema().$ref(remoteRef)))))));

    final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve();
    final RequestBody param =  swagger.getPaths().get("/fun").getGet().getRequestBody();
    final Schema ref =  param.getContent().get("*/*").getSchema();
    assertEquals(ref.get$ref(), "#/components/schemas/Tag");
    assertNotNull(swagger.getComponents().getSchemas().get("Tag"));
}
 
Example #28
Source File: JavaModelTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(description = "convert an array of array schema in a RequestBody")
public void arrayOfArraySchemaTestInRequestBody() {
    final Schema testSchema = new ArraySchema()
            .items(new ArraySchema()
                    .items(new Schema<>().$ref("#/components/schemas/Pet")));
    Operation operation = new Operation()
            .requestBody(new RequestBody()
                    .content(new Content().addMediaType("application/json",
                            new MediaType().schema(testSchema))))
            .responses(
                    new ApiResponses().addApiResponse("204", new ApiResponse()
                            .description("Ok response")));
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("Pet", new ObjectSchema().addProperties("name", new StringSchema()));
    final DefaultCodegen codegen = new JavaClientCodegen();
    codegen.setOpenAPI(openAPI);
    final CodegenOperation co = codegen.fromOperation("testSchema", "GET", operation, null);

    Assert.assertEquals(co.bodyParams.size(), 1);
    CodegenParameter cp1 = co.bodyParams.get(0);
    Assert.assertEquals(cp1.baseType, "List");
    Assert.assertEquals(cp1.dataType, "List<List<Pet>>");
    Assert.assertTrue(cp1.isContainer);
    Assert.assertTrue(cp1.isListContainer);
    Assert.assertFalse(cp1.isMapContainer);
    Assert.assertEquals(cp1.items.baseType, "List");
    Assert.assertEquals(cp1.items.complexType, "Pet");
    Assert.assertEquals(cp1.items.dataType, "List<Pet>");
    Assert.assertEquals(cp1.items.items.baseType, "Pet");
    Assert.assertEquals(cp1.items.items.complexType, "Pet");
    Assert.assertEquals(cp1.items.items.dataType, "Pet");

    Assert.assertEquals(co.responses.size(), 1);

    Assert.assertTrue(co.imports.contains("Pet"));
    Assert.assertTrue(co.imports.contains("List"));
}
 
Example #29
Source File: JavaModelTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(description = "convert an array schema in a RequestBody")
public void arraySchemaTestInRequestBody() {
    final Schema testSchema = new ArraySchema()
            .items(new Schema<>().$ref("#/components/schemas/Pet"));
    Operation operation = new Operation()
            .requestBody(new RequestBody()
                    .content(new Content().addMediaType("application/json",
                            new MediaType().schema(testSchema))))
            .responses(
                    new ApiResponses().addApiResponse("204", new ApiResponse()
                            .description("Ok response")));
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("Pet", new ObjectSchema().addProperties("name", new StringSchema()));
    final DefaultCodegen codegen = new JavaClientCodegen();
    codegen.setOpenAPI(openAPI);
    final CodegenOperation co = codegen.fromOperation("testSchema", "GET", operation, null);

    Assert.assertEquals(co.bodyParams.size(), 1);
    CodegenParameter cp1 = co.bodyParams.get(0);
    Assert.assertEquals(cp1.baseType, "Pet");
    Assert.assertEquals(cp1.dataType, "List<Pet>");
    Assert.assertTrue(cp1.isContainer);
    Assert.assertTrue(cp1.isListContainer);
    Assert.assertFalse(cp1.isMapContainer);
    Assert.assertEquals(cp1.items.baseType, "Pet");
    Assert.assertEquals(cp1.items.complexType, "Pet");
    Assert.assertEquals(cp1.items.dataType, "Pet");

    Assert.assertEquals(co.responses.size(), 1);

    Assert.assertTrue(co.imports.contains("List"));
    Assert.assertTrue(co.imports.contains("Pet"));
}
 
Example #30
Source File: ModelUtils.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public static RequestBody getRequestBody(OpenAPI openAPI, String name) {
    if (name == null) {
        return null;
    }

    if (openAPI != null && openAPI.getComponents() != null && openAPI.getComponents().getRequestBodies() != null) {
        return openAPI.getComponents().getRequestBodies().get(name);
    }
    return null;
}