com.github.dreamhead.moco.matcher.JsonRequestMatcher Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of moco-core Show documentation
Show all versions of moco-core Show documentation
Moco is an easy setup stub framework, mainly focusing on testing and integration.
package com.github.dreamhead.moco.matcher;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dreamhead.moco.MocoConfig;
import com.github.dreamhead.moco.Request;
import com.github.dreamhead.moco.RequestExtractor;
import com.github.dreamhead.moco.RequestMatcher;
import com.github.dreamhead.moco.resource.Resource;
import com.google.common.base.Optional;
import java.io.IOException;
import static com.google.common.base.Optional.of;
public class JsonRequestMatcher extends AbstractRequestMatcher {
private final RequestExtractor extractor;
private final Resource resource;
private final ObjectMapper mapper;
public JsonRequestMatcher(final RequestExtractor extractor, final Resource resource) {
this.extractor = extractor;
this.resource = resource;
this.mapper = new ObjectMapper();
}
@Override
public boolean match(final Request request) {
Optional content = extractor.extract(request);
return content.isPresent() && doMatch(request, content.get());
}
private boolean doMatch(final Request request, final String content) {
try {
JsonNode requestNode = mapper.readTree(content);
JsonNode resourceNode = mapper.readTree(resource.readFor(of(request)).getContent());
return requestNode.equals(resourceNode);
} catch (JsonProcessingException jpe) {
return false;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
@SuppressWarnings("unchecked")
public RequestMatcher doApply(final MocoConfig config) {
Resource appliedResource = this.resource.apply(config);
if (appliedResource == this.resource) {
return this;
}
return new JsonRequestMatcher(this.extractor, appliedResource);
}
}