Search in sources :

Example 1 with TemplateService

use of org.alfresco.service.cmr.repository.TemplateService 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 TemplateService

use of org.alfresco.service.cmr.repository.TemplateService 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)

Aggregations

StringTokenizer (java.util.StringTokenizer)2 NodeRef (org.alfresco.service.cmr.repository.NodeRef)2 TemplateException (org.alfresco.service.cmr.repository.TemplateException)2 TemplateService (org.alfresco.service.cmr.repository.TemplateService)2 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 SocketException (java.net.SocketException)1 ServletException (javax.servlet.ServletException)1 UserTransaction (javax.transaction.UserTransaction)1 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)1 AccessDeniedException (org.alfresco.repo.security.permissions.AccessDeniedException)1 ServiceRegistry (org.alfresco.service.ServiceRegistry)1 NodeService (org.alfresco.service.cmr.repository.NodeService)1 StoreRef (org.alfresco.service.cmr.repository.StoreRef)1 PermissionService (org.alfresco.service.cmr.security.PermissionService)1 Log (org.apache.commons.logging.Log)1