use of groovy.json.JsonSlurper in project pact-jvm by DiUS.
the class Defect266Test method getUsersFragment.
@Pact(provider = "266_provider", consumer = "test_consumer")
public RequestResponsePact getUsersFragment(PactDslWithProvider builder) {
Map<String, Map<String, Object>> matchers = (Map<String, Map<String, Object>>) new JsonSlurper().parseText("{" + "\"$.body[0][*].userName\": {\"match\": \"type\"}," + "\"$.body[0][*].id\": {\"match\": \"regex\", \"regex\": \"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\"}," + "\"$.body[0]\": {\"match\": \"type\", \"max\": 5}," + "\"$.body[0][*].email\": {\"match\": \"type\"}" + "}");
DslPart body = new PactDslJsonArray().maxArrayLike(5).uuid("id").stringType("userName").stringType("email").closeObject();
RequestResponsePact pact = builder.given("a user with an id named 'user' exists").uponReceiving("get all users for max").path("/idm/user").method("GET").willRespondWith().status(200).body(body).toPact();
assertThat(pact.getInteractions().get(0).getResponse().getMatchingRules(), is(equalTo(matchers)));
return pact;
}
use of groovy.json.JsonSlurper in project pact-jvm by DiUS.
the class Defect266Test method getUsersFragment2.
@Pact(provider = "266_provider", consumer = "test_consumer")
public RequestResponsePact getUsersFragment2(PactDslWithProvider builder) {
Map<String, Map<String, Object>> matchers = (Map<String, Map<String, Object>>) new JsonSlurper().parseText("{" + "\"$.body[0][*].userName\": {\"match\": \"type\"}," + "\"$.body[0][*].id\": {\"match\": \"regex\", \"regex\": \"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\"}," + "\"$.body[0]\": {\"match\": \"type\", \"min\": 5}," + "\"$.body[0][*].email\": {\"match\": \"type\"}" + "}");
DslPart body = new PactDslJsonArray().minArrayLike(5).uuid("id").stringType("userName").stringType("email").closeObject();
RequestResponsePact pact = builder.given("a user with an id named 'user' exists").uponReceiving("get all users for min").path("/idm/user").method("GET").willRespondWith().status(200).body(body).toPact();
assertThat(pact.getInteractions().get(0).getResponse().getMatchingRules(), is(equalTo(matchers)));
return pact;
}
use of groovy.json.JsonSlurper in project groovity by disney.
the class Parse method parse.
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object parse(Object value, String format, final Object target) throws Exception {
Reader reader = null;
Object result = target;
if (value instanceof Reader) {
reader = ((Reader) value);
} else if (value instanceof InputStream) {
reader = new BufferedReader(new InputStreamReader((InputStream) value, "UTF-8"));
} else if (value instanceof File) {
reader = new FileReader((File) value);
} else if (value instanceof byte[]) {
String str = new String(((byte[]) value), "UTF-8").trim();
reader = new StringReader(str);
if (format == null) {
if (str.startsWith("<")) {
format = "xml";
}
}
} else if (value instanceof HttpResponse) {
HttpResponse response = (HttpResponse) value;
HttpEntity entity = response.getEntity();
if (entity != null) {
org.apache.http.Header ct = entity.getContentType();
String charset = "UTF-8";
if (ct != null) {
String contentType = ct.getValue();
Matcher charMatcher = charsetPattern.matcher(contentType);
if (charMatcher.find()) {
charset = charMatcher.group(1);
}
if (format == null) {
if (contentType.contains("xml")) {
format = "xml";
}
}
}
reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset));
}
} else if (value instanceof Map) {
if (target.equals(Object.class)) {
result = Model.copy(value);
} else {
((Map) value).forEach((k, v) -> {
Model.put(target, k.toString(), v);
});
}
} else if (value != null) {
// check for http request
MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(value.getClass());
MetaProperty mp = mc.hasProperty(value, "reader");
if (mp != null && Reader.class.isAssignableFrom(mp.getType())) {
reader = (Reader) mp.getProperty(value);
if (format == null) {
MetaProperty ctp = mc.hasProperty(value, "contentType");
if (ctp != null) {
String ct = (String) ctp.getProperty(value);
if (ct != null && ct.contains("xml")) {
format = "xml";
}
}
}
} else {
String toParse = value.toString().trim();
reader = new StringReader(toParse);
if (format == null) {
if (toParse.startsWith("<")) {
format = "xml";
}
}
}
}
if (reader != null) {
if (format != null && "xml".equalsIgnoreCase(format.toString())) {
boolean usejaxb = false;
if (!target.equals(Object.class)) {
if (target.getClass().isAnnotationPresent(XmlRootElement.class)) {
usejaxb = true;
}
}
if (usejaxb) {
JAXBContext context = getJAXBContext(target.getClass());
Unmarshaller um = context.createUnmarshaller();
XMLReader xreader = borrowXMLReader();
try {
result = um.unmarshal(new SAXSource(xreader, new InputSource(reader)));
} finally {
returnXMLReader(xreader);
reader.close();
}
} else {
XMLReader xreader = borrowXMLReader();
try {
XmlSlurper slurper = new XmlSlurper(xreader);
GPathResult gpr = slurper.parse(reader);
Object converted = convert(gpr);
if (!target.equals(Object.class)) {
if (target instanceof Model) {
Model.each(converted, ((Model) target)::put);
} else {
Model.each(converted, (k, v) -> {
Model.put(target, k, v);
});
}
} else {
result = converted;
}
} finally {
returnXMLReader(xreader);
reader.close();
}
}
} else {
try {
Object parsed = new JsonSlurper().parse(reader);
if (!target.equals(Object.class)) {
if (target instanceof Model) {
Model.each(parsed, ((Model) target)::put);
} else {
Model.each(parsed, (k, v) -> {
Model.put(target, k, v);
});
}
} else {
result = parsed;
}
} finally {
reader.close();
}
}
}
return result;
}
use of groovy.json.JsonSlurper in project mdw-designer by CenturyLinkCloud.
the class GroovyTestCaseScript method adapter.
/**
* responder closure call is delayed until stub server calls back
*/
public TestCaseAdapterStub adapter(Closure<Boolean> matcher, Closure<String> responder, Closure<?> init) throws TestException {
final TestCaseAdapterStub adapterStub = new TestCaseAdapterStub(matcher, responder);
if (init != null) {
init.setResolveStrategy(Closure.DELEGATE_FIRST);
init.setDelegate(adapterStub);
init.call();
}
if (responder == null) {
final TestCaseRun testCaseRun = getTestCaseRun();
adapterStub.setResponder(new Closure<String>(this, adapterStub) {
@Override
public String call(Object request) {
// binding for request
if (adapterStub.getResponse().indexOf("${") >= 0) {
try {
Binding binding = getBinding();
if (request.toString().startsWith("{")) {
Object req = new JsonSlurper().parseText(request.toString());
binding.setVariable("request", req);
} else {
GPathResult gpathRequest = new XmlSlurper().parseText(request.toString());
binding.setVariable("request", gpathRequest);
}
CompilerConfiguration compilerCfg = new CompilerConfiguration();
compilerCfg.setScriptBaseClass(DelegatingScript.class.getName());
GroovyShell shell = new GroovyShell(GroovyTestCaseScript.class.getClassLoader(), binding, compilerCfg);
shell.setProperty("out", testCaseRun.log);
DelegatingScript script = (DelegatingScript) shell.parse("return \"\"\"" + adapterStub.getResponse() + "\"\"\"");
script.setDelegate(GroovyTestCaseScript.this);
return script.run().toString();
} catch (Exception ex) {
getTestCaseRun().log.println("Cannot perform stub substitutions for request: " + request);
ex.printStackTrace(getTestCaseRun().log);
}
}
return adapterStub.getResponse();
}
});
}
return adapterStub;
}
use of groovy.json.JsonSlurper in project pact-jvm by DiUS.
the class ValueMatcherTest method runTest.
@Test
@PactVerification("ValueMatcherProvider")
public void runTest() throws IOException {
String result = Request.get(provider.getUrl()).addHeader("Accept", APPLICATION_JSON).execute().returnContent().asString();
Map<String, Object> body = (Map<String, Object>) new JsonSlurper().parseText(result);
assertThat(body, hasKey("foo"));
Map<String, Object> foo = (Map<String, Object>) body.get("foo");
assertThat(foo, hasKey("001"));
assertThat(foo.get("001"), is(42));
assertThat(body, hasKey("articles"));
List articles = (List) body.get("articles");
assertThat(articles.size(), is(1));
Map<String, Object> article = (Map<String, Object>) articles.get(0);
assertThat(article, hasKey("variants"));
List variants = (List) article.get("variants");
assertThat(variants.size(), is(1));
Map<String, Object> variant = (Map<String, Object>) variants.get(0);
assertThat(variant.keySet(), is(equalTo(Sets.newHashSet("001"))));
List variant001 = (List) variant.get("001");
assertThat(variant001.size(), is(1));
Map<String, Object> firstVariant001 = (Map<String, Object>) variant001.get(0);
assertThat(firstVariant001, hasKey("bundles"));
List bundles = (List) firstVariant001.get("bundles");
assertThat(bundles.size(), is(1));
Map<String, Object> bundle = (Map<String, Object>) bundles.get(0);
assertThat(bundle.keySet(), is(equalTo(Sets.newHashSet("001-A"))));
Map<String, Object> bundle001A = (Map<String, Object>) bundle.get("001-A");
assertThat(bundle001A.get("description").toString(), is("Some Description"));
assertThat(bundle001A, hasKey("referencedArticles"));
List referencedArticles = (List) bundle001A.get("referencedArticles");
assertThat(referencedArticles.size(), is(1));
Map<String, Object> referencedArticle = (Map<String, Object>) referencedArticles.get(0);
assertThat(referencedArticle, hasKey("bundleId"));
assertThat(referencedArticle.get("bundleId").toString(), is("23456"));
}
Aggregations