Search in sources :

Example 1 with GPathResult

use of groovy.util.slurpersupport.GPathResult 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 2 with GPathResult

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

use of groovy.util.slurpersupport.GPathResult 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)

Example 4 with GPathResult

use of groovy.util.slurpersupport.GPathResult in project rest-assured by rest-assured.

the class XmlPath method peek.

/**
 * Peeks into the XML/HTML that XmlPath will parse by printing it to the console. You can
 * continue working with XmlPath afterwards. This is mainly for debug purposes. If you want to return a prettified version of the content
 * see {@link #prettify()}. If you want to return a prettified version of the content and also print it to the console use {@link #prettyPrint()}.
 * <p/>
 * <p>
 * Note that the content is not guaranteed to be looking exactly like the it does at the source. This is because once you peek
 * the content has been downloaded and transformed into another data structure (used by XmlPath) and the XML is rendered
 * from this data structure.
 * </p>
 *
 * @return The same XmlPath instance
 */
public XmlPath peek() {
    final GPathResult result = lazyXmlParser.invoke();
    final String render = XmlRenderer.render(result);
    System.out.println(render);
    return this;
}
Also used : GPathResult(groovy.util.slurpersupport.GPathResult)

Example 5 with GPathResult

use of groovy.util.slurpersupport.GPathResult in project groovity by disney.

the class Http method tag.

@SuppressWarnings({ "rawtypes", "unchecked" })
public Object tag(Map attributes, Closure body) throws Exception {
    Object url = resolve(attributes, "url");
    if (url == null) {
        throw new RuntimeException("<g:http> requires 'url' attribute");
    }
    Object var = resolve(attributes, VAR);
    String method = "GET";
    Object methodAtt = resolve(attributes, "method");
    if (methodAtt != null) {
        method = methodAtt.toString();
    }
    boolean followRedirects = true;
    Object redirectsAtt = resolve(attributes, "redirects");
    if (redirectsAtt != null) {
        followRedirects = Boolean.parseBoolean(redirectsAtt.toString());
    }
    CookieOption cookieOption = CookieOption.DEFAULT;
    Object cookiesAtt = resolve(attributes, "cookies");
    if (cookiesAtt != null) {
        cookieOption = CookieOption.valueOf(cookiesAtt.toString().toUpperCase());
    }
    Object timeout = resolve(attributes, TIMEOUT);
    final int timeoutSeconds = timeout == null ? -1 : timeout instanceof Number ? ((Number) timeout).intValue() : Integer.parseInt(timeout.toString());
    Object target = resolve(attributes, "to");
    if (target instanceof Class) {
        if (!Object.class.equals(target)) {
            target = ((Class) target).newInstance();
        }
    }
    if (target == null) {
        target = Object.class;
    }
    Object async = resolve(attributes, "async");
    if (async != null && !(async instanceof Boolean)) {
        async = Boolean.valueOf(async.toString());
    }
    HttpEntity dataEntity = null;
    Object data = resolve(attributes, "data");
    HttpClientContext clientContext = resolve(attributes, "context", HttpClientContext.class);
    if (clientContext == null) {
        clientContext = HttpClientContext.create();
    }
    if (clientContext.getCookieStore() == null) {
        // we don't want to let cookies be shared across contexts
        clientContext.setCookieStore(new BasicCookieStore());
    }
    if (clientContext.getAuthCache() == null) {
        // we also don't want to share credentials across contexts
        clientContext.setAuthCache(new BasicAuthCache());
    }
    final HttpClientContext fContext = clientContext;
    ScriptHelper context = getScriptHelper(body);
    Object oldOut = get(context, OUT);
    // execute body to assemble URL params, headers, post body
    Map variables = context.getBinding().getVariables();
    URI uri;
    URIBuilder builder;
    ArrayList<Header> headers;
    Optional<UserPass> userPass;
    Optional<HttpSignatureSigner> signer;
    Optional<HttpRequestInterceptor> interceptor;
    try {
        builder = new URIBuilder(url.toString());
        bind(context, Uri.CURRENT_URI_BUILDER, builder);
        headers = new ArrayList<Header>();
        bind(context, com.disney.groovity.tags.Header.CURRENT_LIST_FOR_HEADERS, headers);
        Credentials.acceptCredentials(variables);
        Signature.acceptSigner(variables);
        acceptInterceptor(variables);
        StringWriter sw = new StringWriter();
        bind(context, OUT, sw);
        try {
            Object rval = body.call();
            if (rval instanceof Writable) {
                ((Writable) rval).writeTo(sw);
            }
        } finally {
            bind(context, OUT, oldOut);
            userPass = Credentials.resolveCredentials(variables);
            signer = Signature.resolveSigner(variables);
            interceptor = resolveInterceptor(variables);
        }
        String val = sw.toString();
        if (val.trim().length() > 0) {
            dataEntity = new StringEntity(val);
        }
        uri = builder.build();
        if (userPass.isPresent()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(userPass.get().getUser(), new String(userPass.get().getPass())));
            clientContext.setCredentialsProvider(credsProvider);
        }
    } catch (URISyntaxException e1) {
        throw new RuntimeException("Invalid URI " + url, e1);
    } finally {
        unbind(context, Uri.CURRENT_URI_BUILDER);
        unbind(context, com.disney.groovity.tags.Header.CURRENT_LIST_FOR_HEADERS);
    }
    final HttpRequestBase request = "POST".equalsIgnoreCase(method) ? new HttpPost(uri) : "PUT".equalsIgnoreCase(method) ? new HttpPut(uri) : "HEAD".equalsIgnoreCase(method) ? new HttpHead(uri) : "DELETE".equalsIgnoreCase(method) ? new HttpDelete(uri) : "OPTIONS".equalsIgnoreCase(method) ? new HttpOptions(uri) : new HttpGet(uri);
    if (headers.size() > 0) {
        request.setHeaders(headers.toArray(new Header[0]));
    }
    if (request instanceof HttpEntityEnclosingRequest) {
        if (data != null) {
            // decide on strategy to convert data to entity
            if (data instanceof HttpEntity) {
                dataEntity = (HttpEntity) data;
            } else {
                // look at content type for a hint
                Header targetType = request.getFirstHeader("Content-Type");
                if (targetType != null && targetType.getValue().contains("json")) {
                    CharArrayWriter caw = new CharArrayWriter();
                    new ModelJsonWriter(caw).visit(data);
                    dataEntity = new StringEntity(caw.toString());
                } else if (targetType != null && targetType.getValue().contains("xml")) {
                    if (data instanceof groovy.util.Node) {
                        dataEntity = new StringEntity(XmlUtil.serialize((groovy.util.Node) data));
                    } else if (data instanceof GPathResult) {
                        dataEntity = new StringEntity(XmlUtil.serialize((GPathResult) data));
                    } else if (data instanceof Element) {
                        dataEntity = new StringEntity(XmlUtil.serialize((Element) data));
                    } else if (data instanceof Document) {
                        dataEntity = new StringEntity(XmlUtil.serialize(((Document) data).getDocumentElement()));
                    } else {
                        // if it's not an XML model assume it's a well formed XML string
                        dataEntity = new StringEntity(data.toString());
                    }
                } else if ((targetType != null && targetType.getValue().contains("x-www-form-urlencoded")) || (targetType == null && (data instanceof Map || data instanceof List))) {
                    // key/value pairs, accept a map, a list of maps, or a list of NameValuePairs
                    Iterator source = data instanceof Map ? ((Map) data).entrySet().iterator() : ((List) data).iterator();
                    ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
                    while (source.hasNext()) {
                        Object next = source.next();
                        if (next instanceof Map.Entry) {
                            Map.Entry entry = (Entry) next;
                            pairs.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue() != null ? entry.getValue().toString() : ""));
                        } else if (next instanceof NameValuePair) {
                            pairs.add((NameValuePair) next);
                        } else if (next instanceof Map) {
                            Iterator<Map.Entry> sub = ((Map) next).entrySet().iterator();
                            while (sub.hasNext()) {
                                Map.Entry se = sub.next();
                                pairs.add(new BasicNameValuePair(se.getKey().toString(), se.getValue() != null ? se.getValue().toString() : ""));
                            }
                        }
                    }
                    dataEntity = new UrlEncodedFormEntity(pairs);
                } else if (targetType != null && targetType.getValue().contains("multipart/form-data")) {
                    // list of maps, each map must contain "name" and "body", plus optional "type" and "filename"
                    Iterator<Map> parts = ((List<Map>) data).iterator();
                    MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
                    while (parts.hasNext()) {
                        Map part = parts.next();
                        Object pbody = part.get("body");
                        String name = (String) part.get("name");
                        String type = (String) part.get("type");
                        String filename = (String) part.get("filename");
                        ContentType ct = type != null ? ContentType.parse(type) : null;
                        if (pbody instanceof File) {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_BINARY;
                            }
                            meBuilder.addBinaryBody(name, (File) pbody, ct, filename);
                        } else if (pbody instanceof byte[]) {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_BINARY;
                            }
                            meBuilder.addBinaryBody(name, (byte[]) pbody, ct, filename);
                        } else if (pbody instanceof ContentBody) {
                            meBuilder.addPart(name, (ContentBody) pbody);
                        } else if (pbody instanceof InputStream) {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_BINARY;
                            }
                            meBuilder.addBinaryBody(name, (InputStream) pbody, ct, filename);
                        } else {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_TEXT;
                            }
                            meBuilder.addTextBody(name, pbody.toString(), ct);
                        }
                    }
                    dataEntity = meBuilder.build();
                } else {
                    // no help from content type header, check for modeled XML
                    if (data instanceof groovy.util.Node) {
                        dataEntity = new StringEntity(XmlUtil.serialize((groovy.util.Node) data), ContentType.APPLICATION_XML);
                    } else if (data instanceof GPathResult) {
                        dataEntity = new StringEntity(XmlUtil.serialize((GPathResult) data), ContentType.APPLICATION_XML);
                    } else if (data instanceof Element) {
                        dataEntity = new StringEntity(XmlUtil.serialize((Element) data), ContentType.APPLICATION_XML);
                    } else if (data instanceof Document) {
                        dataEntity = new StringEntity(XmlUtil.serialize(((Document) data).getDocumentElement()), ContentType.APPLICATION_XML);
                    } else if (data instanceof byte[]) {
                        dataEntity = new ByteArrayEntity((byte[]) data);
                    } else if (data instanceof InputStream) {
                        dataEntity = new InputStreamEntity((InputStream) data);
                    } else if (data instanceof File) {
                        dataEntity = new FileEntity((File) data);
                    } else {
                        // best option left is to post the toString value of the data
                        dataEntity = new StringEntity(data.toString());
                    }
                }
            }
        }
        if (dataEntity != null) {
            ((HttpEntityEnclosingRequest) request).setEntity(dataEntity);
        }
    }
    RequestConfig.Builder configBuilder = request.getConfig() == null ? RequestConfig.custom() : RequestConfig.copy(request.getConfig());
    if (!followRedirects) {
        configBuilder.setRedirectsEnabled(followRedirects);
    }
    configBuilder.setCookieSpec(cookieOption.getCookieSpec());
    request.setConfig(configBuilder.build());
    final String varName = var != null ? var.toString() : null;
    ResponseHandler handler = null;
    try {
        Function handlerFunction = (Function) get(body, Handler.HANDLER_BINDING);
        if (handlerFunction != null) {
            handler = new ResponseHandler<Object>() {

                @Override
                public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                    return handlerFunction.apply(response);
                }
            };
        }
        unbind(body, Handler.HANDLER_BINDING);
    } catch (Exception e) {
    }
    if (handler == null) {
        handler = new AutoParsingResponseHandler(target);
    }
    final List<HttpRequestInterceptor> interceptors = new ArrayList<>();
    if (signer.isPresent()) {
        interceptors.add(signer.get());
    }
    if (interceptor.isPresent()) {
        interceptors.add(interceptor.get());
    }
    final ResponseHandler rHandler = handler;
    final boolean isAsync = (async != null && Boolean.TRUE.equals(async));
    Callable<Object> requester = new Callable() {

        public Object call() throws Exception {
            TimeoutTask timeoutTask = null;
            if (timeoutSeconds > 0) {
                timeoutTask = new TimeoutTask(request);
                timeoutTimer.schedule(timeoutTask, timeoutSeconds * 1000);
            }
            try {
                Binding oldThreadBinding = null;
                if (isAsync) {
                    oldThreadBinding = ScriptHelper.THREAD_BINDING.get();
                    Binding asyncBinding = new Binding();
                    asyncBinding.setVariable("request", request);
                    ScriptHelper.THREAD_BINDING.set(asyncBinding);
                }
                try {
                    for (HttpRequestInterceptor interceptor : interceptors) {
                        interceptor.process(request, null);
                    }
                    return httpClient.execute(request, rHandler, fContext);
                } finally {
                    if (isAsync) {
                        if (oldThreadBinding == null) {
                            ScriptHelper.THREAD_BINDING.remove();
                        } else {
                            ScriptHelper.THREAD_BINDING.set(oldThreadBinding);
                        }
                    }
                }
            } catch (HttpResponseException e) {
                if (isAsync) {
                    log.error("Async HTTP response error for " + request.getURI() + ": " + e.getMessage());
                }
                throw e;
            } catch (Exception e) {
                if (request.isAborted()) {
                    if (isAsync) {
                        log.error("Async <g:http> request timed out for " + request.getURI());
                    }
                    throw new TimeoutException("Timed out executing <g:http> for " + request.getURI());
                } else {
                    if (isAsync) {
                        log.error("Async <g:http> request error for " + request.getURI(), e);
                    }
                    throw new RuntimeException("Error executing <g:http> for " + request.getURI(), e);
                }
            } finally {
                if (timeoutTask != null) {
                    timeoutTask.cancel();
                }
            }
        }
    };
    Object responseVar = null;
    if (isAsync) {
        // return the Future to the calling code
        Future<Object> f = asyncExecutor.submit(requester);
        responseVar = new Future<Object>() {

            @Override
            public boolean cancel(boolean mayInterruptIfRunning) {
                return f.cancel(mayInterruptIfRunning);
            }

            @Override
            public boolean isCancelled() {
                return f.isCancelled();
            }

            @Override
            public boolean isDone() {
                return f.isDone();
            }

            @Override
            public Object get() throws InterruptedException, ExecutionException {
                GroovityStatistics.startExecution("http(async)");
                try {
                    return f.get();
                } finally {
                    GroovityStatistics.endExecution();
                }
            }

            @Override
            public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
                GroovityStatistics.startExecution("http(async)");
                try {
                    return f.get(timeout, unit);
                } finally {
                    GroovityStatistics.endExecution();
                }
            }
        };
    } else {
        // return the parsed/handled response object
        GroovityStatistics.startExecution("http(sync)");
        try {
            responseVar = requester.call();
        } finally {
            GroovityStatistics.endExecution();
        }
    }
    if (varName != null) {
        bind(context, varName, responseVar);
    }
    return responseVar;
}
Also used : Entry(java.util.Map.Entry) HttpPost(org.apache.http.client.methods.HttpPost) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) ContentType(org.apache.http.entity.ContentType) ResponseHandler(org.apache.http.client.ResponseHandler) HttpOptions(org.apache.http.client.methods.HttpOptions) ArrayList(java.util.ArrayList) Writable(groovy.lang.Writable) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) Document(org.w3c.dom.Document) HttpPut(org.apache.http.client.methods.HttpPut) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) ArrayList(java.util.ArrayList) TimeoutException(java.util.concurrent.TimeoutException) Binding(groovy.lang.Binding) RequestConfig(org.apache.http.client.config.RequestConfig) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) URIBuilder(org.apache.http.client.utils.URIBuilder) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Header(org.apache.http.Header) ContentBody(org.apache.http.entity.mime.content.ContentBody) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) AuthScope(org.apache.http.auth.AuthScope) ModelJsonWriter(com.disney.groovity.model.ModelJsonWriter) ScriptHelper(com.disney.groovity.util.ScriptHelper) Map(java.util.Map) File(java.io.File) HttpEntity(org.apache.http.HttpEntity) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpGet(org.apache.http.client.methods.HttpGet) Element(org.w3c.dom.Element) HttpResponseException(org.apache.http.client.HttpResponseException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) HttpHead(org.apache.http.client.methods.HttpHead) CharArrayWriter(java.io.CharArrayWriter) Callable(java.util.concurrent.Callable) Function(java.util.function.Function) Entry(java.util.Map.Entry) StringWriter(java.io.StringWriter) HttpSignatureSigner(com.disney.http.auth.client.signer.HttpSignatureSigner) Iterator(java.util.Iterator) GPathResult(groovy.util.slurpersupport.GPathResult) ExecutionException(java.util.concurrent.ExecutionException) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) FileEntity(org.apache.http.entity.FileEntity) InputStream(java.io.InputStream) HttpResponse(org.apache.http.HttpResponse) UserPass(com.disney.groovity.tags.Credentials.UserPass) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) TimeoutException(java.util.concurrent.TimeoutException) ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) InputStreamEntity(org.apache.http.entity.InputStreamEntity)

Aggregations

GPathResult (groovy.util.slurpersupport.GPathResult)7 Binding (groovy.lang.Binding)3 XmlSlurper (groovy.util.XmlSlurper)3 IOException (java.io.IOException)3 MbengException (com.qwest.mbeng.MbengException)2 JsonSlurper (groovy.json.JsonSlurper)2 Closure (groovy.lang.Closure)2 GroovyShell (groovy.lang.GroovyShell)2 Writable (groovy.lang.Writable)2 CharArrayWriter (java.io.CharArrayWriter)2 File (java.io.File)2 InputStream (java.io.InputStream)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Map (java.util.Map)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