Search in sources :

Example 36 with Yaml

use of io.swagger.v3.core.util.Yaml in project swagger-core by swagger-api.

the class ReaderTest method testMoreResponses.

@Test(description = "More Responses")
public void testMoreResponses() {
    Reader reader = new Reader(new OpenAPI());
    OpenAPI openAPI = reader.read(EnhancedResponsesResource.class);
    String yaml = "openapi: 3.0.1\n" + "paths:\n" + "  /:\n" + "    get:\n" + "      summary: Simple get operation\n" + "      description: Defines a simple get operation with no inputs and a complex output\n" + "        object\n" + "      operationId: getWithPayloadResponse\n" + "      responses:\n" + "        \"200\":\n" + "          description: voila!\n" + "          content:\n" + "            application/json:\n" + "              schema:\n" + "                $ref: '#/components/schemas/SampleResponseSchema'\n" + "        \"404\":\n" + "          description: not found!\n" + "        \"400\":\n" + "          description: boo\n" + "          content:\n" + "            '*/*':\n" + "              schema:\n" + "                $ref: '#/components/schemas/GenericError'\n" + "      deprecated: true\n" + "components:\n" + "  schemas:\n" + "    GenericError:\n" + "      type: object\n" + "    SampleResponseSchema:\n" + "      type: object\n";
    SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
Also used : OpenAPI(io.swagger.v3.oas.models.OpenAPI) Test(org.testng.annotations.Test)

Example 37 with Yaml

use of io.swagger.v3.core.util.Yaml in project swagger-core by swagger-api.

the class SwaggerMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {
        getLog().info("Skipping OpenAPI specification resolution");
        return;
    }
    getLog().info("Resolving OpenAPI specification..");
    if (project != null) {
        String pEnc = project.getProperties().getProperty("project.build.sourceEncoding");
        if (StringUtils.isNotBlank(pEnc)) {
            projectEncoding = pEnc;
        }
    }
    if (StringUtils.isBlank(encoding)) {
        encoding = projectEncoding;
    }
    // read swagger configuration if one was provided
    Optional<SwaggerConfiguration> swaggerConfiguration = readStructuredDataFromFile(configurationFilePath, SwaggerConfiguration.class, "configurationFilePath");
    // read openApi config, if one was provided
    Optional<OpenAPI> openAPIInput = readStructuredDataFromFile(openapiFilePath, OpenAPI.class, "openapiFilePath");
    config = mergeConfig(openAPIInput.orElse(null), swaggerConfiguration.orElse(new SwaggerConfiguration()));
    setDefaultsIfMissing(config);
    try {
        GenericOpenApiContextBuilder builder = new JaxrsOpenApiContextBuilder().openApiConfiguration(config);
        if (StringUtils.isNotBlank(contextId)) {
            builder.ctxId(contextId);
        }
        OpenApiContext context = builder.buildContext(true);
        OpenAPI openAPI = context.read();
        if (StringUtils.isNotBlank(config.getFilterClass())) {
            try {
                OpenAPISpecFilter filterImpl = (OpenAPISpecFilter) this.getClass().getClassLoader().loadClass(config.getFilterClass()).newInstance();
                SpecFilter f = new SpecFilter();
                openAPI = f.filter(openAPI, filterImpl, new HashMap<>(), new HashMap<>(), new HashMap<>());
            } catch (Exception e) {
                getLog().error("Error applying filter to API specification", e);
                throw new MojoExecutionException("Error applying filter to API specification: " + e.getMessage(), e);
            }
        }
        String openapiJson = null;
        String openapiYaml = null;
        if (Format.JSON.equals(outputFormat) || Format.JSONANDYAML.equals(outputFormat)) {
            if (config.isPrettyPrint() != null && config.isPrettyPrint()) {
                openapiJson = context.getOutputJsonMapper().writer(new DefaultPrettyPrinter()).writeValueAsString(openAPI);
            } else {
                openapiJson = context.getOutputJsonMapper().writeValueAsString(openAPI);
            }
        }
        if (Format.YAML.equals(outputFormat) || Format.JSONANDYAML.equals(outputFormat)) {
            if (config.isPrettyPrint() != null && config.isPrettyPrint()) {
                openapiYaml = context.getOutputYamlMapper().writer(new DefaultPrettyPrinter()).writeValueAsString(openAPI);
            } else {
                openapiYaml = context.getOutputYamlMapper().writeValueAsString(openAPI);
            }
        }
        Path path = Paths.get(outputPath, "temp");
        final File parentFile = path.toFile().getParentFile();
        if (parentFile != null) {
            parentFile.mkdirs();
        }
        if (openapiJson != null) {
            path = Paths.get(outputPath, outputFileName + ".json");
            Files.write(path, openapiJson.getBytes(Charset.forName(encoding)));
            getLog().info("JSON output: " + path.toFile().getCanonicalPath());
        }
        if (openapiYaml != null) {
            path = Paths.get(outputPath, outputFileName + ".yaml");
            Files.write(path, openapiYaml.getBytes(Charset.forName(encoding)));
            getLog().info("YAML output: " + path.toFile().getCanonicalPath());
        }
    } catch (OpenApiConfigurationException e) {
        getLog().error("Error resolving API specification", e);
        throw new MojoFailureException(e.getMessage(), e);
    } catch (IOException e) {
        getLog().error("Error writing API specification", e);
        throw new MojoExecutionException("Failed to write API definition", e);
    } catch (Exception e) {
        getLog().error("Error resolving API specification", e);
        throw new MojoExecutionException(e.getMessage(), e);
    }
}
Also used : DefaultPrettyPrinter(com.fasterxml.jackson.core.util.DefaultPrettyPrinter) Path(java.nio.file.Path) OpenAPISpecFilter(io.swagger.v3.core.filter.OpenAPISpecFilter) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) GenericOpenApiContextBuilder(io.swagger.v3.oas.integration.GenericOpenApiContextBuilder) OpenApiConfigurationException(io.swagger.v3.oas.integration.OpenApiConfigurationException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) IOException(java.io.IOException) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) OpenApiConfigurationException(io.swagger.v3.oas.integration.OpenApiConfigurationException) JaxrsOpenApiContextBuilder(io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder) OpenAPI(io.swagger.v3.oas.models.OpenAPI) File(java.io.File) SpecFilter(io.swagger.v3.core.filter.SpecFilter) OpenAPISpecFilter(io.swagger.v3.core.filter.OpenAPISpecFilter) OpenApiContext(io.swagger.v3.oas.integration.api.OpenApiContext)

Example 38 with Yaml

use of io.swagger.v3.core.util.Yaml in project swagger-core by swagger-api.

the class SwaggerLoader method resolve.

public Map<String, String> resolve() throws Exception {
    Set<String> ignoredRoutesSet = null;
    if (StringUtils.isNotBlank(ignoredRoutes)) {
        ignoredRoutesSet = new HashSet<>(Arrays.asList(ignoredRoutes.split(",")));
    }
    Set<String> resourceClassesSet = null;
    if (StringUtils.isNotBlank(resourceClasses)) {
        resourceClassesSet = new HashSet<>(Arrays.asList(resourceClasses.split(",")));
    }
    Set<String> resourcePackagesSet = null;
    if (StringUtils.isNotBlank(resourcePackages)) {
        resourcePackagesSet = new HashSet<>(Arrays.asList(resourcePackages.split(",")));
    }
    LinkedHashSet<String> modelConverterSet = null;
    if (StringUtils.isNotBlank(modelConverterClasses)) {
        modelConverterSet = new LinkedHashSet<>(Arrays.asList(modelConverterClasses.split(",")));
    }
    OpenAPI openAPIInput = null;
    if (StringUtils.isNotBlank(openapiAsString)) {
        try {
            openAPIInput = Json.mapper().readValue(openapiAsString, OpenAPI.class);
        } catch (Exception e) {
            try {
                openAPIInput = Yaml.mapper().readValue(openapiAsString, OpenAPI.class);
            } catch (Exception e1) {
                throw new Exception("Error reading/deserializing openapi input: " + e.getMessage(), e);
            }
        }
    }
    SwaggerConfiguration config = new SwaggerConfiguration().filterClass(filterClass).ignoredRoutes(ignoredRoutesSet).prettyPrint(prettyPrint).readAllResources(readAllResources).openAPI(openAPIInput).readerClass(readerClass).scannerClass(scannerClass).resourceClasses(resourceClassesSet).resourcePackages(resourcePackagesSet).objectMapperProcessorClass(objectMapperProcessorClass).modelConverterClasses(modelConverterSet).sortOutput(sortOutput).alwaysResolveAppPath(alwaysResolveAppPath);
    try {
        GenericOpenApiContextBuilder builder = new JaxrsOpenApiContextBuilder().openApiConfiguration(config);
        if (StringUtils.isNotBlank(contextId)) {
            builder.ctxId(contextId);
        }
        OpenApiContext context = builder.buildContext(true);
        OpenAPI openAPI = context.read();
        if (StringUtils.isNotBlank(filterClass)) {
            try {
                OpenAPISpecFilter filterImpl = (OpenAPISpecFilter) this.getClass().getClassLoader().loadClass(filterClass).newInstance();
                SpecFilter f = new SpecFilter();
                openAPI = f.filter(openAPI, filterImpl, new HashMap<>(), new HashMap<>(), new HashMap<>());
            } catch (Exception e) {
                throw new Exception("Error applying filter to API specification: " + e.getMessage(), e);
            }
        }
        String openapiJson = null;
        String openapiYaml = null;
        if ("JSON".equals(outputFormat) || "JSONANDYAML".equals(outputFormat)) {
            if (prettyPrint != null && prettyPrint) {
                openapiJson = context.getOutputJsonMapper().writer(new DefaultPrettyPrinter()).writeValueAsString(openAPI);
            } else {
                openapiJson = context.getOutputJsonMapper().writeValueAsString(openAPI);
            }
        }
        if ("YAML".equals(outputFormat) || "JSONANDYAML".equals(outputFormat)) {
            if (prettyPrint != null && prettyPrint) {
                openapiYaml = context.getOutputYamlMapper().writer(new DefaultPrettyPrinter()).writeValueAsString(openAPI);
            } else {
                openapiYaml = context.getOutputYamlMapper().writeValueAsString(openAPI);
            }
        }
        Map<String, String> map = new HashMap<>();
        map.put("JSON", openapiJson);
        map.put("YAML", openapiYaml);
        return map;
    } catch (OpenApiConfigurationException e) {
        throw new Exception("Error resolving API specification: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new Exception("Error resolving API specification: " + e.getMessage(), e);
    }
}
Also used : DefaultPrettyPrinter(com.fasterxml.jackson.core.util.DefaultPrettyPrinter) OpenAPISpecFilter(io.swagger.v3.core.filter.OpenAPISpecFilter) HashMap(java.util.HashMap) GenericOpenApiContextBuilder(io.swagger.v3.oas.integration.GenericOpenApiContextBuilder) OpenApiConfigurationException(io.swagger.v3.oas.integration.OpenApiConfigurationException) OpenApiConfigurationException(io.swagger.v3.oas.integration.OpenApiConfigurationException) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) OpenAPI(io.swagger.v3.oas.models.OpenAPI) SpecFilter(io.swagger.v3.core.filter.SpecFilter) OpenAPISpecFilter(io.swagger.v3.core.filter.OpenAPISpecFilter) OpenApiContext(io.swagger.v3.oas.integration.api.OpenApiContext)

Example 39 with Yaml

use of io.swagger.v3.core.util.Yaml in project cxf by apache.

the class OpenApiCustomizedResource method getOpenApi.

@GET
@Produces({ MediaType.APPLICATION_JSON, "application/yaml" })
@Operation(hidden = true)
public Response getOpenApi(@Context ServletConfig config, @Context HttpHeaders headers, @Context UriInfo uriInfo, @PathParam("type") String type) throws Exception {
    if (customizer != null) {
        final OpenAPIConfiguration configuration = customizer.customize(getOpenApiConfiguration());
        setOpenApiConfiguration(configuration);
        // By default, the OpenApiContext instance is cached. It means that the configuration
        // changes won't be taken into account (due to the deep copying rather than reference
        // passing). In order to reflect any changes which customization may do, we have to
        // update reader's configuration directly.
        final String ctxId = ServletConfigContextUtils.getContextIdFromServletConfig(config);
        final OpenApiContext ctx = OpenApiContextLocator.getInstance().getOpenApiContext(ctxId);
        if (ctx instanceof GenericOpenApiContext<?>) {
            ((GenericOpenApiContext<?>) ctx).getOpenApiReader().setConfiguration(configuration);
            customizer.customize(ctx.read());
        }
    }
    return super.getOpenApi(headers, uriInfo, type);
}
Also used : OpenAPIConfiguration(io.swagger.v3.oas.integration.api.OpenAPIConfiguration) GenericOpenApiContext(io.swagger.v3.oas.integration.GenericOpenApiContext) GenericOpenApiContext(io.swagger.v3.oas.integration.GenericOpenApiContext) OpenApiContext(io.swagger.v3.oas.integration.api.OpenApiContext) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Operation(io.swagger.v3.oas.annotations.Operation)

Example 40 with Yaml

use of io.swagger.v3.core.util.Yaml in project swagger-core by swagger-api.

the class JsonDeserializationTest method deserializeLongSchema.

@Test(description = "it should desserialize Long schema correctly")
public void deserializeLongSchema() throws IOException {
    final String jsonString = ResourceUtils.loadClassResource(getClass(), "specFiles/oas3_2.yaml");
    final OpenAPI swagger = Yaml.mapper().readValue(jsonString, OpenAPI.class);
    assertNotNull(swagger);
    Schema s = swagger.getPaths().get("/withIntegerEnum/{stage}").getGet().getParameters().get(0).getSchema();
    assertEquals(s.getEnum().get(0), 2147483647);
    assertEquals(s.getEnum().get(1), 3147483647L);
    assertEquals(s.getEnum().get(2), 31474836475505055L);
    assertEquals(s.getEnum().get(3), -9223372036854775808L);
}
Also used : ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) Schema(io.swagger.v3.oas.models.media.Schema) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Test(org.testng.annotations.Test)

Aggregations

Test (org.testng.annotations.Test)63 OpenAPI (io.swagger.v3.oas.models.OpenAPI)55 Schema (io.swagger.v3.oas.models.media.Schema)15 Components (io.swagger.v3.oas.models.Components)13 Info (io.swagger.v3.oas.models.info.Info)13 AnnotatedType (io.swagger.v3.core.converter.AnnotatedType)9 OpenAPISpecFilter (io.swagger.v3.core.filter.OpenAPISpecFilter)8 SpecFilter (io.swagger.v3.core.filter.SpecFilter)8 StringSchema (io.swagger.v3.oas.models.media.StringSchema)8 AfterTest (org.testng.annotations.AfterTest)6 OpenApiContext (io.swagger.v3.oas.integration.api.OpenApiContext)5 IntegerSchema (io.swagger.v3.oas.models.media.IntegerSchema)5 Parameter (io.swagger.v3.oas.models.parameters.Parameter)5 DefaultPrettyPrinter (com.fasterxml.jackson.core.util.DefaultPrettyPrinter)4 AbstractSpecFilter (io.swagger.v3.core.filter.AbstractSpecFilter)4 OpenApiConfigurationException (io.swagger.v3.oas.integration.OpenApiConfigurationException)4 ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)4 IOException (java.io.IOException)4 RequestBody (io.swagger.v3.oas.models.parameters.RequestBody)3 ApiResponse (io.swagger.v3.oas.models.responses.ApiResponse)3