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

@@ -70,8 +70,7 @@ public class Main {
log.info("Generated schema!");
}
private String generateJsonSchemaForClass(Class clazz)
throws JsonProcessingException {
private String generateJsonSchemaForClass(Class clazz) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(mapper);
@@ -94,8 +93,7 @@ public class Main {
mapper.disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);
StringBuilder sb = new StringBuilder();
for (Class metadatum : metadata) {
SpringCloudContractMetadata newInstance = (SpringCloudContractMetadata) metadatum
.newInstance();
SpringCloudContractMetadata newInstance = (SpringCloudContractMetadata) metadatum.newInstance();
String description = newInstance.description();
String key = newInstance.key();
List<Class> additionalClasses = classesToLookAt(metadatum, newInstance);
@@ -119,8 +117,7 @@ public class Main {
return sb;
}
private List<Class> classesToLookAt(Class metadatum,
SpringCloudContractMetadata newInstance) {
private List<Class> classesToLookAt(Class metadatum, SpringCloudContractMetadata newInstance) {
List<Class> additionalClasses = new ArrayList<>();
additionalClasses.add(metadatum);
additionalClasses.addAll(newInstance.additionalClassesToLookAt());

View File

@@ -40,12 +40,11 @@ public class GroovyDslPropertyConverter implements DslPropertyConverter {
return object;
}
List<Object> generatedValues = Arrays.stream(((GString) object).getValues())
.map(it -> it instanceof RegexProperty
? ((RegexProperty) it).generate() : it)
.map(it -> it instanceof RegexProperty ? ((RegexProperty) it).generate() : it)
.collect(Collectors.toList());
Object[] arrayOfObjects = generatedValues.toArray();
String[] strings = Arrays.copyOf(((GString) object).getStrings(),
((GString) object).getStrings().length, String[].class);
String[] strings = Arrays.copyOf(((GString) object).getStrings(), ((GString) object).getStrings().length,
String[].class);
String newUrl = new GStringImpl(arrayOfObjects, strings).toString();
return new Url(newUrl);
}

View File

@@ -393,29 +393,24 @@ public class Contract {
}
Contract contract = (Contract) o;
return ignored == contract.ignored && Objects.equals(priority, contract.priority)
&& Objects.equals(request, contract.request)
&& Objects.equals(response, contract.response)
&& Objects.equals(label, contract.label)
&& Objects.equals(description, contract.description)
&& Objects.equals(name, contract.name)
&& Objects.equals(input, contract.input)
&& Objects.equals(metadata, contract.metadata)
&& Objects.equals(outputMessage, contract.outputMessage);
&& Objects.equals(request, contract.request) && Objects.equals(response, contract.response)
&& Objects.equals(label, contract.label) && Objects.equals(description, contract.description)
&& Objects.equals(name, contract.name) && Objects.equals(input, contract.input)
&& Objects.equals(metadata, contract.metadata) && Objects.equals(outputMessage, contract.outputMessage);
}
@Override
public int hashCode() {
return Objects.hash(priority, request, response, label, description, name, input,
outputMessage, metadata, ignored);
return Objects.hash(priority, request, response, label, description, name, input, outputMessage, metadata,
ignored);
}
@Override
public String toString() {
return "Contract{" + "\npriority=" + priority + ", \n\trequest=" + request
+ ", \n\tresponse=" + response + ", \n\tlabel='" + label + '\''
+ ", \n\tdescription='" + description + '\'' + ", \n\tname='" + name
+ '\'' + ", \n\tinput=" + input + ", \n\toutputMessage=" + outputMessage
+ ", \n\tignored=" + ignored + '}';
return "Contract{" + "\npriority=" + priority + ", \n\trequest=" + request + ", \n\tresponse=" + response
+ ", \n\tlabel='" + label + '\'' + ", \n\tdescription='" + description + '\'' + ", \n\tname='" + name
+ '\'' + ", \n\tinput=" + input + ", \n\toutputMessage=" + outputMessage + ", \n\tignored=" + ignored
+ '}';
}
}

View File

@@ -31,20 +31,16 @@ import java.util.stream.Collectors;
public class Body extends DslProperty {
public Body(Map<String, DslProperty> body) {
super(extractValue(body, ContractUtils.CLIENT_VALUE),
extractValue(body, ContractUtils.SERVER_VALUE));
super(extractValue(body, ContractUtils.CLIENT_VALUE), extractValue(body, ContractUtils.SERVER_VALUE));
}
public Body(List<DslProperty> bodyAsList) {
super(bodyAsList.stream().map(DslProperty::getClientValue)
.collect(Collectors.toList()),
bodyAsList.stream().map(DslProperty::getServerValue)
.collect(Collectors.toList()));
super(bodyAsList.stream().map(DslProperty::getClientValue).collect(Collectors.toList()),
bodyAsList.stream().map(DslProperty::getServerValue).collect(Collectors.toList()));
}
public Body(Object value) {
super(ContractUtils.CLIENT_VALUE.apply(value),
ContractUtils.SERVER_VALUE.apply(value));
super(ContractUtils.CLIENT_VALUE.apply(value), ContractUtils.SERVER_VALUE.apply(value));
}
public Body(Byte[] bodyAsValue) {
@@ -71,8 +67,7 @@ public class Body extends DslProperty {
super(matchingStrategy, matchingStrategy);
}
private static Map<String, Object> extractValue(Map<String, DslProperty> body,
final Function valueProvider) {
private static Map<String, Object> extractValue(Map<String, DslProperty> body, final Function valueProvider) {
final Map<String, Object> map = new LinkedHashMap<String, Object>();
body.forEach((key, value) -> map.put(key, valueProvider.apply(value)));
return map;

View File

@@ -143,8 +143,7 @@ public class BodyMatchers {
* @param consumer function to manipulate the output message
* @return matching type
*/
public MatchingTypeValue byType(
@DelegatesTo(MatchingTypeValueHolder.class) Closure consumer) {
public MatchingTypeValue byType(@DelegatesTo(MatchingTypeValueHolder.class) Closure consumer) {
MatchingTypeValueHolder matchingTypeValue = new MatchingTypeValueHolder();
consumer.setDelegate(matchingTypeValue);
consumer.call();

View File

@@ -39,12 +39,11 @@ import java.util.stream.Collectors;
*/
public class Common {
public Map<String, DslProperty> convertObjectsToDslProperties(
Map<String, Object> body) {
return body.entrySet().stream().collect(Collectors.toMap(
(Function<Map.Entry, String>) t -> t.getKey().toString(),
(Function<Map.Entry, DslProperty>) t -> toDslProperty(t.getValue()),
throwingMerger(), LinkedHashMap::new));
public Map<String, DslProperty> convertObjectsToDslProperties(Map<String, Object> body) {
return body.entrySet().stream()
.collect(Collectors.toMap((Function<Map.Entry, String>) t -> t.getKey().toString(),
(Function<Map.Entry, DslProperty>) t -> toDslProperty(t.getValue()), throwingMerger(),
LinkedHashMap::new));
}
private static <T> BinaryOperator<T> throwingMerger() {
@@ -77,8 +76,7 @@ public class Common {
return new NamedProperty(name, value);
}
public NamedProperty named(DslProperty name, DslProperty value,
DslProperty contentType) {
public NamedProperty named(DslProperty name, DslProperty value, DslProperty contentType) {
return new NamedProperty(name, value, contentType);
}
@@ -241,8 +239,7 @@ public class Common {
* @return file contents as an array of bytes
*/
private File fileLocation(String relativePath) {
URL resource = Thread.currentThread().getContextClassLoader()
.getResource(relativePath);
URL resource = Thread.currentThread().getContextClassLoader().getResource(relativePath);
if (resource == null) {
throw new IllegalStateException("File [" + relativePath + "] is not present");
}
@@ -278,48 +275,38 @@ public class Common {
if (secondSide == null) {
return;
}
assertThat(
secondSide.toString()
.matches(((OptionalProperty) firstSide).optionalPattern()),
"Pattern [" + ((OptionalProperty) firstSide).optionalPattern()
+ "] is not matched by [" + secondSide.toString() + "]");
assertThat(secondSide.toString().matches(((OptionalProperty) firstSide).optionalPattern()),
"Pattern [" + ((OptionalProperty) firstSide).optionalPattern() + "] is not matched by ["
+ secondSide.toString() + "]");
}
else if ((firstSide instanceof Pattern || firstSide instanceof RegexProperty)
&& secondSide instanceof String) {
else if ((firstSide instanceof Pattern || firstSide instanceof RegexProperty) && secondSide instanceof String) {
Pattern pattern = firstSide instanceof Pattern ? (Pattern) firstSide
: ((RegexProperty) firstSide).getPattern();
assertThat(((String) secondSide).toString().matches(pattern.pattern()),
"Pattern [" + pattern.pattern() + "] is not matched by ["
+ secondSide.toString() + "]");
"Pattern [" + pattern.pattern() + "] is not matched by [" + secondSide.toString() + "]");
}
else if ((secondSide instanceof Pattern || secondSide instanceof RegexProperty)
&& firstSide instanceof String) {
Pattern pattern = secondSide instanceof Pattern ? (Pattern) secondSide
: ((RegexProperty) secondSide).getPattern();
assertThat(((String) firstSide).matches(pattern.pattern()),
"Pattern [" + pattern.pattern() + "] is not matched by ["
+ firstSide.toString() + "]");
"Pattern [" + pattern.pattern() + "] is not matched by [" + firstSide.toString() + "]");
}
else if (firstSide instanceof MatchingStrategy
&& secondSide instanceof MatchingStrategy) {
if (((MatchingStrategy) firstSide).getType()
.equals(MatchingStrategy.Type.ABSENT)
&& !((MatchingStrategy) secondSide).getType()
.equals(MatchingStrategy.Type.ABSENT)) {
else if (firstSide instanceof MatchingStrategy && secondSide instanceof MatchingStrategy) {
if (((MatchingStrategy) firstSide).getType().equals(MatchingStrategy.Type.ABSENT)
&& !((MatchingStrategy) secondSide).getType().equals(MatchingStrategy.Type.ABSENT)) {
throwAbsentError();
}
}
else if (firstSide instanceof MatchingStrategy) {
if (((MatchingStrategy) firstSide).getType()
.equals(MatchingStrategy.Type.ABSENT)) {
if (((MatchingStrategy) firstSide).getType().equals(MatchingStrategy.Type.ABSENT)) {
throwAbsentError();
}
}
else if (secondSide instanceof MatchingStrategy) {
if (((MatchingStrategy) secondSide).getType()
.equals(MatchingStrategy.Type.ABSENT)) {
if (((MatchingStrategy) secondSide).getType().equals(MatchingStrategy.Type.ABSENT)) {
throwAbsentError();
}

View File

@@ -20,10 +20,8 @@ import java.util.function.Function;
final class ContractUtils {
static final Function CLIENT_VALUE = o -> o instanceof DslProperty
? ((DslProperty) o).getClientValue() : o;
static final Function SERVER_VALUE = o -> o instanceof DslProperty
? ((DslProperty) o).getServerValue() : o;
static final Function CLIENT_VALUE = o -> o instanceof DslProperty ? ((DslProperty) o).getClientValue() : o;
static final Function SERVER_VALUE = o -> o instanceof DslProperty ? ((DslProperty) o).getServerValue() : o;
private ContractUtils() {
throw new IllegalStateException("Can't instantiate an utility class");

View File

@@ -39,8 +39,7 @@ public class Cookie extends DslProperty {
}
public Cookie(String key, Object value) {
super(ContractUtils.CLIENT_VALUE.apply(value),
ContractUtils.SERVER_VALUE.apply(value));
super(ContractUtils.CLIENT_VALUE.apply(value), ContractUtils.SERVER_VALUE.apply(value));
this.key = key;
}

View File

@@ -86,8 +86,7 @@ public class Cookies {
*/
public Map<String, Object> asStubSideMap() {
final Map<String, Object> map = new LinkedHashMap<>();
entries.forEach(cookie -> map.put(cookie.getKey(),
ContractUtils.convertStubSideRecursively(cookie)));
entries.forEach(cookie -> map.put(cookie.getKey(), ContractUtils.convertStubSideRecursively(cookie)));
return map;
}
@@ -98,8 +97,7 @@ public class Cookies {
*/
public Map<String, Object> asTestSideMap() {
final Map<String, Object> map = new HashMap<String, Object>();
entries.forEach(cookie -> map.put(cookie.getKey(),
ContractUtils.convertTestSideRecursively(cookie)));
entries.forEach(cookie -> map.put(cookie.getKey(), ContractUtils.convertTestSideRecursively(cookie)));
return map;
}

View File

@@ -42,8 +42,7 @@ public class DslProperty<T> implements Serializable {
}
public boolean isSingleValue() {
return this.clientValue.equals(this.serverValue)
|| (this.clientValue != null && this.serverValue == null)
return this.clientValue.equals(this.serverValue) || (this.clientValue != null && this.serverValue == null)
|| (this.serverValue != null && this.clientValue == null);
}
@@ -60,8 +59,7 @@ public class DslProperty<T> implements Serializable {
Object thatClientValue = stringPatternIfPattern(that.clientValue);
Object thisServerValue = stringPatternIfPattern(serverValue);
Object thatServerValue = stringPatternIfPattern(that.serverValue);
return Objects.equals(thisClientValue, thatClientValue)
&& Objects.equals(thisServerValue, thatServerValue);
return Objects.equals(thisClientValue, thatClientValue) && Objects.equals(thisServerValue, thatServerValue);
}
private Object stringPatternIfPattern(Object value) {
@@ -70,14 +68,13 @@ public class DslProperty<T> implements Serializable {
@Override
public int hashCode() {
return Objects.hash(stringPatternIfPattern(clientValue),
stringPatternIfPattern(serverValue));
return Objects.hash(stringPatternIfPattern(clientValue), stringPatternIfPattern(serverValue));
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" + "\nclientValue=" + clientValue
+ ", \n\tserverValue=" + serverValue + '}';
return getClass().getSimpleName() + "{" + "\nclientValue=" + clientValue + ", \n\tserverValue=" + serverValue
+ '}';
}
public final T getClientValue() {

View File

@@ -48,8 +48,7 @@ public interface DslPropertyConverter {
if (INSTANCE != null) {
return INSTANCE;
}
List<DslPropertyConverter> converters = SpringFactoriesLoader
.loadFactories(DslPropertyConverter.class, null);
List<DslPropertyConverter> converters = SpringFactoriesLoader.loadFactories(DslPropertyConverter.class, null);
if (converters.isEmpty()) {
return DEFAULT;
}

View File

@@ -119,8 +119,7 @@ public class HandlebarsContractTemplate implements ContractTemplate {
@Override
public String escapedQuery(String key, int index) {
return escapedWrapped(
"request.query." + key + ".[" + String.valueOf(index) + "]");
return escapedWrapped("request.query." + key + ".[" + String.valueOf(index) + "]");
}
@Override
@@ -140,8 +139,7 @@ public class HandlebarsContractTemplate implements ContractTemplate {
@Override
public String escapedHeader(String key, int index) {
return escapedWrapped(
"request.headers." + key + ".[" + String.valueOf(index) + "]");
return escapedWrapped("request.headers." + key + ".[" + String.valueOf(index) + "]");
}
@Override

View File

@@ -38,8 +38,7 @@ public class Header extends DslProperty {
}
public Header(String name, Object value) {
super(ContractUtils.CLIENT_VALUE.apply(value),
ContractUtils.SERVER_VALUE.apply(value));
super(ContractUtils.CLIENT_VALUE.apply(value), ContractUtils.SERVER_VALUE.apply(value));
this.name = name;
}

View File

@@ -36,11 +36,11 @@ import java.util.regex.Pattern;
*/
public class Headers {
private static final BiFunction<String, Header, Object> CLIENT_SIDE = (s,
header) -> ContractUtils.convertStubSideRecursively(header);
private static final BiFunction<String, Header, Object> CLIENT_SIDE = (s, header) -> ContractUtils
.convertStubSideRecursively(header);
private static final BiFunction<String, Header, Object> SERVER_SIDE = (s,
header) -> ContractUtils.convertTestSideRecursively(header);
private static final BiFunction<String, Header, Object> SERVER_SIDE = (s, header) -> ContractUtils
.convertTestSideRecursively(header);
private Set<Header> entries = new LinkedHashSet<>();
@@ -95,8 +95,7 @@ public class Headers {
public Map<String, Object> asMap(final BiFunction<String, Header, Object> consumer) {
final Map<String, Object> map = new LinkedHashMap<>();
entries.forEach(header -> map.put(header.getName(),
consumer.apply(header.getName(), header)));
entries.forEach(header -> map.put(header.getName(), consumer.apply(header.getName(), header)));
return map;
}

View File

@@ -31,8 +31,7 @@ public final class HttpMethods {
private static final Log log = LogFactory.getLog(HttpMethods.class);
public HttpMethods() {
log.warn(
"WARNING: HttpMethods shouldn't be instantiated. Use its static methods instead.");
log.warn("WARNING: HttpMethods shouldn't be instantiated. Use its static methods instead.");
}
/**
@@ -149,10 +148,8 @@ public final class HttpMethods {
public enum HttpMethod {
GET(HttpMethods.GET), HEAD(HttpMethods.HEAD), POST(HttpMethods.POST), PUT(
HttpMethods.PUT), PATCH(HttpMethods.PATCH), DELETE(
HttpMethods.DELETE), OPTIONS(
HttpMethods.OPTIONS), TRACE(HttpMethods.TRACE),;
GET(HttpMethods.GET), HEAD(HttpMethods.HEAD), POST(HttpMethods.POST), PUT(HttpMethods.PUT), PATCH(
HttpMethods.PATCH), DELETE(HttpMethods.DELETE), OPTIONS(HttpMethods.OPTIONS), TRACE(HttpMethods.TRACE),;
private final String methodName;

View File

@@ -31,8 +31,7 @@ public final class HttpStatus {
private static final Log log = LogFactory.getLog(HttpStatus.class);
public HttpStatus() {
log.warn(
"WARNING: HttpStatus shouldn't be instantiated. Use its static methods instead.");
log.warn("WARNING: HttpStatus shouldn't be instantiated. Use its static methods instead.");
}
/**

View File

@@ -357,26 +357,22 @@ public class Input extends Common implements RegexCreatingProperty<ClientDslProp
return false;
}
Input input = (Input) o;
return Objects.equals(messageFrom, input.messageFrom)
&& Objects.equals(triggeredBy, input.triggeredBy)
return Objects.equals(messageFrom, input.messageFrom) && Objects.equals(triggeredBy, input.triggeredBy)
&& Objects.equals(messageHeaders, input.messageHeaders)
&& Objects.equals(messageBody, input.messageBody)
&& Objects.equals(assertThat, input.assertThat)
&& Objects.equals(messageBody, input.messageBody) && Objects.equals(assertThat, input.assertThat)
&& Objects.equals(bodyMatchers, input.bodyMatchers);
}
@Override
public int hashCode() {
return Objects.hash(messageFrom, triggeredBy, messageHeaders, messageBody,
assertThat, bodyMatchers);
return Objects.hash(messageFrom, triggeredBy, messageHeaders, messageBody, assertThat, bodyMatchers);
}
@Override
public String toString() {
return "Input{\n\tmessageFrom=" + messageFrom + ", \n\ttriggeredBy=" + triggeredBy
+ ", \n\tmessageHeaders=" + messageHeaders + ", \n\tmessageBody="
+ messageBody + ", \n\tassertThat=" + assertThat + ", \n\tbodyMatchers="
+ bodyMatchers + "} \n\t" + super.toString();
return "Input{\n\tmessageFrom=" + messageFrom + ", \n\ttriggeredBy=" + triggeredBy + ", \n\tmessageHeaders="
+ messageHeaders + ", \n\tmessageBody=" + messageBody + ", \n\tassertThat=" + assertThat
+ ", \n\tbodyMatchers=" + bodyMatchers + "} \n\t" + super.toString();
}
public static class BodyType extends DslProperty {
@@ -391,12 +387,10 @@ public class Input extends Common implements RegexCreatingProperty<ClientDslProp
}
private class ClientPatternValueDslProperty
extends PatternValueDslProperty<ClientDslProperty> {
private class ClientPatternValueDslProperty extends PatternValueDslProperty<ClientDslProperty> {
@Override
protected ClientDslProperty createProperty(Pattern pattern,
Object generatedValue) {
protected ClientDslProperty createProperty(Pattern pattern, Object generatedValue) {
return new ClientDslProperty(pattern, generatedValue);
}

View File

@@ -43,8 +43,7 @@ public class MatchingStrategy extends DslProperty {
this(value, type, null);
}
public MatchingStrategy(DslProperty value, Type type,
JSONCompareMode jsonCompareMode) {
public MatchingStrategy(DslProperty value, Type type, JSONCompareMode jsonCompareMode) {
super(value.getClientValue(), value.getServerValue());
this.type = type;
this.jsonCompareMode = jsonCompareMode;
@@ -68,8 +67,7 @@ public class MatchingStrategy extends DslProperty {
@Override
public String toString() {
return "MatchingStrategy{" + "type=" + type + ", jsonCompareMode="
+ jsonCompareMode + '}';
return "MatchingStrategy{" + "type=" + type + ", jsonCompareMode=" + jsonCompareMode + '}';
}
@Override

View File

@@ -62,8 +62,7 @@ public enum MatchingType {
NULL;
public static boolean regexRelated(MatchingType type) {
return !type.equals(EQUALITY) && !type.equals(TYPE) && !type.equals(COMMAND)
&& !type.equals(NULL);
return !type.equals(EQUALITY) && !type.equals(TYPE) && !type.equals(COMMAND) && !type.equals(NULL);
}
}

View File

@@ -58,8 +58,7 @@ public class MatchingTypeValue {
this.minTypeOccurrence = minTypeOccurrence;
}
MatchingTypeValue(MatchingType type, Object value, Integer minTypeOccurrence,
Integer maxTypeOccurrence) {
MatchingTypeValue(MatchingType type, Object value, Integer minTypeOccurrence, Integer maxTypeOccurrence) {
this.type = type;
this.value = value;
this.minTypeOccurrence = minTypeOccurrence;
@@ -119,9 +118,8 @@ public class MatchingTypeValue {
@Override
public String toString() {
return "MatchingTypeValue{" + "type=" + type + ", value=" + value
+ ", minTypeOccurrence=" + minTypeOccurrence + ", maxTypeOccurrence="
+ maxTypeOccurrence + '}';
return "MatchingTypeValue{" + "type=" + type + ", value=" + value + ", minTypeOccurrence=" + minTypeOccurrence
+ ", maxTypeOccurrence=" + maxTypeOccurrence + '}';
}
}

View File

@@ -31,8 +31,7 @@ public class MediaTypes {
private static final Log log = LogFactory.getLog(MediaTypes.class);
public MediaTypes() {
log.warn(
"WARNING: MediaTypes shouldn't be instantiated. Use its static methods instead.");
log.warn("WARNING: MediaTypes shouldn't be instantiated. Use its static methods instead.");
}
/**
@@ -58,8 +57,7 @@ public class MediaTypes {
/**
* Public constant for {@code application/json;charset=UTF-8}.
*/
public static final String APPLICATION_JSON_UTF8 = APPLICATION_JSON
+ ";charset=UTF-8";
public static final String APPLICATION_JSON_UTF8 = APPLICATION_JSON + ";charset=UTF-8";
/**
* Public constant for {@code application/octet-stream}.

View File

@@ -31,8 +31,7 @@ public class MessagingHeaders {
private static final Log log = LogFactory.getLog(MessagingHeaders.class);
public MessagingHeaders() {
log.warn(
"WARNING: MessagingHeaders shouldn't be instantiated. Use its static methods instead.");
log.warn("WARNING: MessagingHeaders shouldn't be instantiated. Use its static methods instead.");
}
/**

View File

@@ -25,20 +25,16 @@ import java.util.stream.Collectors;
public class Multipart extends DslProperty {
public Multipart(Map<String, DslProperty> multipart) {
super(extractValue(multipart, ContractUtils.CLIENT_VALUE),
extractValue(multipart, ContractUtils.SERVER_VALUE));
super(extractValue(multipart, ContractUtils.CLIENT_VALUE), extractValue(multipart, ContractUtils.SERVER_VALUE));
}
public Multipart(List<DslProperty> multipartAsList) {
super(multipartAsList.stream().map(DslProperty::getClientValue)
.collect(Collectors.toList()),
multipartAsList.stream().map(DslProperty::getServerValue)
.collect(Collectors.toList()));
super(multipartAsList.stream().map(DslProperty::getClientValue).collect(Collectors.toList()),
multipartAsList.stream().map(DslProperty::getServerValue).collect(Collectors.toList()));
}
public Multipart(Object value) {
super(ContractUtils.CLIENT_VALUE.apply(value),
ContractUtils.SERVER_VALUE.apply(value));
super(ContractUtils.CLIENT_VALUE.apply(value), ContractUtils.SERVER_VALUE.apply(value));
}
public Multipart(DslProperty multipartAsValue) {
@@ -56,11 +52,9 @@ public class Multipart extends DslProperty {
return new Multipart(value);
}
private static Map<String, Object> extractValue(Map<String, DslProperty> multipart,
final Function valueProvider) {
private static Map<String, Object> extractValue(Map<String, DslProperty> multipart, final Function valueProvider) {
final Map<String, Object> map = new LinkedHashMap<String, Object>();
multipart.forEach(
(s, dslProperty) -> map.put(s, valueProvider.apply(dslProperty)));
multipart.forEach((s, dslProperty) -> map.put(s, valueProvider.apply(dslProperty)));
return map;
}

View File

@@ -51,8 +51,7 @@ public class NamedProperty {
}
public NamedProperty(Map<String, DslProperty> namedMap) {
this(asDslProperty(value(namedMap, NAME)),
asDslProperty(value(namedMap, CONTENT)),
this(asDslProperty(value(namedMap, NAME)), asDslProperty(value(namedMap, CONTENT)),
asDslProperty(value(namedMap, CONTENT_TYPE)));
}
@@ -120,8 +119,7 @@ public class NamedProperty {
@Override
public String toString() {
return "NamedProperty{" + "name=" + name + ", value=" + value + ", contentType="
+ contentType + '}';
return "NamedProperty{" + "name=" + name + ", value=" + value + ", contentType=" + contentType + '}';
}
}

View File

@@ -33,8 +33,7 @@ import org.apache.commons.logging.LogFactory;
* @author Tim Ysewyn
* @since 1.0.0
*/
public class OutputMessage extends Common
implements RegexCreatingProperty<ServerDslProperty> {
public class OutputMessage extends Common implements RegexCreatingProperty<ServerDslProperty> {
private static final Log log = LogFactory.getLog(OutputMessage.class);
@@ -86,8 +85,7 @@ public class OutputMessage extends Common
*/
@Deprecated
public DslProperty value(ClientDslProperty clientDslProperty) {
return value(new ServerDslProperty(clientDslProperty.getServerValue(),
clientDslProperty.getClientValue()));
return value(new ServerDslProperty(clientDslProperty.getServerValue(), clientDslProperty.getClientValue()));
}
public DslProperty value(ServerDslProperty serverDslProperty) {
@@ -361,10 +359,8 @@ public class OutputMessage extends Common
return false;
}
OutputMessage that = (OutputMessage) o;
return Objects.equals(sentTo, that.sentTo)
&& Objects.equals(headers, that.headers)
&& Objects.equals(body, that.body)
&& Objects.equals(assertThat, that.assertThat)
return Objects.equals(sentTo, that.sentTo) && Objects.equals(headers, that.headers)
&& Objects.equals(body, that.body) && Objects.equals(assertThat, that.assertThat)
&& Objects.equals(bodyMatchers, that.bodyMatchers);
}
@@ -375,17 +371,14 @@ public class OutputMessage extends Common
@Override
public String toString() {
return "OutputMessage{" + "\n\tsentTo=" + sentTo + ", \n\theaders=" + headers
+ ", \n\tbody=" + body + ", \n\tassertThat=" + assertThat
+ ", \n\tbodyMatchers=" + bodyMatchers + "} \n\t" + super.toString();
return "OutputMessage{" + "\n\tsentTo=" + sentTo + ", \n\theaders=" + headers + ", \n\tbody=" + body
+ ", \n\tassertThat=" + assertThat + ", \n\tbodyMatchers=" + bodyMatchers + "} \n\t" + super.toString();
}
private class ServerPatternValueDslProperty
extends PatternValueDslProperty<ServerDslProperty> {
private class ServerPatternValueDslProperty extends PatternValueDslProperty<ServerDslProperty> {
@Override
protected ServerDslProperty createProperty(Pattern pattern,
Object generatedValue) {
protected ServerDslProperty createProperty(Pattern pattern, Object generatedValue) {
return new ServerDslProperty(pattern, generatedValue);
}

View File

@@ -66,8 +66,7 @@ public class PathBodyMatcher implements BodyMatcher {
return false;
}
PathBodyMatcher that = (PathBodyMatcher) o;
return Objects.equals(path, that.path)
&& Objects.equals(matchingTypeValue, that.matchingTypeValue);
return Objects.equals(path, that.path) && Objects.equals(matchingTypeValue, that.matchingTypeValue);
}
@Override
@@ -77,8 +76,7 @@ public class PathBodyMatcher implements BodyMatcher {
@Override
public String toString() {
return "PathBodyMatcher{" + "path='" + path + '\'' + ", matchingTypeValue="
+ matchingTypeValue + '}';
return "PathBodyMatcher{" + "path='" + path + '\'' + ", matchingTypeValue=" + matchingTypeValue + '}';
}
}

View File

@@ -26,8 +26,7 @@ import org.apache.commons.lang3.RandomStringUtils;
* @author Marcin Grzejszczak
* @author Tim Ysewyn
*/
abstract class PatternValueDslProperty<T extends DslProperty>
implements RegexCreatingProperty<T> {
abstract class PatternValueDslProperty<T extends DslProperty> implements RegexCreatingProperty<T> {
private final Random random = new Random();
@@ -61,14 +60,12 @@ abstract class PatternValueDslProperty<T extends DslProperty>
@Override
public T anyAlphaUnicode() {
return createAndValidateProperty(RegexPatterns.ONLY_ALPHA_UNICODE,
RandomStringGenerator.randomString(20));
return createAndValidateProperty(RegexPatterns.ONLY_ALPHA_UNICODE, RandomStringGenerator.randomString(20));
}
@Override
public T anyAlphaNumeric() {
return createAndValidateProperty(RegexPatterns.ALPHA_NUMERIC,
RandomStringUtils.randomAlphanumeric(20));
return createAndValidateProperty(RegexPatterns.ALPHA_NUMERIC, RandomStringUtils.randomAlphanumeric(20));
}
@Override
@@ -83,20 +80,17 @@ abstract class PatternValueDslProperty<T extends DslProperty>
@Override
public T anyPositiveInt() {
return createAndValidateProperty(RegexPatterns.POSITIVE_INT,
Math.abs(this.random.nextInt() + 1));
return createAndValidateProperty(RegexPatterns.POSITIVE_INT, Math.abs(this.random.nextInt() + 1));
}
@Override
public T anyDouble() {
return createAndValidateProperty(RegexPatterns.DOUBLE,
this.random.nextInt(100) + this.random.nextDouble());
return createAndValidateProperty(RegexPatterns.DOUBLE, this.random.nextInt(100) + this.random.nextDouble());
}
@Override
public T anyHex() {
return createAndValidateProperty(RegexPatterns.HEX,
RandomStringUtils.random(10, "0123456789abcdef"));
return createAndValidateProperty(RegexPatterns.HEX, RandomStringUtils.random(10, "0123456789abcdef"));
}
@Override
@@ -106,8 +100,7 @@ abstract class PatternValueDslProperty<T extends DslProperty>
@Override
public T anyIpAddress() {
return createAndValidateProperty(RegexPatterns.IP_ADDRESS,
"192.168.0." + this.random.nextInt(10));
return createAndValidateProperty(RegexPatterns.IP_ADDRESS, "192.168.0." + this.random.nextInt(10));
}
@Override
@@ -118,68 +111,59 @@ abstract class PatternValueDslProperty<T extends DslProperty>
@Override
public T anyEmail() {
return createAndValidateProperty(RegexPatterns.EMAIL,
"foo@bar" + this.random.nextInt() + ".com");
return createAndValidateProperty(RegexPatterns.EMAIL, "foo@bar" + this.random.nextInt() + ".com");
}
@Override
public T anyUrl() {
return createAndValidateProperty(RegexPatterns.URL,
"https://foo" + this.random.nextInt() + ".com");
return createAndValidateProperty(RegexPatterns.URL, "https://foo" + this.random.nextInt() + ".com");
}
@Override
public T anyHttpsUrl() {
return createAndValidateProperty(RegexPatterns.HTTPS_URL,
"https://baz" + this.random.nextInt() + ".com");
return createAndValidateProperty(RegexPatterns.HTTPS_URL, "https://baz" + this.random.nextInt() + ".com");
}
@Override
public T anyUuid() {
return createAndValidateProperty(RegexPatterns.UUID,
UUID.randomUUID().toString());
return createAndValidateProperty(RegexPatterns.UUID, UUID.randomUUID().toString());
}
@Override
public T anyDate() {
int d = this.random.nextInt(8) + 1;
return createAndValidateProperty(RegexPatterns.ANY_DATE, "201" + String.valueOf(d)
+ "-0" + String.valueOf(d) + "-1" + String.valueOf(d));
return createAndValidateProperty(RegexPatterns.ANY_DATE,
"201" + String.valueOf(d) + "-0" + String.valueOf(d) + "-1" + String.valueOf(d));
}
@Override
public T anyDateTime() {
final int d = this.random.nextInt(8) + 1;
return createAndValidateProperty(RegexPatterns.ANY_DATE_TIME,
"201" + String.valueOf(d) + "-0" + String.valueOf(d) + "-1"
+ String.valueOf(d) + "T12:23:34");
"201" + String.valueOf(d) + "-0" + String.valueOf(d) + "-1" + String.valueOf(d) + "T12:23:34");
}
@Override
public T anyTime() {
int d = this.random.nextInt(9);
return createAndValidateProperty(RegexPatterns.ANY_TIME,
"12:2" + String.valueOf(d) + ":3" + String.valueOf(d));
return createAndValidateProperty(RegexPatterns.ANY_TIME, "12:2" + String.valueOf(d) + ":3" + String.valueOf(d));
}
@Override
public T anyIso8601WithOffset() {
final int d = this.random.nextInt(8) + 1;
return createAndValidateProperty(RegexPatterns.ISO8601_WITH_OFFSET,
"201" + String.valueOf(d) + "-0" + String.valueOf(d) + "-1"
+ String.valueOf(d) + "T12:23:34.123Z");
"201" + String.valueOf(d) + "-0" + String.valueOf(d) + "-1" + String.valueOf(d) + "T12:23:34.123Z");
}
@Override
public T anyNonBlankString() {
return createAndValidateProperty(RegexPatterns.NON_BLANK,
RandomStringGenerator.randomString(20));
return createAndValidateProperty(RegexPatterns.NON_BLANK, RandomStringGenerator.randomString(20));
}
@Override
public T anyNonEmptyString() {
return createAndValidateProperty(RegexPatterns.NON_EMPTY,
RandomStringGenerator.randomString(20));
return createAndValidateProperty(RegexPatterns.NON_EMPTY, RandomStringGenerator.randomString(20));
}
@Override

View File

@@ -31,23 +31,19 @@ public class QueryParameter extends DslProperty {
public QueryParameter(String name, DslProperty dslProperty) {
super(dslProperty.getClientValue(), dslProperty.getServerValue());
ValidateUtils.validateServerValueIsAvailable(dslProperty.getServerValue(),
"Query parameter \'" + name + "\'");
ValidateUtils.validateServerValueIsAvailable(dslProperty.getServerValue(), "Query parameter \'" + name + "\'");
this.name = name;
}
public QueryParameter(String name, MatchingStrategy matchingStrategy) {
super(matchingStrategy);
ValidateUtils.validateServerValueIsAvailable(matchingStrategy,
"Query parameter \'" + name + "\'");
ValidateUtils.validateServerValueIsAvailable(matchingStrategy, "Query parameter \'" + name + "\'");
this.name = name;
}
public QueryParameter(String name, Object value) {
super(ContractUtils.CLIENT_VALUE.apply(value),
ContractUtils.SERVER_VALUE.apply(value));
ValidateUtils.validateServerValueIsAvailable(value,
"Query parameter \'" + name + "\'");
super(ContractUtils.CLIENT_VALUE.apply(value), ContractUtils.SERVER_VALUE.apply(value));
ValidateUtils.validateServerValueIsAvailable(value, "Query parameter \'" + name + "\'");
this.name = name;
}
@@ -56,8 +52,7 @@ public class QueryParameter extends DslProperty {
return new QueryParameter(key, (MatchingStrategy) value);
}
else if (value instanceof RegexProperty) {
return new QueryParameter(key,
((RegexProperty) value).dynamicClientEscapedConcreteProducer());
return new QueryParameter(key, ((RegexProperty) value).dynamicClientEscapedConcreteProducer());
}
return new QueryParameter(key, value);
}
@@ -92,8 +87,7 @@ public class QueryParameter extends DslProperty {
@Override
public String toString() {
return "QueryParameter{" + "name='" + name + '\'' + ", value=" + super.toString()
+ '}';
return "QueryParameter{" + "name='" + name + '\'' + ", value=" + super.toString() + '}';
}
}

View File

@@ -27,8 +27,7 @@ public class QueryParameters {
private List<QueryParameter> parameters = new LinkedList<QueryParameter>();
public void parameter(Map<String, Object> singleParameter) {
Iterator<Map.Entry<String, Object>> iterator = singleParameter.entrySet()
.iterator();
Iterator<Map.Entry<String, Object>> iterator = singleParameter.entrySet().iterator();
if (iterator.hasNext()) {
Map.Entry<String, Object> first = iterator.next();
if (first != null) {

View File

@@ -21,8 +21,7 @@ package org.springframework.cloud.contract.spec.internal;
*/
public class RegexMatchingTypeValue extends MatchingTypeValue {
RegexMatchingTypeValue(MatchingType type, Object value, Integer minTypeOccurrence,
Integer maxTypeOccurrence) {
RegexMatchingTypeValue(MatchingType type, Object value, Integer minTypeOccurrence, Integer maxTypeOccurrence) {
super(type, value, minTypeOccurrence, maxTypeOccurrence);
}
@@ -40,8 +39,7 @@ public class RegexMatchingTypeValue extends MatchingTypeValue {
}
RegexProperty regexProperty = (RegexProperty) this.getValue();
return new RegexMatchingTypeValue(this.getType(),
new RegexProperty(regexProperty.getClientValue(),
regexProperty.getServerValue(), clazz),
new RegexProperty(regexProperty.getClientValue(), regexProperty.getServerValue(), clazz),
this.getMinTypeOccurrence(), this.getMaxTypeOccurrence());
}

View File

@@ -35,8 +35,7 @@ public final class RegexPatterns {
private static final Log log = LogFactory.getLog(RegexPatterns.class);
public RegexPatterns() {
log.warn(
"WARNING: RegexPatterns shouldn't be instantiated. Use its static methods instead.");
log.warn("WARNING: RegexPatterns shouldn't be instantiated. Use its static methods instead.");
}
protected static final Pattern TRUE_OR_FALSE = Pattern.compile("(true|false)");
@@ -58,11 +57,9 @@ public final class RegexPatterns {
protected static final Pattern IP_ADDRESS = Pattern.compile(
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])");
protected static final Pattern HOSTNAME_PATTERN = Pattern
.compile("((http[s]?|ftp):/)/?([^:/\\s]+)(:[0-9]{1,5})?");
protected static final Pattern HOSTNAME_PATTERN = Pattern.compile("((http[s]?|ftp):/)/?([^:/\\s]+)(:[0-9]{1,5})?");
protected static final Pattern EMAIL = Pattern
.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}");
protected static final Pattern EMAIL = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}");
protected static final Pattern URL = UrlHelper.URL;
@@ -77,8 +74,7 @@ public final class RegexPatterns {
protected static final Pattern ANY_DATE_TIME = Pattern.compile(
"([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
protected static final Pattern ANY_TIME = Pattern
.compile("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
protected static final Pattern ANY_TIME = Pattern.compile("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
protected static final Pattern NON_EMPTY = Pattern.compile("[\\S\\s]+");
@@ -88,8 +84,7 @@ public final class RegexPatterns {
"([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\\.\\d+)?(Z|[+-][01]\\d:[0-5]\\d)");
protected static Pattern anyOf(String... values) {
return Pattern.compile(Arrays.stream(values).map(it -> '^' + it + '$')
.collect(Collectors.joining("|")));
return Pattern.compile(Arrays.stream(values).map(it -> '^' + it + '$').collect(Collectors.joining("|")));
}
public static String multipartParam(Object name, Object value) {
@@ -98,13 +93,10 @@ public final class RegexPatterns {
+ value + "\r\n--\\1.*";
}
public static String multipartFile(Object name, Object filename, Object content,
Object contentType) {
return ".*--(.*)\r\nContent-Disposition: form-data; name=\"" + name
+ "\"; filename=\"" + filename + "\"\r\n(Content-Type: "
+ toContentType(contentType)
+ "\r\n)?(Content-Transfer-Encoding: .*\r\n)?(Content-Length: \\d+\r\n)?\r\n"
+ content + "\r\n--\\1.*";
public static String multipartFile(Object name, Object filename, Object content, Object contentType) {
return ".*--(.*)\r\nContent-Disposition: form-data; name=\"" + name + "\"; filename=\"" + filename
+ "\"\r\n(Content-Type: " + toContentType(contentType)
+ "\r\n)?(Content-Transfer-Encoding: .*\r\n)?(Content-Length: \\d+\r\n)?\r\n" + content + "\r\n--\\1.*";
}
private static String toContentType(Object contentType) {

View File

@@ -44,10 +44,8 @@ public class RegexProperty extends DslProperty implements CanBeDynamic {
public RegexProperty(Object client, Object server, Class clazz) {
super(client, server);
boolean clientDynamic = client instanceof Pattern
|| client instanceof RegexProperty;
boolean serverDynamic = server instanceof Pattern
|| server instanceof RegexProperty;
boolean clientDynamic = client instanceof Pattern || client instanceof RegexProperty;
boolean serverDynamic = server instanceof Pattern || server instanceof RegexProperty;
if (!clientDynamic && !serverDynamic) {
throw new IllegalStateException("Neither client not server side is dynamic");
}
@@ -80,38 +78,31 @@ public class RegexProperty extends DslProperty implements CanBeDynamic {
}
public RegexProperty asInteger() {
return new RegexProperty(this.getClientValue(), this.getServerValue(),
Integer.class);
return new RegexProperty(this.getClientValue(), this.getServerValue(), Integer.class);
}
public RegexProperty asDouble() {
return new RegexProperty(this.getClientValue(), this.getServerValue(),
Double.class);
return new RegexProperty(this.getClientValue(), this.getServerValue(), Double.class);
}
public RegexProperty asFloat() {
return new RegexProperty(this.getClientValue(), this.getServerValue(),
Float.class);
return new RegexProperty(this.getClientValue(), this.getServerValue(), Float.class);
}
public RegexProperty asLong() {
return new RegexProperty(this.getClientValue(), this.getServerValue(),
Long.class);
return new RegexProperty(this.getClientValue(), this.getServerValue(), Long.class);
}
public RegexProperty asShort() {
return new RegexProperty(this.getClientValue(), this.getServerValue(),
Short.class);
return new RegexProperty(this.getClientValue(), this.getServerValue(), Short.class);
}
public RegexProperty asString() {
return new RegexProperty(this.getClientValue(), this.getServerValue(),
String.class);
return new RegexProperty(this.getClientValue(), this.getServerValue(), String.class);
}
public RegexProperty asBooleanType() {
return new RegexProperty(this.getClientValue(), this.getServerValue(),
Boolean.class);
return new RegexProperty(this.getClientValue(), this.getServerValue(), Boolean.class);
}
public Object generate() {
@@ -171,13 +162,11 @@ public class RegexProperty extends DslProperty implements CanBeDynamic {
}
public RegexProperty concreteClientEscapedDynamicProducer() {
return new RegexProperty(generateAndEscapeJavaStringIfNeeded(), this.pattern,
this.clazz);
return new RegexProperty(generateAndEscapeJavaStringIfNeeded(), this.pattern, this.clazz);
}
public RegexProperty dynamicClientEscapedConcreteProducer() {
return new RegexProperty(this.pattern, generateAndEscapeJavaStringIfNeeded(),
this.clazz);
return new RegexProperty(this.pattern, generateAndEscapeJavaStringIfNeeded(), this.clazz);
}
@Override
@@ -189,8 +178,7 @@ public class RegexProperty extends DslProperty implements CanBeDynamic {
return false;
}
RegexProperty that = (RegexProperty) o;
return Objects.equals(stringPatternIfPresent(pattern),
stringPatternIfPresent(that.pattern))
return Objects.equals(stringPatternIfPresent(pattern), stringPatternIfPresent(that.pattern))
&& Objects.equals(clazz, that.clazz);
}

View File

@@ -277,8 +277,7 @@ public class Request extends Common implements RegexCreatingProperty<ClientDslPr
@Override
public void assertThatSidesMatch(Object stubSide, Object testSide) {
if (testSide instanceof OptionalProperty) {
throw new IllegalStateException(
"Optional can be used only for the stub side of the request!");
throw new IllegalStateException("Optional can be used only for the stub side of the request!");
}
super.assertThatSidesMatch(stubSide, testSide);
}
@@ -360,8 +359,7 @@ public class Request extends Common implements RegexCreatingProperty<ClientDslPr
@Override
public DslProperty value(ClientDslProperty client, ServerDslProperty server) {
if (server.getClientValue() instanceof RegexProperty) {
throw new IllegalStateException(
"You can't have a regular expression for the request on the server side");
throw new IllegalStateException("You can't have a regular expression for the request on the server side");
}
return super.value(client, server);
}
@@ -375,8 +373,7 @@ public class Request extends Common implements RegexCreatingProperty<ClientDslPr
@Override
public DslProperty value(ServerDslProperty server, ClientDslProperty client) {
if (server.getClientValue() instanceof RegexProperty) {
throw new IllegalStateException(
"You can't have a regular expression for the request on the server side");
throw new IllegalStateException("You can't have a regular expression for the request on the server side");
}
return super.value(server, client);
@@ -593,25 +590,20 @@ public class Request extends Common implements RegexCreatingProperty<ClientDslPr
}
Request request = (Request) o;
return Objects.equals(method, request.method) && Objects.equals(url, request.url)
&& Objects.equals(urlPath, request.urlPath)
&& Objects.equals(headers, request.headers)
&& Objects.equals(cookies, request.cookies)
&& Objects.equals(body, request.body)
&& Objects.equals(multipart, request.multipart)
&& Objects.equals(bodyMatchers, request.bodyMatchers);
&& Objects.equals(urlPath, request.urlPath) && Objects.equals(headers, request.headers)
&& Objects.equals(cookies, request.cookies) && Objects.equals(body, request.body)
&& Objects.equals(multipart, request.multipart) && Objects.equals(bodyMatchers, request.bodyMatchers);
}
@Override
public int hashCode() {
return Objects.hash(method, url, urlPath, headers, cookies, body, multipart,
bodyMatchers);
return Objects.hash(method, url, urlPath, headers, cookies, body, multipart, bodyMatchers);
}
@Override
public String toString() {
return "Request{" + "\nmethod=" + method + ", \n\turl=" + url + ", \n\turlPath="
+ urlPath + ", \n\theaders=" + headers + ", \n\tcookies=" + cookies
+ ", \n\tbody=" + body + ", \n\tmultipart=" + multipart
return "Request{" + "\nmethod=" + method + ", \n\turl=" + url + ", \n\turlPath=" + urlPath + ", \n\theaders="
+ headers + ", \n\tcookies=" + cookies + ", \n\tbody=" + body + ", \n\tmultipart=" + multipart
+ ", \n\tbodyMatchers=" + bodyMatchers + '}';
}
@@ -790,8 +782,8 @@ public class Request extends Common implements RegexCreatingProperty<ClientDslPr
@Override
public DslProperty matching(String value) {
return this.common.$(this.common.c(this.common
.regex(RegexpUtils.escapeSpecialRegexWithSingleEscape(value) + ".*")),
return this.common.$(
this.common.c(this.common.regex(RegexpUtils.escapeSpecialRegexWithSingleEscape(value) + ".*")),
this.common.p(value));
}
@@ -803,8 +795,8 @@ public class Request extends Common implements RegexCreatingProperty<ClientDslPr
@Override
public DslProperty matching(String value) {
return this.common.$(this.common.c(this.common
.regex(RegexpUtils.escapeSpecialRegexWithSingleEscape(value) + ".*")),
return this.common.$(
this.common.c(this.common.regex(RegexpUtils.escapeSpecialRegexWithSingleEscape(value) + ".*")),
this.common.p(value));
}
@@ -826,12 +818,10 @@ public class Request extends Common implements RegexCreatingProperty<ClientDslPr
}
private class ClientPatternValueDslProperty
extends PatternValueDslProperty<ClientDslProperty> {
private class ClientPatternValueDslProperty extends PatternValueDslProperty<ClientDslProperty> {
@Override
protected ClientDslProperty createProperty(Pattern pattern,
Object generatedValue) {
protected ClientDslProperty createProperty(Pattern pattern, Object generatedValue) {
return new ClientDslProperty(pattern, generatedValue);
}

View File

@@ -131,8 +131,7 @@ public class Response extends Common implements RegexCreatingProperty<ServerDslP
@Override
public void assertThatSidesMatch(Object stubSide, Object testSide) {
if (stubSide instanceof OptionalProperty) {
throw new IllegalStateException(
"Optional can be used only in the test side of the response!");
throw new IllegalStateException("Optional can be used only in the test side of the response!");
}
super.assertThatSidesMatch(stubSide, testSide);
}
@@ -218,8 +217,7 @@ public class Response extends Common implements RegexCreatingProperty<ServerDslP
@Override
public DslProperty value(ClientDslProperty client, ServerDslProperty server) {
if (client.getClientValue() instanceof RegexProperty) {
throw new IllegalStateException(
"You can't have a regular expression for the response on the client side");
throw new IllegalStateException("You can't have a regular expression for the response on the client side");
}
return super.value(client, server);
@@ -234,8 +232,7 @@ public class Response extends Common implements RegexCreatingProperty<ServerDslP
@Override
public DslProperty value(ServerDslProperty server, ClientDslProperty client) {
if (client.getClientValue() instanceof RegexProperty) {
throw new IllegalStateException(
"You can't have a regular expression for the response on the client side");
throw new IllegalStateException("You can't have a regular expression for the response on the client side");
}
return super.value(server, client);
@@ -699,10 +696,8 @@ public class Response extends Common implements RegexCreatingProperty<ServerDslP
}
Response response = (Response) o;
return async == response.async && Objects.equals(status, response.status)
&& Objects.equals(delay, response.delay)
&& Objects.equals(headers, response.headers)
&& Objects.equals(cookies, response.cookies)
&& Objects.equals(body, response.body)
&& Objects.equals(delay, response.delay) && Objects.equals(headers, response.headers)
&& Objects.equals(cookies, response.cookies) && Objects.equals(body, response.body)
&& Objects.equals(bodyMatchers, response.bodyMatchers);
}
@@ -713,10 +708,9 @@ public class Response extends Common implements RegexCreatingProperty<ServerDslP
@Override
public String toString() {
return "Response{" + "\nstatus=" + status + ", \n\tdelay=" + delay
+ ", \n\theaders=" + headers + ", \n\tcookies=" + cookies + ", \n\tbody="
+ body + ", \n\tasync=" + async + ", \n\tbodyMatchers=" + bodyMatchers
+ '}';
return "Response{" + "\nstatus=" + status + ", \n\tdelay=" + delay + ", \n\theaders=" + headers
+ ", \n\tcookies=" + cookies + ", \n\tbody=" + body + ", \n\tasync=" + async + ", \n\tbodyMatchers="
+ bodyMatchers + '}';
}
/**
@@ -804,8 +798,9 @@ public class Response extends Common implements RegexCreatingProperty<ServerDslP
@Override
public DslProperty matching(final String value) {
return this.common.$(this.common.p(notEscaped(Pattern.compile(
RegexpUtils.escapeSpecialRegexWithSingleEscape(value) + ".*"))),
return this.common.$(
this.common.p(
notEscaped(Pattern.compile(RegexpUtils.escapeSpecialRegexWithSingleEscape(value) + ".*"))),
this.common.c(value));
}
@@ -817,8 +812,8 @@ public class Response extends Common implements RegexCreatingProperty<ServerDslP
@Override
public DslProperty matching(final String value) {
return this.common.$(this.common.p(this.common
.regex(RegexpUtils.escapeSpecialRegexWithSingleEscape(value) + ".*")),
return this.common.$(
this.common.p(this.common.regex(RegexpUtils.escapeSpecialRegexWithSingleEscape(value) + ".*")),
this.common.c(value));
}
@@ -840,12 +835,10 @@ public class Response extends Common implements RegexCreatingProperty<ServerDslP
}
private class ServerPatternValueDslProperty
extends PatternValueDslProperty<ServerDslProperty> {
private class ServerPatternValueDslProperty extends PatternValueDslProperty<ServerDslProperty> {
@Override
protected ServerDslProperty createProperty(Pattern pattern,
Object generatedValue) {
protected ServerDslProperty createProperty(Pattern pattern, Object generatedValue) {
return new ServerDslProperty(pattern, generatedValue);
}

View File

@@ -78,8 +78,7 @@ public class Url extends DslProperty {
@Override
public String toString() {
return "Url{" + "\nqueryParameters=" + queryParameters + "} \n"
+ super.toString();
return "Url{" + "\nqueryParameters=" + queryParameters + "} \n" + super.toString();
}
/**

View File

@@ -39,8 +39,8 @@ final class UrlHelper {
private static final String REGEX_USERINFO = "(?:\\S+(?::\\S*)?@)?";
private static final String REGEX_HOST = "(?:"
+ "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
+ "|" + "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)"
+ "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" + "|"
+ "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)"
+ "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*"
+ "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))|(?:localhost))";
@@ -48,13 +48,11 @@ final class UrlHelper {
private static final String REGEX_RESOURCE_PATH = "(?:/\\S*)?";
protected static final Pattern HTTPS_URL = Pattern.compile(
"^(?:" + HTTPS_REGEX_SCHEME + REGEX_AUTHORATIVE_DECLARATION + REGEX_USERINFO
+ REGEX_HOST + REGEX_PORT + REGEX_RESOURCE_PATH + ")$");
protected static final Pattern HTTPS_URL = Pattern.compile("^(?:" + HTTPS_REGEX_SCHEME
+ REGEX_AUTHORATIVE_DECLARATION + REGEX_USERINFO + REGEX_HOST + REGEX_PORT + REGEX_RESOURCE_PATH + ")$");
protected static final Pattern URL = Pattern.compile("^(?:(?:" + REGEX_SCHEME
+ REGEX_AUTHORATIVE_DECLARATION + ")?" + REGEX_USERINFO + REGEX_HOST
+ REGEX_PORT + REGEX_RESOURCE_PATH + ")$");
protected static final Pattern URL = Pattern.compile("^(?:(?:" + REGEX_SCHEME + REGEX_AUTHORATIVE_DECLARATION + ")?"
+ REGEX_USERINFO + REGEX_HOST + REGEX_PORT + REGEX_RESOURCE_PATH + ")$");
private UrlHelper() {
throw new IllegalStateException("Can't instantiate an utility class");

View File

@@ -37,7 +37,6 @@ public final class RegexpUtils {
return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
}
private static final Pattern SPECIAL_REGEX_CHARS = Pattern
.compile("[{}()\\[\\].+*?^$\\\\|]");
private static final Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");
}

View File

@@ -73,12 +73,10 @@ public final class ValidateUtils {
throw new IllegalStateException(msg + " can\'t be a pattern for the server side");
}
public static void validateServerValue(MatchingStrategy matchingStrategy,
String msg) {
public static void validateServerValue(MatchingStrategy matchingStrategy, String msg) {
if (!ALLOWED_MATCHING_TYPES_ON_SERVER_SIDE.contains(matchingStrategy.getType())) {
throw new IllegalStateException(msg + " can\'t be of a matching type: "
+ String.valueOf(matchingStrategy.getType())
+ " for the server side");
+ String.valueOf(matchingStrategy.getType()) + " for the server side");
}
validateServerValue(matchingStrategy.getServerValue(), msg);

View File

@@ -63,10 +63,8 @@ public class Xeger {
.replace("\\s", "[ \t\r\n]"); // Used s="White"Space
this.automaton = new RegExp(pattern).toAutomaton();
this.random = random;
String generatedCharsSysProp = System
.getProperty("springCloudContractGeneratedCharsFromRegex");
String generatedCharsEnvVar = System
.getenv("SPRING_CLOUD_CONTRACT_GENERATED_CHARS_FROM_REGEX");
String generatedCharsSysProp = System.getProperty("springCloudContractGeneratedCharsFromRegex");
String generatedCharsEnvVar = System.getenv("SPRING_CLOUD_CONTRACT_GENERATED_CHARS_FROM_REGEX");
if (StringUtils.isNotEmpty(generatedCharsSysProp)) {
ITERATION_LIMIT = Integer.parseInt(generatedCharsSysProp);
}
@@ -130,8 +128,7 @@ public class Xeger {
}
private void appendChoice(StringBuilder builder, Transition transition) {
char c = (char) Xeger.getRandomInt(transition.getMin(), transition.getMax(),
this.random);
char c = (char) Xeger.getRandomInt(transition.getMin(), transition.getMax(), this.random);
builder.append(c);
}

View File

@@ -33,91 +33,78 @@ class HttpHeadersTests {
@Test
public void ACCEPT_CHARSET() {
BDDAssertions.then(HttpHeaders.ACCEPT_CHARSET).isEqualTo("Accept-Charset");
BDDAssertions.then(new HttpHeaders().acceptCharset())
.isEqualTo(HttpHeaders.ACCEPT_CHARSET);
BDDAssertions.then(new HttpHeaders().acceptCharset()).isEqualTo(HttpHeaders.ACCEPT_CHARSET);
}
@Test
public void ACCEPT_ENCODING() {
BDDAssertions.then(HttpHeaders.ACCEPT_ENCODING).isEqualTo("Accept-Encoding");
BDDAssertions.then(new HttpHeaders().acceptEncoding())
.isEqualTo(HttpHeaders.ACCEPT_ENCODING);
BDDAssertions.then(new HttpHeaders().acceptEncoding()).isEqualTo(HttpHeaders.ACCEPT_ENCODING);
}
@Test
public void ACCEPT_LANGUAGE() {
BDDAssertions.then(HttpHeaders.ACCEPT_LANGUAGE).isEqualTo("Accept-Language");
BDDAssertions.then(new HttpHeaders().acceptLanguage())
.isEqualTo(HttpHeaders.ACCEPT_LANGUAGE);
BDDAssertions.then(new HttpHeaders().acceptLanguage()).isEqualTo(HttpHeaders.ACCEPT_LANGUAGE);
}
@Test
public void ACCEPT_RANGES() {
BDDAssertions.then(HttpHeaders.ACCEPT_RANGES).isEqualTo("Accept-Ranges");
BDDAssertions.then(new HttpHeaders().acceptRanges())
.isEqualTo(HttpHeaders.ACCEPT_RANGES);
BDDAssertions.then(new HttpHeaders().acceptRanges()).isEqualTo(HttpHeaders.ACCEPT_RANGES);
}
@Test
public void ACCESS_CONTROL_ALLOW_CREDENTIALS() {
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)
.isEqualTo("Access-Control-Allow-Credentials");
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS).isEqualTo("Access-Control-Allow-Credentials");
BDDAssertions.then(new HttpHeaders().accessControlAllowCredentials())
.isEqualTo(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS);
}
@Test
public void ACCESS_CONTROL_ALLOW_HEADERS() {
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)
.isEqualTo("Access-Control-Allow-Headers");
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).isEqualTo("Access-Control-Allow-Headers");
BDDAssertions.then(new HttpHeaders().accessControlAllowHeaders())
.isEqualTo(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS);
}
@Test
public void ACCESS_CONTROL_ALLOW_METHODS() {
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)
.isEqualTo("Access-Control-Allow-Methods");
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS).isEqualTo("Access-Control-Allow-Methods");
BDDAssertions.then(new HttpHeaders().accessControlAllowMethods())
.isEqualTo(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS);
}
@Test
public void ACCESS_CONTROL_ALLOW_ORIGIN() {
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)
.isEqualTo("Access-Control-Allow-Origin");
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN).isEqualTo("Access-Control-Allow-Origin");
BDDAssertions.then(new HttpHeaders().accessControlAllowOrigin())
.isEqualTo(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN);
}
@Test
public void ACCESS_CONTROL_EXPOSE_HEADERS() {
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)
.isEqualTo("Access-Control-Expose-Headers");
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).isEqualTo("Access-Control-Expose-Headers");
BDDAssertions.then(new HttpHeaders().accessControlExposeHeaders())
.isEqualTo(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS);
}
@Test
public void ACCESS_CONTROL_MAX_AGE() {
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_MAX_AGE)
.isEqualTo("Access-Control-Max-Age");
BDDAssertions.then(new HttpHeaders().accessControlMaxAge())
.isEqualTo(HttpHeaders.ACCESS_CONTROL_MAX_AGE);
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_MAX_AGE).isEqualTo("Access-Control-Max-Age");
BDDAssertions.then(new HttpHeaders().accessControlMaxAge()).isEqualTo(HttpHeaders.ACCESS_CONTROL_MAX_AGE);
}
@Test
public void ACCESS_CONTROL_REQUEST_HEADERS() {
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)
.isEqualTo("Access-Control-Request-Headers");
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS).isEqualTo("Access-Control-Request-Headers");
BDDAssertions.then(new HttpHeaders().accessControlRequestHeaders())
.isEqualTo(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
}
@Test
public void ACCESS_CONTROL_REQUEST_METHOD() {
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD)
.isEqualTo("Access-Control-Request-Method");
BDDAssertions.then(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD).isEqualTo("Access-Control-Request-Method");
BDDAssertions.then(new HttpHeaders().accessControlRequestMethod())
.isEqualTo(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD);
}
@@ -137,72 +124,61 @@ class HttpHeadersTests {
@Test
public void AUTHORIZATION() {
BDDAssertions.then(HttpHeaders.AUTHORIZATION).isEqualTo("Authorization");
BDDAssertions.then(new HttpHeaders().authorization())
.isEqualTo(HttpHeaders.AUTHORIZATION);
BDDAssertions.then(new HttpHeaders().authorization()).isEqualTo(HttpHeaders.AUTHORIZATION);
}
@Test
public void CACHE_CONTROL() {
BDDAssertions.then(HttpHeaders.CACHE_CONTROL).isEqualTo("Cache-Control");
BDDAssertions.then(new HttpHeaders().cacheControl())
.isEqualTo(HttpHeaders.CACHE_CONTROL);
BDDAssertions.then(new HttpHeaders().cacheControl()).isEqualTo(HttpHeaders.CACHE_CONTROL);
}
@Test
public void CONNECTION() {
BDDAssertions.then(HttpHeaders.CONNECTION).isEqualTo("Connection");
BDDAssertions.then(new HttpHeaders().connection())
.isEqualTo(HttpHeaders.CONNECTION);
BDDAssertions.then(new HttpHeaders().connection()).isEqualTo(HttpHeaders.CONNECTION);
}
@Test
public void CONTENT_ENCODING() {
BDDAssertions.then(HttpHeaders.CONTENT_ENCODING).isEqualTo("Content-Encoding");
BDDAssertions.then(new HttpHeaders().contentEncoding())
.isEqualTo(HttpHeaders.CONTENT_ENCODING);
BDDAssertions.then(new HttpHeaders().contentEncoding()).isEqualTo(HttpHeaders.CONTENT_ENCODING);
}
@Test
public void CONTENT_DISPOSITION() {
BDDAssertions.then(HttpHeaders.CONTENT_DISPOSITION)
.isEqualTo("Content-Disposition");
BDDAssertions.then(new HttpHeaders().contentDisposition())
.isEqualTo(HttpHeaders.CONTENT_DISPOSITION);
BDDAssertions.then(HttpHeaders.CONTENT_DISPOSITION).isEqualTo("Content-Disposition");
BDDAssertions.then(new HttpHeaders().contentDisposition()).isEqualTo(HttpHeaders.CONTENT_DISPOSITION);
}
@Test
public void CONTENT_LANGUAGE() {
BDDAssertions.then(HttpHeaders.CONTENT_LANGUAGE).isEqualTo("Content-Language");
BDDAssertions.then(new HttpHeaders().contentLanguage())
.isEqualTo(HttpHeaders.CONTENT_LANGUAGE);
BDDAssertions.then(new HttpHeaders().contentLanguage()).isEqualTo(HttpHeaders.CONTENT_LANGUAGE);
}
@Test
public void CONTENT_LENGTH() {
BDDAssertions.then(HttpHeaders.CONTENT_LENGTH).isEqualTo("Content-Length");
BDDAssertions.then(new HttpHeaders().contentLength())
.isEqualTo(HttpHeaders.CONTENT_LENGTH);
BDDAssertions.then(new HttpHeaders().contentLength()).isEqualTo(HttpHeaders.CONTENT_LENGTH);
}
@Test
public void CONTENT_LOCATION() {
BDDAssertions.then(HttpHeaders.CONTENT_LOCATION).isEqualTo("Content-Location");
BDDAssertions.then(new HttpHeaders().contentLocation())
.isEqualTo(HttpHeaders.CONTENT_LOCATION);
BDDAssertions.then(new HttpHeaders().contentLocation()).isEqualTo(HttpHeaders.CONTENT_LOCATION);
}
@Test
public void CONTENT_RANGE() {
BDDAssertions.then(HttpHeaders.CONTENT_RANGE).isEqualTo("Content-Range");
BDDAssertions.then(new HttpHeaders().contentRange())
.isEqualTo(HttpHeaders.CONTENT_RANGE);
BDDAssertions.then(new HttpHeaders().contentRange()).isEqualTo(HttpHeaders.CONTENT_RANGE);
}
@Test
public void CONTENT_TYPE() {
BDDAssertions.then(HttpHeaders.CONTENT_TYPE).isEqualTo("Content-Type");
BDDAssertions.then(new HttpHeaders().contentType())
.isEqualTo(HttpHeaders.CONTENT_TYPE);
BDDAssertions.then(new HttpHeaders().contentType()).isEqualTo(HttpHeaders.CONTENT_TYPE);
}
@Test
@@ -256,15 +232,13 @@ class HttpHeadersTests {
@Test
public void IF_MODIFIED_SINCE() {
BDDAssertions.then(HttpHeaders.IF_MODIFIED_SINCE).isEqualTo("If-Modified-Since");
BDDAssertions.then(new HttpHeaders().ifModifiedSince())
.isEqualTo(HttpHeaders.IF_MODIFIED_SINCE);
BDDAssertions.then(new HttpHeaders().ifModifiedSince()).isEqualTo(HttpHeaders.IF_MODIFIED_SINCE);
}
@Test
public void IF_NONE_MATCH() {
BDDAssertions.then(HttpHeaders.IF_NONE_MATCH).isEqualTo("If-None-Match");
BDDAssertions.then(new HttpHeaders().ifNoneMatch())
.isEqualTo(HttpHeaders.IF_NONE_MATCH);
BDDAssertions.then(new HttpHeaders().ifNoneMatch()).isEqualTo(HttpHeaders.IF_NONE_MATCH);
}
@Test
@@ -275,17 +249,14 @@ class HttpHeadersTests {
@Test
public void IF_UNMODIFIED_SINCE() {
BDDAssertions.then(HttpHeaders.IF_UNMODIFIED_SINCE)
.isEqualTo("If-Unmodified-Since");
BDDAssertions.then(new HttpHeaders().ifUnmodifiedSince())
.isEqualTo(HttpHeaders.IF_UNMODIFIED_SINCE);
BDDAssertions.then(HttpHeaders.IF_UNMODIFIED_SINCE).isEqualTo("If-Unmodified-Since");
BDDAssertions.then(new HttpHeaders().ifUnmodifiedSince()).isEqualTo(HttpHeaders.IF_UNMODIFIED_SINCE);
}
@Test
public void LAST_MODIFIED() {
BDDAssertions.then(HttpHeaders.LAST_MODIFIED).isEqualTo("Last-Modified");
BDDAssertions.then(new HttpHeaders().lastModified())
.isEqualTo(HttpHeaders.LAST_MODIFIED);
BDDAssertions.then(new HttpHeaders().lastModified()).isEqualTo(HttpHeaders.LAST_MODIFIED);
}
@Test
@@ -303,8 +274,7 @@ class HttpHeadersTests {
@Test
public void MAX_FORWARDS() {
BDDAssertions.then(HttpHeaders.MAX_FORWARDS).isEqualTo("Max-Forwards");
BDDAssertions.then(new HttpHeaders().max_forwards())
.isEqualTo(HttpHeaders.MAX_FORWARDS);
BDDAssertions.then(new HttpHeaders().max_forwards()).isEqualTo(HttpHeaders.MAX_FORWARDS);
}
@Test
@@ -321,18 +291,14 @@ class HttpHeadersTests {
@Test
public void PROXY_AUTHENTICATE() {
BDDAssertions.then(HttpHeaders.PROXY_AUTHENTICATE)
.isEqualTo("Proxy-Authenticate");
BDDAssertions.then(new HttpHeaders().proxyAuthenticate())
.isEqualTo(HttpHeaders.PROXY_AUTHENTICATE);
BDDAssertions.then(HttpHeaders.PROXY_AUTHENTICATE).isEqualTo("Proxy-Authenticate");
BDDAssertions.then(new HttpHeaders().proxyAuthenticate()).isEqualTo(HttpHeaders.PROXY_AUTHENTICATE);
}
@Test
public void PROXY_AUTHORIZATION() {
BDDAssertions.then(HttpHeaders.PROXY_AUTHORIZATION)
.isEqualTo("Proxy-Authorization");
BDDAssertions.then(new HttpHeaders().proxyAuthorization())
.isEqualTo(HttpHeaders.PROXY_AUTHORIZATION);
BDDAssertions.then(HttpHeaders.PROXY_AUTHORIZATION).isEqualTo("Proxy-Authorization");
BDDAssertions.then(new HttpHeaders().proxyAuthorization()).isEqualTo(HttpHeaders.PROXY_AUTHORIZATION);
}
@Test
@@ -350,8 +316,7 @@ class HttpHeadersTests {
@Test
public void RETRY_AFTER() {
BDDAssertions.then(HttpHeaders.RETRY_AFTER).isEqualTo("Retry-After");
BDDAssertions.then(new HttpHeaders().retryAfter())
.isEqualTo(HttpHeaders.RETRY_AFTER);
BDDAssertions.then(new HttpHeaders().retryAfter()).isEqualTo(HttpHeaders.RETRY_AFTER);
}
@Test
@@ -363,15 +328,13 @@ class HttpHeadersTests {
@Test
public void SET_COOKIE() {
BDDAssertions.then(HttpHeaders.SET_COOKIE).isEqualTo("Set-Cookie");
BDDAssertions.then(new HttpHeaders().setCookie())
.isEqualTo(HttpHeaders.SET_COOKIE);
BDDAssertions.then(new HttpHeaders().setCookie()).isEqualTo(HttpHeaders.SET_COOKIE);
}
@Test
public void SET_COOKIE_2() {
BDDAssertions.then(HttpHeaders.SET_COOKIE_2).isEqualTo("Set-Cookie2");
BDDAssertions.then(new HttpHeaders().setCookie2())
.isEqualTo(HttpHeaders.SET_COOKIE_2);
BDDAssertions.then(new HttpHeaders().setCookie2()).isEqualTo(HttpHeaders.SET_COOKIE_2);
}
@Test
@@ -389,8 +352,7 @@ class HttpHeadersTests {
@Test
public void TRANSFER_ENCODING() {
BDDAssertions.then(HttpHeaders.TRANSFER_ENCODING).isEqualTo("Transfer-Encoding");
BDDAssertions.then(new HttpHeaders().transferEncoding())
.isEqualTo(HttpHeaders.TRANSFER_ENCODING);
BDDAssertions.then(new HttpHeaders().transferEncoding()).isEqualTo(HttpHeaders.TRANSFER_ENCODING);
}
@Test
@@ -402,8 +364,7 @@ class HttpHeadersTests {
@Test
public void USER_AGENT() {
BDDAssertions.then(HttpHeaders.USER_AGENT).isEqualTo("User-Agent");
BDDAssertions.then(new HttpHeaders().user_agent())
.isEqualTo(HttpHeaders.USER_AGENT);
BDDAssertions.then(new HttpHeaders().user_agent()).isEqualTo(HttpHeaders.USER_AGENT);
}
@Test
@@ -427,8 +388,7 @@ class HttpHeadersTests {
@Test
public void WWW_AUTHENTICATE() {
BDDAssertions.then(HttpHeaders.WWW_AUTHENTICATE).isEqualTo("WWW-Authenticate");
BDDAssertions.then(new HttpHeaders().wwwAuthenticate())
.isEqualTo(HttpHeaders.WWW_AUTHENTICATE);
BDDAssertions.then(new HttpHeaders().wwwAuthenticate()).isEqualTo(HttpHeaders.WWW_AUTHENTICATE);
}
}

View File

@@ -27,57 +27,49 @@ class HttpMethodsTests {
@Test
public void GET() {
BDDAssertions.then(HttpMethods.GET).isEqualTo("GET");
BDDAssertions.then(new HttpMethods().GET().getMethodName())
.isEqualTo(HttpMethods.GET);
BDDAssertions.then(new HttpMethods().GET().getMethodName()).isEqualTo(HttpMethods.GET);
}
@Test
public void HEAD() {
BDDAssertions.then(HttpMethods.HEAD).isEqualTo("HEAD");
BDDAssertions.then(new HttpMethods().HEAD().getMethodName())
.isEqualTo(HttpMethods.HEAD);
BDDAssertions.then(new HttpMethods().HEAD().getMethodName()).isEqualTo(HttpMethods.HEAD);
}
@Test
public void POST() {
BDDAssertions.then(HttpMethods.POST).isEqualTo("POST");
BDDAssertions.then(new HttpMethods().POST().getMethodName())
.isEqualTo(HttpMethods.POST);
BDDAssertions.then(new HttpMethods().POST().getMethodName()).isEqualTo(HttpMethods.POST);
}
@Test
public void PUT() {
BDDAssertions.then(HttpMethods.PUT).isEqualTo("PUT");
BDDAssertions.then(new HttpMethods().PUT().getMethodName())
.isEqualTo(HttpMethods.PUT);
BDDAssertions.then(new HttpMethods().PUT().getMethodName()).isEqualTo(HttpMethods.PUT);
}
@Test
public void PATCH() {
BDDAssertions.then(HttpMethods.PATCH).isEqualTo("PATCH");
BDDAssertions.then(new HttpMethods().PATCH().getMethodName())
.isEqualTo(HttpMethods.PATCH);
BDDAssertions.then(new HttpMethods().PATCH().getMethodName()).isEqualTo(HttpMethods.PATCH);
}
@Test
public void DELETE() {
BDDAssertions.then(HttpMethods.DELETE).isEqualTo("DELETE");
BDDAssertions.then(new HttpMethods().DELETE().getMethodName())
.isEqualTo(HttpMethods.DELETE);
BDDAssertions.then(new HttpMethods().DELETE().getMethodName()).isEqualTo(HttpMethods.DELETE);
}
@Test
public void OPTIONS() {
BDDAssertions.then(HttpMethods.OPTIONS).isEqualTo("OPTIONS");
BDDAssertions.then(new HttpMethods().OPTIONS().getMethodName())
.isEqualTo(HttpMethods.OPTIONS);
BDDAssertions.then(new HttpMethods().OPTIONS().getMethodName()).isEqualTo(HttpMethods.OPTIONS);
}
@Test
public void TRACE() {
BDDAssertions.then(HttpMethods.TRACE).isEqualTo("TRACE");
BDDAssertions.then(new HttpMethods().TRACE().getMethodName())
.isEqualTo(HttpMethods.TRACE);
BDDAssertions.then(new HttpMethods().TRACE().getMethodName()).isEqualTo(HttpMethods.TRACE);
}
}

View File

@@ -32,16 +32,13 @@ class MediaTypesTests {
@Test
public void APPLICATION_ATOM_XML() {
BDDAssertions.then(MediaTypes.APPLICATION_ATOM_XML)
.isEqualTo("application/atom+xml");
BDDAssertions.then(new MediaTypes().applicationAtomXml())
.isEqualTo(MediaTypes.APPLICATION_ATOM_XML);
BDDAssertions.then(MediaTypes.APPLICATION_ATOM_XML).isEqualTo("application/atom+xml");
BDDAssertions.then(new MediaTypes().applicationAtomXml()).isEqualTo(MediaTypes.APPLICATION_ATOM_XML);
}
@Test
public void APPLICATION_FORM_URLENCODED() {
BDDAssertions.then(MediaTypes.APPLICATION_FORM_URLENCODED)
.isEqualTo("application/x-www-form-urlencoded");
BDDAssertions.then(MediaTypes.APPLICATION_FORM_URLENCODED).isEqualTo("application/x-www-form-urlencoded");
BDDAssertions.then(new MediaTypes().applicationFormUrlencoded())
.isEqualTo(MediaTypes.APPLICATION_FORM_URLENCODED);
}
@@ -49,46 +46,37 @@ class MediaTypesTests {
@Test
public void APPLICATION_JSON() {
BDDAssertions.then(MediaTypes.APPLICATION_JSON).isEqualTo("application/json");
BDDAssertions.then(new MediaTypes().applicationJson())
.isEqualTo(MediaTypes.APPLICATION_JSON);
BDDAssertions.then(new MediaTypes().applicationJson()).isEqualTo(MediaTypes.APPLICATION_JSON);
}
@Test
public void APPLICATION_JSON_UTF8() {
BDDAssertions.then(MediaTypes.APPLICATION_JSON_UTF8)
.isEqualTo("application/json;charset=UTF-8");
BDDAssertions.then(new MediaTypes().applicationJsonUtf8())
.isEqualTo(MediaTypes.APPLICATION_JSON_UTF8);
BDDAssertions.then(MediaTypes.APPLICATION_JSON_UTF8).isEqualTo("application/json;charset=UTF-8");
BDDAssertions.then(new MediaTypes().applicationJsonUtf8()).isEqualTo(MediaTypes.APPLICATION_JSON_UTF8);
}
@Test
public void APPLICATION_OCTET_STREAM() {
BDDAssertions.then(MediaTypes.APPLICATION_OCTET_STREAM)
.isEqualTo("application/octet-stream");
BDDAssertions.then(new MediaTypes().applicationOctetStream())
.isEqualTo(MediaTypes.APPLICATION_OCTET_STREAM);
BDDAssertions.then(MediaTypes.APPLICATION_OCTET_STREAM).isEqualTo("application/octet-stream");
BDDAssertions.then(new MediaTypes().applicationOctetStream()).isEqualTo(MediaTypes.APPLICATION_OCTET_STREAM);
}
@Test
public void APPLICATION_PDF() {
BDDAssertions.then(MediaTypes.APPLICATION_PDF).isEqualTo("application/pdf");
BDDAssertions.then(new MediaTypes().applicationPdf())
.isEqualTo(MediaTypes.APPLICATION_PDF);
BDDAssertions.then(new MediaTypes().applicationPdf()).isEqualTo(MediaTypes.APPLICATION_PDF);
}
@Test
public void APPLICATION_XHTML_XML() {
BDDAssertions.then(MediaTypes.APPLICATION_XHTML_XML)
.isEqualTo("application/xhtml+xml");
BDDAssertions.then(new MediaTypes().applicationXhtmlXml())
.isEqualTo(MediaTypes.APPLICATION_XHTML_XML);
BDDAssertions.then(MediaTypes.APPLICATION_XHTML_XML).isEqualTo("application/xhtml+xml");
BDDAssertions.then(new MediaTypes().applicationXhtmlXml()).isEqualTo(MediaTypes.APPLICATION_XHTML_XML);
}
@Test
public void APPLICATION_XML() {
BDDAssertions.then(MediaTypes.APPLICATION_XML).isEqualTo("application/xml");
BDDAssertions.then(new MediaTypes().applicationXml())
.isEqualTo(MediaTypes.APPLICATION_XML);
BDDAssertions.then(new MediaTypes().applicationXml()).isEqualTo(MediaTypes.APPLICATION_XML);
}
@Test
@@ -111,10 +99,8 @@ class MediaTypesTests {
@Test
public void MULTIPART_FORM_DATA() {
BDDAssertions.then(MediaTypes.MULTIPART_FORM_DATA)
.isEqualTo("multipart/form-data");
BDDAssertions.then(new MediaTypes().multipartFormData())
.isEqualTo(MediaTypes.MULTIPART_FORM_DATA);
BDDAssertions.then(MediaTypes.MULTIPART_FORM_DATA).isEqualTo("multipart/form-data");
BDDAssertions.then(new MediaTypes().multipartFormData()).isEqualTo(MediaTypes.MULTIPART_FORM_DATA);
}
@Test
@@ -126,8 +112,7 @@ class MediaTypesTests {
@Test
public void TEXT_MARKDOWN() {
BDDAssertions.then(MediaTypes.TEXT_MARKDOWN).isEqualTo("text/markdown");
BDDAssertions.then(new MediaTypes().textMarkdown())
.isEqualTo(MediaTypes.TEXT_MARKDOWN);
BDDAssertions.then(new MediaTypes().textMarkdown()).isEqualTo(MediaTypes.TEXT_MARKDOWN);
}
@Test

View File

@@ -26,8 +26,7 @@ class MessagingHeadersTests {
@Test
public void MESSAGING_CONTENT_TYPE() {
BDDAssertions.then(MessagingHeaders.MESSAGING_CONTENT_TYPE)
.isEqualTo("contentType");
BDDAssertions.then(MessagingHeaders.MESSAGING_CONTENT_TYPE).isEqualTo("contentType");
BDDAssertions.then(new MessagingHeaders().messagingContentType())
.isEqualTo(MessagingHeaders.MESSAGING_CONTENT_TYPE);
}

View File

@@ -90,8 +90,7 @@ public class XegerTest {
List<String> secondRegexList = generateRegex(generator2, 100);
for (int i = 0; i < firstRegexList.size(); i++) {
assertEquals("Index mismatch: " + i, firstRegexList.get(i),
secondRegexList.get(i));
assertEquals("Index mismatch: " + i, firstRegexList.get(i), secondRegexList.get(i));
}
}
}

View File

@@ -34,22 +34,19 @@ public class HttpStatusTests {
@Test
public void SWITCHING_PROTOCOLS() {
BDDAssertions.then(HttpStatus.SWITCHING_PROTOCOLS).isEqualTo(101);
BDDAssertions.then(new HttpStatus().SWITCHING_PROTOCOLS())
.isEqualTo(HttpStatus.SWITCHING_PROTOCOLS);
BDDAssertions.then(new HttpStatus().SWITCHING_PROTOCOLS()).isEqualTo(HttpStatus.SWITCHING_PROTOCOLS);
}
@Test
public void PROCESSING() {
BDDAssertions.then(HttpStatus.PROCESSING).isEqualTo(102);
BDDAssertions.then(new HttpStatus().PROCESSING())
.isEqualTo(HttpStatus.PROCESSING);
BDDAssertions.then(new HttpStatus().PROCESSING()).isEqualTo(HttpStatus.PROCESSING);
}
@Test
public void CHECKPOINT() {
BDDAssertions.then(HttpStatus.CHECKPOINT).isEqualTo(103);
BDDAssertions.then(new HttpStatus().CHECKPOINT())
.isEqualTo(HttpStatus.CHECKPOINT);
BDDAssertions.then(new HttpStatus().CHECKPOINT()).isEqualTo(HttpStatus.CHECKPOINT);
}
@Test
@@ -80,36 +77,31 @@ public class HttpStatusTests {
@Test
public void NO_CONTENT() {
BDDAssertions.then(HttpStatus.NO_CONTENT).isEqualTo(204);
BDDAssertions.then(new HttpStatus().NO_CONTENT())
.isEqualTo(HttpStatus.NO_CONTENT);
BDDAssertions.then(new HttpStatus().NO_CONTENT()).isEqualTo(HttpStatus.NO_CONTENT);
}
@Test
public void RESET_CONTENT() {
BDDAssertions.then(HttpStatus.RESET_CONTENT).isEqualTo(205);
BDDAssertions.then(new HttpStatus().RESET_CONTENT())
.isEqualTo(HttpStatus.RESET_CONTENT);
BDDAssertions.then(new HttpStatus().RESET_CONTENT()).isEqualTo(HttpStatus.RESET_CONTENT);
}
@Test
public void PARTIAL_CONTENT() {
BDDAssertions.then(HttpStatus.PARTIAL_CONTENT).isEqualTo(206);
BDDAssertions.then(new HttpStatus().PARTIAL_CONTENT())
.isEqualTo(HttpStatus.PARTIAL_CONTENT);
BDDAssertions.then(new HttpStatus().PARTIAL_CONTENT()).isEqualTo(HttpStatus.PARTIAL_CONTENT);
}
@Test
public void MULTI_STATUS() {
BDDAssertions.then(HttpStatus.MULTI_STATUS).isEqualTo(207);
BDDAssertions.then(new HttpStatus().MULTI_STATUS())
.isEqualTo(HttpStatus.MULTI_STATUS);
BDDAssertions.then(new HttpStatus().MULTI_STATUS()).isEqualTo(HttpStatus.MULTI_STATUS);
}
@Test
public void ALREADY_REPORTED() {
BDDAssertions.then(HttpStatus.ALREADY_REPORTED).isEqualTo(208);
BDDAssertions.then(new HttpStatus().ALREADY_REPORTED())
.isEqualTo(HttpStatus.ALREADY_REPORTED);
BDDAssertions.then(new HttpStatus().ALREADY_REPORTED()).isEqualTo(HttpStatus.ALREADY_REPORTED);
}
@Test
@@ -121,15 +113,13 @@ public class HttpStatusTests {
@Test
public void MULTIPLE_CHOICES() {
BDDAssertions.then(HttpStatus.MULTIPLE_CHOICES).isEqualTo(300);
BDDAssertions.then(new HttpStatus().MULTIPLE_CHOICES())
.isEqualTo(HttpStatus.MULTIPLE_CHOICES);
BDDAssertions.then(new HttpStatus().MULTIPLE_CHOICES()).isEqualTo(HttpStatus.MULTIPLE_CHOICES);
}
@Test
public void MOVED_PERMANENTLY() {
BDDAssertions.then(HttpStatus.MOVED_PERMANENTLY).isEqualTo(301);
BDDAssertions.then(new HttpStatus().MOVED_PERMANENTLY())
.isEqualTo(HttpStatus.MOVED_PERMANENTLY);
BDDAssertions.then(new HttpStatus().MOVED_PERMANENTLY()).isEqualTo(HttpStatus.MOVED_PERMANENTLY);
}
@Test
@@ -141,8 +131,7 @@ public class HttpStatusTests {
@Test
public void MOVED_TEMPORARILY() {
BDDAssertions.then(HttpStatus.MOVED_TEMPORARILY).isEqualTo(302);
BDDAssertions.then(new HttpStatus().MOVED_TEMPORARILY())
.isEqualTo(HttpStatus.MOVED_TEMPORARILY);
BDDAssertions.then(new HttpStatus().MOVED_TEMPORARILY()).isEqualTo(HttpStatus.MOVED_TEMPORARILY);
}
@Test
@@ -154,8 +143,7 @@ public class HttpStatusTests {
@Test
public void NOT_MODIFIED() {
BDDAssertions.then(HttpStatus.NOT_MODIFIED).isEqualTo(304);
BDDAssertions.then(new HttpStatus().NOT_MODIFIED())
.isEqualTo(HttpStatus.NOT_MODIFIED);
BDDAssertions.then(new HttpStatus().NOT_MODIFIED()).isEqualTo(HttpStatus.NOT_MODIFIED);
}
@Test
@@ -167,36 +155,31 @@ public class HttpStatusTests {
@Test
public void TEMPORARY_REDIRECT() {
BDDAssertions.then(HttpStatus.TEMPORARY_REDIRECT).isEqualTo(307);
BDDAssertions.then(new HttpStatus().TEMPORARY_REDIRECT())
.isEqualTo(HttpStatus.TEMPORARY_REDIRECT);
BDDAssertions.then(new HttpStatus().TEMPORARY_REDIRECT()).isEqualTo(HttpStatus.TEMPORARY_REDIRECT);
}
@Test
public void PERMANENT_REDIRECT() {
BDDAssertions.then(HttpStatus.PERMANENT_REDIRECT).isEqualTo(308);
BDDAssertions.then(new HttpStatus().PERMANENT_REDIRECT())
.isEqualTo(HttpStatus.PERMANENT_REDIRECT);
BDDAssertions.then(new HttpStatus().PERMANENT_REDIRECT()).isEqualTo(HttpStatus.PERMANENT_REDIRECT);
}
@Test
public void BAD_REQUEST() {
BDDAssertions.then(HttpStatus.BAD_REQUEST).isEqualTo(400);
BDDAssertions.then(new HttpStatus().BAD_REQUEST())
.isEqualTo(HttpStatus.BAD_REQUEST);
BDDAssertions.then(new HttpStatus().BAD_REQUEST()).isEqualTo(HttpStatus.BAD_REQUEST);
}
@Test
public void UNAUTHORIZED() {
BDDAssertions.then(HttpStatus.UNAUTHORIZED).isEqualTo(401);
BDDAssertions.then(new HttpStatus().UNAUTHORIZED())
.isEqualTo(HttpStatus.UNAUTHORIZED);
BDDAssertions.then(new HttpStatus().UNAUTHORIZED()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void PAYMENT_REQUIRED() {
BDDAssertions.then(HttpStatus.PAYMENT_REQUIRED).isEqualTo(402);
BDDAssertions.then(new HttpStatus().PAYMENT_REQUIRED())
.isEqualTo(HttpStatus.PAYMENT_REQUIRED);
BDDAssertions.then(new HttpStatus().PAYMENT_REQUIRED()).isEqualTo(HttpStatus.PAYMENT_REQUIRED);
}
@Test
@@ -214,15 +197,13 @@ public class HttpStatusTests {
@Test
public void METHOD_NOT_ALLOWED() {
BDDAssertions.then(HttpStatus.METHOD_NOT_ALLOWED).isEqualTo(405);
BDDAssertions.then(new HttpStatus().METHOD_NOT_ALLOWED())
.isEqualTo(HttpStatus.METHOD_NOT_ALLOWED);
BDDAssertions.then(new HttpStatus().METHOD_NOT_ALLOWED()).isEqualTo(HttpStatus.METHOD_NOT_ALLOWED);
}
@Test
public void NOT_ACCEPTABLE() {
BDDAssertions.then(HttpStatus.NOT_ACCEPTABLE).isEqualTo(406);
BDDAssertions.then(new HttpStatus().NOT_ACCEPTABLE())
.isEqualTo(HttpStatus.NOT_ACCEPTABLE);
BDDAssertions.then(new HttpStatus().NOT_ACCEPTABLE()).isEqualTo(HttpStatus.NOT_ACCEPTABLE);
}
@Test
@@ -235,8 +216,7 @@ public class HttpStatusTests {
@Test
public void REQUEST_TIMEOUT() {
BDDAssertions.then(HttpStatus.REQUEST_TIMEOUT).isEqualTo(408);
BDDAssertions.then(new HttpStatus().REQUEST_TIMEOUT())
.isEqualTo(HttpStatus.REQUEST_TIMEOUT);
BDDAssertions.then(new HttpStatus().REQUEST_TIMEOUT()).isEqualTo(HttpStatus.REQUEST_TIMEOUT);
}
@Test
@@ -254,50 +234,43 @@ public class HttpStatusTests {
@Test
public void LENGTH_REQUIRED() {
BDDAssertions.then(HttpStatus.LENGTH_REQUIRED).isEqualTo(411);
BDDAssertions.then(new HttpStatus().LENGTH_REQUIRED())
.isEqualTo(HttpStatus.LENGTH_REQUIRED);
BDDAssertions.then(new HttpStatus().LENGTH_REQUIRED()).isEqualTo(HttpStatus.LENGTH_REQUIRED);
}
@Test
public void PRECONDITION_FAILED() {
BDDAssertions.then(HttpStatus.PRECONDITION_FAILED).isEqualTo(412);
BDDAssertions.then(new HttpStatus().PRECONDITION_FAILED())
.isEqualTo(HttpStatus.PRECONDITION_FAILED);
BDDAssertions.then(new HttpStatus().PRECONDITION_FAILED()).isEqualTo(HttpStatus.PRECONDITION_FAILED);
}
@Test
public void PAYLOAD_TOO_LARGE() {
BDDAssertions.then(HttpStatus.PAYLOAD_TOO_LARGE).isEqualTo(413);
BDDAssertions.then(new HttpStatus().PAYLOAD_TOO_LARGE())
.isEqualTo(HttpStatus.PAYLOAD_TOO_LARGE);
BDDAssertions.then(new HttpStatus().PAYLOAD_TOO_LARGE()).isEqualTo(HttpStatus.PAYLOAD_TOO_LARGE);
}
@Test
public void REQUEST_ENTITY_TOO_LARGE() {
BDDAssertions.then(HttpStatus.REQUEST_ENTITY_TOO_LARGE).isEqualTo(413);
BDDAssertions.then(new HttpStatus().REQUEST_ENTITY_TOO_LARGE())
.isEqualTo(HttpStatus.REQUEST_ENTITY_TOO_LARGE);
BDDAssertions.then(new HttpStatus().REQUEST_ENTITY_TOO_LARGE()).isEqualTo(HttpStatus.REQUEST_ENTITY_TOO_LARGE);
}
@Test
public void URI_TOO_LONG() {
BDDAssertions.then(HttpStatus.URI_TOO_LONG).isEqualTo(414);
BDDAssertions.then(new HttpStatus().URI_TOO_LONG())
.isEqualTo(HttpStatus.URI_TOO_LONG);
BDDAssertions.then(new HttpStatus().URI_TOO_LONG()).isEqualTo(HttpStatus.URI_TOO_LONG);
}
@Test
public void REQUEST_URI_TOO_LONG() {
BDDAssertions.then(HttpStatus.REQUEST_URI_TOO_LONG).isEqualTo(414);
BDDAssertions.then(new HttpStatus().REQUEST_URI_TOO_LONG())
.isEqualTo(HttpStatus.REQUEST_URI_TOO_LONG);
BDDAssertions.then(new HttpStatus().REQUEST_URI_TOO_LONG()).isEqualTo(HttpStatus.REQUEST_URI_TOO_LONG);
}
@Test
public void UNSUPPORTED_MEDIA_TYPE() {
BDDAssertions.then(HttpStatus.UNSUPPORTED_MEDIA_TYPE).isEqualTo(415);
BDDAssertions.then(new HttpStatus().UNSUPPORTED_MEDIA_TYPE())
.isEqualTo(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
BDDAssertions.then(new HttpStatus().UNSUPPORTED_MEDIA_TYPE()).isEqualTo(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
}
@Test
@@ -310,15 +283,13 @@ public class HttpStatusTests {
@Test
public void EXPECTATION_FAILED() {
BDDAssertions.then(HttpStatus.EXPECTATION_FAILED).isEqualTo(417);
BDDAssertions.then(new HttpStatus().EXPECTATION_FAILED())
.isEqualTo(HttpStatus.EXPECTATION_FAILED);
BDDAssertions.then(new HttpStatus().EXPECTATION_FAILED()).isEqualTo(HttpStatus.EXPECTATION_FAILED);
}
@Test
public void I_AM_A_TEAPOT() {
BDDAssertions.then(HttpStatus.I_AM_A_TEAPOT).isEqualTo(418);
BDDAssertions.then(new HttpStatus().I_AM_A_TEAPOT())
.isEqualTo(HttpStatus.I_AM_A_TEAPOT);
BDDAssertions.then(new HttpStatus().I_AM_A_TEAPOT()).isEqualTo(HttpStatus.I_AM_A_TEAPOT);
}
@Test
@@ -331,22 +302,19 @@ public class HttpStatusTests {
@Test
public void METHOD_FAILURE() {
BDDAssertions.then(HttpStatus.METHOD_FAILURE).isEqualTo(420);
BDDAssertions.then(new HttpStatus().METHOD_FAILURE())
.isEqualTo(HttpStatus.METHOD_FAILURE);
BDDAssertions.then(new HttpStatus().METHOD_FAILURE()).isEqualTo(HttpStatus.METHOD_FAILURE);
}
@Test
public void DESTINATION_LOCKED() {
BDDAssertions.then(HttpStatus.DESTINATION_LOCKED).isEqualTo(421);
BDDAssertions.then(new HttpStatus().DESTINATION_LOCKED())
.isEqualTo(HttpStatus.DESTINATION_LOCKED);
BDDAssertions.then(new HttpStatus().DESTINATION_LOCKED()).isEqualTo(HttpStatus.DESTINATION_LOCKED);
}
@Test
public void UNPROCESSABLE_ENTITY() {
BDDAssertions.then(HttpStatus.UNPROCESSABLE_ENTITY).isEqualTo(422);
BDDAssertions.then(new HttpStatus().UNPROCESSABLE_ENTITY())
.isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY);
BDDAssertions.then(new HttpStatus().UNPROCESSABLE_ENTITY()).isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY);
}
@Test
@@ -358,29 +326,25 @@ public class HttpStatusTests {
@Test
public void FAILED_DEPENDENCY() {
BDDAssertions.then(HttpStatus.FAILED_DEPENDENCY).isEqualTo(424);
BDDAssertions.then(new HttpStatus().FAILED_DEPENDENCY())
.isEqualTo(HttpStatus.FAILED_DEPENDENCY);
BDDAssertions.then(new HttpStatus().FAILED_DEPENDENCY()).isEqualTo(HttpStatus.FAILED_DEPENDENCY);
}
@Test
public void UPGRADE_REQUIRED() {
BDDAssertions.then(HttpStatus.UPGRADE_REQUIRED).isEqualTo(426);
BDDAssertions.then(new HttpStatus().UPGRADE_REQUIRED())
.isEqualTo(HttpStatus.UPGRADE_REQUIRED);
BDDAssertions.then(new HttpStatus().UPGRADE_REQUIRED()).isEqualTo(HttpStatus.UPGRADE_REQUIRED);
}
@Test
public void PRECONDITION_REQUIRED() {
BDDAssertions.then(HttpStatus.PRECONDITION_REQUIRED).isEqualTo(428);
BDDAssertions.then(new HttpStatus().PRECONDITION_REQUIRED())
.isEqualTo(HttpStatus.PRECONDITION_REQUIRED);
BDDAssertions.then(new HttpStatus().PRECONDITION_REQUIRED()).isEqualTo(HttpStatus.PRECONDITION_REQUIRED);
}
@Test
public void TOO_MANY_REQUESTS() {
BDDAssertions.then(HttpStatus.TOO_MANY_REQUESTS).isEqualTo(429);
BDDAssertions.then(new HttpStatus().TOO_MANY_REQUESTS())
.isEqualTo(HttpStatus.TOO_MANY_REQUESTS);
BDDAssertions.then(new HttpStatus().TOO_MANY_REQUESTS()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS);
}
@Test
@@ -400,36 +364,31 @@ public class HttpStatusTests {
@Test
public void INTERNAL_SERVER_ERROR() {
BDDAssertions.then(HttpStatus.INTERNAL_SERVER_ERROR).isEqualTo(500);
BDDAssertions.then(new HttpStatus().INTERNAL_SERVER_ERROR())
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
BDDAssertions.then(new HttpStatus().INTERNAL_SERVER_ERROR()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
}
@Test
public void NOT_IMPLEMENTED() {
BDDAssertions.then(HttpStatus.NOT_IMPLEMENTED).isEqualTo(501);
BDDAssertions.then(new HttpStatus().NOT_IMPLEMENTED())
.isEqualTo(HttpStatus.NOT_IMPLEMENTED);
BDDAssertions.then(new HttpStatus().NOT_IMPLEMENTED()).isEqualTo(HttpStatus.NOT_IMPLEMENTED);
}
@Test
public void BAD_GATEWAY() {
BDDAssertions.then(HttpStatus.BAD_GATEWAY).isEqualTo(502);
BDDAssertions.then(new HttpStatus().BAD_GATEWAY())
.isEqualTo(HttpStatus.BAD_GATEWAY);
BDDAssertions.then(new HttpStatus().BAD_GATEWAY()).isEqualTo(HttpStatus.BAD_GATEWAY);
}
@Test
public void SERVICE_UNAVAILABLE() {
BDDAssertions.then(HttpStatus.SERVICE_UNAVAILABLE).isEqualTo(503);
BDDAssertions.then(new HttpStatus().SERVICE_UNAVAILABLE())
.isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
BDDAssertions.then(new HttpStatus().SERVICE_UNAVAILABLE()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
}
@Test
public void GATEWAY_TIMEOUT() {
BDDAssertions.then(HttpStatus.GATEWAY_TIMEOUT).isEqualTo(504);
BDDAssertions.then(new HttpStatus().GATEWAY_TIMEOUT())
.isEqualTo(HttpStatus.GATEWAY_TIMEOUT);
BDDAssertions.then(new HttpStatus().GATEWAY_TIMEOUT()).isEqualTo(HttpStatus.GATEWAY_TIMEOUT);
}
@Test
@@ -442,36 +401,31 @@ public class HttpStatusTests {
@Test
public void VARIANT_ALSO_NEGOTIATES() {
BDDAssertions.then(HttpStatus.VARIANT_ALSO_NEGOTIATES).isEqualTo(506);
BDDAssertions.then(new HttpStatus().VARIANT_ALSO_NEGOTIATES())
.isEqualTo(HttpStatus.VARIANT_ALSO_NEGOTIATES);
BDDAssertions.then(new HttpStatus().VARIANT_ALSO_NEGOTIATES()).isEqualTo(HttpStatus.VARIANT_ALSO_NEGOTIATES);
}
@Test
public void INSUFFICIENT_STORAGE() {
BDDAssertions.then(HttpStatus.INSUFFICIENT_STORAGE).isEqualTo(507);
BDDAssertions.then(new HttpStatus().INSUFFICIENT_STORAGE())
.isEqualTo(HttpStatus.INSUFFICIENT_STORAGE);
BDDAssertions.then(new HttpStatus().INSUFFICIENT_STORAGE()).isEqualTo(HttpStatus.INSUFFICIENT_STORAGE);
}
@Test
public void LOOP_DETECTED() {
BDDAssertions.then(HttpStatus.LOOP_DETECTED).isEqualTo(508);
BDDAssertions.then(new HttpStatus().LOOP_DETECTED())
.isEqualTo(HttpStatus.LOOP_DETECTED);
BDDAssertions.then(new HttpStatus().LOOP_DETECTED()).isEqualTo(HttpStatus.LOOP_DETECTED);
}
@Test
public void BANDWIDTH_LIMIT_EXCEEDED() {
BDDAssertions.then(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED).isEqualTo(509);
BDDAssertions.then(new HttpStatus().BANDWIDTH_LIMIT_EXCEEDED())
.isEqualTo(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED);
BDDAssertions.then(new HttpStatus().BANDWIDTH_LIMIT_EXCEEDED()).isEqualTo(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED);
}
@Test
public void NOT_EXTENDED() {
BDDAssertions.then(HttpStatus.NOT_EXTENDED).isEqualTo(510);
BDDAssertions.then(new HttpStatus().NOT_EXTENDED())
.isEqualTo(HttpStatus.NOT_EXTENDED);
BDDAssertions.then(new HttpStatus().NOT_EXTENDED()).isEqualTo(HttpStatus.NOT_EXTENDED);
}
@Test

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();

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