Search in sources :

Example 1 with TemplateExceptionHandler

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

the class FreemarkerServlet method process.

private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Give chance to subclasses to perform preprocessing
    if (preprocessRequest(request, response)) {
        return;
    }
    if (bufferSize != null && !response.isCommitted()) {
        try {
            response.setBufferSize(bufferSize.intValue());
        } catch (IllegalStateException e) {
            LOG.debug("Can't set buffer size any more,", e);
        }
    }
    String templatePath = requestUrlToTemplatePath(request);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Requested template " + StringUtil.jQuoteNoXSS(templatePath) + ".");
    }
    Locale locale = request.getLocale();
    if (locale == null || overrideResponseLocale != OverrideResponseLocale.NEVER) {
        locale = deduceLocale(templatePath, request, response);
    }
    final Template template;
    try {
        template = config.getTemplate(templatePath, locale);
    } catch (TemplateNotFoundException e) {
        if (exceptionOnMissingTemplate) {
            throw newServletExceptionWithFreeMarkerLogging("Template not found for name " + StringUtil.jQuoteNoXSS(templatePath) + ".", e);
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Responding HTTP 404 \"Not found\" for missing template " + StringUtil.jQuoteNoXSS(templatePath) + ".", e);
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "Page template not found");
            return;
        }
    } catch (freemarker.core.ParseException e) {
        throw newServletExceptionWithFreeMarkerLogging("Parsing error with template " + StringUtil.jQuoteNoXSS(templatePath) + ".", e);
    } catch (Exception e) {
        throw newServletExceptionWithFreeMarkerLogging("Unexpected error when loading template " + StringUtil.jQuoteNoXSS(templatePath) + ".", e);
    }
    boolean tempSpecContentTypeContainsCharset = false;
    if (response.getContentType() == null || overrideResponseContentType != OverrideResponseContentType.NEVER) {
        ContentType templateSpecificContentType = getTemplateSpecificContentType(template);
        if (templateSpecificContentType != null) {
            // With ResponseCharacterEncoding.LEGACY we should append the charset, but we don't do that for b. c.
            response.setContentType(responseCharacterEncoding != ResponseCharacterEncoding.DO_NOT_SET ? templateSpecificContentType.httpHeaderValue : templateSpecificContentType.getMimeType());
            tempSpecContentTypeContainsCharset = templateSpecificContentType.containsCharset;
        } else if (response.getContentType() == null || overrideResponseContentType == OverrideResponseContentType.ALWAYS) {
            if (responseCharacterEncoding == ResponseCharacterEncoding.LEGACY && !contentType.containsCharset) {
                // In legacy mode we don't call response.setCharacterEncoding, so the charset must be set here:
                response.setContentType(contentType.httpHeaderValue + "; charset=" + getTemplateSpecificOutputEncoding(template));
            } else {
                response.setContentType(contentType.httpHeaderValue);
            }
        }
    }
    if (responseCharacterEncoding != ResponseCharacterEncoding.LEGACY && responseCharacterEncoding != ResponseCharacterEncoding.DO_NOT_SET) {
        // Using the Servlet 2.4 way of setting character encoding.
        if (responseCharacterEncoding != ResponseCharacterEncoding.FORCE_CHARSET) {
            if (!tempSpecContentTypeContainsCharset) {
                response.setCharacterEncoding(getTemplateSpecificOutputEncoding(template));
            }
        } else {
            response.setCharacterEncoding(forcedResponseCharacterEncoding.name());
        }
    }
    setBrowserCachingPolicy(response);
    ServletContext servletContext = getServletContext();
    try {
        logWarnOnObjectWrapperMismatch();
        TemplateModel model = createModel(wrapper, servletContext, request, response);
        // Give subclasses a chance to hook into preprocessing
        if (preTemplateProcess(request, response, template, model)) {
            try {
                // Process the template
                Environment env = template.createProcessingEnvironment(model, response.getWriter());
                if (responseCharacterEncoding != ResponseCharacterEncoding.LEGACY) {
                    String actualOutputCharset = response.getCharacterEncoding();
                    if (actualOutputCharset != null) {
                        env.setOutputEncoding(actualOutputCharset);
                    }
                }
                processEnvironment(env, request, response);
            } finally {
                // Give subclasses a chance to hook into postprocessing
                postTemplateProcess(request, response, template, model);
            }
        }
    } catch (TemplateException e) {
        final TemplateExceptionHandler teh = config.getTemplateExceptionHandler();
        // Ensure that debug handler responses aren't rolled back:
        if (teh == TemplateExceptionHandler.HTML_DEBUG_HANDLER || teh == TemplateExceptionHandler.DEBUG_HANDLER || teh.getClass().getName().indexOf("Debug") != -1) {
            response.flushBuffer();
        }
        throw newServletExceptionWithFreeMarkerLogging("Error executing FreeMarker template", e);
    }
}
Also used : Locale(java.util.Locale) TemplateException(freemarker.template.TemplateException) TemplateModel(freemarker.template.TemplateModel) ServletException(javax.servlet.ServletException) TemplateModelException(freemarker.template.TemplateModelException) TemplateException(freemarker.template.TemplateException) TemplateNotFoundException(freemarker.template.TemplateNotFoundException) ParseException(java.text.ParseException) IOException(java.io.IOException) Template(freemarker.template.Template) ServletContext(javax.servlet.ServletContext) Environment(freemarker.core.Environment) TemplateNotFoundException(freemarker.template.TemplateNotFoundException) TemplateExceptionHandler(freemarker.template.TemplateExceptionHandler)

Example 2 with TemplateExceptionHandler

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

the class AttemptLoggingTest method dontReportSuppressedExceptionsTest.

@Test
public void dontReportSuppressedExceptionsTest() throws IOException, TemplateException {
    List<String> reports = new ArrayList<String>();
    getConfiguration().setAttemptExceptionReporter(new TestAttemptExceptionReporter(reports));
    getConfiguration().setTemplateExceptionHandler(new TemplateExceptionHandler() {

        public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException {
            try {
                out.write("[E]");
            } catch (IOException e) {
                throw new TemplateException("Failed to write to the output", e, env);
            }
        }
    });
    assertOutput("<#attempt>${missingVar1}t<#recover>r</#attempt>", "[E]t");
    assertEquals(0, reports.size());
}
Also used : TemplateException(freemarker.template.TemplateException) ArrayList(java.util.ArrayList) TemplateExceptionHandler(freemarker.template.TemplateExceptionHandler) IOException(java.io.IOException) Writer(java.io.Writer) Test(org.junit.Test) TemplateTest(freemarker.test.TemplateTest)

Example 3 with TemplateExceptionHandler

use of freemarker.template.TemplateExceptionHandler in project perun by CESNET.

the class PerunNotifTemplateManagerImpl method compileTemplate.

private String compileTemplate(final String templateName, Locale locale, Map<String, Object> container) throws IOException, TemplateException {
    class NotificationTemplateExceptionHandler implements TemplateExceptionHandler {

        @Override
        public void handleTemplateException(TemplateException te, Environment env, java.io.Writer out) throws TemplateException {
            if (te instanceof InvalidReferenceException) {
                // skip undefined values
                logger.info("Undefined value found in the TemplateMessage " + templateName + ".", te);
            } else {
                throw te;
            }
        }
    }
    this.configuration.setTemplateExceptionHandler(new NotificationTemplateExceptionHandler());
    StringWriter stringWriter = new StringWriter(4096);
    Template freeMarkerTemplate = null;
    try {
        freeMarkerTemplate = this.configuration.getTemplate(templateName + "_" + locale.getLanguage(), locale);
    } catch (FileNotFoundException ex) {
        if (!(locale.equals(DEFAULT_LOCALE))) {
            // if we do not know the language, try to send it at least in default locale
            freeMarkerTemplate = this.configuration.getTemplate(templateName + "_" + DEFAULT_LOCALE.getLanguage(), DEFAULT_LOCALE);
            logger.info("There is no message with template " + templateName + " in locale " + locale.getLanguage() + ", therefore the message will be sent in " + DEFAULT_LOCALE.getLanguage() + " locale.");
        } else {
            throw ex;
        }
    }
    freeMarkerTemplate.process(container, stringWriter);
    return stringWriter.toString();
}
Also used : StringWriter(java.io.StringWriter) TemplateException(freemarker.template.TemplateException) FileNotFoundException(java.io.FileNotFoundException) Environment(freemarker.core.Environment) TemplateExceptionHandler(freemarker.template.TemplateExceptionHandler) StringWriter(java.io.StringWriter) InvalidReferenceException(freemarker.core.InvalidReferenceException) Template(freemarker.template.Template)

Aggregations

TemplateException (freemarker.template.TemplateException)3 TemplateExceptionHandler (freemarker.template.TemplateExceptionHandler)3 Environment (freemarker.core.Environment)2 Template (freemarker.template.Template)2 IOException (java.io.IOException)2 InvalidReferenceException (freemarker.core.InvalidReferenceException)1 TemplateModel (freemarker.template.TemplateModel)1 TemplateModelException (freemarker.template.TemplateModelException)1 TemplateNotFoundException (freemarker.template.TemplateNotFoundException)1 TemplateTest (freemarker.test.TemplateTest)1 FileNotFoundException (java.io.FileNotFoundException)1 StringWriter (java.io.StringWriter)1 Writer (java.io.Writer)1 ParseException (java.text.ParseException)1 ArrayList (java.util.ArrayList)1 Locale (java.util.Locale)1 ServletContext (javax.servlet.ServletContext)1 ServletException (javax.servlet.ServletException)1 Test (org.junit.Test)1