io.swagger.v3.oas.models.media.Content Java Examples

The following examples show how to use io.swagger.v3.oas.models.media.Content. 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: OpenAPIDeserializer.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public Content getContent(ObjectNode node, String location, ParseResult result){
    if (node == null) {
        return null;
    }
    Content content = new Content();

    Set<String> keys = getKeys(node);
    for(String key : keys) {
        MediaType mediaType = getMediaType((ObjectNode) node.get(key), String.format("%s.'%s'", location, key), result);
        if (mediaType != null) {
            content.addMediaType(key, mediaType);
        }
    }

    return content;
}
 
Example #2
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 #3
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 #4
Source File: MediaContentComponent.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Override
public StructuralNode apply(StructuralNode node, MediaContentComponent.Parameters parameters) {
    Content content = parameters.content;
    if (content == null || content.isEmpty()) return node;

    DescriptionListImpl mediaContentList = new DescriptionListImpl(node);
    mediaContentList.setTitle(labels.getLabel(LABEL_CONTENT));

    content.forEach((type, mediaType) -> {
        DescriptionListEntryImpl tagEntry = new DescriptionListEntryImpl(mediaContentList, Collections.singletonList(new ListItemImpl(mediaContentList, type)));
        ListItemImpl tagDesc = new ListItemImpl(tagEntry, "");

        Document tagDescDocument = schemaComponent.apply(mediaContentList, mediaType.getSchema());
        mediaTypeExampleComponent.apply(tagDescDocument, mediaType.getExample());
        examplesComponent.apply(tagDescDocument, mediaType.getExamples());
        encodingComponent.apply(tagDescDocument, mediaType.getEncoding());
        tagDesc.append(tagDescDocument);

        tagEntry.setDescription(tagDesc);
        mediaContentList.addEntry(tagEntry);
    });
    node.append(mediaContentList);
    return node;
}
 
Example #5
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 #6
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
private ApiResponse createApiSuccessfulResponse(
        MethodDeclaration methodDeclaration) {
    Content successfulContent = new Content();
    // "description" is a REQUIRED property of Response
    ApiResponse successfulResponse = new ApiResponse().description("");
    methodDeclaration.getJavadoc().ifPresent(javadoc -> {
        for (JavadocBlockTag blockTag : javadoc.getBlockTags()) {
            if (blockTag.getType() == JavadocBlockTag.Type.RETURN) {
                successfulResponse.setDescription(
                        "Return " + blockTag.getContent().toText());
            }
        }
    });
    if (!methodDeclaration.getType().isVoidType()) {
        MediaType mediaItem = createReturnMediaType(methodDeclaration);
        successfulContent.addMediaType("application/json", mediaItem);
        successfulResponse.content(successfulContent);
    }
    return successfulResponse;
}
 
Example #7
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testArbitraryObjectResponseMapInline() {
    OpenAPI openAPI = new OpenAPI();

    Schema schema = new Schema();
    schema.setAdditionalProperties(new ObjectSchema());

    openAPI.path("/foo/baz", new PathItem()
            .get(new Operation()
                    .responses(new ApiResponses().addApiResponse("200", new ApiResponse()
                            .description("it works!")
                            .content(new Content().addMediaType("*/*", new MediaType().schema(schema)))))));

    new InlineModelResolver().flatten(openAPI);

    ApiResponse response = openAPI.getPaths().get("/foo/baz").getGet().getResponses().get("200");

    Schema property = response.getContent().get("*/*").getSchema();
    assertTrue(property.getAdditionalProperties() != null);
    assertTrue(property.getAdditionalProperties() instanceof  Schema);
    assertTrue(openAPI.getComponents().getSchemas() == null);
    Schema inlineProp = (Schema)property.getAdditionalProperties();
    assertTrue(inlineProp instanceof ObjectSchema);
    ObjectSchema op = (ObjectSchema) inlineProp;
    assertNull(op.getProperties());
}
 
Example #8
Source File: OASErrors.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
public static Map<String, ApiResponse> generateStandardApiErrorResponses() {
  Map<String, ApiResponse> responses = new LinkedHashMap<>();

  List<Integer> responseCodes = getStandardHttpStatusCodes();
  for (Integer responseCode : responseCodes) {
    if (responseCode >= 400 && responseCode <= 599) {
      ApiResponse apiResponse = new ApiResponse();
      apiResponse.description(HttpStatus.toMessage(responseCode));
      apiResponse.content(new Content()
          .addMediaType("application/vnd.api+json",
              new MediaType().schema(new Failure().$ref()))
      );
      responses.put(responseCode.toString(), apiResponse);
    }
  }

  return responses;
}
 
Example #9
Source File: SpringDocAnnotationsUtils.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Gets media type.
 *
 * @param schema the schema
 * @param components the components
 * @param jsonViewAnnotation the json view annotation
 * @param annotationContent the annotation content
 * @return the media type
 */
private static MediaType getMediaType(Schema schema, Components components, JsonView jsonViewAnnotation,
		io.swagger.v3.oas.annotations.media.Content annotationContent) {
	MediaType mediaType = new MediaType();
	if (!annotationContent.schema().hidden()) {
		if (components != null) {
			try {
				getSchema(annotationContent, components, jsonViewAnnotation).ifPresent(mediaType::setSchema);
			}
			catch (Exception e) {
				if (isArray(annotationContent))
					mediaType.setSchema(new ArraySchema().items(new StringSchema()));
				else
					mediaType.setSchema(new StringSchema());
			}
		}
		else {
			mediaType.setSchema(schema);
		}
	}
	return mediaType;
}
 
Example #10
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(description = "resolve array response remote refs in yaml")
public void testYamlArrayResponseRemoteRefs() {
    final OpenAPI swagger = new OpenAPI();
    swagger.path("/fun", new PathItem()
            .get(new Operation()
                    .responses(new ApiResponses().addApiResponse("200", new ApiResponse()
                            .content(new Content().addMediaType("*/*",new MediaType().schema(
                                    new ArraySchema().items(
                                            new Schema().$ref(replacePort(REMOTE_REF_YAML))))))))));

    final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve();
    final ApiResponse response = swagger.getPaths().get("/fun").getGet().getResponses().get("200");
    final ArraySchema array = (ArraySchema) response.getContent().get("*/*").getSchema();
    assertNotNull(array.getItems());

    assertEquals(array.getItems().get$ref(), "#/components/schemas/Tag");
    assertNotNull(swagger.getComponents().getSchemas().get("Tag"));
}
 
Example #11
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue853() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setFlatten(true);
    final OpenAPI openAPI = new OpenAPIV3Parser().readLocation("issue-837-853-1131/main.yaml", null, options).getOpenAPI();
    Assert.assertNotNull(openAPI);

    Operation post = openAPI.getPaths().get("/guests").getPost();
    Assert.assertNotNull(post);

    Content content = post.getResponses().get("201").getContent();
    Assert.assertNotNull(content);

    Map<String, Example> examples = content.get("application/json").getExamples();
    Assert.assertEquals(examples.size(), 1);
    assertNotNull(openAPI.getComponents());
    assertNotNull(openAPI.getComponents().getExamples());
    assertNotNull(openAPI.getComponents().getExamples().get("testExample"));
    assertEquals(((LinkedHashMap<String, Object>)openAPI.getComponents().getExamples().get("testExample").getValue()).get("test"),"value");
}
 
Example #12
Source File: GenericResponseBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Build content content.
 *
 * @param components the components
 * @param annotations the annotations
 * @param methodProduces the method produces
 * @param jsonView the json view
 * @param returnType the return type
 * @return the content
 */
public Content buildContent(Components components, Annotation[] annotations, String[] methodProduces, JsonView jsonView, Type returnType) {
	Content content = new Content();
	// if void, no content
	if (isVoid(returnType))
		return null;
	if (ArrayUtils.isNotEmpty(methodProduces)) {
		Schema<?> schemaN = calculateSchema(components, returnType, jsonView, annotations);
		if (schemaN != null) {
			io.swagger.v3.oas.models.media.MediaType mediaType = new io.swagger.v3.oas.models.media.MediaType();
			mediaType.setSchema(schemaN);
			// Fill the content
			setContent(methodProduces, content, mediaType);
		}
	}
	return content;
}
 
Example #13
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 #14
Source File: OperationContext.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
private void processProduces() {

    if (getProduces() == null) {
      return;
    }

    List<String> produceList = Arrays.stream(produces).filter(s -> !StringUtils.isEmpty(s))
        .collect(Collectors.toList());

    if (!produceList.isEmpty()) {
      ApiResponse apiResponse = new ApiResponse();
      Content content = new Content();
      MediaType mediaType = new MediaType();
      Schema schema = ModelConverter
          .getSchema(getMethod().getReturnType(), getComponents(), RequestResponse.RESPONSE);
      mediaType.schema(schema);
      for (String produce : produceList) {
        content.addMediaType(produce, mediaType);
      }
      apiResponse.description("OK");
      apiResponse.setContent(content);
      addResponse(HttpStatuses.OK, apiResponse);
    }
  }
 
Example #15
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 #16
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue834() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult result = new OpenAPIV3Parser().readLocation("issue-834/index.yaml", null, options);
    assertNotNull(result.getOpenAPI());

    Content foo200Content = result.getOpenAPI().getPaths().get("/foo").getGet().getResponses().get("200").getContent();
    assertNotNull(foo200Content);
    String foo200SchemaRef = foo200Content.get("application/json").getSchema().get$ref();
    assertEquals(foo200SchemaRef, "#/components/schemas/schema");

    Content foo300Content = result.getOpenAPI().getPaths().get("/foo").getGet().getResponses().get("300").getContent();
    assertNotNull(foo300Content);
    String foo300SchemaRef = foo300Content.get("application/json").getSchema().get$ref();
    assertEquals(foo300SchemaRef, "#/components/schemas/schema");

    Content bar200Content = result.getOpenAPI().getPaths().get("/bar").getGet().getResponses().get("200").getContent();
    assertNotNull(bar200Content);
    String bar200SchemaRef = bar200Content.get("application/json").getSchema().get$ref();
    assertEquals(bar200SchemaRef, "#/components/schemas/schema");
}
 
Example #17
Source File: OperationBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #18
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 #19
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue837() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    final OpenAPI openAPI = new OpenAPIV3Parser().readLocation("issue-837-853-1131/main.yaml", null, options).getOpenAPI();
    Assert.assertNotNull(openAPI);

    Content content = openAPI.getPaths().get("/events").getGet().getResponses().get("200").getContent();
    Assert.assertNotNull(content);

    Map<String, Example> examples = content.get("application/json").getExamples();
    Assert.assertEquals(examples.size(), 3);
    Assert.assertEquals(((ObjectNode) examples.get("plain").getValue()).get("test").asText(), "plain");
    Assert.assertEquals(examples.get("local").get$ref(), "#/components/examples/LocalRef");
    Assert.assertEquals(examples.get("external").get$ref(), "#/components/examples/ExternalRef");
}
 
Example #20
Source File: ChangedContent.java    From openapi-diff with Apache License 2.0 5 votes vote down vote up
public ChangedContent(Content oldContent, Content newContent, DiffContext context) {
  this.oldContent = oldContent;
  this.newContent = newContent;
  this.context = context;
  this.increased = new LinkedHashMap<>();
  this.missing = new LinkedHashMap<>();
  this.changed = new LinkedHashMap<>();
}
 
Example #21
Source File: ContentDiff.java    From openapi-diff with Apache License 2.0 5 votes vote down vote up
public Optional<ChangedContent> diff(Content left, Content right, DiffContext context) {

    MapKeyDiff<String, MediaType> mediaTypeDiff = MapKeyDiff.diff(left, right);
    List<String> sharedMediaTypes = mediaTypeDiff.getSharedKey();
    Map<String, ChangedMediaType> changedMediaTypes = new LinkedHashMap<>();
    for (String mediaTypeKey : sharedMediaTypes) {
      MediaType oldMediaType = left.get(mediaTypeKey);
      MediaType newMediaType = right.get(mediaTypeKey);
      ChangedMediaType changedMediaType =
          new ChangedMediaType(oldMediaType.getSchema(), newMediaType.getSchema(), context);
      openApiDiff
          .getSchemaDiff()
          .diff(
              new HashSet<>(),
              oldMediaType.getSchema(),
              newMediaType.getSchema(),
              context.copyWithRequired(true))
          .ifPresent(changedMediaType::setSchema);
      if (!isUnchanged(changedMediaType)) {
        changedMediaTypes.put(mediaTypeKey, changedMediaType);
      }
    }
    return isChanged(
        new ChangedContent(left, right, context)
            .setIncreased(mediaTypeDiff.getIncreased())
            .setMissing(mediaTypeDiff.getMissing())
            .setChanged(changedMediaTypes));
  }
 
Example #22
Source File: ResourceReferencesResponseTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
void response() {
  ApiResponse apiResponse = new ResourceReferencesResponse(metaResource).response();
  Assert.assertNotNull(apiResponse);
  Assert.assertEquals("OK", apiResponse.getDescription());
  Content content = apiResponse.getContent();
  Assert.assertEquals(1, content.size());
  Schema schema = content.get("application/vnd.api+json").getSchema();
  Assert.assertEquals(
      "#/components/schemas/ResourceTypeResourceReferencesResponseSchema",
      schema.get$ref()
  );
}
 
Example #23
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testArrayResponse() {
    OpenAPI openAPI = new OpenAPI();


    ObjectSchema objectSchema = new ObjectSchema();
    objectSchema.addProperties("name", new StringSchema());
    ArraySchema schema = new ArraySchema();
    schema.setItems(objectSchema);

    ApiResponse apiResponse = new ApiResponse();
    apiResponse.addExtension("x-foo", "bar");
    apiResponse.setDescription("it works!");
    apiResponse.setContent(new Content().addMediaType("*/*", new MediaType().schema(schema)));

    openAPI.path("/foo/baz", new PathItem()
            .get(new Operation()
                    .responses(new ApiResponses().addApiResponse("200", apiResponse))));

    new InlineModelResolver().flatten(openAPI);

    ApiResponse response = openAPI.getPaths().get("/foo/baz").getGet().getResponses().get("200");
    assertTrue(response.getContent().get("*/*").getSchema() instanceof ArraySchema);

    ArraySchema am = (ArraySchema) response.getContent().get("*/*").getSchema();
    Schema items = am.getItems();
    assertTrue(items.get$ref() != null);

    assertEquals(items.get$ref(), "#/components/schemas/inline_response_200");


    Schema inline = openAPI.getComponents().getSchemas().get("inline_response_200");
    assertTrue(inline instanceof Schema);

    assertNotNull(inline.getProperties().get("name"));
    assertTrue(inline.getProperties().get("name") instanceof StringSchema);
}
 
Example #24
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testInlineMapResponseWithObjectSchema() throws Exception {
    OpenAPI openAPI = new OpenAPI();

    Schema schema = new Schema();
    schema.setAdditionalProperties(new ObjectSchema()
            .addProperties("name", new StringSchema()));
    schema.addExtension("x-ext", "ext-prop");

    ApiResponse apiResponse = new ApiResponse()
            .description("it works!")
            .content(new Content().addMediaType("*/*",new MediaType().schema(schema)));
    apiResponse.addExtension("x-foo", "bar");

    ApiResponses apiResponses = new ApiResponses().addApiResponse("200",apiResponse);

    openAPI.path("/foo/baz", new PathItem()
            .get(new Operation()
                    .responses(apiResponses)));

    new InlineModelResolver().flatten(openAPI);

    ApiResponse response = openAPI.getPaths().get("/foo/baz").getGet().getResponses().get("200");
    Schema property = response.getContent().get("*/*").getSchema();
    assertTrue(property.getAdditionalProperties() != null);
    assertEquals(1, property.getExtensions().size());
    assertEquals("ext-prop", property.getExtensions().get("x-ext"));
    assertTrue(openAPI.getComponents().getSchemas().size() == 1);

    Schema inline = openAPI.getComponents().getSchemas().get("inline_response_map200");
    assertTrue(inline instanceof Schema);
    assertNotNull(inline.getProperties().get("name"));
    assertTrue(inline.getProperties().get("name") instanceof StringSchema);
}
 
Example #25
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue1131() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    final OpenAPI openAPI = new OpenAPIV3Parser().readLocation("issue-837-853-1131/main.yaml", null, options).getOpenAPI();
    Assert.assertNotNull(openAPI);

    Content content = openAPI.getPaths().get("/events").getGet().getRequestBody().getContent();
    Assert.assertNotNull(content);

    Map<String, Example> examples = content.get("application/json").getExamples();
    Assert.assertEquals(examples.size(), 3);
    Assert.assertEquals(((ObjectNode) examples.get("plain").getValue()).get("test").asText(), "plain");
    Assert.assertEquals(examples.get("local").get$ref(), "#/components/examples/LocalRef");
    Assert.assertEquals(examples.get("external").get$ref(), "#/components/examples/ExternalRef");

    // Also cover the case from Issue 853
    Operation post = openAPI.getPaths().get("/guests").getPost();
    Assert.assertNotNull(post);

    content = post.getRequestBody().getContent();
    Assert.assertNotNull(content);

    examples = content.get("application/json").getExamples();
    Assert.assertEquals(examples.size(), 1);
    assertNotNull(openAPI.getComponents());
    assertNotNull(openAPI.getComponents().getExamples());
    assertNotNull(openAPI.getComponents().getExamples().get("testExample"));
    assertEquals(((LinkedHashMap<String, Object>)openAPI.getComponents().getExamples().get("testExample").getValue()).get("test"),"value");
}
 
Example #26
Source File: ResourcesResponseTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
void response() {
  ApiResponse apiResponse = new ResourcesResponse(metaResource).response();
  Assert.assertNotNull(apiResponse);
  Assert.assertEquals("OK", apiResponse.getDescription());
  Content content = apiResponse.getContent();
  Assert.assertEquals(1, content.size());
  Schema schema = content.get("application/vnd.api+json").getSchema();
  Assert.assertEquals(
      "#/components/schemas/ResourceTypeResourcesResponseSchema",
      schema.get$ref()
  );
}
 
Example #27
Source File: BodyParamExtractionTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertComplexArrayBodyParam() 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 Schema().$ref("#/components/schemas/Person")))));



    JavaType jt = utils.getTypeFromRequestBody(body, "application/json" ,definitions)[0];
    assertEquals(jt.getRawClass(), Person[].class);
}
 
Example #28
Source File: BodyParamExtractionTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertComplexBodyParamWithConfigMapping() throws Exception {
    Map<String, Schema> definitions = new HashMap<>();

    RequestBody body = new RequestBody().
            content(new Content()
                    .addMediaType("application/json",new MediaType()
                            .schema(new Schema().$ref("#/components/schema/User"))));

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

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

    RequestBody body = new RequestBody().
            content(new Content()
                    .addMediaType("application/json",new MediaType()
                            .schema(new Schema().$ref("#/components/schemas/Person"))));

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

    // will look up from the config model package and ref.simpleName of Person
    assertEquals(jt.getRawClass(), Person.class);
}
 
Example #30
Source File: BodyParamExtractionTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testUUIDBodyParam() throws Exception {
    Map<String, Schema> definitions = new HashMap<>();

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

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

    assertEquals(jt.getRawClass(), UUID.class);
}