Search in sources :

Example 51 with Template

use of freemarker.template.Template in project camel by apache.

the class FreemarkerEndpoint method onExchange.

@Override
protected void onExchange(Exchange exchange) throws Exception {
    String path = getResourceUri();
    ObjectHelper.notNull(configuration, "configuration");
    ObjectHelper.notNull(path, "resourceUri");
    String newResourceUri = exchange.getIn().getHeader(FreemarkerConstants.FREEMARKER_RESOURCE_URI, String.class);
    if (newResourceUri != null) {
        exchange.getIn().removeHeader(FreemarkerConstants.FREEMARKER_RESOURCE_URI);
        log.debug("{} set to {} creating new endpoint to handle exchange", FreemarkerConstants.FREEMARKER_RESOURCE_URI, newResourceUri);
        FreemarkerEndpoint newEndpoint = findOrCreateEndpoint(getEndpointUri(), newResourceUri);
        newEndpoint.onExchange(exchange);
        return;
    }
    Reader reader = null;
    String content = exchange.getIn().getHeader(FreemarkerConstants.FREEMARKER_TEMPLATE, String.class);
    if (content != null) {
        // use content from header
        reader = new StringReader(content);
        // remove the header to avoid it being propagated in the routing
        exchange.getIn().removeHeader(FreemarkerConstants.FREEMARKER_TEMPLATE);
    }
    Object dataModel = exchange.getIn().getHeader(FreemarkerConstants.FREEMARKER_DATA_MODEL, Object.class);
    if (dataModel == null) {
        dataModel = ExchangeHelper.createVariableMap(exchange);
    }
    // let freemarker parse and generate the result in buffer
    Template template;
    if (reader != null) {
        log.debug("Freemarker is evaluating template read from header {} using context: {}", FreemarkerConstants.FREEMARKER_TEMPLATE, dataModel);
        template = new Template("temp", reader, new Configuration());
    } else {
        log.debug("Freemarker is evaluating {} using context: {}", path, dataModel);
        if (getEncoding() != null) {
            template = configuration.getTemplate(path, getEncoding());
        } else {
            template = configuration.getTemplate(path);
        }
    }
    StringWriter buffer = new StringWriter();
    template.process(dataModel, buffer);
    buffer.flush();
    // now lets output the results to the exchange
    Message out = exchange.getOut();
    out.setBody(buffer.toString());
    out.setHeaders(exchange.getIn().getHeaders());
    out.setAttachments(exchange.getIn().getAttachments());
}
Also used : Configuration(freemarker.template.Configuration) StringWriter(java.io.StringWriter) Message(org.apache.camel.Message) StringReader(java.io.StringReader) Reader(java.io.Reader) StringReader(java.io.StringReader) Template(freemarker.template.Template)

Example 52 with Template

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

the class ResourceTemplateResponseWriter method writeResponse.

@Override
public boolean writeResponse(final Object result, final Response response) throws ResourceException {
    MediaType type = getVariant(response.getRequest(), ENGLISH, supportedMediaTypes).getMediaType();
    if (type != null) {
        // Try to find template for this specific resource
        StringBuilder templateBuilder = (StringBuilder) response.getRequest().getAttributes().get("template");
        String templateName = templateBuilder.toString();
        if (result instanceof ValueDescriptor) {
            templateName += "_form";
        }
        final String extension = metadataService.getExtension(type);
        templateName += "." + extension;
        // Have we failed on this one before, then don't try again
        if (skip.contains(templateName)) {
            return false;
        }
        try {
            final Template template = cfg.getTemplate(templateName);
            Representation rep = 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 {
                        template.process(context, writer);
                    } catch (TemplateException e) {
                        throw new IOException(e);
                    }
                }
            };
            response.setEntity(rep);
            return true;
        } catch (Exception e) {
            skip.add(templateName);
        // Ignore
        }
    }
    return false;
}
Also used : HashMap(java.util.HashMap) TemplateException(freemarker.template.TemplateException) ValueDescriptor(org.qi4j.api.value.ValueDescriptor) Representation(org.restlet.representation.Representation) WriterRepresentation(org.restlet.representation.WriterRepresentation) IOException(java.io.IOException) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException) ResourceException(org.restlet.resource.ResourceException) Template(freemarker.template.Template) WriterRepresentation(org.restlet.representation.WriterRepresentation) MediaType(org.restlet.data.MediaType) Writer(java.io.Writer)

Example 53 with Template

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

the class FormResponseWriter method writeResponse.

@Override
public boolean writeResponse(final Object result, final Response response) throws ResourceException {
    if (result instanceof Form) {
        MediaType type = getVariant(response.getRequest(), ENGLISH, supportedMediaTypes).getMediaType();
        if (MediaType.APPLICATION_JSON.equals(type)) {
            JSONObject json = new JSONObject();
            Form form = (Form) result;
            try {
                for (Parameter parameter : form) {
                    String value = parameter.getValue();
                    if (value == null) {
                        json.put(parameter.getName(), JSONObject.NULL);
                    } else {
                        json.put(parameter.getName(), value);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            StringRepresentation representation = new StringRepresentation(json.toString(), MediaType.APPLICATION_JSON);
            response.setEntity(representation);
            return true;
        } else if (MediaType.TEXT_HTML.equals(type)) {
            Representation rep = new WriterRepresentation(MediaType.TEXT_HTML) {

                @Override
                public void write(Writer writer) throws IOException {
                    Map<String, Object> root = new HashMap<String, Object>();
                    root.put("request", response.getRequest());
                    root.put("response", response);
                    root.put("result", result);
                    try {
                        Template formHtmlTemplate = cfg.getTemplate("form.htm");
                        formHtmlTemplate.process(root, writer);
                    } catch (TemplateException e) {
                        throw new IOException(e);
                    }
                }
            };
            response.setEntity(rep);
            return true;
        }
    }
    return false;
}
Also used : Form(org.restlet.data.Form) TemplateException(freemarker.template.TemplateException) JSONException(org.json.JSONException) StringRepresentation(org.restlet.representation.StringRepresentation) Representation(org.restlet.representation.Representation) WriterRepresentation(org.restlet.representation.WriterRepresentation) IOException(java.io.IOException) Template(freemarker.template.Template) JSONObject(org.json.JSONObject) StringRepresentation(org.restlet.representation.StringRepresentation) WriterRepresentation(org.restlet.representation.WriterRepresentation) MediaType(org.restlet.data.MediaType) Parameter(org.restlet.data.Parameter) JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) Map(java.util.Map) Writer(java.io.Writer)

Example 54 with Template

use of freemarker.template.Template in project sonarqube by SonarSource.

the class HtmlReport method writeToFile.

public void writeToFile(IssuesReport report, File toFile, boolean complete) {
    try {
        freemarker.log.Logger.selectLoggerLibrary(freemarker.log.Logger.LIBRARY_NONE);
        freemarker.template.Configuration cfg = new freemarker.template.Configuration();
        cfg.setClassForTemplateLoading(HtmlReport.class, "");
        Map<String, Object> root = Maps.newHashMap();
        root.put("report", report);
        root.put("ruleNameProvider", ruleNameProvider);
        root.put("sourceProvider", sourceProvider);
        root.put("complete", complete);
        Template template = cfg.getTemplate("issuesreport.ftl");
        try (FileOutputStream fos = new FileOutputStream(toFile);
            Writer writer = new OutputStreamWriter(fos, fs.encoding())) {
            template.process(root, writer);
            writer.flush();
        }
    } catch (Exception e) {
        throw new IllegalStateException("Fail to generate HTML Issues Report to: " + toFile, e);
    }
}
Also used : URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) Template(freemarker.template.Template) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter)

Example 55 with Template

use of freemarker.template.Template in project platformlayer by platformlayer.

the class TemplateEngine method runTemplate.

public void runTemplate(String templateName, Map<String, Object> model, Writer writer) throws MojoExecutionException, IOException {
    Template template;
    try {
        template = getTemplate(templateName);
    } catch (IOException e) {
        throw new MojoExecutionException("Error reading template: " + templateName, e);
    }
    try {
        template.process(model, writer);
    } catch (freemarker.template.TemplateException e) {
        throw new MojoExecutionException("Error running template: " + templateName, e);
    }
    writer.flush();
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) IOException(java.io.IOException) Template(freemarker.template.Template)

Aggregations

Template (freemarker.template.Template)72 IOException (java.io.IOException)33 StringWriter (java.io.StringWriter)32 Configuration (freemarker.template.Configuration)30 Writer (java.io.Writer)26 HashMap (java.util.HashMap)26 TemplateException (freemarker.template.TemplateException)23 OutputStreamWriter (java.io.OutputStreamWriter)13 File (java.io.File)9 Map (java.util.Map)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 JSONObject (org.json.JSONObject)6 SimpleHash (freemarker.template.SimpleHash)5 ThirdEyeAnomalyConfiguration (com.linkedin.thirdeye.anomaly.ThirdEyeAnomalyConfiguration)4 StringTemplateLoader (freemarker.cache.StringTemplateLoader)4 Environment (freemarker.core.Environment)4 DefaultObjectWrapper (freemarker.template.DefaultObjectWrapper)4 BufferedWriter (java.io.BufferedWriter)4 FileOutputStream (java.io.FileOutputStream)4 StringReader (java.io.StringReader)4