Search in sources :

Example 31 with TemplateModelException

use of freemarker.template.TemplateModelException in project freemarker by apache.

the class NodeModel method get.

public TemplateModel get(String key) throws TemplateModelException {
    if (key.startsWith("@@")) {
        if (key.equals(AtAtKey.TEXT.getKey())) {
            return new SimpleScalar(getText(node));
        } else if (key.equals(AtAtKey.NAMESPACE.getKey())) {
            String nsURI = node.getNamespaceURI();
            return nsURI == null ? null : new SimpleScalar(nsURI);
        } else if (key.equals(AtAtKey.LOCAL_NAME.getKey())) {
            String localName = node.getLocalName();
            if (localName == null) {
                localName = getNodeName();
            }
            return new SimpleScalar(localName);
        } else if (key.equals(AtAtKey.MARKUP.getKey())) {
            StringBuilder buf = new StringBuilder();
            NodeOutputter nu = new NodeOutputter(node);
            nu.outputContent(node, buf);
            return new SimpleScalar(buf.toString());
        } else if (key.equals(AtAtKey.NESTED_MARKUP.getKey())) {
            StringBuilder buf = new StringBuilder();
            NodeOutputter nu = new NodeOutputter(node);
            nu.outputContent(node.getChildNodes(), buf);
            return new SimpleScalar(buf.toString());
        } else if (key.equals(AtAtKey.QNAME.getKey())) {
            String qname = getQualifiedName();
            return qname != null ? new SimpleScalar(qname) : null;
        } else {
            // As @@... would cause exception in the XPath engine, we throw a nicer exception now.
            if (AtAtKey.containsKey(key)) {
                throw new TemplateModelException("\"" + key + "\" is not supported for an XML node of type \"" + getNodeType() + "\".");
            } else {
                throw new TemplateModelException("Unsupported @@ key: " + key);
            }
        }
    } else {
        XPathSupport xps = getXPathSupport();
        if (xps != null) {
            return xps.executeQuery(node, key);
        } else {
            throw new TemplateModelException("Can't try to resolve the XML query key, because no XPath support is available. " + "This is either malformed or an XPath expression: " + key);
        }
    }
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) SimpleScalar(freemarker.template.SimpleScalar)

Example 32 with TemplateModelException

use of freemarker.template.TemplateModelException in project freemarker by apache.

the class XalanXPathSupport method executeQuery.

/* " + ERRMSG_RECOMMEND_JAXEN;*/
public synchronized TemplateModel executeQuery(Object context, String xpathQuery) throws TemplateModelException {
    if (!(context instanceof Node)) {
        if (context != null) {
            if (isNodeList(context)) {
                int cnt = ((List) context).size();
                if (cnt != 0) {
                    throw new TemplateModelException("Cannot perform an XPath query against a node set of " + cnt + " nodes. Expecting a single node.");
                } else {
                    throw new TemplateModelException(ERRMSG_EMPTY_NODE_SET);
                }
            } else {
                throw new TemplateModelException("Cannot perform an XPath query against a " + context.getClass().getName() + ". Expecting a single org.w3c.dom.Node.");
            }
        } else {
            throw new TemplateModelException(ERRMSG_EMPTY_NODE_SET);
        }
    }
    Node node = (Node) context;
    try {
        XPath xpath = new XPath(xpathQuery, null, customPrefixResolver, XPath.SELECT, null);
        int ctxtNode = xpathContext.getDTMHandleFromNode(node);
        XObject xresult = xpath.execute(xpathContext, ctxtNode, customPrefixResolver);
        if (xresult instanceof XNodeSet) {
            NodeListModel result = new NodeListModel(node);
            result.xpathSupport = this;
            NodeIterator nodeIterator = xresult.nodeset();
            Node n;
            do {
                n = nodeIterator.nextNode();
                if (n != null) {
                    result.add(n);
                }
            } while (n != null);
            return result.size() == 1 ? result.get(0) : result;
        }
        if (xresult instanceof XBoolean) {
            return ((XBoolean) xresult).bool() ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
        }
        if (xresult instanceof XNull) {
            return null;
        }
        if (xresult instanceof XString) {
            return new SimpleScalar(xresult.toString());
        }
        if (xresult instanceof XNumber) {
            return new SimpleNumber(Double.valueOf(((XNumber) xresult).num()));
        }
        throw new TemplateModelException("Cannot deal with type: " + xresult.getClass().getName());
    } catch (TransformerException te) {
        throw new TemplateModelException(te);
    }
}
Also used : XPath(org.apache.xpath.XPath) NodeIterator(org.w3c.dom.traversal.NodeIterator) TemplateModelException(freemarker.template.TemplateModelException) XNull(org.apache.xpath.objects.XNull) XNumber(org.apache.xpath.objects.XNumber) Node(org.w3c.dom.Node) XBoolean(org.apache.xpath.objects.XBoolean) SimpleScalar(freemarker.template.SimpleScalar) XNodeSet(org.apache.xpath.objects.XNodeSet) SimpleNumber(freemarker.template.SimpleNumber) XString(org.apache.xpath.objects.XString) List(java.util.List) XObject(org.apache.xpath.objects.XObject) TransformerException(javax.xml.transform.TransformerException)

Example 33 with TemplateModelException

use of freemarker.template.TemplateModelException in project freemarker by apache.

the class DOMNodeModel method get.

public TemplateModel get(String key) throws TemplateModelException {
    TemplateModel result = null;
    if (equivalenceTable.containsKey(key)) {
        key = (String) equivalenceTable.get(key);
    }
    if (cache.containsKey(key)) {
        result = (TemplateModel) cache.get(key);
    }
    if (result == null) {
        if ("attributes".equals(key)) {
            NamedNodeMap attributes = node.getAttributes();
            if (attributes != null) {
                SimpleHash hash = new SimpleHash();
                for (int i = 0; i < attributes.getLength(); i++) {
                    Attr att = (Attr) attributes.item(i);
                    hash.put(att.getName(), att.getValue());
                }
                result = hash;
            }
        } else if (key.charAt(0) == '@') {
            if (node instanceof Element) {
                String attValue = ((Element) node).getAttribute(key.substring(1));
                result = new SimpleScalar(attValue);
            } else {
                throw new TemplateModelException("Trying to get an attribute value for a non-element node");
            }
        } else if ("is_element".equals(key)) {
            result = (node instanceof Element) ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
        } else if ("is_text".equals(key)) {
            result = (node instanceof Text) ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
        } else if ("name".equals(key)) {
            result = new SimpleScalar(node.getNodeName());
        } else if ("children".equals(key)) {
            result = new NodeListTM(node.getChildNodes());
        } else if ("parent".equals(key)) {
            Node parent = node.getParentNode();
            result = (parent == null) ? null : new DOMNodeModel(parent);
        } else if ("ancestorByName".equals(key)) {
            result = new AncestorByName();
        } else if ("nextSibling".equals(key)) {
            Node next = node.getNextSibling();
            result = (next == null) ? null : new DOMNodeModel(next);
        } else if ("previousSibling".equals(key)) {
            Node previous = node.getPreviousSibling();
            result = (previous == null) ? null : new DOMNodeModel(previous);
        } else if ("nextSiblingElement".equals(key)) {
            Node next = nextSiblingElement(node);
            result = (next == null) ? null : new DOMNodeModel(next);
        } else if ("previousSiblingElement".equals(key)) {
            Node previous = previousSiblingElement(node);
            result = (previous == null) ? null : new DOMNodeModel(previous);
        } else if ("nextElement".equals(key)) {
            Node next = nextElement(node);
            result = (next == null) ? null : new DOMNodeModel(next);
        } else if ("previousElement".equals(key)) {
            Node previous = previousElement(node);
            result = (previous == null) ? null : new DOMNodeModel(previous);
        } else if ("text".equals(key)) {
            result = new SimpleScalar(getText(node));
        }
        cache.put(key, result);
    }
    return result;
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) NamedNodeMap(org.w3c.dom.NamedNodeMap) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) Text(org.w3c.dom.Text) TemplateModel(freemarker.template.TemplateModel) SimpleScalar(freemarker.template.SimpleScalar) Attr(org.w3c.dom.Attr) SimpleHash(freemarker.template.SimpleHash)

Example 34 with TemplateModelException

use of freemarker.template.TemplateModelException in project freemarker by apache.

the class StandardCompress method getWriter.

public Writer getWriter(final Writer out, Map args) throws TemplateModelException {
    int bufferSize = defaultBufferSize;
    boolean singleLine = false;
    if (args != null) {
        try {
            TemplateNumberModel num = (TemplateNumberModel) args.get(BUFFER_SIZE_KEY);
            if (num != null)
                bufferSize = num.getAsNumber().intValue();
        } catch (ClassCastException e) {
            throw new TemplateModelException("Expecting numerical argument to " + BUFFER_SIZE_KEY);
        }
        try {
            TemplateBooleanModel flag = (TemplateBooleanModel) args.get(SINGLE_LINE_KEY);
            if (flag != null)
                singleLine = flag.getAsBoolean();
        } catch (ClassCastException e) {
            throw new TemplateModelException("Expecting boolean argument to " + SINGLE_LINE_KEY);
        }
    }
    return new StandardCompressWriter(out, bufferSize, singleLine);
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) TemplateNumberModel(freemarker.template.TemplateNumberModel) TemplateBooleanModel(freemarker.template.TemplateBooleanModel)

Example 35 with TemplateModelException

use of freemarker.template.TemplateModelException in project PublicCMS-preview by sanluan.

the class GetHtmlMethod method exec.

@SuppressWarnings("unchecked")
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException {
    String url = getString(0, arguments);
    TemplateHashModelEx paramters = getMap(1, arguments);
    String body = getString(1, arguments);
    String html = null;
    if (CommonUtils.notEmpty(url)) {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpUriRequest request;
            if (null != paramters || CommonUtils.notEmpty(body)) {
                HttpPost httppost = new HttpPost(url);
                if (null != paramters) {
                    List<NameValuePair> nvps = new ArrayList<>();
                    TemplateModelIterator it = paramters.keys().iterator();
                    while (it.hasNext()) {
                        String key = TemplateModelUtils.converString(it.next());
                        nvps.add(new BasicNameValuePair(key, TemplateModelUtils.converString(paramters.get(key))));
                    }
                    httppost.setEntity(new UrlEncodedFormEntity(nvps, DEFAULT_CHARSET));
                } else {
                    httppost.setEntity(new StringEntity(body, DEFAULT_CHARSET));
                }
                request = httppost;
            } else {
                request = new HttpGet(url);
            }
            try (CloseableHttpResponse response = httpclient.execute(request)) {
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    html = EntityUtils.toString(entity, DEFAULT_CHARSET);
                    EntityUtils.consume(entity);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
        return html;
    }
    return null;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) TemplateModelIterator(freemarker.template.TemplateModelIterator) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) TemplateModelException(freemarker.template.TemplateModelException) StringEntity(org.apache.http.entity.StringEntity) TemplateHashModelEx(freemarker.template.TemplateHashModelEx) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Aggregations

TemplateModelException (freemarker.template.TemplateModelException)87 TemplateModel (freemarker.template.TemplateModel)24 IOException (java.io.IOException)21 TemplateScalarModel (freemarker.template.TemplateScalarModel)18 SimpleScalar (freemarker.template.SimpleScalar)17 BeanModel (freemarker.ext.beans.BeanModel)14 Environment (freemarker.core.Environment)13 Writer (java.io.Writer)13 ArrayList (java.util.ArrayList)13 HttpServletRequest (javax.servlet.http.HttpServletRequest)12 Map (java.util.Map)10 List (java.util.List)9 SimpleNumber (freemarker.template.SimpleNumber)7 TemplateHashModel (freemarker.template.TemplateHashModel)7 Iterator (java.util.Iterator)6 freemarker.core._TemplateModelException (freemarker.core._TemplateModelException)5 TemplateHashModelEx (freemarker.template.TemplateHashModelEx)5 TemplateMethodModelEx (freemarker.template.TemplateMethodModelEx)5 TemplateModelIterator (freemarker.template.TemplateModelIterator)5 UMAException (com.ibm.uma.UMAException)4