Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ref #3144 - support filter in maven/gradle plugins #3183

Merged
merged 1 commit into from
Apr 17, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -55,50 +55,52 @@ public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, Lis
final Set<String> filteredTags = new HashSet<>();

Paths clonedPaths = new Paths();
for (String resourcePath : filteredOpenAPI.getPaths().keySet()) {
PathItem pathItem = filteredOpenAPI.getPaths().get(resourcePath);

PathItem filteredPathItem = filterPathItem(filter, pathItem, resourcePath, params, cookies, headers);

if (filteredPathItem != null) {

PathItem clonedPathItem = new PathItem();
clonedPathItem.set$ref(filteredPathItem.get$ref());
clonedPathItem.setDescription(filteredPathItem.getDescription());
clonedPathItem.setSummary(filteredPathItem.getSummary());
clonedPathItem.setExtensions(filteredPathItem.getExtensions());
clonedPathItem.setParameters(filteredPathItem.getParameters());
clonedPathItem.setServers(filteredPathItem.getServers());

Map<PathItem.HttpMethod, Operation> ops = filteredPathItem.readOperationsMap();

for (PathItem.HttpMethod key : ops.keySet()) {
Operation op = ops.get(key);
List<String> opTagsBeforeFilter = null;
if (op.getTags() != null) {
opTagsBeforeFilter = new ArrayList<>(op.getTags());
} else {
opTagsBeforeFilter = new ArrayList<>();
}
op = filterOperation(filter, op, resourcePath, key.toString(), params, cookies, headers);
clonedPathItem.operation(key, op);
if (op == null) {
filteredTags.addAll(opTagsBeforeFilter);
} else {
if (filteredOpenAPI.getPaths() != null) {
for (String resourcePath : filteredOpenAPI.getPaths().keySet()) {
PathItem pathItem = filteredOpenAPI.getPaths().get(resourcePath);

PathItem filteredPathItem = filterPathItem(filter, pathItem, resourcePath, params, cookies, headers);

if (filteredPathItem != null) {

PathItem clonedPathItem = new PathItem();
clonedPathItem.set$ref(filteredPathItem.get$ref());
clonedPathItem.setDescription(filteredPathItem.getDescription());
clonedPathItem.setSummary(filteredPathItem.getSummary());
clonedPathItem.setExtensions(filteredPathItem.getExtensions());
clonedPathItem.setParameters(filteredPathItem.getParameters());
clonedPathItem.setServers(filteredPathItem.getServers());

Map<PathItem.HttpMethod, Operation> ops = filteredPathItem.readOperationsMap();

for (PathItem.HttpMethod key : ops.keySet()) {
Operation op = ops.get(key);
List<String> opTagsBeforeFilter = null;
if (op.getTags() != null) {
opTagsBeforeFilter.removeAll(op.getTags());
allowedTags.addAll(op.getTags());
opTagsBeforeFilter = new ArrayList<>(op.getTags());
} else {
opTagsBeforeFilter = new ArrayList<>();
}
op = filterOperation(filter, op, resourcePath, key.toString(), params, cookies, headers);
clonedPathItem.operation(key, op);
if (op == null) {
filteredTags.addAll(opTagsBeforeFilter);
} else {
if (op.getTags() != null) {
opTagsBeforeFilter.removeAll(op.getTags());
allowedTags.addAll(op.getTags());
}
filteredTags.addAll(opTagsBeforeFilter);
}
filteredTags.addAll(opTagsBeforeFilter);
}

}
if (!clonedPathItem.readOperations().isEmpty()) {
clonedPaths.addPathItem(resourcePath, clonedPathItem);
}
if (!clonedPathItem.readOperations().isEmpty()) {
clonedPaths.addPathItem(resourcePath, clonedPathItem);
}
}
}
clone.paths(clonedPaths);
}
clone.paths(clonedPaths);

filteredTags.removeAll(allowedTags);

Expand Down
1 change: 1 addition & 0 deletions modules/swagger-gradle-plugin/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ dependencies {
compile group: 'javax.servlet', name: 'javax.servlet-api', version:'3.1.0'
testCompile group: 'com.github.tomakehurst', name: 'wiremock', version:'2.14.0'
testCompile gradleTestKit()
testCompile group: 'commons-io', name: 'commons-io', version:'2.6'
testCompile 'junit:junit:4+'


Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.swagger.v3.plugins.gradle;

import org.apache.commons.io.FileUtils;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import org.junit.Before;
Expand Down Expand Up @@ -54,7 +55,7 @@ public void setup() throws IOException {
public void testSwaggerResolveTask() throws IOException {
outputDir = testProjectDir.getRoot().toString() + "/target";
outputFile = testProjectDir.getRoot().toString() + "/testAPI.json";
outputDir = "/tmp/a/target";
//outputDir = "/tmp/a/target";
String resolveTask = "resolve";

String buildFileContent =
Expand Down Expand Up @@ -99,6 +100,7 @@ public void testSwaggerResolveTask() throws IOException {
" classpath = sourceSets.test.runtimeClasspath\n" +
" resourcePackages = ['io.swagger.v3.plugins.gradle.petstore']\n" +
" outputPath = \'" + outputDir + "\'\n" +
" filterClass = \'io.swagger.v3.plugins.gradle.resources.MyFilter\'\n" +
" openApiFile = file(\'" + openapiInputFile.getAbsolutePath() + "\')\n" +
"}";

Expand Down Expand Up @@ -126,6 +128,7 @@ public void testSwaggerResolveTask() throws IOException {

assertEquals(SUCCESS, result.task(":" + resolveTask).getOutcome());
assertTrue(new File(outputDir + "/PetStoreAPI.json").exists());
assertTrue(FileUtils.readFileToString(new File(outputDir + "/PetStoreAPI.json")).contains("UPDATEDBYFILTER"));
}

private void writeFile(File destination, String content) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package io.swagger.v3.plugins.gradle.resources;

import io.swagger.v3.core.filter.AbstractSpecFilter;
import io.swagger.v3.core.model.ApiDescription;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Optional;

public class MyFilter extends AbstractSpecFilter {
private static Logger LOGGER = LoggerFactory.getLogger(MyFilter.class);

@Override
public Optional<OpenAPI> filterOpenAPI(
OpenAPI openAPI,
Map<String, List<String>> params,
Map<String, String> cookies,
Map<String, List<String>> headers) {
openAPI.getInfo().setTitle("UPDATEDBYFILTER");
return Optional.of(openAPI);
// some processing
//return super.filterOpenAPI(openAPI, params, cookies, headers);
}

@Override
public Optional<io.swagger.v3.oas.models.Operation> filterOperation(
Operation operation,
ApiDescription api,
Map<String, List<String>> params,
Map<String, String> cookies,
Map<String, List<String>> headers) {
// some processing
return Optional.of(operation);
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package io.swagger.v3.jaxrs2.integration;

import io.swagger.v3.core.filter.OpenAPISpecFilter;
import io.swagger.v3.core.filter.SpecFilter;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.core.util.Yaml;
import io.swagger.v3.oas.integration.GenericOpenApiContextBuilder;
Expand Down Expand Up @@ -213,6 +215,17 @@ public Map<String, String> resolve() throws Exception{
OpenAPI openAPI = builder
.buildContext(true)
.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)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package io.swagger.v3.plugin.maven;

import io.swagger.v3.core.filter.OpenAPISpecFilter;
import io.swagger.v3.core.filter.SpecFilter;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.core.util.Yaml;
import io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder;
Expand Down Expand Up @@ -79,6 +81,19 @@ public void execute() throws MojoExecutionException, MojoFailureException {
OpenAPI openAPI = builder
.buildContext(true)
.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) {
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)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ public void testResolve() throws Exception {
checkOutput(runTest(pom));
}

public void testResolveWithFilter() throws Exception {
File pom = getTestFile("src/test/resources/pom.resolveToFileWithFilter.xml");
checkOutput(runTest(pom));
}

public void testResolveNoName() throws Exception {
File pom = getTestFile("src/test/resources/pom.resolveToFileNoName.xml");
checkOutput(runTest(pom));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package io.swagger.v3.plugin.maven.resources;

import io.swagger.v3.core.filter.AbstractSpecFilter;
import io.swagger.v3.core.model.ApiDescription;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Optional;

public class MyFilter extends AbstractSpecFilter {
private static Logger LOGGER = LoggerFactory.getLogger(MyFilter.class);

@Override
public Optional<OpenAPI> filterOpenAPI(
OpenAPI openAPI,
Map<String, List<String>> params,
Map<String, String> cookies,
Map<String, List<String>> headers) {
openAPI.getInfo().setTitle("UPDATEDBYFILTER");
return Optional.of(openAPI);
// some processing
//return super.filterOpenAPI(openAPI, params, cookies, headers);
}

@Override
public Optional<Operation> filterOperation(
Operation operation,
ApiDescription api,
Map<String, List<String>> params,
Map<String, String> cookies,
Map<String, List<String>> headers) {
// some processing
return Optional.of(operation);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-maven-plugin-test</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Test Resolve YAML</name>

<build>
<plugins>
<plugin>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-maven-plugin</artifactId>
<configuration>
<outputFileName>spec</outputFileName>
<outputPath>${project.basedir}/../../../target/generatedtest</outputPath>
<openapiFilePath>${project.basedir}/../../../src/test/resources/openapiinput.yaml</openapiFilePath>
<outputFormat>YAML</outputFormat>
<resourcePackages>
<package>io.swagger.v3.plugin.maven.petstore.petstore</package>
</resourcePackages>
<prettyPrint>TRUE</prettyPrint>
<filterClass>io.swagger.v3.plugin.maven.resources.MyFilter</filterClass>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-jaxrs2</artifactId>
<version>${project.version}</version>
</dependency>

<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1</version>
</dependency>

</dependencies>
<properties>
<project.build.sourceEncoding>ISO-8859-1</project.build.sourceEncoding>
</properties>
</project>