io.swagger.v3.core.util.Json Java Examples

The following examples show how to use io.swagger.v3.core.util.Json. 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: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void testInlinedArrayExample() throws Exception {
    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/array-example.yaml");

    ApiResponse response = openAPI.getPaths().get("/").getGet().getResponses().get("200");
    Example example = ExampleBuilder.fromSchema(response.getContent().get("application/json").getSchema(), openAPI.getComponents().getSchemas());

    String output = Json.pretty(example);
    assertEqualsIgnoreLineEnding(output, "[ {\n" +
            "  \"id\" : 1,\n" +
            "  \"name\" : \"Arthur Dent\"\n" +
            "}, {\n" +
            "  \"id\" : 2,\n" +
            "  \"name\" : \"Ford Prefect\"\n" +
            "} ]");
}
 
Example #2
Source File: ResponseSupportConverter.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
	JavaType javaType = Json.mapper().constructType(type.getType());
	if (javaType != null) {
		Class<?> cls = javaType.getRawClass();
		if (isResponseTypeWrapper(cls)) {
			JavaType innerType = javaType.getBindings().getBoundType(0);
			if (innerType == null)
				return new StringSchema();
			else if (innerType.getBindings() != null && isResponseTypeWrapper(innerType.getRawClass())) {
				type = new AnnotatedType(innerType).jsonViewAnnotation(type.getJsonViewAnnotation()).ctxAnnotations(type.getCtxAnnotations()).resolveAsRef(true);
				return this.resolve(type, context, chain);
			}
			else
				type = new AnnotatedType(innerType).jsonViewAnnotation(type.getJsonViewAnnotation()).ctxAnnotations((type.getCtxAnnotations())).resolveAsRef(true);
		}
		else if (isResponseTypeToIgnore(cls))
			return null;
	}
	return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
}
 
Example #3
Source File: SpringDocApp9Test.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void init() throws IllegalAccessException {
	Field convertersField2 = FieldUtils.getDeclaredField(ObjectMapper.class, "_mixIns", true);
	SimpleMixInResolver _mixIns = (SimpleMixInResolver) convertersField2.get(Json.mapper());
	Field convertersField3 = FieldUtils.getDeclaredField(SimpleMixInResolver.class, "_localMixIns", true);
	Map<ClassKey, Class<?>> _localMixIns = (Map<ClassKey, Class<?>>) convertersField3.get(_mixIns);
	Iterator<Map.Entry<ClassKey, Class<?>>> it = _localMixIns.entrySet().iterator();
	while (it.hasNext()) {
		Map.Entry<ClassKey, Class<?>> entry = it.next();
		if (entry.getKey().toString().startsWith("org.springframework")) {
			springMixins.put(entry.getKey(), entry.getValue());
			it.remove();
		}
	}

}
 
Example #4
Source File: V2ConverterTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(description = "Convert schema, property and array examples")
public void testIssue32() throws Exception {
    OpenAPI oas = getConvertedOpenAPIFromJsonFile(ISSUE_32_JSON);
    Map<String, Schema> schemas = oas.getComponents().getSchemas();
    assertNotNull(schemas);
    Map properties = schemas.get(USER_MODEL).getProperties();
    assertNotNull(properties);
    assertEquals(((Schema) properties.get(ID)).getExample(), EXAMPLE_42_NUMBER);
    assertEquals(((Schema) properties.get(NAME)).getExample(), ARTHUR_DENT_NAME);
    assertEquals(((ArraySchema) properties.get(FRIEND_IDS)).getItems().getExample(), EXAMPLE_8_NUMBER);
    final List<Integer> numbers = new ArrayList<>();
    numbers.add(3);
    numbers.add(4);
    numbers.add(5);
    assertEquals(((ArraySchema) properties.get(FRIEND_IDS)).getExample(), numbers);
    assertEquals(Json.mapper().writeValueAsString(schemas.get(ARRAY_OF_USERS_MODEL).getExample()), ARRAY_VALUES);
}
 
Example #5
Source File: ApiClient.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
/**
 * Deserialize the given JSON string to Java object.
 *
 * @param json          The JSON string
 * @param containerType The container type, one of "list", "array" or ""
 * @param cls           The type of the Java object
 * @return The deserialized Java object
 */
public Object deserialize(String json, String containerType, Class cls) throws ApiException {
    if (null != containerType) {
        containerType = containerType.toLowerCase();
    }
    try {
        if ("list".equals(containerType) || "array".equals(containerType)) {
            JavaType typeInfo = Json.mapper().getTypeFactory().constructCollectionType(List.class, cls);
            List response = (List<?>) Json.mapper().readValue(json, typeInfo);
            return response;
        } else if (String.class.equals(cls)) {
            if (json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) {
                return json.substring(1, json.length() - 2);
            } else {
                return json;
            }
        } else {
            return Json.mapper().readValue(json, cls);
        }
    } catch (IOException e) {
        throw new ApiException(500, e.getMessage(), null, json);
    }
}
 
Example #6
Source File: PropertyCustomizer.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
@Override
public Schema customize(Schema property, AnnotatedType type) {
	Annotation[] ctxAnnotations = type.getCtxAnnotations();
	if (ctxAnnotations == null) {
		return property;
	}

	Optional<CustomizedProperty> propertyAnnotation = Stream.of(ctxAnnotations)
			.filter(CustomizedProperty.class::isInstance)
			.findFirst()
			.map(CustomizedProperty.class::cast);

	JavaType javaType = Json.mapper().constructType(type.getType());
	if (javaType.getRawClass().equals(Duration.class)) {
		property = new StringSchema().format("duration").properties(Collections.emptyMap());
	}
	return property;
}
 
Example #7
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue360() {
    OpenAPI openAPI = new OpenAPI();

    Schema model = new Schema();
    model.setEnum((List<String>) null);
    openAPI.components(new Components().addSchemas("modelWithNullEnum", model));

    String json = Json.pretty(openAPI);

    OpenAPIV3Parser parser = new OpenAPIV3Parser();

    SwaggerParseResult result = parser.readContents(json, null, null);
    OpenAPI rebuilt = result.getOpenAPI();
    assertNotNull(rebuilt);
}
 
Example #8
Source File: SpringDocHateoasConfiguration.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Registers an OpenApiCustomiser and a jackson mixin to ensure the definition of `Links` matches the serialized
 * output. This is done because the customer serializer converts the data to a map before serializing it.
 *
 * @param halProvider the hal provider
 * @return the open api customiser
 * @see org.springframework.hateoas.mediatype.hal.Jackson2HalModule.HalLinkListSerializer#serialize(Links, JsonGenerator, SerializerProvider) org.springframework.hateoas.mediatype.hal.Jackson2HalModule.HalLinkListSerializer#serialize(Links, JsonGenerator, SerializerProvider)
 */
@Bean
@ConditionalOnMissingBean
@Lazy(false)
OpenApiCustomiser linksSchemaCustomiser(HateoasHalProvider halProvider) {
	if (!halProvider.isHalEnabled()) {
		return openApi -> {
		};
	}
	Json.mapper().addMixIn(RepresentationModel.class, RepresentationModelLinksOASMixin.class);

	ResolvedSchema resolvedLinkSchema = ModelConverters.getInstance()
			.resolveAsResolvedSchema(new AnnotatedType(Link.class));

	return openApi -> openApi
			.schema("Link", resolvedLinkSchema.schema)
			.schema("Links", new MapSchema()
					.additionalProperties(new StringSchema())
					.additionalProperties(new ObjectSchema().$ref(AnnotationsUtils.COMPONENTS_REF +"Link")));
}
 
Example #9
Source File: ResponseWithExceptionTestIT.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyNonApiException() throws IOException {
    try {
        client.invokeAPI("/throwNonApiException", "GET", new HashMap<String, String>(), null,
                new HashMap<String, String>(), null, null, null, new String[0]);
        Assert.fail("Exception was expected!");
    } catch (ApiException e) {
        final Response.Status expected = Response.Status.INTERNAL_SERVER_ERROR;
        Assert.assertEquals(e.getCode(), expected.getStatusCode());
        final ApiError error = Json.mapper().readValue(e.getMessage(), ApiError.class);
        Assert.assertEquals(error.getCode(), expected.getStatusCode());
        Assert.assertEquals(
                error.getMessage().replaceFirst("\\(ID: [^\\)]+\\)$", "(ID: XXXXXXXX)"),
                "There was an error processing your request. It has been logged (ID: XXXXXXXX)");
    }
}
 
Example #10
Source File: SchemaValidationTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidation() throws Exception {
    String schemaAsString =
            "{\n" +
            "  \"properties\": {\n" +
            "    \"id\": {\n" +
            "      \"type\": \"integer\",\n" +
            "      \"format\": \"int64\"\n" +
            "    }\n" +
            "  }\n" +
            "}";
    JsonNode schemaObject = Json.mapper().readTree(schemaAsString);
    JsonNode content = Json.mapper().readValue("{\n" +
            "  \"id\": 123\n" +
            "}", JsonNode.class);

    JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
    com.github.fge.jsonschema.main.JsonSchema schema = factory.getJsonSchema(schemaObject);

    ProcessingReport report = schema.validate(content);
    assertTrue(report.isSuccess());
}
 
Example #11
Source File: BodyGenerator.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
private String generateFromArraySchema(ArraySchema schema) {
    if (schema.getExample() instanceof String) {
        return (String) schema.getExample();
    }

    if (schema.getExample() instanceof Iterable) {
        try {
            return Json.mapper().writeValueAsString(schema.getExample());
        } catch (JsonProcessingException e) {
            LOG.warn(
                    "Failed to encode Example Object. Falling back to default example generation",
                    e);
        }
    }

    return createJsonArrayWith(generate(schema.getItems()));
}
 
Example #12
Source File: WebFluxSupportConverter.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
	JavaType javaType = Json.mapper().constructType(type.getType());
	if (javaType != null) {
		Class<?> cls = javaType.getRawClass();
		if (isFluxTypeWrapper(cls)) {
			JavaType innerType = javaType.getBindings().getBoundType(0);
			if (innerType == null)
				return new StringSchema();
			else if (innerType.getBindings() != null && isResponseTypeWrapper(innerType.getRawClass())) {
				type = new AnnotatedType(innerType).jsonViewAnnotation(type.getJsonViewAnnotation()).resolveAsRef(true);
				return this.resolve(type, context, chain);
			}
			else {
				ArrayType arrayType = ArrayType.construct(innerType, null);
				type = new AnnotatedType(arrayType).jsonViewAnnotation(type.getJsonViewAnnotation()).resolveAsRef(true);
			}
		}
	}
	return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
}
 
Example #13
Source File: ReflectionUtils.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
private JavaType getTypeFromModelName(String name) {
    final TypeFactory tf = Json.mapper().getTypeFactory();
    // it's legal to have quotes around the model name so trim them
    String modelName = name.replaceAll("^\"|\"$", "");
    Class<?> cls = loadClass(modelName);
    if(cls != null) {
        return tf.constructType(cls);
    }
    if(config.getModelPackage() != null && !modelName.contains(".")) {
        modelName = config.getModelPackage() + "." + modelName;
        cls = loadClass(modelName);
        if (cls != null) {
            return tf.constructType(cls);
        }
    }
    unimplementedMappedModels.add(modelName);
    return null;
}
 
Example #14
Source File: OpenAPIOperationController.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
private void doValidation(Object value, Object schema, SchemaValidator.Direction direction) throws ApiException {
    if (config.getValidatePayloads().isEmpty()) {
        return;
    }
    switch (direction) {
        case INPUT:
            if (config.getValidatePayloads().contains(Configuration.Direction.IN)
                    && !SchemaValidator.validate(value, Json.pretty(schema), direction)) {
                throw new ApiException(new ApiError()
                        .code(config.getInvalidRequestStatusCode())
                        .message("Input does not match the expected structure"));
            }
            break;
        case OUTPUT:
            if (config.getValidatePayloads().contains(Configuration.Direction.OUT)
                    && !SchemaValidator.validate(value, Json.pretty(schema), direction)) {
                throw new ApiException(new ApiError()
                        .code(config.getInvalidRequestStatusCode())
                        .message("The server generated an invalid response"));
            }
            break;
    }
}
 
Example #15
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue127() throws Exception {
    IntegerSchema integerProperty = new IntegerSchema();
    integerProperty.setFormat(null);
    integerProperty.setExample(new Long(4321));
    Schema model = new Schema();
    model.addProperties("unboundedInteger",integerProperty);


    Map<String, Schema> definitions = new HashMap<>();
    definitions.put("Address", model);

    Example rep = ExampleBuilder.fromSchema(new Schema().$ref("Address"), definitions);

    Json.prettyPrint(rep);
    assertEqualsIgnoreLineEnding(Json.pretty(rep),
            "{\n" +
            "  \"unboundedInteger\" : 4321\n" +
            "}");
}
 
Example #16
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void recursiveIssue984() {
    ParseOptions parseOptions = new ParseOptions();
    parseOptions.setResolve(true);
    parseOptions.setResolveFully(true);
    OpenAPI openAPI = new OpenAPIV3Parser().read("issue-984-simple.yaml", null, parseOptions);
    if (openAPI == null) fail("failed parsing issue-984");
    try {
        Json.pretty(openAPI);
        //System.out.println(Json.pretty(openAPI));
    }
    catch (Exception e) {
        e.printStackTrace();
        fail("Recursive loop found");
    }
}
 
Example #17
Source File: JacksonProcessor.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Override
public Object process(MediaType mediaType, InputStream entityStream,
                      JavaType javaType) {
    try {
        if (MediaType.APPLICATION_JSON_TYPE.isCompatible(mediaType)) {
            return Json.mapper().readValue(entityStream, javaType);
        }
        if (MediaType.APPLICATION_XML_TYPE.isCompatible(mediaType)) {
            return XML.readValue(entityStream, javaType);
        }
        if (APPLICATION_YAML_TYPE.isCompatible(mediaType)) {
            return Yaml.mapper().readValue(entityStream, javaType);
        }
    } catch (IOException e) {
        LOGGER.error("unable to extract entity from content-type `" + mediaType + "` to " + javaType.toCanonical(), e);
    }

    return null;
}
 
Example #18
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyAdditionalPropertiesWithArray() throws Exception {
    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/oas3_array.yaml");
    ApiResponse response = openAPI.getPaths().get("/dictionaryOfArray").getGet().getResponses().get("200");

    Example example = ExampleBuilder.fromSchema(response.getContent().get("application/json").getSchema(), openAPI.getComponents().getSchemas(), ExampleBuilder.RequestType.READ);
    String output = Json.pretty(example);
    assertEqualsIgnoreLineEnding(output, "{\n" +
            "  \"additionalProp1\" : [ {\n" +
            "    \"joel\" : \"string\",\n" +
            "    \"prop2\" : 0\n" +
            "  } ],\n" +
            "  \"additionalProp2\" : [ {\n" +
            "    \"joel\" : \"string\",\n" +
            "    \"prop2\" : 0\n" +
            "  } ],\n" +
            "  \"additionalProp3\" : [ {\n" +
            "    \"joel\" : \"string\",\n" +
            "    \"prop2\" : 0\n" +
            "  } ]\n" +
            "}");
}
 
Example #19
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void testDifferentExampleTypes() throws Exception {
    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/example-types.yaml");

    ApiResponse response = openAPI.getPaths().get("/user").getGet().getResponses().get("200");
    Example example = ExampleBuilder.fromSchema(response.getContent().get("application/json").getSchema(), null);

    String output = Json.pretty(example);
    assertEqualsIgnoreLineEnding(output, "{\n" +
            "  \"obj\" : {\n" +
            "    \"b\" : \"ho\",\n" +
            "    \"a\" : \"hey\"\n" +
            "  },\n" +
            "  \"arr\" : [ \"hey\", \"ho\" ],\n" +
            "  \"double\" : 1.2,\n" +
            "  \"int\" : 42,\n" +
            "  \"biginteger\" : 118059162071741130342442,\n" +
            "  \"long\" : 1099511627776,\n" +
            "  \"boolean\" : true,\n" +
            "  \"string\" : \"Arthur Dent\"\n" +
            "}");
}
 
Example #20
Source File: SwaggerConverter.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
private void convertV1ToV2() throws SwaggerException {
    Swagger swagger;
    // convert older spec to v2
    try {
        // Try the older spec
        // Annoyingly the converter only reads files
        File temp = File.createTempFile("openapi", ".defn");
        BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
        bw.write(this.defn);
        bw.close();

        swagger = new SwaggerCompatConverter().read(temp.getAbsolutePath());
        if (!temp.delete()) {
            String msg = "Failed to delete " + temp.getAbsolutePath();
            LOG.warn(msg);
            this.errors.add(msg);
        }
        this.defn = Json.mapper().writerWithDefaultPrettyPrinter().writeValueAsString(swagger);

    } catch (IOException e) {
        throw new SwaggerException(
                Constant.messages.getString(
                        "openapi.swaggerconverter.parse.defn.exception", defn),
                e);
    }
}
 
Example #21
Source File: SwaggerService_TransformTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTransformAPIFromSwaggerV3_json() throws IOException {
    PageEntity pageEntity = getPage("io/gravitee/rest/api/management/service/openapi.json", MediaType.APPLICATION_JSON);

    OAIDescriptor descriptor = (OAIDescriptor) swaggerService.parse(pageEntity.getContent());

    swaggerService.transform(descriptor,
            Collections.singleton(new PageConfigurationOAITransformer(pageEntity)));

    assertNotNull(descriptor.toJson());
    validateV3(Json.mapper().readTree(descriptor.toJson()));
}
 
Example #22
Source File: SwaggerService_ParseTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldParseSwaggerV3_json() throws IOException {
    PageEntity pageEntity = getPage("io/gravitee/rest/api/management/service/openapi.json", MediaType.APPLICATION_JSON);

    SwaggerDescriptor descriptor = swaggerService.parse(pageEntity.getContent());

    assertNotNull(descriptor);
    assertEquals(SwaggerDescriptor.Version.OAI_V3, descriptor.getVersion());
    validateV3(Json.mapper().readTree(descriptor.toJson()));
}
 
Example #23
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 #24
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void allOfExampleGeneration(@Injectable final List<AuthorizationValue> auths) throws JsonProcessingException {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);
    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/resources/simpleAllOf.yaml", null, options);

    Assert.assertNotNull(openAPI);
    Object withoutExample = openAPI.getPaths().get("/foo").getGet().getResponses().get("200").getContent().get("application/json").getSchema().getExample();
    Assert.assertNull(withoutExample);

    Object withExample = openAPI.getPaths().get("/bar").getGet().getResponses().get("200").getContent().get("application/json").getSchema().getExample();
    Assert.assertEquals("{\"someProperty\":\"ABC\",\"someOtherProperty\":42}", Json.mapper().writeValueAsString(withExample));
}
 
Example #25
Source File: SchemaGenerator.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
private static Schema<?> processType(Type type, Path modelsDir) {
    final Map<String, Class<?>> referencedClasses = new HashMap<>();
    final int globalSetSize = globalModelSet.size();

    final Schema<?> schema;
    if (!(type instanceof ParameterizedType)) {
        if (Map.class.isAssignableFrom((Class<?>) type) || Collection.class.isAssignableFrom((Class<?>) type)) {
            schema = processType(type, null, referencedClasses);
        } else {
            schema = createReference((Class<?>) type, null, referencedClasses);
        }
    } else {
        schema = processType(type, null, referencedClasses);
    }

    if (globalSetSize < globalModelSet.size()) {
        referencedClasses.forEach((k, v) -> {
            try {
                final Path modelFile = modelsDir.resolve(k + ".json");
                Files.createDirectories(modelFile.getParent());
                final Schema<?> referencedSchema = processClass(v, modelsDir);
                Files.write(modelFile, Json.mapper().writerWithDefaultPrettyPrinter().writeValueAsBytes(referencedSchema), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
            } catch (IOException e) {
                throw new RuntimeException("Error while create model files", e);
            }
        });
    }

    return schema;
}
 
Example #26
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void recursiveResolving() {
    ParseOptions parseOptions = new ParseOptions();
    parseOptions.setResolveFully(true);
    OpenAPI openAPI = new OpenAPIV3Parser().read("recursive.yaml", null, parseOptions);
    Assert.assertNotNull(openAPI.getPaths().get("/myPath").getGet().getResponses().get("200").getContent().get("application/json").getSchema().getProperties().get("myProp"));
    try {
        Json.mapper().writeValueAsString(openAPI);
    }
    catch (Exception e) {
        fail("Recursive loop found");
    }

}
 
Example #27
Source File: SwaggerService_TransformTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTransformAPIFromSwaggerV1_json() throws IOException {
    PageEntity pageEntity = getPage("io/gravitee/rest/api/management/service/swagger-v1.json", MediaType.APPLICATION_JSON);

    SwaggerV1Descriptor descriptor = (SwaggerV1Descriptor) swaggerService.parse(pageEntity.getContent());

    swaggerService.transform(descriptor,
            Collections.singleton(new PageConfigurationSwaggerV2Transformer(pageEntity)));

    assertNotNull(descriptor.toJson());
    validateV2(Json.mapper().readTree(descriptor.toJson()));
}
 
Example #28
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void recursiveResolving2() {
    ParseOptions parseOptions = new ParseOptions();
    parseOptions.setResolve(true);
    parseOptions.setResolveFully(true);
    OpenAPI openAPI = new OpenAPIV3Parser().read("recursive2.yaml", null, parseOptions);
    try {
        Json.mapper().writeValueAsString(openAPI);
    }
    catch (Exception e) {
        fail("Recursive loop found");
    }
}
 
Example #29
Source File: JacksonProcessor.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Override
public Object process(MediaType mediaType, InputStream entityStream, Class<?> cls) throws ConversionException {
    try {
        if(String.class.equals(cls)) {
            OutputStream outputStream = new ByteArrayOutputStream();
            IOUtils.copy(entityStream, outputStream);
            return outputStream.toString();
        }
        if (MediaType.APPLICATION_JSON_TYPE.isCompatible(mediaType)) {
            return Json.mapper().readValue(entityStream, cls);
        }
        if (MediaType.APPLICATION_XML_TYPE.isCompatible(mediaType)) {
            return XML.readValue(entityStream, cls);
        }
        if (APPLICATION_YAML_TYPE.isCompatible(mediaType)) {
            return Yaml.mapper().readValue(entityStream, cls);
        }
    } catch (Exception e) {
        LOGGER.trace("unable to extract entity from content-type `" + mediaType + "` to " + cls.getCanonicalName(), e);
        throw new ConversionException()
                .message(new ValidationMessage()
                        .code(ValidationError.UNACCEPTABLE_VALUE)
                        .message("unable to convert input to " + cls.getCanonicalName()));
    }

    return null;
}
 
Example #30
Source File: ResponseModelTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testComplexModel() throws Exception {
    Schema property = new Schema().$ref("User");
    Map<String, Schema> definitions = ModelConverters.getInstance().readAll(User.class);
    Object o = ExampleBuilder.fromSchema(property, definitions);

    ObjectExample n = Json.mapper().convertValue(o, ObjectExample.class);
    assertNotNull(n);
}