Search in sources :

Example 11 with SwaggerConfiguration

use of io.swagger.v3.oas.integration.SwaggerConfiguration in project swagger-core by swagger-api.

the class GenericOpenApiContext method init.

@Override
public T init() throws OpenApiConfigurationException {
    if (openApiConfiguration == null) {
        openApiConfiguration = loadConfiguration();
    }
    if (openApiConfiguration == null) {
        openApiConfiguration = new SwaggerConfiguration().resourcePackages(resourcePackages).resourceClasses(resourceClasses);
        ((SwaggerConfiguration) openApiConfiguration).setId(id);
        ((SwaggerConfiguration) openApiConfiguration).setOpenAPI31(openAPI31);
    }
    openApiConfiguration = mergeParentConfiguration(openApiConfiguration, parent);
    try {
        if (openApiReader == null) {
            openApiReader = buildReader(ContextUtils.deepCopy(openApiConfiguration));
        }
        if (openApiScanner == null) {
            openApiScanner = buildScanner(ContextUtils.deepCopy(openApiConfiguration));
        }
        if (objectMapperProcessor == null) {
            objectMapperProcessor = buildObjectMapperProcessor(ContextUtils.deepCopy(openApiConfiguration));
        }
        if (modelConverters == null || modelConverters.isEmpty()) {
            modelConverters = buildModelConverters(ContextUtils.deepCopy(openApiConfiguration));
        }
        if (outputJsonMapper == null) {
            if (Boolean.TRUE.equals(openApiConfiguration.isOpenAPI31())) {
                outputJsonMapper = Json31.mapper().copy();
            } else {
                outputJsonMapper = Json.mapper().copy();
            }
        }
        if (outputYamlMapper == null) {
            if (Boolean.TRUE.equals(openApiConfiguration.isOpenAPI31())) {
                outputYamlMapper = Yaml31.mapper().copy();
            } else {
                outputYamlMapper = Yaml.mapper().copy();
            }
        }
        if (openApiConfiguration.isSortOutput() != null && openApiConfiguration.isSortOutput()) {
            outputJsonMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
            outputJsonMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
            outputYamlMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
            outputYamlMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
            if (Boolean.TRUE.equals(openApiConfiguration.isOpenAPI31())) {
                outputJsonMapper.addMixIn(OpenAPI.class, SortedOpenAPIMixin31.class);
                outputJsonMapper.addMixIn(Schema.class, SortedSchemaMixin31.class);
                outputYamlMapper.addMixIn(OpenAPI.class, SortedOpenAPIMixin31.class);
                outputYamlMapper.addMixIn(Schema.class, SortedSchemaMixin31.class);
            } else {
                outputJsonMapper.addMixIn(OpenAPI.class, SortedOpenAPIMixin.class);
                outputJsonMapper.addMixIn(Schema.class, SortedSchemaMixin.class);
                outputYamlMapper.addMixIn(OpenAPI.class, SortedOpenAPIMixin.class);
                outputYamlMapper.addMixIn(Schema.class, SortedSchemaMixin.class);
            }
        }
    } catch (Exception e) {
        LOGGER.error("error initializing context: " + e.getMessage(), e);
        throw new OpenApiConfigurationException("error initializing context: " + e.getMessage(), e);
    }
    try {
        if (objectMapperProcessor != null) {
            ObjectMapper mapper = IntegrationObjectMapperFactory.createJson();
            objectMapperProcessor.processJsonObjectMapper(mapper);
            ModelConverters.getInstance().addConverter(new ModelResolver(mapper));
            objectMapperProcessor.processOutputJsonObjectMapper(outputJsonMapper);
            objectMapperProcessor.processOutputYamlObjectMapper(outputYamlMapper);
        }
    } catch (Exception e) {
        LOGGER.error("error configuring objectMapper: " + e.getMessage(), e);
        throw new OpenApiConfigurationException("error configuring objectMapper: " + e.getMessage(), e);
    }
    try {
        if (modelConverters != null && !modelConverters.isEmpty()) {
            for (ModelConverter converter : modelConverters) {
                ModelConverters.getInstance().addConverter(converter);
            }
        }
    } catch (Exception e) {
        LOGGER.error("error configuring model converters: " + e.getMessage(), e);
        throw new OpenApiConfigurationException("error configuring model converters: " + e.getMessage(), e);
    }
    // set cache TTL if present in configuration
    if (openApiConfiguration.getCacheTTL() != null) {
        this.cacheTTL = openApiConfiguration.getCacheTTL();
    }
    register();
    return (T) this;
}
Also used : IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ModelConverter(io.swagger.v3.core.converter.ModelConverter) ModelResolver(io.swagger.v3.core.jackson.ModelResolver)

Example 12 with SwaggerConfiguration

use of io.swagger.v3.oas.integration.SwaggerConfiguration in project swagger-core by swagger-api.

the class GenericOpenApiContext method mergeParentConfiguration.

private OpenAPIConfiguration mergeParentConfiguration(OpenAPIConfiguration config, OpenApiContext parent) {
    if (parent == null || parent.getOpenApiConfiguration() == null) {
        return config;
    }
    OpenAPIConfiguration parentConfig = parent.getOpenApiConfiguration();
    SwaggerConfiguration merged = null;
    if (config instanceof SwaggerConfiguration) {
        merged = (SwaggerConfiguration) config;
    } else {
        merged = (SwaggerConfiguration) ContextUtils.deepCopy(config);
    }
    if (merged.getResourceClasses() == null) {
        merged.setResourceClasses(parentConfig.getResourceClasses());
    }
    if (merged.getFilterClass() == null) {
        merged.setFilterClass(parentConfig.getFilterClass());
    }
    if (merged.getIgnoredRoutes() == null) {
        merged.setIgnoredRoutes(parentConfig.getIgnoredRoutes());
    }
    if (merged.getOpenAPI() == null) {
        merged.setOpenAPI(parentConfig.getOpenAPI());
    }
    if (merged.getReaderClass() == null) {
        merged.setReaderClass(parentConfig.getReaderClass());
    }
    if (merged.getResourcePackages() == null) {
        merged.setResourcePackages(parentConfig.getResourcePackages());
    }
    if (merged.getScannerClass() == null) {
        merged.setScannerClass(parentConfig.getScannerClass());
    }
    if (merged.getCacheTTL() == null) {
        merged.setCacheTTL(parentConfig.getCacheTTL());
    }
    if (merged.getUserDefinedOptions() == null) {
        merged.setUserDefinedOptions(parentConfig.getUserDefinedOptions());
    }
    if (merged.isPrettyPrint() == null) {
        merged.setPrettyPrint(parentConfig.isPrettyPrint());
    }
    if (merged.isSortOutput() == null) {
        merged.setSortOutput(parentConfig.isSortOutput());
    }
    if (merged.isAlwaysResolveAppPath() == null) {
        merged.setAlwaysResolveAppPath(parentConfig.isAlwaysResolveAppPath());
    }
    if (merged.isReadAllResources() == null) {
        merged.setReadAllResources(parentConfig.isReadAllResources());
    }
    if (merged.getObjectMapperProcessorClass() == null) {
        merged.setObjectMapperProcessorClass(parentConfig.getObjectMapperProcessorClass());
    }
    if (merged.getModelConverterClasses() == null) {
        merged.setModelConverterClassess(parentConfig.getModelConverterClasses());
    }
    if (merged.isOpenAPI31() == null) {
        merged.setOpenAPI31(parentConfig.isOpenAPI31());
    }
    return merged;
}
Also used : OpenAPIConfiguration(io.swagger.v3.oas.integration.api.OpenAPIConfiguration)

Example 13 with SwaggerConfiguration

use of io.swagger.v3.oas.integration.SwaggerConfiguration in project swagger-core by swagger-api.

the class JaxrsAnnotationScanner method classes.

@Override
public Set<Class<?>> classes() {
    if (openApiConfiguration == null) {
        openApiConfiguration = new SwaggerConfiguration();
    }
    ClassGraph graph = new ClassGraph().enableAllInfo();
    Set<String> acceptablePackages = new HashSet<>();
    Set<Class<?>> output = new HashSet<>();
    // if classes are passed, use them
    if (openApiConfiguration.getResourceClasses() != null && !openApiConfiguration.getResourceClasses().isEmpty()) {
        for (String className : openApiConfiguration.getResourceClasses()) {
            if (!isIgnored(className)) {
                try {
                    output.add(Class.forName(className));
                } catch (ClassNotFoundException e) {
                    LOGGER.warn("error loading class from resourceClasses: " + e.getMessage(), e);
                }
            }
        }
        return output;
    }
    boolean allowAllPackages = false;
    if (openApiConfiguration.getResourcePackages() != null && !openApiConfiguration.getResourcePackages().isEmpty()) {
        for (String pkg : openApiConfiguration.getResourcePackages()) {
            if (!isIgnored(pkg)) {
                acceptablePackages.add(pkg);
                graph.whitelistPackages(pkg);
            }
        }
    } else {
        if (!onlyConsiderResourcePackages) {
            allowAllPackages = true;
        }
    }
    final Set<Class<?>> classes;
    try (ScanResult scanResult = graph.scan()) {
        classes = new HashSet<>(scanResult.getClassesWithAnnotation(javax.ws.rs.Path.class.getName()).loadClasses());
        classes.addAll(new HashSet<>(scanResult.getClassesWithAnnotation(OpenAPIDefinition.class.getName()).loadClasses()));
        if (Boolean.TRUE.equals(openApiConfiguration.isAlwaysResolveAppPath())) {
            classes.addAll(new HashSet<>(scanResult.getClassesWithAnnotation(ApplicationPath.class.getName()).loadClasses()));
        }
    }
    for (Class<?> cls : classes) {
        if (allowAllPackages) {
            output.add(cls);
        } else {
            for (String pkg : acceptablePackages) {
                if (cls.getPackage().getName().startsWith(pkg)) {
                    output.add(cls);
                }
            }
        }
    }
    LOGGER.trace("classes() - output size {}", output.size());
    return output;
}
Also used : ScanResult(io.github.classgraph.ScanResult) ClassGraph(io.github.classgraph.ClassGraph) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) HashSet(java.util.HashSet)

Example 14 with SwaggerConfiguration

use of io.swagger.v3.oas.integration.SwaggerConfiguration in project swagger-core by swagger-api.

the class ServletOpenApiConfigurationLoader method load.

@Override
public OpenAPIConfiguration load(String path) throws IOException {
    if (servletConfig == null) {
        return null;
    }
    if (StringUtils.isBlank(path)) {
        // we want to resolve from servlet params
        SwaggerConfiguration configuration = new SwaggerConfiguration().resourcePackages(resolveResourcePackages(servletConfig)).filterClass(getInitParam(servletConfig, OPENAPI_CONFIGURATION_FILTER_KEY)).resourceClasses(resolveResourceClasses(servletConfig)).readAllResources(getBooleanInitParam(servletConfig, OPENAPI_CONFIGURATION_READALLRESOURCES_KEY)).prettyPrint(getBooleanInitParam(servletConfig, OPENAPI_CONFIGURATION_PRETTYPRINT_KEY)).sortOutput(getBooleanInitParam(servletConfig, OPENAPI_CONFIGURATION_SORTOUTPUT_KEY)).alwaysResolveAppPath(getBooleanInitParam(servletConfig, OPENAPI_CONFIGURATION_ALWAYSRESOLVEAPPPATH_KEY)).readerClass(getInitParam(servletConfig, OPENAPI_CONFIGURATION_READER_KEY)).cacheTTL(getLongInitParam(servletConfig, OPENAPI_CONFIGURATION_CACHE_TTL_KEY)).scannerClass(getInitParam(servletConfig, OPENAPI_CONFIGURATION_SCANNER_KEY)).objectMapperProcessorClass(getInitParam(servletConfig, OPENAPI_CONFIGURATION_OBJECT_MAPPER_PROCESSOR_KEY)).modelConverterClasses(resolveModelConverterClasses(servletConfig));
        return configuration;
    }
    String location = ServletConfigContextUtils.getInitParam(servletConfig, path);
    if (!StringUtils.isBlank(location)) {
        if (classpathOpenApiConfigurationLoader.exists(location)) {
            return classpathOpenApiConfigurationLoader.load(location);
        } else if (fileOpenApiConfigurationLoader.exists(location)) {
            return fileOpenApiConfigurationLoader.load(location);
        }
    }
    String builderClassName = getInitParam(servletConfig, OPENAPI_CONFIGURATION_BUILDER_KEY);
    if (StringUtils.isNotBlank(builderClassName)) {
        try {
            Class cls = getClass().getClassLoader().loadClass(builderClassName);
            // TODO instantiate with configuration
            OpenAPIConfigBuilder builder = (OpenAPIConfigBuilder) cls.newInstance();
            return builder.build();
        } catch (Exception e) {
            LOGGER.error("error loading builder: " + e.getMessage(), e);
        }
    }
    return null;
}
Also used : OpenAPIConfigBuilder(io.swagger.v3.oas.integration.api.OpenAPIConfigBuilder) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) IOException(java.io.IOException)

Example 15 with SwaggerConfiguration

use of io.swagger.v3.oas.integration.SwaggerConfiguration in project swagger-core by swagger-api.

the class IntegrationTest method shouldInitialize.

@Test(description = "initialize a context and read")
public void shouldInitialize() throws Exception {
    OpenAPIConfiguration config = new SwaggerConfiguration().resourcePackages(Stream.of("com.my.project.resources", "org.my.project.resources").collect(Collectors.toSet())).openAPI(new OpenAPI().info(new Info().description("TEST INFO DESC")));
    OpenApiContext ctx = new GenericOpenApiContext().openApiConfiguration(config).init();
    OpenAPI openApi = ctx.read();
    assertNotNull(openApi);
}
Also used : OpenAPIConfiguration(io.swagger.v3.oas.integration.api.OpenAPIConfiguration) Info(io.swagger.v3.oas.models.info.Info) OpenAPI(io.swagger.v3.oas.models.OpenAPI) OpenApiContext(io.swagger.v3.oas.integration.api.OpenApiContext) Test(org.testng.annotations.Test)

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