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

The following examples show how to use io.swagger.v3.core.util.Yaml. 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: JsonToYamlFileDuplicator.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
private static void processFile(File next, Path inputDirectory, Path outputDirectory) {
    try {
        String fileContents = IOUtils.toString(new FileInputStream(next));
        fileContents = fileContents.replaceAll("\\.json", ".yaml");

        final JsonNode jsonNode = DeserializationUtils.deserializeIntoTree(fileContents, next.toString());

        final String yamlOutput = Yaml.mapper().writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode)
                .replaceAll("\\n", System.getProperty("line.separator"));

        final String relativePath = "./" + next.toString().replace(inputDirectory.toString(), "").replace(".json", ".yaml");

        final Path outputFile = outputDirectory.resolve(relativePath).normalize();
        LOGGER.debug("output file: " + outputFile);

        final File file = outputFile.toAbsolutePath().toFile();
        FileUtils.forceMkdir(outputFile.getParent().toFile());
        FileUtils.write(file, yamlOutput);

    } catch (IOException e) {
        throw new RuntimeException("Could not process file " + next, e);
    }

}
 
Example #2
Source File: SerializerUtils.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public static String toYamlString(OpenAPI openAPI) {
    if (openAPI == null) {
        return null;
    }
    SimpleModule module = createModule();
    try {
        ObjectMapper yamlMapper = Yaml.mapper().copy();
        // there is an unfortunate YAML condition where user inputs should be treated as strings (e.g. "1234_1234"), but in yaml this is a valid number and
        // removing quotes forcibly by default means we are potentially doing a data conversion resulting in an unexpected change to the user's YAML outputs.
        // We may allow for property-based enable/disable, retaining the default of enabled for backward compatibility.
        if (minimizeYamlQuotes) {
            ((YAMLFactory) yamlMapper.getFactory()).enable(YAMLGenerator.Feature.MINIMIZE_QUOTES);
        } else {
            ((YAMLFactory) yamlMapper.getFactory()).disable(YAMLGenerator.Feature.MINIMIZE_QUOTES);
        }
        return yamlMapper.registerModule(module)
                .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
                .writeValueAsString(openAPI)
                .replace("\r\n", "\n");
    } catch (JsonProcessingException e) {
        LOGGER.warn("Can not create yaml content", e);
    }
    return null;
}
 
Example #3
Source File: CodegenConfigurator.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private static DynamicSettings readDynamicSettings(String configFile, Module... modules) {
    ObjectMapper mapper;

    if (FilenameUtils.isExtension(configFile.toLowerCase(Locale.ROOT), new String[]{"yml", "yaml"})) {
        mapper = Yaml.mapper().copy();
    } else {
        mapper = Json.mapper().copy();
    }

    if (modules != null && modules.length > 0) {
        mapper.registerModules(modules);
    }

    mapper.registerModule(new GuavaModule());

    try {
        return mapper.readValue(new File(configFile), DynamicSettings.class);
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage());
        throw new RuntimeException("Unable to deserialize config file: " + configFile);
    }
}
 
Example #4
Source File: DeserializationUtils.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public static <T> T deserialize(Object contents, String fileOrHost, Class<T> expectedType) {
    T result;

    boolean isJson = false;

    if(contents instanceof String && isJson((String)contents)) {
        isJson = true;
    }

    try {
        if (contents instanceof String) {
            if (isJson) {
                result = Json.mapper().readValue((String) contents, expectedType);
            } else {
                result = Yaml.mapper().readValue((String) contents, expectedType);
            }
        } else {
            result = Json.mapper().convertValue(contents, expectedType);
        }
    } catch (Exception e) {
        throw new RuntimeException("An exception was thrown while trying to deserialize the contents of " + fileOrHost + " into type " + expectedType, e);
    }

    return result;
}
 
Example #5
Source File: SwaggerConverter.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
private SwaggerParseResult readResult(SwaggerDeserializationResult result, List<AuthorizationValue> auth, ParseOptions options) {
    SwaggerParseResult out = convert(result);
    if (out != null && options != null && options.isFlatten()) {
        try {
            SwaggerParseResult resultV3 = new OpenAPIV3Parser().readContents(Yaml.pretty(out.getOpenAPI()), auth, options);
            out.setOpenAPI(resultV3.getOpenAPI());
            if (out.getMessages() != null) {
                out.getMessages().addAll(resultV3.getMessages());
                out.messages(out.getMessages().stream()
                        .distinct()
                        .collect(Collectors.toList()));
            } else {
                out.messages(resultV3.getMessages());
            }
        } catch (Exception ignore) {}
    }
    return out;
}
 
Example #6
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 #7
Source File: OpenApiResource.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Openapi yaml string.
 *
 * @param request the request
 * @param apiDocsUrl the api docs url
 * @return the string
 * @throws JsonProcessingException the json processing exception
 */
@Operation(hidden = true)
@GetMapping(value = DEFAULT_API_DOCS_URL_YAML, produces = APPLICATION_OPENAPI_YAML)
public String openapiYaml(HttpServletRequest request, @Value(DEFAULT_API_DOCS_URL_YAML) String apiDocsUrl)
		throws JsonProcessingException {
	calculateServerUrl(request, apiDocsUrl);
	OpenAPI openAPI = this.getOpenApi();
	if (!springDocConfigProperties.isWriterWithDefaultPrettyPrinter())
		return Yaml.mapper().writeValueAsString(openAPI);
	else
		return Yaml.mapper().writerWithDefaultPrettyPrinter().writeValueAsString(openAPI);
}
 
Example #8
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_yaml() throws IOException {
    PageEntity pageEntity = getPage("io/gravitee/rest/api/management/service/openapi.yaml", MediaType.TEXT_PLAIN);

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

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

    assertNotNull(descriptor.toYaml());
    validateV3(Yaml.mapper().readTree(descriptor.toYaml()));
}
 
Example #9
Source File: SwaggerConverter.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private OpenAPI parseV2(ParseOptions options) {
    OpenAPI openAPI;
    try {
        openAPI = new OpenAPIParser().readContents(this.defn, null, options).getOpenAPI();
        // parse again to resolve refs , may be there is a cleaner way
        String string =
                Yaml.mapper().writerWithDefaultPrettyPrinter().writeValueAsString(openAPI);
        openAPI = new OpenAPIV3Parser().readContents(string, null, options).getOpenAPI();
    } catch (JsonProcessingException e) {
        LOG.warn(e.getMessage());
        openAPI = null;
    }
    return openAPI;
}
 
Example #10
Source File: OpenAPIInflector.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
private ObjectMapper getRightMapper(String data) {
    ObjectMapper mapper;
    if (data.trim().startsWith("{")) {
        mapper = Json.mapper();
    } else {
        mapper = Yaml.mapper();
    }

    return mapper;
}
 
Example #11
Source File: YamlExampleProvider.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(Example data,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> headers,
                    OutputStream out) throws IOException {
  if (mediaType.toString().startsWith("application/yaml")) {
      headers.remove("Content-Type");
      headers.add("Content-Type", "application/yaml");
      out.write(Yaml.mapper().writeValueAsString(data).getBytes("utf-8"));
  }
}
 
Example #12
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 #13
Source File: Configuration.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
public static Configuration read(String configLocation) throws Exception {
    Configuration config = Yaml.mapper().readValue(new File(configLocation), Configuration.class);
    if(config != null && config.getExceptionMappers().size() == 0) {
        config.setExceptionMappers(Configuration.defaultConfiguration().getExceptionMappers());
    }
    String environment = System.getProperty("environment");
    if(environment != null) {
        System.out.println("Overriding environment to " + environment);
        config.setEnvironment(Environment.valueOf(environment));
    }
    return config;
}
 
Example #14
Source File: DirectionDeserializerTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromArray() throws Exception {
    try (InputStream in = DirectionDeserializerTest.class.getResourceAsStream(
            "validation-as-set.yaml")) {
        final Holder holder = Yaml.mapper().readValue(in, Holder.class);
        Assert.assertEquals(holder.getValue(), EnumSet.of(Configuration.Direction.IN));
    }
}
 
Example #15
Source File: DirectionDeserializerTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = BOOLEAN)
public void testFromBoolean(String source,
        Set<Configuration.Direction> expected) throws Exception {
    try (InputStream in = DirectionDeserializerTest.class.getResourceAsStream(source)) {
        final Holder holder = Yaml.mapper().readValue(in, Holder.class);
        Assert.assertEquals(holder.getValue(), expected);
    }
}
 
Example #16
Source File: SwaggerListingIT.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
private OpenAPI getYamlSwagger() throws Exception {
    ApiClient client = new ApiClient();

    String str = client.invokeAPI("swagger/openapi.yaml", "GET", new HashMap<String, String>(), null, new HashMap<String, String>(), null, "application/yaml", null, new String[0]);
    LoggerFactory.getLogger(this.getClass().getName()).error("TEST string\n" + str);
    return Yaml.mapper().readValue(str, OpenAPI.class);
}
 
Example #17
Source File: ResponseExamplesTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseYamlExample(@Injectable final List<io.swagger.v3.parser.core.models.AuthorizationValue> auths) throws Exception {

    Configuration config = new Configuration();
    List<String> exampleProcessor = new ArrayList<>();
    exampleProcessor.add("random");
    config.setExampleProcessors(exampleProcessor);
    ParseOptions options = new ParseOptions();
    options.setResolve(true);

    OpenAPI openAPI = new OpenAPIV3Parser().readLocation( "src/test/swagger/oas3.yaml",auths, options).getOpenAPI();
    Operation operation = openAPI.getPaths().get( "/mockResponses/responseWithExamples").getGet();

    OpenAPIOperationController controller = new OpenAPIOperationController(
        config, "/mockResponses/responseWithExamples", "GET", operation,"" ,openAPI.getComponents().getSchemas());

    ContainerRequestContext requestContext = mock(ContainerRequestContext.class);
    UriInfo uriInfo = mock( UriInfo.class );

    stub( uriInfo.getPath()).toReturn( "/mockResponses/responseWithExamples");
    stub( uriInfo.getQueryParameters()).toReturn( new MultivaluedHashMap<String, String>());
    stub( uriInfo.getPathParameters()).toReturn( new MultivaluedHashMap<String, String>());

    stub( requestContext.getAcceptableMediaTypes()).toReturn(Arrays.asList(MediaType.valueOf("application/yaml")));
    stub( requestContext.getHeaders()).toReturn( new MultivaluedHashMap<String, String>());
    stub( requestContext.getUriInfo()).toReturn( uriInfo );

    Response response = controller.apply( requestContext );

    assertEquals( 200, response.getStatus() );
    assertEqualsIgnoreLineEnding(  Yaml.mapper().writeValueAsString(response.getEntity()), "value:  test: yamlvalue");
}
 
Example #18
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadRelativeFileTree_Yaml() throws Exception {
    JsonToYamlFileDuplicator.duplicateFilesInYamlFormat("src/test/resources/relative-file-references/json",
            "src/test/resources/relative-file-references/yaml");
    final OpenAPI openAPI = doRelativeFileTest("src/test/resources/relative-file-references/yaml/parent.yaml");

    assertNotNull(Yaml.mapper().writeValueAsString(openAPI));
}
 
Example #19
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test(description = "A string example should not be over quoted when parsing a yaml node")
public void readingSpecNodeShouldNotOverQuotingStringExample() throws Exception {
    String yaml = Files.readFile(new File("src/test/resources/over-quoted-example.yaml"));
    JsonNode rootNode = Yaml.mapper().readValue(yaml, JsonNode.class);
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    OpenAPI openAPI = (parser.parseJsonNode(null, rootNode)).getOpenAPI();

    Map<String, Schema> definitions = openAPI.getComponents().getSchemas();
    assertEquals("NoQuotePlease", definitions.get("CustomerType").getExample());
}
 
Example #20
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_yaml() throws IOException {
    PageEntity pageEntity = getPage("io/gravitee/rest/api/management/service/openapi.yaml", MediaType.TEXT_PLAIN);

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

    assertNotNull(descriptor);
    assertEquals(SwaggerDescriptor.Version.OAI_V3, descriptor.getVersion());
    validateV3(Yaml.mapper().readTree(descriptor.toYaml()));
}
 
Example #21
Source File: OpenApiResource.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Openapi yaml mono.
 *
 * @param serverHttpRequest the server http request
 * @param apiDocsUrl the api docs url
 * @return the mono
 * @throws JsonProcessingException the json processing exception
 */
@Operation(hidden = true)
@GetMapping(value = DEFAULT_API_DOCS_URL_YAML, produces = APPLICATION_OPENAPI_YAML)
public Mono<String> openapiYaml(ServerHttpRequest serverHttpRequest,
		@Value(DEFAULT_API_DOCS_URL_YAML) String apiDocsUrl) throws JsonProcessingException {
	calculateServerUrl(serverHttpRequest, apiDocsUrl);
	OpenAPI openAPI = this.getOpenApi();
	if (!springDocConfigProperties.isWriterWithDefaultPrettyPrinter())
		return Mono.just(Yaml.mapper().writeValueAsString(openAPI));
	else
		return Mono.just(Yaml.mapper().writerWithDefaultPrettyPrinter().writeValueAsString(openAPI));
}
 
Example #22
Source File: DynamicSettingsTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void tesDynamicSettingsWithDynamicProperties() throws Exception {
    ObjectMapper mapper = Yaml.mapper();
    mapper.registerModule(new GuavaModule());

    String spec =
            "gemName: 'petstore'" + System.lineSeparator() +
            "moduleName: 'Petstore'" + System.lineSeparator() +
            "gemVersion: '1.0.0'" + System.lineSeparator() +
            "apiPackage: 'testing'" + System.lineSeparator();

    DynamicSettings dynamicSettings = mapper.readValue(spec, DynamicSettings.class);
    GeneratorSettings generatorSettings = dynamicSettings.getGeneratorSettings();
    WorkflowSettings workflowSettings = dynamicSettings.getWorkflowSettings();

    assertNotNull(dynamicSettings);
    assertNotNull(generatorSettings);
    assertNotNull(workflowSettings);

    assertEquals(generatorSettings.getApiPackage(), "testing");
    assertEquals(generatorSettings.getAdditionalProperties().size(), 8);
    assertEquals(generatorSettings.getAdditionalProperties().get("gemName"), "petstore");
    assertEquals(generatorSettings.getAdditionalProperties().get("moduleName"), "Petstore");
    assertEquals(generatorSettings.getAdditionalProperties().get("gemVersion"), "1.0.0");
    assertEquals(generatorSettings.getAdditionalProperties().get("apiPackage"), "testing");
    assertEquals(generatorSettings.getAdditionalProperties().get("gitHost"), "github.com");
    assertEquals(generatorSettings.getAdditionalProperties().get("gitUserId"), "GIT_USER_ID");
    assertEquals(generatorSettings.getAdditionalProperties().get("gitRepoId"), "GIT_REPO_ID");
    assertEquals(generatorSettings.getAdditionalProperties().get("releaseNote"), "Minor update");
}
 
Example #23
Source File: DynamicSettingsTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testDynamicSettingsWithBuilderSideEffects() throws Exception {
    ObjectMapper mapper = Yaml.mapper();
    mapper.registerModule(new GuavaModule());

    // example here is that templateDir is intended to provide the _full_ absolute path
    String input = ".";
    File current = new File(input);

    // sanity
    assertTrue(current.exists());
    assertTrue(current.isDirectory());

    String spec =
            "generatorName: none" + System.lineSeparator() +
            "templateDir: '" + input + "'" + System.lineSeparator();

    DynamicSettings dynamicSettings = mapper.readValue(spec, DynamicSettings.class);
    GeneratorSettings generatorSettings = dynamicSettings.getGeneratorSettings();
    WorkflowSettings workflowSettings = dynamicSettings.getWorkflowSettings();

    assertNotNull(dynamicSettings);
    assertNotNull(generatorSettings);
    assertNotNull(workflowSettings);

    assertEquals(generatorSettings.getGeneratorName(), "none");
    assertEquals(workflowSettings.getTemplateDir(), current.getAbsolutePath());
    assertNotEquals(workflowSettings.getTemplateDir(), input);

    assertEquals(generatorSettings.getAdditionalProperties().size(), 4);
    assertEquals(generatorSettings.getAdditionalProperties().get("gitHost"), "github.com");
    assertEquals(generatorSettings.getAdditionalProperties().get("gitUserId"), "GIT_USER_ID");
    assertEquals(generatorSettings.getAdditionalProperties().get("gitRepoId"), "GIT_REPO_ID");
    assertEquals(generatorSettings.getAdditionalProperties().get("releaseNote"), "Minor update");
}
 
Example #24
Source File: DynamicSettingsTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testDynamicSettingsSetsConstructorDefaultsOnDeserialization() throws Exception {
    ObjectMapper mapper = Yaml.mapper();
    mapper.registerModule(new GuavaModule());

    String gitHost = "test.com";
    String gitUserId = "openapitools";
    String spec =
            "supportPython2: true" + System.lineSeparator() +
            "gitHost: '" + gitHost + "'" + System.lineSeparator() +
            "gitUserId: '" + gitUserId + "'" + System.lineSeparator();

    DynamicSettings dynamicSettings = mapper.readValue(spec, DynamicSettings.class);
    GeneratorSettings generatorSettings = dynamicSettings.getGeneratorSettings();
    WorkflowSettings workflowSettings = dynamicSettings.getWorkflowSettings();

    assertNotNull(dynamicSettings);
    assertNotNull(generatorSettings);
    assertNotNull(workflowSettings);

    assertEquals(generatorSettings.getGitHost(), gitHost);
    assertEquals(generatorSettings.getGitUserId(), gitUserId);
    assertEquals(generatorSettings.getGitRepoId(), "GIT_REPO_ID");
    assertEquals(generatorSettings.getReleaseNote(), "Minor update");

    assertEquals(generatorSettings.getAdditionalProperties().size(), 5);
    assertEquals(generatorSettings.getAdditionalProperties().get("supportPython2"), true);
    assertEquals(generatorSettings.getAdditionalProperties().get("gitHost"), gitHost);
    assertEquals(generatorSettings.getAdditionalProperties().get("gitUserId"), gitUserId);
    assertEquals(generatorSettings.getAdditionalProperties().get("gitRepoId"), "GIT_REPO_ID");
    assertEquals(generatorSettings.getAdditionalProperties().get("releaseNote"), "Minor update");
}
 
Example #25
Source File: CodeGenerator.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
/**
 * Save the openAPI definition created from the services included in the .proto files.
 *
 * @param projectName projectName
 * @param openAPI {@link OpenAPI} object corresponding to the gRPC service
 */
private void createProtoOpenAPIFile(String projectName, OpenAPI openAPI) {
    String protoOpenAPIDirPath =  CmdUtils.getProjectTargetGenGrpcSrcOpenAPIsDirectory(projectName);
    String fileName = openAPI.getInfo().getTitle() + "_" +
            openAPI.getInfo().getVersion().replace(".", "_") + CliConstants.YAML_EXTENSION;
    String protoOpenAPIFilePath =  protoOpenAPIDirPath + File.separator + fileName;
    try {
        CmdUtils.createFile(protoOpenAPIDirPath, fileName, true);
        CmdUtils.writeContent(Yaml.pretty(openAPI), new File(protoOpenAPIFilePath));
    } catch (IOException e) {
        throw new CLIInternalException("Error while writing openAPI files to the directory: " +
                protoOpenAPIDirPath + ".");
    }
}
 
Example #26
Source File: OpenAPIService.java    From proteus with Apache License 2.0 5 votes vote down vote up
public OpenAPIService()
{
	mapper = Json.mapper();

	mapper.registerModule(new Jdk8Module());

	yamlMapper = Yaml.mapper();
	writer = Yaml.pretty();
}
 
Example #27
Source File: OpenApiResource.java    From aries-jax-rs-whiteboard with Apache License 2.0 5 votes vote down vote up
@GET
@Produces({MediaType.APPLICATION_JSON, "application/yaml"})
@Operation(hidden = true)
public Response getOpenApi(@Context HttpHeaders headers,
                           @Context UriInfo uriInfo,
                           @PathParam("type") String type) throws Exception {

    String ctxId = app.getClass().getCanonicalName()
        .concat("#").concat(String.valueOf(System.identityHashCode(app)));

    OpenApiContext ctx = new JaxrsOpenApiContextBuilder<>()
        .servletConfig(config)
        .application(app)
        .configLocation(configLocation)
        .openApiConfiguration(openApiConfiguration)
        .ctxId(ctxId)
        .buildContext(true);

    ctx.setOpenApiScanner(new JaxrsWhiteboardScanner(applicationClasses));

    OpenAPI oas = ctx.read();

    if (oas == null) {
        return Response.status(404).build();
    }

    boolean pretty = Optional.ofNullable(ctx.getOpenApiConfiguration()).map(OpenAPIConfiguration::isPrettyPrint).orElse(Boolean.FALSE);

    if (Optional.ofNullable(type).map(String::trim).map("yaml"::equalsIgnoreCase).orElse(Boolean.FALSE)) {
        return Response.status(Response.Status.OK)
              .entity(pretty ? Yaml.pretty(oas) : Yaml.mapper().writeValueAsString(oas))
              .type("application/yaml")
              .build();
    } else {
        return Response.status(Response.Status.OK)
              .entity(pretty ? Json.pretty(oas) : Json.mapper().writeValueAsString(oas))
              .type(MediaType.APPLICATION_JSON_TYPE)
              .build();
    }
}
 
Example #28
Source File: SwaggerService_ParseTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldParseSwaggerV2_yaml() throws IOException {
    PageEntity pageEntity = getPage("io/gravitee/rest/api/management/service/swagger-v2.yaml", MediaType.TEXT_PLAIN);

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

    assertNotNull(descriptor);
    assertEquals(SwaggerDescriptor.Version.SWAGGER_V2, descriptor.getVersion());
    validateV2(Yaml.mapper().readTree(descriptor.toYaml()));
}
 
Example #29
Source File: SwaggerService_TransformTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTransformAPIFromSwaggerV2_yaml() throws IOException {
    PageEntity pageEntity = getPage("io/gravitee/rest/api/management/service/swagger-v2.yaml", MediaType.TEXT_PLAIN);

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

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

    assertNotNull(descriptor.toYaml());
    validateV2(Yaml.mapper().readTree(descriptor.toYaml()));
}
 
Example #30
Source File: OpenAPIGeneratorTestBase.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
@Before
public void resetYamlSingleton() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
   Field instance = Yaml.class.getDeclaredField("mapper");
   instance.setAccessible(true);
   instance.set(null, null);
}