Search in sources :

Example 16 with TemplateModelException

use of freemarker.template.TemplateModelException in project ofbiz-framework by apache.

the class OfbizCatalogAltUrlTransform method getWriter.

@Override
public Writer getWriter(final Writer out, final Map args) throws TemplateModelException, IOException {
    final StringBuilder buf = new StringBuilder();
    final boolean fullPath = checkArg(args, "fullPath", false);
    final boolean secure = checkArg(args, "secure", false);
    return new Writer(out) {

        @Override
        public void write(char[] cbuf, int off, int len) throws IOException {
            buf.append(cbuf, off, len);
        }

        @Override
        public void flush() throws IOException {
            out.flush();
        }

        @Override
        public void close() throws IOException {
            try {
                Environment env = Environment.getCurrentEnvironment();
                BeanModel req = (BeanModel) env.getVariable("request");
                String previousCategoryId = getStringArg(args, "previousCategoryId");
                String productCategoryId = getStringArg(args, "productCategoryId");
                String productId = getStringArg(args, "productId");
                String url = "";
                Object prefix = env.getVariable("urlPrefix");
                String viewSize = getStringArg(args, "viewSize");
                String viewIndex = getStringArg(args, "viewIndex");
                String viewSort = getStringArg(args, "viewSort");
                String searchString = getStringArg(args, "searchString");
                if (req != null) {
                    HttpServletRequest request = (HttpServletRequest) req.getWrappedObject();
                    StringBuilder newURL = new StringBuilder();
                    if (UtilValidate.isNotEmpty(productId)) {
                        url = CatalogUrlFilter.makeProductUrl(request, previousCategoryId, productCategoryId, productId);
                    } else {
                        url = CatalogUrlFilter.makeCategoryUrl(request, previousCategoryId, productCategoryId, productId, viewSize, viewIndex, viewSort, searchString);
                    }
                    // make the link
                    if (fullPath) {
                        OfbizUrlBuilder builder = OfbizUrlBuilder.from(request);
                        builder.buildHostPart(newURL, url, secure);
                    }
                    newURL.append(url);
                    out.write(newURL.toString());
                } else if (prefix != null) {
                    Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
                    LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
                    Locale locale = (Locale) args.get("locale");
                    if (UtilValidate.isNotEmpty(productId)) {
                        GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
                        ProductContentWrapper wrapper = new ProductContentWrapper(dispatcher, product, locale, EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", delegator));
                        url = CatalogUrlFilter.makeProductUrl(wrapper, null, ((StringModel) prefix).getAsString(), previousCategoryId, productCategoryId, productId);
                    } else {
                        GenericValue productCategory = EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", productCategoryId).queryOne();
                        CategoryContentWrapper wrapper = new CategoryContentWrapper(dispatcher, productCategory, locale, EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", delegator));
                        url = CatalogUrlFilter.makeCategoryUrl(delegator, wrapper, null, ((StringModel) prefix).getAsString(), previousCategoryId, productCategoryId, productId, viewSize, viewIndex, viewSort, searchString);
                    }
                    out.write(url);
                } else {
                    out.write(buf.toString());
                }
            } catch (TemplateModelException | GenericEntityException | WebAppConfigurationException e) {
                throw new IOException(e.getMessage());
            }
        }
    };
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) TemplateModelException(freemarker.template.TemplateModelException) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) BeanModel(freemarker.ext.beans.BeanModel) OfbizUrlBuilder(org.apache.ofbiz.webapp.OfbizUrlBuilder) CategoryContentWrapper(org.apache.ofbiz.product.category.CategoryContentWrapper) IOException(java.io.IOException) WebAppConfigurationException(org.apache.ofbiz.webapp.control.WebAppConfigurationException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Delegator(org.apache.ofbiz.entity.Delegator) ProductContentWrapper(org.apache.ofbiz.product.product.ProductContentWrapper) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Environment(freemarker.core.Environment) Writer(java.io.Writer)

Example 17 with TemplateModelException

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

the class FreemarkerServlet method createModel.

protected TemplateModel createModel(ObjectWrapper objectWrapper, ServletContext servletContext, final HttpServletRequest request, final HttpServletResponse response) throws TemplateModelException {
    try {
        AllHttpScopesHashModel params = new AllHttpScopesHashModel(objectWrapper, servletContext, request);
        // Create hash model wrapper for servlet context (the application)
        final ServletContextHashModel servletContextModel;
        final TaglibFactory taglibFactory;
        synchronized (lazyInitFieldsLock) {
            if (this.servletContextModel == null) {
                servletContextModel = new ServletContextHashModel(this, objectWrapper);
                taglibFactory = createTaglibFactory(objectWrapper, servletContext);
                // For backward compatibility only. We don't use these:
                servletContext.setAttribute(ATTR_APPLICATION_MODEL, servletContextModel);
                servletContext.setAttribute(ATTR_JSP_TAGLIBS_MODEL, taglibFactory);
                initializeServletContext(request, response);
                this.taglibFactory = taglibFactory;
                this.servletContextModel = servletContextModel;
            } else {
                servletContextModel = this.servletContextModel;
                taglibFactory = this.taglibFactory;
            }
        }
        params.putUnlistedModel(KEY_APPLICATION, servletContextModel);
        params.putUnlistedModel(KEY_APPLICATION_PRIVATE, servletContextModel);
        params.putUnlistedModel(KEY_JSP_TAGLIBS, taglibFactory);
        // Create hash model wrapper for session
        HttpSessionHashModel sessionModel;
        HttpSession session = request.getSession(false);
        if (session != null) {
            sessionModel = (HttpSessionHashModel) session.getAttribute(ATTR_SESSION_MODEL);
            if (sessionModel == null || sessionModel.isOrphaned(session)) {
                sessionModel = new HttpSessionHashModel(session, objectWrapper);
                initializeSessionAndInstallModel(request, response, sessionModel, session);
            }
        } else {
            sessionModel = new HttpSessionHashModel(this, request, response, objectWrapper);
        }
        params.putUnlistedModel(KEY_SESSION, sessionModel);
        // Create hash model wrapper for request
        HttpRequestHashModel requestModel = (HttpRequestHashModel) request.getAttribute(ATTR_REQUEST_MODEL);
        if (requestModel == null || requestModel.getRequest() != request) {
            requestModel = new HttpRequestHashModel(request, response, objectWrapper);
            request.setAttribute(ATTR_REQUEST_MODEL, requestModel);
            request.setAttribute(ATTR_REQUEST_PARAMETERS_MODEL, createRequestParametersHashModel(request));
        }
        params.putUnlistedModel(KEY_REQUEST, requestModel);
        params.putUnlistedModel(KEY_INCLUDE, new IncludePage(request, response));
        params.putUnlistedModel(KEY_REQUEST_PRIVATE, requestModel);
        // Create hash model wrapper for request parameters
        HttpRequestParametersHashModel requestParametersModel = (HttpRequestParametersHashModel) request.getAttribute(ATTR_REQUEST_PARAMETERS_MODEL);
        params.putUnlistedModel(KEY_REQUEST_PARAMETERS, requestParametersModel);
        return params;
    } catch (ServletException e) {
        throw new TemplateModelException(e);
    } catch (IOException e) {
        throw new TemplateModelException(e);
    }
}
Also used : ServletException(javax.servlet.ServletException) TemplateModelException(freemarker.template.TemplateModelException) HttpSession(javax.servlet.http.HttpSession) TaglibFactory(freemarker.ext.jsp.TaglibFactory) IOException(java.io.IOException)

Example 18 with TemplateModelException

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

the class Navigator method applyXPath.

List applyXPath(List nodes, String xpathString, Object namespaces) throws TemplateModelException {
    XPathEx xpath = null;
    try {
        synchronized (xpathCache) {
            xpath = (XPathEx) xpathCache.get(xpathString);
            if (xpath == null) {
                xpath = createXPathEx(xpathString);
                xpathCache.put(xpathString, xpath);
            }
        }
        return xpath.selectNodes(nodes, (NamespaceContext) namespaces);
    } catch (Exception e) {
        throw new TemplateModelException("Could not evaulate XPath expression " + xpathString, e);
    }
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) TemplateModelException(freemarker.template.TemplateModelException)

Example 19 with TemplateModelException

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

the class NodeListModel method get.

/**
 * Returns a new NodeListModel containing the nodes that result from applying
 * an operator to this model's nodes.
 * @param key the operator to apply to nodes. Available operators are:
 * <table style="width: auto; border-collapse: collapse" border="1" summary="XML node hash keys">
 *   <thead>
 *     <tr>
 *       <th align="left">Key name</th>
 *       <th align="left">Evaluates to</th>
 *     </tr>
 *   </thead>
 *   <tbody>
 *     <tr>
 *       <td><tt>*</tt> or <tt>_children</tt></td>
 *       <td>all direct element children of current nodes (non-recursive).
 *         Applicable to element and document nodes.</td>
 *     </tr>
 *     <tr>
 *       <td><tt>@*</tt> or <tt>_attributes</tt></td>
 *       <td>all attributes of current nodes. Applicable to elements only.
 *         </td>
 *     </tr>
 *     <tr>
 *       <td><tt>@<i>attributeName</i></tt></td>
 *       <td>named attributes of current nodes. Applicable to elements,
 *         doctypes and processing instructions. On doctypes it supports
 *         attributes <tt>publicId</tt>, <tt>systemId</tt> and
 *         <tt>elementName</tt>. On processing instructions, it supports
 *         attributes <tt>target</tt> and <tt>data</tt>, as well as any
 *         other attribute name specified in data as
 *         <tt>name=&quot;value&quot;</tt> pair on dom4j or JDOM models.
 *         The attribute nodes for doctype and processing instruction are
 *         synthetic, and as such have no parent. Note, however that
 *         <tt>@*</tt> does NOT operate on doctypes or processing
 *         instructions.</td>
 *     </tr>
 *
 *     <tr>
 *       <td><tt>_ancestor</tt></td>
 *       <td>all ancestors up to root element (recursive) of current nodes.
 *         Applicable to same node types as <tt>_parent</tt>.</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_ancestorOrSelf</tt></td>
 *       <td>all ancestors of current nodes plus current nodes. Applicable
 *         to same node types as <tt>_parent</tt>.</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_cname</tt></td>
 *       <td>the canonical names of current nodes (namespace URI + local
 *         name), one string per node (non-recursive). Applicable to
 *         elements and attributes</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_content</tt></td>
 *       <td>the complete content of current nodes, including children
 *         elements, text, entity references, and processing instructions
 *         (non-recursive). Applicable to elements and documents.</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_descendant</tt></td>
 *       <td>all recursive descendant element children of current nodes.
 *         Applicable to document and element nodes.</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_descendantOrSelf</tt></td>
 *       <td>all recursive descendant element children of current nodes
 *         plus current nodes. Applicable to document and element nodes.
 *         </td>
 *     </tr>
 *     <tr>
 *       <td><tt>_document</tt></td>
 *       <td>all documents the current nodes belong to. Applicable to all
 *       nodes except text.</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_doctype</tt></td>
 *       <td>doctypes of the current nodes. Applicable to document nodes
 *       only.</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_filterType</tt></td>
 *       <td>is a filter-by-type template method model. When called, it
 *         will yield a node list that contains only those current nodes
 *         whose type matches one of types passed as argument. You can pass
 *         as many string arguments as you want, each representing one of
 *         the types to select: &quot;attribute&quot;, &quot;cdata&quot;,
 *         &quot;comment&quot;, &quot;document&quot;,
 *         &quot;documentType&quot;, &quot;element&quot;,
 *         &quot;entity&quot;, &quot;entityReference&quot;,
 *         &quot;namespace&quot;, &quot;processingInstruction&quot;, or
 *         &quot;text&quot;.</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_name</tt></td>
 *       <td>the names of current nodes, one string per node
 *         (non-recursive). Applicable to elements and attributes
 *         (returns their local names), entity references, processing
 *         instructions (returns its target), doctypes (returns its public
 *         ID)</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_nsprefix</tt></td>
 *       <td>the namespace prefixes of current nodes, one string per node
 *         (non-recursive). Applicable to elements and attributes</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_nsuri</tt></td>
 *       <td>the namespace URIs of current nodes, one string per node
 *       (non-recursive). Applicable to elements and attributes</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_parent</tt></td>
 *       <td>parent elements of current nodes. Applicable to element,
 *       attribute, comment, entity, processing instruction.</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_qname</tt></td>
 *       <td>the qualified names of current nodes in
 *         <tt>[namespacePrefix:]localName</tt> form, one string per node
 *         (non-recursive). Applicable to elements and attributes</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_registerNamespace(prefix, uri)</tt></td>
 *       <td>register a XML namespace with the specified prefix and URI for
 *         the current node list and all node lists that are derived from
 *         the current node list. After registering, you can use the
 *         <tt>nodelist[&quot;prefix:localname&quot;]</tt> or
 *         <tt>nodelist[&quot;@prefix:localname&quot;]</tt> syntaxes to
 *         reach elements and attributes whose names are namespace-scoped.
 *         Note that the namespace prefix need not match the actual prefix
 *         used by the XML document itself since namespaces are compared
 *         solely by their URI.</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_text</tt></td>
 *       <td>the text of current nodes, one string per node
 *         (non-recursive). Applicable to elements, attributes, comments,
 *         processing instructions (returns its data) and CDATA sections.
 *         The reserved XML characters ('&lt;' and '&amp;') are NOT
 *         escaped.</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_type</tt></td>
 *       <td>Returns a string describing the type of nodes, one
 *         string per node. The returned values are &quot;attribute&quot;,
 *         &quot;cdata&quot;, &quot;comment&quot;, &quot;document&quot;,
 *         &quot;documentType&quot;, &quot;element&quot;,
 *         &quot;entity&quot;, &quot;entityReference&quot;,
 *         &quot;namespace&quot;, &quot;processingInstruction&quot;,
 *         &quot;text&quot;, or &quot;unknown&quot;.</td>
 *     </tr>
 *     <tr>
 *       <td><tt>_unique</tt></td>
 *       <td>a copy of the current nodes that keeps only the first
 *         occurrence of every node, eliminating duplicates. Duplicates can
 *         occur in the node list by applying uptree-traversals
 *         <tt>_parent</tt>, <tt>_ancestor</tt>, <tt>_ancestorOrSelf</tt>,
 *         and <tt>_document</tt> on a node list with multiple elements.
 *         I.e. <tt>foo._children._parent</tt> will return a node list that
 *         has duplicates of nodes in foo - each node will have the number
 *         of occurrences equal to the number of its children. In these
 *         cases, use <tt>foo._children._parent._unique</tt> to eliminate
 *         duplicates. Applicable to all node types.</td>
 *     </tr>
 *     <tr>
 *       <td>any other key</td>
 *       <td>element children of current nodes with name matching the key.
 *       This allows for convenience child traversal in
 *       <tt>book.chapter.title</tt> style syntax. Applicable to document
 *       and element nodes.</td>
 *     </tr>
 *   </tbody>
 * </table>
 * @return a new NodeListModel containing the nodes that result from applying
 * the operator to this model's nodes.
 * @see freemarker.template.TemplateHashModel#get(String)
 */
public TemplateModel get(String key) throws TemplateModelException {
    // Try a built-in navigator operator
    NodeOperator op = navigator.getOperator(key);
    String localName = null;
    String namespaceUri = "";
    // If not a nav op, then check for special keys.
    if (op == null && key.length() > 0 && key.charAt(0) == '_') {
        if (key.equals("_unique")) {
            return deriveModel(removeDuplicates(nodes));
        } else if (key.equals("_filterType") || key.equals("_ftype")) {
            return new FilterByType();
        } else if (key.equals("_registerNamespace")) {
            if (namespaces.isShared()) {
                namespaces = (Namespaces) namespaces.clone();
            }
        }
    }
    // Last, do a named child element or attribute lookup
    if (op == null) {
        int colon = key.indexOf(':');
        if (colon == -1) {
            // No namespace prefix specified
            localName = key;
        } else {
            // Namespace prefix specified
            localName = key.substring(colon + 1);
            String prefix = key.substring(0, colon);
            namespaceUri = namespaces.translateNamespacePrefixToUri(prefix);
            if (namespaceUri == null) {
                throw new TemplateModelException("Namespace prefix " + prefix + " is not registered.");
            }
        }
        if (localName.charAt(0) == '@') {
            op = navigator.getAttributeOperator();
            localName = localName.substring(1);
        } else {
            op = navigator.getChildrenOperator();
        }
    }
    List result = new ArrayList();
    for (Iterator iter = nodes.iterator(); iter.hasNext(); ) {
        try {
            op.process(iter.next(), localName, namespaceUri, result);
        } catch (RuntimeException e) {
            throw new TemplateModelException(e);
        }
    }
    return deriveModel(result);
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) ArrayList(java.util.ArrayList) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List)

Example 20 with TemplateModelException

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

the class TagTransformModel method getWriter.

public Writer getWriter(Writer out, Map args) throws TemplateModelException {
    try {
        Tag tag = (Tag) getTagInstance();
        FreeMarkerPageContext pageContext = PageContextFactory.getCurrentPageContext();
        Tag parentTag = (Tag) pageContext.peekTopTag(Tag.class);
        tag.setParent(parentTag);
        tag.setPageContext(pageContext);
        setupTag(tag, args, pageContext.getObjectWrapper());
        // If the parent of this writer is not a JspWriter itself, use
        // a little Writer-to-JspWriter adapter...
        boolean usesAdapter;
        if (out instanceof JspWriter) {
            // we'd use an assert.
            if (out != pageContext.getOut()) {
                throw new TemplateModelException("out != pageContext.getOut(). Out is " + out + " pageContext.getOut() is " + pageContext.getOut());
            }
            usesAdapter = false;
        } else {
            out = new JspWriterAdapter(out);
            pageContext.pushWriter((JspWriter) out);
            usesAdapter = true;
        }
        JspWriter w = new TagWriter(out, tag, pageContext, usesAdapter);
        pageContext.pushTopTag(tag);
        pageContext.pushWriter(w);
        return w;
    } catch (Exception e) {
        throw toTemplateModelExceptionOrRethrow(e);
    }
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) BodyTag(javax.servlet.jsp.tagext.BodyTag) Tag(javax.servlet.jsp.tagext.Tag) IterationTag(javax.servlet.jsp.tagext.IterationTag) SimpleTag(javax.servlet.jsp.tagext.SimpleTag) JspWriter(javax.servlet.jsp.JspWriter) TemplateModelException(freemarker.template.TemplateModelException) JspException(javax.servlet.jsp.JspException) IOException(java.io.IOException) IntrospectionException(java.beans.IntrospectionException)

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