Search in sources :

Example 1 with JsonSlurper

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;
}
Also used : JsonSlurper(groovy.json.JsonSlurper) PactDslJsonArray(au.com.dius.pact.consumer.dsl.PactDslJsonArray) RequestResponsePact(au.com.dius.pact.model.RequestResponsePact) DslPart(au.com.dius.pact.consumer.dsl.DslPart) Map(java.util.Map) RequestResponsePact(au.com.dius.pact.model.RequestResponsePact)

Example 2 with JsonSlurper

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;
}
Also used : JsonSlurper(groovy.json.JsonSlurper) PactDslJsonArray(au.com.dius.pact.consumer.dsl.PactDslJsonArray) RequestResponsePact(au.com.dius.pact.model.RequestResponsePact) DslPart(au.com.dius.pact.consumer.dsl.DslPart) Map(java.util.Map) RequestResponsePact(au.com.dius.pact.model.RequestResponsePact)

Example 3 with JsonSlurper

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;
}
Also used : XmlSlurper(groovy.util.XmlSlurper) Taggable(com.disney.groovity.Taggable) GroovySystem(groovy.lang.GroovySystem) Closure(groovy.lang.Closure) Writable(groovy.lang.Writable) GPathResult(groovy.util.slurpersupport.GPathResult) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) XMLReader(org.xml.sax.XMLReader) Node(groovy.util.slurpersupport.Node) Matcher(java.util.regex.Matcher) Map(java.util.Map) MetaProperty(groovy.lang.MetaProperty) JAXBContext(javax.xml.bind.JAXBContext) MetaClass(groovy.lang.MetaClass) Unmarshaller(javax.xml.bind.Unmarshaller) InputSource(org.xml.sax.InputSource) JsonSlurper(groovy.json.JsonSlurper) NodeChild(groovy.util.slurpersupport.NodeChild) Tag(com.disney.groovity.doc.Tag) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HttpEntity(org.apache.http.HttpEntity) CharArrayWriter(java.io.CharArrayWriter) Reader(java.io.Reader) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) JAXBException(javax.xml.bind.JAXBException) File(java.io.File) Attr(com.disney.groovity.doc.Attr) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) XMLReaderFactory(org.xml.sax.helpers.XMLReaderFactory) List(java.util.List) SAXSource(javax.xml.transform.sax.SAXSource) StringReader(java.io.StringReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) GroovityConstants(com.disney.groovity.GroovityConstants) HttpResponse(org.apache.http.HttpResponse) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) Queue(java.util.Queue) Pattern(java.util.regex.Pattern) Model(com.disney.groovity.model.Model) InputStream(java.io.InputStream) InputSource(org.xml.sax.InputSource) HttpEntity(org.apache.http.HttpEntity) Matcher(java.util.regex.Matcher) XmlSlurper(groovy.util.XmlSlurper) XMLReader(org.xml.sax.XMLReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) StringReader(java.io.StringReader) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) JAXBContext(javax.xml.bind.JAXBContext) StringReader(java.io.StringReader) FileReader(java.io.FileReader) GPathResult(groovy.util.slurpersupport.GPathResult) MetaProperty(groovy.lang.MetaProperty) Unmarshaller(javax.xml.bind.Unmarshaller) XMLReader(org.xml.sax.XMLReader) JsonSlurper(groovy.json.JsonSlurper) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) HttpResponse(org.apache.http.HttpResponse) SAXSource(javax.xml.transform.sax.SAXSource) MetaClass(groovy.lang.MetaClass) BufferedReader(java.io.BufferedReader) Model(com.disney.groovity.model.Model) File(java.io.File) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 4 with JsonSlurper

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;
}
Also used : Binding(groovy.lang.Binding) JsonSlurper(groovy.json.JsonSlurper) XmlSlurper(groovy.util.XmlSlurper) GroovyShell(groovy.lang.GroovyShell) IOException(java.io.IOException) MbengException(com.qwest.mbeng.MbengException) DelegatingScript(groovy.util.DelegatingScript) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) JSONObject(org.json.JSONObject) GPathResult(groovy.util.slurpersupport.GPathResult)

Example 5 with JsonSlurper

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"));
}
Also used : JsonSlurper(groovy.json.JsonSlurper) List(java.util.List) Map(java.util.Map) Test(org.junit.Test)

Aggregations

JsonSlurper (groovy.json.JsonSlurper)14 Map (java.util.Map)9 List (java.util.List)6 IOException (java.io.IOException)4 File (java.io.File)3 StringReader (java.io.StringReader)3 ArrayList (java.util.ArrayList)3 Test (org.junit.Test)3 DslPart (au.com.dius.pact.consumer.dsl.DslPart)2 PactDslJsonArray (au.com.dius.pact.consumer.dsl.PactDslJsonArray)2 RequestResponsePact (au.com.dius.pact.model.RequestResponsePact)2 XmlSlurper (groovy.util.XmlSlurper)2 GPathResult (groovy.util.slurpersupport.GPathResult)2 FileInputStream (java.io.FileInputStream)2 InputStream (java.io.InputStream)2 StringWriter (java.io.StringWriter)2 ArgsLookup (com.disney.groovity.ArgsLookup)1 BindingDecorator (com.disney.groovity.BindingDecorator)1 Groovity (com.disney.groovity.Groovity)1 GroovityBuilder (com.disney.groovity.GroovityBuilder)1