Bumping versions

This commit is contained in:
buildmaster
2020-09-17 00:23:53 +00:00
parent 3a1e3c9640
commit ffd6574532
460 changed files with 3789 additions and 6477 deletions

View File

@@ -63,15 +63,13 @@ final class AetherFactories {
public static RepositorySystem newRepositorySystem() {
DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator();
locator.addService(RepositoryConnectorFactory.class,
BasicRepositoryConnectorFactory.class);
locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class);
locator.addService(TransporterFactory.class, FileTransporterFactory.class);
locator.addService(TransporterFactory.class, HttpTransporterFactory.class);
return locator.getService(RepositorySystem.class);
}
public static RepositorySystemSession newSession(RepositorySystem system,
boolean workOffline) {
public static RepositorySystemSession newSession(RepositorySystem system, boolean workOffline) {
DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
session.setOffline(workOffline);
if (!workOffline) {
@@ -80,19 +78,17 @@ final class AetherFactories {
session.setChecksumPolicy(RepositoryPolicy.CHECKSUM_POLICY_WARN);
String localRepositoryDirectory = localRepositoryDirectory(workOffline);
if (log.isDebugEnabled()) {
log.debug("Local Repository Directory set to [" + localRepositoryDirectory
+ "]. Work offline: [" + workOffline + "]");
log.debug("Local Repository Directory set to [" + localRepositoryDirectory + "]. Work offline: ["
+ workOffline + "]");
}
LocalRepository localRepo = new LocalRepository(localRepositoryDirectory);
session.setLocalRepositoryManager(
system.newLocalRepositoryManager(session, localRepo));
session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));
return session;
}
protected static String localRepositoryDirectory(boolean workOffline) {
String localRepoLocationFromSettings = settings().getLocalRepository();
String currentLocalRepo = readPropertyFromSystemProps(
localRepoLocationFromSettings);
String currentLocalRepo = readPropertyFromSystemProps(localRepoLocationFromSettings);
if (workOffline) {
return currentLocalRepo;
}
@@ -105,21 +101,17 @@ final class AetherFactories {
}
catch (IOException e) {
if (log.isDebugEnabled()) {
log.debug(
"Failed to create a new temporary directory, will generate a new one under temp dir");
log.debug("Failed to create a new temporary directory, will generate a new one under temp dir");
}
return System.getProperty("java.io.tmpdir") + File.separator
+ RANDOM.nextInt();
return System.getProperty("java.io.tmpdir") + File.separator + RANDOM.nextInt();
}
}
private static String readPropertyFromSystemProps(
String localRepoLocationFromSettings) {
private static String readPropertyFromSystemProps(String localRepoLocationFromSettings) {
String mavenLocalRepo = fromSystemPropOrEnv(MAVEN_LOCAL_REPOSITORY_LOCATION);
return StringUtils.hasText(mavenLocalRepo) ? mavenLocalRepo
: localRepoLocationFromSettings != null ? localRepoLocationFromSettings
: System.getProperty("user.home") + File.separator + ".m2"
+ File.separator + "repository";
: System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository";
}
// system prop takes precedence over env var
@@ -134,12 +126,10 @@ final class AetherFactories {
private static File userSettings() {
String user = fromSystemPropOrEnv(MAVEN_USER_SETTINGS_LOCATION);
if (user == null) {
File file = new File(
new File(System.getProperty("user.home")).getAbsoluteFile(),
File file = new File(new File(System.getProperty("user.home")).getAbsoluteFile(),
File.separator + ".m2" + File.separator + "settings.xml");
if (log.isDebugEnabled()) {
log.debug("No custom maven user settings provided, will use [" + file
+ "]");
log.debug("No custom maven user settings provided, will use [" + file + "]");
}
return file;
}

View File

@@ -86,8 +86,7 @@ public class AetherStubDownloader implements StubDownloader {
public AetherStubDownloader(StubRunnerOptions stubRunnerOptions) {
this.deleteStubsAfterTest = stubRunnerOptions.isDeleteStubsAfterTest();
if (log.isDebugEnabled()) {
log.debug("Will be resolving versions for the following options: ["
+ stubRunnerOptions + "]");
log.debug("Will be resolving versions for the following options: [" + stubRunnerOptions + "]");
}
this.settings = settings();
this.remoteRepos = remoteRepositories(stubRunnerOptions);
@@ -119,25 +118,22 @@ public class AetherStubDownloader implements StubDownloader {
* @param remoteRepositories remote artifact repositories
* @param session repository system session
*/
public AetherStubDownloader(RepositorySystem repositorySystem,
List<RemoteRepository> remoteRepositories, RepositorySystemSession session,
Settings settings) {
public AetherStubDownloader(RepositorySystem repositorySystem, List<RemoteRepository> remoteRepositories,
RepositorySystemSession session, Settings settings) {
this.deleteStubsAfterTest = true;
this.remoteRepos = remoteRepositories;
this.settings = settings;
this.repositorySystem = repositorySystem;
this.session = session;
if (remoteReposMissing()) {
log.error(
"Remote repositories for stubs are not specified and work offline flag wasn't passed");
log.error("Remote repositories for stubs are not specified and work offline flag wasn't passed");
}
this.workOffline = false;
registerShutdownHook();
}
private static File unpackStubJarToATemporaryFolder(URI stubJarUri) {
File tmpDirWhereStubsWillBeUnzipped = TemporaryFileStorage
.createTempDir(TEMP_DIR_PREFIX);
File tmpDirWhereStubsWillBeUnzipped = TemporaryFileStorage.createTempDir(TEMP_DIR_PREFIX);
log.info("Unpacking stub from JAR [URI: " + stubJarUri + "]");
unzipTo(new File(stubJarUri), tmpDirWhereStubsWillBeUnzipped);
TemporaryFileStorage.add(tmpDirWhereStubsWillBeUnzipped);
@@ -148,19 +144,16 @@ public class AetherStubDownloader implements StubDownloader {
return this.remoteRepos == null || this.remoteRepos.isEmpty();
}
private List<RemoteRepository> remoteRepositories(
StubRunnerOptions stubRunnerOptions) {
private List<RemoteRepository> remoteRepositories(StubRunnerOptions stubRunnerOptions) {
if (stubRunnerOptions.stubRepositoryRoot == null) {
return new ArrayList<>();
}
final String[] repos = stubRunnerOptions.getStubRepositoryRootAsString()
.split(",");
final String[] repos = stubRunnerOptions.getStubRepositoryRootAsString().split(",");
final List<RemoteRepository> remoteRepos = new ArrayList<>();
for (int i = 0; i < repos.length; i++) {
if (StringUtils.hasText(repos[i])) {
final RemoteRepository.Builder builder = new RemoteRepository.Builder(
"remote" + i, "default", repos[i]).setAuthentication(
resolveAuthentication(stubRunnerOptions));
final RemoteRepository.Builder builder = new RemoteRepository.Builder("remote" + i, "default", repos[i])
.setAuthentication(resolveAuthentication(stubRunnerOptions));
if (stubRunnerOptions.getProxyOptions() != null) {
final StubRunnerProxyOptions p = stubRunnerOptions.getProxyOptions();
builder.setProxy(new Proxy(null, p.getProxyHost(), p.getProxyPort()));
@@ -179,49 +172,38 @@ public class AetherStubDownloader implements StubDownloader {
Server stubServer = this.settings.getServer(stubRunnerOptions.serverId);
if (stubServer != null) {
if (log.isDebugEnabled()) {
log.debug("Custom server id [" + stubServer.getId()
+ "] passed will resolve credentials");
log.debug("Custom server id [" + stubServer.getId() + "] passed will resolve credentials");
}
SettingsDecryptionRequest settingsDecryptionRequest = new DefaultSettingsDecryptionRequest(
stubServer);
SettingsDecryptionRequest settingsDecryptionRequest = new DefaultSettingsDecryptionRequest(stubServer);
String stubServerPassword = new MavenSettings().createSettingsDecrypter()
.decrypt(settingsDecryptionRequest).getServer().getPassword();
return buildAuthentication(stubServerPassword, stubServer.getUsername());
}
}
return buildAuthentication(stubRunnerOptions.password,
stubRunnerOptions.username);
return buildAuthentication(stubRunnerOptions.password, stubRunnerOptions.username);
}
Authentication buildAuthentication(String stubServerPassword, String username) {
return new AuthenticationBuilder().addUsername(username)
.addPassword(stubServerPassword).build();
return new AuthenticationBuilder().addUsername(username).addPassword(stubServerPassword).build();
}
private File unpackedJar(String resolvedVersion, String stubsGroup,
String stubsModule, String classifier) {
private File unpackedJar(String resolvedVersion, String stubsGroup, String stubsModule, String classifier) {
try {
log.info("Resolved version is [" + resolvedVersion + "]");
if (StringUtils.isEmpty(resolvedVersion)) {
log.warn("Stub for group [" + stubsGroup + "] module [" + stubsModule
+ "] and classifier [" + classifier + "] not found in "
+ this.remoteRepos);
log.warn("Stub for group [" + stubsGroup + "] module [" + stubsModule + "] and classifier ["
+ classifier + "] not found in " + this.remoteRepos);
return null;
}
Artifact artifact = new DefaultArtifact(stubsGroup, stubsModule, classifier,
ARTIFACT_EXTENSION, resolvedVersion);
ArtifactRequest request = new ArtifactRequest(artifact, this.remoteRepos,
null);
Artifact artifact = new DefaultArtifact(stubsGroup, stubsModule, classifier, ARTIFACT_EXTENSION,
resolvedVersion);
ArtifactRequest request = new ArtifactRequest(artifact, this.remoteRepos, null);
if (log.isDebugEnabled()) {
log.debug("Resolving artifact [" + artifact
+ "] using remote repositories " + this.remoteRepos);
log.debug("Resolving artifact [" + artifact + "] using remote repositories " + this.remoteRepos);
}
ArtifactResult result = this.repositorySystem.resolveArtifact(this.session,
request);
log.info("Resolved artifact [" + artifact + "] to "
+ result.getArtifact().getFile());
File temporaryFile = unpackStubJarToATemporaryFolder(
result.getArtifact().getFile().toURI());
ArtifactResult result = this.repositorySystem.resolveArtifact(this.session, request);
log.info("Resolved artifact [" + artifact + "] to " + result.getArtifact().getFile());
File temporaryFile = unpackStubJarToATemporaryFolder(result.getArtifact().getFile().toURI());
log.info("Unpacked file to [" + temporaryFile + "]");
return temporaryFile;
}
@@ -230,44 +212,35 @@ public class AetherStubDownloader implements StubDownloader {
}
catch (Exception e) {
throw new IllegalStateException(
"Exception occurred while trying to download a stub for group ["
+ stubsGroup + "] module [" + stubsModule
+ "] and classifier [" + classifier + "] in "
+ this.remoteRepos,
"Exception occurred while trying to download a stub for group [" + stubsGroup + "] module ["
+ stubsModule + "] and classifier [" + classifier + "] in " + this.remoteRepos,
e);
}
}
private String getVersion(String stubsGroup, String stubsModule, String version,
String classifier) {
private String getVersion(String stubsGroup, String stubsModule, String version, String classifier) {
if (StringUtils.isEmpty(version) || LATEST_VERSION_IN_IVY.equals(version)) {
log.info("Desired version is [" + version
+ "] - will try to resolve the latest version");
return resolveHighestArtifactVersion(stubsGroup, stubsModule, classifier,
LATEST_ARTIFACT_VERSION);
log.info("Desired version is [" + version + "] - will try to resolve the latest version");
return resolveHighestArtifactVersion(stubsGroup, stubsModule, classifier, LATEST_ARTIFACT_VERSION);
}
return resolveHighestArtifactVersion(stubsGroup, stubsModule, classifier,
version);
return resolveHighestArtifactVersion(stubsGroup, stubsModule, classifier, version);
}
@Override
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
StubConfiguration stubConfiguration) {
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(StubConfiguration stubConfiguration) {
try {
String version = getVersion(stubConfiguration.groupId,
stubConfiguration.artifactId, stubConfiguration.version,
stubConfiguration.classifier);
String version = getVersion(stubConfiguration.groupId, stubConfiguration.artifactId,
stubConfiguration.version, stubConfiguration.classifier);
if (log.isDebugEnabled()) {
log.debug("Will download the stub for version [" + version + "]");
}
File unpackedJar = unpackedJar(version, stubConfiguration.groupId,
stubConfiguration.artifactId, stubConfiguration.classifier);
File unpackedJar = unpackedJar(version, stubConfiguration.groupId, stubConfiguration.artifactId,
stubConfiguration.classifier);
if (unpackedJar == null) {
return null;
}
return new AbstractMap.SimpleEntry<>(new StubConfiguration(
stubConfiguration.groupId, stubConfiguration.artifactId, version,
stubConfiguration.classifier), unpackedJar);
return new AbstractMap.SimpleEntry<>(new StubConfiguration(stubConfiguration.groupId,
stubConfiguration.artifactId, version, stubConfiguration.classifier), unpackedJar);
}
catch (Exception ex) {
log.warn("Exception occurred while trying to fetch the stubs", ex);
@@ -275,16 +248,13 @@ public class AetherStubDownloader implements StubDownloader {
}
}
private String resolveHighestArtifactVersion(String stubsGroup, String stubsModule,
String classifier, String version) {
Artifact artifact = new DefaultArtifact(stubsGroup, stubsModule, classifier,
ARTIFACT_EXTENSION, version);
VersionRangeRequest versionRangeRequest = new VersionRangeRequest(artifact,
this.remoteRepos, null);
private String resolveHighestArtifactVersion(String stubsGroup, String stubsModule, String classifier,
String version) {
Artifact artifact = new DefaultArtifact(stubsGroup, stubsModule, classifier, ARTIFACT_EXTENSION, version);
VersionRangeRequest versionRangeRequest = new VersionRangeRequest(artifact, this.remoteRepos, null);
VersionRangeResult rangeResult;
try {
rangeResult = this.repositorySystem.resolveVersionRange(this.session,
versionRangeRequest);
rangeResult = this.repositorySystem.resolveVersionRange(this.session, versionRangeRequest);
if (log.isDebugEnabled()) {
log.debug("Resolved version range is [" + rangeResult + "]");
}
@@ -293,19 +263,17 @@ public class AetherStubDownloader implements StubDownloader {
throw new IllegalStateException("Cannot resolve version range", e);
}
if (rangeResult.getHighestVersion() == null) {
throw new IllegalArgumentException("For groupId [" + stubsGroup
+ "] artifactId [" + stubsModule + "] " + "and classifier ["
+ classifier
+ "] the version was not resolved! The following exceptions took place "
+ rangeResult.getExceptions());
throw new IllegalArgumentException(
"For groupId [" + stubsGroup + "] artifactId [" + stubsModule + "] " + "and classifier ["
+ classifier + "] the version was not resolved! The following exceptions took place "
+ rangeResult.getExceptions());
}
return rangeResult.getHighestVersion() == null ? null
: rangeResult.getHighestVersion().toString();
return rangeResult.getHighestVersion() == null ? null : rangeResult.getHighestVersion().toString();
}
private void registerShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(() -> TemporaryFileStorage
.cleanup(AetherStubDownloader.this.deleteStubsAfterTest)));
Runtime.getRuntime().addShutdownHook(
new Thread(() -> TemporaryFileStorage.cleanup(AetherStubDownloader.this.deleteStubsAfterTest)));
}
}

View File

@@ -33,8 +33,7 @@ class Arguments {
this(stubRunnerOptions, "", null);
}
Arguments(StubRunnerOptions stubRunnerOptions, String repositoryPath,
StubConfiguration stub) {
Arguments(StubRunnerOptions stubRunnerOptions, String repositoryPath, StubConfiguration stub) {
this.stubRunnerOptions = stubRunnerOptions;
this.repositoryPath = repositoryPath == null ? "" : repositoryPath;
this.stub = stub;
@@ -54,9 +53,8 @@ class Arguments {
@Override
public String toString() {
return "Arguments{" + "stubRunnerOptions=" + this.stubRunnerOptions
+ ", repositoryPath='" + this.repositoryPath + '\'' + ", stub="
+ this.stub + '}';
return "Arguments{" + "stubRunnerOptions=" + this.stubRunnerOptions + ", repositoryPath='" + this.repositoryPath
+ '\'' + ", stub=" + this.stub + '}';
}
}

View File

@@ -59,23 +59,20 @@ class AvailablePortScanner {
for (int i = 0; i < this.maxRetryCount; i++) {
try {
int numberOfPortsToBind = this.maxPortNumber - this.minPortNumber + 1;
int portToScan = new Random().nextInt(numberOfPortsToBind)
+ this.minPortNumber;
int portToScan = new Random().nextInt(numberOfPortsToBind) + this.minPortNumber;
checkIfPortIsAvailable(portToScan);
return executeLogicForAvailablePort(portToScan, closure);
}
catch (IOException exception) {
if (log.isDebugEnabled()) {
log.debug("Failed to execute callback (try: " + i + "/"
+ this.maxRetryCount + ")", exception);
log.debug("Failed to execute callback (try: " + i + "/" + this.maxRetryCount + ")", exception);
}
}
}
throw new NoPortAvailableException(this.minPortNumber, this.maxPortNumber);
}
private <T> T executeLogicForAvailablePort(int portToScan, PortCallback<T> closure)
throws IOException {
private <T> T executeLogicForAvailablePort(int portToScan, PortCallback<T> closure) throws IOException {
if (log.isDebugEnabled()) {
log.debug("Trying to execute closure with port [" + portToScan + "]");
}
@@ -104,8 +101,7 @@ class AvailablePortScanner {
static class NoPortAvailableException extends RuntimeException {
NoPortAvailableException(int lowerBound, int upperBound) {
super("Could not find available port in range " + lowerBound + ":"
+ upperBound);
super("Could not find available port in range " + lowerBound + ":" + upperBound);
}
}
@@ -114,8 +110,8 @@ class AvailablePortScanner {
static class InvalidPortRange extends RuntimeException {
InvalidPortRange(int lowerBound, int upperBound) {
super("Invalid bounds exceptions, min port [" + lowerBound
+ "] is greater to max port [" + upperBound + "]");
super("Invalid bounds exceptions, min port [" + lowerBound + "] is greater to max port [" + upperBound
+ "]");
}
}

View File

@@ -87,8 +87,7 @@ public class BatchStubRunner implements StubRunning {
public Map<StubConfiguration, Collection<Contract>> getContracts() {
Map<StubConfiguration, Collection<Contract>> map = new LinkedHashMap<>();
for (StubRunner stubRunner : this.stubRunners) {
for (Entry<StubConfiguration, Collection<Contract>> entry : stubRunner
.getContracts().entrySet()) {
for (Entry<StubConfiguration, Collection<Contract>> entry : stubRunner.getContracts().entrySet()) {
if (map.containsKey(entry.getKey())) {
map.get(entry.getKey()).addAll(entry.getValue());
}
@@ -109,10 +108,9 @@ public class BatchStubRunner implements StubRunning {
}
}
if (!success) {
throw new IllegalArgumentException("No label with name [" + labelName
+ "] for " + "dependency [" + ivyNotation
+ "] was found. Here you have the list of dependencies "
+ "and their labels [" + ivyToLabels() + "]");
throw new IllegalArgumentException("No label with name [" + labelName + "] for " + "dependency ["
+ ivyNotation + "] was found. Here you have the list of dependencies " + "and their labels ["
+ ivyToLabels() + "]");
}
return success;
}
@@ -123,8 +121,7 @@ public class BatchStubRunner implements StubRunning {
if (builder.length() > 0) {
builder.append("\n");
}
builder.append("Dependency [").append(entry.getKey()).append("] has labels ")
.append(entry.getValue());
builder.append("Dependency [").append(entry.getKey()).append("] has labels ").append(entry.getValue());
}
return builder.toString();
}
@@ -138,10 +135,8 @@ public class BatchStubRunner implements StubRunning {
}
}
if (!success) {
throw new IllegalArgumentException(
"No label with name [" + labelName + "] was found. "
+ "Here you have the list of dependencies and their labels ["
+ ivyToLabels() + "]");
throw new IllegalArgumentException("No label with name [" + labelName + "] was found. "
+ "Here you have the list of dependencies and their labels [" + ivyToLabels() + "]");
}
return success;
}
@@ -161,8 +156,7 @@ public class BatchStubRunner implements StubRunning {
public Map<String, Collection<String>> labels() {
Map<String, Collection<String>> map = new LinkedHashMap<>();
for (StubRunner stubRunner : this.stubRunners) {
for (Entry<String, Collection<String>> entry : stubRunner.labels()
.entrySet()) {
for (Entry<String, Collection<String>> entry : stubRunner.labels().entrySet()) {
if (map.containsKey(entry.getKey())) {
map.get(entry.getKey()).addAll(entry.getValue());
}

View File

@@ -38,35 +38,30 @@ public class BatchStubRunnerFactory {
this(stubRunnerOptions, new NoOpStubMessages());
}
public BatchStubRunnerFactory(StubRunnerOptions stubRunnerOptions,
MessageVerifier verifier) {
public BatchStubRunnerFactory(StubRunnerOptions stubRunnerOptions, MessageVerifier verifier) {
this(stubRunnerOptions, aetherStubDownloader(stubRunnerOptions), verifier);
}
public BatchStubRunnerFactory(StubRunnerOptions stubRunnerOptions,
StubDownloader stubDownloader) {
public BatchStubRunnerFactory(StubRunnerOptions stubRunnerOptions, StubDownloader stubDownloader) {
this(stubRunnerOptions, stubDownloader, new NoOpStubMessages());
}
public BatchStubRunnerFactory(StubRunnerOptions stubRunnerOptions,
StubDownloader stubDownloader, MessageVerifier<?> contractVerifierMessaging) {
public BatchStubRunnerFactory(StubRunnerOptions stubRunnerOptions, StubDownloader stubDownloader,
MessageVerifier<?> contractVerifierMessaging) {
this.stubRunnerOptions = stubRunnerOptions;
this.stubDownloader = stubDownloader;
this.contractVerifierMessaging = contractVerifierMessaging;
}
private static StubDownloader aetherStubDownloader(
StubRunnerOptions stubRunnerOptions) {
private static StubDownloader aetherStubDownloader(StubRunnerOptions stubRunnerOptions) {
StubDownloaderBuilderProvider provider = new StubDownloaderBuilderProvider();
return provider.get(stubRunnerOptions);
}
public BatchStubRunner buildBatchStubRunner() {
StubRunnerFactory stubRunnerFactory = new StubRunnerFactory(
this.stubRunnerOptions, this.stubDownloader,
StubRunnerFactory stubRunnerFactory = new StubRunnerFactory(this.stubRunnerOptions, this.stubDownloader,
this.contractVerifierMessaging);
return new BatchStubRunner(
stubRunnerFactory.createStubsFromServiceConfiguration());
return new BatchStubRunner(stubRunnerFactory.createStubsFromServiceConfiguration());
}
}

View File

@@ -62,23 +62,19 @@ public class ClasspathStubProvider implements StubDownloaderBuilder {
return null;
}
log.info("Will download stubs from classpath");
return new ResourceResolvingStubDownloader(stubRunnerOptions, this::repoRoot,
this::gavPattern);
return new ResourceResolvingStubDownloader(stubRunnerOptions, this::repoRoot, this::gavPattern);
}
private RepoRoots repoRoot(StubRunnerOptions stubRunnerOptions,
StubConfiguration configuration) {
private RepoRoots repoRoot(StubRunnerOptions stubRunnerOptions, StubConfiguration configuration) {
Resource repositoryRoot = stubRunnerOptions.getStubRepositoryRoot();
if (repositoryRoot instanceof ClassPathResource) {
ClassPathResource classPathResource = (ClassPathResource) repositoryRoot;
String path = classPathResource.getPath();
if (StringUtils.hasText(path)) {
return RepoRoots.asList(
new RepoRoot(stubRunnerOptions.getStubRepositoryRootAsString()));
return RepoRoots.asList(new RepoRoot(stubRunnerOptions.getStubRepositoryRootAsString()));
}
}
String path = "/**/" + configuration.getGroupId() + "/"
+ configuration.getArtifactId();
String path = "/**/" + configuration.getGroupId() + "/" + configuration.getArtifactId();
return RepoRoots.asList(new RepoRoot("classpath*:/META-INF" + path, "/**/*.*"),
new RepoRoot("classpath*:/contracts" + path, "/**/*.*"),
new RepoRoot("classpath*:/mappings" + path, "/**/*.*"));

View File

@@ -54,56 +54,49 @@ class CompositeStubDownloader implements StubDownloader {
private final StubRunnerOptions stubRunnerOptions;
CompositeStubDownloader(List<StubDownloaderBuilder> builders,
StubRunnerOptions stubRunnerOptions) {
CompositeStubDownloader(List<StubDownloaderBuilder> builders, StubRunnerOptions stubRunnerOptions) {
this.builders = builders;
this.stubRunnerOptions = stubRunnerOptions;
if (log.isDebugEnabled()) {
log.debug("Registered following stub downloaders " + this.builders.stream()
.map(b -> b.getClass().getName()).collect(Collectors.toList()));
log.debug("Registered following stub downloaders "
+ this.builders.stream().map(b -> b.getClass().getName()).collect(Collectors.toList()));
}
}
@Override
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
StubConfiguration stubConfiguration) {
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(StubConfiguration stubConfiguration) {
Map.Entry<StubConfiguration, File> entry = entry(stubConfiguration);
if (entry != null) {
return entry;
}
log.warn("No matching stubs or contracts were found");
if (this.stubRunnerOptions.isFailOnNoStubs()) {
throw new IllegalArgumentException("No stubs or contracts were found for ["
+ stubConfiguration.toColonSeparatedDependencyNotation()
+ "] and the switch to fail on no stubs was set.");
throw new IllegalArgumentException(
"No stubs or contracts were found for [" + stubConfiguration.toColonSeparatedDependencyNotation()
+ "] and the switch to fail on no stubs was set.");
}
return null;
}
private Map.Entry<StubConfiguration, File> entry(
StubConfiguration stubConfiguration) {
private Map.Entry<StubConfiguration, File> entry(StubConfiguration stubConfiguration) {
for (StubDownloaderBuilder builder : this.builders) {
StubDownloader downloader = builder.build(this.stubRunnerOptions);
if (downloader == null) {
continue;
}
if (log.isDebugEnabled()) {
log.debug("Found a matching stub downloader ["
+ downloader.getClass().getName() + "]");
log.debug("Found a matching stub downloader [" + downloader.getClass().getName() + "]");
}
Map.Entry<StubConfiguration, File> entry = downloader
.downloadAndUnpackStubJar(stubConfiguration);
Map.Entry<StubConfiguration, File> entry = downloader.downloadAndUnpackStubJar(stubConfiguration);
if (entry != null) {
if (log.isDebugEnabled()) {
log.debug(
"Found a matching entry [" + entry + "] by stub downloader ["
+ downloader.getClass().getName() + "]");
log.debug("Found a matching entry [" + entry + "] by stub downloader ["
+ downloader.getClass().getName() + "]");
}
return entry;
}
else {
log.warn("Stub Downloader [" + downloader.getClass().getName() + "] "
+ "failed to find an entry for ["
log.warn("Stub Downloader [" + downloader.getClass().getName() + "] " + "failed to find an entry for ["
+ stubConfiguration.toColonSeparatedDependencyNotation() + "]. "
+ "Will proceed to the next one");
}

View File

@@ -35,8 +35,7 @@ import org.springframework.util.StringUtils;
*/
public class ContractDownloader {
private static final Log log = LogFactory
.getLog(MethodHandles.lookup().lookupClass());
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
private final StubDownloader stubDownloader;
@@ -50,9 +49,8 @@ public class ContractDownloader {
private final String projectVersion;
public ContractDownloader(StubDownloader stubDownloader,
StubConfiguration contractsJarStubConfiguration, String contractsPath,
String projectGroupId, String projectArtifactId, String projectVersion) {
public ContractDownloader(StubDownloader stubDownloader, StubConfiguration contractsJarStubConfiguration,
String contractsPath, String projectGroupId, String projectArtifactId, String projectVersion) {
this.stubDownloader = stubDownloader;
this.contractsJarStubConfiguration = contractsJarStubConfiguration;
this.contractsPath = contractsPath;
@@ -80,13 +78,11 @@ public class ContractDownloader {
// Use createNewInclusionProperties() instead
@Deprecated
public ContractVerifierConfigProperties updatePropertiesWithInclusion(
File contractsDirectory, ContractVerifierConfigProperties config) {
final InclusionProperties newInclusionProperties = createNewInclusionProperties(
contractsDirectory);
public ContractVerifierConfigProperties updatePropertiesWithInclusion(File contractsDirectory,
ContractVerifierConfigProperties config) {
final InclusionProperties newInclusionProperties = createNewInclusionProperties(contractsDirectory);
config.setIncludedContracts(newInclusionProperties.getIncludedContracts());
config.setIncludedRootFolderAntPattern(
newInclusionProperties.getIncludedRootFolderAntPattern());
config.setIncludedRootFolderAntPattern(newInclusionProperties.getIncludedRootFolderAntPattern());
return config;
}
@@ -97,8 +93,7 @@ public class ContractDownloader {
*/
public File unpackAndDownloadContracts() {
if (log.isDebugEnabled()) {
log.debug("Will download contracts for [" + this.contractsJarStubConfiguration
+ "]");
log.debug("Will download contracts for [" + this.contractsJarStubConfiguration + "]");
}
Map.Entry<StubConfiguration, File> unpackedContractStubs = this.stubDownloader
.downloadAndUnpackStubJar(this.contractsJarStubConfiguration);
@@ -139,8 +134,7 @@ public class ContractDownloader {
log.debug("No group & artifact in path");
}
pattern = groupArtifactToPattern(contractsDirectory);
includedAntPattern = wrapWithAntPattern(
slashSeparatedGroupId() + "/" + this.projectArtifactId);
includedAntPattern = wrapWithAntPattern(slashSeparatedGroupId() + "/" + this.projectArtifactId);
}
}
log.info("Pattern to pick contracts equals [" + pattern + "]");
@@ -177,9 +171,8 @@ public class ContractDownloader {
}
private String patternFromProperty(File contractsDirectory) {
return ("^" + contractsDirectory.getAbsolutePath() + "(" + File.separator + ")?"
+ ".*" + contractsPath().replace("/", File.separator) + ".*$")
.replace("\\", "\\\\");
return ("^" + contractsDirectory.getAbsolutePath() + "(" + File.separator + ")?" + ".*"
+ contractsPath().replace("/", File.separator) + ".*$").replace("\\", "\\\\");
}
private String contractsPath() {
@@ -187,8 +180,7 @@ public class ContractDownloader {
}
private String surroundWithSeparator(String string) {
String path = string.startsWith(File.separator) ? string
: File.separator + string;
String path = string.startsWith(File.separator) ? string : File.separator + string;
return path.endsWith(File.separator) ? path : path + File.separator;
}
@@ -198,9 +190,9 @@ public class ContractDownloader {
}
private String groupArtifactToPattern(File contractsDirectory) {
return ("^" + contractsDirectory.getAbsolutePath() + "(" + File.separator + ")?"
+ ".*" + slashSeparatedGroupId() + File.separator + this.projectArtifactId
+ File.separator + ".*$").replace("\\", "\\\\");
return ("^" + contractsDirectory.getAbsolutePath() + "(" + File.separator + ")?" + ".*"
+ slashSeparatedGroupId() + File.separator + this.projectArtifactId + File.separator + ".*$")
.replace("\\", "\\\\");
}
private String fileToPattern(File contractsDirectory) {
@@ -227,8 +219,7 @@ public class ContractDownloader {
*/
private final String includedRootFolderAntPattern;
InclusionProperties(final String includedContracts,
final String includedRootFolderAntPattern) {
InclusionProperties(final String includedContracts, final String includedRootFolderAntPattern) {
this.includedContracts = includedContracts;
this.includedRootFolderAntPattern = includedRootFolderAntPattern;
}

View File

@@ -72,40 +72,32 @@ public class ContractProjectUpdater {
* @param rootStubsFolder root folder of the stubs
*/
public void updateContractProject(String projectName, Path rootStubsFolder) {
File clonedRepo = this.gitContractsRepo
.clonedRepo(this.stubRunnerOptions.stubRepositoryRoot);
File clonedRepo = this.gitContractsRepo.clonedRepo(this.stubRunnerOptions.stubRepositoryRoot);
GitStubDownloaderProperties properties = new GitStubDownloaderProperties(
this.stubRunnerOptions.stubRepositoryRoot, this.stubRunnerOptions);
copyStubs(projectName, rootStubsFolder, clonedRepo);
GitRepo gitRepo = new GitRepo(clonedRepo, properties);
String msg = StubRunnerPropertyUtils
.getProperty(this.stubRunnerOptions.getProperties(), GIT_COMMIT_MESSAGE);
GitRepo.CommitResult commit = gitRepo.commit(clonedRepo,
commitMessage(projectName, msg));
String msg = StubRunnerPropertyUtils.getProperty(this.stubRunnerOptions.getProperties(), GIT_COMMIT_MESSAGE);
GitRepo.CommitResult commit = gitRepo.commit(clonedRepo, commitMessage(projectName, msg));
if (commit == GitRepo.CommitResult.EMPTY) {
log.info("There were no changes to commit. Won't push the changes");
return;
}
String attempts = StubRunnerPropertyUtils.getProperty(
this.stubRunnerOptions.getProperties(), GIT_ATTEMPTS_NO_PROP);
int intAttempts = StringUtils.hasText(attempts) ? Integer.parseInt(attempts)
: DEFAULT_ATTEMPTS_NO;
String wait = StubRunnerPropertyUtils.getProperty(
this.stubRunnerOptions.getProperties(), GIT_WAIT_BETWEEN_ATTEMPTS);
long longWait = StringUtils.hasText(wait) ? Long.parseLong(wait)
: DEFAULT_WAIT_BETWEEN_ATTEMPTS;
String attempts = StubRunnerPropertyUtils.getProperty(this.stubRunnerOptions.getProperties(),
GIT_ATTEMPTS_NO_PROP);
int intAttempts = StringUtils.hasText(attempts) ? Integer.parseInt(attempts) : DEFAULT_ATTEMPTS_NO;
String wait = StubRunnerPropertyUtils.getProperty(this.stubRunnerOptions.getProperties(),
GIT_WAIT_BETWEEN_ATTEMPTS);
long longWait = StringUtils.hasText(wait) ? Long.parseLong(wait) : DEFAULT_WAIT_BETWEEN_ATTEMPTS;
tryToPushCurrentBranch(clonedRepo, gitRepo, intAttempts, longWait);
}
private void tryToPushCurrentBranch(File clonedRepo, GitRepo gitRepo, int intAttempts,
long longWait) {
private void tryToPushCurrentBranch(File clonedRepo, GitRepo gitRepo, int intAttempts, long longWait) {
int currentAttempt = 0;
while (currentAttempt < intAttempts) {
log.info("Trying to push changes, attempt " + (currentAttempt + 1) + "/"
+ intAttempts);
log.info("Trying to push changes, attempt " + (currentAttempt + 1) + "/" + intAttempts);
gitRepo.pull(clonedRepo);
log.info(
"Successfully pulled changes from remote for project with contract and stubs");
log.info("Successfully pulled changes from remote for project with contract and stubs");
try {
gitRepo.pushCurrentBranch(clonedRepo);
log.info("Successfully pushed changes with current stubs");
@@ -142,15 +134,12 @@ public class ContractProjectUpdater {
private void copyStubs(String projectName, Path rootStubsFolder, File clonedRepo) {
try {
if (log.isDebugEnabled()) {
log.debug("Copying stubs from [" + rootStubsFolder.toString()
+ "] to the cloned repo [" + clonedRepo.getAbsolutePath()
+ "] for project [" + projectName + "]");
log.debug("Copying stubs from [" + rootStubsFolder.toString() + "] to the cloned repo ["
+ clonedRepo.getAbsolutePath() + "] for project [" + projectName + "]");
}
Files.walkFileTree(rootStubsFolder,
new DirectoryCopyingVisitor(rootStubsFolder, clonedRepo.toPath()));
Files.walkFileTree(rootStubsFolder, new DirectoryCopyingVisitor(rootStubsFolder, clonedRepo.toPath()));
if (log.isDebugEnabled()) {
log.debug("Successfully copied stubs to the cloned repo for project ["
+ projectName + "]");
log.debug("Successfully copied stubs to the cloned repo for project [" + projectName + "]");
}
}
catch (IOException e) {
@@ -162,8 +151,7 @@ public class ContractProjectUpdater {
class DirectoryCopyingVisitor extends SimpleFileVisitor<Path> {
private static final List<String> FOLDERS_TO_DELETE = Arrays.asList("contracts",
"mappings");
private static final List<String> FOLDERS_TO_DELETE = Arrays.asList("contracts", "mappings");
private static final Log log = LogFactory.getLog(DirectoryCopyingVisitor.class);
@@ -175,14 +163,12 @@ class DirectoryCopyingVisitor extends SimpleFileVisitor<Path> {
this.from = from;
this.to = to;
if (log.isDebugEnabled()) {
log.debug("Will copy from [" + from.toString() + "] to [" + to.toString()
+ "]");
log.debug("Will copy from [" + from.toString() + "] to [" + to.toString() + "]");
}
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Path relativePath = this.from.relativize(dir);
if (".git".equals(relativePath.toString())) {
return FileVisitResult.SKIP_SUBTREE;
@@ -221,15 +207,13 @@ class DirectoryCopyingVisitor extends SimpleFileVisitor<Path> {
}
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
// a hack for Windows not to fail when directory is removed
// related to
// https://github.com/spring-cloud/spring-cloud-sleuth/issues/834
@@ -262,8 +246,7 @@ class DirectoryCopyingVisitor extends SimpleFileVisitor<Path> {
while (count < maxTries);
if (!deleted) {
if (log.isDebugEnabled()) {
log.debug("Failed to delete [" + dir + "] after [" + maxTries
+ "] attempts to do it");
log.debug("Failed to delete [" + dir + "] after [" + maxTries + "] attempts to do it");
}
throw new DirectoryNotEmptyException(dir.toString());
}
@@ -288,13 +271,11 @@ class DirectoryCopyingVisitor extends SimpleFileVisitor<Path> {
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path relativePath = this.to.resolve(this.from.relativize(file));
Files.copy(file, relativePath, StandardCopyOption.REPLACE_EXISTING);
if (log.isDebugEnabled()) {
log.debug("Copied file from [" + file.toString() + "] to ["
+ relativePath.toString() + "]");
log.debug("Copied file from [" + file.toString() + "] to [" + relativePath.toString() + "]");
}
return FileVisitResult.CONTINUE;
}

View File

@@ -43,8 +43,7 @@ import org.springframework.util.StringUtils;
*/
public class FileStubDownloader implements StubDownloaderBuilder {
private static final List<String> ACCEPTABLE_PROTOCOLS = Collections
.singletonList("stubs");
private static final List<String> ACCEPTABLE_PROTOCOLS = Collections.singletonList("stubs");
/**
* Does any of the accepted protocols matches the URL of the repository.
@@ -94,8 +93,7 @@ public class FileStubDownloader implements StubDownloaderBuilder {
}
private String separatorsToUnix(String location) {
return location != null && location.indexOf(92) != -1
? location.replace('\\', '/') : location;
return location != null && location.indexOf(92) != -1 ? location.replace('\\', '/') : location;
}
}
@@ -148,19 +146,16 @@ class StubsStubDownloader implements StubDownloader {
// StubConfiguration is the concrete stub to be fetched
@Override
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
StubConfiguration stubConfiguration) {
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(StubConfiguration stubConfiguration) {
boolean shouldFindProducer = shouldFindProducer();
if (!shouldFindProducer) {
String schemeSpecific = schemeSpecificPart();
log.info("Stubs are present under [" + schemeSpecific
+ "]. Will copy them to a temporary directory.");
return new ResourceResolvingStubDownloader(stubRunnerOptions,
this::repoRootForSchemeSpecificPart, this::anyPattern)
.downloadAndUnpackStubJar(stubConfiguration);
log.info("Stubs are present under [" + schemeSpecific + "]. Will copy them to a temporary directory.");
return new ResourceResolvingStubDownloader(stubRunnerOptions, this::repoRootForSchemeSpecificPart,
this::anyPattern).downloadAndUnpackStubJar(stubConfiguration);
}
return new ResourceResolvingStubDownloader(stubRunnerOptions, this::repoRoot,
this::gavPattern).downloadAndUnpackStubJar(stubConfiguration);
return new ResourceResolvingStubDownloader(stubRunnerOptions, this::repoRoot, this::gavPattern)
.downloadAndUnpackStubJar(stubConfiguration);
}
private RepoRoots repoRootForSchemeSpecificPart(StubRunnerOptions stubRunnerOptions,
@@ -192,30 +187,21 @@ class StubsStubDownloader implements StubDownloader {
// for group id a.b.c and artifact id d
// a.b.c/d
// a/b/c/d
private RepoRoots repoRoot(StubRunnerOptions stubRunnerOptions,
StubConfiguration configuration) {
String pathWithGroupAndArtifactId = "/" + configuration.getGroupId() + "/"
+ configuration.getArtifactId();
String pathWithGroupAndArtifactIdSlashSeparated = "/"
+ configuration.getGroupId().replace(".", File.separator) + "/"
+ configuration.getArtifactId();
private RepoRoots repoRoot(StubRunnerOptions stubRunnerOptions, StubConfiguration configuration) {
String pathWithGroupAndArtifactId = "/" + configuration.getGroupId() + "/" + configuration.getArtifactId();
String pathWithGroupAndArtifactIdSlashSeparated = "/" + configuration.getGroupId().replace(".", File.separator)
+ "/" + configuration.getArtifactId();
String anyFileSuffix = "/**/*.*";
RepoRoots roots = RepoRoots.asList(
new RepoRoot(schemeSpecificPart() + pathWithGroupAndArtifactId,
anyFileSuffix),
new RepoRoot(
schemeSpecificPart() + pathWithGroupAndArtifactIdSlashSeparated,
anyFileSuffix),
new RepoRoot(schemeSpecificPart() + pathWithGroupAndArtifactId, anyFileSuffix),
new RepoRoot(schemeSpecificPart() + pathWithGroupAndArtifactIdSlashSeparated, anyFileSuffix),
new RepoRoot(schemeSpecificPart() + anyFileSuffix));
if (!latestVersionIsSet(configuration)) {
String pathWithGAV = pathWithGroupAndArtifactId + "/"
String pathWithGAV = pathWithGroupAndArtifactId + "/" + configuration.getVersion();
String pathWithSlashSeparatedGAV = pathWithGroupAndArtifactIdSlashSeparated + "/"
+ configuration.getVersion();
String pathWithSlashSeparatedGAV = pathWithGroupAndArtifactIdSlashSeparated
+ "/" + configuration.getVersion();
roots.addAll(RepoRoots.asList(
new RepoRoot(schemeSpecificPart() + pathWithGAV, anyFileSuffix),
new RepoRoot(schemeSpecificPart() + pathWithSlashSeparatedGAV,
anyFileSuffix)));
roots.addAll(RepoRoots.asList(new RepoRoot(schemeSpecificPart() + pathWithGAV, anyFileSuffix),
new RepoRoot(schemeSpecificPart() + pathWithSlashSeparatedGAV, anyFileSuffix)));
}
return roots;
}
@@ -233,16 +219,14 @@ class StubsStubDownloader implements StubDownloader {
private boolean shouldFindProducer() {
Map<String, String> args = this.stubRunnerOptions.getProperties();
String findProducer = StubRunnerPropertyUtils.getProperty(args,
STUBS_FIND_PRODUCER_PROPERTY);
String findProducer = StubRunnerPropertyUtils.getProperty(args, STUBS_FIND_PRODUCER_PROPERTY);
return Boolean.parseBoolean(findProducer);
}
// stubs://foo -> foo
private String schemeSpecificPart() {
try {
String part = this.stubRunnerOptions.getStubRepositoryRoot().getURI()
.getSchemeSpecificPart();
String part = this.stubRunnerOptions.getStubRepositoryRoot().getURI().getSchemeSpecificPart();
if (StringUtils.isEmpty(part)) {
return part;
}

View File

@@ -208,8 +208,8 @@ class GitRepo {
if (log.isDebugEnabled()) {
log.debug("Project git url [" + projectGitUrl + "]");
}
CloneCommand command = this.gitFactory.getCloneCommandByCloneRepository()
.setURI(projectGitUrl).setDirectory(destinationFolder);
CloneCommand command = this.gitFactory.getCloneCommandByCloneRepository().setURI(projectGitUrl)
.setDirectory(destinationFolder);
try {
Git git = command.call();
if (git.getRepository().getRemoteNames().isEmpty()) {
@@ -262,8 +262,7 @@ class GitRepo {
}
private void trackBranch(CheckoutCommand checkout, String label) {
checkout.setCreateBranch(true).setName(label)
.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
checkout.setCreateBranch(true).setName(label).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
.setStartPoint("origin/" + label);
}
@@ -275,8 +274,7 @@ class GitRepo {
return containsBranch(git, label, null);
}
private boolean containsBranch(Git git, String label,
ListBranchCommand.ListMode listMode) throws GitAPIException {
private boolean containsBranch(Git git, String label, ListBranchCommand.ListMode listMode) throws GitAPIException {
ListBranchCommand command = git.branchList();
if (listMode != null) {
command.setListMode(listMode);
@@ -310,8 +308,7 @@ class GitRepo {
*/
static class JGitFactory {
private static final Logger log = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
final CredentialsProvider provider;
@@ -332,17 +329,14 @@ class GitRepo {
log.info("Successfully connected to an agent");
}
catch (AgentProxyException e) {
log.error(
"Exception occurred while trying to connect to agent. Will create"
+ "the default JSch connection",
e);
log.error("Exception occurred while trying to connect to agent. Will create"
+ "the default JSch connection", e);
return super.createDefaultJSch(fs);
}
final JSch jsch = super.createDefaultJSch(fs);
if (connector != null) {
JSch.setConfig("PreferredAuthentications", "publickey,password");
IdentityRepository identityRepository = new RemoteIdentityRepository(
connector);
IdentityRepository identityRepository = new RemoteIdentityRepository(connector);
jsch.setIdentityRepository(identityRepository);
}
return jsch;
@@ -358,8 +352,7 @@ class GitRepo {
JGitFactory(GitStubDownloaderProperties properties) {
if (org.springframework.util.StringUtils.hasText(properties.username)) {
log.info(
"Passed username and password - will set a custom credentials provider");
log.info("Passed username and password - will set a custom credentials provider");
this.provider = credentialsProvider(properties);
}
else {
@@ -376,8 +369,7 @@ class GitRepo {
}
CredentialsProvider credentialsProvider(GitStubDownloaderProperties properties) {
return new UsernamePasswordCredentialsProvider(properties.username,
properties.password);
return new UsernamePasswordCredentialsProvider(properties.username, properties.password);
}
CloneCommand getCloneCommandByCloneRepository() {
@@ -386,13 +378,11 @@ class GitRepo {
}
PushCommand push(Git git) {
return git.push().setCredentialsProvider(this.provider)
.setTransportConfigCallback(this.callback);
return git.push().setCredentialsProvider(this.provider).setTransportConfigCallback(this.callback);
}
PullCommand pull(Git git) {
return git.pull().setCredentialsProvider(this.provider)
.setTransportConfigCallback(this.callback);
return git.pull().setCredentialsProvider(this.provider).setTransportConfigCallback(this.callback);
}
Git open(File file) {

View File

@@ -49,15 +49,13 @@ public final class HttpServerStubConfiguration {
*/
public boolean randomPort;
public HttpServerStubConfiguration(HttpServerStubConfigurer configurer,
StubRunnerOptions stubRunnerOptions, StubConfiguration stubConfiguration,
Integer port) {
public HttpServerStubConfiguration(HttpServerStubConfigurer configurer, StubRunnerOptions stubRunnerOptions,
StubConfiguration stubConfiguration, Integer port) {
this(configurer, stubRunnerOptions, stubConfiguration, port, randomPort(port));
}
public HttpServerStubConfiguration(HttpServerStubConfigurer configurer,
StubRunnerOptions stubRunnerOptions, StubConfiguration stubConfiguration,
Integer port, boolean randomPort) {
public HttpServerStubConfiguration(HttpServerStubConfigurer configurer, StubRunnerOptions stubRunnerOptions,
StubConfiguration stubConfiguration, Integer port, boolean randomPort) {
this.configurer = configurer;
this.stubRunnerOptions = stubRunnerOptions;
this.stubConfiguration = stubConfiguration;
@@ -74,8 +72,7 @@ public final class HttpServerStubConfiguration {
}
public String toColonSeparatedDependencyNotation() {
return this.stubConfiguration != null
? this.stubConfiguration.toColonSeparatedDependencyNotation() : "";
return this.stubConfiguration != null ? this.stubConfiguration.toColonSeparatedDependencyNotation() : "";
}
}

View File

@@ -38,8 +38,7 @@ public interface HttpServerStubConfigurer<T> {
* @param httpServerStubConfiguration - Spring Cloud Contract stub configuration
* @return the modified stub configuration
*/
default T configure(T httpStubConfiguration,
HttpServerStubConfiguration httpServerStubConfiguration) {
default T configure(T httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
return httpStubConfiguration;
}

View File

@@ -41,25 +41,20 @@ final class MappingGenerator {
throw new IllegalStateException("Can't instantiate utility class");
}
static Collection<Path> toMappings(File contractFile, Collection<Contract> contracts,
File mappingsFolder) {
static Collection<Path> toMappings(File contractFile, Collection<Contract> contracts, File mappingsFolder) {
StubGeneratorProvider provider = new StubGeneratorProvider();
Collection<StubGenerator> stubGenerators = provider
.converterForName(contractFile.getName());
Collection<StubGenerator> stubGenerators = provider.converterForName(contractFile.getName());
if (log.isDebugEnabled()) {
log.debug("Found following matching stub generators " + stubGenerators);
}
Collection<Path> mappings = new LinkedList<>();
for (StubGenerator stubGenerator : stubGenerators) {
Map<Contract, String> map = stubGenerator.convertContents(
contractFile.getName(), new ContractMetadata(contractFile.toPath(),
false, contracts.size(), null, contracts));
Map<Contract, String> map = stubGenerator.convertContents(contractFile.getName(),
new ContractMetadata(contractFile.toPath(), false, contracts.size(), null, contracts));
for (Map.Entry<Contract, String> entry : map.entrySet()) {
String value = entry.getValue();
File mapping = new File(mappingsFolder,
StringUtils.stripFilenameExtension(contractFile.getName()) + "_"
+ Math.abs(entry.getKey().hashCode())
+ stubGenerator.fileExtension());
File mapping = new File(mappingsFolder, StringUtils.stripFilenameExtension(contractFile.getName()) + "_"
+ Math.abs(entry.getKey().hashCode()) + stubGenerator.fileExtension());
mappings.add(storeFile(mapping.toPath(), value.getBytes()));
}
}

View File

@@ -64,16 +64,14 @@ public class MavenSettings {
return settingsDecrypter;
}
private void setField(Class<?> sourceClass, String fieldName, Object target,
Object value) {
private void setField(Class<?> sourceClass, String fieldName, Object target, Object value) {
try {
Field field = sourceClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(target, value);
}
catch (Exception ex) {
throw new IllegalStateException(
"Failed to set field '" + fieldName + "' on '" + target + "'", ex);
throw new IllegalStateException("Failed to set field '" + fieldName + "' on '" + target + "'", ex);
}
}

View File

@@ -32,8 +32,7 @@ import org.springframework.util.StringUtils;
*/
class ProjectVersion implements Comparable<ProjectVersion>, Serializable {
private static final Pattern SNAPSHOT_PATTERN = Pattern
.compile("^.*[\\.|\\-](BUILD-)?SNAPSHOT.*$");
private static final Pattern SNAPSHOT_PATTERN = Pattern.compile("^.*[\\.|\\-](BUILD-)?SNAPSHOT.*$");
private static final String MILESTONE_REGEX = ".*[\\.|\\-]M[0-9]+";
@@ -44,8 +43,8 @@ class ProjectVersion implements Comparable<ProjectVersion>, Serializable {
private static final String SR_REGEX = "^.*[\\.|\\-]SR[0-9]+.*$";
private static final List<Pattern> VALID_PATTERNS = Arrays.asList(SNAPSHOT_PATTERN,
Pattern.compile(MILESTONE_REGEX), Pattern.compile(RC_REGEX),
Pattern.compile(RELEASE_REGEX), Pattern.compile(SR_REGEX));
Pattern.compile(MILESTONE_REGEX), Pattern.compile(RC_REGEX), Pattern.compile(RELEASE_REGEX),
Pattern.compile(SR_REGEX));
/**
* Version of the project.
@@ -79,8 +78,7 @@ class ProjectVersion implements Comparable<ProjectVersion>, Serializable {
int numberOfHyphens = splitByHyphens - 1;
int indexOfFirstHyphen = this.version.indexOf("-");
boolean buildSnapshot = this.version.endsWith("BUILD-SNAPSHOT");
if (numberOfHyphens == 1 && !buildSnapshot
|| (numberOfHyphens > 1 && buildSnapshot)) {
if (numberOfHyphens == 1 && !buildSnapshot || (numberOfHyphens > 1 && buildSnapshot)) {
// Dysprosium or 1.0.0
String versionName = this.version.substring(0, indexOfFirstHyphen);
boolean hasDots = versionName.contains(".");
@@ -100,8 +98,7 @@ class ProjectVersion implements Comparable<ProjectVersion>, Serializable {
return SplitVersion.hyphen(newArray);
}
else {
throw new UnsupportedOperationException(
"Unknown version [" + this.version + "]");
throw new UnsupportedOperationException("Unknown version [" + this.version + "]");
}
}
return null;
@@ -172,8 +169,7 @@ class ProjectVersion implements Comparable<ProjectVersion>, Serializable {
SplitVersion thatSplit = that.assertVersion();
int releaseTypeComparison = this.releaseType.compareTo(that.releaseType);
boolean thisReleaseTypeHigher = releaseTypeComparison > 0;
boolean bothGa = this.isReleaseOrServiceRelease()
&& that.isReleaseOrServiceRelease();
boolean bothGa = this.isReleaseOrServiceRelease() && that.isReleaseOrServiceRelease();
// 1.0.1.M2 vs 1.0.0.RELEASE (x)
if (thisReleaseTypeHigher && !bothGa) {
return 1;
@@ -205,8 +201,7 @@ class ProjectVersion implements Comparable<ProjectVersion>, Serializable {
boolean isSameWithoutSuffix(ProjectVersion that) {
SplitVersion thisSplit = assertVersion();
SplitVersion thatSplit = that.assertVersion();
return thisSplit.major.equals(thatSplit.major)
&& thisSplit.minor.equals(thatSplit.minor)
return thisSplit.major.equals(thatSplit.major) && thisSplit.minor.equals(thatSplit.minor)
&& thisSplit.patch.equals(thatSplit.patch);
}
@@ -255,8 +250,7 @@ class ProjectVersion implements Comparable<ProjectVersion>, Serializable {
// 1.0.0.RELEASE
// 1.0.0-RELEASE
private SplitVersion(String major, String minor, String patch, String delimiter,
String suffix) {
private SplitVersion(String major, String minor, String patch, String delimiter, String suffix) {
this.major = major;
this.minor = minor;
this.patch = patch;
@@ -314,8 +308,7 @@ class ProjectVersion implements Comparable<ProjectVersion>, Serializable {
}
private boolean isInvalid() {
return wrongReleaseTrainVersion() || wrongLibraryVersion() || wrongDelimiter()
|| noSuffix();
return wrongReleaseTrainVersion() || wrongLibraryVersion() || wrongDelimiter() || noSuffix();
}
private boolean noSuffix() {
@@ -345,9 +338,8 @@ class ProjectVersion implements Comparable<ProjectVersion>, Serializable {
// must have
// either major and suffix (release train)
// major, minor, patch and suffix
return isNumeric(major) && (StringUtils.isEmpty(minor)
|| StringUtils.isEmpty(patch) || StringUtils.isEmpty(suffix)
|| StringUtils.isEmpty(delimiter));
return isNumeric(major) && (StringUtils.isEmpty(minor) || StringUtils.isEmpty(patch)
|| StringUtils.isEmpty(suffix) || StringUtils.isEmpty(delimiter));
}
private boolean wrongReleaseTrainVersion() {

View File

@@ -48,10 +48,8 @@ public final class ResourceResolver {
private static final DefaultResourceLoader LOADER = new DefaultResourceLoader();
static {
RESOLVERS.addAll(
SpringFactoriesLoader.loadFactories(StubDownloaderBuilder.class, null));
RESOLVERS.addAll(
new StubDownloaderBuilderProvider().defaultStubDownloaderBuilders());
RESOLVERS.addAll(SpringFactoriesLoader.loadFactories(StubDownloaderBuilder.class, null));
RESOLVERS.addAll(new StubDownloaderBuilderProvider().defaultStubDownloaderBuilders());
for (ProtocolResolver resolver : RESOLVERS) {
LOADER.addProtocolResolver(resolver);
}
@@ -70,9 +68,7 @@ public final class ResourceResolver {
return LOADER.getResource(url);
}
catch (Exception e) {
log.error(
"Exception occurred while trying to read the resource [" + url + "]",
e);
log.error("Exception occurred while trying to read the resource [" + url + "]", e);
return null;
}
}

View File

@@ -43,8 +43,7 @@ import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
class ResourceResolvingStubDownloader implements StubDownloader {
private static final Log log = LogFactory
.getLog(ResourceResolvingStubDownloader.class);
private static final Log log = LogFactory.getLog(ResourceResolvingStubDownloader.class);
private final StubRunnerOptions stubRunnerOptions;
@@ -64,8 +63,7 @@ class ResourceResolvingStubDownloader implements StubDownloader {
}
@Override
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
StubConfiguration config) {
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(StubConfiguration config) {
registerShutdownHook();
List<RepoRoot> repoRoots = repoRootFunction.apply(stubRunnerOptions, config);
List<String> paths = toPaths(repoRoots);
@@ -74,8 +72,8 @@ class ResourceResolvingStubDownloader implements StubDownloader {
log.debug("For paths " + paths + " found following resources " + resources);
}
if (resources.isEmpty() && this.stubRunnerOptions.isFailOnNoStubs()) {
throw new IllegalStateException("No stubs were found on classpath for ["
+ config.getGroupId() + ":" + config.getArtifactId() + "]");
throw new IllegalStateException("No stubs were found on classpath for [" + config.getGroupId() + ":"
+ config.getArtifactId() + "]");
}
final File tmp = TemporaryFileStorage.createTempDir("classpath-stubs");
if (stubRunnerOptions.isDeleteStubsAfterTest()) {
@@ -84,8 +82,7 @@ class ResourceResolvingStubDownloader implements StubDownloader {
boolean atLeastOneFound = false;
for (Resource resource : resources) {
try {
String relativePath = relativePathPicker(resource,
this.gavPattern.apply(config));
String relativePath = relativePathPicker(resource, this.gavPattern.apply(config));
if (log.isDebugEnabled()) {
log.debug("Relative path for resource is [" + relativePath + "]");
}
@@ -105,31 +102,25 @@ class ResourceResolvingStubDownloader implements StubDownloader {
log.warn("Didn't find any matching stubs");
return null;
}
log.info("Unpacked files for [" + config.getGroupId() + ":"
+ config.getArtifactId() + ":" + config.getVersion() + "] to folder ["
+ tmp + "]");
return new AbstractMap.SimpleEntry<>(new StubConfiguration(config.getGroupId(),
config.getArtifactId(), config.getVersion(), config.getClassifier()),
tmp);
log.info("Unpacked files for [" + config.getGroupId() + ":" + config.getArtifactId() + ":" + config.getVersion()
+ "] to folder [" + tmp + "]");
return new AbstractMap.SimpleEntry<>(new StubConfiguration(config.getGroupId(), config.getArtifactId(),
config.getVersion(), config.getClassifier()), tmp);
}
private void registerShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(() -> TemporaryFileStorage
.cleanup(stubRunnerOptions.isDeleteStubsAfterTest())));
Runtime.getRuntime().addShutdownHook(
new Thread(() -> TemporaryFileStorage.cleanup(stubRunnerOptions.isDeleteStubsAfterTest())));
}
private void copyTheFoundFiles(File tmp, Resource resource, String relativePath)
throws IOException {
private void copyTheFoundFiles(File tmp, Resource resource, String relativePath) throws IOException {
// the relative path is OS agnostic and contains / only
int lastIndexOf = relativePath.lastIndexOf("/");
String relativePathWithoutFile = lastIndexOf > -1
? relativePath.substring(0, lastIndexOf) : relativePath;
String relativePathWithoutFile = lastIndexOf > -1 ? relativePath.substring(0, lastIndexOf) : relativePath;
if (log.isDebugEnabled()) {
log.debug("Relative path without file name is [" + relativePathWithoutFile
+ "]");
log.debug("Relative path without file name is [" + relativePathWithoutFile + "]");
}
Path directory = Files
.createDirectories(new File(tmp, relativePathWithoutFile).toPath());
Path directory = Files.createDirectories(new File(tmp, relativePathWithoutFile).toPath());
File newFile = new File(directory.toFile(), resource.getFilename());
if (!newFile.exists() && !isDirectory(resource)) {
try (InputStream stream = resource.getInputStream()) {
@@ -148,20 +139,15 @@ class ResourceResolvingStubDownloader implements StubDownloader {
}
catch (Exception e) {
if (log.isTraceEnabled()) {
log.trace(
"Exception occurred while trying to convert path to file for resource ["
+ resource + "]",
e);
log.trace("Exception occurred while trying to convert path to file for resource [" + resource + "]", e);
}
return false;
}
}
String relativePathPicker(Resource resource, Pattern groupAndArtifactPattern)
throws IOException {
String relativePathPicker(Resource resource, Pattern groupAndArtifactPattern) throws IOException {
Matcher groupAndArtifactMatcher = matcher(resource, groupAndArtifactPattern);
if (groupAndArtifactMatcher.matches()
&& groupAndArtifactMatcher.groupCount() > 2) {
if (groupAndArtifactMatcher.matches() && groupAndArtifactMatcher.groupCount() > 2) {
MatchResult groupAndArtifactResult = groupAndArtifactMatcher.toMatchResult();
return groupAndArtifactResult.group(2) + groupAndArtifactResult.group(3);
}
@@ -173,8 +159,7 @@ class ResourceResolvingStubDownloader implements StubDownloader {
}
}
private Matcher matcher(Resource resource, Pattern groupAndArtifactPattern)
throws IOException {
private Matcher matcher(Resource resource, Pattern groupAndArtifactPattern) throws IOException {
try {
String path = resource.getURI().getPath();
return groupAndArtifactPattern.matcher(path);
@@ -201,8 +186,7 @@ class ResourceResolvingStubDownloader implements StubDownloader {
resources.addAll(list);
}
catch (IOException e) {
log.error("Exception occurred while trying to fetch resources from ["
+ path + "]");
log.error("Exception occurred while trying to fetch resources from [" + path + "]");
throw new IllegalStateException(e);
}
}

View File

@@ -112,8 +112,7 @@ public class RunningStubs {
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((this.namesAndPorts == null) ? 0 : this.namesAndPorts.hashCode());
result = prime * result + ((this.namesAndPorts == null) ? 0 : this.namesAndPorts.hashCode());
return result;
}

View File

@@ -54,8 +54,7 @@ import org.springframework.util.StringUtils;
*/
public final class ScmStubDownloaderBuilder implements StubDownloaderBuilder {
private static final List<String> ACCEPTABLE_PROTOCOLS = Collections
.singletonList("git");
private static final List<String> ACCEPTABLE_PROTOCOLS = Collections.singletonList("git");
/**
* Does any of the accepted protocols matches the URL of the repository.
@@ -133,18 +132,15 @@ class GitContractsRepo {
File clonedRepo(Resource repo) {
File file = CACHED_LOCATIONS.get(repo);
GitStubDownloaderProperties properties = new GitStubDownloaderProperties(repo,
this.options);
GitStubDownloaderProperties properties = new GitStubDownloaderProperties(repo, this.options);
if (file == null) {
File tmpDirWhereStubsWillBeUnzipped = TemporaryFileStorage
.createTempDir(TEMP_DIR_PREFIX);
File tmpDirWhereStubsWillBeUnzipped = TemporaryFileStorage.createTempDir(TEMP_DIR_PREFIX);
GitRepo gitRepo = new GitRepo(tmpDirWhereStubsWillBeUnzipped, properties);
file = gitRepo.cloneProject(properties.url);
gitRepo.checkout(file, properties.branch);
CACHED_LOCATIONS.put(repo, file);
if (log.isDebugEnabled()) {
log.debug("The project hasn't already been cloned. Cloned it to [" + file
+ "]");
log.debug("The project hasn't already been cloned. Cloned it to [" + file + "]");
}
}
else {
@@ -182,20 +178,18 @@ class GitStubDownloader implements StubDownloader {
}
@Override
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
StubConfiguration stubConfiguration) {
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(StubConfiguration stubConfiguration) {
try {
if (log.isDebugEnabled()) {
log.debug("Trying to find a contract for ["
+ stubConfiguration.toColonSeparatedDependencyNotation() + "]");
log.debug("Trying to find a contract for [" + stubConfiguration.toColonSeparatedDependencyNotation()
+ "]");
}
Resource repo = this.stubRunnerOptions.getStubRepositoryRoot();
File clonedRepo = this.gitContractsRepo.clonedRepo(repo);
FileWalker walker = new FileWalker(stubConfiguration);
Files.walkFileTree(clonedRepo.toPath(), walker);
if (walker.foundFile != null) {
return new AbstractMap.SimpleEntry<>(stubConfiguration,
walker.foundFile.toFile());
return new AbstractMap.SimpleEntry<>(stubConfiguration, walker.foundFile.toFile());
}
}
catch (IOException e) {
@@ -209,8 +203,8 @@ class GitStubDownloader implements StubDownloader {
}
private void registerShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(() -> TemporaryFileStorage
.cleanup(GitStubDownloader.this.deleteStubsAfterTest)));
Runtime.getRuntime().addShutdownHook(
new Thread(() -> TemporaryFileStorage.cleanup(GitStubDownloader.this.deleteStubsAfterTest)));
}
}
@@ -245,21 +239,17 @@ class GitStubDownloaderProperties {
// if we had git://https://... we want the part starting from https
// if we had git://git@... we want the full address again
// if the URL starts with git@... and ends with .git, we want to remove it
String modifiedRepo = repoUrl.startsWith("git@") ? modifyUrlForGitRepo(repoUrl)
: repoUrl;
String modifiedRepo = repoUrl.startsWith("git@") ? modifyUrlForGitRepo(repoUrl) : repoUrl;
this.url = URI.create(modifiedRepo);
String username = StubRunnerPropertyUtils.getProperty(args,
GIT_USERNAME_PROPERTY);
String username = StubRunnerPropertyUtils.getProperty(args, GIT_USERNAME_PROPERTY);
this.username = StringUtils.hasText(username) ? username : options.getUsername();
String password = StubRunnerPropertyUtils.getProperty(args,
GIT_PASSWORD_PROPERTY);
String password = StubRunnerPropertyUtils.getProperty(args, GIT_PASSWORD_PROPERTY);
this.password = StringUtils.hasText(password) ? password : options.getPassword();
String branch = StubRunnerPropertyUtils.getProperty(args, GIT_BRANCH_PROPERTY);
this.branch = StringUtils.hasText(branch) ? branch : "master";
if (log.isDebugEnabled()) {
log.debug("Repo url is [" + repoUrl + "], modified url string " + "is ["
+ modifiedRepo + "] URL is [" + this.url + "] and " + "branch is ["
+ this.branch + "]");
log.debug("Repo url is [" + repoUrl + "], modified url string " + "is [" + modifiedRepo + "] URL is ["
+ this.url + "] and " + "branch is [" + this.branch + "]");
}
}
@@ -296,39 +286,27 @@ class FileWalker extends SimpleFileVisitor<Path> {
Path foundFile;
FileWalker(StubConfiguration stubConfiguration) {
this.latestSnapshotVersion = LATEST.stream()
.anyMatch(s -> s.equals(stubConfiguration.version.toLowerCase()));
this.latestReleaseVersion = RELEASE
.equals(stubConfiguration.version.toLowerCase());
this.matcherWithDot = FileSystems.getDefault()
.getPathMatcher("glob:" + matcherGlob(stubConfiguration, "."));
this.matcherWithoutDot = FileSystems.getDefault()
.getPathMatcher("glob:" + matcherGlob(stubConfiguration, "/"));
this.latestSnapshotVersion = LATEST.stream().anyMatch(s -> s.equals(stubConfiguration.version.toLowerCase()));
this.latestReleaseVersion = RELEASE.equals(stubConfiguration.version.toLowerCase());
this.matcherWithDot = FileSystems.getDefault().getPathMatcher("glob:" + matcherGlob(stubConfiguration, "."));
this.matcherWithoutDot = FileSystems.getDefault().getPathMatcher("glob:" + matcherGlob(stubConfiguration, "/"));
}
private String matcherGlob(StubConfiguration stubConfiguration,
String groupArtifactSeparator) {
return "**" + stubConfiguration.groupId + groupArtifactSeparator
+ stubConfiguration.artifactId + "/"
+ (this.latestSnapshotVersion || this.latestReleaseVersion ? "**"
: stubConfiguration.version);
private String matcherGlob(StubConfiguration stubConfiguration, String groupArtifactSeparator) {
return "**" + stubConfiguration.groupId + groupArtifactSeparator + stubConfiguration.artifactId + "/"
+ (this.latestSnapshotVersion || this.latestReleaseVersion ? "**" : stubConfiguration.version);
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
if (this.matcherWithDot.matches(dir.toAbsolutePath())
|| this.matcherWithoutDot.matches(dir.toAbsolutePath())) {
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (this.matcherWithDot.matches(dir.toAbsolutePath()) || this.matcherWithoutDot.matches(dir.toAbsolutePath())) {
if (this.latestSnapshotVersion || this.latestReleaseVersion) {
// folders with name latest, release
File[] files = Objects.requireNonNull(
dir.getParent().toFile().listFiles(File::isDirectory));
File[] files = Objects.requireNonNull(dir.getParent().toFile().listFiles(File::isDirectory));
File file = folderWithPredefinedName(files);
if (file != null) {
if (log.isDebugEnabled()) {
log.debug(
"Found folder with name corresponding to a latest version ["
+ file + "] ");
log.debug("Found folder with name corresponding to a latest version [" + file + "] ");
this.foundFile = file.toPath();
return FileVisitResult.TERMINATE;
}
@@ -347,30 +325,26 @@ class FileWalker extends SimpleFileVisitor<Path> {
List<DefaultArtifactVersionWrapper> versions = pickLatestVersion(files);
if (versions.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Not a single version matching semver for path ["
+ dir.toAbsolutePath().toString() + "] was found");
log.debug("Not a single version matching semver for path [" + dir.toAbsolutePath().toString()
+ "] was found");
}
return FileVisitResult.CONTINUE;
}
// 2.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT
// 2.0.0.RELEASE
DefaultArtifactVersionWrapper latestFoundVersion = versions
.get(versions.size() - 1);
latestFoundVersion = replaceWithSnapshotIfSameVersions(versions,
latestFoundVersion);
DefaultArtifactVersionWrapper latestFoundVersion = versions.get(versions.size() - 1);
latestFoundVersion = replaceWithSnapshotIfSameVersions(versions, latestFoundVersion);
this.foundFile = latestFoundVersion.file.toPath();
return FileVisitResult.TERMINATE;
}
private DefaultArtifactVersionWrapper replaceWithSnapshotIfSameVersions(
List<DefaultArtifactVersionWrapper> versions,
final DefaultArtifactVersionWrapper latestFoundVersion) {
List<DefaultArtifactVersionWrapper> versions, final DefaultArtifactVersionWrapper latestFoundVersion) {
if (versions.size() > 1 && this.latestSnapshotVersion) {
// 2.0.1.BUILD-SNAPSHOT, 2.0.0.BUILD-SNAPSHOT
// 2.0.0.BUILD-SNAPSHOT, 2.0.0.RELEASE
DefaultArtifactVersionWrapper sameVersionButSnapshot = versions.stream()
.filter(w -> w.projectVersion.isSameWithoutSuffix(
latestFoundVersion.projectVersion) && w.isSnapshot())
DefaultArtifactVersionWrapper sameVersionButSnapshot = versions.stream().filter(
w -> w.projectVersion.isSameWithoutSuffix(latestFoundVersion.projectVersion) && w.isSnapshot())
.findFirst().orElse(latestFoundVersion);
// 2.0.0 vs 2.0.0
// replace the RELEASE one with SNAPSHOT
@@ -384,19 +358,17 @@ class FileWalker extends SimpleFileVisitor<Path> {
private File folderWithPredefinedName(File[] files) {
if (this.latestSnapshotVersion) {
return Arrays.stream(files)
.filter(file -> LATEST.stream()
.anyMatch(s -> s.equals(file.getName().toLowerCase())))
.findFirst().orElse(null);
.filter(file -> LATEST.stream().anyMatch(s -> s.equals(file.getName().toLowerCase()))).findFirst()
.orElse(null);
}
return Arrays.stream(files)
.filter(file -> RELEASE.equals(file.getName().toLowerCase())).findFirst()
return Arrays.stream(files).filter(file -> RELEASE.equals(file.getName().toLowerCase())).findFirst()
.orElse(null);
}
private List<DefaultArtifactVersionWrapper> pickLatestVersion(File[] files) {
return Arrays.stream(files).map(DefaultArtifactVersionWrapper::new)
.filter(wrapper -> this.latestSnapshotVersion || wrapper.isNotSnapshot())
.sorted().collect(Collectors.toList());
.filter(wrapper -> this.latestSnapshotVersion || wrapper.isNotSnapshot()).sorted()
.collect(Collectors.toList());
}
}

View File

@@ -50,8 +50,7 @@ public class StubConfiguration {
this.classifier = DEFAULT_CLASSIFIER;
}
public StubConfiguration(String groupId, String artifactId, String version,
String classifier) {
public StubConfiguration(String groupId, String artifactId, String version, String classifier) {
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
@@ -59,8 +58,7 @@ public class StubConfiguration {
}
public StubConfiguration(String stubPath, String defaultClassifier) {
String[] parsedPath = parsedPathEmptyByDefault(stubPath, STUB_COLON_DELIMITER,
defaultClassifier);
String[] parsedPath = parsedPathEmptyByDefault(stubPath, STUB_COLON_DELIMITER, defaultClassifier);
this.groupId = parsedPath[0];
this.artifactId = parsedPath[1];
this.version = parsedPath[2];
@@ -68,16 +66,14 @@ public class StubConfiguration {
}
public StubConfiguration(String stubPath) {
String[] parsedPath = parsedPathEmptyByDefault(stubPath, STUB_COLON_DELIMITER,
DEFAULT_CLASSIFIER);
String[] parsedPath = parsedPathEmptyByDefault(stubPath, STUB_COLON_DELIMITER, DEFAULT_CLASSIFIER);
this.groupId = parsedPath[0];
this.artifactId = parsedPath[1];
this.version = parsedPath[2];
this.classifier = parsedPath[3];
}
private String[] parsedPathEmptyByDefault(String path, String delimiter,
String defaultClassifier) {
private String[] parsedPathEmptyByDefault(String path, String delimiter, String defaultClassifier) {
String[] splitPath = path.split(delimiter, -1);
String stubsGroupId = "";
String stubsArtifactId = "";
@@ -89,8 +85,7 @@ public class StubConfiguration {
stubsVersion = splitPath.length >= 3 ? splitPath[2] : DEFAULT_VERSION;
stubsClassifier = splitPath.length >= 4 ? splitPath[3] : defaultClassifier;
}
return new String[] { stubsGroupId, stubsArtifactId, stubsVersion,
stubsClassifier };
return new String[] { stubsGroupId, stubsArtifactId, stubsVersion, stubsClassifier };
}
private boolean isDefined() {
@@ -105,10 +100,8 @@ public class StubConfiguration {
if (!isDefined()) {
return "";
}
return StringUtils.arrayToDelimitedString(
new String[] { nullCheck(this.groupId), nullCheck(this.artifactId),
nullCheck(this.version), nullCheck(this.classifier) },
STUB_COLON_DELIMITER);
return StringUtils.arrayToDelimitedString(new String[] { nullCheck(this.groupId), nullCheck(this.artifactId),
nullCheck(this.version), nullCheck(this.classifier) }, STUB_COLON_DELIMITER);
}
private String nullCheck(String value) {
@@ -135,8 +128,7 @@ public class StubConfiguration {
* @return {@code true} for a snapshot or a LATEST (+) version.
*/
public boolean isVersionChanging() {
return DEFAULT_VERSION.equals(this.version)
|| this.version.toLowerCase().contains("snapshot");
return DEFAULT_VERSION.equals(this.version) || this.version.toLowerCase().contains("snapshot");
}
public String getGroupId() {
@@ -159,8 +151,7 @@ public class StubConfiguration {
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((this.artifactId == null) ? 0 : this.artifactId.hashCode());
result = prime * result + ((this.artifactId == null) ? 0 : this.artifactId.hashCode());
result = prime * result + ((this.groupId == null) ? 0 : this.groupId.hashCode());
return result;
}
@@ -201,16 +192,13 @@ public class StubConfiguration {
if (strings.length == 1) {
return this.artifactId.equals(ivyNotationAsString);
}
if (strings.length >= 2 && !(this.groupId.equals(strings[0])
&& this.artifactId.equals(strings[1]))) {
if (strings.length >= 2 && !(this.groupId.equals(strings[0]) && this.artifactId.equals(strings[1]))) {
return false;
}
if (strings.length >= 3 && !(this.version.equals(strings[2])
|| DEFAULT_VERSION.equals(strings[2]))) {
if (strings.length >= 3 && !(this.version.equals(strings[2]) || DEFAULT_VERSION.equals(strings[2]))) {
return false;
}
if (strings.length == 4 && !(this.classifier.equals(strings[3])
|| DEFAULT_CLASSIFIER.equals(strings[3]))) {
if (strings.length == 4 && !(this.classifier.equals(strings[3]) || DEFAULT_CLASSIFIER.equals(strings[3]))) {
return false;
}
return true;

View File

@@ -40,7 +40,6 @@ public interface StubDownloader {
* version) and the location of the downloaded stubs. If there was no artifact this
* method will return {@code null}.
*/
Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
StubConfiguration stubConfiguration);
Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(StubConfiguration stubConfiguration);
}

View File

@@ -34,8 +34,7 @@ public class StubDownloaderBuilderProvider {
private final List<StubDownloaderBuilder> builders = new ArrayList<>();
public StubDownloaderBuilderProvider() {
this.builders.addAll(
SpringFactoriesLoader.loadFactories(StubDownloaderBuilder.class, null));
this.builders.addAll(SpringFactoriesLoader.loadFactories(StubDownloaderBuilder.class, null));
}
StubDownloaderBuilderProvider(List<StubDownloaderBuilder> builders) {
@@ -49,8 +48,7 @@ public class StubDownloaderBuilderProvider {
* @return composite {@link StubDownloader} that iterates over a list of stub
* downloaders
*/
public StubDownloader get(StubRunnerOptions stubRunnerOptions,
StubDownloaderBuilder... additionalBuilders) {
public StubDownloader get(StubRunnerOptions stubRunnerOptions, StubDownloaderBuilder... additionalBuilders) {
List<StubDownloaderBuilder> builders = this.builders;
if (additionalBuilders != null) {
builders.addAll(Arrays.asList(additionalBuilders));
@@ -61,8 +59,8 @@ public class StubDownloaderBuilderProvider {
}
List<StubDownloaderBuilder> defaultStubDownloaderBuilders() {
return Arrays.asList(new ScmStubDownloaderBuilder(), new ClasspathStubProvider(),
new FileStubDownloader(), new AetherStubDownloaderBuilder());
return Arrays.asList(new ScmStubDownloaderBuilder(), new ClasspathStubProvider(), new FileStubDownloader(),
new AetherStubDownloaderBuilder());
}
}

View File

@@ -25,8 +25,7 @@ package org.springframework.cloud.contract.stubrunner;
public class StubNotFoundException extends RuntimeException {
public StubNotFoundException(String groupId, String artifactId) {
super("Stub not found for groupid [" + groupId + "] and artifactid [" + artifactId
+ "]");
super("Stub not found for groupid [" + groupId + "] and artifactid [" + artifactId + "]");
}
public StubNotFoundException(String ivyNotation) {

View File

@@ -57,17 +57,13 @@ class StubRepository {
private final StubRunnerOptions options;
StubRepository(File repository, List<HttpServerStub> httpServerStubs,
StubRunnerOptions options) {
StubRepository(File repository, List<HttpServerStub> httpServerStubs, StubRunnerOptions options) {
if (!repository.isDirectory()) {
throw new IllegalArgumentException(
"Missing descriptor repository under path [" + repository + "]");
throw new IllegalArgumentException("Missing descriptor repository under path [" + repository + "]");
}
this.contractConverters = SpringFactoriesLoader
.loadFactories(ContractConverter.class, null);
this.contractConverters = SpringFactoriesLoader.loadFactories(ContractConverter.class, null);
if (log.isTraceEnabled()) {
log.trace(
"Found the following contract converters " + this.contractConverters);
log.trace("Found the following contract converters " + this.contractConverters);
}
this.httpServerStubs = httpServerStubs;
this.path = repository;
@@ -110,26 +106,22 @@ class StubRepository {
}
private List<File> collectedStubs() {
return this.path.exists() ? collectMappings(this.path)
: Collections.<File>emptyList();
return this.path.exists() ? collectMappings(this.path) : Collections.<File>emptyList();
}
private List<File> collectMappings(File descriptorsDirectory) {
final List<File> mappingDescriptors = new ArrayList<>();
try {
Files.walkFileTree(Paths.get(descriptorsDirectory.toURI()),
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path,
BasicFileAttributes attrs) throws IOException {
File file = path.toFile();
if (httpServerStubAccepts(file)
&& isStubPerConsumerPathMatching(file)) {
mappingDescriptors.add(file);
}
return super.visitFile(path, attrs);
}
});
Files.walkFileTree(Paths.get(descriptorsDirectory.toURI()), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
File file = path.toFile();
if (httpServerStubAccepts(file) && isStubPerConsumerPathMatching(file)) {
mappingDescriptors.add(file);
}
return super.visitFile(path, attrs);
}
});
}
catch (IOException e) {
log.warn("Exception occurred while trying to parse file", e);
@@ -158,8 +150,7 @@ class StubRepository {
private Collection<Contract> contractDescriptors() {
return (this.path.exists()
? ContractScanner.collectContractDescriptors(this.path,
this::isStubPerConsumerPathMatching)
? ContractScanner.collectContractDescriptors(this.path, this::isStubPerConsumerPathMatching)
: Collections.<Contract>emptySet());
}
@@ -172,9 +163,8 @@ class StubRepository {
String absolutePath = file.getAbsolutePath();
boolean stubPerConsumerMatching = absolutePath.contains(searchedConsumerName);
if (log.isDebugEnabled()) {
log.debug("Absolute path [" + absolutePath + "] contains ["
+ searchedConsumerName + "] in its path [" + stubPerConsumerMatching
+ "]");
log.debug("Absolute path [" + absolutePath + "] contains [" + searchedConsumerName + "] in its path ["
+ stubPerConsumerMatching + "]");
}
return stubPerConsumerMatching;
}

View File

@@ -56,48 +56,38 @@ public class StubRunner implements StubRunning {
public StubRunner(StubRunnerOptions stubRunnerOptions, String repositoryPath,
StubConfiguration stubsConfiguration) {
this(stubRunnerOptions, repositoryPath, stubsConfiguration,
new NoOpStubMessages());
this(stubRunnerOptions, repositoryPath, stubsConfiguration, new NoOpStubMessages());
}
public StubRunner(StubRunnerOptions stubRunnerOptions, String repositoryPath,
StubConfiguration stubsConfiguration,
public StubRunner(StubRunnerOptions stubRunnerOptions, String repositoryPath, StubConfiguration stubsConfiguration,
MessageVerifier<?> contractVerifierMessaging) {
this.stubsConfiguration = stubsConfiguration;
this.stubRunnerOptions = stubRunnerOptions;
List<HttpServerStub> serverStubs = SpringFactoriesLoader
.loadFactories(HttpServerStub.class, null);
this.stubRepository = new StubRepository(new File(repositoryPath), serverStubs,
this.stubRunnerOptions);
AvailablePortScanner portScanner = new AvailablePortScanner(
stubRunnerOptions.getMinPortValue(), stubRunnerOptions.getMaxPortValue());
this.localStubRunner = new StubRunnerExecutor(portScanner,
contractVerifierMessaging, serverStubs);
List<HttpServerStub> serverStubs = SpringFactoriesLoader.loadFactories(HttpServerStub.class, null);
this.stubRepository = new StubRepository(new File(repositoryPath), serverStubs, this.stubRunnerOptions);
AvailablePortScanner portScanner = new AvailablePortScanner(stubRunnerOptions.getMinPortValue(),
stubRunnerOptions.getMaxPortValue());
this.localStubRunner = new StubRunnerExecutor(portScanner, contractVerifierMessaging, serverStubs);
}
@Override
public RunningStubs runStubs() {
registerShutdownHook();
RunningStubs stubs = this.localStubRunner.runStubs(this.stubRunnerOptions,
this.stubRepository, this.stubsConfiguration);
RunningStubs stubs = this.localStubRunner.runStubs(this.stubRunnerOptions, this.stubRepository,
this.stubsConfiguration);
if (this.stubRunnerOptions.hasMappingsOutputFolder()) {
String registeredMappings = this.localStubRunner.registeredMappings();
if (StringUtils.hasText(registeredMappings)) {
File outputMappings = new File(
this.stubRunnerOptions.getMappingsOutputFolder(),
File outputMappings = new File(this.stubRunnerOptions.getMappingsOutputFolder(),
this.stubsConfiguration.artifactId + "_"
+ stubs.getPort(this.stubsConfiguration
.toColonSeparatedDependencyNotation()));
+ stubs.getPort(this.stubsConfiguration.toColonSeparatedDependencyNotation()));
try {
outputMappings.getParentFile().mkdirs();
clearOldFiles(outputMappings.getParentFile(),
this.stubsConfiguration.artifactId);
clearOldFiles(outputMappings.getParentFile(), this.stubsConfiguration.artifactId);
outputMappings.createNewFile();
Files.write(Paths.get(outputMappings.toURI()),
registeredMappings.getBytes());
Files.write(Paths.get(outputMappings.toURI()), registeredMappings.getBytes());
if (log.isDebugEnabled()) {
log.debug("Stored the mappings for artifactid ["
+ this.stubsConfiguration.artifactId + "] at ["
log.debug("Stored the mappings for artifactid [" + this.stubsConfiguration.artifactId + "] at ["
+ outputMappings + "] location");
}
}
@@ -126,8 +116,7 @@ public class StubRunner implements StubRunning {
for (final File file : files) {
if (!file.delete()) {
if (log.isDebugEnabled()) {
log.debug("Exception occurred while trying to remove ["
+ file.getAbsolutePath() + "]");
log.debug("Exception occurred while trying to remove [" + file.getAbsolutePath() + "]");
}
}
}

View File

@@ -51,8 +51,7 @@ import org.springframework.cloud.contract.verifier.util.BodyExtractor;
*/
class StubRunnerExecutor implements StubFinder {
static final Set<StubServer> STUB_SERVERS = Collections
.synchronizedSet(new HashSet<>());
static final Set<StubServer> STUB_SERVERS = Collections.synchronizedSet(new HashSet<>());
private static final Log log = LogFactory.getLog(StubRunnerExecutor.class);
@@ -66,16 +65,14 @@ class StubRunnerExecutor implements StubFinder {
private final YamlContractConverter yamlContractConverter = new YamlContractConverter();
StubRunnerExecutor(AvailablePortScanner portScanner,
MessageVerifier<?> contractVerifierMessaging,
StubRunnerExecutor(AvailablePortScanner portScanner, MessageVerifier<?> contractVerifierMessaging,
List<HttpServerStub> serverStubs) {
this.portScanner = portScanner;
this.contractVerifierMessaging = contractVerifierMessaging;
this.serverStubs = serverStubs;
}
StubRunnerExecutor(AvailablePortScanner portScanner,
List<HttpServerStub> serverStubs) {
StubRunnerExecutor(AvailablePortScanner portScanner, List<HttpServerStub> serverStubs) {
this(portScanner, new NoOpStubMessages(), serverStubs);
}
@@ -83,12 +80,12 @@ class StubRunnerExecutor implements StubFinder {
this(portScanner, new NoOpStubMessages(), new ArrayList<>());
}
public RunningStubs runStubs(StubRunnerOptions stubRunnerOptions,
StubRepository repository, StubConfiguration stubConfiguration) {
public RunningStubs runStubs(StubRunnerOptions stubRunnerOptions, StubRepository repository,
StubConfiguration stubConfiguration) {
if (this.stubServer != null) {
if (log.isDebugEnabled()) {
log.debug("Returning cached version of stubs ["
+ stubConfiguration.toColonSeparatedDependencyNotation() + "]");
log.debug("Returning cached version of stubs [" + stubConfiguration.toColonSeparatedDependencyNotation()
+ "]");
}
return runningStubs();
}
@@ -101,8 +98,8 @@ class StubRunnerExecutor implements StubFinder {
}
private RunningStubs runningStubs() {
return new RunningStubs(Collections.singletonMap(
this.stubServer.getStubConfiguration(), this.stubServer.getPort()));
return new RunningStubs(
Collections.singletonMap(this.stubServer.getStubConfiguration(), this.stubServer.getPort()));
}
public void shutdown() {
@@ -119,13 +116,11 @@ class StubRunnerExecutor implements StubFinder {
public URL findStubUrl(String groupId, String artifactId) {
URL url = null;
if (groupId == null) {
url = findStubUrl(
this.stubServer.stubConfiguration.artifactId.equals(artifactId));
url = findStubUrl(this.stubServer.stubConfiguration.artifactId.equals(artifactId));
}
if (url == null) {
url = findStubUrl(
this.stubServer.stubConfiguration.artifactId.equals(artifactId)
&& this.stubServer.stubConfiguration.groupId.equals(groupId));
url = findStubUrl(this.stubServer.stubConfiguration.artifactId.equals(artifactId)
&& this.stubServer.stubConfiguration.groupId.equals(groupId));
}
if (url == null) {
throw new StubNotFoundException(groupId, artifactId);
@@ -137,8 +132,8 @@ class StubRunnerExecutor implements StubFinder {
public URL findStubUrl(String ivyNotation) {
String[] splitString = ivyNotation.split(":", -1);
if (splitString.length > 4) {
throw new IllegalArgumentException("[" + ivyNotation
+ "] is an invalid notation. Pass [groupId]:artifactId[:version][:classifier].");
throw new IllegalArgumentException(
"[" + ivyNotation + "] is an invalid notation. Pass [groupId]:artifactId[:version][:classifier].");
}
else if (splitString.length == 1) {
return findStubUrl(null, splitString[0]);
@@ -149,8 +144,7 @@ class StubRunnerExecutor implements StubFinder {
else if (splitString.length == 3) {
return findStubUrl(groupIdArtifactVersionMatches(splitString));
}
return findStubUrl(groupIdArtifactVersionMatches(splitString)
&& classifierMatches(splitString));
return findStubUrl(groupIdArtifactVersionMatches(splitString) && classifierMatches(splitString));
}
private boolean classifierMatches(String[] splitString) {
@@ -169,21 +163,18 @@ class StubRunnerExecutor implements StubFinder {
@Override
public RunningStubs findAllRunningStubs() {
return new RunningStubs(Collections.singletonMap(
this.stubServer.stubConfiguration, this.stubServer.getPort()));
return new RunningStubs(Collections.singletonMap(this.stubServer.stubConfiguration, this.stubServer.getPort()));
}
@Override
public Map<StubConfiguration, Collection<Contract>> getContracts() {
return Collections.singletonMap(this.stubServer.stubConfiguration,
this.stubServer.getContracts());
return Collections.singletonMap(this.stubServer.stubConfiguration, this.stubServer.getContracts());
}
@Override
public boolean trigger(String ivyNotationAsString, String labelName) {
Collection<Contract> matchingContracts = new ArrayList<>();
for (Entry<StubConfiguration, Collection<Contract>> it : getContracts()
.entrySet()) {
for (Entry<StubConfiguration, Collection<Contract>> it : getContracts().entrySet()) {
if (it.getKey().groupIdAndArtifactMatches(ivyNotationAsString)) {
matchingContracts.addAll(it.getValue());
}
@@ -203,8 +194,7 @@ class StubRunnerExecutor implements StubFinder {
private boolean triggerForDsls(Collection<Contract> dsls, String labelName) {
Collection<Contract> matchingDsls = new ArrayList<>();
for (Contract contract : dsls) {
if (labelName.equals(contract.getLabel())
&& contract.getOutputMessage() != null) {
if (labelName.equals(contract.getLabel()) && contract.getOutputMessage() != null) {
matchingDsls.add(contract);
}
}
@@ -239,8 +229,7 @@ class StubRunnerExecutor implements StubFinder {
@Override
public Map<String, Collection<String>> labels() {
Map<String, Collection<String>> labels = new LinkedHashMap<>();
for (Entry<StubConfiguration, Collection<Contract>> it : getContracts()
.entrySet()) {
for (Entry<StubConfiguration, Collection<Contract>> it : getContracts().entrySet()) {
Collection<String> values = new ArrayList<>();
for (Contract contract : it.getValue()) {
if (contract.getLabel() != null) {
@@ -256,20 +245,17 @@ class StubRunnerExecutor implements StubFinder {
OutputMessage outputMessage = groovyDsl.getOutputMessage();
DslProperty<?> body = outputMessage.getBody();
Headers headers = outputMessage.getHeaders();
List<YamlContract> yamlContracts = yamlContractConverter
.convertTo(Collections.singleton(groovyDsl));
List<YamlContract> yamlContracts = yamlContractConverter.convertTo(Collections.singleton(groovyDsl));
YamlContract contract = yamlContracts.get(0);
setMessageType(contract, ContractVerifierMessageMetadata.MessageType.OUTPUT);
// TODO: Json is harcoded here
this.contractVerifierMessaging.send(
JsonOutput.toJson(BodyExtractor.extractClientValueFromBody(
body == null ? null : body.getClientValue())),
headers == null ? null : headers.asStubSideMap(),
outputMessage.getSentTo().getClientValue(), contract);
JsonOutput
.toJson(BodyExtractor.extractClientValueFromBody(body == null ? null : body.getClientValue())),
headers == null ? null : headers.asStubSideMap(), outputMessage.getSentTo().getClientValue(), contract);
}
private void setMessageType(YamlContract contract,
ContractVerifierMessageMetadata.MessageType output) {
private void setMessageType(YamlContract contract, ContractVerifierMessageMetadata.MessageType output) {
contract.metadata.put(ContractVerifierMessageMetadata.METADATA_KEY,
new ContractVerifierMessageMetadata(output));
}
@@ -278,39 +264,35 @@ class StubRunnerExecutor implements StubFinder {
return condition ? this.stubServer.getStubUrl() : null;
}
private StubServer startStubServers(HttpServerStubConfigurer configurer,
final StubRunnerOptions stubRunnerOptions,
private StubServer startStubServers(HttpServerStubConfigurer configurer, final StubRunnerOptions stubRunnerOptions,
final StubConfiguration stubConfiguration, StubRepository repository) {
final List<File> mappings = repository.getStubs();
final Collection<Contract> contracts = repository.contracts;
Integer port = stubRunnerOptions.port(stubConfiguration);
boolean randomPort = randomPort(port);
HttpServerStubConfiguration configuration = new HttpServerStubConfiguration(
configurer, stubRunnerOptions, stubConfiguration, port, randomPort);
HttpServerStubConfiguration configuration = new HttpServerStubConfiguration(configurer, stubRunnerOptions,
stubConfiguration, port, randomPort);
if (!hasRequest(contracts) && mappings.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("There are no HTTP related contracts. Won't start any servers");
}
this.stubServer = new StubServer(stubConfiguration, mappings, contracts,
new NoOpHttpServerStub()).start(configuration);
this.stubServer = new StubServer(stubConfiguration, mappings, contracts, new NoOpHttpServerStub())
.start(configuration);
return this.stubServer;
}
if (!randomPort) {
this.stubServer = new StubServer(stubConfiguration, mappings, contracts,
httpServerStub()).start(configuration);
this.stubServer = new StubServer(stubConfiguration, mappings, contracts, httpServerStub())
.start(configuration);
}
else {
this.stubServer = this.portScanner
.tryToExecuteWithFreePort(new PortCallback<StubServer>() {
@Override
public StubServer call(int availablePort) {
return new StubServer(stubConfiguration, mappings, contracts,
httpServerStub()).start(
new HttpServerStubConfiguration(configurer,
stubRunnerOptions, stubConfiguration,
availablePort, true));
}
});
this.stubServer = this.portScanner.tryToExecuteWithFreePort(new PortCallback<StubServer>() {
@Override
public StubServer call(int availablePort) {
return new StubServer(stubConfiguration, mappings, contracts, httpServerStub())
.start(new HttpServerStubConfiguration(configurer, stubRunnerOptions, stubConfiguration,
availablePort, true));
}
});
}
STUB_SERVERS.add(this.stubServer);
return this.stubServer;

View File

@@ -60,22 +60,18 @@ class StubRunnerFactory {
public Collection<StubRunner> createStubsFromServiceConfiguration() {
if (log.isDebugEnabled()) {
log.debug("Will download stubs for dependencies "
+ this.stubRunnerOptions.getDependencies());
log.debug("Will download stubs for dependencies " + this.stubRunnerOptions.getDependencies());
}
if (this.stubRunnerOptions.getDependencies().isEmpty()) {
log.warn(
"No stubs to download have been passed. Most likely you have forgotten to pass "
+ "them either via annotation or a property");
log.warn("No stubs to download have been passed. Most likely you have forgotten to pass "
+ "them either via annotation or a property");
}
Collection<StubRunner> result = new ArrayList<>();
for (StubConfiguration stubsConfiguration : this.stubRunnerOptions
.getDependencies()) {
Map.Entry<StubConfiguration, File> entry = this.stubDownloader
.downloadAndUnpackStubJar(stubsConfiguration);
for (StubConfiguration stubsConfiguration : this.stubRunnerOptions.getDependencies()) {
Map.Entry<StubConfiguration, File> entry = this.stubDownloader.downloadAndUnpackStubJar(stubsConfiguration);
if (log.isDebugEnabled()) {
log.debug("For stub configuration [" + stubsConfiguration
+ "] the downloaded entry is [" + entry + "]");
log.debug(
"For stub configuration [" + stubsConfiguration + "] the downloaded entry is [" + entry + "]");
}
if (entry != null) {
Path path = resolvePath(entry.getValue());
@@ -122,8 +118,7 @@ class StubRunnerFactory {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
Collection<StubGenerator> stubGenerators = this.provider
.converterForName(file.toString());
Collection<StubGenerator> stubGenerators = this.provider.converterForName(file.toString());
if (!stubGenerators.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Deleting file [" + file.toString()
@@ -133,8 +128,7 @@ class StubRunnerFactory {
Files.delete(file);
}
catch (IOException ex) {
log.warn("Failed to delete file [" + file.toString() + "]",
ex);
log.warn("Failed to delete file [" + file.toString() + "]", ex);
}
}
return FileVisitResult.CONTINUE;
@@ -149,9 +143,8 @@ class StubRunnerFactory {
private void generateNewMappings(Path path) {
File unpackedLocation = path.toFile();
RecursiveFilesConverter converter = new RecursiveFilesConverter(
subfolderIfPresent(unpackedLocation, "mappings"),
subfolderIfPresent(unpackedLocation, "contracts"), new ArrayList<>(),
".*", false);
subfolderIfPresent(unpackedLocation, "mappings"), subfolderIfPresent(unpackedLocation, "contracts"),
new ArrayList<>(), ".*", false);
converter.processFiles();
}
@@ -163,19 +156,17 @@ class StubRunnerFactory {
return unpackedLocation;
}
private StubRunner createStubRunner(StubConfiguration stubsConfiguration,
File unzipedStubDir) {
private StubRunner createStubRunner(StubConfiguration stubsConfiguration, File unzipedStubDir) {
if (unzipedStubDir == null) {
return null;
}
return createStubRunner(unzipedStubDir, stubsConfiguration,
this.stubRunnerOptions);
return createStubRunner(unzipedStubDir, stubsConfiguration, this.stubRunnerOptions);
}
private StubRunner createStubRunner(File unzippedStubsDir,
StubConfiguration stubsConfiguration, StubRunnerOptions stubRunnerOptions) {
return new StubRunner(stubRunnerOptions, unzippedStubsDir.getPath(),
stubsConfiguration, this.contractVerifierMessaging);
private StubRunner createStubRunner(File unzippedStubsDir, StubConfiguration stubsConfiguration,
StubRunnerOptions stubRunnerOptions) {
return new StubRunner(stubRunnerOptions, unzippedStubsDir.getPath(), stubsConfiguration,
this.contractVerifierMessaging);
}
}

View File

@@ -43,51 +43,45 @@ public class StubRunnerMain {
private StubRunnerMain(String[] args) throws Exception {
OptionParser parser = new OptionParser();
try {
ArgumentAcceptingOptionSpec<Integer> minPortValueOpt = parser.acceptsAll(
Arrays.asList("minp", "minPort"),
"Minimum port value to be assigned to the WireMock instance. Defaults to 10000")
ArgumentAcceptingOptionSpec<Integer> minPortValueOpt = parser
.acceptsAll(Arrays.asList("minp", "minPort"),
"Minimum port value to be assigned to the WireMock instance. Defaults to 10000")
.withRequiredArg().ofType(Integer.class).defaultsTo(10000);
ArgumentAcceptingOptionSpec<Integer> maxPortValueOpt = parser.acceptsAll(
Arrays.asList("maxp", "maxPort"),
"Maximum port value to be assigned to the WireMock instance. Defaults to 15000")
ArgumentAcceptingOptionSpec<Integer> maxPortValueOpt = parser
.acceptsAll(Arrays.asList("maxp", "maxPort"),
"Maximum port value to be assigned to the WireMock instance. Defaults to 15000")
.withRequiredArg().ofType(Integer.class).defaultsTo(15000);
ArgumentAcceptingOptionSpec<String> stubsOpt = parser.acceptsAll(
Arrays.asList("s", "stubs"),
"Comma separated list of Ivy representation "
+ "of jars with stubs. Eg. groupid:artifactid1,groupid2:artifactid2:classifier")
ArgumentAcceptingOptionSpec<String> stubsOpt = parser
.acceptsAll(Arrays.asList("s", "stubs"),
"Comma separated list of Ivy representation "
+ "of jars with stubs. Eg. groupid:artifactid1,groupid2:artifactid2:classifier")
.withRequiredArg();
ArgumentAcceptingOptionSpec<String> classifierOpt = parser.acceptsAll(
Arrays.asList("c", "classifier"),
"Suffix for the jar containing stubs (e.g. 'stubs' "
ArgumentAcceptingOptionSpec<String> classifierOpt = parser
.acceptsAll(Arrays.asList("c", "classifier"), "Suffix for the jar containing stubs (e.g. 'stubs' "
+ "if the stub jar would have a 'stubs' classifier for stubs: foobar-stubs ). Defaults to 'stubs'")
.withRequiredArg().defaultsTo("stubs");
ArgumentAcceptingOptionSpec<String> rootOpt = parser.acceptsAll(
Arrays.asList("r", "root"),
"Location of a Jar containing server where you keep "
+ "your stubs (e.g. https://nexus.net/content/repositories/repository)")
ArgumentAcceptingOptionSpec<String> rootOpt = parser
.acceptsAll(Arrays.asList("r", "root"),
"Location of a Jar containing server where you keep "
+ "your stubs (e.g. https://nexus.net/content/repositories/repository)")
.withRequiredArg();
ArgumentAcceptingOptionSpec<String> usernameOpt = parser
.acceptsAll(Arrays.asList("u", "username"),
"Username to user when connecting to repository")
.acceptsAll(Arrays.asList("u", "username"), "Username to user when connecting to repository")
.withOptionalArg();
ArgumentAcceptingOptionSpec<String> passwordOpt = parser
.acceptsAll(Arrays.asList("p", "password"),
"Password to user when connecting to repository")
.acceptsAll(Arrays.asList("p", "password"), "Password to user when connecting to repository")
.withOptionalArg();
ArgumentAcceptingOptionSpec<String> proxyHostOpt = parser
.acceptsAll(Arrays.asList("phost", "proxyHost"),
"Proxy host to use for repository requests")
.acceptsAll(Arrays.asList("phost", "proxyHost"), "Proxy host to use for repository requests")
.withOptionalArg();
ArgumentAcceptingOptionSpec<Integer> proxyPortOpt = parser
.acceptsAll(Arrays.asList("pport", "proxyPort"),
"Proxy port to use for repository requests")
.acceptsAll(Arrays.asList("pport", "proxyPort"), "Proxy port to use for repository requests")
.withOptionalArg().ofType(Integer.class);
ArgumentAcceptingOptionSpec<String> stubsMode = parser
.acceptsAll(Arrays.asList("sm", "stubsMode"),
"Stubs mode to be used. Acceptable values " + Arrays
.toString(StubRunnerProperties.StubsMode.values()))
.withRequiredArg()
.defaultsTo(StubRunnerProperties.StubsMode.CLASSPATH.toString());
"Stubs mode to be used. Acceptable values "
+ Arrays.toString(StubRunnerProperties.StubsMode.values()))
.withRequiredArg().defaultsTo(StubRunnerProperties.StubsMode.CLASSPATH.toString());
OptionSet options = parser.parse(args);
String stubs = options.valueOf(stubsOpt);
StubRunnerProperties.StubsMode stubsModeValue = StubRunnerProperties.StubsMode
@@ -101,10 +95,9 @@ public class StubRunnerMain {
final String proxyHost = options.valueOf(proxyHostOpt);
final Integer proxyPort = options.valueOf(proxyPortOpt);
final StubRunnerOptionsBuilder builder = new StubRunnerOptionsBuilder()
.withMinMaxPort(minPortValue, maxPortValue)
.withStubRepositoryRoot(stubRepositoryRoot)
.withStubsMode(stubsModeValue).withStubsClassifier(stubsSuffix)
.withUsername(username).withPassword(password).withStubs(stubs);
.withMinMaxPort(minPortValue, maxPortValue).withStubRepositoryRoot(stubRepositoryRoot)
.withStubsMode(stubsModeValue).withStubsClassifier(stubsSuffix).withUsername(username)
.withPassword(password).withStubs(stubs);
if (proxyHost != null) {
builder.withProxy(proxyHost, proxyPort);
}
@@ -126,8 +119,7 @@ public class StubRunnerMain {
System.err.println("java -jar stub-runner.jar [options...] ");
parser.printHelpOn(System.err);
System.err.println();
System.err.println(
"Example: java -jar stub-runner.jar ${parser.printExample(ALL)}");
System.err.println("Example: java -jar stub-runner.jar ${parser.printExample(ALL)}");
}
private void execute() {
@@ -136,8 +128,8 @@ public class StubRunnerMain {
log.debug("Launching StubRunner with args: " + this.arguments);
}
// TODO: Pass StubsToRun either from String or File
BatchStubRunner stubRunner = new BatchStubRunnerFactory(
this.arguments.getStubRunnerOptions()).buildBatchStubRunner();
BatchStubRunner stubRunner = new BatchStubRunnerFactory(this.arguments.getStubRunnerOptions())
.buildBatchStubRunner();
RunningStubs runningCollaborators = stubRunner.runStubs();
log.info(runningCollaborators.toString());
}

View File

@@ -140,21 +140,17 @@ public class StubRunnerOptions {
*/
final String serverId;
StubRunnerOptions(Integer minPortValue, Integer maxPortValue,
Resource stubRepositoryRoot, StubRunnerProperties.StubsMode stubsMode,
String stubsClassifier, Collection<StubConfiguration> dependencies,
Map<StubConfiguration, Integer> stubIdsToPortMapping, String username,
String password, final StubRunnerProxyOptions stubRunnerProxyOptions,
boolean stubsPerConsumer, String consumerName, String mappingsOutputFolder,
boolean deleteStubsAfterTest, boolean generateStubs, boolean failOnNoStubs,
Map<String, String> properties,
Class<? extends HttpServerStubConfigurer> httpServerStubConfigurer,
String serverId) {
StubRunnerOptions(Integer minPortValue, Integer maxPortValue, Resource stubRepositoryRoot,
StubRunnerProperties.StubsMode stubsMode, String stubsClassifier,
Collection<StubConfiguration> dependencies, Map<StubConfiguration, Integer> stubIdsToPortMapping,
String username, String password, final StubRunnerProxyOptions stubRunnerProxyOptions,
boolean stubsPerConsumer, String consumerName, String mappingsOutputFolder, boolean deleteStubsAfterTest,
boolean generateStubs, boolean failOnNoStubs, Map<String, String> properties,
Class<? extends HttpServerStubConfigurer> httpServerStubConfigurer, String serverId) {
this.minPortValue = minPortValue;
this.maxPortValue = maxPortValue;
this.stubRepositoryRoot = stubRepositoryRoot;
this.stubsMode = stubsMode != null ? stubsMode
: StubRunnerProperties.StubsMode.CLASSPATH;
this.stubsMode = stubsMode != null ? stubsMode : StubRunnerProperties.StubsMode.CLASSPATH;
this.stubsClassifier = stubsClassifier;
this.dependencies = dependencies;
this.stubIdsToPortMapping = stubIdsToPortMapping;
@@ -174,51 +170,39 @@ public class StubRunnerOptions {
public static StubRunnerOptions fromSystemProps() {
StubRunnerOptionsBuilder builder = new StubRunnerOptionsBuilder()
.withMinPort(Integer.valueOf(
System.getProperty("stubrunner.port.range.min", "10000")))
.withMaxPort(Integer.valueOf(
System.getProperty("stubrunner.port.range.max", "15000")))
.withStubRepositoryRoot(ResourceResolver
.resource(System.getProperty("stubrunner.repository.root", "")))
.withMinPort(Integer.valueOf(System.getProperty("stubrunner.port.range.min", "10000")))
.withMaxPort(Integer.valueOf(System.getProperty("stubrunner.port.range.max", "15000")))
.withStubRepositoryRoot(ResourceResolver.resource(System.getProperty("stubrunner.repository.root", "")))
.withStubsMode(System.getProperty("stubrunner.stubs-mode", "LOCAL"))
.withStubsClassifier(System.getProperty("stubrunner.classifier", "stubs"))
.withStubs(System.getProperty("stubrunner.ids", ""))
.withUsername(System.getProperty("stubrunner.username"))
.withPassword(System.getProperty("stubrunner.password"))
.withStubPerConsumer(Boolean.parseBoolean(
System.getProperty("stubrunner.stubs-per-consumer", "false")))
.withStubPerConsumer(Boolean.parseBoolean(System.getProperty("stubrunner.stubs-per-consumer", "false")))
.withConsumerName(System.getProperty("stubrunner.consumer-name"))
.withMappingsOutputFolder(
System.getProperty("stubrunner.mappings-output-folder"))
.withDeleteStubsAfterTest(Boolean.parseBoolean(
System.getProperty("stubrunner.delete-stubs-after-test", "true")))
.withGenerateStubs(Boolean.parseBoolean(
System.getProperty("stubrunner.generate-stubs", "false")))
.withFailOnNoStubs(Boolean.parseBoolean(
System.getProperty("stubrunner.fail-on-no-stubs", "false")))
.withProperties(stubRunnerProps())
.withServerId(System.getProperty("stubrunner.server-id", ""));
.withMappingsOutputFolder(System.getProperty("stubrunner.mappings-output-folder"))
.withDeleteStubsAfterTest(
Boolean.parseBoolean(System.getProperty("stubrunner.delete-stubs-after-test", "true")))
.withGenerateStubs(Boolean.parseBoolean(System.getProperty("stubrunner.generate-stubs", "false")))
.withFailOnNoStubs(Boolean.parseBoolean(System.getProperty("stubrunner.fail-on-no-stubs", "false")))
.withProperties(stubRunnerProps()).withServerId(System.getProperty("stubrunner.server-id", ""));
builder = httpStubConfigurer(builder);
String proxyHost = System.getProperty("stubrunner.proxy.host");
if (proxyHost != null) {
builder.withProxy(proxyHost,
Integer.parseInt(System.getProperty("stubrunner.proxy.port")));
builder.withProxy(proxyHost, Integer.parseInt(System.getProperty("stubrunner.proxy.port")));
}
return builder.build();
}
private static StubRunnerOptionsBuilder httpStubConfigurer(
StubRunnerOptionsBuilder builder) {
String classProperty = System.getProperty(
"stubrunner.http-server-stub-configurer",
private static StubRunnerOptionsBuilder httpStubConfigurer(StubRunnerOptionsBuilder builder) {
String classProperty = System.getProperty("stubrunner.http-server-stub-configurer",
HttpServerStubConfigurer.NoOpHttpServerStubConfigurer.class.getName());
try {
Class clazz = Class.forName(classProperty);
return builder.withHttpServerStubConfigurer(clazz);
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException("Class [" + classProperty + "] not found",
ex);
throw new IllegalStateException("Class [" + classProperty + "] not found", ex);
}
}
@@ -230,8 +214,7 @@ public class StubRunnerOptions {
// stubrunner.properties.foo.bar=baz
.filter(s -> s.toLowerCase().startsWith("stubrunner.properties"))
// foo.bar=baz
.forEach(s -> map.put(s.substring("stubrunner.properties".length() + 1),
System.getProperty(s)));
.forEach(s -> map.put(s.substring("stubrunner.properties".length() + 1), System.getProperty(s)));
return map;
}
@@ -373,17 +356,14 @@ public class StubRunnerOptions {
@Override
public String toString() {
return "StubRunnerOptions{" + "minPortValue=" + this.minPortValue
+ ", maxPortValue=" + this.maxPortValue + ", stubRepositoryRoot='"
+ this.stubRepositoryRoot + '\'' + ", stubsMode='" + this.stubsMode
+ "', stubsClassifier='" + this.stubsClassifier + '\'' + ", dependencies="
+ this.dependencies + ", stubIdsToPortMapping="
+ this.stubIdsToPortMapping + ", username='" + obfuscate(this.username)
+ '\'' + ", password='" + obfuscate(this.password) + '\''
+ ", stubRunnerProxyOptions='" + this.stubRunnerProxyOptions
+ "', stubsPerConsumer='" + this.stubsPerConsumer + '\''
+ ", httpServerStubConfigurer='" + this.httpServerStubConfigurer + '\''
+ ", serverId='" + this.serverId + '\'' + '}';
return "StubRunnerOptions{" + "minPortValue=" + this.minPortValue + ", maxPortValue=" + this.maxPortValue
+ ", stubRepositoryRoot='" + this.stubRepositoryRoot + '\'' + ", stubsMode='" + this.stubsMode
+ "', stubsClassifier='" + this.stubsClassifier + '\'' + ", dependencies=" + this.dependencies
+ ", stubIdsToPortMapping=" + this.stubIdsToPortMapping + ", username='" + obfuscate(this.username)
+ '\'' + ", password='" + obfuscate(this.password) + '\'' + ", stubRunnerProxyOptions='"
+ this.stubRunnerProxyOptions + "', stubsPerConsumer='" + this.stubsPerConsumer + '\''
+ ", httpServerStubConfigurer='" + this.httpServerStubConfigurer + '\'' + ", serverId='" + this.serverId
+ '\'' + '}';
}
private String obfuscate(String string) {
@@ -414,8 +394,8 @@ public class StubRunnerOptions {
@Override
public String toString() {
return "StubRunnerProxyOptions{" + "proxyHost='" + this.proxyHost + '\''
+ ", proxyPort=" + this.proxyPort + '}';
return "StubRunnerProxyOptions{" + "proxyHost='" + this.proxyHost + '\'' + ", proxyPort=" + this.proxyPort
+ '}';
}
}

View File

@@ -93,8 +93,7 @@ public class StubRunnerOptionsBuilder {
list.addAll(StringUtils.commaDelimitedListToSet(stubIdsToPortMapping[0]));
return list;
}
else if (stubIdsToPortMapping.length == 1
&& containsRange(stubIdsToPortMapping[0])) {
else if (stubIdsToPortMapping.length == 1 && containsRange(stubIdsToPortMapping[0])) {
LinkedList<String> linkedList = new LinkedList<>();
String[] split = stubIdsToPortMapping[0].split(",");
for (String string : split) {
@@ -133,8 +132,7 @@ public class StubRunnerOptionsBuilder {
return this;
}
public StubRunnerOptionsBuilder withMinMaxPort(Integer minPortValue,
Integer maxPortValue) {
public StubRunnerOptionsBuilder withMinMaxPort(Integer minPortValue, Integer maxPortValue) {
this.minPortValue = minPortValue;
this.maxPortValue = maxPortValue;
return this;
@@ -162,8 +160,7 @@ public class StubRunnerOptionsBuilder {
return this;
}
public StubRunnerOptionsBuilder withStubsMode(
StubRunnerProperties.StubsMode stubsMode) {
public StubRunnerOptionsBuilder withStubsMode(StubRunnerProperties.StubsMode stubsMode) {
if (stubsMode == null) {
return this;
}
@@ -202,10 +199,9 @@ public class StubRunnerOptionsBuilder {
this.stubsPerConsumer = options.isStubsPerConsumer();
this.consumerName = options.getConsumerName();
this.mappingsOutputFolder = options.getMappingsOutputFolder();
this.stubConfigurations = options.dependencies != null ? options.dependencies
: new ArrayList<>();
this.stubIdsToPortMapping = options.stubIdsToPortMapping != null
? options.stubIdsToPortMapping : new LinkedHashMap<>();
this.stubConfigurations = options.dependencies != null ? options.dependencies : new ArrayList<>();
this.stubIdsToPortMapping = options.stubIdsToPortMapping != null ? options.stubIdsToPortMapping
: new LinkedHashMap<>();
this.deleteStubsAfterTest = options.isDeleteStubsAfterTest();
this.generateStubs = options.isGenerateStubs();
this.failOnNoStubs = options.isFailOnNoStubs();
@@ -215,14 +211,12 @@ public class StubRunnerOptionsBuilder {
return this;
}
public StubRunnerOptionsBuilder withMappingsOutputFolder(
String mappingsOutputFolder) {
public StubRunnerOptionsBuilder withMappingsOutputFolder(String mappingsOutputFolder) {
this.mappingsOutputFolder = mappingsOutputFolder;
return this;
}
public StubRunnerOptionsBuilder withDeleteStubsAfterTest(
boolean deleteStubsAfterTest) {
public StubRunnerOptionsBuilder withDeleteStubsAfterTest(boolean deleteStubsAfterTest) {
this.deleteStubsAfterTest = deleteStubsAfterTest;
return this;
}
@@ -242,8 +236,7 @@ public class StubRunnerOptionsBuilder {
return this;
}
public StubRunnerOptionsBuilder withHttpServerStubConfigurer(
Class httpServerStubConfigurer) {
public StubRunnerOptionsBuilder withHttpServerStubConfigurer(Class httpServerStubConfigurer) {
this.httpServerStubConfigurer = httpServerStubConfigurer;
return this;
}
@@ -254,18 +247,15 @@ public class StubRunnerOptionsBuilder {
}
public StubRunnerOptions build() {
return new StubRunnerOptions(this.minPortValue, this.maxPortValue,
this.stubRepositoryRoot, this.stubsMode, this.stubsClassifier,
buildDependencies(), this.stubIdsToPortMapping, this.username,
this.password, this.stubRunnerProxyOptions, this.stubsPerConsumer,
this.consumerName, this.mappingsOutputFolder, this.deleteStubsAfterTest,
this.generateStubs, this.failOnNoStubs, this.properties,
return new StubRunnerOptions(this.minPortValue, this.maxPortValue, this.stubRepositoryRoot, this.stubsMode,
this.stubsClassifier, buildDependencies(), this.stubIdsToPortMapping, this.username, this.password,
this.stubRunnerProxyOptions, this.stubsPerConsumer, this.consumerName, this.mappingsOutputFolder,
this.deleteStubsAfterTest, this.generateStubs, this.failOnNoStubs, this.properties,
this.httpServerStubConfigurer, this.serverId);
}
private Collection<StubConfiguration> buildDependencies() {
List<StubConfiguration> stubConfigurations = StubsParser.fromString(this.stubs,
this.stubsClassifier);
List<StubConfiguration> stubConfigurations = StubsParser.fromString(this.stubs, this.stubsClassifier);
this.stubConfigurations.addAll(stubConfigurations);
return this.stubConfigurations;
}
@@ -290,8 +280,7 @@ public class StubRunnerOptionsBuilder {
putStubIdsToPortMapping(StubsParser.fromStringWithPort(notation));
}
private void putStubIdsToPortMapping(
Map<StubConfiguration, Integer> stubIdsToPortMapping) {
private void putStubIdsToPortMapping(Map<StubConfiguration, Integer> stubIdsToPortMapping) {
this.stubIdsToPortMapping.putAll(stubIdsToPortMapping);
}
@@ -305,10 +294,8 @@ public class StubRunnerOptionsBuilder {
return this;
}
public StubRunnerOptionsBuilder withProxy(final String proxyHost,
final int proxyPort) {
this.stubRunnerProxyOptions = new StubRunnerOptions.StubRunnerProxyOptions(
proxyHost, proxyPort);
public StubRunnerOptionsBuilder withProxy(final String proxyHost, final int proxyPort) {
this.stubRunnerProxyOptions = new StubRunnerOptions.StubRunnerProxyOptions(proxyHost, proxyPort);
return this;
}

View File

@@ -73,8 +73,7 @@ public final class StubRunnerPropertyUtils {
if (options != null && options.containsKey(propName)) {
String value = options.get(propName);
if (log.isTraceEnabled()) {
log.trace("Options map contains the prop [" + propName + "] with value ["
+ value + "]");
log.trace("Options map contains the prop [" + propName + "] with value [" + value + "]");
}
return value;
}
@@ -92,17 +91,14 @@ public final class StubRunnerPropertyUtils {
String systemProp = FETCHER.systemProp(stubRunnerProp);
if (StringUtils.hasText(systemProp)) {
if (log.isTraceEnabled()) {
log.trace("System property [" + stubRunnerProp + "] has value ["
+ systemProp + "]");
log.trace("System property [" + stubRunnerProp + "] has value [" + systemProp + "]");
}
return systemProp;
}
String convertedEnvProp = stubRunnerProp.replaceAll("\\.", "_")
.replaceAll("-", "_").toUpperCase();
String convertedEnvProp = stubRunnerProp.replaceAll("\\.", "_").replaceAll("-", "_").toUpperCase();
String envVar = FETCHER.envVar(convertedEnvProp);
if (log.isTraceEnabled()) {
log.trace("Environment variable [" + convertedEnvProp + "] has value ["
+ envVar + "]");
log.trace("Environment variable [" + convertedEnvProp + "] has value [" + envVar + "]");
}
return envVar;
}

View File

@@ -39,8 +39,8 @@ class StubServer {
private final HttpServerStub httpServerStub;
StubServer(StubConfiguration stubConfiguration, Collection<File> mappings,
Collection<Contract> contracts, HttpServerStub httpServerStub) {
StubServer(StubConfiguration stubConfiguration, Collection<File> mappings, Collection<Contract> contracts,
HttpServerStub httpServerStub) {
this.stubConfiguration = stubConfiguration;
this.mappings = mappings;
this.httpServerStub = httpServerStub;
@@ -54,10 +54,8 @@ class StubServer {
private StubServer stubServer() {
this.httpServerStub.registerMappings(this.mappings);
log.info("Started stub server for project ["
+ this.stubConfiguration.toColonSeparatedDependencyNotation()
+ "] on port " + this.httpServerStub.port() + " with ["
+ this.mappings.size() + "] mappings");
log.info("Started stub server for project [" + this.stubConfiguration.toColonSeparatedDependencyNotation()
+ "] on port " + this.httpServerStub.port() + " with [" + this.mappings.size() + "] mappings");
if (this.mappings.isEmpty() && getPort() != -1) {
log.warn(
"There are no HTTP mappings registered, if your contracts are not messaging based then something went wrong");
@@ -81,8 +79,7 @@ class StubServer {
int httpsPort = this.httpServerStub.httpsPort();
int httpPort = this.httpServerStub.port();
if (log.isDebugEnabled()) {
log.debug("Ports for this server are https [" + httpsPort + "] and http ["
+ httpPort + "]");
log.debug("Ports for this server are https [" + httpsPort + "] and http [" + httpPort + "]");
}
return httpsPort != -1 ? httpsPort : httpPort;
}
@@ -100,8 +97,7 @@ class StubServer {
public URL getStubUrl() {
try {
return new URL(
(hasHttps() ? "https:" : "http:") + "//localhost:" + getPort());
return new URL((hasHttps() ? "https:" : "http:") + "//localhost:" + getPort());
}
catch (MalformedURLException e) {
throw new IllegalStateException("Cannot parse URL", e);
@@ -144,8 +140,8 @@ class StubServer {
@Override
public String toString() {
return "StubServer{" + "stubConfiguration=" + this.stubConfiguration
+ ", mappingsSize=" + this.mappings.size() + '}';
return "StubServer{" + "stubConfiguration=" + this.stubConfiguration + ", mappingsSize=" + this.mappings.size()
+ '}';
}
}

View File

@@ -47,8 +47,7 @@ final class TemporaryFileStorage {
* we're creating a bounded in-memory storage of unpacked files and later we register
* a shutdown hook to remove all these files.
*/
private static final BlockingQueue<File> TEMP_FILES_LOG = new LinkedBlockingQueue<>(
20_000);
private static final BlockingQueue<File> TEMP_FILES_LOG = new LinkedBlockingQueue<>(20_000);
private TemporaryFileStorage() {
throw new IllegalStateException("Can't instantiate a utility class");
@@ -72,8 +71,7 @@ final class TemporaryFileStorage {
if (file.isDirectory()) {
Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (log.isTraceEnabled()) {
log.trace("Removing file [" + file + "]");
}
@@ -82,8 +80,7 @@ final class TemporaryFileStorage {
}
@Override
public FileVisitResult postVisitDirectory(Path dir,
IOException exc) throws IOException {
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (log.isTraceEnabled()) {
log.trace("Removing dir [" + dir + "]");
}
@@ -117,9 +114,8 @@ final class TemporaryFileStorage {
return tempDir;
}
}
throw new IllegalStateException("Failed to create directory within "
+ TEMP_DIR_ATTEMPTS + " attempts (tried " + baseName + "0 to " + baseName
+ (TEMP_DIR_ATTEMPTS - 1) + ")");
throw new IllegalStateException("Failed to create directory within " + TEMP_DIR_ATTEMPTS + " attempts (tried "
+ baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ")");
}
}

View File

@@ -36,8 +36,7 @@ class ExceptionThrowingMessageVerifier implements MessageVerifier {
}
@Override
public Object receive(String destination, long timeout, TimeUnit timeUnit,
YamlContract contract) {
public Object receive(String destination, long timeout, TimeUnit timeUnit, YamlContract contract) {
throw new UnsupportedOperationException(EXCEPTION_MESSAGE);
}
@@ -47,8 +46,7 @@ class ExceptionThrowingMessageVerifier implements MessageVerifier {
}
@Override
public void send(Object payload, Map headers, String destination,
YamlContract contract) {
public void send(Object payload, Map headers, String destination, YamlContract contract) {
throw new UnsupportedOperationException(EXCEPTION_MESSAGE);
}

View File

@@ -51,8 +51,8 @@ import org.springframework.cloud.contract.verifier.messaging.MessageVerifier;
* @author Olga Maciaszek-Sharma
* @since 2.1.0
*/
public class StubRunnerExtension implements BeforeAllCallback, AfterAllCallback,
BeforeEachCallback, AfterEachCallback, StubFinder, StubRunnerExtensionOptions {
public class StubRunnerExtension implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback,
StubFinder, StubRunnerExtensionOptions {
private static final String DELIMITER = ":";
@@ -121,8 +121,7 @@ public class StubRunnerExtension implements BeforeAllCallback, AfterAllCallback,
}
private void before() {
stubFinder(new BatchStubRunnerFactory(builder().build(), verifier())
.buildBatchStubRunner());
stubFinder(new BatchStubRunnerFactory(builder().build(), verifier()).buildBatchStubRunner());
stubFinder().runStubs();
}
@@ -136,8 +135,7 @@ public class StubRunnerExtension implements BeforeAllCallback, AfterAllCallback,
}
@Override
public URL findStubUrl(String groupId, String artifactId)
throws StubNotFoundException {
public URL findStubUrl(String groupId, String artifactId) throws StubNotFoundException {
return stubFinder().findStubUrl(groupId, artifactId);
}
@@ -160,8 +158,8 @@ public class StubRunnerExtension implements BeforeAllCallback, AfterAllCallback,
public boolean trigger(String ivyNotation, String labelName) {
boolean result = stubFinder().trigger(ivyNotation, labelName);
if (!result) {
throw new IllegalStateException("Failed to trigger a message with notation ["
+ ivyNotation + "] and label [" + labelName + "]");
throw new IllegalStateException(
"Failed to trigger a message with notation [" + ivyNotation + "] and label [" + labelName + "]");
}
return result;
}
@@ -170,8 +168,7 @@ public class StubRunnerExtension implements BeforeAllCallback, AfterAllCallback,
public boolean trigger(String labelName) {
boolean result = stubFinder().trigger(labelName);
if (!result) {
throw new IllegalStateException(
"Failed to trigger a message with label [" + labelName + "]");
throw new IllegalStateException("Failed to trigger a message with label [" + labelName + "]");
}
return result;
}
@@ -227,24 +224,19 @@ public class StubRunnerExtension implements BeforeAllCallback, AfterAllCallback,
}
@Override
public PortStubRunnerExtension downloadStub(String groupId, String artifactId,
String version, String classifier) {
builder().withStubs(groupId + DELIMITER + artifactId + DELIMITER + version
+ DELIMITER + classifier);
public PortStubRunnerExtension downloadStub(String groupId, String artifactId, String version, String classifier) {
builder().withStubs(groupId + DELIMITER + artifactId + DELIMITER + version + DELIMITER + classifier);
return new PortStubRunnerExtension(this.delegate);
}
@Override
public PortStubRunnerExtension downloadLatestStub(String groupId, String artifactId,
String classifier) {
builder().withStubs(groupId + DELIMITER + artifactId + DELIMITER + LATEST_VERSION
+ DELIMITER + classifier);
public PortStubRunnerExtension downloadLatestStub(String groupId, String artifactId, String classifier) {
builder().withStubs(groupId + DELIMITER + artifactId + DELIMITER + LATEST_VERSION + DELIMITER + classifier);
return new PortStubRunnerExtension(this.delegate);
}
@Override
public PortStubRunnerExtension downloadStub(String groupId, String artifactId,
String version) {
public PortStubRunnerExtension downloadStub(String groupId, String artifactId, String version) {
builder().withStubs(groupId + DELIMITER + artifactId + DELIMITER + version);
return new PortStubRunnerExtension(this.delegate);
}
@@ -348,8 +340,7 @@ public class StubRunnerExtension implements BeforeAllCallback, AfterAllCallback,
*
* @since 1.2.0
*/
public static class PortStubRunnerExtension extends StubRunnerExtension
implements PortStubRunnerExtensionOptions {
public static class PortStubRunnerExtension extends StubRunnerExtension implements PortStubRunnerExtensionOptions {
PortStubRunnerExtension(StubRunnerExtension delegate) {
super(delegate);

View File

@@ -78,8 +78,7 @@ interface StubRunnerExtensionOptions {
* @param classifier classifier of the stub
* @return the stub runner extension with ports
*/
PortStubRunnerExtensionOptions downloadStub(String groupId, String artifactId,
String version, String classifier);
PortStubRunnerExtensionOptions downloadStub(String groupId, String artifactId, String version, String classifier);
/**
* @param groupId group id of the stub
@@ -87,8 +86,7 @@ interface StubRunnerExtensionOptions {
* @param classifier classifier of the stub
* @return the stub runner extension with ports
*/
PortStubRunnerExtensionOptions downloadLatestStub(String groupId, String artifactId,
String classifier);
PortStubRunnerExtensionOptions downloadLatestStub(String groupId, String artifactId, String classifier);
/**
* @param groupId group id of the stub
@@ -96,8 +94,7 @@ interface StubRunnerExtensionOptions {
* @param version version of the stub
* @return the stub runner extension with ports
*/
PortStubRunnerExtensionOptions downloadStub(String groupId, String artifactId,
String version);
PortStubRunnerExtensionOptions downloadStub(String groupId, String artifactId, String version);
/**
* @param groupId group id of the stub

View File

@@ -76,8 +76,7 @@ public class StubRunnerRule implements TestRule, StubFinder, StubRunnerRuleOptio
}
private void before() {
stubFinder(new BatchStubRunnerFactory(builder().build(), verifier())
.buildBatchStubRunner());
stubFinder(new BatchStubRunnerFactory(builder().build(), verifier()).buildBatchStubRunner());
StubRunnerRule.this.stubFinder().runStubs();
}
};
@@ -120,24 +119,19 @@ public class StubRunnerRule implements TestRule, StubFinder, StubRunnerRuleOptio
}
@Override
public PortStubRunnerRule downloadStub(String groupId, String artifactId,
String version, String classifier) {
builder().withStubs(groupId + DELIMITER + artifactId + DELIMITER + version
+ DELIMITER + classifier);
public PortStubRunnerRule downloadStub(String groupId, String artifactId, String version, String classifier) {
builder().withStubs(groupId + DELIMITER + artifactId + DELIMITER + version + DELIMITER + classifier);
return new PortStubRunnerRule(this.delegate);
}
@Override
public PortStubRunnerRule downloadLatestStub(String groupId, String artifactId,
String classifier) {
builder().withStubs(groupId + DELIMITER + artifactId + DELIMITER + LATEST_VERSION
+ DELIMITER + classifier);
public PortStubRunnerRule downloadLatestStub(String groupId, String artifactId, String classifier) {
builder().withStubs(groupId + DELIMITER + artifactId + DELIMITER + LATEST_VERSION + DELIMITER + classifier);
return new PortStubRunnerRule(this.delegate);
}
@Override
public PortStubRunnerRule downloadStub(String groupId, String artifactId,
String version) {
public PortStubRunnerRule downloadStub(String groupId, String artifactId, String version) {
builder().withStubs(groupId + DELIMITER + artifactId + DELIMITER + version);
return new PortStubRunnerRule(this.delegate);
}
@@ -239,8 +233,8 @@ public class StubRunnerRule implements TestRule, StubFinder, StubRunnerRuleOptio
public boolean trigger(String ivyNotation, String labelName) {
boolean result = this.stubFinder().trigger(ivyNotation, labelName);
if (!result) {
throw new IllegalStateException("Failed to trigger a message with notation ["
+ ivyNotation + "] and label [" + labelName + "]");
throw new IllegalStateException(
"Failed to trigger a message with notation [" + ivyNotation + "] and label [" + labelName + "]");
}
return result;
}
@@ -249,8 +243,7 @@ public class StubRunnerRule implements TestRule, StubFinder, StubRunnerRuleOptio
public boolean trigger(String labelName) {
boolean result = this.stubFinder().trigger(labelName);
if (!result) {
throw new IllegalStateException(
"Failed to trigger a message with label [" + labelName + "]");
throw new IllegalStateException("Failed to trigger a message with label [" + labelName + "]");
}
return result;
}
@@ -295,8 +288,7 @@ public class StubRunnerRule implements TestRule, StubFinder, StubRunnerRuleOptio
*
* @since 1.2.0
*/
public static class PortStubRunnerRule extends StubRunnerRule
implements PortStubRunnerRuleOptions {
public static class PortStubRunnerRule extends StubRunnerRule implements PortStubRunnerRuleOptions {
PortStubRunnerRule(StubRunnerRule delegate) {
super(delegate);

View File

@@ -74,8 +74,7 @@ interface StubRunnerRuleOptions {
* @param classifier classifier of the stub
* @return the rule with port
*/
PortStubRunnerRuleOptions downloadStub(String groupId, String artifactId,
String version, String classifier);
PortStubRunnerRuleOptions downloadStub(String groupId, String artifactId, String version, String classifier);
/**
* @param groupId group id of the stub
@@ -83,8 +82,7 @@ interface StubRunnerRuleOptions {
* @param classifier classifier of the stub
* @return the rule with port
*/
PortStubRunnerRuleOptions downloadLatestStub(String groupId, String artifactId,
String classifier);
PortStubRunnerRuleOptions downloadLatestStub(String groupId, String artifactId, String classifier);
/**
* @param groupId group id of the stub
@@ -92,8 +90,7 @@ interface StubRunnerRuleOptions {
* @param version version of the stub
* @return the rule with port
*/
PortStubRunnerRuleOptions downloadStub(String groupId, String artifactId,
String version);
PortStubRunnerRuleOptions downloadStub(String groupId, String artifactId, String version);
/**
* @param groupId group id of the stub
@@ -170,7 +167,6 @@ interface StubRunnerRuleOptions {
* @param httpServerStubConfigurer Configuration for an HTTP server stub
* @return the rule
*/
StubRunnerRule withHttpServerStubConfigurer(
Class<? extends HttpServerStubConfigurer> httpServerStubConfigurer);
StubRunnerRule withHttpServerStubConfigurer(Class<? extends HttpServerStubConfigurer> httpServerStubConfigurer);
}

View File

@@ -46,8 +46,7 @@ import org.springframework.util.StringUtils;
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RoutesBuilder.class)
@ConditionalOnProperty(name = "stubrunner.camel.enabled", havingValue = "true",
matchIfMissing = true)
@ConditionalOnProperty(name = "stubrunner.camel.enabled", havingValue = "true", matchIfMissing = true)
public class StubRunnerCamelConfiguration {
static final String STUBRUNNER_DESTINATION_URL_HEADER_NAME = "STUBRUNNER_DESTINATION_URL";
@@ -57,31 +56,24 @@ public class StubRunnerCamelConfiguration {
return new SpringRouteBuilder() {
@Override
public void configure() throws Exception {
Map<StubConfiguration, Collection<Contract>> contracts = batchStubRunner
.getContracts();
for (Map.Entry<StubConfiguration, Collection<Contract>> entry : contracts
.entrySet()) {
Map<StubConfiguration, Collection<Contract>> contracts = batchStubRunner.getContracts();
for (Map.Entry<StubConfiguration, Collection<Contract>> entry : contracts.entrySet()) {
Collection<Contract> value = entry.getValue();
MultiValueMap<String, Contract> map = new LinkedMultiValueMap<>();
for (Contract dsl : value) {
if (dsl == null) {
continue;
}
if (dsl.getInput() != null
&& dsl.getInput().getMessageFrom() != null
&& StringUtils.hasText(dsl.getInput().getMessageFrom()
.getClientValue())) {
String from = dsl.getInput().getMessageFrom()
.getClientValue();
if (dsl.getInput() != null && dsl.getInput().getMessageFrom() != null
&& StringUtils.hasText(dsl.getInput().getMessageFrom().getClientValue())) {
String from = dsl.getInput().getMessageFrom().getClientValue();
map.add(from, dsl);
}
}
for (Map.Entry<String, List<Contract>> entries : map.entrySet()) {
from(entries.getKey())
.filter(new StubRunnerCamelPredicate(entries.getValue()))
.process(new StubRunnerCamelProcessor())
.dynamicRouter(header(
StubRunnerCamelConfiguration.STUBRUNNER_DESTINATION_URL_HEADER_NAME));
from(entries.getKey()).filter(new StubRunnerCamelPredicate(entries.getValue()))
.process(new StubRunnerCamelProcessor()).dynamicRouter(
header(StubRunnerCamelConfiguration.STUBRUNNER_DESTINATION_URL_HEADER_NAME));
}
}
}

View File

@@ -67,8 +67,7 @@ class StubRunnerCamelPredicate implements Predicate {
public boolean matches(Exchange exchange) {
Contract contract = getContract(exchange.getMessage());
if (log.isDebugEnabled()) {
log.debug(
"For exchange [" + exchange + "] found contract [" + contract + "]");
log.debug("For exchange [" + exchange + "] found contract [" + contract + "]");
}
if (contract == null) {
return false;
@@ -91,14 +90,12 @@ class StubRunnerCamelPredicate implements Predicate {
List<String> unmatchedHeaders = headersMatch(message, groovyDsl);
if (!unmatchedHeaders.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Contract [" + groovyDsl
+ "] hasn't matched the following headers " + unmatchedHeaders);
log.debug("Contract [" + groovyDsl + "] hasn't matched the following headers " + unmatchedHeaders);
}
return null;
}
Object inputMessage = message.getBody();
Object dslBody = MapConverter
.getStubSideValues(groovyDsl.getInput().getMessageBody());
Object dslBody = MapConverter.getStubSideValues(groovyDsl.getInput().getMessageBody());
if (dslBody instanceof FromFileProperty) {
if (log.isDebugEnabled()) {
log.debug("Will compare file content");
@@ -110,19 +107,15 @@ class StubRunnerCamelPredicate implements Predicate {
}
else if (!(inputMessage instanceof byte[])) {
if (log.isDebugEnabled()) {
log.debug(
"Contract provided byte comparison, but the input message is of type ["
+ inputMessage.getClass()
+ "]. Can't compare the two.");
log.debug("Contract provided byte comparison, but the input message is of type ["
+ inputMessage.getClass() + "]. Can't compare the two.");
}
return null;
}
else {
boolean matches = Arrays.equals(property.asBytes(),
(byte[]) inputMessage);
boolean matches = Arrays.equals(property.asBytes(), (byte[]) inputMessage);
if (log.isDebugEnabled() && !matches) {
log.debug(
"Contract provided byte comparison, but the byte arrays don't match");
log.debug("Contract provided byte comparison, but the byte arrays don't match");
}
return matches ? groovyDsl : null;
}
@@ -133,11 +126,9 @@ class StubRunnerCamelPredicate implements Predicate {
return null;
}
private boolean matchViaContent(Contract groovyDsl, Object inputMessage,
Object dslBody) {
private boolean matchViaContent(Contract groovyDsl, Object inputMessage, Object dslBody) {
boolean matches;
ContentType type = ContentUtils.getClientContentType(inputMessage,
groovyDsl.getInput().getMessageHeaders());
ContentType type = ContentUtils.getClientContentType(inputMessage, groovyDsl.getInput().getMessageHeaders());
if (type == ContentType.JSON) {
BodyMatchers matchers = groovyDsl.getInput().getBodyMatchers();
matches = matchesForJsonPayload(groovyDsl, inputMessage, matchers, dslBody);
@@ -156,22 +147,19 @@ class StubRunnerCamelPredicate implements Predicate {
private void bodyUnmatchedLog(Object dslBody, boolean matches, Object pattern) {
if (log.isDebugEnabled() && !matches) {
log.debug("Body was supposed to " + unmatchedText(pattern)
+ " but the value is [" + dslBody.toString() + "]");
log.debug("Body was supposed to " + unmatchedText(pattern) + " but the value is [" + dslBody.toString()
+ "]");
}
}
private boolean matchesForJsonPayload(Contract groovyDsl, Object inputMessage,
BodyMatchers matchers, Object dslBody) {
Object matchingInputMessage = JsonToJsonPathsConverter
.removeMatchingJsonPaths(dslBody, matchers);
private boolean matchesForJsonPayload(Contract groovyDsl, Object inputMessage, BodyMatchers matchers,
Object dslBody) {
Object matchingInputMessage = JsonToJsonPathsConverter.removeMatchingJsonPaths(dslBody, matchers);
JsonPaths jsonPaths = JsonToJsonPathsConverter
.transformToJsonPathWithStubsSideValuesAndNoArraySizeCheck(
matchingInputMessage);
.transformToJsonPathWithStubsSideValuesAndNoArraySizeCheck(matchingInputMessage);
DocumentContext parsedJson;
try {
parsedJson = JsonPath
.parse(this.objectMapper.writeValueAsString(inputMessage));
parsedJson = JsonPath.parse(this.objectMapper.writeValueAsString(inputMessage));
}
catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot serialize to JSON", e);
@@ -183,22 +171,19 @@ class StubRunnerCamelPredicate implements Predicate {
}
if (matchers != null && matchers.hasMatchers()) {
for (BodyMatcher matcher : matchers.matchers()) {
String jsonPath = JsonToJsonPathsConverter
.convertJsonPathAndRegexToAJsonPath(matcher, dslBody);
String jsonPath = JsonToJsonPathsConverter.convertJsonPathAndRegexToAJsonPath(matcher, dslBody);
matches &= matchesJsonPath(unmatchedJsonPath, parsedJson, jsonPath);
}
}
if (!unmatchedJsonPath.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Contract [" + groovyDsl + "] didn't match the body due to "
+ unmatchedJsonPath);
log.debug("Contract [" + groovyDsl + "] didn't match the body due to " + unmatchedJsonPath);
}
}
return matches;
}
private boolean matchesJsonPath(List<String> unmatchedJsonPath,
DocumentContext parsedJson, String jsonPath) {
private boolean matchesJsonPath(List<String> unmatchedJsonPath, DocumentContext parsedJson, String jsonPath) {
try {
JsonAssertion.assertThat(parsedJson).matchesJsonPath(jsonPath);
return true;
@@ -222,14 +207,11 @@ class StubRunnerCamelPredicate implements Predicate {
matches = pattern.matcher(valueInHeader.toString()).matches();
}
else {
matches = valueInHeader != null
&& valueInHeader.toString().equals(value.toString());
matches = valueInHeader != null && valueInHeader.toString().equals(value.toString());
}
if (!matches) {
unmatchedHeaders.add("Header with name [" + name + "] was supposed to "
+ unmatchedText(value) + " but the value is ["
+ (valueInHeader != null ? valueInHeader.toString() : "null")
+ "]");
unmatchedHeaders.add("Header with name [" + name + "] was supposed to " + unmatchedText(value)
+ " but the value is [" + (valueInHeader != null ? valueInHeader.toString() : "null") + "]");
}
}
return unmatchedHeaders;

View File

@@ -65,8 +65,7 @@ class StubRunnerCamelProcessor implements Processor {
}
private Object outputBody(Contract groovyDsl) {
Object outputBody = BodyExtractor
.extractClientValueFromBody(groovyDsl.getOutputMessage().getBody());
Object outputBody = BodyExtractor.extractClientValueFromBody(groovyDsl.getOutputMessage().getBody());
if (outputBody instanceof FromFileProperty) {
FromFileProperty property = (FromFileProperty) outputBody;
return property.asBytes();
@@ -74,15 +73,13 @@ class StubRunnerCamelProcessor implements Processor {
return BodyExtractor.extractStubValueFrom(outputBody);
}
private void setStubRunnerDestinationHeader(Exchange exchange,
StubRunnerCamelPayload body) {
private void setStubRunnerDestinationHeader(Exchange exchange, StubRunnerCamelPayload body) {
boolean outputPart = body.contract.getOutputMessage() != null;
String url = DUMMY_BEAN_URL;
if (outputPart && body.contract.getOutputMessage().getSentTo() != null) {
url = body.contract.getOutputMessage().getSentTo().getClientValue();
}
exchange.getIn().setHeader(
StubRunnerCamelConfiguration.STUBRUNNER_DESTINATION_URL_HEADER_NAME, url);
exchange.getIn().setHeader(StubRunnerCamelConfiguration.STUBRUNNER_DESTINATION_URL_HEADER_NAME, url);
if (log.isDebugEnabled()) {
log.debug("Set stub runner destination header to [" + url + "]");
}

View File

@@ -48,23 +48,17 @@ import org.springframework.util.StringUtils;
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(IntegrationFlowBuilder.class)
@ConditionalOnProperty(name = "stubrunner.integration.enabled", havingValue = "true",
matchIfMissing = true)
@ConditionalOnProperty(name = "stubrunner.integration.enabled", havingValue = "true", matchIfMissing = true)
public class StubRunnerIntegrationConfiguration {
@Bean
@ConditionalOnMissingBean(name = "stubFlowRegistrar")
public FlowRegistrar stubFlowRegistrar(AutowireCapableBeanFactory beanFactory,
BatchStubRunner batchStubRunner) {
Map<StubConfiguration, Collection<Contract>> contracts = batchStubRunner
.getContracts();
IntegrationFlowBuilder dummyBuilder = IntegrationFlows
.from(DummyMessageHandler.CHANNEL_NAME)
public FlowRegistrar stubFlowRegistrar(AutowireCapableBeanFactory beanFactory, BatchStubRunner batchStubRunner) {
Map<StubConfiguration, Collection<Contract>> contracts = batchStubRunner.getContracts();
IntegrationFlowBuilder dummyBuilder = IntegrationFlows.from(DummyMessageHandler.CHANNEL_NAME)
.handle(new DummyMessageHandler(), "handle");
beanFactory.initializeBean(dummyBuilder.get(),
DummyMessageHandler.CHANNEL_NAME + ".flow");
for (Entry<StubConfiguration, Collection<Contract>> entry : contracts
.entrySet()) {
beanFactory.initializeBean(dummyBuilder.get(), DummyMessageHandler.CHANNEL_NAME + ".flow");
for (Entry<StubConfiguration, Collection<Contract>> entry : contracts.entrySet()) {
StubConfiguration key = entry.getKey();
Collection<Contract> value = entry.getValue();
String name = key.getGroupId() + "_" + key.getArtifactId();
@@ -74,29 +68,23 @@ public class StubRunnerIntegrationConfiguration {
continue;
}
if (dsl.getInput() != null && dsl.getInput().getMessageFrom() != null
&& StringUtils.hasText(
dsl.getInput().getMessageFrom().getClientValue())) {
&& StringUtils.hasText(dsl.getInput().getMessageFrom().getClientValue())) {
String from = dsl.getInput().getMessageFrom().getClientValue();
map.add(from, dsl);
}
}
for (Entry<String, List<Contract>> entries : map.entrySet()) {
final String flowName = name + "_" + entries.getKey() + "_"
+ entries.getValue().hashCode();
IntegrationFlowBuilder builder = IntegrationFlows
.from(entries.getKey()).filter(
new StubRunnerIntegrationMessageSelector(
entries.getValue()),
final String flowName = name + "_" + entries.getKey() + "_" + entries.getValue().hashCode();
IntegrationFlowBuilder builder = IntegrationFlows.from(entries.getKey())
.filter(new StubRunnerIntegrationMessageSelector(entries.getValue()),
new Consumer<FilterEndpointSpec>() {
@Override
public void accept(FilterEndpointSpec e) {
e.id(flowName + ".filter");
}
})
.transform(
new StubRunnerIntegrationTransformer(entries.getValue()))
.route(new StubRunnerIntegrationRouter(entries.getValue(),
beanFactory));
.transform(new StubRunnerIntegrationTransformer(entries.getValue()))
.route(new StubRunnerIntegrationRouter(entries.getValue(), beanFactory));
beanFactory.initializeBean(builder.get(), flowName);
beanFactory.getBean(flowName + ".filter", Lifecycle.class).start();
}

View File

@@ -55,11 +55,9 @@ import org.springframework.messaging.Message;
*/
class StubRunnerIntegrationMessageSelector implements MessageSelector {
private static final Map<Message, Contract> CACHE = Collections
.synchronizedMap(new WeakHashMap<>());
private static final Map<Message, Contract> CACHE = Collections.synchronizedMap(new WeakHashMap<>());
private static final Log log = LogFactory
.getLog(StubRunnerIntegrationMessageSelector.class);
private static final Log log = LogFactory.getLog(StubRunnerIntegrationMessageSelector.class);
private final List<Contract> groovyDsls;
@@ -107,14 +105,12 @@ class StubRunnerIntegrationMessageSelector implements MessageSelector {
List<String> unmatchedHeaders = headersMatch(message, groovyDsl);
if (!unmatchedHeaders.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Contract [" + groovyDsl
+ "] hasn't matched the following headers " + unmatchedHeaders);
log.debug("Contract [" + groovyDsl + "] hasn't matched the following headers " + unmatchedHeaders);
}
return null;
}
Object inputMessage = message.getPayload();
Object dslBody = MapConverter
.getStubSideValues(groovyDsl.getInput().getMessageBody());
Object dslBody = MapConverter.getStubSideValues(groovyDsl.getInput().getMessageBody());
if (dslBody instanceof FromFileProperty) {
if (log.isDebugEnabled()) {
log.debug("Will compare file content");
@@ -126,19 +122,15 @@ class StubRunnerIntegrationMessageSelector implements MessageSelector {
}
else if (!(inputMessage instanceof byte[])) {
if (log.isDebugEnabled()) {
log.debug(
"Contract provided byte comparison, but the input message is of type ["
+ inputMessage.getClass()
+ "]. Can't compare the two.");
log.debug("Contract provided byte comparison, but the input message is of type ["
+ inputMessage.getClass() + "]. Can't compare the two.");
}
return null;
}
else {
boolean matches = Arrays.equals(property.asBytes(),
(byte[]) inputMessage);
boolean matches = Arrays.equals(property.asBytes(), (byte[]) inputMessage);
if (log.isDebugEnabled() && !matches) {
log.debug(
"Contract provided byte comparison, but the byte arrays don't match");
log.debug("Contract provided byte comparison, but the byte arrays don't match");
}
return matches ? groovyDsl : null;
}
@@ -149,11 +141,9 @@ class StubRunnerIntegrationMessageSelector implements MessageSelector {
return null;
}
private boolean matchViaContent(Contract groovyDsl, Object inputMessage,
Object dslBody) {
private boolean matchViaContent(Contract groovyDsl, Object inputMessage, Object dslBody) {
boolean matches;
ContentType type = ContentUtils.getClientContentType(inputMessage,
groovyDsl.getInput().getMessageHeaders());
ContentType type = ContentUtils.getClientContentType(inputMessage, groovyDsl.getInput().getMessageHeaders());
if (type == ContentType.JSON) {
BodyMatchers matchers = groovyDsl.getInput().getBodyMatchers();
matches = matchesForJsonPayload(groovyDsl, inputMessage, matchers, dslBody);
@@ -172,22 +162,19 @@ class StubRunnerIntegrationMessageSelector implements MessageSelector {
private void bodyUnmatchedLog(Object dslBody, boolean matches, Object pattern) {
if (log.isDebugEnabled() && !matches) {
log.debug("Body was supposed to " + unmatchedText(pattern)
+ " but the value is [" + dslBody.toString() + "]");
log.debug("Body was supposed to " + unmatchedText(pattern) + " but the value is [" + dslBody.toString()
+ "]");
}
}
private boolean matchesForJsonPayload(Contract groovyDsl, Object inputMessage,
BodyMatchers matchers, Object dslBody) {
Object matchingInputMessage = JsonToJsonPathsConverter
.removeMatchingJsonPaths(dslBody, matchers);
private boolean matchesForJsonPayload(Contract groovyDsl, Object inputMessage, BodyMatchers matchers,
Object dslBody) {
Object matchingInputMessage = JsonToJsonPathsConverter.removeMatchingJsonPaths(dslBody, matchers);
JsonPaths jsonPaths = JsonToJsonPathsConverter
.transformToJsonPathWithStubsSideValuesAndNoArraySizeCheck(
matchingInputMessage);
.transformToJsonPathWithStubsSideValuesAndNoArraySizeCheck(matchingInputMessage);
DocumentContext parsedJson;
try {
parsedJson = JsonPath
.parse(this.objectMapper.writeValueAsString(inputMessage));
parsedJson = JsonPath.parse(this.objectMapper.writeValueAsString(inputMessage));
}
catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot serialize to JSON", e);
@@ -199,22 +186,19 @@ class StubRunnerIntegrationMessageSelector implements MessageSelector {
}
if (matchers != null && matchers.hasMatchers()) {
for (BodyMatcher matcher : matchers.matchers()) {
String jsonPath = JsonToJsonPathsConverter
.convertJsonPathAndRegexToAJsonPath(matcher, dslBody);
String jsonPath = JsonToJsonPathsConverter.convertJsonPathAndRegexToAJsonPath(matcher, dslBody);
matches &= matchesJsonPath(unmatchedJsonPath, parsedJson, jsonPath);
}
}
if (!unmatchedJsonPath.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Contract [" + groovyDsl + "] didn't match the body due to "
+ unmatchedJsonPath);
log.debug("Contract [" + groovyDsl + "] didn't match the body due to " + unmatchedJsonPath);
}
}
return matches;
}
private boolean matchesJsonPath(List<String> unmatchedJsonPath,
DocumentContext parsedJson, String jsonPath) {
private boolean matchesJsonPath(List<String> unmatchedJsonPath, DocumentContext parsedJson, String jsonPath) {
try {
JsonAssertion.assertThat(parsedJson).matchesJsonPath(jsonPath);
return true;
@@ -238,14 +222,11 @@ class StubRunnerIntegrationMessageSelector implements MessageSelector {
matches = pattern.matcher(valueInHeader.toString()).matches();
}
else {
matches = valueInHeader != null
&& valueInHeader.toString().equals(value.toString());
matches = valueInHeader != null && valueInHeader.toString().equals(value.toString());
}
if (!matches) {
unmatchedHeaders.add("Header with name [" + name + "] was supposed to "
+ unmatchedText(value) + " but the value is ["
+ (valueInHeader != null ? valueInHeader.toString() : "null")
+ "]");
unmatchedHeaders.add("Header with name [" + name + "] was supposed to " + unmatchedText(value)
+ " but the value is [" + (valueInHeader != null ? valueInHeader.toString() : "null") + "]");
}
}
return unmatchedHeaders;

View File

@@ -43,14 +43,12 @@ class StubRunnerIntegrationRouter extends AbstractMessageRouter {
@Override
protected Collection<MessageChannel> determineTargetChannels(Message<?> message) {
Contract dsl = this.selector.matchingContract(message);
if (dsl != null && dsl.getOutputMessage() != null
&& dsl.getOutputMessage().getSentTo() != null) {
if (dsl != null && dsl.getOutputMessage() != null && dsl.getOutputMessage().getSentTo() != null) {
String channelName = dsl.getOutputMessage().getSentTo().getClientValue();
return Collections
.singleton((MessageChannel) this.beanFactory.getBean(channelName));
return Collections.singleton((MessageChannel) this.beanFactory.getBean(channelName));
}
return Collections.singleton((MessageChannel) this.beanFactory.getBean(
StubRunnerIntegrationConfiguration.DummyMessageHandler.CHANNEL_NAME));
return Collections.singleton((MessageChannel) this.beanFactory
.getBean(StubRunnerIntegrationConfiguration.DummyMessageHandler.CHANNEL_NAME));
}
}

View File

@@ -50,18 +50,15 @@ class StubRunnerIntegrationTransformer {
return source;
}
Object outputBody = outputBody(groovyDsl);
Map<String, Object> headers = groovyDsl.getOutputMessage().getHeaders()
.asStubSideMap();
Map<String, Object> headers = groovyDsl.getOutputMessage().getHeaders().asStubSideMap();
MessageHeaders messageHeaders = new MessageHeaders(headers);
Message<Object> message = MessageBuilder.createMessage(outputBody,
messageHeaders);
Message<Object> message = MessageBuilder.createMessage(outputBody, messageHeaders);
this.selector.updateCache(message, groovyDsl);
return message;
}
private Object outputBody(Contract groovyDsl) {
Object outputBody = BodyExtractor
.extractClientValueFromBody(groovyDsl.getOutputMessage().getBody());
Object outputBody = BodyExtractor.extractClientValueFromBody(groovyDsl.getOutputMessage().getBody());
if (outputBody instanceof FromFileProperty) {
FromFileProperty property = (FromFileProperty) outputBody;
return property.asBytes();

View File

@@ -49,18 +49,15 @@ import org.springframework.util.StringUtils;
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(JmsTemplate.class)
@ConditionalOnProperty(name = "stubrunner.jms.enabled", havingValue = "true",
matchIfMissing = true)
@ConditionalOnProperty(name = "stubrunner.jms.enabled", havingValue = "true", matchIfMissing = true)
public class StubRunnerJmsConfiguration {
@Bean
@ConditionalOnMissingBean(name = "stubFlowRegistrar")
public FlowRegistrar stubFlowRegistrar(ConfigurableListableBeanFactory beanFactory,
BatchStubRunner batchStubRunner) {
Map<StubConfiguration, Collection<Contract>> contracts = batchStubRunner
.getContracts();
for (Entry<StubConfiguration, Collection<Contract>> entry : contracts
.entrySet()) {
Map<StubConfiguration, Collection<Contract>> contracts = batchStubRunner.getContracts();
for (Entry<StubConfiguration, Collection<Contract>> entry : contracts.entrySet()) {
StubConfiguration key = entry.getKey();
Collection<Contract> value = entry.getValue();
String name = key.getGroupId() + "_" + key.getArtifactId();
@@ -70,21 +67,17 @@ public class StubRunnerJmsConfiguration {
continue;
}
if (dsl.getInput() != null && dsl.getInput().getMessageFrom() != null
&& StringUtils.hasText(
dsl.getInput().getMessageFrom().getClientValue())) {
&& StringUtils.hasText(dsl.getInput().getMessageFrom().getClientValue())) {
String from = dsl.getInput().getMessageFrom().getClientValue();
map.add(from, dsl);
}
}
for (Entry<String, List<Contract>> entries : map.entrySet()) {
List<Contract> matchingContracts = entries.getValue();
final String flowName = name + "_" + entries.getKey() + "_"
+ Math.abs(matchingContracts.hashCode());
final String flowName = name + "_" + entries.getKey() + "_" + Math.abs(matchingContracts.hashCode());
// listener
StubRunnerJmsRouter router = new StubRunnerJmsRouter(matchingContracts,
beanFactory);
StubRunnerJmsRouter listener = (StubRunnerJmsRouter) beanFactory
.initializeBean(router, flowName);
StubRunnerJmsRouter router = new StubRunnerJmsRouter(matchingContracts, beanFactory);
StubRunnerJmsRouter listener = (StubRunnerJmsRouter) beanFactory.initializeBean(router, flowName);
beanFactory.registerSingleton(flowName, listener);
registerContainers(beanFactory, matchingContracts, flowName, listener);
}
@@ -93,29 +86,25 @@ public class StubRunnerJmsConfiguration {
return new FlowRegistrar();
}
private void registerContainers(ConfigurableListableBeanFactory beanFactory,
List<Contract> matchingContracts, String flowName,
StubRunnerJmsRouter listener) {
private void registerContainers(ConfigurableListableBeanFactory beanFactory, List<Contract> matchingContracts,
String flowName, StubRunnerJmsRouter listener) {
// listener's container
ConnectionFactory connectionFactory = beanFactory
.getBean(ConnectionFactory.class);
ConnectionFactory connectionFactory = beanFactory.getBean(ConnectionFactory.class);
for (Contract matchingContract : matchingContracts) {
if (matchingContract.getInput() == null) {
continue;
}
String destination = MapConverter.getStubSideValuesForNonBody(
matchingContract.getInput().getMessageFrom()).toString();
MessageListenerContainer container = listenerContainer(destination,
connectionFactory, listener);
String destination = MapConverter.getStubSideValuesForNonBody(matchingContract.getInput().getMessageFrom())
.toString();
MessageListenerContainer container = listenerContainer(destination, connectionFactory, listener);
String containerName = flowName + ".container";
Object initializedContainer = beanFactory.initializeBean(container,
containerName);
Object initializedContainer = beanFactory.initializeBean(container, containerName);
beanFactory.registerSingleton(containerName, initializedContainer);
}
}
private MessageListenerContainer listenerContainer(String queueName,
ConnectionFactory connectionFactory, MessageListener listener) {
private MessageListenerContainer listenerContainer(String queueName, ConnectionFactory connectionFactory,
MessageListener listener) {
DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setDestinationName(queueName);

View File

@@ -55,8 +55,7 @@ import org.springframework.cloud.contract.verifier.util.MethodBufferingJsonVerif
*/
class StubRunnerJmsMessageSelector {
private static final Map<Message, Contract> CACHE = Collections
.synchronizedMap(new WeakHashMap<>());
private static final Map<Message, Contract> CACHE = Collections.synchronizedMap(new WeakHashMap<>());
private static final Log log = LogFactory.getLog(StubRunnerJmsMessageSelector.class);
@@ -97,14 +96,12 @@ class StubRunnerJmsMessageSelector {
List<String> unmatchedHeaders = headersMatch(message, groovyDsl);
if (!unmatchedHeaders.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Contract [" + groovyDsl
+ "] hasn't matched the following headers " + unmatchedHeaders);
log.debug("Contract [" + groovyDsl + "] hasn't matched the following headers " + unmatchedHeaders);
}
return null;
}
Object inputMessage = StubRunnerJmsAccessor.getBody(message);
Object dslBody = MapConverter
.getStubSideValues(groovyDsl.getInput().getMessageBody());
Object dslBody = MapConverter.getStubSideValues(groovyDsl.getInput().getMessageBody());
if (dslBody instanceof FromFileProperty) {
if (log.isDebugEnabled()) {
log.debug("Will compare file content");
@@ -116,19 +113,15 @@ class StubRunnerJmsMessageSelector {
}
else if (!(inputMessage instanceof byte[])) {
if (log.isDebugEnabled()) {
log.debug(
"Contract provided byte comparison, but the input message is of type ["
+ inputMessage.getClass()
+ "]. Can't compare the two.");
log.debug("Contract provided byte comparison, but the input message is of type ["
+ inputMessage.getClass() + "]. Can't compare the two.");
}
return null;
}
else {
boolean matches = Arrays.equals(property.asBytes(),
(byte[]) inputMessage);
boolean matches = Arrays.equals(property.asBytes(), (byte[]) inputMessage);
if (log.isDebugEnabled() && !matches) {
log.debug(
"Contract provided byte comparison, but the byte arrays don't match");
log.debug("Contract provided byte comparison, but the byte arrays don't match");
}
return matches ? groovyDsl : null;
}
@@ -139,11 +132,9 @@ class StubRunnerJmsMessageSelector {
return null;
}
private boolean matchViaContent(Contract groovyDsl, Object inputMessage,
Object dslBody) {
private boolean matchViaContent(Contract groovyDsl, Object inputMessage, Object dslBody) {
boolean matches;
ContentType type = ContentUtils.getClientContentType(inputMessage,
groovyDsl.getInput().getMessageHeaders());
ContentType type = ContentUtils.getClientContentType(inputMessage, groovyDsl.getInput().getMessageHeaders());
if (type == ContentType.JSON) {
BodyMatchers matchers = groovyDsl.getInput().getBodyMatchers();
matches = matchesForJsonPayload(groovyDsl, inputMessage, matchers, dslBody);
@@ -162,22 +153,19 @@ class StubRunnerJmsMessageSelector {
private void bodyUnmatchedLog(Object dslBody, boolean matches, Object pattern) {
if (log.isDebugEnabled() && !matches) {
log.debug("Body was supposed to " + unmatchedText(pattern)
+ " but the value is [" + dslBody.toString() + "]");
log.debug("Body was supposed to " + unmatchedText(pattern) + " but the value is [" + dslBody.toString()
+ "]");
}
}
private boolean matchesForJsonPayload(Contract groovyDsl, Object inputMessage,
BodyMatchers matchers, Object dslBody) {
Object matchingInputMessage = JsonToJsonPathsConverter
.removeMatchingJsonPaths(dslBody, matchers);
private boolean matchesForJsonPayload(Contract groovyDsl, Object inputMessage, BodyMatchers matchers,
Object dslBody) {
Object matchingInputMessage = JsonToJsonPathsConverter.removeMatchingJsonPaths(dslBody, matchers);
JsonPaths jsonPaths = JsonToJsonPathsConverter
.transformToJsonPathWithStubsSideValuesAndNoArraySizeCheck(
matchingInputMessage);
.transformToJsonPathWithStubsSideValuesAndNoArraySizeCheck(matchingInputMessage);
DocumentContext parsedJson;
try {
parsedJson = JsonPath
.parse(this.objectMapper.writeValueAsString(inputMessage));
parsedJson = JsonPath.parse(this.objectMapper.writeValueAsString(inputMessage));
}
catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot serialize to JSON", e);
@@ -189,22 +177,19 @@ class StubRunnerJmsMessageSelector {
}
if (matchers != null && matchers.hasMatchers()) {
for (BodyMatcher matcher : matchers.matchers()) {
String jsonPath = JsonToJsonPathsConverter
.convertJsonPathAndRegexToAJsonPath(matcher, dslBody);
String jsonPath = JsonToJsonPathsConverter.convertJsonPathAndRegexToAJsonPath(matcher, dslBody);
matches &= matchesJsonPath(unmatchedJsonPath, parsedJson, jsonPath);
}
}
if (!unmatchedJsonPath.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Contract [" + groovyDsl + "] didn't match the body due to "
+ unmatchedJsonPath);
log.debug("Contract [" + groovyDsl + "] didn't match the body due to " + unmatchedJsonPath);
}
}
return matches;
}
private boolean matchesJsonPath(List<String> unmatchedJsonPath,
DocumentContext parsedJson, String jsonPath) {
private boolean matchesJsonPath(List<String> unmatchedJsonPath, DocumentContext parsedJson, String jsonPath) {
try {
JsonAssertion.assertThat(parsedJson).matchesJsonPath(jsonPath);
return true;
@@ -228,14 +213,11 @@ class StubRunnerJmsMessageSelector {
matches = pattern.matcher(valueInHeader.toString()).matches();
}
else {
matches = valueInHeader != null
&& valueInHeader.toString().equals(value.toString());
matches = valueInHeader != null && valueInHeader.toString().equals(value.toString());
}
if (!matches) {
unmatchedHeaders.add("Header with name [" + name + "] was supposed to "
+ unmatchedText(value) + " but the value is ["
+ (valueInHeader != null ? valueInHeader.toString() : "null")
+ "]");
unmatchedHeaders.add("Header with name [" + name + "] was supposed to " + unmatchedText(value)
+ " but the value is [" + (valueInHeader != null ? valueInHeader.toString() : "null") + "]");
}
}
return unmatchedHeaders;

View File

@@ -49,12 +49,10 @@ class StubRunnerJmsRouter implements MessageListener {
@Override
public void onMessage(javax.jms.Message message) {
Contract dsl = this.selector.matchingContract(message);
if (dsl != null && dsl.getOutputMessage() != null
&& dsl.getOutputMessage().getSentTo() != null) {
if (dsl != null && dsl.getOutputMessage() != null && dsl.getOutputMessage().getSentTo() != null) {
String destination = dsl.getOutputMessage().getSentTo().getClientValue();
jmsTemplate().send(destination,
session -> new StubRunnerJmsTransformer(this.contracts)
.transform(session, dsl));
session -> new StubRunnerJmsTransformer(this.contracts).transform(session, dsl));
}
}

View File

@@ -44,8 +44,7 @@ class StubRunnerJmsTransformer {
public Message transform(Session session, Contract groovyDsl) {
Object outputBody = outputBody(groovyDsl);
Map<String, Object> headers = groovyDsl.getOutputMessage().getHeaders()
.asStubSideMap();
Map<String, Object> headers = groovyDsl.getOutputMessage().getHeaders().asStubSideMap();
Message newMessage = createMessage(session, outputBody);
setHeaders(newMessage, headers);
this.selector.updateCache(newMessage, groovyDsl);
@@ -53,8 +52,7 @@ class StubRunnerJmsTransformer {
}
private Object outputBody(Contract groovyDsl) {
Object outputBody = BodyExtractor
.extractClientValueFromBody(groovyDsl.getOutputMessage().getBody());
Object outputBody = BodyExtractor.extractClientValueFromBody(groovyDsl.getOutputMessage().getBody());
if (outputBody instanceof FromFileProperty) {
FromFileProperty property = (FromFileProperty) outputBody;
return property.asBytes();

View File

@@ -57,8 +57,7 @@ import org.springframework.util.StringUtils;
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ KafkaTemplate.class, EmbeddedKafkaBroker.class })
@ConditionalOnProperty(name = "stubrunner.kafka.enabled", havingValue = "true",
matchIfMissing = true)
@ConditionalOnProperty(name = "stubrunner.kafka.enabled", havingValue = "true", matchIfMissing = true)
@ConditionalOnBean(EmbeddedKafkaBroker.class)
@AutoConfigureBefore(ContractVerifierKafkaConfiguration.class)
public class StubRunnerKafkaConfiguration {
@@ -67,8 +66,7 @@ public class StubRunnerKafkaConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(name = "stubrunner.kafka.initializer.enabled",
havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(name = "stubrunner.kafka.initializer.enabled", havingValue = "true", matchIfMissing = true)
KafkaStubMessagesInitializer stubRunnerKafkaStubMessagesInitializer() {
if (log.isDebugEnabled()) {
log.debug("Registering a noop kafka messages initializer");
@@ -80,10 +78,8 @@ public class StubRunnerKafkaConfiguration {
@ConditionalOnMissingBean(name = "stubFlowRegistrar")
public FlowRegistrar stubFlowRegistrar(ConfigurableListableBeanFactory beanFactory,
BatchStubRunner batchStubRunner) {
Map<StubConfiguration, Collection<Contract>> contracts = batchStubRunner
.getContracts();
for (Entry<StubConfiguration, Collection<Contract>> entry : contracts
.entrySet()) {
Map<StubConfiguration, Collection<Contract>> contracts = batchStubRunner.getContracts();
for (Entry<StubConfiguration, Collection<Contract>> entry : contracts.entrySet()) {
StubConfiguration key = entry.getKey();
Collection<Contract> value = entry.getValue();
String name = key.getGroupId() + "_" + key.getArtifactId();
@@ -93,21 +89,17 @@ public class StubRunnerKafkaConfiguration {
continue;
}
if (dsl.getInput() != null && dsl.getInput().getMessageFrom() != null
&& StringUtils.hasText(
dsl.getInput().getMessageFrom().getClientValue())) {
&& StringUtils.hasText(dsl.getInput().getMessageFrom().getClientValue())) {
String from = dsl.getInput().getMessageFrom().getClientValue();
map.add(from, dsl);
}
}
for (Entry<String, List<Contract>> entries : map.entrySet()) {
List<Contract> matchingContracts = entries.getValue();
final String flowName = name + "_" + entries.getKey() + "_"
+ Math.abs(matchingContracts.hashCode());
final String flowName = name + "_" + entries.getKey() + "_" + Math.abs(matchingContracts.hashCode());
// listener
StubRunnerKafkaRouter router = new StubRunnerKafkaRouter(
matchingContracts, beanFactory);
StubRunnerKafkaRouter listener = (StubRunnerKafkaRouter) beanFactory
.initializeBean(router, flowName);
StubRunnerKafkaRouter router = new StubRunnerKafkaRouter(matchingContracts, beanFactory);
StubRunnerKafkaRouter listener = (StubRunnerKafkaRouter) beanFactory.initializeBean(router, flowName);
if (log.isDebugEnabled()) {
log.debug("Initialized kafka router with name [" + flowName + "]");
}
@@ -119,38 +111,32 @@ public class StubRunnerKafkaConfiguration {
return new FlowRegistrar();
}
private void registerContainers(ConfigurableListableBeanFactory beanFactory,
List<Contract> matchingContracts, String flowName,
StubRunnerKafkaRouter listener) {
private void registerContainers(ConfigurableListableBeanFactory beanFactory, List<Contract> matchingContracts,
String flowName, StubRunnerKafkaRouter listener) {
// listener's container
ConsumerFactory consumerFactory = beanFactory.getBean(ConsumerFactory.class);
for (Contract matchingContract : matchingContracts) {
if (matchingContract.getInput() == null) {
continue;
}
String destination = MapConverter.getStubSideValuesForNonBody(
matchingContract.getInput().getMessageFrom()).toString();
ContainerProperties containerProperties = new ContainerProperties(
destination);
KafkaMessageListenerContainer container = listenerContainer(consumerFactory,
containerProperties, listener);
String destination = MapConverter.getStubSideValuesForNonBody(matchingContract.getInput().getMessageFrom())
.toString();
ContainerProperties containerProperties = new ContainerProperties(destination);
KafkaMessageListenerContainer container = listenerContainer(consumerFactory, containerProperties, listener);
String containerName = flowName + ".container";
Object initializedContainer = beanFactory.initializeBean(container,
containerName);
Object initializedContainer = beanFactory.initializeBean(container, containerName);
beanFactory.registerSingleton(containerName, initializedContainer);
if (log.isDebugEnabled()) {
log.debug(
"Initialized kafka message container with name [" + containerName
+ "] listening to destination [" + destination + "]");
log.debug("Initialized kafka message container with name [" + containerName
+ "] listening to destination [" + destination + "]");
}
}
}
private KafkaMessageListenerContainer listenerContainer(
ConsumerFactory consumerFactory, ContainerProperties containerProperties,
GenericMessageListener listener) {
KafkaMessageListenerContainer container = new KafkaMessageListenerContainer(
consumerFactory, containerProperties);
private KafkaMessageListenerContainer listenerContainer(ConsumerFactory consumerFactory,
ContainerProperties containerProperties, GenericMessageListener listener) {
KafkaMessageListenerContainer container = new KafkaMessageListenerContainer(consumerFactory,
containerProperties);
container.setupMessageListener(listener);
return container;
}

View File

@@ -53,11 +53,9 @@ import org.springframework.messaging.Message;
*/
class StubRunnerKafkaMessageSelector {
private static final Map<Message<?>, Contract> CACHE = Collections
.synchronizedMap(new WeakHashMap<>());
private static final Map<Message<?>, Contract> CACHE = Collections.synchronizedMap(new WeakHashMap<>());
private static final Log log = LogFactory
.getLog(StubRunnerKafkaMessageSelector.class);
private static final Log log = LogFactory.getLog(StubRunnerKafkaMessageSelector.class);
private final List<Contract> groovyDsls;
@@ -96,14 +94,12 @@ class StubRunnerKafkaMessageSelector {
List<String> unmatchedHeaders = headersMatch(message, groovyDsl);
if (!unmatchedHeaders.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Contract [" + groovyDsl
+ "] hasn't matched the following headers " + unmatchedHeaders);
log.debug("Contract [" + groovyDsl + "] hasn't matched the following headers " + unmatchedHeaders);
}
return null;
}
Object inputMessage = message.getPayload();
Object dslBody = MapConverter
.getStubSideValues(groovyDsl.getInput().getMessageBody());
Object dslBody = MapConverter.getStubSideValues(groovyDsl.getInput().getMessageBody());
if (dslBody instanceof FromFileProperty) {
if (log.isDebugEnabled()) {
log.debug("Will compare file content");
@@ -115,19 +111,15 @@ class StubRunnerKafkaMessageSelector {
}
else if (!(inputMessage instanceof byte[])) {
if (log.isDebugEnabled()) {
log.debug(
"Contract provided byte comparison, but the input message is of type ["
+ inputMessage.getClass()
+ "]. Can't compare the two.");
log.debug("Contract provided byte comparison, but the input message is of type ["
+ inputMessage.getClass() + "]. Can't compare the two.");
}
return null;
}
else {
boolean matches = Arrays.equals(property.asBytes(),
(byte[]) inputMessage);
boolean matches = Arrays.equals(property.asBytes(), (byte[]) inputMessage);
if (log.isDebugEnabled() && !matches) {
log.debug(
"Contract provided byte comparison, but the byte arrays don't match");
log.debug("Contract provided byte comparison, but the byte arrays don't match");
}
return matches ? groovyDsl : null;
}
@@ -138,11 +130,9 @@ class StubRunnerKafkaMessageSelector {
return null;
}
private boolean matchViaContent(Contract groovyDsl, Object inputMessage,
Object dslBody) {
private boolean matchViaContent(Contract groovyDsl, Object inputMessage, Object dslBody) {
boolean matches;
ContentType type = ContentUtils.getClientContentType(inputMessage,
groovyDsl.getInput().getMessageHeaders());
ContentType type = ContentUtils.getClientContentType(inputMessage, groovyDsl.getInput().getMessageHeaders());
if (type == ContentType.JSON) {
BodyMatchers matchers = groovyDsl.getInput().getBodyMatchers();
matches = matchesForJsonPayload(groovyDsl, inputMessage, matchers, dslBody);
@@ -161,22 +151,19 @@ class StubRunnerKafkaMessageSelector {
private void bodyUnmatchedLog(Object dslBody, boolean matches, Object pattern) {
if (log.isDebugEnabled() && !matches) {
log.debug("Body was supposed to " + unmatchedText(pattern)
+ " but the value is [" + dslBody.toString() + "]");
log.debug("Body was supposed to " + unmatchedText(pattern) + " but the value is [" + dslBody.toString()
+ "]");
}
}
private boolean matchesForJsonPayload(Contract groovyDsl, Object inputMessage,
BodyMatchers matchers, Object dslBody) {
Object matchingInputMessage = JsonToJsonPathsConverter
.removeMatchingJsonPaths(dslBody, matchers);
private boolean matchesForJsonPayload(Contract groovyDsl, Object inputMessage, BodyMatchers matchers,
Object dslBody) {
Object matchingInputMessage = JsonToJsonPathsConverter.removeMatchingJsonPaths(dslBody, matchers);
JsonPaths jsonPaths = JsonToJsonPathsConverter
.transformToJsonPathWithStubsSideValuesAndNoArraySizeCheck(
matchingInputMessage);
.transformToJsonPathWithStubsSideValuesAndNoArraySizeCheck(matchingInputMessage);
DocumentContext parsedJson;
try {
parsedJson = JsonPath
.parse(this.objectMapper.writeValueAsString(inputMessage));
parsedJson = JsonPath.parse(this.objectMapper.writeValueAsString(inputMessage));
}
catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot serialize to JSON", e);
@@ -188,22 +175,19 @@ class StubRunnerKafkaMessageSelector {
}
if (matchers != null && matchers.hasMatchers()) {
for (BodyMatcher matcher : matchers.matchers()) {
String jsonPath = JsonToJsonPathsConverter
.convertJsonPathAndRegexToAJsonPath(matcher, dslBody);
String jsonPath = JsonToJsonPathsConverter.convertJsonPathAndRegexToAJsonPath(matcher, dslBody);
matches &= matchesJsonPath(unmatchedJsonPath, parsedJson, jsonPath);
}
}
if (!unmatchedJsonPath.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Contract [" + groovyDsl + "] didn't match the body due to "
+ unmatchedJsonPath);
log.debug("Contract [" + groovyDsl + "] didn't match the body due to " + unmatchedJsonPath);
}
}
return matches;
}
private boolean matchesJsonPath(List<String> unmatchedJsonPath,
DocumentContext parsedJson, String jsonPath) {
private boolean matchesJsonPath(List<String> unmatchedJsonPath, DocumentContext parsedJson, String jsonPath) {
try {
JsonAssertion.assertThat(parsedJson).matchesJsonPath(jsonPath);
return true;
@@ -221,22 +205,18 @@ class StubRunnerKafkaMessageSelector {
String name = it.getName();
Object value = it.getClientValue();
Object valueInHeader = headers.get(name);
valueInHeader = valueInHeader instanceof byte[]
? fromByte((byte[]) valueInHeader) : valueInHeader;
valueInHeader = valueInHeader instanceof byte[] ? fromByte((byte[]) valueInHeader) : valueInHeader;
boolean matches;
if (value instanceof RegexProperty) {
Pattern pattern = ((RegexProperty) value).getPattern();
matches = pattern.matcher(valueInHeader.toString()).matches();
}
else {
matches = valueInHeader != null
&& valueInHeader.toString().equals(value.toString());
matches = valueInHeader != null && valueInHeader.toString().equals(value.toString());
}
if (!matches) {
unmatchedHeaders.add("Header with name [" + name + "] was supposed to "
+ unmatchedText(value) + " but the value is ["
+ (valueInHeader != null ? valueInHeader.toString() : "null")
+ "]");
unmatchedHeaders.add("Header with name [" + name + "] was supposed to " + unmatchedText(value)
+ " but the value is [" + (valueInHeader != null ? valueInHeader.toString() : "null") + "]");
}
}
return unmatchedHeaders;

View File

@@ -69,19 +69,15 @@ class StubRunnerKafkaRouter implements MessageListener<Object, Object> {
if (log.isDebugEnabled()) {
log.debug("Received message [" + data + "]");
}
Message<?> message = MessageBuilder.createMessage(data.value(),
headers(data.headers()));
Message<?> message = MessageBuilder.createMessage(data.value(), headers(data.headers()));
Contract dsl = this.selector.matchingContract(message);
if (dsl != null && dsl.getOutputMessage() != null
&& dsl.getOutputMessage().getSentTo() != null) {
if (dsl != null && dsl.getOutputMessage() != null && dsl.getOutputMessage().getSentTo() != null) {
String destination = dsl.getOutputMessage().getSentTo().getClientValue();
if (log.isDebugEnabled()) {
log.debug(
"Found a matching contract with an output message. Will send it to the ["
+ destination + "] destination");
log.debug("Found a matching contract with an output message. Will send it to the [" + destination
+ "] destination");
}
Message<?> transform = new StubRunnerKafkaTransformer(this.contracts)
.transform(dsl);
Message<?> transform = new StubRunnerKafkaTransformer(this.contracts).transform(dsl);
String defaultTopic = kafkaTemplate().getDefaultTopic();
try {
kafkaTemplate().setDefaultTopic(destination);
@@ -102,8 +98,7 @@ class StubRunnerKafkaRouter implements MessageListener<Object, Object> {
}
@Override
public void onMessage(ConsumerRecord<Object, Object> data,
Acknowledgment acknowledgment) {
public void onMessage(ConsumerRecord<Object, Object> data, Acknowledgment acknowledgment) {
onMessage(data);
}
@@ -113,8 +108,7 @@ class StubRunnerKafkaRouter implements MessageListener<Object, Object> {
}
@Override
public void onMessage(ConsumerRecord<Object, Object> data,
Acknowledgment acknowledgment, Consumer<?, ?> consumer) {
public void onMessage(ConsumerRecord<Object, Object> data, Acknowledgment acknowledgment, Consumer<?, ?> consumer) {
onMessage(data);
}

View File

@@ -41,17 +41,14 @@ class StubRunnerKafkaTransformer {
public Message<?> transform(Contract groovyDsl) {
Object outputBody = outputBody(groovyDsl);
Map<String, Object> headers = groovyDsl.getOutputMessage().getHeaders()
.asStubSideMap();
Message newMessage = MessageBuilder.createMessage(outputBody,
new MessageHeaders(headers));
Map<String, Object> headers = groovyDsl.getOutputMessage().getHeaders().asStubSideMap();
Message newMessage = MessageBuilder.createMessage(outputBody, new MessageHeaders(headers));
this.selector.updateCache(newMessage, groovyDsl);
return newMessage;
}
private Object outputBody(Contract groovyDsl) {
Object outputBody = BodyExtractor
.extractClientValueFromBody(groovyDsl.getOutputMessage().getBody());
Object outputBody = BodyExtractor.extractClientValueFromBody(groovyDsl.getOutputMessage().getBody());
if (outputBody instanceof FromFileProperty) {
FromFileProperty property = (FromFileProperty) outputBody;
return property.asBytes();

View File

@@ -43,16 +43,12 @@ class StubRunnerMessageRouter extends AbstractMessageRouter {
@Override
protected Collection<MessageChannel> determineTargetChannels(Message<?> message) {
Contract dsl = this.selector.matchingContract(message);
if (dsl != null && dsl.getOutputMessage() != null
&& dsl.getOutputMessage().getSentTo() != null) {
String channelName = StubRunnerStreamConfiguration.resolvedDestination(
this.beanFactory,
if (dsl != null && dsl.getOutputMessage() != null && dsl.getOutputMessage().getSentTo() != null) {
String channelName = StubRunnerStreamConfiguration.resolvedDestination(this.beanFactory,
dsl.getOutputMessage().getSentTo().getClientValue());
return Collections
.singleton((MessageChannel) this.beanFactory.getBean(channelName));
return Collections.singleton((MessageChannel) this.beanFactory.getBean(channelName));
}
return Collections
.singleton((MessageChannel) this.beanFactory.getBean("nullChannel"));
return Collections.singleton((MessageChannel) this.beanFactory.getBean("nullChannel"));
}
}

View File

@@ -57,8 +57,7 @@ import org.springframework.util.StringUtils;
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ IntegrationFlows.class, InputDestination.class })
@ConditionalOnProperty(name = "stubrunner.stream.enabled", havingValue = "true",
matchIfMissing = true)
@ConditionalOnProperty(name = "stubrunner.stream.enabled", havingValue = "true", matchIfMissing = true)
@AutoConfigureBefore(StubRunnerIntegrationConfiguration.class)
public class StubRunnerStreamConfiguration {
@@ -69,8 +68,7 @@ public class StubRunnerStreamConfiguration {
for (Map.Entry<String, BindingProperties> entry : bindings.entrySet()) {
if (destination.equals(entry.getValue().getDestination())) {
if (log.isDebugEnabled()) {
log.debug("Found a channel named [" + entry.getKey()
+ "] with destination [" + destination + "]");
log.debug("Found a channel named [" + entry.getKey() + "] with destination [" + destination + "]");
}
return entry.getKey();
}
@@ -89,12 +87,9 @@ public class StubRunnerStreamConfiguration {
@Bean
@ConditionalOnMissingBean(name = "stubFlowRegistrar")
@ConditionalOnBean(BindingServiceProperties.class)
public FlowRegistrar stubFlowRegistrar(AutowireCapableBeanFactory beanFactory,
BatchStubRunner batchStubRunner) {
Map<StubConfiguration, Collection<Contract>> contracts = batchStubRunner
.getContracts();
for (Entry<StubConfiguration, Collection<Contract>> entry : contracts
.entrySet()) {
public FlowRegistrar stubFlowRegistrar(AutowireCapableBeanFactory beanFactory, BatchStubRunner batchStubRunner) {
Map<StubConfiguration, Collection<Contract>> contracts = batchStubRunner.getContracts();
for (Entry<StubConfiguration, Collection<Contract>> entry : contracts.entrySet()) {
StubConfiguration key = entry.getKey();
Collection<Contract> value = entry.getValue();
String name = key.getGroupId() + "_" + key.getArtifactId();
@@ -104,16 +99,13 @@ public class StubRunnerStreamConfiguration {
continue;
}
if (dsl.getInput() != null && dsl.getInput().getMessageFrom() != null
&& StringUtils.hasText(
dsl.getInput().getMessageFrom().getClientValue())) {
String from = resolvedDestination(beanFactory,
dsl.getInput().getMessageFrom().getClientValue());
&& StringUtils.hasText(dsl.getInput().getMessageFrom().getClientValue())) {
String from = resolvedDestination(beanFactory, dsl.getInput().getMessageFrom().getClientValue());
map.add(from, dsl);
}
}
for (Entry<String, List<Contract>> entries : map.entrySet()) {
final String flowName = name + "_" + entries.getKey() + "_"
+ entries.getValue().hashCode();
final String flowName = name + "_" + entries.getKey() + "_" + entries.getValue().hashCode();
IntegrationFlowBuilder builder = IntegrationFlows.from(entries.getKey())
.filter(new StubRunnerStreamMessageSelector(entries.getValue()),
new Consumer<FilterEndpointSpec>() {
@@ -123,8 +115,7 @@ public class StubRunnerStreamConfiguration {
}
})
.transform(new StubRunnerStreamTransformer(entries.getValue()))
.route(new StubRunnerMessageRouter(entries.getValue(),
beanFactory));
.route(new StubRunnerMessageRouter(entries.getValue(), beanFactory));
beanFactory.initializeBean(builder.get(), flowName);
beanFactory.getBean(flowName + ".filter", Lifecycle.class).start();
}

View File

@@ -55,11 +55,9 @@ import org.springframework.messaging.Message;
*/
class StubRunnerStreamMessageSelector implements MessageSelector {
private static final Map<Message, Contract> CACHE = Collections
.synchronizedMap(new WeakHashMap<>());
private static final Map<Message, Contract> CACHE = Collections.synchronizedMap(new WeakHashMap<>());
private static final Log log = LogFactory
.getLog(StubRunnerStreamMessageSelector.class);
private static final Log log = LogFactory.getLog(StubRunnerStreamMessageSelector.class);
private final List<Contract> groovyDsls;
@@ -107,14 +105,12 @@ class StubRunnerStreamMessageSelector implements MessageSelector {
List<String> unmatchedHeaders = headersMatch(message, groovyDsl);
if (!unmatchedHeaders.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Contract [" + groovyDsl
+ "] hasn't matched the following headers " + unmatchedHeaders);
log.debug("Contract [" + groovyDsl + "] hasn't matched the following headers " + unmatchedHeaders);
}
return null;
}
Object inputMessage = message.getPayload();
Object dslBody = MapConverter
.getStubSideValues(groovyDsl.getInput().getMessageBody());
Object dslBody = MapConverter.getStubSideValues(groovyDsl.getInput().getMessageBody());
if (dslBody instanceof FromFileProperty) {
if (log.isDebugEnabled()) {
log.debug("Will compare file content");
@@ -126,19 +122,15 @@ class StubRunnerStreamMessageSelector implements MessageSelector {
}
else if (!(inputMessage instanceof byte[])) {
if (log.isDebugEnabled()) {
log.debug(
"Contract provided byte comparison, but the input message is of type ["
+ inputMessage.getClass()
+ "]. Can't compare the two.");
log.debug("Contract provided byte comparison, but the input message is of type ["
+ inputMessage.getClass() + "]. Can't compare the two.");
}
return null;
}
else {
boolean matches = Arrays.equals(property.asBytes(),
(byte[]) inputMessage);
boolean matches = Arrays.equals(property.asBytes(), (byte[]) inputMessage);
if (log.isDebugEnabled() && !matches) {
log.debug(
"Contract provided byte comparison, but the byte arrays don't match");
log.debug("Contract provided byte comparison, but the byte arrays don't match");
}
return matches ? groovyDsl : null;
}
@@ -149,17 +141,14 @@ class StubRunnerStreamMessageSelector implements MessageSelector {
return null;
}
private boolean matchViaContent(Contract groovyDsl, Object inputMessage,
Object dslBody) {
private boolean matchViaContent(Contract groovyDsl, Object inputMessage, Object dslBody) {
boolean matches;
ContentType type = ContentUtils.getClientContentType(inputMessage,
groovyDsl.getInput().getMessageHeaders());
ContentType type = ContentUtils.getClientContentType(inputMessage, groovyDsl.getInput().getMessageHeaders());
if (type == ContentType.JSON) {
BodyMatchers matchers = groovyDsl.getInput().getBodyMatchers();
matches = matchesForJsonPayload(groovyDsl, inputMessage, matchers, dslBody);
}
else if ((dslBody instanceof RegexProperty || dslBody instanceof Pattern)
&& inputMessage instanceof String) {
else if ((dslBody instanceof RegexProperty || dslBody instanceof Pattern) && inputMessage instanceof String) {
Pattern pattern = new RegexProperty(dslBody).getPattern();
matches = pattern.matcher((String) inputMessage).matches();
bodyUnmatchedLog(dslBody, matches, pattern);
@@ -173,22 +162,19 @@ class StubRunnerStreamMessageSelector implements MessageSelector {
private void bodyUnmatchedLog(Object dslBody, boolean matches, Object pattern) {
if (log.isDebugEnabled() && !matches) {
log.debug("Body was supposed to " + unmatchedText(pattern)
+ " but the value is [" + dslBody.toString() + "]");
log.debug("Body was supposed to " + unmatchedText(pattern) + " but the value is [" + dslBody.toString()
+ "]");
}
}
private boolean matchesForJsonPayload(Contract groovyDsl, Object inputMessage,
BodyMatchers matchers, Object dslBody) {
Object matchingInputMessage = JsonToJsonPathsConverter
.removeMatchingJsonPaths(dslBody, matchers);
private boolean matchesForJsonPayload(Contract groovyDsl, Object inputMessage, BodyMatchers matchers,
Object dslBody) {
Object matchingInputMessage = JsonToJsonPathsConverter.removeMatchingJsonPaths(dslBody, matchers);
JsonPaths jsonPaths = JsonToJsonPathsConverter
.transformToJsonPathWithStubsSideValuesAndNoArraySizeCheck(
matchingInputMessage);
.transformToJsonPathWithStubsSideValuesAndNoArraySizeCheck(matchingInputMessage);
DocumentContext parsedJson;
try {
parsedJson = JsonPath
.parse(this.objectMapper.writeValueAsString(inputMessage));
parsedJson = JsonPath.parse(this.objectMapper.writeValueAsString(inputMessage));
}
catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot serialize to JSON", e);
@@ -200,22 +186,19 @@ class StubRunnerStreamMessageSelector implements MessageSelector {
}
if (matchers != null && matchers.hasMatchers()) {
for (BodyMatcher matcher : matchers.matchers()) {
String jsonPath = JsonToJsonPathsConverter
.convertJsonPathAndRegexToAJsonPath(matcher, dslBody);
String jsonPath = JsonToJsonPathsConverter.convertJsonPathAndRegexToAJsonPath(matcher, dslBody);
matches &= matchesJsonPath(unmatchedJsonPath, parsedJson, jsonPath);
}
}
if (!unmatchedJsonPath.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Contract [" + groovyDsl + "] didn't match the body due to "
+ unmatchedJsonPath);
log.debug("Contract [" + groovyDsl + "] didn't match the body due to " + unmatchedJsonPath);
}
}
return matches;
}
private boolean matchesJsonPath(List<String> unmatchedJsonPath,
DocumentContext parsedJson, String jsonPath) {
private boolean matchesJsonPath(List<String> unmatchedJsonPath, DocumentContext parsedJson, String jsonPath) {
try {
JsonAssertion.assertThat(parsedJson).matchesJsonPath(jsonPath);
return true;
@@ -239,14 +222,11 @@ class StubRunnerStreamMessageSelector implements MessageSelector {
matches = pattern.matcher(valueInHeader.toString()).matches();
}
else {
matches = valueInHeader != null
&& valueInHeader.toString().equals(value.toString());
matches = valueInHeader != null && valueInHeader.toString().equals(value.toString());
}
if (!matches) {
unmatchedHeaders.add("Header with name [" + name + "] was supposed to "
+ unmatchedText(value) + " but the value is ["
+ (valueInHeader != null ? valueInHeader.toString() : "null")
+ "]");
unmatchedHeaders.add("Header with name [" + name + "] was supposed to " + unmatchedText(value)
+ " but the value is [" + (valueInHeader != null ? valueInHeader.toString() : "null") + "]");
}
}
return unmatchedHeaders;

View File

@@ -50,18 +50,15 @@ class StubRunnerStreamTransformer {
return source;
}
byte[] outputBody = outputBodyAsBytes(groovyDsl);
Map<String, Object> headers = groovyDsl.getOutputMessage().getHeaders()
.asStubSideMap();
Map<String, Object> headers = groovyDsl.getOutputMessage().getHeaders().asStubSideMap();
MessageHeaders messageHeaders = new MessageHeaders(headers);
Message<byte[]> message = MessageBuilder.createMessage(outputBody,
messageHeaders);
Message<byte[]> message = MessageBuilder.createMessage(outputBody, messageHeaders);
this.selector.updateCache(message, groovyDsl);
return message;
}
private byte[] outputBodyAsBytes(Contract groovyDsl) {
Object outputBody = BodyExtractor
.extractClientValueFromBody(groovyDsl.getOutputMessage().getBody());
Object outputBody = BodyExtractor.extractClientValueFromBody(groovyDsl.getOutputMessage().getBody());
if (outputBody instanceof FromFileProperty) {
FromFileProperty property = (FromFileProperty) outputBody;
return property.asBytes();

View File

@@ -30,32 +30,28 @@ import org.springframework.test.context.support.AbstractTestExecutionListener;
* @author Marcin Grzejszczak
* @since 1.2.6
*/
public final class StubRunnerWireMockTestExecutionListener
extends AbstractTestExecutionListener {
public final class StubRunnerWireMockTestExecutionListener extends AbstractTestExecutionListener {
private static final Log log = LogFactory
.getLog(StubRunnerWireMockTestExecutionListener.class);
private static final Log log = LogFactory.getLog(StubRunnerWireMockTestExecutionListener.class);
@Override
public void afterTestClass(TestContext testContext) {
if (testContext.getTestClass()
.getAnnotationsByType(AutoConfigureStubRunner.class).length == 0) {
if (testContext.getTestClass().getAnnotationsByType(AutoConfigureStubRunner.class).length == 0) {
if (log.isDebugEnabled()) {
log.debug("No @AutoConfigureStubRunner annotation found on ["
+ testContext.getTestClass() + "]. Skipping");
log.debug("No @AutoConfigureStubRunner annotation found on [" + testContext.getTestClass()
+ "]. Skipping");
}
return;
}
if (!WireMockHttpServerStub.SERVERS.isEmpty() && WireMockHttpServerStub.SERVERS
.values().stream().noneMatch(p -> p.random)) {
if (!WireMockHttpServerStub.SERVERS.isEmpty()
&& WireMockHttpServerStub.SERVERS.values().stream().noneMatch(p -> p.random)) {
if (log.isWarnEnabled()) {
log.warn("You've used fixed ports for WireMock setup - "
+ "will mark context as dirty. Please use random ports, as much "
+ "as possible. Your tests will be faster and more reliable and this "
+ "warning will go away");
}
testContext
.markApplicationContextDirty(DirtiesContext.HierarchyMode.EXHAUSTIVE);
testContext.markApplicationContextDirty(DirtiesContext.HierarchyMode.EXHAUSTIVE);
}
// potential race condition
WireMockHttpServerStub.SERVERS.clear();

View File

@@ -77,16 +77,15 @@ public class WireMockHttpServerStub implements HttpServerStub {
private WireMockConfiguration wireMockConfiguration;
private WireMockConfiguration config() {
if (ClassUtils.isPresent(
"org.springframework.cloud.contract.wiremock.WireMockSpring", null)) {
if (ClassUtils.isPresent("org.springframework.cloud.contract.wiremock.WireMockSpring", null)) {
return WireMockSpring.options().extensions(responseTransformers());
}
return new WireMockConfiguration().extensions(responseTransformers());
}
private Extension[] responseTransformers() {
List<WireMockExtensions> wireMockExtensions = SpringFactoriesLoader
.loadFactories(WireMockExtensions.class, null);
List<WireMockExtensions> wireMockExtensions = SpringFactoriesLoader.loadFactories(WireMockExtensions.class,
null);
List<Extension> extensions = new ArrayList<>();
if (!wireMockExtensions.isEmpty()) {
for (WireMockExtensions wireMockExtension : wireMockExtensions) {
@@ -94,9 +93,8 @@ public class WireMockHttpServerStub implements HttpServerStub {
}
}
else {
extensions.addAll(
Arrays.asList(new DefaultResponseTransformer(false, helpers()),
new SpringCloudContractRequestMatcher()));
extensions.addAll(Arrays.asList(new DefaultResponseTransformer(false, helpers()),
new SpringCloudContractRequestMatcher()));
}
return extensions.toArray(new Extension[extensions.size()]);
}
@@ -117,8 +115,7 @@ public class WireMockHttpServerStub implements HttpServerStub {
@Override
public int port() {
return isRunning() ? (this.https ? this.wireMockServer.httpsPort()
: this.wireMockServer.port()) : INVALID_PORT;
return isRunning() ? (this.https ? this.wireMockServer.httpsPort() : this.wireMockServer.port()) : INVALID_PORT;
}
@Override
@@ -141,15 +138,13 @@ public class WireMockHttpServerStub implements HttpServerStub {
}
private HttpServerStubConfiguration defaultConfiguration(int port) {
return new HttpServerStubConfiguration(
HttpServerStubConfigurer.NoOpHttpServerStubConfigurer.INSTANCE, null,
return new HttpServerStubConfiguration(HttpServerStubConfigurer.NoOpHttpServerStubConfigurer.INSTANCE, null,
null, port);
}
private HttpServerStubConfiguration defaultConfiguration() {
int port = SocketUtils.findAvailableTcpPort();
return new HttpServerStubConfiguration(
HttpServerStubConfigurer.NoOpHttpServerStubConfigurer.INSTANCE, null,
return new HttpServerStubConfiguration(HttpServerStubConfigurer.NoOpHttpServerStubConfigurer.INSTANCE, null,
null, port, true);
}
@@ -167,24 +162,20 @@ public class WireMockHttpServerStub implements HttpServerStub {
return this;
}
int port = configuration.port;
WireMockConfiguration wireMockConfiguration = config().port(port)
.notifier(new Slf4jNotifier(true));
WireMockConfiguration wireMockConfiguration = config().port(port).notifier(new Slf4jNotifier(true));
if (configuration.configurer.isAccepted(wireMockConfiguration)) {
@SuppressWarnings("unchecked")
HttpServerStubConfigurer<WireMockConfiguration> configurer = configuration.configurer;
wireMockConfiguration = configurer.configure(wireMockConfiguration,
configuration);
wireMockConfiguration = configurer.configure(wireMockConfiguration, configuration);
}
this.wireMockConfiguration = wireMockConfiguration;
this.https = wireMockConfiguration.httpsSettings().enabled();
port = this.https ? wireMockConfiguration.httpsSettings().port()
: wireMockConfiguration.portNumber();
port = this.https ? wireMockConfiguration.httpsSettings().port() : wireMockConfiguration.portNumber();
this.wireMockServer = new WireMockServer(wireMockConfiguration);
this.wireMockServer.start();
if (log.isDebugEnabled()) {
log.debug("For " + configuration.toColonSeparatedDependencyNotation()
+ " Started WireMock at [" + (this.https ? "https" : "http")
+ "] port [" + port + "]");
log.debug("For " + configuration.toColonSeparatedDependencyNotation() + " Started WireMock at ["
+ (this.https ? "https" : "http") + "] port [" + port + "]");
}
cacheStubServer(configuration.randomPort, port);
return this;
@@ -246,8 +237,7 @@ public class WireMockHttpServerStub implements HttpServerStub {
StubMapping getMapping(File file) {
try (InputStream stream = Files.newInputStream(file.toPath())) {
return StubMapping.buildFrom(
StreamUtils.copyToString(stream, Charset.forName("UTF-8")));
return StubMapping.buildFrom(StreamUtils.copyToString(stream, Charset.forName("UTF-8")));
}
catch (IOException e) {
throw new IllegalStateException("Cannot read file", e);
@@ -269,8 +259,7 @@ public class WireMockHttpServerStub implements HttpServerStub {
String proxyHost = this.wireMockConfiguration.proxyHostHeader();
int proxyPort = this.wireMockConfiguration.proxyVia().port();
ClientAuthenticator authenticator = NoClientAuthenticator.noClientAuthenticator();
return new WireMock(scheme, host, port, urlPathPrefix, hostHeader, proxyHost,
proxyPort, authenticator);
return new WireMock(scheme, host, port, urlPathPrefix, hostHeader, proxyHost, proxyPort, authenticator);
}
private void registerDefaultHealthChecks(WireMock wireMock) {
@@ -284,20 +273,17 @@ public class WireMockHttpServerStub implements HttpServerStub {
try {
stubMappings.add(registerDescriptor(wireMock, mappingDescriptor));
if (log.isDebugEnabled()) {
log.debug(
"Registered stub mappings from [" + mappingDescriptor + "]");
log.debug("Registered stub mappings from [" + mappingDescriptor + "]");
}
}
catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Failed to register the stub mapping [" + mappingDescriptor
+ "]", e);
log.debug("Failed to register the stub mapping [" + mappingDescriptor + "]", e);
}
}
}
PortAndMappings portAndMappings = SERVERS.get(this);
SERVERS.put(this, new PortAndMappings(portAndMappings.random,
portAndMappings.port, stubMappings));
SERVERS.put(this, new PortAndMappings(portAndMappings.random, portAndMappings.port, stubMappings));
}
private StubMapping registerDescriptor(WireMock wireMock, File mappingDescriptor) {
@@ -311,8 +297,8 @@ public class WireMockHttpServerStub implements HttpServerStub {
}
private void registerHealthCheck(WireMock wireMock, String url, String body) {
wireMock.register(WireMock.get(WireMock.urlEqualTo(url))
.willReturn(WireMock.aResponse().withBody(body).withStatus(200)));
wireMock.register(
WireMock.get(WireMock.urlEqualTo(url)).willReturn(WireMock.aResponse().withBody(body).withStatus(200)));
}
}
@@ -333,8 +319,8 @@ class PortAndMappings {
@Override
public String toString() {
return "PortAndMappings{" + "random=" + this.random + ", port=" + this.port
+ ", mappings=" + this.mappings + '}';
return "PortAndMappings{" + "random=" + this.random + ", port=" + this.port + ", mappings=" + this.mappings
+ '}';
}
}

View File

@@ -27,8 +27,7 @@ import org.springframework.cloud.contract.stubrunner.HttpServerStubConfigurer;
* @author Marcin Grzejszczak
* @since 2.1.0
*/
public class WireMockHttpServerStubConfigurer
implements HttpServerStubConfigurer<WireMockConfiguration> {
public class WireMockHttpServerStubConfigurer implements HttpServerStubConfigurer<WireMockConfiguration> {
@Override
public boolean isAccepted(Object httpStubConfiguration) {

View File

@@ -35,8 +35,7 @@ import org.springframework.context.annotation.Import;
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({ HttpStubsController.class, StubRunnerConfiguration.class,
StubRunnerServerConfiguration.class })
@Import({ HttpStubsController.class, StubRunnerConfiguration.class, StubRunnerServerConfiguration.class })
public @interface EnableStubRunnerServer {
}

View File

@@ -28,8 +28,7 @@ import org.springframework.context.annotation.Import;
@Configuration(proxyBeanMethods = false)
class StubRunnerServerConfiguration {
@ConditionalOnProperty(name = "stubrunner.messaging.enabled", havingValue = "true",
matchIfMissing = true)
@ConditionalOnProperty(name = "stubrunner.messaging.enabled", havingValue = "true", matchIfMissing = true)
@AutoConfigureMessageVerifier
@Import({ TriggerController.class })
static class StubRunnerMessagingAutoConfiguration {

View File

@@ -45,32 +45,27 @@ public class TriggerController {
}
@PostMapping("/{label:.*}")
public ResponseEntity<Map<String, Collection<String>>> trigger(
@PathVariable String label) {
public ResponseEntity<Map<String, Collection<String>>> trigger(@PathVariable String label) {
try {
this.stubFinder.trigger(label);
return ResponseEntity.ok()
.body(Collections.<String, Collection<String>>emptyMap());
return ResponseEntity.ok().body(Collections.<String, Collection<String>>emptyMap());
}
catch (Exception e) {
throw new RuntimeException("Exception occurred while trying to return ["
+ label + "] label. \n\nAvailable labels are ["
+ this.stubFinder.labels() + " ]", e);
throw new RuntimeException("Exception occurred while trying to return [" + label
+ "] label. \n\nAvailable labels are [" + this.stubFinder.labels() + " ]", e);
}
}
@PostMapping("/{ivyNotation:.*}/{label:.*}")
public ResponseEntity<Map<String, Collection<String>>> triggerByArtifact(
@PathVariable String ivyNotation, @PathVariable String label) {
public ResponseEntity<Map<String, Collection<String>>> triggerByArtifact(@PathVariable String ivyNotation,
@PathVariable String label) {
try {
this.stubFinder.trigger(ivyNotation, label);
return ResponseEntity.ok()
.body(Collections.<String, Collection<String>>emptyMap());
return ResponseEntity.ok().body(Collections.<String, Collection<String>>emptyMap());
}
catch (Exception e) {
throw new RuntimeException("Exception occurred while trying to return ["
+ label + "] label. \n\nAvailable labels are ["
+ this.stubFinder.labels() + " ]", e);
throw new RuntimeException("Exception occurred while trying to return [" + label
+ "] label. \n\nAvailable labels are [" + this.stubFinder.labels() + " ]", e);
}
}

View File

@@ -55,8 +55,7 @@ import org.springframework.util.StringUtils;
*/
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(StubRunnerProperties.class)
@ConditionalOnMissingBean(
type = "org.springframework.cloud.contract.wiremock.WiremockServerConfiguration")
@ConditionalOnMissingBean(type = "org.springframework.cloud.contract.wiremock.WiremockServerConfiguration")
@Import(StubRunnerPortBeanPostProcessor.class)
public class StubRunnerConfiguration {
@@ -83,8 +82,7 @@ public class StubRunnerConfiguration {
}
StubRunnerOptions stubRunnerOptions = stubRunnerOptions(builder);
BatchStubRunner batchStubRunner = new BatchStubRunnerFactory(stubRunnerOptions,
this.provider.get(stubRunnerOptions),
new LazyMessageVerifier(beanFactory)).buildBatchStubRunner();
this.provider.get(stubRunnerOptions), new LazyMessageVerifier(beanFactory)).buildBatchStubRunner();
// TODO: Consider running it in a separate thread
RunningStubs runningStubs = batchStubRunner.runStubs();
registerPort(runningStubs);
@@ -103,28 +101,19 @@ public class StubRunnerConfiguration {
private StubRunnerOptionsBuilder builder(StubRunnerProperties props) {
return new StubRunnerOptionsBuilder()
.withMinMaxPort(
Integer.valueOf(resolvePlaceholder(props.getMinPort(),
props.getMinPort())),
Integer.valueOf(resolvePlaceholder(props.getMaxPort(),
props.getMaxPort())))
.withMinMaxPort(Integer.valueOf(resolvePlaceholder(props.getMinPort(), props.getMinPort())),
Integer.valueOf(resolvePlaceholder(props.getMaxPort(), props.getMaxPort())))
.withStubRepositoryRoot(props.getRepositoryRoot())
.withStubsMode(resolvePlaceholder(props.getStubsMode()))
.withStubsClassifier(resolvePlaceholder(props.getClassifier()))
.withStubs(resolvePlaceholder(props.getIds()))
.withUsername(resolvePlaceholder(props.getUsername()))
.withStubs(resolvePlaceholder(props.getIds())).withUsername(resolvePlaceholder(props.getUsername()))
.withPassword(resolvePlaceholder(props.getPassword()))
.withStubPerConsumer(Boolean
.parseBoolean(resolvePlaceholder(props.isStubsPerConsumer())))
.withStubPerConsumer(Boolean.parseBoolean(resolvePlaceholder(props.isStubsPerConsumer())))
.withConsumerName(consumerName(props))
.withMappingsOutputFolder(
resolvePlaceholder(props.getMappingsOutputFolder()))
.withDeleteStubsAfterTest(Boolean
.parseBoolean(resolvePlaceholder(props.isDeleteStubsAfterTest())))
.withGenerateStubs(
Boolean.parseBoolean(resolvePlaceholder(props.isGenerateStubs())))
.withProperties(props.getProperties())
.withHttpServerStubConfigurer(props.getHttpServerStubConfigurer())
.withMappingsOutputFolder(resolvePlaceholder(props.getMappingsOutputFolder()))
.withDeleteStubsAfterTest(Boolean.parseBoolean(resolvePlaceholder(props.isDeleteStubsAfterTest())))
.withGenerateStubs(Boolean.parseBoolean(resolvePlaceholder(props.isGenerateStubs())))
.withProperties(props.getProperties()).withHttpServerStubConfigurer(props.getHttpServerStubConfigurer())
.withServerId(resolvePlaceholder(props.getServerId()));
}
@@ -153,19 +142,15 @@ public class StubRunnerConfiguration {
private void registerPort(RunningStubs runStubs) {
MutablePropertySources propertySources = this.environment.getPropertySources();
if (!propertySources.contains(STUBRUNNER_PREFIX)) {
propertySources
.addFirst(new MapPropertySource(STUBRUNNER_PREFIX, new HashMap<>()));
propertySources.addFirst(new MapPropertySource(STUBRUNNER_PREFIX, new HashMap<>()));
}
Map<String, Object> source = ((MapPropertySource) propertySources
.get(STUBRUNNER_PREFIX)).getSource();
for (Map.Entry<StubConfiguration, Integer> entry : runStubs.validNamesAndPorts()
.entrySet()) {
source.put(STUBRUNNER_PREFIX + "." + entry.getKey().getArtifactId() + ".port",
entry.getValue());
Map<String, Object> source = ((MapPropertySource) propertySources.get(STUBRUNNER_PREFIX)).getSource();
for (Map.Entry<StubConfiguration, Integer> entry : runStubs.validNamesAndPorts().entrySet()) {
source.put(STUBRUNNER_PREFIX + "." + entry.getKey().getArtifactId() + ".port", entry.getValue());
// there are projects where artifact id is the same, what differs is the group
// id
source.put(STUBRUNNER_PREFIX + "." + entry.getKey().getGroupId() + "."
+ entry.getKey().getArtifactId() + ".port", entry.getValue());
source.put(STUBRUNNER_PREFIX + "." + entry.getKey().getGroupId() + "." + entry.getKey().getArtifactId()
+ ".port", entry.getValue());
}
}
@@ -199,8 +184,7 @@ class LazyMessageVerifier implements MessageVerifier {
}
@Override
public Object receive(String destination, long timeout, TimeUnit timeUnit,
YamlContract contract) {
public Object receive(String destination, long timeout, TimeUnit timeUnit, YamlContract contract) {
return messageVerifier().receive(destination, timeout, timeUnit, contract);
}
@@ -210,8 +194,7 @@ class LazyMessageVerifier implements MessageVerifier {
}
@Override
public void send(Object payload, Map headers, String destination,
YamlContract contract) {
public void send(Object payload, Map headers, String destination, YamlContract contract) {
messageVerifier().send(payload, headers, destination, contract);
}

View File

@@ -38,16 +38,14 @@ class StubRunnerPortBeanPostProcessor implements BeanPostProcessor {
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
injectStubRunnerPort(bean);
return bean;
}
private void injectStubRunnerPort(Object bean) {
Class<?> clazz = bean.getClass();
ReflectionUtils.FieldCallback fieldCallback = new StubRunnerPortFieldCallback(
this.environment, bean);
ReflectionUtils.FieldCallback fieldCallback = new StubRunnerPortFieldCallback(this.environment, bean);
ReflectionUtils.doWithFields(clazz, fieldCallback);
}
@@ -65,16 +63,14 @@ class StubRunnerPortFieldCallback implements ReflectionUtils.FieldCallback {
}
@Override
public void doWith(Field field)
throws IllegalArgumentException, IllegalAccessException {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
if (!field.isAnnotationPresent(StubRunnerPort.class)) {
return;
}
ReflectionUtils.makeAccessible(field);
String stub = field.getDeclaredAnnotation(StubRunnerPort.class).value();
Integer port = this.environment
.getProperty(StubRunnerConfiguration.STUBRUNNER_PREFIX + "."
+ stub.replace(":", ".") + ".port", Integer.class);
Integer port = this.environment.getProperty(
StubRunnerConfiguration.STUBRUNNER_PREFIX + "." + stub.replace(":", ".") + ".port", Integer.class);
if (port != null) {
field.set(this.bean, port);
}

View File

@@ -253,8 +253,7 @@ public class StubRunnerProperties {
}
public void setProperties(String[] properties) {
Properties elements = StringUtils.splitArrayElementsIntoProperties(properties,
"=");
Properties elements = StringUtils.splitArrayElementsIntoProperties(properties, "=");
if (elements == null) {
return;
}
@@ -297,12 +296,10 @@ public class StubRunnerProperties {
@Override
public String toString() {
return "StubRunnerProperties{" + "minPort=" + this.minPort + ", maxPort="
+ this.maxPort + ", repositoryRoot=" + this.repositoryRoot + ", ids="
+ Arrays.toString(this.ids) + ", classifier='" + this.classifier + '\''
+ ", setStubsPerConsumer='" + this.stubsPerConsumer + "', consumerName='"
+ this.consumerName + '\'' + ", stubsMode='" + this.stubsMode + '\''
+ ", size of properties=" + this.properties.size() + '}';
return "StubRunnerProperties{" + "minPort=" + this.minPort + ", maxPort=" + this.maxPort + ", repositoryRoot="
+ this.repositoryRoot + ", ids=" + Arrays.toString(this.ids) + ", classifier='" + this.classifier + '\''
+ ", setStubsPerConsumer='" + this.stubsPerConsumer + "', consumerName='" + this.consumerName + '\''
+ ", stubsMode='" + this.stubsMode + '\'' + ", size of properties=" + this.properties.size() + '}';
}
/**

View File

@@ -34,8 +34,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@ConditionalOnProperty(value = "stubrunner.cloud.stubbed.discovery.enabled",
havingValue = "false")
@ConditionalOnProperty(value = "stubrunner.cloud.stubbed.discovery.enabled", havingValue = "false")
public @interface ConditionalOnStubbedDiscoveryDisabled {
}

View File

@@ -35,8 +35,8 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@ConditionalOnProperty(value = "stubrunner.cloud.stubbed.discovery.enabled",
havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(value = "stubrunner.cloud.stubbed.discovery.enabled", havingValue = "true",
matchIfMissing = true)
public @interface ConditionalOnStubbedDiscoveryEnabled {
}

View File

@@ -62,8 +62,8 @@ public class StubMapperProperties {
if (StringUtils.hasText(id)) {
return id;
}
String groupAndArtifact = this.idsToServiceIds.get(
stubConfiguration.getGroupId() + ":" + stubConfiguration.getArtifactId());
String groupAndArtifact = this.idsToServiceIds
.get(stubConfiguration.getGroupId() + ":" + stubConfiguration.getArtifactId());
if (StringUtils.hasText(groupAndArtifact)) {
return groupAndArtifact;
}

View File

@@ -50,22 +50,18 @@ class StubRunnerDiscoveryClient implements DiscoveryClient {
StubRunnerDiscoveryClient(DiscoveryClient delegate, StubFinder stubFinder,
StubMapperProperties stubMapperProperties) {
this.delegate = delegate instanceof StubRunnerDiscoveryClient
? noOpDiscoveryClient() : delegate;
this.delegate = delegate instanceof StubRunnerDiscoveryClient ? noOpDiscoveryClient() : delegate;
if (log.isDebugEnabled()) {
log.debug("Will delegate calls to discovery service [" + this.delegate
+ "] if a stub is not found");
log.debug("Will delegate calls to discovery service [" + this.delegate + "] if a stub is not found");
}
this.stubFinder = stubFinder;
this.stubMapperProperties = stubMapperProperties;
}
StubRunnerDiscoveryClient(StubFinder stubFinder,
StubMapperProperties stubMapperProperties) {
StubRunnerDiscoveryClient(StubFinder stubFinder, StubMapperProperties stubMapperProperties) {
this.delegate = noOpDiscoveryClient();
if (log.isDebugEnabled()) {
log.debug("Will delegate calls to discovery service [" + this.delegate
+ "] if a stub is not found");
log.debug("Will delegate calls to discovery service [" + this.delegate + "] if a stub is not found");
}
this.stubFinder = stubFinder;
this.stubMapperProperties = stubMapperProperties;
@@ -90,18 +86,16 @@ class StubRunnerDiscoveryClient implements DiscoveryClient {
@Override
public List<ServiceInstance> getInstances(String serviceId) {
String ivyNotation = this.stubMapperProperties
.fromServiceIdToIvyNotation(serviceId);
String ivyNotation = this.stubMapperProperties.fromServiceIdToIvyNotation(serviceId);
String serviceToFind = StringUtils.hasText(ivyNotation) ? ivyNotation : serviceId;
URL stubUrl = this.stubFinder.findStubUrl(serviceToFind);
log.info("Resolved from ivy [" + ivyNotation + "] service to find ["
+ serviceToFind + "]. Found stub is available under URL [" + stubUrl
+ "]");
log.info("Resolved from ivy [" + ivyNotation + "] service to find [" + serviceToFind
+ "]. Found stub is available under URL [" + stubUrl + "]");
if (stubUrl == null) {
return getInstancesFromDelegate(serviceId);
}
return Collections.singletonList(new StubRunnerServiceInstance(serviceId,
stubUrl.getHost(), stubUrl.getPort(), toUri(stubUrl)));
return Collections.singletonList(
new StubRunnerServiceInstance(serviceId, stubUrl.getHost(), stubUrl.getPort(), toUri(stubUrl)));
}
private List<ServiceInstance> getInstancesFromDelegate(String serviceId) {

View File

@@ -34,8 +34,7 @@ import org.springframework.cloud.contract.stubrunner.StubFinder;
*/
class StubRunnerReactiveDiscoveryClient implements ReactiveDiscoveryClient {
private static final Log log = LogFactory
.getLog(StubRunnerReactiveDiscoveryClient.class);
private static final Log log = LogFactory.getLog(StubRunnerReactiveDiscoveryClient.class);
private final ReactiveDiscoveryClient delegate;
@@ -43,24 +42,20 @@ class StubRunnerReactiveDiscoveryClient implements ReactiveDiscoveryClient {
private final StubMapperProperties stubMapperProperties;
StubRunnerReactiveDiscoveryClient(ReactiveDiscoveryClient delegate,
StubFinder stubFinder, StubMapperProperties stubMapperProperties) {
this.delegate = delegate instanceof StubRunnerDiscoveryClient
? noOpDiscoveryClient() : delegate;
StubRunnerReactiveDiscoveryClient(ReactiveDiscoveryClient delegate, StubFinder stubFinder,
StubMapperProperties stubMapperProperties) {
this.delegate = delegate instanceof StubRunnerDiscoveryClient ? noOpDiscoveryClient() : delegate;
if (log.isDebugEnabled()) {
log.debug("Will delegate calls to discovery service [" + this.delegate
+ "] if a stub is not found");
log.debug("Will delegate calls to discovery service [" + this.delegate + "] if a stub is not found");
}
this.stubFinder = stubFinder;
this.stubMapperProperties = stubMapperProperties;
}
StubRunnerReactiveDiscoveryClient(StubFinder stubFinder,
StubMapperProperties stubMapperProperties) {
StubRunnerReactiveDiscoveryClient(StubFinder stubFinder, StubMapperProperties stubMapperProperties) {
this.delegate = noOpDiscoveryClient();
if (log.isDebugEnabled()) {
log.debug("Will delegate calls to discovery service [" + this.delegate
+ "] if a stub is not found");
log.debug("Will delegate calls to discovery service [" + this.delegate + "] if a stub is not found");
}
this.stubFinder = stubFinder;
this.stubMapperProperties = stubMapperProperties;
@@ -94,8 +89,7 @@ class StubRunnerReactiveDiscoveryClient implements ReactiveDiscoveryClient {
@Override
public Flux<String> getServices() {
return Flux.just(client())
.flatMapIterable(StubRunnerDiscoveryClient::getServices);
return Flux.just(client()).flatMapIterable(StubRunnerDiscoveryClient::getServices);
}
@Override

View File

@@ -44,16 +44,14 @@ import org.springframework.core.env.Environment;
public class StubRunnerSpringCloudAutoConfiguration {
@Bean
public StubRunnerDiscoveryClientWrapper stubRunnerDiscoveryClientWrapper(
BeanFactory beanFactory) {
public StubRunnerDiscoveryClientWrapper stubRunnerDiscoveryClientWrapper(BeanFactory beanFactory) {
return new StubRunnerDiscoveryClientWrapper(beanFactory);
}
@Bean
@ConditionalOnMissingBean(DiscoveryClient.class)
@ConditionalOnStubbedDiscoveryEnabled
@ConditionalOnProperty(value = "stubrunner.cloud.delegate.enabled",
havingValue = "false", matchIfMissing = true)
@ConditionalOnProperty(value = "stubrunner.cloud.delegate.enabled", havingValue = "false", matchIfMissing = true)
public DiscoveryClient noOpStubRunnerDiscoveryClient(StubFinder stubFinder,
StubMapperProperties stubMapperProperties) {
return new StubRunnerDiscoveryClient(stubFinder, stubMapperProperties);
@@ -62,10 +60,9 @@ public class StubRunnerSpringCloudAutoConfiguration {
@Bean
@ConditionalOnMissingBean(ReactiveDiscoveryClient.class)
@ConditionalOnStubbedDiscoveryEnabled
@ConditionalOnProperty(value = "stubrunner.cloud.delegate.enabled",
havingValue = "false", matchIfMissing = true)
public ReactiveDiscoveryClient noOpStubRunnerReactiveDiscoveryClient(
StubFinder stubFinder, StubMapperProperties stubMapperProperties) {
@ConditionalOnProperty(value = "stubrunner.cloud.delegate.enabled", havingValue = "false", matchIfMissing = true)
public ReactiveDiscoveryClient noOpStubRunnerReactiveDiscoveryClient(StubFinder stubFinder,
StubMapperProperties stubMapperProperties) {
return new StubRunnerReactiveDiscoveryClient(stubFinder, stubMapperProperties);
}
@@ -90,22 +87,18 @@ class StubRunnerDiscoveryClientWrapper implements BeanPostProcessor {
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof DiscoveryClient
&& !(bean instanceof StubRunnerDiscoveryClient)) {
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof DiscoveryClient && !(bean instanceof StubRunnerDiscoveryClient)) {
if (!isStubbedDiscoveryEnabled()) {
return bean;
}
if (isCloudDelegateEnabled()) {
return new StubRunnerDiscoveryClient((DiscoveryClient) bean, stubFinder(),
stubMapperProperties());
return new StubRunnerDiscoveryClient((DiscoveryClient) bean, stubFinder(), stubMapperProperties());
}
return new StubRunnerDiscoveryClient(stubFinder(), stubMapperProperties());
}
@@ -121,26 +114,23 @@ class StubRunnerDiscoveryClientWrapper implements BeanPostProcessor {
StubMapperProperties stubMapperProperties() {
if (this.stubMapperProperties == null) {
this.stubMapperProperties = this.beanFactory
.getBean(StubMapperProperties.class);
this.stubMapperProperties = this.beanFactory.getBean(StubMapperProperties.class);
}
return this.stubMapperProperties;
}
boolean isStubbedDiscoveryEnabled() {
if (this.stubbedDiscoveryEnabled == null) {
this.stubbedDiscoveryEnabled = Boolean
.valueOf(this.beanFactory.getBean(Environment.class).getProperty(
"stubrunner.cloud.stubbed.discovery.enabled", "true"));
this.stubbedDiscoveryEnabled = Boolean.valueOf(this.beanFactory.getBean(Environment.class)
.getProperty("stubrunner.cloud.stubbed.discovery.enabled", "true"));
}
return this.stubbedDiscoveryEnabled;
}
boolean isCloudDelegateEnabled() {
if (this.cloudDelegateEnabled == null) {
this.cloudDelegateEnabled = Boolean
.valueOf(this.beanFactory.getBean(Environment.class)
.getProperty("stubrunner.cloud.delegate.enabled", "false"));
this.cloudDelegateEnabled = Boolean.valueOf(this.beanFactory.getBean(Environment.class)
.getProperty("stubrunner.cloud.delegate.enabled", "false"));
}
return this.cloudDelegateEnabled;
}

View File

@@ -42,8 +42,7 @@ import org.springframework.util.StringUtils;
*/
public class ConsulStubsRegistrar implements StubsRegistrar {
private static final Log log = LogFactory
.getLog(MethodHandles.lookup().lookupClass());
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
private final StubRunning stubRunning;
@@ -58,8 +57,8 @@ public class ConsulStubsRegistrar implements StubsRegistrar {
private final List<NewService> services = new LinkedList<>();
public ConsulStubsRegistrar(StubRunning stubRunning, ConsulClient consulClient,
StubMapperProperties stubMapperProperties,
ConsulDiscoveryProperties consulDiscoveryProperties, InetUtils inetUtils) {
StubMapperProperties stubMapperProperties, ConsulDiscoveryProperties consulDiscoveryProperties,
InetUtils inetUtils) {
this.stubRunning = stubRunning;
this.consulClient = consulClient;
this.stubMapperProperties = stubMapperProperties;
@@ -69,33 +68,29 @@ public class ConsulStubsRegistrar implements StubsRegistrar {
@Override
public void registerStubs() {
Map<StubConfiguration, Integer> activeStubs = this.stubRunning.runStubs()
.validNamesAndPorts();
Map<StubConfiguration, Integer> activeStubs = this.stubRunning.runStubs().validNamesAndPorts();
for (Map.Entry<StubConfiguration, Integer> entry : activeStubs.entrySet()) {
NewService newService = newService(entry.getKey(), entry.getValue());
this.services.add(newService);
try {
this.consulClient.agentServiceRegister(newService);
if (log.isDebugEnabled()) {
log.debug("Successfully registered stub ["
+ entry.getKey().toColonSeparatedDependencyNotation()
log.debug("Successfully registered stub [" + entry.getKey().toColonSeparatedDependencyNotation()
+ "] in Service Discovery");
}
}
catch (Exception e) {
log.warn("Exception occurred while trying to register a stub ["
+ entry.getKey().toColonSeparatedDependencyNotation()
+ "] in Service Discovery", e);
+ entry.getKey().toColonSeparatedDependencyNotation() + "] in Service Discovery", e);
}
}
}
protected NewService newService(StubConfiguration stubConfiguration, Integer port) {
NewService newService = new NewService();
newService.setAddress(
StringUtils.hasText(this.consulDiscoveryProperties.getHostname())
? this.consulDiscoveryProperties.getHostname()
: this.inetUtils.findFirstNonLoopbackAddress().getHostName());
newService.setAddress(StringUtils.hasText(this.consulDiscoveryProperties.getHostname())
? this.consulDiscoveryProperties.getHostname()
: this.inetUtils.findFirstNonLoopbackAddress().getHostName());
newService.setId(stubConfiguration.getArtifactId());
newService.setName(name(stubConfiguration));
newService.setPort(port);
@@ -103,8 +98,8 @@ public class ConsulStubsRegistrar implements StubsRegistrar {
}
protected String name(StubConfiguration stubConfiguration) {
String resolvedName = this.stubMapperProperties.fromIvyNotationToId(
stubConfiguration.toColonSeparatedDependencyNotation());
String resolvedName = this.stubMapperProperties
.fromIvyNotationToId(stubConfiguration.toColonSeparatedDependencyNotation());
if (StringUtils.hasText(resolvedName)) {
return resolvedName;
}

View File

@@ -39,19 +39,18 @@ import org.springframework.context.annotation.Configuration;
* @since 1.0.0
*/
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter({ StubRunnerConfiguration.class,
ConsulServiceRegistryAutoConfiguration.class })
@AutoConfigureAfter({ StubRunnerConfiguration.class, ConsulServiceRegistryAutoConfiguration.class })
@ConditionalOnClass(ConsulClient.class)
@ConditionalOnStubbedDiscoveryDisabled
@ConditionalOnProperty(value = "stubrunner.cloud.consul.enabled", matchIfMissing = true)
public class StubRunnerSpringCloudConsulAutoConfiguration {
@Bean(initMethod = "registerStubs")
public StubsRegistrar stubsRegistrar(StubRunning stubRunning,
ConsulClient consulClient, StubMapperProperties stubMapperProperties,
ConsulDiscoveryProperties consulDiscoveryProperties, InetUtils inetUtils) {
return new ConsulStubsRegistrar(stubRunning, consulClient, stubMapperProperties,
consulDiscoveryProperties, inetUtils);
public StubsRegistrar stubsRegistrar(StubRunning stubRunning, ConsulClient consulClient,
StubMapperProperties stubMapperProperties, ConsulDiscoveryProperties consulDiscoveryProperties,
InetUtils inetUtils) {
return new ConsulStubsRegistrar(stubRunning, consulClient, stubMapperProperties, consulDiscoveryProperties,
inetUtils);
}
}

View File

@@ -34,8 +34,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@ConditionalOnProperty(value = "eureka.client.enabled", havingValue = "true",
matchIfMissing = true)
@ConditionalOnProperty(value = "eureka.client.enabled", havingValue = "true", matchIfMissing = true)
@interface ConditionalOnEurekaEnabled {
}

View File

@@ -52,8 +52,7 @@ import org.springframework.util.StringUtils;
*/
public class EurekaStubsRegistrar implements StubsRegistrar {
private static final Log log = LogFactory
.getLog(MethodHandles.lookup().lookupClass());
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
private final StubRunning stubRunning;
@@ -71,11 +70,10 @@ public class EurekaStubsRegistrar implements StubsRegistrar {
private final ApplicationContext context;
public EurekaStubsRegistrar(StubRunning stubRunning,
ServiceRegistry<EurekaRegistration> serviceRegistry,
public EurekaStubsRegistrar(StubRunning stubRunning, ServiceRegistry<EurekaRegistration> serviceRegistry,
StubMapperProperties stubMapperProperties, InetUtils inetUtils,
EurekaInstanceConfigBean eurekaInstanceConfigBean,
EurekaClientConfigBean eurekaClientConfigBean, ApplicationContext context) {
EurekaInstanceConfigBean eurekaInstanceConfigBean, EurekaClientConfigBean eurekaClientConfigBean,
ApplicationContext context) {
this.stubRunning = stubRunning;
this.stubMapperProperties = stubMapperProperties;
this.serviceRegistry = serviceRegistry;
@@ -87,32 +85,27 @@ public class EurekaStubsRegistrar implements StubsRegistrar {
@Override
public void registerStubs() {
Map<StubConfiguration, Integer> activeStubs = this.stubRunning.runStubs()
.validNamesAndPorts();
Map<StubConfiguration, Integer> activeStubs = this.stubRunning.runStubs().validNamesAndPorts();
for (Map.Entry<StubConfiguration, Integer> entry : activeStubs.entrySet()) {
EurekaInstanceConfigBean instance = registration(entry);
log.info("Will register stub in Eureka " + "[" + instance.getAppname() + ", "
+ instance.getHostname() + ", " + instance.getNonSecurePort() + ", "
+ instance.getInstanceId() + "]");
log.info("Will register stub in Eureka " + "[" + instance.getAppname() + ", " + instance.getHostname()
+ ", " + instance.getNonSecurePort() + ", " + instance.getInstanceId() + "]");
InstanceInfo instanceInfo = new InstanceInfoFactory().create(instance);
ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(
instance, instanceInfo);
ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(instance, instanceInfo);
AbstractDiscoveryClientOptionalArgs args = args();
EurekaClient client = new CloudEurekaClient(applicationInfoManager,
this.eurekaClientConfigBean, args, this.context);
EurekaClient client = new CloudEurekaClient(applicationInfoManager, this.eurekaClientConfigBean, args,
this.context);
EurekaRegistration registration = EurekaRegistration.builder(instance)
.with(this.eurekaClientConfigBean, this.context).with(client).build();
this.registrations.add(registration);
try {
this.serviceRegistry.register(registration);
log.info("Successfully registered stub " + "["
+ entry.getKey().toColonSeparatedDependencyNotation()
log.info("Successfully registered stub " + "[" + entry.getKey().toColonSeparatedDependencyNotation()
+ "] in Service Discovery");
}
catch (Exception e) {
log.warn("Exception occurred while trying to register a stub ["
+ entry.getKey().toColonSeparatedDependencyNotation()
+ "] in Service Discovery", e);
+ entry.getKey().toColonSeparatedDependencyNotation() + "] in Service Discovery", e);
}
}
}
@@ -126,22 +119,19 @@ public class EurekaStubsRegistrar implements StubsRegistrar {
}
}
private EurekaInstanceConfigBean registration(
Map.Entry<StubConfiguration, Integer> entry) {
private EurekaInstanceConfigBean registration(Map.Entry<StubConfiguration, Integer> entry) {
EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(this.inetUtils);
String appName = name(entry.getKey());
config.setInstanceEnabledOnit(true);
InetAddress address = this.inetUtils.findFirstNonLoopbackAddress();
config.setIpAddress(address.getHostAddress());
config.setHostname(StringUtils.hasText(hostName(entry)) ? hostName(entry)
: address.getHostName());
config.setHostname(StringUtils.hasText(hostName(entry)) ? hostName(entry) : address.getHostName());
config.setAppname(appName);
config.setVirtualHostName(appName);
config.setSecureVirtualHostName(appName);
int port = port(entry);
config.setNonSecurePort(port);
config.setInstanceId(address.getHostAddress() + ":"
+ entry.getKey().getArtifactId() + ":" + port);
config.setInstanceId(address.getHostAddress() + ":" + entry.getKey().getArtifactId() + ":" + port);
config.setLeaseRenewalIntervalInSeconds(1);
return config;
}
@@ -155,8 +145,8 @@ public class EurekaStubsRegistrar implements StubsRegistrar {
}
private String name(StubConfiguration stubConfiguration) {
String resolvedName = this.stubMapperProperties.fromIvyNotationToId(
stubConfiguration.toColonSeparatedDependencyNotation());
String resolvedName = this.stubMapperProperties
.fromIvyNotationToId(stubConfiguration.toColonSeparatedDependencyNotation());
if (StringUtils.hasText(resolvedName)) {
return resolvedName;
}

View File

@@ -51,8 +51,7 @@ import org.springframework.core.env.Environment;
* @since 1.0.0
*/
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter({ StubRunnerConfiguration.class,
EurekaClientAutoConfiguration.class })
@AutoConfigureAfter({ StubRunnerConfiguration.class, EurekaClientAutoConfiguration.class })
@ConditionalOnClass(CloudEurekaClient.class)
@ConditionalOnStubbedDiscoveryDisabled
@ConditionalOnEurekaEnabled
@@ -65,13 +64,11 @@ public class StubRunnerSpringCloudEurekaAutoConfiguration {
@Bean(initMethod = "registerStubs")
public StubsRegistrar stubsRegistrar(StubRunning stubRunning,
ServiceRegistry<EurekaRegistration> serviceRegistry,
ApplicationContext context, StubMapperProperties stubMapperProperties,
InetUtils inetUtils, EurekaInstanceConfigBean eurekaInstanceConfigBean,
EurekaClientConfigBean eurekaClientConfigBean) {
return new EurekaStubsRegistrar(stubRunning, serviceRegistry,
stubMapperProperties, inetUtils, eurekaInstanceConfigBean,
eurekaClientConfigBean, context);
ServiceRegistry<EurekaRegistration> serviceRegistry, ApplicationContext context,
StubMapperProperties stubMapperProperties, InetUtils inetUtils,
EurekaInstanceConfigBean eurekaInstanceConfigBean, EurekaClientConfigBean eurekaClientConfigBean) {
return new EurekaStubsRegistrar(stubRunning, serviceRegistry, stubMapperProperties, inetUtils,
eurekaInstanceConfigBean, eurekaClientConfigBean, context);
}
}
@@ -89,21 +86,17 @@ public class StubRunnerSpringCloudEurekaAutoConfiguration {
@Bean(initMethod = "registerStubs")
public StubsRegistrar stubsRegistrar(StubRunning stubRunning,
ServiceRegistry<EurekaRegistration> serviceRegistry,
ApplicationContext context, StubMapperProperties stubMapperProperties,
InetUtils inetUtils, EurekaInstanceConfigBean eurekaInstanceConfigBean,
EurekaClientConfigBean eurekaClientConfigBean) {
return new EurekaStubsRegistrar(stubRunning, serviceRegistry,
stubMapperProperties, inetUtils, eurekaInstanceConfigBean,
eurekaClientConfigBean, context) {
ServiceRegistry<EurekaRegistration> serviceRegistry, ApplicationContext context,
StubMapperProperties stubMapperProperties, InetUtils inetUtils,
EurekaInstanceConfigBean eurekaInstanceConfigBean, EurekaClientConfigBean eurekaClientConfigBean) {
return new EurekaStubsRegistrar(stubRunning, serviceRegistry, stubMapperProperties, inetUtils,
eurekaInstanceConfigBean, eurekaClientConfigBean, context) {
@Override
protected String hostName(Map.Entry<StubConfiguration, Integer> entry) {
String hostname = CloudConfig.this.environment
.getProperty("application.hostname") + "-" + entry.getValue()
+ "." + CloudConfig.this.environment
.getProperty("application.domain");
log.info("Registering stub [" + entry.getKey().getArtifactId()
+ "] with hostname [" + hostname + "]");
String hostname = CloudConfig.this.environment.getProperty("application.hostname") + "-"
+ entry.getValue() + "." + CloudConfig.this.environment.getProperty("application.domain");
log.info("Registering stub [" + entry.getKey().getArtifactId() + "] with hostname [" + hostname
+ "]");
return hostname;
}

View File

@@ -62,26 +62,22 @@ import org.springframework.util.StringUtils;
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@ConditionalOnProperty(value = "stubrunner.cloud.loadbalancer.enabled",
matchIfMissing = true)
@ConditionalOnProperty(value = "stubrunner.cloud.loadbalancer.enabled", matchIfMissing = true)
@ConditionalOnBean(StubMapperProperties.class)
@AutoConfigureBefore(LoadBalancerAutoConfiguration.class)
@AutoConfigureAfter({ LoadBalancerClientConfiguration.class,
StubRunnerSpringCloudAutoConfiguration.class })
@AutoConfigureAfter({ LoadBalancerClientConfiguration.class, StubRunnerSpringCloudAutoConfiguration.class })
@ConditionalOnStubbedDiscoveryEnabled
public class SpringCloudLoadBalancerAutoConfiguration {
@Bean
@Primary
LoadBalancerClientFactory stubRunnerLoadBalancerClientFactory(
BeanFactory beanFactory) {
LoadBalancerClientFactory stubRunnerLoadBalancerClientFactory(BeanFactory beanFactory) {
return new StubRunnerLoadBalancerClientFactory(beanFactory);
}
}
class StubRunnerLoadBalancerClientFactory extends LoadBalancerClientFactory
implements Closeable {
class StubRunnerLoadBalancerClientFactory extends LoadBalancerClientFactory implements Closeable {
private final BeanFactory beanFactory;
@@ -91,8 +87,7 @@ class StubRunnerLoadBalancerClientFactory extends LoadBalancerClientFactory
@Override
public ReactiveLoadBalancer<ServiceInstance> getInstance(String serviceId) {
return new ContractReactorServiceInstanceLoadBalancer(this.beanFactory,
serviceId);
return new ContractReactorServiceInstanceLoadBalancer(this.beanFactory, serviceId);
}
@Override
@@ -138,8 +133,7 @@ class StubbedServiceInstance implements ServiceInstance {
static final Map<String, Map.Entry<StubConfiguration, Integer>> CACHE = new ConcurrentHashMap<>();
StubbedServiceInstance(StubFinder stubFinder,
StubMapperProperties stubMapperProperties, String serviceId) {
StubbedServiceInstance(StubFinder stubFinder, StubMapperProperties stubMapperProperties, String serviceId) {
this.stubFinder = stubFinder;
this.stubMapperProperties = stubMapperProperties;
this.serviceId = serviceId;
@@ -151,11 +145,9 @@ class StubbedServiceInstance implements ServiceInstance {
return entry;
}
RunningStubs runningStubs = this.stubFinder.findAllRunningStubs();
String mappedServiceName = StringUtils.hasText(
this.stubMapperProperties.fromServiceIdToIvyNotation(this.serviceId))
? this.stubMapperProperties.fromServiceIdToIvyNotation(
this.serviceId)
: this.serviceId;
String mappedServiceName = StringUtils
.hasText(this.stubMapperProperties.fromServiceIdToIvyNotation(this.serviceId))
? this.stubMapperProperties.fromServiceIdToIvyNotation(this.serviceId) : this.serviceId;
entry = runningStubs.getEntry(mappedServiceName);
CACHE.put(this.serviceId, entry);
return entry;
@@ -188,8 +180,7 @@ class StubbedServiceInstance implements ServiceInstance {
@Override
public URI getUri() {
return URI.create(
(isSecure() ? "https://" : "http://") + getHost() + ":" + getPort());
return URI.create((isSecure() ? "https://" : "http://") + getHost() + ":" + getPort());
}
@Override
@@ -199,8 +190,7 @@ class StubbedServiceInstance implements ServiceInstance {
}
class ContractReactorServiceInstanceLoadBalancer
implements ReactorServiceInstanceLoadBalancer, LoadBalancerLifecycle {
class ContractReactorServiceInstanceLoadBalancer implements ReactorServiceInstanceLoadBalancer, LoadBalancerLifecycle {
private final BeanFactory beanFactory;
@@ -210,8 +200,7 @@ class ContractReactorServiceInstanceLoadBalancer
private StubMapperProperties stubMapperProperties;
ContractReactorServiceInstanceLoadBalancer(BeanFactory beanFactory,
String serviceId) {
ContractReactorServiceInstanceLoadBalancer(BeanFactory beanFactory, String serviceId) {
this.beanFactory = beanFactory;
this.serviceId = serviceId;
}
@@ -228,8 +217,8 @@ class ContractReactorServiceInstanceLoadBalancer
@Override
public Mono<Response<ServiceInstance>> choose(Request request) {
return Mono.just(new DefaultResponse(new StubbedServiceInstance(stubFinder(),
stubMapperProperties(), this.serviceId)));
return Mono.just(
new DefaultResponse(new StubbedServiceInstance(stubFinder(), stubMapperProperties(), this.serviceId)));
}
private StubFinder stubFinder() {
@@ -241,8 +230,7 @@ class ContractReactorServiceInstanceLoadBalancer
private StubMapperProperties stubMapperProperties() {
if (this.stubMapperProperties == null) {
this.stubMapperProperties = this.beanFactory
.getBean(StubMapperProperties.class);
this.stubMapperProperties = this.beanFactory.getBean(StubMapperProperties.class);
}
return this.stubMapperProperties;
}

View File

@@ -39,21 +39,18 @@ import org.springframework.context.annotation.Configuration;
* @since 1.0.0
*/
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter({ StubRunnerConfiguration.class,
CuratorServiceDiscoveryAutoConfiguration.class })
@AutoConfigureAfter({ StubRunnerConfiguration.class, CuratorServiceDiscoveryAutoConfiguration.class })
@ConditionalOnClass(org.apache.curator.x.discovery.ServiceInstance.class)
@ConditionalOnStubbedDiscoveryDisabled
@ConditionalOnZookeeperDiscoveryEnabled
@ConditionalOnProperty(value = "stubrunner.cloud.zookeeper.enabled",
matchIfMissing = true)
@ConditionalOnProperty(value = "stubrunner.cloud.zookeeper.enabled", matchIfMissing = true)
public class StubRunnerSpringCloudZookeeperAutoConfiguration {
@Bean(initMethod = "registerStubs")
public StubsRegistrar stubsRegistrar(StubRunning stubRunning,
CuratorFramework curatorFramework, StubMapperProperties stubMapperProperties,
ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) {
return new ZookeeperStubsRegistrar(stubRunning, curatorFramework,
stubMapperProperties, zookeeperDiscoveryProperties);
public StubsRegistrar stubsRegistrar(StubRunning stubRunning, CuratorFramework curatorFramework,
StubMapperProperties stubMapperProperties, ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) {
return new ZookeeperStubsRegistrar(stubRunning, curatorFramework, stubMapperProperties,
zookeeperDiscoveryProperties);
}
}

View File

@@ -44,8 +44,7 @@ import org.springframework.util.StringUtils;
*/
public class ZookeeperStubsRegistrar implements StubsRegistrar {
private static final Log log = LogFactory
.getLog(MethodHandles.lookup().lookupClass());
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
private final StubRunning stubRunning;
@@ -57,9 +56,8 @@ public class ZookeeperStubsRegistrar implements StubsRegistrar {
private final List<ServiceDiscovery> discoveryList = new LinkedList<>();
public ZookeeperStubsRegistrar(StubRunning stubRunning,
CuratorFramework curatorFramework, StubMapperProperties stubMapperProperties,
ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) {
public ZookeeperStubsRegistrar(StubRunning stubRunning, CuratorFramework curatorFramework,
StubMapperProperties stubMapperProperties, ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) {
this.stubRunning = stubRunning;
this.curatorFramework = curatorFramework;
this.stubMapperProperties = stubMapperProperties;
@@ -68,36 +66,29 @@ public class ZookeeperStubsRegistrar implements StubsRegistrar {
@Override
public void registerStubs() {
Map<StubConfiguration, Integer> activeStubs = this.stubRunning.runStubs()
.validNamesAndPorts();
Map<StubConfiguration, Integer> activeStubs = this.stubRunning.runStubs().validNamesAndPorts();
for (Map.Entry<StubConfiguration, Integer> entry : activeStubs.entrySet()) {
ServiceInstance serviceInstance = serviceInstance(entry.getKey(),
entry.getValue());
ServiceInstance serviceInstance = serviceInstance(entry.getKey(), entry.getValue());
ServiceDiscovery serviceDiscovery = serviceDiscovery(serviceInstance);
this.discoveryList.add(serviceDiscovery);
try {
serviceDiscovery.start();
if (log.isDebugEnabled()) {
log.debug("Successfully registered stub ["
+ entry.getKey().toColonSeparatedDependencyNotation()
log.debug("Successfully registered stub [" + entry.getKey().toColonSeparatedDependencyNotation()
+ "] in Service Discovery");
}
}
catch (Exception e) {
log.warn("Exception occurred while trying to register a stub ["
+ entry.getKey().toColonSeparatedDependencyNotation()
+ "] in Service Discovery", e);
+ entry.getKey().toColonSeparatedDependencyNotation() + "] in Service Discovery", e);
}
}
}
protected ServiceInstance serviceInstance(StubConfiguration stubConfiguration,
int port) {
protected ServiceInstance serviceInstance(StubConfiguration stubConfiguration, int port) {
try {
return ServiceInstance.builder()
.uriSpec(new UriSpec(this.zookeeperDiscoveryProperties.getUriSpec()))
.address("localhost").port(port).name(name(stubConfiguration))
.build();
return ServiceInstance.builder().uriSpec(new UriSpec(this.zookeeperDiscoveryProperties.getUriSpec()))
.address("localhost").port(port).name(name(stubConfiguration)).build();
}
catch (Exception e) {
throw new IllegalStateException(e);
@@ -105,8 +96,8 @@ public class ZookeeperStubsRegistrar implements StubsRegistrar {
}
private String name(StubConfiguration stubConfiguration) {
String resolvedName = this.stubMapperProperties.fromIvyNotationToId(
stubConfiguration.toColonSeparatedDependencyNotation());
String resolvedName = this.stubMapperProperties
.fromIvyNotationToId(stubConfiguration.toColonSeparatedDependencyNotation());
if (StringUtils.hasText(resolvedName)) {
return resolvedName;
}
@@ -114,8 +105,7 @@ public class ZookeeperStubsRegistrar implements StubsRegistrar {
}
protected ServiceDiscovery serviceDiscovery(ServiceInstance serviceInstance) {
return ServiceDiscoveryBuilder.builder(Void.class)
.basePath(this.zookeeperDiscoveryProperties.getRoot())
return ServiceDiscoveryBuilder.builder(Void.class).basePath(this.zookeeperDiscoveryProperties.getRoot())
.client(this.curatorFramework).thisInstance(serviceInstance).build();
}

View File

@@ -56,8 +56,7 @@ public final class StubsParser {
* @param defaultClassifier default classifier to append if one is missing
* @return parsed stub configurations
*/
public static List<StubConfiguration> fromString(Collection<String> collection,
String defaultClassifier) {
public static List<StubConfiguration> fromString(Collection<String> collection, String defaultClassifier) {
List<StubConfiguration> stubs = new ArrayList<>();
for (String config : collection) {
if (StringUtils.hasText(config)) {
@@ -72,8 +71,7 @@ public final class StubsParser {
* @return mapping of parsed stub configurations to ports on which the stub is running
*/
public static Map<StubConfiguration, Integer> fromStringWithPort(String notation) {
StubSpecification stub = StubSpecification.parse(notation,
StubConfiguration.DEFAULT_CLASSIFIER);
StubSpecification stub = StubSpecification.parse(notation, StubConfiguration.DEFAULT_CLASSIFIER);
if (!stub.hasPort()) {
return Collections.emptyMap();
}
@@ -86,8 +84,7 @@ public final class StubsParser {
* present
*/
public static String ivyFromStringWithPort(String notation) {
StubSpecification stub = StubSpecification.parse(notation,
StubConfiguration.DEFAULT_CLASSIFIER);
StubSpecification stub = StubSpecification.parse(notation, StubConfiguration.DEFAULT_CLASSIFIER);
if (!stub.hasPort()) {
return "";
}
@@ -129,8 +126,7 @@ public final class StubsParser {
}
catch (NumberFormatException e) {
}
return new StubSpecification(new StubConfiguration(id, defaultClassifier),
port);
return new StubSpecification(new StubConfiguration(id, defaultClassifier), port);
}
public boolean hasPort() {

View File

@@ -63,8 +63,7 @@ public final class ZipCategory {
List<File> unzippedFiles = new ArrayList<>();
try (InputStream fileInputStream = Files.newInputStream(self.toPath())) {
try (ZipInputStream zipInput = new ZipInputStream(fileInputStream)) {
for (ZipEntry entry = zipInput
.getNextEntry(); entry != null; entry = zipInput.getNextEntry()) {
for (ZipEntry entry = zipInput.getNextEntry(); entry != null; entry = zipInput.getNextEntry()) {
if (!entry.isDirectory()) {
final File file = new File(destination, entry.getName());
if (file.getParentFile() != null) {

View File

@@ -39,10 +39,8 @@ public class StubRunnerRuleCustomPortJUnitTest {
@ClassRule
public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
.downloadStub("org.springframework.cloud.contract.verifier.stubs",
"loanIssuance")
.withPort(12345).downloadStub(
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:12346");
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance").withPort(12345)
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:12346");
@BeforeClass
@AfterClass
@@ -55,8 +53,7 @@ public class StubRunnerRuleCustomPortJUnitTest {
private static String repoRoot() {
try {
return StubRunnerRuleCustomPortJUnitTest.class
.getResource("/m2repo/repository/").toURI().toString();
return StubRunnerRuleCustomPortJUnitTest.class.getResource("/m2repo/repository/").toURI().toString();
}
catch (Exception e) {
return "";
@@ -66,33 +63,24 @@ public class StubRunnerRuleCustomPortJUnitTest {
@Test
public void should_start_wiremock_servers() throws Exception {
// expect: 'WireMocks are running'
then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs",
"loanIssuance")).isNotNull();
then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")).isNotNull();
then(rule.findStubUrl("loanIssuance")).isNotNull();
then(rule.findStubUrl("loanIssuance")).isEqualTo(rule.findStubUrl(
"org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
then(rule.findStubUrl(
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
.isNotNull();
then(rule.findStubUrl("loanIssuance"))
.isEqualTo(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isNotNull();
// and:
then(rule.findAllRunningStubs().isPresent("loanIssuance")).isTrue();
then(rule.findAllRunningStubs().isPresent(
"org.springframework.cloud.contract.verifier.stubs",
then(rule.findAllRunningStubs().isPresent("org.springframework.cloud.contract.verifier.stubs",
"fraudDetectionServer")).isTrue();
then(rule.findAllRunningStubs().isPresent(
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
.isTrue();
then(rule.findAllRunningStubs()
.isPresent("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isTrue();
// and: 'Stubs were registered'
then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name"))
.isEqualTo("loanIssuance");
then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name"))
.isEqualTo("fraudDetectionServer");
then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name")).isEqualTo("loanIssuance");
then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name")).isEqualTo("fraudDetectionServer");
// and: 'The port is fixed'
// tag::test_with_port[]
then(rule.findStubUrl("loanIssuance"))
.isEqualTo(URI.create("http://localhost:12345").toURL());
then(rule.findStubUrl("fraudDetectionServer"))
.isEqualTo(URI.create("http://localhost:12346").toURL());
then(rule.findStubUrl("loanIssuance")).isEqualTo(URI.create("http://localhost:12345").toURL());
then(rule.findStubUrl("fraudDetectionServer")).isEqualTo(URI.create("http://localhost:12346").toURL());
// end::test_with_port[]
}

View File

@@ -39,10 +39,8 @@ public class StubRunnerRuleJUnitTest {
@ClassRule
public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
.downloadStub("org.springframework.cloud.contract.verifier.stubs",
"loanIssuance")
.downloadStub(
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");
@BeforeClass
@AfterClass
@@ -55,8 +53,7 @@ public class StubRunnerRuleJUnitTest {
private static String repoRoot() {
try {
return StubRunnerRuleJUnitTest.class.getResource("/m2repo/repository/")
.toURI().toString();
return StubRunnerRuleJUnitTest.class.getResource("/m2repo/repository/").toURI().toString();
}
catch (Exception e) {
return "";
@@ -67,27 +64,20 @@ public class StubRunnerRuleJUnitTest {
@Test
public void should_start_wiremock_servers() throws Exception {
// expect: 'WireMocks are running'
then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs",
"loanIssuance")).isNotNull();
then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")).isNotNull();
then(rule.findStubUrl("loanIssuance")).isNotNull();
then(rule.findStubUrl("loanIssuance")).isEqualTo(rule.findStubUrl(
"org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
then(rule.findStubUrl(
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
.isNotNull();
then(rule.findStubUrl("loanIssuance"))
.isEqualTo(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isNotNull();
// and:
then(rule.findAllRunningStubs().isPresent("loanIssuance")).isTrue();
then(rule.findAllRunningStubs().isPresent(
"org.springframework.cloud.contract.verifier.stubs",
then(rule.findAllRunningStubs().isPresent("org.springframework.cloud.contract.verifier.stubs",
"fraudDetectionServer")).isTrue();
then(rule.findAllRunningStubs().isPresent(
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
.isTrue();
then(rule.findAllRunningStubs()
.isPresent("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isTrue();
// and: 'Stubs were registered'
then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name"))
.isEqualTo("loanIssuance");
then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name"))
.isEqualTo("fraudDetectionServer");
then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name")).isEqualTo("loanIssuance");
then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name")).isEqualTo("fraudDetectionServer");
}
// end::test[]

View File

@@ -74,8 +74,7 @@ public abstract class AbstractGitTest {
command.call();
StoredConfig config = git.getRepository().getConfig();
RemoteConfig originConfig = new RemoteConfig(config, "origin");
originConfig
.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
originConfig.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
originConfig.update(config);
config.save();
}

View File

@@ -30,8 +30,7 @@ public class ClasspathStubProviderTest {
@Test
public void should_return_null_if_stub_mode_is_not_classpath() {
StubDownloader stubDownloader = new ClasspathStubProvider()
.build(new StubRunnerOptionsBuilder()
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE).build());
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE).build());
then(stubDownloader).isNull();
}

View File

@@ -35,14 +35,12 @@ public class CompositeStubDownloaderBuilderTests {
public void should_delegate_work_to_other_stub_downloaders() {
EmptyStubDownloaderBuilder emptyStubDownloaderBuilder = new EmptyStubDownloaderBuilder();
ImpossibleToBuildStubDownloaderBuilder impossible = new ImpossibleToBuildStubDownloaderBuilder();
List<StubDownloaderBuilder> builders = Arrays.asList(emptyStubDownloaderBuilder,
impossible, new SomeStubDownloaderBuilder());
CompositeStubDownloaderBuilder builder = new CompositeStubDownloaderBuilder(
builders);
List<StubDownloaderBuilder> builders = Arrays.asList(emptyStubDownloaderBuilder, impossible,
new SomeStubDownloaderBuilder());
CompositeStubDownloaderBuilder builder = new CompositeStubDownloaderBuilder(builders);
StubDownloader downloader = builder.build(new StubRunnerOptionsBuilder().build());
Map.Entry<StubConfiguration, File> entry = downloader
.downloadAndUnpackStubJar(new StubConfiguration("a:b:v"));
Map.Entry<StubConfiguration, File> entry = downloader.downloadAndUnpackStubJar(new StubConfiguration("a:b:v"));
BDDAssertions.then(entry).isNotNull();
BDDAssertions.then(emptyStubDownloaderBuilder.downloaderCalled()).isTrue();
@@ -63,11 +61,9 @@ public class CompositeStubDownloaderBuilderTests {
EmptyStubDownloaderBuilder emptyStubDownloaderBuilder = new EmptyStubDownloaderBuilder();
CompositeStubDownloaderBuilder builder = new CompositeStubDownloaderBuilder(
Collections.singletonList(emptyStubDownloaderBuilder));
StubDownloader downloader = builder
.build(new StubRunnerOptionsBuilder().withFailOnNoStubs(false).build());
StubDownloader downloader = builder.build(new StubRunnerOptionsBuilder().withFailOnNoStubs(false).build());
Map.Entry<StubConfiguration, File> entry = downloader
.downloadAndUnpackStubJar(new StubConfiguration("a:b:v"));
Map.Entry<StubConfiguration, File> entry = downloader.downloadAndUnpackStubJar(new StubConfiguration("a:b:v"));
BDDAssertions.then(entry).isNull();
}
@@ -77,11 +73,9 @@ public class CompositeStubDownloaderBuilderTests {
EmptyStubDownloaderBuilder emptyStubDownloaderBuilder = new EmptyStubDownloaderBuilder();
CompositeStubDownloaderBuilder builder = new CompositeStubDownloaderBuilder(
Collections.singletonList(emptyStubDownloaderBuilder));
StubDownloader downloader = builder
.build(new StubRunnerOptionsBuilder().withFailOnNoStubs(true).build());
StubDownloader downloader = builder.build(new StubRunnerOptionsBuilder().withFailOnNoStubs(true).build());
BDDAssertions.thenThrownBy(
() -> downloader.downloadAndUnpackStubJar(new StubConfiguration("a:b:v")))
BDDAssertions.thenThrownBy(() -> downloader.downloadAndUnpackStubJar(new StubConfiguration("a:b:v")))
.isInstanceOf(IllegalArgumentException.class);
}
@@ -120,8 +114,7 @@ class EmptyStubDownloader implements StubDownloader {
boolean called;
@Override
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
StubConfiguration stubConfiguration) {
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(StubConfiguration stubConfiguration) {
this.called = true;
return null;
}
@@ -140,8 +133,7 @@ class SomeStubDownloaderBuilder implements StubDownloaderBuilder {
class SomeStubDownloader implements StubDownloader {
@Override
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
StubConfiguration stubConfiguration) {
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(StubConfiguration stubConfiguration) {
return new AbstractMap.SimpleEntry<>(stubConfiguration, new File("."));
}

View File

@@ -53,8 +53,7 @@ public class ContractProjectUpdaterTest extends AbstractGitTest {
@Before
public void setup() throws Exception {
GitContractsRepo.CACHED_LOCATIONS.clear();
this.originalProject = new File(
GitRepoTests.class.getResource("/git_samples/contract-git").toURI());
this.originalProject = new File(GitRepoTests.class.getResource("/git_samples/contract-git").toURI());
TestUtils.prepareLocalRepo();
this.gitRepo = new GitRepo(this.tmpFolder);
this.origin = clonedProject(this.tmp.newFolder(), this.originalProject);
@@ -69,91 +68,76 @@ public class ContractProjectUpdaterTest extends AbstractGitTest {
@Test
public void should_push_changes_to_current_branch() throws Exception {
File stubs = new File(
GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI());
File stubs = new File(GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI());
this.updater.updateContractProject("hello-world", stubs.toPath());
// project, not origin, cause we're making one more clone of the local copy
try (Git git = openGitProject(this.project)) {
RevCommit revCommit = git.log().call().iterator().next();
then(revCommit.getShortMessage())
.isEqualTo("Updating project [hello-world] with stubs");
then(revCommit.getShortMessage()).isEqualTo("Updating project [hello-world] with stubs");
// I have no idea but the file gets deleted after pushing
git.reset().setMode(ResetCommand.ResetType.HARD).call();
}
BDDAssertions.then(new File(this.project,
"META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
BDDAssertions.then(new File(this.project, "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
.exists();
BDDAssertions.then(this.gitRepo.gitFactory.provider).isNull();
BDDAssertions.then(this.outputCapture.toString())
.contains("No custom credentials provider will be set");
BDDAssertions.then(this.outputCapture.toString()).contains("No custom credentials provider will be set");
}
@Test
public void should_push_changes_to_current_branch_using_credentials()
throws Exception {
public void should_push_changes_to_current_branch_using_credentials() throws Exception {
StubRunnerOptions options = new StubRunnerOptionsBuilder()
.withStubRepositoryRoot("file://" + this.project.getAbsolutePath() + "/")
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withProperties(new HashMap<String, String>() {
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE).withProperties(new HashMap<String, String>() {
{
put("git.username", "foo");
put("git.password", "bar");
}
}).build();
ContractProjectUpdater updater = new ContractProjectUpdater(options);
File stubs = new File(
GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI());
File stubs = new File(GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI());
updater.updateContractProject("hello-world", stubs.toPath());
// project, not origin, cause we're making one more clone of the local copy
try (Git git = openGitProject(this.project)) {
RevCommit revCommit = git.log().call().iterator().next();
then(revCommit.getShortMessage())
.isEqualTo("Updating project [hello-world] with stubs");
then(revCommit.getShortMessage()).isEqualTo("Updating project [hello-world] with stubs");
// I have no idea but the file gets deleted after pushing
git.reset().setMode(ResetCommand.ResetType.HARD).call();
}
BDDAssertions.then(new File(this.project,
"META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
BDDAssertions.then(new File(this.project, "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
.exists();
BDDAssertions.then(this.outputCapture.toString()).contains(
"Passed username and password - will set a custom credentials provider");
BDDAssertions.then(this.outputCapture.toString())
.contains("Passed username and password - will set a custom credentials provider");
}
@Test
public void should_push_changes_to_current_branch_using_root_credentials()
throws Exception {
public void should_push_changes_to_current_branch_using_root_credentials() throws Exception {
StubRunnerOptions options = new StubRunnerOptionsBuilder()
.withStubRepositoryRoot("file://" + this.project.getAbsolutePath() + "/")
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE).withUsername("foo")
.withPassword("bar").build();
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE).withUsername("foo").withPassword("bar").build();
ContractProjectUpdater updater = new ContractProjectUpdater(options);
File stubs = new File(
GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI());
File stubs = new File(GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI());
updater.updateContractProject("hello-world", stubs.toPath());
// project, not origin, cause we're making one more clone of the local copy
try (Git git = openGitProject(this.project)) {
RevCommit revCommit = git.log().call().iterator().next();
then(revCommit.getShortMessage())
.isEqualTo("Updating project [hello-world] with stubs");
then(revCommit.getShortMessage()).isEqualTo("Updating project [hello-world] with stubs");
// I have no idea but the file gets deleted after pushing
git.reset().setMode(ResetCommand.ResetType.HARD).call();
}
BDDAssertions.then(new File(this.project,
"META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
BDDAssertions.then(new File(this.project, "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
.exists();
BDDAssertions.then(this.outputCapture.toString()).contains(
"Passed username and password - will set a custom credentials provider");
BDDAssertions.then(this.outputCapture.toString())
.contains("Passed username and password - will set a custom credentials provider");
}
@Test
public void should_not_push_changes_to_current_branch_when_no_changes_were_made()
throws Exception {
public void should_not_push_changes_to_current_branch_when_no_changes_were_made() throws Exception {
String initialCommit;
try (Git git = openGitProject(this.origin)) {
RevCommit revCommit = git.log().call().iterator().next();
@@ -166,8 +150,7 @@ public class ContractProjectUpdaterTest extends AbstractGitTest {
RevCommit revCommit = git.log().call().iterator().next();
then(revCommit.getShortMessage()).isEqualTo(initialCommit);
}
BDDAssertions.then(new File(this.project,
"META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
BDDAssertions.then(new File(this.project, "META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
.doesNotExist();
}

View File

@@ -30,17 +30,14 @@ public class FileStubDownloaderTests {
public void resolve() {
final FileStubDownloader fileStubDownloader = new FileStubDownloader();
Resource expectedUnixResource = new StubsResource("stubs://file:///User/A/B/C");
Resource expectedWindowsResource = new StubsResource(
"stubs://file:///C:/Users/A/B/C");
Resource expectedWindowsResource = new StubsResource("stubs://file:///C:/Users/A/B/C");
String unixFileFormat = "stubs://file:///User/A/B/C";
String windowsFileFormat = "stubs://file://C:\\Users\\A\\B\\C";
String windowsFileFormatCorrectPathStart = "stubs://file:///C:\\Users\\A\\B\\C";
Assertions.assertThat(expectedUnixResource)
.isEqualTo(fileStubDownloader.resolve(unixFileFormat, null));
Assertions.assertThat(expectedUnixResource).isEqualTo(fileStubDownloader.resolve(unixFileFormat, null));
Assertions.assertThat(expectedWindowsResource).isEqualTo(fileStubDownloader.resolve(windowsFileFormat, null));
Assertions.assertThat(expectedWindowsResource)
.isEqualTo(fileStubDownloader.resolve(windowsFileFormat, null));
Assertions.assertThat(expectedWindowsResource).isEqualTo(
fileStubDownloader.resolve(windowsFileFormatCorrectPathStart, null));
.isEqualTo(fileStubDownloader.resolve(windowsFileFormatCorrectPathStart, null));
}
}

View File

@@ -42,8 +42,7 @@ public class GitRepoTests extends AbstractGitTest {
@Before
public void setup() throws IOException, URISyntaxException {
this.project = new File(
GitRepoTests.class.getResource("/git_samples/contract-git").toURI());
this.project = new File(GitRepoTests.class.getResource("/git_samples/contract-git").toURI());
TestUtils.prepareLocalRepo();
this.gitRepo = new GitRepo(this.tmpFolder);
}
@@ -56,20 +55,16 @@ public class GitRepoTests extends AbstractGitTest {
}
@Test
public void should_throw_exception_when_there_is_no_repo()
throws IOException, URISyntaxException {
thenThrownBy(() -> this.gitRepo
.cloneProject(GitRepoTests.class.getResource("/git_samples/").toURI()))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Exception occurred while cloning repo");
public void should_throw_exception_when_there_is_no_repo() throws IOException, URISyntaxException {
thenThrownBy(() -> this.gitRepo.cloneProject(GitRepoTests.class.getResource("/git_samples/").toURI()))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Exception occurred while cloning repo");
}
@Test
public void should_throw_an_exception_when_failed_to_initialize_the_repo()
throws IOException {
public void should_throw_an_exception_when_failed_to_initialize_the_repo() throws IOException {
thenThrownBy(() -> new GitRepo(this.tmpFolder, new ExceptionThrowingJGitFactory())
.cloneProject(this.project.toURI()))
.isInstanceOf(IllegalStateException.class)
.cloneProject(this.project.toURI())).isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Exception occurred while cloning repo")
.hasCauseInstanceOf(CustomException.class);
}
@@ -84,8 +79,7 @@ public class GitRepoTests extends AbstractGitTest {
}
@Test
public void should_throw_an_exception_when_checking_out_nonexisting_branch()
throws IOException {
public void should_throw_an_exception_when_checking_out_nonexisting_branch() throws IOException {
File project = this.gitRepo.cloneProject(this.project.toURI());
try {
this.gitRepo.checkout(project, "nonExistingBranch");

View File

@@ -49,10 +49,8 @@ public class GitStubDownloaderTests {
public void should_return_a_null_downloader_for_a_classptath_mode() {
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
StubDownloader stubDownloader = stubDownloaderBuilder
.build(new StubRunnerOptionsBuilder()
.withStubsMode(StubRunnerProperties.StubsMode.CLASSPATH)
.withProperties(props()).build());
StubDownloader stubDownloader = stubDownloaderBuilder.build(new StubRunnerOptionsBuilder()
.withStubsMode(StubRunnerProperties.StubsMode.CLASSPATH).withProperties(props()).build());
then(stubDownloader).isNull();
}
@@ -61,10 +59,8 @@ public class GitStubDownloaderTests {
public void should_return_a_null_downloader_for_a_empty_repo() {
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
StubDownloader stubDownloader = stubDownloaderBuilder
.build(new StubRunnerOptionsBuilder()
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withProperties(props()).build());
StubDownloader stubDownloader = stubDownloaderBuilder.build(new StubRunnerOptionsBuilder()
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE).withProperties(props()).build());
then(stubDownloader).isNull();
}
@@ -74,190 +70,161 @@ public class GitStubDownloaderTests {
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
StubDownloader stubDownloader = stubDownloaderBuilder
.build(new StubRunnerOptionsBuilder()
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withStubRepositoryRoot("http://www.foo.com/")
.withProperties(props()).build());
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withStubRepositoryRoot("http://www.foo.com/").withProperties(props()).build());
then(stubDownloader).isNull();
}
@Test
public void should_pick_stubs_for_group_and_artifact_with_version_from_a_git_repo()
throws Exception {
public void should_pick_stubs_for_group_and_artifact_with_version_from_a_git_repo() throws Exception {
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
String contractFolderLocation = (file("/git_samples/contract-git/")
.getAbsolutePath() + "/").replace(File.separator, "/");
String contractFolderLocation = (file("/git_samples/contract-git/").getAbsolutePath() + "/")
.replace(File.separator, "/");
StubDownloader stubDownloader = stubDownloaderBuilder
.build(new StubRunnerOptionsBuilder()
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withStubRepositoryRoot("git://" + contractFolderLocation)
.withProperties(props()).build());
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withStubRepositoryRoot("git://" + contractFolderLocation).withProperties(props()).build());
Map.Entry<StubConfiguration, File> entry = stubDownloader
.downloadAndUnpackStubJar(
new StubConfiguration("foo.bar:bazService:0.0.1-SNAPSHOT"));
.downloadAndUnpackStubJar(new StubConfiguration("foo.bar:bazService:0.0.1-SNAPSHOT"));
then(entry).isNotNull();
then(entry.getValue().getAbsolutePath()).contains("foo.bar" + File.separator
+ "bazService" + File.separator + "0.0.1-SNAPSHOT");
then(entry.getValue().getAbsolutePath())
.contains("foo.bar" + File.separator + "bazService" + File.separator + "0.0.1-SNAPSHOT");
}
@Test
public void should_pick_latest_build_snapshot_stubs_when_latest_version_set()
throws URISyntaxException {
public void should_pick_latest_build_snapshot_stubs_when_latest_version_set() throws URISyntaxException {
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
String contractFolderLocation = (file("/git_samples/contract-git/")
.getAbsolutePath() + "/").replace(File.separator, "/");
String contractFolderLocation = (file("/git_samples/contract-git/").getAbsolutePath() + "/")
.replace(File.separator, "/");
StubDownloader stubDownloader = stubDownloaderBuilder
.build(new StubRunnerOptionsBuilder()
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withStubRepositoryRoot("git://" + contractFolderLocation)
.withProperties(props()).build());
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withStubRepositoryRoot("git://" + contractFolderLocation).withProperties(props()).build());
Map.Entry<StubConfiguration, File> entry = stubDownloader
.downloadAndUnpackStubJar(new StubConfiguration(
"com.example:beer-api-producer-external:+"));
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:+"));
then(entry).isNotNull();
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator
+ "beer-api-producer-external" + File.separator + "1.0.0.BUILD-SNAPSHOT");
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator + "beer-api-producer-external"
+ File.separator + "1.0.0.BUILD-SNAPSHOT");
entry = stubDownloader.downloadAndUnpackStubJar(
new StubConfiguration("com.example:beer-api-producer-external:latest"));
entry = stubDownloader
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:latest"));
then(entry).isNotNull();
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator
+ "beer-api-producer-external" + File.separator + "1.0.0.BUILD-SNAPSHOT");
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator + "beer-api-producer-external"
+ File.separator + "1.0.0.BUILD-SNAPSHOT");
entry = stubDownloader.downloadAndUnpackStubJar(
new StubConfiguration("com.example:beer-api-producer-external:LATEST"));
entry = stubDownloader
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:LATEST"));
then(entry).isNotNull();
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator
+ "beer-api-producer-external" + File.separator + "1.0.0.BUILD-SNAPSHOT");
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator + "beer-api-producer-external"
+ File.separator + "1.0.0.BUILD-SNAPSHOT");
entry = stubDownloader.downloadAndUnpackStubJar(
new StubConfiguration("com.issue1305:beer-api-producer-external:+"));
entry = stubDownloader
.downloadAndUnpackStubJar(new StubConfiguration("com.issue1305:beer-api-producer-external:+"));
then(entry).isNotNull();
then(entry.getValue().getAbsolutePath()).contains("com.issue1305" + File.separator
+ "beer-api-producer-external" + File.separator + "0.0.11-SNAPSHOT");
then(entry.getValue().getAbsolutePath()).contains(
"com.issue1305" + File.separator + "beer-api-producer-external" + File.separator + "0.0.11-SNAPSHOT");
}
@Test
public void should_pick_latest_release_stubs_when_release_version_set()
throws URISyntaxException {
public void should_pick_latest_release_stubs_when_release_version_set() throws URISyntaxException {
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
String contractFolderLocation = (file("/git_samples/contract-git/")
.getAbsolutePath() + "/").replace(File.separator, "/");
String contractFolderLocation = (file("/git_samples/contract-git/").getAbsolutePath() + "/")
.replace(File.separator, "/");
StubDownloader stubDownloader = stubDownloaderBuilder
.build(new StubRunnerOptionsBuilder()
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withStubRepositoryRoot("git://" + contractFolderLocation)
.withProperties(props()).build());
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withStubRepositoryRoot("git://" + contractFolderLocation).withProperties(props()).build());
Map.Entry<StubConfiguration, File> entry = stubDownloader
.downloadAndUnpackStubJar(new StubConfiguration(
"com.example:beer-api-producer-external:release"));
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:release"));
then(entry).isNotNull();
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator
+ "beer-api-producer-external" + File.separator + "1.0.0.RELEASE");
then(entry.getValue().getAbsolutePath()).contains(
"com.example" + File.separator + "beer-api-producer-external" + File.separator + "1.0.0.RELEASE");
entry = stubDownloader.downloadAndUnpackStubJar(
new StubConfiguration("com.example:beer-api-producer-external:RELEASE"));
entry = stubDownloader
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:RELEASE"));
then(entry).isNotNull();
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator
+ "beer-api-producer-external" + File.separator + "1.0.0.RELEASE");
then(entry.getValue().getAbsolutePath()).contains(
"com.example" + File.separator + "beer-api-producer-external" + File.separator + "1.0.0.RELEASE");
}
@Test
public void should_pick_latest_build_snapshot_stubs_when_latest_version_set_and_latest_folder_exists()
throws URISyntaxException {
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
String contractFolderLocation = (file(
"/git_samples/contract-predefined-names-git/").getAbsolutePath()
.replace("/", File.separator)
+ "/").replace(File.separator, "/");
String contractFolderLocation = (file("/git_samples/contract-predefined-names-git/").getAbsolutePath()
.replace("/", File.separator) + "/").replace(File.separator, "/");
StubDownloader stubDownloader = stubDownloaderBuilder
.build(new StubRunnerOptionsBuilder()
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withStubRepositoryRoot("git://" + contractFolderLocation)
.withProperties(props()).build());
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withStubRepositoryRoot("git://" + contractFolderLocation).withProperties(props()).build());
Map.Entry<StubConfiguration, File> entry = stubDownloader
.downloadAndUnpackStubJar(new StubConfiguration(
"com.example:beer-api-producer-external:+"));
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:+"));
then(entry).isNotNull();
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator
+ "beer-api-producer-external" + File.separator + "latest");
then(entry.getValue().getAbsolutePath())
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "latest");
entry = stubDownloader.downloadAndUnpackStubJar(
new StubConfiguration("com.example:beer-api-producer-external:latest"));
entry = stubDownloader
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:latest"));
then(entry).isNotNull();
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator
+ "beer-api-producer-external" + File.separator + "latest");
then(entry.getValue().getAbsolutePath())
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "latest");
entry = stubDownloader.downloadAndUnpackStubJar(
new StubConfiguration("com.example:beer-api-producer-external:LATEST"));
entry = stubDownloader
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:LATEST"));
then(entry).isNotNull();
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator
+ "beer-api-producer-external" + File.separator + "latest");
then(entry.getValue().getAbsolutePath())
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "latest");
}
@Test
public void should_pick_release_folder_when_release_version_set()
throws URISyntaxException {
public void should_pick_release_folder_when_release_version_set() throws URISyntaxException {
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
String contractFolderLocation = (file(
"/git_samples/contract-predefined-names-git/").getAbsolutePath() + "/")
.replace(File.separator, "/");
String contractFolderLocation = (file("/git_samples/contract-predefined-names-git/").getAbsolutePath() + "/")
.replace(File.separator, "/");
StubDownloader stubDownloader = stubDownloaderBuilder
.build(new StubRunnerOptionsBuilder()
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withStubRepositoryRoot("git://" + contractFolderLocation)
.withProperties(props()).build());
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withStubRepositoryRoot("git://" + contractFolderLocation).withProperties(props()).build());
Map.Entry<StubConfiguration, File> entry = stubDownloader
.downloadAndUnpackStubJar(new StubConfiguration(
"com.example:beer-api-producer-external:release"));
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:release"));
then(entry).isNotNull();
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator
+ "beer-api-producer-external" + File.separator + "release");
then(entry.getValue().getAbsolutePath())
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "release");
entry = stubDownloader.downloadAndUnpackStubJar(
new StubConfiguration("com.example:beer-api-producer-external:RELEASE"));
entry = stubDownloader
.downloadAndUnpackStubJar(new StubConfiguration("com.example:beer-api-producer-external:RELEASE"));
then(entry).isNotNull();
then(entry.getValue().getAbsolutePath()).contains("com.example" + File.separator
+ "beer-api-producer-external" + File.separator + "release");
then(entry.getValue().getAbsolutePath())
.contains("com.example" + File.separator + "beer-api-producer-external" + File.separator + "release");
}
@Test
public void should_fail_to_fetch_stubs_when_concrete_version_was_not_specified()
throws URISyntaxException {
public void should_fail_to_fetch_stubs_when_concrete_version_was_not_specified() throws URISyntaxException {
StubDownloaderBuilder stubDownloaderBuilder = new ScmStubDownloaderBuilder();
String contractFolderLocation = (file("/git_samples/contract-git/")
.getAbsolutePath() + "/").replace(File.separator, "/");
String contractFolderLocation = (file("/git_samples/contract-git/").getAbsolutePath() + "/")
.replace(File.separator, "/");
StubDownloader stubDownloader = stubDownloaderBuilder
.build(new StubRunnerOptionsBuilder()
.withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withStubRepositoryRoot("git://" + contractFolderLocation)
.withProperties(props()).build());
.build(new StubRunnerOptionsBuilder().withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
.withStubRepositoryRoot("git://" + contractFolderLocation).withProperties(props()).build());
try {
stubDownloader.downloadAndUnpackStubJar(
new StubConfiguration("foo.bar", "bazService", ""));
stubDownloader.downloadAndUnpackStubJar(new StubConfiguration("foo.bar", "bazService", ""));
}
catch (IllegalStateException e) {
then(e).hasMessageContaining(
"Concrete version wasn't passed for [foo.bar:bazService::stubs]");
then(e).hasMessageContaining("Concrete version wasn't passed for [foo.bar:bazService::stubs]");
}
}

View File

@@ -46,15 +46,12 @@ public class StubDownloaderBuilderProviderTests {
Collections.singletonList(this.one)) {
@Override
List<StubDownloaderBuilder> defaultStubDownloaderBuilders() {
return Collections
.singletonList(StubDownloaderBuilderProviderTests.this.two);
return Collections.singletonList(StubDownloaderBuilderProviderTests.this.two);
}
};
StubRunnerOptions options = new StubRunnerOptionsBuilder()
.withFailOnNoStubs(false).build();
StubRunnerOptions options = new StubRunnerOptionsBuilder().withFailOnNoStubs(false).build();
provider.get(options, this.three)
.downloadAndUnpackStubJar(new StubConfiguration("a:b:c"));
provider.get(options, this.three).downloadAndUnpackStubJar(new StubConfiguration("a:b:c"));
BDDMockito.then(this.one).should().build(options);
BDDMockito.then(this.two).should().build(options);

View File

@@ -30,14 +30,13 @@ import org.springframework.cloud.contract.spec.Contract;
*/
public class StubRepositoryTest {
private static final File YAML_REPOSITORY_LOCATION = new File(
"src/test/resources/customYamlRepository");
private static final File YAML_REPOSITORY_LOCATION = new File("src/test/resources/customYamlRepository");
@Test
public void should_prefer_custom_yaml_converter_over_standard() {
// given:
StubRepository repository = new StubRepository(YAML_REPOSITORY_LOCATION,
new ArrayList<>(), new StubRunnerOptionsBuilder().build());
StubRepository repository = new StubRepository(YAML_REPOSITORY_LOCATION, new ArrayList<>(),
new StubRunnerOptionsBuilder().build());
int expectedDescriptorsSize = 1;
// when:

View File

@@ -38,9 +38,9 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
@RunWith(SpringRunner.class)
@WebMvcTest
@AutoConfigureStubRunner(ids = {
"org.springframework.cloud.contract.verifier.stubs:loanIssuance:+:stubs",
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:+:stubs" },
@AutoConfigureStubRunner(
ids = { "org.springframework.cloud.contract.verifier.stubs:loanIssuance:+:stubs",
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:+:stubs" },
minPort = 10001, maxPort = 10020, mappingsOutputFolder = "target/outputmappings/",
properties = { "hello=world", "foo=bar" })
@ActiveProfiles("test")
@@ -64,25 +64,21 @@ public class StubRunnerSliceTests {
assertThat(this.fraudDetectionServerPort).isBetween(10001, 10020);
assertThat(this.loanIssuancePort).isBetween(10001, 10020);
assertThat(this.stubFinder.findStubUrl(
"org.springframework.cloud.contract.verifier.stubs", "loanIssuance"))
.isNotNull();
assertThat(this.stubFinder.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"))
.isNotNull();
assertThat(this.stubFinder.findStubUrl("loanIssuance")).isNotNull();
assertThat(this.stubFinder.findStubUrl("loanIssuance")).isEqualTo(this.stubFinder
.findStubUrl("org.springframework.cloud.contract.verifier.stubs",
"loanIssuance"));
assertThat(this.stubFinder.findStubUrl("loanIssuance"))
.isEqualTo(this.stubFinder.findStubUrl(
"org.springframework.cloud.contract.verifier.stubs:loanIssuance"));
assertThat(this.stubFinder.findStubUrl(
"org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT"))
assertThat(this.stubFinder.findStubUrl("loanIssuance")).isEqualTo(
this.stubFinder.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
assertThat(this.stubFinder.findStubUrl("loanIssuance")).isEqualTo(
this.stubFinder.findStubUrl("org.springframework.cloud.contract.verifier.stubs:loanIssuance"));
assertThat(this.stubFinder
.findStubUrl("org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT"))
.isEqualTo(this.stubFinder.findStubUrl(
"org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs"));
assertThat(this.stubFinder.findStubUrl(
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
assertThat(
this.stubFinder.findStubUrl("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
.isNotNull();
assertThat(this.properties.getProperties()).containsEntry("hello", "world")
.containsEntry("foo", "bar");
assertThat(this.properties.getProperties()).containsEntry("hello", "world").containsEntry("foo", "bar");
}
@SpringBootConfiguration

View File

@@ -31,8 +31,8 @@ public class StubsStubDownloaderTests {
@Test
public void should_pick_stubs_from_a_given_location() {
String path = url.getPath();
StubRunnerOptions options = new StubRunnerOptionsBuilder()
.withStubRepositoryRoot("stubs://file://" + path).build();
StubRunnerOptions options = new StubRunnerOptionsBuilder().withStubRepositoryRoot("stubs://file://" + path)
.build();
StubsStubDownloader downloader = new StubsStubDownloader(options);
Map.Entry<StubConfiguration, File> entry = downloader
@@ -40,17 +40,14 @@ public class StubsStubDownloaderTests {
BDDAssertions.then(entry).isNotNull();
BDDAssertions.then(entry.getValue()).exists();
BDDAssertions.then(new File(entry.getValue(), "pl/spring/cloud/bye/pl_bye.json"))
.exists();
BDDAssertions.then(new File(entry.getValue(), "lv/spring/cloud/bye/lv_bye.json"))
.exists();
BDDAssertions.then(new File(entry.getValue(), "pl/spring/cloud/bye/pl_bye.json")).exists();
BDDAssertions.then(new File(entry.getValue(), "lv/spring/cloud/bye/lv_bye.json")).exists();
}
@Test
public void should_pick_stubs_from_a_given_location_for_a_find_producer_with_ga() {
String path = url.getPath();
StubRunnerOptions options = new StubRunnerOptionsBuilder()
.withStubRepositoryRoot("stubs://file://" + path)
StubRunnerOptions options = new StubRunnerOptionsBuilder().withStubRepositoryRoot("stubs://file://" + path)
.withProperties(propsWithFindProducer()).build();
StubsStubDownloader downloader = new StubsStubDownloader(options);
@@ -58,16 +55,14 @@ public class StubsStubDownloaderTests {
.downloadAndUnpackStubJar(new StubConfiguration("lv.spring.cloud:bye"));
BDDAssertions.then(entry).isNotNull();
File stub = new File(entry.getValue().getPath(),
"lv/spring/cloud/bye/lv_bye.json");
File stub = new File(entry.getValue().getPath(), "lv/spring/cloud/bye/lv_bye.json");
BDDAssertions.then(stub).exists();
}
@Test
public void should_pick_stubs_from_a_given_location_for_a_find_producer_with_gav() {
String path = url.getPath();
StubRunnerOptions options = new StubRunnerOptionsBuilder()
.withStubRepositoryRoot("stubs://file://" + path)
StubRunnerOptions options = new StubRunnerOptionsBuilder().withStubRepositoryRoot("stubs://file://" + path)
.withProperties(propsWithFindProducer()).build();
StubsStubDownloader downloader = new StubsStubDownloader(options);
@@ -75,8 +70,7 @@ public class StubsStubDownloaderTests {
.downloadAndUnpackStubJar(new StubConfiguration("lv.spring:cloud:bye"));
BDDAssertions.then(entry).isNotNull();
File stub = new File(entry.getValue().getPath(),
"lv/spring/cloud/bye/lv_bye.json");
File stub = new File(entry.getValue().getPath(), "lv/spring/cloud/bye/lv_bye.json");
BDDAssertions.then(stub).exists();
}

View File

@@ -25,12 +25,10 @@ class TestUtils {
public static void prepareLocalRepo() throws IOException {
prepareLocalRepo("target/test-classes/git_samples/", "contract-git");
prepareLocalRepo("target/test-classes/git_samples/",
"contract-predefined-names-git");
prepareLocalRepo("target/test-classes/git_samples/", "contract-predefined-names-git");
}
private static void prepareLocalRepo(String buildDir, String repoPath)
throws IOException {
private static void prepareLocalRepo(String buildDir, String repoPath) throws IOException {
File dotGit = new File(buildDir + repoPath + "/.git");
File git = new File(buildDir + repoPath + "/git");
if (git.exists()) {

View File

@@ -39,10 +39,8 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Biju Kunjummen
*/
@RunWith(SpringRunner.class)
@SpringBootTest(properties = {
"ping.url=http://localhost:${stubrunner.runningstubs.loanIssuance.port}" })
@AutoConfigureStubRunner(ids = {
"org.springframework.cloud.contract.verifier.stubs:loanIssuance:+:stubs",
@SpringBootTest(properties = { "ping.url=http://localhost:${stubrunner.runningstubs.loanIssuance.port}" })
@AutoConfigureStubRunner(ids = { "org.springframework.cloud.contract.verifier.stubs:loanIssuance:+:stubs",
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:+:stubs" })
@ActiveProfiles("test")
public class Issue1225Tests {
@@ -56,8 +54,7 @@ public class Issue1225Tests {
@Test
public void shouldInjectTheStubPortsAsEarlyAsPossible() {
assertThat(this.stubRunnerLoanIssuancePort).isPositive();
assertThat(this.pingProxyController.pingUrl)
.contains(":" + this.stubRunnerLoanIssuancePort);
assertThat(this.pingProxyController.pingUrl).contains(":" + this.stubRunnerLoanIssuancePort);
}
@ComponentScan

View File

@@ -41,8 +41,7 @@ class StubRunnerJUnit5ExtensionCustomMessageVerifierTests {
@RegisterExtension
static StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
.stubsMode(StubRunnerProperties.StubsMode.REMOTE).repoRoot(repoRoot())
.downloadStub("org.springframework.cloud.contract.verifier.stubs",
"bootService")
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "bootService")
.messageVerifier(new MyMessageVerifier());
@BeforeAll
@@ -54,8 +53,7 @@ class StubRunnerJUnit5ExtensionCustomMessageVerifierTests {
private static String repoRoot() {
try {
return StubRunnerRuleCustomPortJUnitTest.class
.getResource("/m2repo/repository/").toURI().toString();
return StubRunnerRuleCustomPortJUnitTest.class.getResource("/m2repo/repository/").toURI().toString();
}
catch (Exception e) {
return "";
@@ -64,20 +62,15 @@ class StubRunnerJUnit5ExtensionCustomMessageVerifierTests {
@Test
void should_use_provided_message_verifier_in_junit5_extension() {
IllegalStateException emptyTriggerException = assertThrows(
IllegalStateException.class, () -> stubRunnerExtension.trigger());
assertThat(emptyTriggerException.getMessage())
.contains("Failed to send a message with headers");
IllegalStateException wrongLabelException = assertThrows(
IllegalStateException.class,
IllegalStateException emptyTriggerException = assertThrows(IllegalStateException.class,
() -> stubRunnerExtension.trigger());
assertThat(emptyTriggerException.getMessage()).contains("Failed to send a message with headers");
IllegalStateException wrongLabelException = assertThrows(IllegalStateException.class,
() -> stubRunnerExtension.trigger("return_book_1"));
assertThat(wrongLabelException.getMessage())
.contains("Failed to send a message with headers");
IllegalStateException wrongLabelWithIvyNotation = assertThrows(
IllegalStateException.class,
assertThat(wrongLabelException.getMessage()).contains("Failed to send a message with headers");
IllegalStateException wrongLabelWithIvyNotation = assertThrows(IllegalStateException.class,
() -> stubRunnerExtension.trigger("bootService", "return_book_1"));
assertThat(wrongLabelWithIvyNotation.getMessage())
.contains("Failed to send a message with headers");
assertThat(wrongLabelWithIvyNotation.getMessage()).contains("Failed to send a message with headers");
}
static class MyMessageVerifier implements MessageVerifier {
@@ -88,8 +81,7 @@ class StubRunnerJUnit5ExtensionCustomMessageVerifierTests {
}
@Override
public Object receive(String destination, long timeout, TimeUnit timeUnit,
YamlContract contract) {
public Object receive(String destination, long timeout, TimeUnit timeUnit, YamlContract contract) {
throw new IllegalStateException("Failed to receive a message with timeout");
}
@@ -99,8 +91,7 @@ class StubRunnerJUnit5ExtensionCustomMessageVerifierTests {
}
@Override
public void send(Object payload, Map headers, String destination,
YamlContract contract) {
public void send(Object payload, Map headers, String destination, YamlContract contract) {
throw new IllegalStateException("Failed to send a message with headers");
}

Some files were not shown because too many files have changed in this diff Show More