Search in sources :

Example 1 with TemplateException

use of org.alfresco.service.cmr.repository.TemplateException in project acs-community-packaging by Alfresco.

the class UITemplate method encodeBegin.

/**
 * @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext)
 */
public void encodeBegin(FacesContext context) throws IOException {
    if (isRendered() == false) {
        return;
    }
    // get the template to process
    String templateRef = getTemplate();
    if (templateRef == null || templateRef.length() == 0) {
        // no noderef/classpath template found - try a name based path
        String path = getTemplatePath();
        if (path != null && path.length() != 0) {
            // convert cm:name based path to a NodeRef
            StringTokenizer t = new StringTokenizer(path, "/");
            int tokenCount = t.countTokens();
            String[] elements = new String[tokenCount];
            for (int i = 0; i < tokenCount; i++) {
                elements[i] = t.nextToken();
            }
            NodeRef pathRef = BaseServlet.resolveWebDAVPath(context, elements, false);
            if (pathRef != null) {
                templateRef = pathRef.toString();
            }
        }
    }
    if (templateRef != null && templateRef.length() != 0) {
        long startTime = 0;
        if (logger.isDebugEnabled()) {
            logger.debug("Using template processor");
            startTime = System.currentTimeMillis();
        }
        // get the data model to use - building default FreeMarker model as required
        Object model = getTemplateModel(getModel(), templateRef);
        // process the template against the model
        try {
            TemplateService templateService = Repository.getServiceRegistry(context).getTemplateService();
            templateService.processTemplate(templateRef, model, context.getResponseWriter());
        } catch (TemplateException err) {
            Utils.addErrorMessage(err.getMessage(), err);
        }
        if (logger.isDebugEnabled()) {
            long endTime = System.currentTimeMillis();
            logger.debug("Time to process template: " + (endTime - startTime) + "ms");
        }
    }
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) StringTokenizer(java.util.StringTokenizer) TemplateException(org.alfresco.service.cmr.repository.TemplateException) TemplateService(org.alfresco.service.cmr.repository.TemplateService)

Example 2 with TemplateException

use of org.alfresco.service.cmr.repository.TemplateException in project alfresco-repository by Alfresco.

the class TemplateServiceImplTest method testProcessTemplate.

@Test
public void testProcessTemplate() {
    Map model = createTemplateModel(root_node);
    StringWriter writer = new StringWriter();
    templateService.processTemplate(TEMPLATE_1, model, writer);
    assertTrue((writer.toString().indexOf(root_node.getId()) != -1));
    try {
        templateService.processTemplate("NOT_REAL", TEMPLATE_1, model, new StringWriter());
        fail("The engine name is nonsense");
    } catch (TemplateException expected) {
    // 
    }
    try {
        templateService.processTemplate("NOT_REAL", TEMPLATE_1, model, I18NUtil.getLocale());
        fail("The engine name is nonsense");
    } catch (TemplateException expected) {
    // 
    }
    try {
        templateService.processTemplateString("NOT_REAL", TEMPLATE_1, model, new StringWriter());
        fail("The engine name is nonsense");
    } catch (TemplateException expected) {
    // 
    }
}
Also used : StringWriter(java.io.StringWriter) TemplateException(org.alfresco.service.cmr.repository.TemplateException) HashMap(java.util.HashMap) Map(java.util.Map) BaseSpringTest(org.alfresco.util.BaseSpringTest) Test(org.junit.Test) BaseNodeServiceTest(org.alfresco.repo.node.BaseNodeServiceTest)

Example 3 with TemplateException

use of org.alfresco.service.cmr.repository.TemplateException in project alfresco-repository by Alfresco.

the class TemplateServiceImpl method processTemplate.

/**
 * @see org.alfresco.service.cmr.repository.TemplateService#processTemplate(java.lang.String, java.lang.String, java.lang.Object, java.util.Locale)
 */
private void processTemplate(String engine, String template, Object model, Writer out, Locale locale) throws TemplateException {
    Locale currentLocale = I18NUtil.getLocaleOrNull();
    Locale currentContentLocale = I18NUtil.getContentLocaleOrNull();
    try {
        // set locale for cases where message method is used inside of template
        I18NUtil.setLocale(locale);
        // execute template processor
        TemplateProcessor processor = getTemplateProcessor(engine);
        processor.process(template, model, out, locale);
    } catch (TemplateException terr) {
        throw terr;
    } catch (Throwable err) {
        throw new TemplateException(err.getMessage(), err);
    } finally {
        I18NUtil.setLocale(currentLocale);
        I18NUtil.setContentLocale(currentContentLocale);
    }
}
Also used : Locale(java.util.Locale) TemplateException(org.alfresco.service.cmr.repository.TemplateException) TemplateProcessor(org.alfresco.service.cmr.repository.TemplateProcessor)

Example 4 with TemplateException

use of org.alfresco.service.cmr.repository.TemplateException in project alfresco-repository by Alfresco.

the class XSLTProcessor method process.

/**
 * @param templateSource
 * @param model
 * @param out
 */
private void process(TemplateSource templateSource, Object model, Writer out) {
    if ((model == null) || !XSLTemplateModel.class.isAssignableFrom(model.getClass())) {
        throw new IllegalArgumentException("\"model\" must be an XSLTemplateModel object: " + model);
    }
    XSLTemplateModel xsltModel = (XSLTemplateModel) model;
    System.setProperty("org.apache.xalan.extensions.bsf.BSFManager", BSFManager.class.getName());
    Document xslTemplate;
    try {
        xslTemplate = XMLUtil.parse(templateSource.getReader(defaultEncoding));
    } catch (IOException ex) {
        throw new TemplateException(MSG_UNABLE_TO_READ_TEMPLATE, new Object[] { ex.getMessage() }, ex);
    } catch (SAXException sax) {
        throw new TemplateException(MSG_UNABLE_TO_PARSE_TEMPLATE, new Object[] { sax.getMessage() }, sax);
    } finally {
        try {
            templateSource.close();
        } catch (IOException ex) {
            // There's little to be done here. Log it and carry on
            log.warn("Error while trying to close template stream", ex);
        }
    }
    List<String> scriptIds = addScripts(xsltModel, xslTemplate);
    addParameters(xsltModel, xslTemplate);
    final LinkedList<TransformerException> errors = new LinkedList<TransformerException>();
    final ErrorListener errorListener = new ErrorListener() {

        public void error(final TransformerException te) throws TransformerException {
            log.debug("error " + te.getMessageAndLocation());
            errors.add(te);
        }

        public void fatalError(final TransformerException te) throws TransformerException {
            log.debug("fatalError " + te.getMessageAndLocation());
            throw te;
        }

        public void warning(final TransformerException te) throws TransformerException {
            log.debug("warning " + te.getMessageAndLocation());
            errors.add(te);
        }
    };
    final TemplateSource resourceSource = templateSource;
    final URIResolver uriResolver = new URIResolver() {

        public Source resolve(final String href, String base) throws TransformerException {
            if (log.isDebugEnabled()) {
                log.debug("request to resolve href " + href + " using base " + base);
            }
            InputStream in = null;
            try {
                in = resourceSource.getResource(href);
                if (in == null) {
                    throw new TransformerException("unable to resolve href " + href);
                }
                Document d = XMLUtil.parse(in);
                if (log.isDebugEnabled()) {
                    log.debug("loaded " + XMLUtil.toString(d));
                }
                return new DOMSource(d);
            } catch (TransformerException ex) {
                throw ex;
            } catch (Exception e) {
                throw new TransformerException("unable to load " + href, e);
            }
        }
    };
    Source xmlSource = this.getXMLSource(xsltModel);
    Transformer t = null;
    try {
        final TransformerFactory tf = TransformerFactory.newInstance();
        tf.setErrorListener(errorListener);
        tf.setURIResolver(uriResolver);
        if (log.isDebugEnabled()) {
            log.debug("xslTemplate: \n" + XMLUtil.toString(xslTemplate));
        }
        t = tf.newTransformer(new DOMSource(xslTemplate));
        if (errors.size() != 0) {
            final StringBuilder msg = new StringBuilder("errors encountered creating tranformer ... \n");
            for (TransformerException te : errors) {
                msg.append(te.getMessageAndLocation()).append("\n");
            }
            throw new TemplateException(msg.toString());
        }
        t.setErrorListener(errorListener);
        t.setURIResolver(uriResolver);
        t.setParameter("versionParam", "2.0");
    } catch (TransformerConfigurationException tce) {
        log.error(tce);
        throw new TemplateException(tce.getMessage(), tce);
    }
    try {
        t.transform(xmlSource, new StreamResult(out));
    } catch (TransformerException te) {
        log.error(te.getMessageAndLocation());
        throw new TemplateException(te.getMessageAndLocation(), te);
    } catch (Exception e) {
        log.error("unexpected error " + e);
        throw new TemplateException(e.getMessage(), e);
    } finally {
        // Clear out any scripts that were created for this transform
        if (!scriptIds.isEmpty()) {
            XSLTProcessorMethodInvoker.removeMethods(scriptIds);
        }
    }
    if (errors.size() != 0) {
        final StringBuilder msg = new StringBuilder("errors encountered during transformation ... \n");
        for (TransformerException te : errors) {
            msg.append(te.getMessageAndLocation()).append("\n");
        }
        throw new TemplateException(msg.toString());
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) URIResolver(javax.xml.transform.URIResolver) Document(org.w3c.dom.Document) DOMSource(javax.xml.transform.dom.DOMSource) Source(javax.xml.transform.Source) SAXException(org.xml.sax.SAXException) ErrorListener(javax.xml.transform.ErrorListener) TransformerException(javax.xml.transform.TransformerException) TransformerFactory(javax.xml.transform.TransformerFactory) StreamResult(javax.xml.transform.stream.StreamResult) TemplateException(org.alfresco.service.cmr.repository.TemplateException) InputStream(java.io.InputStream) BSFManager(org.apache.bsf.BSFManager) IOException(java.io.IOException) LinkedList(java.util.LinkedList) TransformerException(javax.xml.transform.TransformerException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) IOException(java.io.IOException) TemplateException(org.alfresco.service.cmr.repository.TemplateException) SAXException(org.xml.sax.SAXException)

Example 5 with TemplateException

use of org.alfresco.service.cmr.repository.TemplateException in project alfresco-repository by Alfresco.

the class XSLTProcessor method process.

public void process(String template, Object model, Writer out) {
    TemplateSource templateSource;
    try {
        templateSource = (TemplateSource) templateLoader.findTemplateSource(template);
    } catch (IOException ex) {
        throw new TemplateException(MSG_UNABLE_TO_READ_TEMPLATE, new Object[] { ex.getMessage() }, ex);
    }
    process(templateSource, model, out);
}
Also used : TemplateException(org.alfresco.service.cmr.repository.TemplateException) IOException(java.io.IOException)

Aggregations

TemplateException (org.alfresco.service.cmr.repository.TemplateException)14 IOException (java.io.IOException)7 NodeRef (org.alfresco.service.cmr.repository.NodeRef)4 Template (freemarker.template.Template)3 TemplateProcessor (org.alfresco.service.cmr.repository.TemplateProcessor)3 Environment (freemarker.core.Environment)2 HashMap (java.util.HashMap)2 StringTokenizer (java.util.StringTokenizer)2 NodeService (org.alfresco.service.cmr.repository.NodeService)2 TemplateService (org.alfresco.service.cmr.repository.TemplateService)2 Document (org.w3c.dom.Document)2 SimpleDate (freemarker.template.SimpleDate)1 SimpleHash (freemarker.template.SimpleHash)1 InputStream (java.io.InputStream)1 StringWriter (java.io.StringWriter)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 SocketException (java.net.SocketException)1 Date (java.util.Date)1 LinkedList (java.util.LinkedList)1 Locale (java.util.Locale)1