Migrated from Groovy to Java in Maven plugin

This commit is contained in:
Marcin Grzejszczak
2016-07-20 12:26:50 +02:00
parent 3e9aabab9d
commit 5b900561c9
15 changed files with 568 additions and 552 deletions

View File

@@ -125,34 +125,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.mycila</groupId>
<artifactId>license-maven-plugin</artifactId>
<configuration>
<header>src/etc/header.txt</header>
<includes>
<include>src/**</include>
</includes>
<excludes>
<exclude>**/.idea/**</exclude>
<exclude>**/*.adoc</exclude>
</excludes>
<useDefaultExcludes>true</useDefaultExcludes>
<useDefaultMapping>true</useDefaultMapping>
<properties>
<year>${project.inceptionYear}</year>
<company>Pivotal</company>
</properties>
<encoding>UTF-8</encoding>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>

View File

@@ -1,14 +0,0 @@
Copyright 2013-${year} the original author or authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -1,63 +0,0 @@
/**
*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.contract.maven.verifier
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import org.apache.maven.execution.MavenSession
import org.apache.maven.model.Resource
import org.apache.maven.plugin.MojoExecutionException
import org.apache.maven.project.MavenProject
import org.apache.maven.shared.filtering.MavenFilteringException
import org.apache.maven.shared.filtering.MavenResourcesExecution
import org.apache.maven.shared.filtering.MavenResourcesFiltering
@CompileStatic
@Slf4j
class CopyContracts {
private final MavenProject project
private final MavenSession mavenSession
private final MavenResourcesFiltering mavenResourcesFiltering
CopyContracts(MavenProject project, MavenSession mavenSession, MavenResourcesFiltering mavenResourcesFiltering) {
this.project = project
this.mavenSession = mavenSession
this.mavenResourcesFiltering = mavenResourcesFiltering
}
void copy(File contractsDirectory, File outputDirectory) {
log.info('Copying Spring Cloud Contract Verifier contracts')
Resource testResource = new Resource(directory: contractsDirectory.absolutePath)
MavenResourcesExecution mavenResourcesExecution = new MavenResourcesExecution(
resources: [testResource],
outputDirectory: new File(outputDirectory, 'contracts'),
mavenProject: project,
encoding: 'UTF-8',
mavenSession: mavenSession);
mavenResourcesExecution.injectProjectBuildFilters = false
mavenResourcesExecution.overwrite = true
mavenResourcesExecution.includeEmptyDirs = false
mavenResourcesExecution.filterFilenames = false
try {
mavenResourcesFiltering.filterResources(mavenResourcesExecution);
} catch (MavenFilteringException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
}

View File

@@ -1,36 +0,0 @@
/**
*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.contract.maven.verifier
import org.apache.maven.model.Plugin
import org.apache.maven.project.MavenProject
import org.codehaus.plexus.archiver.jar.Manifest
class ManifestCreator {
static Manifest createManifest(MavenProject project) {
Manifest manifest = new Manifest();
Plugin verifierMavenPlugin = project.getBuildPlugins().find { it.artifactId == 'spring-cloud-contract-maven-plugin' }
manifest.addConfiguredAttribute(new Manifest.Attribute("Spring-Cloud-Contract-Verifier-Maven-Plugin-Version", verifierMavenPlugin.version));
if (verifierMavenPlugin.getDependencies()) {
String verifierVersion = verifierMavenPlugin.getDependencies().find {
it.artifactId == 'spring-cloud-contract-verifier'
}.version
manifest.addConfiguredAttribute(new Manifest.Attribute("Spring-Cloud-Contract-Verifier-Version", verifierVersion));
}
return manifest
}
}

View File

@@ -1,49 +0,0 @@
/**
*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.contract.maven.verifier.stubrunner
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import org.apache.maven.project.MavenProject
import org.eclipse.aether.RepositorySystem
import org.eclipse.aether.RepositorySystemSession
import org.springframework.cloud.contract.stubrunner.AetherStubDownloader
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
@Named
@Singleton
@CompileStatic
@Slf4j
class AetherStubDownloaderFactory {
private final MavenProject project
private final RepositorySystem repoSystem
@Inject
AetherStubDownloaderFactory(RepositorySystem repoSystem, MavenProject project) {
this.repoSystem = repoSystem
this.project = project
}
AetherStubDownloader build(RepositorySystemSession repoSession) {
return new AetherStubDownloader(repoSystem, project.remoteProjectRepositories, repoSession)
}
}

View File

@@ -1,52 +0,0 @@
/**
*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.contract.maven.verifier.stubrunner
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import org.eclipse.aether.RepositorySystemSession
import org.springframework.cloud.contract.stubrunner.*
import javax.inject.Inject
import javax.inject.Named
@Named
@CompileStatic
@Slf4j
class RemoteStubRunner {
private final AetherStubDownloaderFactory aetherStubDownloaderFactory
@Inject
RemoteStubRunner(AetherStubDownloaderFactory aetherStubDownloaderFactory) {
this.aetherStubDownloaderFactory = aetherStubDownloaderFactory
}
BatchStubRunner run(StubRunnerOptions options, RepositorySystemSession repositorySystemSession) {
AetherStubDownloader stubDownloader = aetherStubDownloaderFactory.build(repositorySystemSession)
try {
log.debug("Launching StubRunner with args: $options")
BatchStubRunner stubRunner = new BatchStubRunnerFactory(options, stubDownloader).buildBatchStubRunner()
RunningStubs runningCollaborators = stubRunner.runStubs()
log.info(runningCollaborators.toString())
return stubRunner
} catch (Exception e) {
log.error("An exception occurred while trying to execute the stubs: ${e.message}")
throw e
}
}
}

View File

@@ -1,5 +1,4 @@
/**
*
/*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -28,7 +27,6 @@ import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.filtering.MavenResourcesFiltering;
import org.springframework.cloud.contract.maven.verifier.CopyContracts;
import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties;
import org.springframework.cloud.contract.verifier.wiremock.DslToWireMockClientConverter;
import org.springframework.cloud.contract.verifier.wiremock.RecursiveFilesConverter;
@@ -38,69 +36,77 @@ import org.springframework.cloud.contract.verifier.wiremock.RecursiveFilesConver
* <p>
* This goal allows you to generate `stubs-jar` or execute `spring-cloud-contract:run` with generated WireMock mappings.
*/
@Mojo(name = "convert", requiresProject = false, defaultPhase = LifecyclePhase.PROCESS_TEST_RESOURCES)
@Mojo(name = "convert", requiresProject = false,
defaultPhase = LifecyclePhase.PROCESS_TEST_RESOURCES)
public class ConvertMojo extends AbstractMojo {
/**
* Directory containing Spring Cloud Contract Verifier contracts written using the GroovyDSL
*/
@Parameter(defaultValue = "${basedir}/src/test/resources/contracts")
private File contractsDirectory;
/**
* Directory containing Spring Cloud Contract Verifier contracts written using the GroovyDSL
*/
@Parameter(defaultValue = "${basedir}/src/test/resources/contracts")
private File contractsDirectory;
/**
* Directory where the generated WireMock stubs from Groovy DSL should be placed.
* You can then mention them in your packaging task to create jar with stubs
*/
@Parameter(defaultValue = "${project.build.directory}/stubs")
private File outputDirectory;
/**
* Directory where the generated WireMock stubs from Groovy DSL should be placed.
* You can then mention them in your packaging task to create jar with stubs
*/
@Parameter(defaultValue = "${project.build.directory}/stubs")
private File outputDirectory;
/**
* Directory containing contracts written using the GroovyDSL
* <p>
* This parameter is only used when goal is executed outside of maven project.
*/
@Parameter(property = "contractsDirectory", defaultValue = "${basedir}")
private File source;
/**
* Directory containing contracts written using the GroovyDSL
* <p>
* This parameter is only used when goal is executed outside of maven project.
*/
@Parameter(property = "contractsDirectory", defaultValue = "${basedir}")
private File source;
@Parameter(property = "stubsDirectory", defaultValue = "${basedir}")
private File destination;
@Parameter(property = "stubsDirectory", defaultValue = "${basedir}")
private File destination;
@Parameter(property = "spring.cloud.contract.verifier.skip", defaultValue = "false")
private boolean skip;
@Parameter(property = "spring.cloud.contract.verifier.skip", defaultValue = "false")
private boolean skip;
@Parameter(defaultValue = "${session}", readonly = true)
private MavenSession mavenSession;
@Parameter(defaultValue = "${session}", readonly = true)
private MavenSession mavenSession;
@Parameter(defaultValue = "${project}", readonly = true)
private MavenProject project;
@Parameter(defaultValue = "${project}", readonly = true) private MavenProject project;
@Component(role = MavenResourcesFiltering.class, hint = "default")
private MavenResourcesFiltering mavenResourcesFiltering;
@Component(role = MavenResourcesFiltering.class, hint = "default")
private MavenResourcesFiltering mavenResourcesFiltering;
public void execute() throws MojoExecutionException, MojoFailureException {
public void execute() throws MojoExecutionException, MojoFailureException {
if (skip) {
getLog().info(String.format("Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip=%s", skip));
return;
}
if (skip) {
getLog().info(String.format(
"Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip=%s",
skip));
return;
}
new CopyContracts(project, mavenSession, mavenResourcesFiltering).copy(contractsDirectory, outputDirectory);
new CopyContracts(project, mavenSession, mavenResourcesFiltering)
.copy(contractsDirectory, outputDirectory);
final ContractVerifierConfigProperties config = new ContractVerifierConfigProperties();
config.setContractsDslDir(isInsideProject() ? contractsDirectory : source);
config.setStubsOutputDir(isInsideProject() ? new File(outputDirectory, "mappings") : destination);
final ContractVerifierConfigProperties config = new ContractVerifierConfigProperties();
config.setContractsDslDir(isInsideProject() ? contractsDirectory : source);
config.setStubsOutputDir(
isInsideProject() ? new File(outputDirectory, "mappings") : destination);
getLog().info("Converting from Spring Cloud Contract Verifier contracts to WireMock stubs mappings");
getLog().info(String.format(" Spring Cloud Contract Verifier contracts directory: %s", config.getContractsDslDir()));
getLog().info(String.format("WireMock stubs mappings directory: %s", config.getStubsOutputDir()));
getLog().info(
"Converting from Spring Cloud Contract Verifier contracts to WireMock stubs mappings");
getLog().info(String.format(
" Spring Cloud Contract Verifier contracts directory: %s",
config.getContractsDslDir()));
getLog().info(String.format("WireMock stubs mappings directory: %s",
config.getStubsOutputDir()));
RecursiveFilesConverter converter = new RecursiveFilesConverter(new DslToWireMockClientConverter(), config);
converter.processFiles();
}
private boolean isInsideProject() {
return mavenSession.getRequest().isProjectPresent();
}
RecursiveFilesConverter converter = new RecursiveFilesConverter(
new DslToWireMockClientConverter(), config);
converter.processFiles();
}
private boolean isInsideProject() {
return mavenSession.getRequest().isProjectPresent();
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.contract.maven.verifier;
import java.io.File;
import java.lang.invoke.MethodHandles;
import java.util.Collections;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.filtering.MavenFilteringException;
import org.apache.maven.shared.filtering.MavenResourcesExecution;
import org.apache.maven.shared.filtering.MavenResourcesFiltering;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CopyContracts {
private static final Logger log = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
private final MavenProject project;
private final MavenSession mavenSession;
private final MavenResourcesFiltering mavenResourcesFiltering;
public CopyContracts(MavenProject project, MavenSession mavenSession,
MavenResourcesFiltering mavenResourcesFiltering) {
this.project = project;
this.mavenSession = mavenSession;
this.mavenResourcesFiltering = mavenResourcesFiltering;
}
public void copy(File contractsDirectory, File outputDirectory)
throws MojoExecutionException {
log.info("Copying Spring Cloud Contract Verifier contracts");
Resource resource = new Resource();
resource.setDirectory(contractsDirectory.getAbsolutePath());
MavenResourcesExecution execution = new MavenResourcesExecution();
execution.setResources(Collections.singletonList(resource));
execution.setOutputDirectory(new File(outputDirectory, "contracts"));
execution.setMavenProject(project);
execution.setEncoding("UTF-8");
execution.setMavenSession(mavenSession);
execution.setInjectProjectBuildFilters(false);
execution.setOverwrite(true);
execution.setIncludeEmptyDirs(false);
execution.setFilterFilenames(false);
try {
mavenResourcesFiltering.filterResources(execution);
}
catch (MavenFilteringException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
}

View File

@@ -1,5 +1,4 @@
/**
*
/*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -29,73 +28,87 @@ import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.codehaus.plexus.archiver.Archiver;
import org.codehaus.plexus.archiver.jar.JarArchiver;
import org.springframework.cloud.contract.maven.verifier.ManifestCreator;
@Mojo(name = "generateStubs", defaultPhase = LifecyclePhase.PACKAGE, requiresProject = true)
@Mojo(name = "generateStubs", defaultPhase = LifecyclePhase.PACKAGE,
requiresProject = true)
public class GenerateStubsMojo extends AbstractMojo {
private static final String STUB_MAPPING_FILE_PATTERN = "**/*.json";
private static final String CONTRACT_FILE_PATTERN = "**/*.groovy";
private static final String STUB_MAPPING_FILE_PATTERN = "**/*.json";
private static final String CONTRACT_FILE_PATTERN = "**/*.groovy";
@Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true)
private File projectBuildDirectory;
@Parameter(defaultValue = "${project.build.directory}", readonly = true,
required = true)
private File projectBuildDirectory;
@Parameter(property = "stubsDirectory", defaultValue = "${project.build.directory}/stubs")
private File outputDirectory;
@Parameter(property = "stubsDirectory",
defaultValue = "${project.build.directory}/stubs")
private File outputDirectory;
/**
* Set this to "true" to bypass Verifier execution..
*/
@Parameter(property = "spring.cloud.contract.verifier.skip", defaultValue = "false")
private boolean skip;
/**
* Set this to "true" to bypass Verifier execution..
*/
@Parameter(property = "spring.cloud.contract.verifier.skip", defaultValue = "false")
private boolean skip;
@Component
private MavenProjectHelper projectHelper;
@Component
private MavenProjectHelper projectHelper;
@Parameter(defaultValue = "${project}", readonly = true)
private MavenProject project;
@Parameter(defaultValue = "${project}", readonly = true)
private MavenProject project;
@Component(role = Archiver.class, hint = "jar")
private JarArchiver archiver;
@Component(role = Archiver.class, hint = "jar")
private JarArchiver archiver;
@Parameter(defaultValue = "true")
private boolean attachContracts;
@Parameter(defaultValue = "true")
private boolean attachContracts;
@Parameter(defaultValue = "stubs")
private String classifier;
@Parameter(defaultValue = "stubs")
private String classifier;
public void execute() throws MojoExecutionException, MojoFailureException {
if (skip) {
getLog().info("Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip=" + skip);
return;
}
File stubsJarFile = createStubJar(outputDirectory);
projectHelper.attachArtifact(project, "jar", classifier, stubsJarFile);
}
public void execute() throws MojoExecutionException, MojoFailureException {
if (skip) {
getLog().info(
"Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip="
+ skip);
return;
}
File stubsJarFile = createStubJar(outputDirectory);
projectHelper.attachArtifact(project, "jar", classifier, stubsJarFile);
}
private File createStubJar(File stubsOutputDir) throws MojoFailureException, MojoExecutionException {
if (!stubsOutputDir.exists()) {
throw new MojoExecutionException("Stubs could not be found: [" + stubsOutputDir.getAbsolutePath() + "] .\nPlease make sure that spring-cloud-contract:convert was invoked");
}
String stubArchiveName = project.getBuild().getFinalName() + "-" + classifier + ".jar";
File stubsJarFile = new File(projectBuildDirectory, stubArchiveName);
try {
if (attachContracts) {
archiver.addDirectory(stubsOutputDir, new String[]{STUB_MAPPING_FILE_PATTERN,
CONTRACT_FILE_PATTERN }, new String[0]);
} else {
getLog().info("Skipping attaching Spring Cloud Contract Verifier contracts");
archiver.addDirectory(stubsOutputDir, new String[]{STUB_MAPPING_FILE_PATTERN}, new String[]{
CONTRACT_FILE_PATTERN });
}
archiver.setCompress(true);
archiver.setDestFile(stubsJarFile);
archiver.addConfiguredManifest(ManifestCreator.createManifest(project));
archiver.createArchive();
} catch (Exception e) {
throw new MojoFailureException("Exception while packaging " + classifier + " jar.", e);
}
return stubsJarFile;
}
private File createStubJar(File stubsOutputDir)
throws MojoFailureException, MojoExecutionException {
if (!stubsOutputDir.exists()) {
throw new MojoExecutionException(
"Stubs could not be found: [" + stubsOutputDir.getAbsolutePath()
+ "] .\nPlease make sure that spring-cloud-contract:convert was invoked");
}
String stubArchiveName =
project.getBuild().getFinalName() + "-" + classifier + ".jar";
File stubsJarFile = new File(projectBuildDirectory, stubArchiveName);
try {
if (attachContracts) {
archiver.addDirectory(stubsOutputDir,
new String[] { STUB_MAPPING_FILE_PATTERN, CONTRACT_FILE_PATTERN },
new String[0]);
}
else {
getLog().info(
"Skipping attaching Spring Cloud Contract Verifier contracts");
archiver.addDirectory(stubsOutputDir,
new String[] { STUB_MAPPING_FILE_PATTERN },
new String[] { CONTRACT_FILE_PATTERN });
}
archiver.setCompress(true);
archiver.setDestFile(stubsJarFile);
archiver.addConfiguredManifest(ManifestCreator.createManifest(project));
archiver.createArchive();
}
catch (Exception e) {
throw new MojoFailureException(
"Exception while packaging " + classifier + " jar.", e);
}
return stubsJarFile;
}
}

View File

@@ -1,5 +1,4 @@
/**
*
/*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -33,118 +32,127 @@ import org.springframework.cloud.contract.verifier.config.ContractVerifierConfig
import org.springframework.cloud.contract.verifier.config.TestFramework;
import org.springframework.cloud.contract.verifier.config.TestMode;
@Mojo(name = "generateTests", defaultPhase = LifecyclePhase.GENERATE_TEST_SOURCES, requiresDependencyResolution = ResolutionScope.TEST)
@Mojo(name = "generateTests", defaultPhase = LifecyclePhase.GENERATE_TEST_SOURCES,
requiresDependencyResolution = ResolutionScope.TEST)
public class GenerateTestsMojo extends AbstractMojo {
@Parameter(property = "spring.cloud.contract.verifier.contractsDirectory", defaultValue = "${project.basedir}/src/test/resources/contracts")
private File contractsDirectory;
@Parameter(property = "spring.cloud.contract.verifier.contractsDirectory",
defaultValue = "${project.basedir}/src/test/resources/contracts")
private File contractsDirectory;
@Parameter(defaultValue = "${project.build.directory}/generated-test-sources/contracts")
private File generatedTestSourcesDir;
@Parameter(
defaultValue = "${project.build.directory}/generated-test-sources/contracts")
private File generatedTestSourcesDir;
@Parameter(defaultValue = "org.springframework.cloud.contract.verifier.tests")
private String basePackageForTests;
@Parameter(defaultValue = "org.springframework.cloud.contract.verifier.tests")
private String basePackageForTests;
@Parameter
private String baseClassForTests;
@Parameter
private String baseClassForTests;
@Parameter(defaultValue = "MOCKMVC")
private TestMode testMode;
@Parameter(defaultValue = "MOCKMVC")
private TestMode testMode;
@Parameter(defaultValue = "JUNIT")
private TestFramework testFramework;
@Parameter(defaultValue = "JUNIT")
private TestFramework testFramework;
@Parameter
private String ruleClassForTests;
@Parameter
private String ruleClassForTests;
@Parameter
private String nameSuffixForTests;
@Parameter
private String nameSuffixForTests;
/**
* Imports that should be added to generated tests
*/
@Parameter
private String[] imports;
/**
* Imports that should be added to generated tests
*/
@Parameter
private String[] imports;
/**
* Static imports that should be added to generated tests
*/
@Parameter
private String[] staticImports;
/**
* Static imports that should be added to generated tests
*/
@Parameter
private String[] staticImports;
/**
* Patterns that should not be taken into account for processing
*/
@Parameter
private List<String> excludedFiles;
/**
* Patterns that should not be taken into account for processing
*/
@Parameter
private List<String> excludedFiles;
/**
* Patterns for which Spring Cloud Contract Verifier should generate @Ignored tests
*/
@Parameter
private List<String> ignoredFiles;
/**
* Patterns for which Spring Cloud Contract Verifier should generate @Ignored tests
*/
@Parameter
private List<String> ignoredFiles;
@Parameter(defaultValue = "${project}", readonly = true)
private MavenProject project;
@Parameter(defaultValue = "${project}", readonly = true)
private MavenProject project;
@Parameter(property = "spring.cloud.contract.verifier.skip", defaultValue = "false")
private boolean skip;
@Parameter(property = "spring.cloud.contract.verifier.skip", defaultValue = "false")
private boolean skip;
@Parameter(property = "maven.test.skip", defaultValue = "false")
private boolean mavenTestSkip;
@Parameter(property = "maven.test.skip", defaultValue = "false")
private boolean mavenTestSkip;
@Parameter(property = "skipTests", defaultValue = "false")
private boolean skipTests;
@Parameter(property = "skipTests", defaultValue = "false") private boolean skipTests;
public void execute() throws MojoExecutionException, MojoFailureException {
if (skip || mavenTestSkip || skipTests) {
if (skip) getLog().info("Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip=" + skip);
if (mavenTestSkip) getLog().info("Skipping Spring Cloud Contract Verifier execution: maven.test.skip=" + mavenTestSkip);
if (skipTests) getLog().info("Skipping Spring Cloud Contract Verifier execution: skipTests" + skipTests);
return;
}
getLog().info("Generating server tests source code for Spring Cloud Contract Verifier contract verification");
final ContractVerifierConfigProperties config = new ContractVerifierConfigProperties();
config.setContractsDslDir(contractsDirectory);
config.setGeneratedTestSourcesDir(generatedTestSourcesDir);
config.setTargetFramework(testFramework);
config.setTestMode(testMode);
config.setBasePackageForTests(basePackageForTests);
config.setBaseClassForTests(baseClassForTests);
config.setRuleClassForTests(ruleClassForTests);
config.setNameSuffixForTests(nameSuffixForTests);
config.setImports(imports);
config.setStaticImports(staticImports);
config.setIgnoredFiles(ignoredFiles);
config.setExcludedFiles(excludedFiles);
project.addTestCompileSourceRoot(generatedTestSourcesDir.getAbsolutePath());
if (getLog().isInfoEnabled()) {
getLog().info("Test Source directory: " + generatedTestSourcesDir.getAbsolutePath() + " added.");
getLog().info("Using " + config.getBaseClassForTests() + " as base class for test classes");
}
try {
TestGenerator generator = new TestGenerator(config);
int generatedClasses = generator.generate();
getLog().info("Generated " + generatedClasses + " test classes.");
} catch (ContractVerifierException e) {
throw new MojoExecutionException(String.format("Spring Cloud Contract Verifier Plugin exception: %s", e.getMessage()), e);
}
}
public void execute() throws MojoExecutionException, MojoFailureException {
if (skip || mavenTestSkip || skipTests) {
if (skip) getLog().info("Skipping Spring Cloud Contract Verifier execution: spring.cloud.contract.verifier.skip=" + skip);
if (mavenTestSkip) getLog().info("Skipping Spring Cloud Contract Verifier execution: maven.test.skip=" + mavenTestSkip);
if (skipTests) getLog().info("Skipping Spring Cloud Contract Verifier execution: skipTests" + skipTests);
return;
}
getLog().info(
"Generating server tests source code for Spring Cloud Contract Verifier contract verification");
final ContractVerifierConfigProperties config = new ContractVerifierConfigProperties();
config.setContractsDslDir(contractsDirectory);
config.setGeneratedTestSourcesDir(generatedTestSourcesDir);
config.setTargetFramework(testFramework);
config.setTestMode(testMode);
config.setBasePackageForTests(basePackageForTests);
config.setBaseClassForTests(baseClassForTests);
config.setRuleClassForTests(ruleClassForTests);
config.setNameSuffixForTests(nameSuffixForTests);
config.setImports(imports);
config.setStaticImports(staticImports);
config.setIgnoredFiles(ignoredFiles);
config.setExcludedFiles(excludedFiles);
project.addTestCompileSourceRoot(generatedTestSourcesDir.getAbsolutePath());
if (getLog().isInfoEnabled()) {
getLog().info(
"Test Source directory: " + generatedTestSourcesDir.getAbsolutePath()
+ " added.");
getLog().info("Using " + config.getBaseClassForTests()
+ " as base class for test classes");
}
try {
TestGenerator generator = new TestGenerator(config);
int generatedClasses = generator.generate();
getLog().info("Generated " + generatedClasses + " test classes.");
}
catch (ContractVerifierException e) {
throw new MojoExecutionException(
String.format("Spring Cloud Contract Verifier Plugin exception: %s",
e.getMessage()), e);
}
}
public List<String> getExcludedFiles() {
return excludedFiles;
}
public List<String> getExcludedFiles() {
return excludedFiles;
}
public void setExcludedFiles(List<String> excludedFiles) {
this.excludedFiles = excludedFiles;
}
public void setExcludedFiles(List<String> excludedFiles) {
this.excludedFiles = excludedFiles;
}
public List<String> getIgnoredFiles() {
return ignoredFiles;
}
public List<String> getIgnoredFiles() {
return ignoredFiles;
}
public void setIgnoredFiles(List<String> ignoredFiles) {
this.ignoredFiles = ignoredFiles;
}
public void setIgnoredFiles(List<String> ignoredFiles) {
this.ignoredFiles = ignoredFiles;
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.contract.maven.verifier;
import java.util.List;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Plugin;
import org.apache.maven.project.MavenProject;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.codehaus.plexus.archiver.jar.Manifest;
import org.codehaus.plexus.archiver.jar.ManifestException;
public class ManifestCreator {
public static Manifest createManifest(MavenProject project) throws ManifestException {
Manifest manifest = new Manifest();
Plugin verifierMavenPlugin = findMavenPlugin(project.getBuildPlugins());
manifest.addConfiguredAttribute(new Manifest.Attribute(
"Spring-Cloud-Contract-Verifier-Maven-Plugin-Version", verifierMavenPlugin.getVersion()));
if (DefaultGroovyMethods.asBoolean(verifierMavenPlugin.getDependencies())) {
Dependency verifierDependency = findVerifierDependency(verifierMavenPlugin.getDependencies());
if (verifierDependency != null) {
String verifierVersion = verifierDependency.getVersion();
manifest.addConfiguredAttribute(new Manifest.Attribute("Spring-Cloud-Contract-Verifier-Version",
verifierVersion));
}
}
return manifest;
}
private static Plugin findMavenPlugin(List<Plugin> plugins) {
for (Plugin plugin : plugins) {
if ("spring-cloud-contract-maven-plugin".equals(plugin.getArtifactId())) {
return plugin;
}
}
return null;
}
private static Dependency findVerifierDependency(List<Dependency> deps) {
for (Dependency dep : deps) {
if ("spring-cloud-contract-verifier".equals(dep.getArtifactId())) {
return dep;
}
}
return null;
}
}

View File

@@ -1,5 +1,4 @@
/**
*
/*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,10 +15,10 @@
*/
package org.springframework.cloud.contract.maven.verifier;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import javax.inject.Inject;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
@@ -41,110 +40,110 @@ import static com.google.common.base.Strings.isNullOrEmpty;
@Mojo(name = "run", requiresProject = false, requiresDependencyResolution = ResolutionScope.RUNTIME)
public class RunMojo extends AbstractMojo {
@Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
private RepositorySystemSession repoSession;
@Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
private RepositorySystemSession repoSession;
@Parameter(defaultValue = "${project.build.directory}/contracts/mappings")
private File stubsDirectory;
@Parameter(defaultValue = "${project.build.directory}/contracts/mappings")
private File stubsDirectory;
@Parameter(property = "stubsDirectory", defaultValue = "${basedir}")
private File destination;
@Parameter(property = "stubsDirectory", defaultValue = "${basedir}")
private File destination;
/**
* HTTP port for WireMock server
*/
@Parameter(property = "spring.cloud.contract.verifier.http.port", defaultValue = "8080")
private int httpPort;
/**
* HTTP port for WireMock server
*/
@Parameter(property = "spring.cloud.contract.verifier.http.port", defaultValue = "8080")
private int httpPort;
/**
* Set this to "true" to bypass verifier execution.
*/
@Parameter(property = "spring.cloud.contract.verifier.skip", defaultValue = "false")
private boolean skip;
/**
* Set this to "true" to bypass verifier execution.
*/
@Parameter(property = "spring.cloud.contract.verifier.skip", defaultValue = "false")
private boolean skip;
/**
* Set this to "true" to bypass verifier test generation.
*/
@Parameter(property = "spring.cloud.contract.verifier.skipTestOnly", defaultValue = "false")
private boolean skipTestOnly;
/**
* Set this to "true" to bypass verifier test generation.
*/
@Parameter(property = "spring.cloud.contract.verifier.skipTestOnly", defaultValue = "false")
private boolean skipTestOnly;
@Parameter(property = "spring.cloud.contract.verifier.stubs")
private String stubs;
@Parameter(property = "spring.cloud.contract.verifier.stubs")
private String stubs;
@Parameter(property = "spring.cloud.contract.verifier.http.minPort", defaultValue = "10000")
private int minPort;
@Parameter(property = "spring.cloud.contract.verifier.http.minPort", defaultValue = "10000")
private int minPort;
@Parameter(property = "spring.cloud.contract.verifier.http.maxPort", defaultValue = "15000")
private int maxPort;
@Parameter(property = "spring.cloud.contract.verifier.http.maxPort", defaultValue = "15000")
private int maxPort;
/**
* Classifier used by stubs artifacts.
*/
@Parameter(defaultValue = "stubs")
private String stubsClassifier = "stubs";
/**
* Classifier used by stubs artifacts.
*/
@Parameter(defaultValue = "stubs")
private String stubsClassifier = "stubs";
@Parameter(defaultValue = "${session}", readonly = true)
private MavenSession mavenSession;
@Parameter(defaultValue = "${session}", readonly = true)
private MavenSession mavenSession;
private final LocalStubRunner localStubRunner;
private final LocalStubRunner localStubRunner;
private final RemoteStubRunner remoteStubRunner;
private final RemoteStubRunner remoteStubRunner;
@Inject
public RunMojo(LocalStubRunner localStubRunner, RemoteStubRunner remoteStubRunner) {
this.localStubRunner = localStubRunner;
this.remoteStubRunner = remoteStubRunner;
}
@Inject
public RunMojo(LocalStubRunner localStubRunner, RemoteStubRunner remoteStubRunner) {
this.localStubRunner = localStubRunner;
this.remoteStubRunner = remoteStubRunner;
}
public void execute() throws MojoExecutionException, MojoFailureException {
if (skip || skipTestOnly) {
getLog().info("Skipping verifier execution: spring.cloud.contract.verifier.skip=" + String.valueOf(skip));
return;
}
BatchStubRunner batchStubRunner = null;
StubRunnerOptionsBuilder optionsBuilder = new StubRunnerOptionsBuilder()
.withStubsClassifier(stubsClassifier);
if (isNullOrEmpty(stubs)) {
StubRunnerOptions options = optionsBuilder
.withPort(httpPort)
.build();
StubRunner stubRunner = localStubRunner.run(resolveStubsDirectory().getAbsolutePath(), options);
batchStubRunner = new BatchStubRunner(Collections.singleton(stubRunner));
} else {
StubRunnerOptions options = optionsBuilder
.withStubs(stubs)
.withMinMaxPort(minPort, maxPort)
.build();
batchStubRunner = remoteStubRunner.run(options, repoSession);
}
pressAnyKeyToContinue();
if (batchStubRunner != null) {
try {
batchStubRunner.close();
} catch (IOException e) {
throw new MojoExecutionException("Fail to close batch stub runner", e);
}
}
}
public void execute() throws MojoExecutionException, MojoFailureException {
if (skip || skipTestOnly) {
getLog().info("Skipping verifier execution: spring.cloud.contract.verifier.skip=" + String.valueOf(skip));
return;
}
BatchStubRunner batchStubRunner = null;
StubRunnerOptionsBuilder optionsBuilder = new StubRunnerOptionsBuilder()
.withStubsClassifier(stubsClassifier);
if (isNullOrEmpty(stubs)) {
StubRunnerOptions options = optionsBuilder
.withPort(httpPort)
.build();
StubRunner stubRunner = localStubRunner.run(resolveStubsDirectory().getAbsolutePath(), options);
batchStubRunner = new BatchStubRunner(Collections.singleton(stubRunner));
} else {
StubRunnerOptions options = optionsBuilder
.withStubs(stubs)
.withMinMaxPort(minPort, maxPort)
.build();
batchStubRunner = remoteStubRunner.run(options, repoSession);
}
pressAnyKeyToContinue();
if (batchStubRunner != null) {
try {
batchStubRunner.close();
} catch (IOException e) {
throw new MojoExecutionException("Fail to close batch stub runner", e);
}
}
}
private File resolveStubsDirectory() {
if (isInsideProject()) {
return stubsDirectory;
} else {
return destination;
}
}
private File resolveStubsDirectory() {
if (isInsideProject()) {
return stubsDirectory;
} else {
return destination;
}
}
private void pressAnyKeyToContinue() {
getLog().info("Press ENTER to continue...");
try {
System.in.read();
} catch (Exception ignored) {
}
}
private void pressAnyKeyToContinue() {
getLog().info("Press ENTER to continue...");
try {
System.in.read();
} catch (Exception ignored) {
}
}
private boolean isInsideProject() {
return mavenSession.getRequest().isProjectPresent();
}
private boolean isInsideProject() {
return mavenSession.getRequest().isProjectPresent();
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.contract.maven.verifier.stubrunner;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.apache.maven.project.MavenProject;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.springframework.cloud.contract.stubrunner.AetherStubDownloader;
@Named
@Singleton
public class AetherStubDownloaderFactory {
private final MavenProject project;
private final RepositorySystem repoSystem;
@Inject
public AetherStubDownloaderFactory(RepositorySystem repoSystem,
MavenProject project) {
this.repoSystem = repoSystem;
this.project = project;
}
public AetherStubDownloader build(RepositorySystemSession repoSession) {
return new AetherStubDownloader(repoSystem,
project.getRemoteProjectRepositories(), repoSession);
}
}

View File

@@ -1,5 +1,4 @@
/**
*
/*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,25 +13,26 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.contract.maven.verifier.stubrunner
package org.springframework.cloud.contract.maven.verifier.stubrunner;
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import org.springframework.cloud.contract.stubrunner.StubConfiguration
import org.springframework.cloud.contract.stubrunner.StubRunner
import org.springframework.cloud.contract.stubrunner.StubRunnerOptions
import java.lang.invoke.MethodHandles;
import javax.inject.Named;
import javax.inject.Named
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.contract.stubrunner.StubConfiguration;
import org.springframework.cloud.contract.stubrunner.StubRunner;
import org.springframework.cloud.contract.stubrunner.StubRunnerOptions;
@Named
@CompileStatic
@Slf4j
class LocalStubRunner {
public class LocalStubRunner {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
StubRunner run(String contractsDir, StubRunnerOptions options) {
log.info("Launching StubRunner with contracts from ${contractsDir}")
StubRunner stubRunner = new StubRunner(options, contractsDir, new StubConfiguration(contractsDir))
stubRunner.runStubs()
return stubRunner
}
public StubRunner run(final String contractsDir, StubRunnerOptions options) {
log.info("Launching StubRunner with contracts from " + contractsDir);
StubRunner stubRunner = new StubRunner(options, contractsDir,
new StubConfiguration(contractsDir));
stubRunner.runStubs();
return stubRunner;
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.contract.maven.verifier.stubrunner;
import java.lang.invoke.MethodHandles;
import javax.inject.Inject;
import javax.inject.Named;
import org.eclipse.aether.RepositorySystemSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.contract.stubrunner.AetherStubDownloader;
import org.springframework.cloud.contract.stubrunner.BatchStubRunner;
import org.springframework.cloud.contract.stubrunner.BatchStubRunnerFactory;
import org.springframework.cloud.contract.stubrunner.RunningStubs;
import org.springframework.cloud.contract.stubrunner.StubRunnerOptions;
@Named
public class RemoteStubRunner {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final AetherStubDownloaderFactory aetherStubDownloaderFactory;
@Inject
public RemoteStubRunner(AetherStubDownloaderFactory aetherStubDownloaderFactory) {
this.aetherStubDownloaderFactory = aetherStubDownloaderFactory;
}
public BatchStubRunner run(StubRunnerOptions options, RepositorySystemSession repositorySystemSession) {
AetherStubDownloader stubDownloader = aetherStubDownloaderFactory.build(repositorySystemSession);
try {
log.debug("Launching StubRunner with args: " + String.valueOf(options));
BatchStubRunner stubRunner = new BatchStubRunnerFactory(options,
stubDownloader).buildBatchStubRunner();
RunningStubs runningCollaborators = stubRunner.runStubs();
log.info(runningCollaborators.toString());
return stubRunner;
}
catch (Exception e) {
log.error("An exception occurred while trying to execute the stubs: " + e.getMessage());
throw e;
}
}
}