Search in sources :

Example 21 with TemplateModelException

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

the class TaglibFactory method resolveRelativeUri.

private static String resolveRelativeUri(String uri) throws TaglibGettingException {
    TemplateModel reqHash;
    try {
        reqHash = Environment.getCurrentEnvironment().getVariable(FreemarkerServlet.KEY_REQUEST_PRIVATE);
    } catch (TemplateModelException e) {
        throw new TaglibGettingException("Failed to get FreemarkerServlet request information", e);
    }
    if (reqHash instanceof HttpRequestHashModel) {
        HttpServletRequest req = ((HttpRequestHashModel) reqHash).getRequest();
        String pi = req.getPathInfo();
        String reqPath = req.getServletPath();
        if (reqPath == null) {
            reqPath = "";
        }
        reqPath += (pi == null ? "" : pi);
        // We don't care about paths with ".." in them. If the container
        // wishes to resolve them on its own, let it be.
        int lastSlash = reqPath.lastIndexOf('/');
        if (lastSlash != -1) {
            return reqPath.substring(0, lastSlash + 1) + uri;
        } else {
            return '/' + uri;
        }
    }
    throw new TaglibGettingException("Can't resolve relative URI " + uri + " as request URL information is unavailable.");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) TemplateModelException(freemarker.template.TemplateModelException) HttpRequestHashModel(freemarker.ext.servlet.HttpRequestHashModel) TemplateModel(freemarker.template.TemplateModel)

Example 22 with TemplateModelException

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

the class TaglibFactory method get.

/**
 * Retrieves a JSP tag library identified by an URI. The matching of the URI to a JSP taglib is done as described in
 * the JSP 1.2 FCS specification.
 *
 * @param taglibUri
 *            The URI used in templates to refer to the taglib (like {@code <%@ taglib uri="..." ... %>} in
 *            JSP). It can be any of the three forms allowed by the JSP specification: absolute URI (like
 *            {@code http://example.com/foo}), root relative URI (like {@code /bar/foo.tld}) and non-root relative
 *            URI (like {@code bar/foo.tld}). Note that if a non-root relative URI is used it's resolved relative to
 *            the URL of the current request. In this case, the current request is obtained by looking up a
 *            {@link HttpRequestHashModel} object named <tt>Request</tt> in the root data model.
 *            {@link FreemarkerServlet} provides this object under the expected name, and custom servlets that want
 *            to integrate JSP taglib support should do the same.
 *
 * @return a {@link TemplateHashModel} representing the JSP taglib. Each element of this hash represents a single
 *         custom tag or EL function from the library, implemented as a {@link TemplateTransformModel} or
 *         {@link TemplateMethodModelEx}, respectively.
 */
public TemplateModel get(final String taglibUri) throws TemplateModelException {
    synchronized (lock) {
        {
            final Taglib taglib = (Taglib) taglibs.get(taglibUri);
            if (taglib != null) {
                return taglib;
            }
        }
        boolean failedTldListAlreadyIncluded = false;
        final TldLocation tldLocation;
        final String normalizedTaglibUri;
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Locating TLD for taglib URI " + StringUtil.jQuoteNoXSS(taglibUri) + ".");
            }
            TldLocation explicitlyMappedTldLocation = getExplicitlyMappedTldLocation(taglibUri);
            if (explicitlyMappedTldLocation != null) {
                tldLocation = explicitlyMappedTldLocation;
                normalizedTaglibUri = taglibUri;
            } else {
                // Taglib URI must be directly the path (no mapping).
                final int urlType;
                try {
                    urlType = getUriType(taglibUri);
                } catch (MalformedURLException e) {
                    throw new TaglibGettingException("Malformed taglib URI: " + StringUtil.jQuote(taglibUri), e);
                }
                if (urlType == URL_TYPE_RELATIVE) {
                    normalizedTaglibUri = resolveRelativeUri(taglibUri);
                } else if (urlType == URL_TYPE_ABSOLUTE) {
                    normalizedTaglibUri = taglibUri;
                } else if (urlType == URL_TYPE_FULL) {
                    // Per spec., full URI-s can only be resolved through explicit mapping
                    String failedTLDsList = getFailedTLDsList();
                    failedTldListAlreadyIncluded = true;
                    throw new TaglibGettingException("No TLD was found for the " + StringUtil.jQuoteNoXSS(taglibUri) + " JSP taglib URI. (TLD-s are searched according " + "the JSP 2.2 specification. In development- and embedded-servlet-container " + "setups you may also need the " + "\"" + FreemarkerServlet.INIT_PARAM_META_INF_TLD_LOCATIONS + "\" and " + "\"" + FreemarkerServlet.INIT_PARAM_CLASSPATH_TLDS + "\" " + FreemarkerServlet.class.getName() + " init-params or the similar system " + "properites." + (failedTLDsList == null ? "" : " Also note these TLD-s were skipped earlier due to errors; " + "see error in the log: " + failedTLDsList) + ")");
                } else {
                    throw new BugException();
                }
                if (!normalizedTaglibUri.equals(taglibUri)) {
                    final Taglib taglib = (Taglib) taglibs.get(normalizedTaglibUri);
                    if (taglib != null) {
                        return taglib;
                    }
                }
                tldLocation = isJarPath(normalizedTaglibUri) ? (TldLocation) new ServletContextJarEntryTldLocation(normalizedTaglibUri, DEFAULT_TLD_RESOURCE_PATH) : (TldLocation) new ServletContextTldLocation(normalizedTaglibUri);
            }
        } catch (Exception e) {
            String failedTLDsList = failedTldListAlreadyIncluded ? null : getFailedTLDsList();
            throw new TemplateModelException("Error while looking for TLD file for " + StringUtil.jQuoteNoXSS(taglibUri) + "; see cause exception." + (failedTLDsList == null ? "" : " (Note: These TLD-s were skipped earlier due to errors; " + "see errors in the log: " + failedTLDsList + ")"), e);
        }
        try {
            return loadTaglib(tldLocation, normalizedTaglibUri);
        } catch (Exception e) {
            throw new TemplateModelException("Error while loading tag library for URI " + StringUtil.jQuoteNoXSS(normalizedTaglibUri) + " from TLD location " + StringUtil.jQuoteNoXSS(tldLocation) + "; see cause exception.", e);
        }
    }
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) MalformedURLException(java.net.MalformedURLException) BugException(freemarker.core.BugException) URISyntaxException(java.net.URISyntaxException) NullArgumentException(freemarker.template.utility.NullArgumentException) ZipException(java.util.zip.ZipException) IntrospectionException(java.beans.IntrospectionException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TemplateModelException(freemarker.template.TemplateModelException) BugException(freemarker.core.BugException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 23 with TemplateModelException

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

the class Java8BeansWrapperBridgeMethodsTest method test.

private void test(Class<?> pClass) throws TemplateModelException {
    BeansWrapper ow = new BeansWrapperBuilder(Configuration.VERSION_2_3_26).build();
    TemplateHashModel wrapped;
    try {
        wrapped = (TemplateHashModel) ow.wrap(pClass.newInstance());
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    TemplateMethodModelEx m1 = (TemplateMethodModelEx) wrapped.get("m1");
    assertEquals(BridgeMethodsBean.M1_RETURN_VALUE, "" + m1.exec(Collections.emptyList()));
    TemplateMethodModelEx m2 = (TemplateMethodModelEx) wrapped.get("m2");
    assertNull(m2.exec(Collections.emptyList()));
}
Also used : TemplateHashModel(freemarker.template.TemplateHashModel) TemplateMethodModelEx(freemarker.template.TemplateMethodModelEx) TemplateModelException(freemarker.template.TemplateModelException)

Example 24 with TemplateModelException

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

the class EnumModelsTest method modelCaching.

@Test
public void modelCaching() throws Exception {
    BeansWrapper bw = new BeansWrapper(Configuration.VERSION_2_3_21);
    TemplateHashModel enums = bw.getEnumModels();
    TemplateHashModel e = (TemplateHashModel) enums.get(E.class.getName());
    assertNotNull(e);
    assertNotNull(e.get("A"));
    assertNotNull(e.get("B"));
    assertNull(e.get("C"));
    try {
        enums.get("no.such.ClassExists");
        fail();
    } catch (TemplateModelException ex) {
        assertTrue(ex.getCause() instanceof ClassNotFoundException);
    }
    TemplateModel a = e.get("A");
    assertTrue(a instanceof TemplateScalarModel);
    assertTrue(a instanceof TemplateHashModel);
    assertEquals(((TemplateScalarModel) a).getAsString(), "ts:A");
    TemplateMethodModelEx nameMethod = (TemplateMethodModelEx) ((TemplateHashModel) a).get("name");
    assertEquals(((TemplateScalarModel) nameMethod.exec(new ArrayList())).getAsString(), "A");
    assertSame(e, enums.get(E.class.getName()));
    bw.clearClassIntrospecitonCache();
    TemplateHashModel eAfterClean = (TemplateHashModel) enums.get(E.class.getName());
    assertNotSame(e, eAfterClean);
    assertSame(eAfterClean, enums.get(E.class.getName()));
    assertNotNull(eAfterClean.get("A"));
    assertNotNull(eAfterClean.get("B"));
    assertNull(eAfterClean.get("C"));
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) TemplateHashModel(freemarker.template.TemplateHashModel) TemplateMethodModelEx(freemarker.template.TemplateMethodModelEx) ArrayList(java.util.ArrayList) TemplateScalarModel(freemarker.template.TemplateScalarModel) TemplateModel(freemarker.template.TemplateModel) Test(org.junit.Test)

Example 25 with TemplateModelException

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

the class BeansWrapper method listToArray.

Object listToArray(List<?> list, Class<?> arrayClass, Map<Object, Object> recursionStops) throws TemplateModelException {
    if (list instanceof SequenceAdapter) {
        return unwrapSequenceToArray(((SequenceAdapter) list).getTemplateSequenceModel(), arrayClass, false, recursionStops);
    }
    if (recursionStops != null) {
        Object retval = recursionStops.get(list);
        if (retval != null) {
            return retval;
        }
    } else {
        recursionStops = new IdentityHashMap<Object, Object>();
    }
    Class<?> componentType = arrayClass.getComponentType();
    Object array = Array.newInstance(componentType, list.size());
    recursionStops.put(list, array);
    try {
        boolean isComponentTypeExamined = false;
        // will be filled on demand
        boolean isComponentTypeNumerical = false;
        // will be filled on demand
        boolean isComponentTypeList = false;
        int i = 0;
        for (Iterator<?> it = list.iterator(); it.hasNext(); ) {
            Object listItem = it.next();
            if (listItem != null && !componentType.isInstance(listItem)) {
                // Type conversion is needed. If we can't do it, we just let it fail at Array.set later.
                if (!isComponentTypeExamined) {
                    isComponentTypeNumerical = ClassUtil.isNumerical(componentType);
                    isComponentTypeList = List.class.isAssignableFrom(componentType);
                    isComponentTypeExamined = true;
                }
                if (isComponentTypeNumerical && listItem instanceof Number) {
                    listItem = forceUnwrappedNumberToType((Number) listItem, componentType, true);
                } else if (componentType == String.class && listItem instanceof Character) {
                    listItem = String.valueOf(((Character) listItem).charValue());
                } else if ((componentType == Character.class || componentType == char.class) && listItem instanceof String) {
                    String listItemStr = (String) listItem;
                    if (listItemStr.length() == 1) {
                        listItem = Character.valueOf(listItemStr.charAt(0));
                    }
                } else if (componentType.isArray()) {
                    if (listItem instanceof List) {
                        listItem = listToArray((List<?>) listItem, componentType, recursionStops);
                    } else if (listItem instanceof TemplateSequenceModel) {
                        listItem = unwrapSequenceToArray((TemplateSequenceModel) listItem, componentType, false, recursionStops);
                    }
                } else if (isComponentTypeList && listItem.getClass().isArray()) {
                    listItem = arrayToList(listItem);
                }
            }
            try {
                Array.set(array, i, listItem);
            } catch (IllegalArgumentException e) {
                throw new TemplateModelException("Failed to convert " + ClassUtil.getShortClassNameOfObject(list) + " object to " + ClassUtil.getShortClassNameOfObject(array) + ": Problematic List item at index " + i + " with value type: " + ClassUtil.getShortClassNameOfObject(listItem), e);
            }
            i++;
        }
    } finally {
        recursionStops.remove(list);
    }
    return array;
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) freemarker.core._TemplateModelException(freemarker.core._TemplateModelException) TemplateSequenceModel(freemarker.template.TemplateSequenceModel) AccessibleObject(java.lang.reflect.AccessibleObject) List(java.util.List)

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