use of io.swagger.v3.core.filter.OpenAPISpecFilter in project swagger-core by swagger-api.
the class ReaderTest method testExampleWithFilter.
@Test(description = "Example with Ref Filter")
public void testExampleWithFilter() {
Components components = new Components();
components.addExamples("Id", new Example().description("Id Example").summary("Id Example").value("1"));
OpenAPI oas = new OpenAPI().info(new Info().description("info")).components(components);
Reader reader = new Reader(oas);
OpenAPI openAPI = reader.read(SimpleExamplesResource.class);
OpenAPISpecFilter filterImpl = new RefExampleFilter();
SpecFilter f = new SpecFilter();
openAPI = f.filter(openAPI, filterImpl, null, null, null);
String yaml = "openapi: 3.0.1\n" + "info:\n" + " description: info\n" + "paths:\n" + " /example:\n" + " post:\n" + " description: subscribes a client to updates relevant to the requestor's account\n" + " operationId: subscribe\n" + " parameters:\n" + " - example:\n" + " $ref: '#/components/examples/Id'\n" + " requestBody:\n" + " content:\n" + " '*/*':\n" + " schema:\n" + " type: integer\n" + " format: int32\n" + " responses:\n" + " default:\n" + " description: default response\n" + " content:\n" + " '*/*':\n" + " schema:\n" + " $ref: '#/components/schemas/SubscriptionResponse'\n" + "components:\n" + " schemas:\n" + " SubscriptionResponse:\n" + " type: object\n" + " properties:\n" + " subscriptionId:\n" + " type: string\n" + " examples:\n" + " Id:\n" + " summary: Id Example\n" + " description: Id Example\n" + " value: \"1\"\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
use of io.swagger.v3.core.filter.OpenAPISpecFilter in project swagger-core by swagger-api.
the class ReaderTest method testParameterWithFilter.
@Test(description = "Responses with filter")
public void testParameterWithFilter() {
Components components = new Components();
components.addParameters("id", new Parameter().description("Id Description").schema(new IntegerSchema()).in(ParameterIn.QUERY.toString()).example(1).required(true));
OpenAPI oas = new OpenAPI().info(new Info().description("info")).components(components);
Reader reader = new Reader(oas);
OpenAPI openAPI = reader.read(SimpleParameterResource.class);
OpenAPISpecFilter filterImpl = new RefParameterFilter();
SpecFilter f = new SpecFilter();
openAPI = f.filter(openAPI, filterImpl, null, null, null);
String yaml = "openapi: 3.0.1\n" + "info:\n" + " description: info\n" + "paths:\n" + " /:\n" + " get:\n" + " summary: Simple get operation\n" + " description: Defines a simple get operation with a payload complex input object\n" + " operationId: sendPayload\n" + " parameters:\n" + " - $ref: '#/components/parameters/id'\n" + " responses:\n" + " default:\n" + " description: default response\n" + " content:\n" + " '*/*': {}\n" + " deprecated: true\n" + "components:\n" + " parameters: \n" + " id:\n" + " in: query\n" + " description: Id Description\n" + " required: true\n" + " schema:\n" + " type: integer\n" + " format: int32\n" + " example: 1\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
use of io.swagger.v3.core.filter.OpenAPISpecFilter in project swagger-core by swagger-api.
the class ReaderTest method testRequestBodyWithFilter.
@Test(description = "RequestBody with filter")
public void testRequestBodyWithFilter() {
Components components = new Components();
components.addRequestBodies("User", new RequestBody());
OpenAPI oas = new OpenAPI().info(new Info().description("info")).components(components);
Reader reader = new Reader(oas);
OpenAPI openAPI = reader.read(SimpleRequestBodyResource.class);
OpenAPISpecFilter filterImpl = new RefRequestBodyFilter();
SpecFilter f = new SpecFilter();
openAPI = f.filter(openAPI, filterImpl, null, null, null);
String yaml = "openapi: 3.0.1\n" + "info:\n" + " description: info\n" + "paths:\n" + " /:\n" + " get:\n" + " summary: Simple get operation\n" + " description: Defines a simple get operation with a payload complex input object\n" + " operationId: sendPayload\n" + " requestBody:\n" + " $ref: '#/components/requestBodies/User'\n" + " responses:\n" + " default:\n" + " description: default response\n" + " content:\n" + " '*/*': {}\n" + " deprecated: true\n" + "components:\n" + " schemas:\n" + " User:\n" + " type: object\n" + " properties:\n" + " id:\n" + " type: integer\n" + " format: int64\n" + " username:\n" + " type: string\n" + " firstName:\n" + " type: string\n" + " lastName:\n" + " type: string\n" + " email:\n" + " type: string\n" + " password:\n" + " type: string\n" + " phone:\n" + " type: string\n" + " userStatus:\n" + " type: integer\n" + " description: User Status\n" + " format: int32\n" + " xml:\n" + " name: User\n" + " requestBodies:\n" + " User: {}\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
use of io.swagger.v3.core.filter.OpenAPISpecFilter 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);
}
}
use of io.swagger.v3.core.filter.OpenAPISpecFilter 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);
}
}
Aggregations