Search in sources :

Example 1 with JaxrsOpenApiContextBuilder

use of io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder 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 2 with JaxrsOpenApiContextBuilder

use of io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder in project swagger-core by swagger-api.

the class SwaggerServletInitializer method onStartup.

@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
    if (classes != null && !classes.isEmpty()) {
        Set<Class<?>> resources = new LinkedHashSet();
        classes.stream().filter(c -> ignored.stream().noneMatch(i -> c.getName().startsWith(i))).forEach(resources::add);
        if (!resources.isEmpty()) {
            // init context
            try {
                SwaggerConfiguration oasConfig = new SwaggerConfiguration().resourceClasses(resources.stream().map(Class::getName).collect(Collectors.toSet()));
                new JaxrsOpenApiContextBuilder().openApiConfiguration(oasConfig).buildContext(true);
            } catch (OpenApiConfigurationException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ServletException(javax.servlet.ServletException) HandlesTypes(javax.servlet.annotation.HandlesTypes) Path(javax.ws.rs.Path) ApplicationPath(javax.ws.rs.ApplicationPath) Set(java.util.Set) Collectors(java.util.stream.Collectors) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) HashSet(java.util.HashSet) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) OpenAPIDefinition(io.swagger.v3.oas.annotations.OpenAPIDefinition) OpenApiConfigurationException(io.swagger.v3.oas.integration.OpenApiConfigurationException) ServletContext(javax.servlet.ServletContext) IgnoredPackages(io.swagger.v3.oas.integration.IgnoredPackages) LinkedHashSet(java.util.LinkedHashSet) OpenApiConfigurationException(io.swagger.v3.oas.integration.OpenApiConfigurationException) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration)

Example 3 with JaxrsOpenApiContextBuilder

use of io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder 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 4 with JaxrsOpenApiContextBuilder

use of io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder in project cxf by apache.

the class OpenApiFeature method initialize.

@Override
public void initialize(Server server, Bus bus) {
    final JAXRSServiceFactoryBean sfb = (JAXRSServiceFactoryBean) server.getEndpoint().get(JAXRSServiceFactoryBean.class.getName());
    final ServerProviderFactory factory = (ServerProviderFactory) server.getEndpoint().get(ServerProviderFactory.class.getName());
    final Set<String> packages = new HashSet<>();
    if (resourcePackages != null) {
        packages.addAll(resourcePackages);
    }
    Properties swaggerProps = null;
    GenericOpenApiContextBuilder<?> openApiConfiguration;
    final Application application = getApplicationOrDefault(server, factory, sfb, bus);
    if (StringUtils.isEmpty(getConfigLocation())) {
        swaggerProps = getSwaggerProperties(propertiesLocation, bus);
        if (isScan()) {
            packages.addAll(scanResourcePackages(sfb));
        }
        final OpenAPI oas = new OpenAPI().info(getInfo(swaggerProps));
        registerComponents(securityDefinitions).ifPresent(oas::setComponents);
        final SwaggerConfiguration config = new SwaggerConfiguration().openAPI(oas).prettyPrint(getOrFallback(isPrettyPrint(), swaggerProps, PRETTY_PRINT_PROPERTY)).readAllResources(isReadAllResources()).ignoredRoutes(getIgnoredRoutes()).filterClass(getOrFallback(getFilterClass(), swaggerProps, FILTER_CLASS_PROPERTY)).resourceClasses(getResourceClasses()).resourcePackages(getOrFallback(packages, swaggerProps, RESOURCE_PACKAGE_PROPERTY));
        openApiConfiguration = new JaxrsOpenApiContextBuilder<>().application(application).openApiConfiguration(config);
    } else {
        openApiConfiguration = new JaxrsOpenApiContextBuilder<>().application(application).configLocation(getConfigLocation());
    }
    try {
        final OpenApiContext context = openApiConfiguration.buildContext(true);
        final Properties userProperties = getUserProperties(context.getOpenApiConfiguration().getUserDefinedOptions());
        registerOpenApiResources(sfb, packages, context.getOpenApiConfiguration());
        registerSwaggerUiResources(sfb, combine(swaggerProps, userProperties), factory, bus);
        if (customizer != null) {
            customizer.setApplicationInfo(factory.getApplicationProvider());
        }
    } catch (OpenApiConfigurationException ex) {
        throw new RuntimeException("Unable to initialize OpenAPI context", ex);
    }
}
Also used : ServerProviderFactory(org.apache.cxf.jaxrs.provider.ServerProviderFactory) OpenApiConfigurationException(io.swagger.v3.oas.integration.OpenApiConfigurationException) Properties(java.util.Properties) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) JAXRSServiceFactoryBean(org.apache.cxf.jaxrs.JAXRSServiceFactoryBean) Application(javax.ws.rs.core.Application) OpenAPI(io.swagger.v3.oas.models.OpenAPI) HashSet(java.util.HashSet) OpenApiContext(io.swagger.v3.oas.integration.api.OpenApiContext)

Example 5 with JaxrsOpenApiContextBuilder

use of io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder in project swagger-core by swagger-api.

the class SwaggerServletInitializer method onStartup.

@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
    if (classes != null && !classes.isEmpty()) {
        Set<Class<?>> resources = new LinkedHashSet();
        classes.stream().filter(c -> ignored.stream().noneMatch(i -> c.getName().startsWith(i))).forEach(resources::add);
        if (!resources.isEmpty()) {
            // init context
            try {
                SwaggerConfiguration oasConfig = new SwaggerConfiguration().resourceClasses(resources.stream().map(Class::getName).collect(Collectors.toSet()));
                new JaxrsOpenApiContextBuilder().openApiConfiguration(oasConfig).buildContext(true);
            } catch (OpenApiConfigurationException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ServletException(javax.servlet.ServletException) HandlesTypes(javax.servlet.annotation.HandlesTypes) Path(javax.ws.rs.Path) ApplicationPath(javax.ws.rs.ApplicationPath) Set(java.util.Set) Collectors(java.util.stream.Collectors) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) HashSet(java.util.HashSet) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) OpenAPIDefinition(io.swagger.v3.oas.annotations.OpenAPIDefinition) JaxrsOpenApiContextBuilder(io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder) OpenApiConfigurationException(io.swagger.v3.oas.integration.OpenApiConfigurationException) ServletContext(javax.servlet.ServletContext) IgnoredPackages(io.swagger.v3.oas.integration.IgnoredPackages) LinkedHashSet(java.util.LinkedHashSet) OpenApiConfigurationException(io.swagger.v3.oas.integration.OpenApiConfigurationException) JaxrsOpenApiContextBuilder(io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration)

Aggregations

OpenApiConfigurationException (io.swagger.v3.oas.integration.OpenApiConfigurationException)5 SwaggerConfiguration (io.swagger.v3.oas.integration.SwaggerConfiguration)5 OpenApiContext (io.swagger.v3.oas.integration.api.OpenApiContext)4 OpenAPI (io.swagger.v3.oas.models.OpenAPI)4 DefaultPrettyPrinter (com.fasterxml.jackson.core.util.DefaultPrettyPrinter)3 OpenAPISpecFilter (io.swagger.v3.core.filter.OpenAPISpecFilter)3 SpecFilter (io.swagger.v3.core.filter.SpecFilter)3 JaxrsOpenApiContextBuilder (io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder)3 HashSet (java.util.HashSet)3 OpenAPIDefinition (io.swagger.v3.oas.annotations.OpenAPIDefinition)2 GenericOpenApiContextBuilder (io.swagger.v3.oas.integration.GenericOpenApiContextBuilder)2 IgnoredPackages (io.swagger.v3.oas.integration.IgnoredPackages)2 LinkedHashSet (java.util.LinkedHashSet)2 Set (java.util.Set)2 Collectors (java.util.stream.Collectors)2 ServletContainerInitializer (javax.servlet.ServletContainerInitializer)2 ServletContext (javax.servlet.ServletContext)2 ServletException (javax.servlet.ServletException)2 HandlesTypes (javax.servlet.annotation.HandlesTypes)2 ApplicationPath (javax.ws.rs.ApplicationPath)2