Search in sources :

Example 6 with TemplateException

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

the class NodeInfoBean method sendNodeInfo.

/**
 * Returns information on the node identified by the 'noderef'
 * parameter found in the ExternalContext. If no noderef is supplied, then the template
 * is executed without context.
 * <p>
 * The result is the formatted HTML to show on the client.
 */
public void sendNodeInfo() throws IOException {
    FacesContext context = FacesContext.getCurrentInstance();
    ResponseWriter out = context.getResponseWriter();
    Map<String, String> requestMap = context.getExternalContext().getRequestParameterMap();
    String strNodeRef = (String) requestMap.get("noderef");
    String strTemplate = (String) requestMap.get("template");
    if (strTemplate == null || strTemplate.length() == 0) {
        strTemplate = "node_summary_panel.ftl";
    }
    NodeRef nodeRef = null;
    if (strNodeRef != null && strNodeRef.length() != 0) {
        nodeRef = new NodeRef(strNodeRef);
        if (this.getNodeService().exists(nodeRef) == false) {
            out.write("<span class='errorMessage'>Node could not be found in the repository!</span>");
            return;
        }
    }
    try {
        Repository.getServiceRegistry(context).getTemplateService().processTemplate("/alfresco/templates/client/" + strTemplate, getModel(nodeRef, requestMap), out);
    } catch (TemplateException ex) {
        // Try to catch TransformerInfoException to display it in NodeInfo pane.
        // Fix bug reported in https://issues.alfresco.com/jira/browse/ETWOTWO-440
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause = cause.getCause();
            if (cause instanceof TransformerInfoException) {
                out.write("<tr><td colspan=\"2\"><span class='errorMessage'>" + cause.getMessage() + "</span></td></tr>");
                return;
            }
        }
        throw ex;
    }
}
Also used : FacesContext(javax.faces.context.FacesContext) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ResponseWriter(javax.faces.context.ResponseWriter) TemplateException(org.alfresco.service.cmr.repository.TemplateException) TransformerInfoException(org.alfresco.repo.content.transform.TransformerInfoException)

Example 7 with TemplateException

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

the class BaseTemplateContentServlet method processTemplateRequest.

/**
 * Processes the template request using the current context i.e. no
 * authentication checks are made, it is presumed they have already
 * been done.
 *
 * @param req The HTTP request
 * @param res The HTTP response
 * @param redirectToLogin Flag to determine whether to redirect to the login
 *                        page if the user does not have the correct permissions
 */
protected void processTemplateRequest(HttpServletRequest req, HttpServletResponse res, boolean redirectToLogin) throws ServletException, IOException {
    Log logger = getLogger();
    String uri = req.getRequestURI();
    if (logger.isDebugEnabled()) {
        String queryString = req.getQueryString();
        logger.debug("Processing URL: " + uri + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
    }
    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();
    // skip servlet name
    t.nextToken();
    NodeRef nodeRef = null;
    NodeRef templateRef = null;
    try {
        String contentPath = req.getParameter(ARG_CONTEXT_PATH);
        if (contentPath != null && contentPath.length() != 0) {
            // process the name based path to resolve the NodeRef
            PathRefInfo pathInfo = resolveNamePath(getServletContext(), contentPath);
            nodeRef = pathInfo.NodeRef;
        } else if (tokenCount > 3) {
            // get NodeRef to the content from the URL elements
            StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
            nodeRef = new NodeRef(storeRef, t.nextToken());
        }
        // get NodeRef to the template if supplied
        String templatePath = req.getParameter(ARG_TEMPLATE_PATH);
        if (templatePath != null && templatePath.length() != 0) {
            // process the name based path to resolve the NodeRef
            PathRefInfo pathInfo = resolveNamePath(getServletContext(), templatePath);
            templateRef = pathInfo.NodeRef;
        } else if (tokenCount >= 7) {
            StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
            templateRef = new NodeRef(storeRef, t.nextToken());
        }
    } catch (AccessDeniedException err) {
        if (redirectToLogin) {
            if (logger.isDebugEnabled())
                logger.debug("Redirecting to login page...");
            redirectToLoginPage(req, res, getServletContext());
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Returning 403 Forbidden error...");
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
        return;
    }
    // TODO: should this default to something else?
    if (nodeRef == null && templateRef != null) {
        nodeRef = templateRef;
    }
    if (nodeRef == null) {
        throw new TemplateException("Not enough elements supplied in URL or no 'path' argument specified.");
    }
    // get the services we need to retrieve the content
    ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
    NodeService nodeService = serviceRegistry.getNodeService();
    TemplateService templateService = serviceRegistry.getTemplateService();
    PermissionService permissionService = serviceRegistry.getPermissionService();
    // check that the user has at least READ access on any nodes - else redirect to the login page
    if (permissionService.hasPermission(nodeRef, PermissionService.READ) == AccessStatus.DENIED || (templateRef != null && permissionService.hasPermission(templateRef, PermissionService.READ) == AccessStatus.DENIED)) {
        if (redirectToLogin) {
            if (logger.isDebugEnabled())
                logger.debug("Redirecting to login page...");
            redirectToLoginPage(req, res, getServletContext());
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Returning 403 Forbidden error...");
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
        return;
    }
    String mimetype = MIMETYPE_HTML;
    if (req.getParameter(ARG_MIMETYPE) != null) {
        mimetype = req.getParameter(ARG_MIMETYPE);
    }
    res.setContentType(mimetype);
    try {
        UserTransaction txn = null;
        try {
            txn = serviceRegistry.getTransactionService().getUserTransaction(true);
            txn.begin();
            // if template not supplied, then use the default against the node
            if (templateRef == null) {
                if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_TEMPLATABLE)) {
                    templateRef = (NodeRef) nodeService.getProperty(nodeRef, ContentModel.PROP_TEMPLATE);
                }
                if (templateRef == null) {
                    throw new TemplateException("Template reference not set against node or not supplied in URL.");
                }
            }
            // create the model - put the supplied noderef in as space/document as appropriate
            Map<String, Object> model = getModel(serviceRegistry, req, templateRef, nodeRef);
            // to be streamed directly to the browser response stream.
            try {
                templateService.processTemplate(templateRef.toString(), model, res.getWriter());
                // commit the transaction
                txn.commit();
            } catch (SocketException e) {
                if (e.getMessage().contains("ClientAbortException")) {
                    // the client cut the connection - our mission was accomplished apart from a little error message
                    logger.error("Client aborted stream read:\n   node: " + nodeRef + "\n   template: " + templateRef);
                    try {
                        if (txn != null) {
                            txn.rollback();
                        }
                    } catch (Exception tex) {
                    }
                } else {
                    throw e;
                }
            } finally {
                res.getWriter().close();
            }
        } catch (Throwable txnErr) {
            try {
                if (txn != null) {
                    txn.rollback();
                }
            } catch (Exception tex) {
            }
            throw txnErr;
        }
    } catch (Throwable err) {
        throw new AlfrescoRuntimeException("Error during template servlet processing: " + err.getMessage(), err);
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) StoreRef(org.alfresco.service.cmr.repository.StoreRef) SocketException(java.net.SocketException) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) Log(org.apache.commons.logging.Log) TemplateException(org.alfresco.service.cmr.repository.TemplateException) NodeService(org.alfresco.service.cmr.repository.NodeService) ServletException(javax.servlet.ServletException) SocketException(java.net.SocketException) IOException(java.io.IOException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) TemplateException(org.alfresco.service.cmr.repository.TemplateException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PermissionService(org.alfresco.service.cmr.security.PermissionService) NodeRef(org.alfresco.service.cmr.repository.NodeRef) StringTokenizer(java.util.StringTokenizer) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) ServiceRegistry(org.alfresco.service.ServiceRegistry) TemplateService(org.alfresco.service.cmr.repository.TemplateService)

Example 8 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.io.Writer)
 */
public void processTemplate(String engine, String template, Object model, Writer out) throws TemplateException {
    try {
        // execute template processor
        TemplateProcessor processor = getTemplateProcessor(engine);
        processor.process(template, model, out);
    } catch (TemplateException terr) {
        throw terr;
    } catch (Throwable err) {
        throw new TemplateException(err.getMessage(), err);
    }
}
Also used : TemplateException(org.alfresco.service.cmr.repository.TemplateException) TemplateProcessor(org.alfresco.service.cmr.repository.TemplateProcessor)

Example 9 with TemplateException

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

the class TemplateServiceImpl method processTemplateString.

/**
 * @see org.alfresco.service.cmr.repository.TemplateService#processTemplateString(java.lang.String, java.lang.String, java.lang.Object, java.io.Writer)
 */
public void processTemplateString(String engine, String template, Object model, Writer out) throws TemplateException {
    try {
        // execute template processor
        TemplateProcessor processor = getTemplateProcessor(engine);
        processor.processString(template, model, out);
    } catch (TemplateException terr) {
        throw terr;
    } catch (Throwable err) {
        throw new TemplateException(err.getMessage(), err);
    }
}
Also used : TemplateException(org.alfresco.service.cmr.repository.TemplateException) TemplateProcessor(org.alfresco.service.cmr.repository.TemplateProcessor)

Example 10 with TemplateException

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

the class StandardRenditionLocationResolverImpl method renderPathTemplate.

private String renderPathTemplate(String pathTemplate, NodeRef sourceNode, NodeRef tempRenditionLocation, NodeRef companyHome) {
    NodeService nodeService = serviceRegistry.getNodeService();
    FileFolderService fileFolderService = serviceRegistry.getFileFolderService();
    final Map<String, Object> root = new HashMap<String, Object>();
    List<FileInfo> sourcePathInfo;
    String fullSourceName;
    String cwd;
    try {
        // Since the root of the store is typically not a folder, we use company home as the root of this tree
        sourcePathInfo = fileFolderService.getNamePath(companyHome, sourceNode);
        // Remove the last element (the actual source file name)
        FileInfo sourceFileInfo = sourcePathInfo.remove(sourcePathInfo.size() - 1);
        fullSourceName = sourceFileInfo.getName();
        StringBuilder cwdBuilder = new StringBuilder("/");
        for (FileInfo file : sourcePathInfo) {
            cwdBuilder.append(file.getName());
            cwdBuilder.append('/');
        }
        cwd = cwdBuilder.toString();
    } catch (FileNotFoundException e) {
        log.warn("Failed to resolve path to source node: " + sourceNode + ". Default to Company Home");
        fullSourceName = nodeService.getPrimaryParent(sourceNode).getQName().getLocalName();
        cwd = "/";
    }
    String trimmedSourceName = fullSourceName;
    String sourceExtension = "";
    int extensionIndex = fullSourceName.lastIndexOf('.');
    if (extensionIndex != -1) {
        trimmedSourceName = (extensionIndex == 0) ? "" : fullSourceName.substring(0, extensionIndex);
        sourceExtension = (extensionIndex == fullSourceName.length() - 1) ? "" : fullSourceName.substring(extensionIndex + 1);
    }
    root.put("name", trimmedSourceName);
    root.put("extension", sourceExtension);
    root.put("date", new SimpleDate(new Date(), SimpleDate.DATETIME));
    root.put("cwd", cwd);
    TemplateNode companyHomeNode = new TemplateNode(companyHome, serviceRegistry, null);
    root.put("companyHome", companyHomeNode);
    // Added this to be consistent with the script API
    root.put("companyhome", companyHomeNode);
    root.put("sourceNode", new TemplateNode(sourceNode, serviceRegistry, null));
    root.put("sourceContentType", nodeService.getType(sourceNode).getLocalName());
    root.put("renditionContentType", nodeService.getType(tempRenditionLocation).getLocalName());
    NodeRef person = serviceRegistry.getPersonService().getPerson(AuthenticationUtil.getFullyAuthenticatedUser());
    root.put("person", new TemplateNode(person, serviceRegistry, null));
    if (sourceNodeIsXml(sourceNode)) {
        try {
            Document xml = XMLUtil.parse(sourceNode, serviceRegistry.getContentService());
            pathTemplate = buildNamespaceDeclaration(xml) + pathTemplate;
            root.put("xml", NodeModel.wrap(xml));
        } catch (Exception ex) {
            log.warn("Failed to parse XML content into path template model: Node = " + sourceNode);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Path template model: " + root);
    }
    String result = null;
    try {
        if (log.isDebugEnabled()) {
            log.debug("Processing " + pathTemplate + " using source node " + cwd + fullSourceName);
        }
        result = serviceRegistry.getTemplateService().processTemplateString("freemarker", pathTemplate, new SimpleHash(root));
    } catch (TemplateException te) {
        log.error("Error while trying to process rendition path template: " + pathTemplate);
        log.error(te.getMessage(), te);
    }
    if (log.isDebugEnabled()) {
        log.debug("processed pattern " + pathTemplate + " as " + result);
    }
    return result;
}
Also used : TemplateNode(org.alfresco.repo.template.TemplateNode) HashMap(java.util.HashMap) TemplateException(org.alfresco.service.cmr.repository.TemplateException) NodeService(org.alfresco.service.cmr.repository.NodeService) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) FileFolderService(org.alfresco.service.cmr.model.FileFolderService) Document(org.w3c.dom.Document) SimpleDate(freemarker.template.SimpleDate) Date(java.util.Date) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) RenditionServiceException(org.alfresco.service.cmr.rendition.RenditionServiceException) TemplateException(org.alfresco.service.cmr.repository.TemplateException) NodeRef(org.alfresco.service.cmr.repository.NodeRef) FileInfo(org.alfresco.service.cmr.model.FileInfo) SimpleDate(freemarker.template.SimpleDate) SimpleHash(freemarker.template.SimpleHash)

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