Search in sources :

Example 26 with TemplateException

use of freemarker.template.TemplateException in project qi4j-sdk by Qi4j.

the class LinksResponseWriter method createTextHtmlRepresentation.

private Representation createTextHtmlRepresentation(final Object result, final Response response) {
    return new WriterRepresentation(MediaType.TEXT_HTML) {

        @Override
        public void write(Writer writer) throws IOException {
            Map<String, Object> context = new HashMap<String, Object>();
            context.put("request", response.getRequest());
            context.put("response", response);
            context.put("result", result);
            try {
                cfg.getTemplate("links.htm").process(context, writer);
            } catch (TemplateException e) {
                throw new IOException(e);
            }
        }
    };
}
Also used : HashMap(java.util.HashMap) TemplateException(freemarker.template.TemplateException) WriterRepresentation(org.restlet.representation.WriterRepresentation) IOException(java.io.IOException) Writer(java.io.Writer)

Example 27 with TemplateException

use of freemarker.template.TemplateException 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)

Example 28 with TemplateException

use of freemarker.template.TemplateException in project opennms by OpenNMS.

the class RScriptExecutor method exec.

/**
     * Executes by given script by:
     *   - Searching both the classpath and the filesystem for the path
     *   - Copying the script at the given path to a temporary file and
     *     performing variable substitution with the arguments using Freemarker.
     *   - Invoking the script with commons-exec
     *   - Converting the input table to CSV and passing this to the process via stdin
     *   - Parsing stdout, expecting CSV output, and converting this to an immutable table
     */
public RScriptOutput exec(String script, RScriptInput input) throws RScriptException {
    Preconditions.checkNotNull(script, "script argument");
    Preconditions.checkNotNull(input, "input argument");
    // Grab the script/template
    Template template;
    try {
        template = m_freemarkerConfiguration.getTemplate(script);
    } catch (IOException e) {
        throw new RScriptException("Failed to read the script.", e);
    }
    // Create a temporary file
    File scriptOnDisk;
    try {
        scriptOnDisk = File.createTempFile("Rcsript", "R");
        scriptOnDisk.deleteOnExit();
    } catch (IOException e) {
        throw new RScriptException("Failed to create a temporary file.", e);
    }
    // Perform variable substitution and write the results to the temporary file
    try (FileOutputStream fos = new FileOutputStream(scriptOnDisk);
        Writer out = new OutputStreamWriter(fos)) {
        template.process(input.getArguments(), out);
    } catch (IOException | TemplateException e) {
        scriptOnDisk.delete();
        throw new RScriptException("Failed to process the template.", e);
    }
    // Convert the input matrix to a CSV string which will be passed to the script via stdin.
    // The table may be large, so we try and avoid writing it to disk
    StringBuilder inputTableAsCsv;
    try {
        inputTableAsCsv = toCsv(input.getTable());
    } catch (IOException e) {
        scriptOnDisk.delete();
        throw new RScriptException("Failed to convert the input table to CSV.", e);
    }
    // Invoke Rscript against the script (located in a temporary file)
    CommandLine cmdLine = new CommandLine(RSCRIPT_BINARY);
    cmdLine.addArgument(scriptOnDisk.getAbsolutePath());
    // Use commons-exec to execute the process
    DefaultExecutor executor = new DefaultExecutor();
    // Use the CharSequenceInputStream in order to avoid explicitly converting
    // the StringBuilder a string and then an array of bytes.
    InputStream stdin = new CharSequenceInputStream(inputTableAsCsv, StandardCharsets.UTF_8);
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, stdin));
    // Fail if we get a non-zero exit code
    executor.setExitValue(0);
    // Fail if the process takes too long
    ExecuteWatchdog watchdog = new ExecuteWatchdog(SCRIPT_TIMEOUT_MS);
    executor.setWatchdog(watchdog);
    // Execute
    try {
        executor.execute(cmdLine);
    } catch (IOException e) {
        scriptOnDisk.delete();
        throw new RScriptException("An error occured while executing Rscript, or the requested script.", inputTableAsCsv.toString(), stderr.toString(), stdout.toString(), e);
    }
    // Parse and return the results
    try {
        ImmutableTable<Long, String, Double> table = fromCsv(stdout.toString());
        return new RScriptOutput(table);
    } catch (Throwable t) {
        throw new RScriptException("Failed to parse the script's output.", inputTableAsCsv.toString(), stderr.toString(), stdout.toString(), t);
    } finally {
        scriptOnDisk.delete();
    }
}
Also used : CharSequenceInputStream(org.apache.commons.io.input.CharSequenceInputStream) TemplateException(freemarker.template.TemplateException) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) CharSequenceInputStream(org.apache.commons.io.input.CharSequenceInputStream) InputStream(java.io.InputStream) ExecuteWatchdog(org.apache.commons.exec.ExecuteWatchdog) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Template(freemarker.template.Template) CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer)

Example 29 with TemplateException

use of freemarker.template.TemplateException in project OpenAM by OpenRock.

the class OpenAMResourceOwnerSessionValidator method buildCustomLoginUrl.

private URI buildCustomLoginUrl(Template loginUrlTemplate, String gotoUrl, String acrValues, String realm, String moduleName, String serviceName, String locale) throws ServerException, UnsupportedEncodingException {
    Map<String, String> templateData = new HashMap<>();
    templateData.put("goto", URLEncoder.encode(gotoUrl, StandardCharsets.UTF_8.toString()));
    templateData.put("acrValues", acrValues != null ? URLEncoder.encode(acrValues, StandardCharsets.UTF_8.toString()) : null);
    templateData.put("realm", realm);
    templateData.put("module", moduleName);
    templateData.put("service", serviceName);
    templateData.put("locale", locale);
    try {
        StringWriter loginUrlWriter = new StringWriter();
        loginUrlTemplate.process(templateData, loginUrlWriter);
        return URI.create(loginUrlWriter.toString());
    } catch (IOException | TemplateException e) {
        logger.error("Failed to template custom login url", e);
        throw new ServerException("Failed to template custom login url");
    }
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException)

Example 30 with TemplateException

use of freemarker.template.TemplateException in project pcgen by PCGen.

the class AbstractOutputTestCase method processThroughFreeMarker.

public void processThroughFreeMarker(String testString, String expectedResult) {
    try {
        Configuration c = new Configuration();
        Template t = new Template("test", testString, c);
        StringWriter sw = new StringWriter();
        BufferedWriter bw = new BufferedWriter(sw);
        Map<String, Object> input = OutputDB.buildDataModel(id);
        t.process(input, bw);
        String s = sw.getBuffer().toString();
        assertEquals(expectedResult, s);
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getLocalizedMessage());
    } catch (TemplateException e) {
        e.printStackTrace();
        fail(e.getLocalizedMessage());
    }
}
Also used : Configuration(freemarker.template.Configuration) StringWriter(java.io.StringWriter) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException) Template(freemarker.template.Template) BufferedWriter(java.io.BufferedWriter)

Aggregations

TemplateException (freemarker.template.TemplateException)39 IOException (java.io.IOException)34 Template (freemarker.template.Template)20 HashMap (java.util.HashMap)16 Writer (java.io.Writer)15 StringWriter (java.io.StringWriter)12 Map (java.util.Map)8 Configuration (freemarker.template.Configuration)7 WriterRepresentation (org.restlet.representation.WriterRepresentation)6 File (java.io.File)5 OutputStreamWriter (java.io.OutputStreamWriter)4 MediaType (org.restlet.data.MediaType)4 Representation (org.restlet.representation.Representation)4 BufferedWriter (java.io.BufferedWriter)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 FileWriter (java.io.FileWriter)3 JSONException (org.json.JSONException)3 StringRepresentation (org.restlet.representation.StringRepresentation)3 ParseException (freemarker.core.ParseException)2 DefaultObjectWrapper (freemarker.template.DefaultObjectWrapper)2