Search in sources :

Example 1 with XmlSlurper

use of groovy.util.XmlSlurper in project camel by apache.

the class XmlSlurperDataFormat method newSlurper.

private XmlSlurper newSlurper() throws Exception {
    XmlSlurper slurper = new XmlSlurper(newSaxParser());
    slurper.setErrorHandler(getErrorHandler());
    slurper.setKeepWhitespace(isKeepWhitespace());
    return slurper;
}
Also used : XmlSlurper(groovy.util.XmlSlurper)

Example 2 with XmlSlurper

use of groovy.util.XmlSlurper 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 3 with XmlSlurper

use of groovy.util.XmlSlurper 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 4 with XmlSlurper

use of groovy.util.XmlSlurper in project mdw-designer by CenturyLinkCloud.

the class GroovyTestCaseScript method gpath.

/**
 * Matches according to GPath.
 */
public Closure<Boolean> gpath(final String condition) throws TestException {
    return new Closure<Boolean>(this, this) {

        @Override
        public Boolean call(Object request) {
            try {
                GPathResult gpathRequest = new XmlSlurper().parseText(request.toString());
                Binding binding = getBinding();
                binding.setVariable("request", gpathRequest);
                return (Boolean) new GroovyShell(binding).evaluate(condition);
            } catch (Exception ex) {
                getTestCaseRun().log.println("Failed to parse request as XML/JSON. Stub response: " + AdapterActivity.MAKE_ACTUAL_CALL);
                return false;
            }
        }
    };
}
Also used : Binding(groovy.lang.Binding) Closure(groovy.lang.Closure) XmlSlurper(groovy.util.XmlSlurper) JSONObject(org.json.JSONObject) GPathResult(groovy.util.slurpersupport.GPathResult) GroovyShell(groovy.lang.GroovyShell) IOException(java.io.IOException) MbengException(com.qwest.mbeng.MbengException)

Aggregations

XmlSlurper (groovy.util.XmlSlurper)4 GPathResult (groovy.util.slurpersupport.GPathResult)3 MbengException (com.qwest.mbeng.MbengException)2 JsonSlurper (groovy.json.JsonSlurper)2 Binding (groovy.lang.Binding)2 Closure (groovy.lang.Closure)2 GroovyShell (groovy.lang.GroovyShell)2 IOException (java.io.IOException)2 JSONObject (org.json.JSONObject)2 GroovityConstants (com.disney.groovity.GroovityConstants)1 Taggable (com.disney.groovity.Taggable)1 Attr (com.disney.groovity.doc.Attr)1 Tag (com.disney.groovity.doc.Tag)1 Model (com.disney.groovity.model.Model)1 GroovySystem (groovy.lang.GroovySystem)1 MetaClass (groovy.lang.MetaClass)1 MetaProperty (groovy.lang.MetaProperty)1 Writable (groovy.lang.Writable)1 DelegatingScript (groovy.util.DelegatingScript)1 Node (groovy.util.slurpersupport.Node)1