Search in sources :

Example 6 with SwaggerConfiguration

use of io.swagger.v3.oas.integration.SwaggerConfiguration 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 7 with SwaggerConfiguration

use of io.swagger.v3.oas.integration.SwaggerConfiguration 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 8 with SwaggerConfiguration

use of io.swagger.v3.oas.integration.SwaggerConfiguration 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 9 with SwaggerConfiguration

use of io.swagger.v3.oas.integration.SwaggerConfiguration in project openremote by openremote.

the class ManagerWebService method init.

@Override
public void init(Container container) throws Exception {
    super.init(container);
    String rootRedirectPath = getString(container.getConfig(), ROOT_REDIRECT_PATH, ROOT_REDIRECT_PATH_DEFAULT);
    // Modify swagger object mapper to match ours
    configureObjectMapper(Json.mapper());
    Json.mapper().addMixIn(ServerVariable.class, ServerVariableMixin.class);
    // Add swagger resource
    OpenAPI oas = new OpenAPI().servers(Collections.singletonList(new Server().url("/api/{realm}/").variables(new ServerVariables().addServerVariable("realm", new ServerVariable()._default("master"))))).schemaRequirement("openid", new SecurityScheme().type(SecurityScheme.Type.OAUTH2).flows(new OAuthFlows().authorizationCode(new OAuthFlow().authorizationUrl("/auth/realms/master/protocol/openid-connect/auth").refreshUrl("/auth/realms/master/protocol/openid-connect/token").tokenUrl("/auth/realms/master/protocol/openid-connect/token")))).security(Collections.singletonList(new SecurityRequirement().addList("openid")));
    Info info = new Info().title("OpenRemote Manager REST API").description("This is the documentation for the OpenRemote Manager HTTP REST API.  Please see the [wiki](https://github.com/openremote/openremote/wiki) for more info.").contact(new Contact().email("info@openremote.io")).license(new License().name("AGPL 3.0").url("https://www.gnu.org/licenses/agpl-3.0.en.html"));
    oas.info(info);
    SwaggerConfiguration oasConfig = new SwaggerConfiguration().resourcePackages(Stream.of("org.openremote.model.*").collect(Collectors.toSet())).openAPI(oas);
    OpenApiResource openApiResource = new OpenApiResource();
    openApiResource.openApiConfiguration(oasConfig);
    addApiSingleton(openApiResource);
    initialised = true;
    ResteasyDeployment resteasyDeployment = createResteasyDeployment(container, getApiClasses(), apiSingletons, true);
    // Serve REST API
    HttpHandler apiHandler = createApiHandler(container, resteasyDeployment);
    if (apiHandler != null) {
        // Authenticating requests requires a realm, either we receive this in a header or
        // we extract it (e.g. from request path segment) and set it as a header before
        // processing the request
        HttpHandler baseApiHandler = apiHandler;
        apiHandler = exchange -> {
            String path = exchange.getRelativePath().substring(API_PATH.length());
            Matcher realmSubMatcher = PATTERN_REALM_SUB.matcher(path);
            if (!realmSubMatcher.matches()) {
                exchange.setStatusCode(NOT_FOUND.getStatusCode());
                throw new WebApplicationException(NOT_FOUND);
            }
            // Extract realm from path and push it into REQUEST_HEADER_REALM header
            String realm = realmSubMatcher.group(1);
            // Move the realm from path segment to header
            exchange.getRequestHeaders().put(HttpString.tryFromString(REALM_PARAM_NAME), realm);
            URI url = fromUri(exchange.getRequestURL()).replacePath(realmSubMatcher.group(2)).build();
            exchange.setRequestURI(url.toString(), true);
            exchange.setRequestPath(url.getPath());
            exchange.setRelativePath(url.getPath());
            baseApiHandler.handleRequest(exchange);
        };
    }
    // Serve deployment files unsecured (explicitly map deployment folders to request paths)
    builtInAppDocRoot = Paths.get(getString(container.getConfig(), APP_DOCROOT, APP_DOCROOT_DEFAULT));
    customAppDocRoot = Paths.get(getString(container.getConfig(), CUSTOM_APP_DOCROOT, CUSTOM_APP_DOCROOT_DEFAULT));
    HttpHandler defaultHandler = null;
    if (Files.isDirectory(customAppDocRoot)) {
        HttpHandler customBaseFileHandler = createFileHandler(container, customAppDocRoot, null);
        defaultHandler = exchange -> {
            if (exchange.getRelativePath().isEmpty() || "/".equals(exchange.getRelativePath())) {
                exchange.setRelativePath("/index.html");
            }
            customBaseFileHandler.handleRequest(exchange);
        };
    }
    PathHandler deploymentHandler = defaultHandler != null ? new PathHandler(defaultHandler) : new PathHandler();
    // Serve deployment files
    if (Files.isDirectory(builtInAppDocRoot)) {
        HttpHandler appBaseFileHandler = createFileHandler(container, builtInAppDocRoot, null);
        HttpHandler appFileHandler = exchange -> {
            if (exchange.getRelativePath().isEmpty() || "/".equals(exchange.getRelativePath())) {
                exchange.setRelativePath("/index.html");
            }
            // Reinstate the full path
            exchange.setRelativePath(exchange.getRequestPath());
            appBaseFileHandler.handleRequest(exchange);
        };
        deploymentHandler.addPrefixPath(MANAGER_APP_PATH, appFileHandler);
        deploymentHandler.addPrefixPath(SWAGGER_APP_PATH, appFileHandler);
        deploymentHandler.addPrefixPath(CONSOLE_LOADER_APP_PATH, appFileHandler);
        deploymentHandler.addPrefixPath(SHARED_PATH, appFileHandler);
    }
    // Redirect / to default app
    if (rootRedirectPath != null) {
        getRequestHandlers().add(new RequestHandler("Default app redirect", exchange -> exchange.getRequestPath().equals("/"), exchange -> {
            LOG.finer("Handling root request, redirecting client to default app");
            new RedirectHandler(redirect(exchange, rootRedirectPath)).handleRequest(exchange);
        }));
    }
    if (apiHandler != null) {
        getRequestHandlers().add(pathStartsWithHandler("REST API Handler", API_PATH, apiHandler));
    }
    // This will try and handle any request that makes it to this handler
    getRequestHandlers().add(new RequestHandler("Deployment files", exchange -> true, deploymentHandler));
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Json(io.swagger.v3.core.util.Json) CanonicalPathHandler(io.undertow.server.handlers.CanonicalPathHandler) WebService(org.openremote.container.web.WebService) UriBuilder.fromUri(javax.ws.rs.core.UriBuilder.fromUri) ValueUtil.configureObjectMapper(org.openremote.model.util.ValueUtil.configureObjectMapper) OpenApiResource(io.swagger.v3.jaxrs2.integration.resources.OpenApiResource) ServletInfo(io.undertow.servlet.api.ServletInfo) MapAccess.getString(org.openremote.container.util.MapAccess.getString) HttpString(io.undertow.util.HttpString) RedirectHandler(io.undertow.server.handlers.RedirectHandler) Servlets(io.undertow.servlet.Servlets) HashSet(java.util.HashSet) License(io.swagger.v3.oas.models.info.License) PathHandler(io.undertow.server.handlers.PathHandler) Matcher(java.util.regex.Matcher) ResteasyDeployment(org.jboss.resteasy.spi.ResteasyDeployment) OpenAPI(io.swagger.v3.oas.models.OpenAPI) io.swagger.v3.oas.models.security(io.swagger.v3.oas.models.security) ServerVariables(io.swagger.v3.oas.models.servers.ServerVariables) URI(java.net.URI) Path(java.nio.file.Path) REALM_PARAM_NAME(org.openremote.model.Constants.REALM_PARAM_NAME) Files(java.nio.file.Files) Collection(java.util.Collection) NOT_FOUND(javax.ws.rs.core.Response.Status.NOT_FOUND) Info(io.swagger.v3.oas.models.info.Info) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) HttpServlet30Dispatcher(org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher) HttpHandler(io.undertow.server.HttpHandler) Container(org.openremote.model.Container) IdentityService(org.openremote.container.security.IdentityService) Server(io.swagger.v3.oas.models.servers.Server) Stream(java.util.stream.Stream) Contact(io.swagger.v3.oas.models.info.Contact) Paths(java.nio.file.Paths) ServerVariable(io.swagger.v3.oas.models.servers.ServerVariable) WebApplicationException(javax.ws.rs.WebApplicationException) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) RedirectBuilder.redirect(io.undertow.util.RedirectBuilder.redirect) ServerVariables(io.swagger.v3.oas.models.servers.ServerVariables) HttpHandler(io.undertow.server.HttpHandler) Server(io.swagger.v3.oas.models.servers.Server) WebApplicationException(javax.ws.rs.WebApplicationException) Matcher(java.util.regex.Matcher) RedirectHandler(io.undertow.server.handlers.RedirectHandler) License(io.swagger.v3.oas.models.info.License) CanonicalPathHandler(io.undertow.server.handlers.CanonicalPathHandler) PathHandler(io.undertow.server.handlers.PathHandler) MapAccess.getString(org.openremote.container.util.MapAccess.getString) HttpString(io.undertow.util.HttpString) ServletInfo(io.undertow.servlet.api.ServletInfo) Info(io.swagger.v3.oas.models.info.Info) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) ServerVariable(io.swagger.v3.oas.models.servers.ServerVariable) URI(java.net.URI) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) Contact(io.swagger.v3.oas.models.info.Contact) OpenApiResource(io.swagger.v3.jaxrs2.integration.resources.OpenApiResource) ResteasyDeployment(org.jboss.resteasy.spi.ResteasyDeployment) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Example 10 with SwaggerConfiguration

use of io.swagger.v3.oas.integration.SwaggerConfiguration 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

SwaggerConfiguration (io.swagger.v3.oas.integration.SwaggerConfiguration)16 OpenAPI (io.swagger.v3.oas.models.OpenAPI)11 OpenApiContext (io.swagger.v3.oas.integration.api.OpenApiContext)10 Test (org.testng.annotations.Test)9 GenericOpenApiContext (io.swagger.v3.oas.integration.GenericOpenApiContext)6 Info (io.swagger.v3.oas.models.info.Info)6 OpenApiConfigurationException (io.swagger.v3.oas.integration.OpenApiConfigurationException)5 HashSet (java.util.HashSet)5 DefaultPrettyPrinter (com.fasterxml.jackson.core.util.DefaultPrettyPrinter)4 Reader (io.swagger.v3.jaxrs2.Reader)4 IOException (java.io.IOException)3 Collectors (java.util.stream.Collectors)3 ResourceInPackageA (com.my.project.resources.ResourceInPackageA)2 OpenAPISpecFilter (io.swagger.v3.core.filter.OpenAPISpecFilter)2 SpecFilter (io.swagger.v3.core.filter.SpecFilter)2 JaxrsOpenApiContextBuilder (io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder)2 OpenAPIDefinition (io.swagger.v3.oas.annotations.OpenAPIDefinition)2 GenericOpenApiContextBuilder (io.swagger.v3.oas.integration.GenericOpenApiContextBuilder)2 IgnoredPackages (io.swagger.v3.oas.integration.IgnoredPackages)2 OpenAPIConfiguration (io.swagger.v3.oas.integration.api.OpenAPIConfiguration)2