Search in sources :

Example 31 with NodeService

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

the class AbstractItemSelector method encodeBegin.

/**
 * @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext)
 */
public void encodeBegin(FacesContext context) throws IOException {
    if (isRendered() == false) {
        return;
    }
    NodeService service = getNodeService(context);
    UserTransaction tx = null;
    try {
        tx = Repository.getUserTransaction(context, true);
        tx.begin();
        if (isDisabled()) {
            // render a read-only view of the selected category (if any)
            ResponseWriter out = context.getResponseWriter();
            // see if there is a current value for the category
            NodeRef nodeRef = (NodeRef) getSubmittedValue();
            if (nodeRef == null) {
                Object val = getValue();
                if (val instanceof NodeRef) {
                    nodeRef = (NodeRef) val;
                } else if (val instanceof String && ((String) val).length() != 0) {
                    nodeRef = new NodeRef((String) val);
                } else if (val instanceof List) {
                    // build a comma separated list of node names
                    List nodes = (List) val;
                    StringBuilder buffer = new StringBuilder(64);
                    for (Object obj : nodes) {
                        if (buffer.length() != 0) {
                            buffer.append(", ");
                        }
                        if (obj instanceof NodeRef) {
                            buffer.append(Utils.encode(Repository.getNameForNode(service, (NodeRef) obj)));
                        } else {
                            buffer.append(obj.toString());
                        }
                    }
                    // write out to response
                    out.write(buffer.toString());
                }
            }
            // if there is a value show it's name
            if (nodeRef != null) {
                out.write(Utils.encode(Repository.getNameForNode(service, nodeRef)));
            }
        } else {
            // render an editable control for selecting items
            String clientId = getClientId(context);
            StringBuilder buf = new StringBuilder(512);
            Map attrs = this.getAttributes();
            boolean showValueInHiddenField = false;
            NodeRef value = null;
            switch(this.mode) {
                case MODE_BEFORE_SELECTION:
                case MODE_CONFIRM_SELECTION:
                case MODE_CANCEL_SELECTION:
                    {
                        NodeRef submittedValue = (NodeRef) getSubmittedValue();
                        if (submittedValue != null) {
                            value = submittedValue;
                        } else {
                            Object val = getValue();
                            if (val instanceof NodeRef) {
                                value = (NodeRef) val;
                            } else if (val instanceof String && ((String) val).length() != 0) {
                                value = new NodeRef((String) val);
                            }
                        }
                        // show just the initial or current selection link
                        String label;
                        if (value == null) {
                            label = getLabel();
                            // if the label is still null get the default from the message bundle
                            if (label == null) {
                                label = getDefaultLabel();
                            }
                        } else {
                            label = Repository.getNameForNode(service, value);
                            showValueInHiddenField = true;
                        }
                        // output surrounding span for style purposes
                        buf.append("<span");
                        if (attrs.get("style") != null) {
                            buf.append(" style=\"").append(attrs.get("style")).append('"');
                        }
                        if (attrs.get("styleClass") != null) {
                            buf.append(" class=").append(attrs.get("styleClass"));
                        }
                        buf.append(">");
                        // rendering as initial selection mode means the sibilings of the selected
                        // item are shown instead of the children on first click in.
                        int theMode = MODE_INITIAL_SELECTION;
                        // if we have an initial selection and no value set the initial one up
                        if (value == null && this.getInitialSelection() != null) {
                            value = new NodeRef(Repository.getStoreRef(), this.getInitialSelection());
                        }
                        // field value is whether we are picking and the current or parent Id value
                        String fieldValue;
                        if (value != null) {
                            fieldValue = encodeFieldValues(theMode, value.getId());
                        } else {
                            fieldValue = encodeFieldValues(theMode, null);
                        }
                        buf.append("<a href='#' onclick=\"");
                        buf.append(Utils.generateFormSubmit(context, this, getHiddenFieldName(), fieldValue));
                        buf.append('"');
                        if (attrs.get("nodeStyle") != null) {
                            buf.append(" style=\"").append(attrs.get("nodeStyle")).append('"');
                        }
                        if (attrs.get("nodeStyleClass") != null) {
                            buf.append(" class=").append(attrs.get("nodeStyleClass"));
                        }
                        buf.append(">").append(Utils.encode(label)).append("</a></span>");
                        break;
                    }
                case MODE_DRILLDOWN_SELECTION:
                case MODE_INITIAL_SELECTION:
                    {
                        // show the picker list
                        // get the children of the node ref to show
                        buf.append("<table border=0 cellspacing=1 cellpadding=1");
                        if (attrs.get("style") != null) {
                            buf.append(" style=\"").append(attrs.get("style")).append('"');
                        }
                        if (attrs.get("styleClass") != null) {
                            buf.append(" class=").append(attrs.get("styleClass"));
                        }
                        buf.append(">");
                        // the item when the list is rendered
                        if (this.mode == MODE_INITIAL_SELECTION) {
                            this.navigationId = getParentNodeId(context);
                        }
                        // render "Go Up" link if not at the root level
                        if (this.navigationId != null) {
                            // get the id of the parent node of the current navigation node,
                            // null indicates we are at the root level
                            String id = getParentNodeId(context);
                            buf.append("<tr><td></td><td>");
                            String upImage = Utils.buildImageTag(context, WebResources.IMAGE_GO_UP, null, "absmiddle");
                            // render a link to the parent node
                            renderNodeLink(context, id, Application.getMessage(context, MSG_GO_UP), upImage, buf);
                            buf.append("</td></tr>");
                        }
                        String okButtonId = clientId + OK_BUTTON;
                        boolean okButtonEnabled = false;
                        // display the children of the specified navigation node ID
                        Collection<NodeRef> childRefs;
                        if (this.navigationId != null) {
                            // get a list of children for the current navigation node
                            childRefs = getChildrenForNode(context);
                        } else {
                            // no node set - special case to show the initial root items
                            childRefs = getRootChildren(context);
                        }
                        for (NodeRef childRef : childRefs) {
                            // render each child found
                            String childId = childRef.getId();
                            buf.append("<tr><td><input type='radio' name='").append(clientId).append(OPTION).append("' value='").append(childId).append("'");
                            if (childId.equals(this.initialSelectionId)) {
                                buf.append(" checked");
                                // if any radio buttons are checked, the OK button must start enabled
                                okButtonEnabled = true;
                                // now remove the initial selection as we only need it the first time
                                this.initialSelectionId = null;
                            }
                            buf.append(" onclick=\"javascript:document.getElementById('").append(okButtonId).append("').disabled=false;\"");
                            buf.append("/></td><td>");
                            // get the name for the child and output as link
                            String name = Repository.getNameForNode(service, childRef);
                            String prefixHtml = null;
                            String icon = getItemIcon(context, childRef);
                            if (icon != null) {
                                prefixHtml = "<span style='padding-right:4px'>" + Utils.buildImageTag(context, icon, null, "absmiddle") + "</span>";
                            }
                            renderNodeLink(context, childId, name, prefixHtml, buf);
                            buf.append("</td></tr>");
                        }
                        // render OK button
                        String fieldValue = encodeFieldValues(MODE_CONFIRM_SELECTION, null);
                        buf.append("<tr style='padding-top:4px'><td></td><td align=center>").append("<input type='button' ").append(okButtonEnabled == false ? "disabled" : "").append(" onclick=\"").append(Utils.generateFormSubmit(context, this, getHiddenFieldName(), fieldValue)).append("\" value='").append(Application.getMessage(context, MSG_OK)).append("' id='").append(okButtonId).append("'>&nbsp;");
                        // render Cancel button
                        fieldValue = encodeFieldValues(MODE_CANCEL_SELECTION, null);
                        buf.append("<input type='button' onclick=\"").append(Utils.generateFormSubmit(context, this, getHiddenFieldName(), fieldValue)).append("\" value='").append(Application.getMessage(context, MSG_CANCEL)).append("'></td></tr>");
                        buf.append("</table>");
                        break;
                    }
            }
            // output a hidden field containing the currently selected NodeRef so that JavaScript
            // can be used to check the state of the component
            buf.append("<input type='hidden' name='");
            buf.append(clientId);
            buf.append("_selected' id='");
            buf.append(clientId);
            buf.append("_selected' value='");
            if (showValueInHiddenField) {
                buf.append(value);
            }
            buf.append("'/>");
            context.getResponseWriter().write(buf.toString());
        }
        // commit the transaction
        tx.commit();
    } catch (Throwable err) {
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) NodeService(org.alfresco.service.cmr.repository.NodeService) AbortProcessingException(javax.faces.event.AbortProcessingException) IOException(java.io.IOException) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ResponseWriter(javax.faces.context.ResponseWriter) Collection(java.util.Collection) List(java.util.List) Map(java.util.Map)

Example 32 with NodeService

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

the class AuthenticationHelper method createUser.

/**
 * Creates an object for an authentication user.
 *
 * @param wc
 *           the web application context
 * @param currentUsername
 *           the current user name
 * @param ticket
 *           a validated ticket
 * @return the user object
 */
private static User createUser(final WebApplicationContext wc, final String currentUsername, final String ticket) {
    if (logger.isDebugEnabled())
        logger.debug("Creating an object for " + currentUsername + " with ticket: " + ticket);
    final ServiceRegistry services = (ServiceRegistry) wc.getBean(ServiceRegistry.SERVICE_REGISTRY);
    // If the repository is read only, we have to settle for a read only transaction. Auto user creation
    // will not be possible.
    boolean readOnly = services.getTransactionService().isReadOnly();
    return services.getTransactionService().getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<User>() {

        public User execute() throws Throwable {
            NodeService nodeService = services.getNodeService();
            PersonService personService = (PersonService) wc.getBean(PERSON_SERVICE);
            NodeRef personRef = personService.getPerson(currentUsername);
            User user = new User(currentUsername, ticket, personRef);
            NodeRef homeRef = (NodeRef) nodeService.getProperty(personRef, ContentModel.PROP_HOMEFOLDER);
            if (homeRef == null || !nodeService.exists(homeRef)) {
                throw new AuthenticationException("Home folder is missing for user " + currentUsername);
            }
            user.setHomeSpaceId(homeRef.getId());
            return user;
        }
    }, readOnly, false);
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) SessionUser(org.alfresco.repo.SessionUser) User(org.alfresco.web.bean.repository.User) RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) NodeService(org.alfresco.service.cmr.repository.NodeService) PersonService(org.alfresco.service.cmr.security.PersonService) ServiceRegistry(org.alfresco.service.ServiceRegistry)

Example 33 with NodeService

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

the class BaseDownloadContentServlet method processDownloadRequest.

/**
 * Processes the download 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 allowLogIn
 *           Indicates whether guest users without access to the content should be redirected to the log in page. If
 *           <code>false</code>, a status 403 forbidden page is displayed instead.
 */
protected void processDownloadRequest(HttpServletRequest req, HttpServletResponse res, boolean allowLogIn, boolean transmitContent) 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();
    // attachment mode (either 'attach' or 'direct')
    String attachToken = t.nextToken();
    boolean attachment = URL_ATTACH.equals(attachToken) || URL_ATTACH_LONG.equals(attachToken);
    ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
    // get or calculate the noderef and filename to download as
    NodeRef nodeRef;
    String filename;
    // do we have a path parameter instead of a NodeRef?
    String path = req.getParameter(ARG_PATH);
    if (path != null && path.length() != 0) {
        // process the name based path to resolve the NodeRef and the Filename element
        try {
            PathRefInfo pathInfo = resolveNamePath(getServletContext(), path);
            nodeRef = pathInfo.NodeRef;
            filename = pathInfo.Filename;
        } catch (IllegalArgumentException e) {
            Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND, HttpServletResponse.SC_NOT_FOUND, logger);
            return;
        }
    } else {
        // a NodeRef must have been specified if no path has been found
        if (tokenCount < 6) {
            throw new IllegalArgumentException("Download URL did not contain all required args: " + uri);
        }
        // assume 'workspace' or other NodeRef based protocol for remaining URL elements
        StoreRef storeRef = new StoreRef(URLDecoder.decode(t.nextToken()), URLDecoder.decode(t.nextToken()));
        String id = URLDecoder.decode(t.nextToken());
        // build noderef from the appropriate URL elements
        nodeRef = new NodeRef(storeRef, id);
        if (tokenCount > 6) {
            // found additional relative path elements i.e. noderefid/images/file.txt
            // this allows a url to reference siblings nodes via a cm:name based relative path
            // solves the issue with opening HTML content containing relative URLs in HREF or IMG tags etc.
            List<String> paths = new ArrayList<String>(tokenCount - 5);
            while (t.hasMoreTokens()) {
                paths.add(URLDecoder.decode(t.nextToken()));
            }
            filename = paths.get(paths.size() - 1);
            try {
                NodeRef parentRef = serviceRegistry.getNodeService().getPrimaryParent(nodeRef).getParentRef();
                FileInfo fileInfo = serviceRegistry.getFileFolderService().resolveNamePath(parentRef, paths);
                nodeRef = fileInfo.getNodeRef();
            } catch (FileNotFoundException e) {
                Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND, HttpServletResponse.SC_NOT_FOUND, logger);
                return;
            }
        } else {
            // filename is last remaining token
            filename = t.nextToken();
        }
    }
    // get qualified of the property to get content from - default to ContentModel.PROP_CONTENT
    QName propertyQName = ContentModel.PROP_CONTENT;
    String property = req.getParameter(ARG_PROPERTY);
    if (property != null && property.length() != 0) {
        propertyQName = QName.createQName(property);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Found NodeRef: " + nodeRef);
        logger.debug("Will use filename: " + filename);
        logger.debug("For property: " + propertyQName);
        logger.debug("With attachment mode: " + attachment);
    }
    // get the services we need to retrieve the content
    NodeService nodeService = serviceRegistry.getNodeService();
    ContentService contentService = serviceRegistry.getContentService();
    // Check that the node still exists
    if (!nodeService.exists(nodeRef)) {
        Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND, HttpServletResponse.SC_NOT_FOUND, logger);
        return;
    }
    try {
        // check that the user has at least READ_CONTENT access - else redirect to an error or login page
        if (!checkAccess(req, res, nodeRef, PermissionService.READ_CONTENT, allowLogIn)) {
            return;
        }
        // check If-Modified-Since header and set Last-Modified header as appropriate
        Date modified = (Date) nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIED);
        if (modified != null) {
            long modifiedSince = req.getDateHeader(HEADER_IF_MODIFIED_SINCE);
            if (modifiedSince > 0L) {
                // round the date to the ignore millisecond value which is not supplied by header
                long modDate = (modified.getTime() / 1000L) * 1000L;
                if (modDate <= modifiedSince) {
                    if (logger.isDebugEnabled())
                        logger.debug("Returning 304 Not Modified.");
                    res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return;
                }
            }
            res.setDateHeader(HEADER_LAST_MODIFIED, modified.getTime());
            res.setHeader(HEADER_CACHE_CONTROL, "must-revalidate, max-age=0");
            res.setHeader(HEADER_ETAG, "\"" + Long.toString(modified.getTime()) + "\"");
        }
        if (attachment == true) {
            setHeaderContentDisposition(req, res, filename);
        }
        // get the content reader
        ContentReader reader = contentService.getReader(nodeRef, propertyQName);
        // ensure that it is safe to use
        reader = FileContentReader.getSafeContentReader(reader, Application.getMessage(req.getSession(), MSG_ERROR_CONTENT_MISSING), nodeRef, reader);
        String mimetype = reader.getMimetype();
        // fall back if unable to resolve mimetype property
        if (mimetype == null || mimetype.length() == 0) {
            MimetypeService mimetypeMap = serviceRegistry.getMimetypeService();
            mimetype = MIMETYPE_OCTET_STREAM;
            int extIndex = filename.lastIndexOf('.');
            if (extIndex != -1) {
                String ext = filename.substring(extIndex + 1);
                mimetype = mimetypeMap.getMimetype(ext);
            }
        }
        // explicitly set the content disposition header if the content is powerpoint
        if (!attachment && (mimetype.equals(POWER_POINT_2007_DOCUMENT_MIMETYPE) || mimetype.equals(POWER_POINT_DOCUMENT_MIMETYPE))) {
            setHeaderContentDisposition(req, res, filename);
        }
        // get the content and stream directly to the response output stream
        // assuming the repo is capable of streaming in chunks, this should allow large files
        // to be streamed directly to the browser response stream.
        res.setHeader(HEADER_ACCEPT_RANGES, "bytes");
        // for a GET request, transmit the content else just the headers are sent
        if (transmitContent) {
            try {
                boolean processedRange = false;
                String range = req.getHeader(HEADER_CONTENT_RANGE);
                if (range == null) {
                    range = req.getHeader(HEADER_RANGE);
                }
                if (range != null) {
                    if (logger.isDebugEnabled())
                        logger.debug("Found content range header: " + range);
                    // ensure the range header is starts with "bytes=" and process the range(s)
                    if (range.length() > 6) {
                        HttpRangeProcessor rangeProcessor = new HttpRangeProcessor(contentService);
                        processedRange = rangeProcessor.processRange(res, reader, range.substring(6), nodeRef, propertyQName, mimetype, req.getHeader(HEADER_USER_AGENT));
                    }
                }
                if (processedRange == false) {
                    if (logger.isDebugEnabled())
                        logger.debug("Sending complete file content...");
                    // set mimetype for the content and the character encoding for the stream
                    res.setContentType(mimetype);
                    res.setCharacterEncoding(reader.getEncoding());
                    // MNT-10642 Alfresco Explorer has javascript vulnerability opening HTML files
                    if (req.getRequestURI().contains("/d/d/") && (mimetype.equals("text/html") || mimetype.equals("application/xhtml+xml") || mimetype.equals("text/xml"))) {
                        String content = reader.getContentString();
                        if (mimetype.equals("text/html") || mimetype.equals("application/xhtml+xml")) {
                            // process with HTML stripper
                            content = StringUtils.stripUnsafeHTMLTags(content, false);
                        } else if (mimetype.equals("text/xml") && mimetype.equals("text/x-component")) {
                            // IE supports "behaviour" which means that css can load a .htc file that could
                            // contain XSS code in the form of jscript, vbscript etc, to stop it form being
                            // evaluated we set the contient type to text/plain
                            res.setContentType("text/plain");
                        }
                        String encoding = reader.getEncoding();
                        byte[] bytes = encoding != null ? content.getBytes(encoding) : content.getBytes();
                        res.setContentLength(bytes.length);
                        res.getOutputStream().write(bytes);
                        return;
                    }
                    // return the complete entity range
                    long size = reader.getSize();
                    res.setHeader(HEADER_CONTENT_RANGE, "bytes 0-" + Long.toString(size - 1L) + "/" + Long.toString(size));
                    res.setHeader(HEADER_CONTENT_LENGTH, Long.toString(size));
                    reader.getContent(res.getOutputStream());
                }
            } catch (SocketException e1) {
                // the client cut the connection - our mission was accomplished apart from a little error message
                if (logger.isDebugEnabled())
                    logger.debug("Client aborted stream read:\n\tnode: " + nodeRef + "\n\tcontent: " + reader);
            } catch (ContentIOException e2) {
                if (logger.isInfoEnabled())
                    logger.info("Failed stream read:\n\tnode: " + nodeRef + " due to: " + e2.getMessage());
            } catch (Throwable err) {
                if (err.getCause() instanceof SocketException) {
                    // the client cut the connection - our mission was accomplished apart from a little error message
                    if (logger.isDebugEnabled())
                        logger.debug("Client aborted stream read:\n\tnode: " + nodeRef + "\n\tcontent: " + reader);
                } else
                    throw err;
            }
        } else {
            if (logger.isDebugEnabled())
                logger.debug("HEAD request processed - no content sent.");
            res.getOutputStream().close();
        }
    } catch (Throwable err) {
        throw new AlfrescoRuntimeException("Error during download content servlet processing: " + err.getMessage(), err);
    }
}
Also used : SocketException(java.net.SocketException) ArrayList(java.util.ArrayList) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) ContentIOException(org.alfresco.service.cmr.repository.ContentIOException) NodeRef(org.alfresco.service.cmr.repository.NodeRef) FileInfo(org.alfresco.service.cmr.model.FileInfo) HttpRangeProcessor(org.alfresco.repo.web.util.HttpRangeProcessor) StoreRef(org.alfresco.service.cmr.repository.StoreRef) Log(org.apache.commons.logging.Log) QName(org.alfresco.service.namespace.QName) NodeService(org.alfresco.service.cmr.repository.NodeService) FileContentReader(org.alfresco.repo.content.filestore.FileContentReader) ContentReader(org.alfresco.service.cmr.repository.ContentReader) ContentService(org.alfresco.service.cmr.repository.ContentService) Date(java.util.Date) StringTokenizer(java.util.StringTokenizer) MimetypeService(org.alfresco.service.cmr.repository.MimetypeService) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) ServiceRegistry(org.alfresco.service.ServiceRegistry)

Example 34 with NodeService

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

the class ContextListener method contextInitialized.

/**
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 */
public void contextInitialized(ServletContextEvent event) {
    // make sure that the spaces store in the repository exists
    this.servletContext = event.getServletContext();
    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
    // If no context has been initialised, exit silently so config changes can be made
    if (ctx == null) {
        return;
    }
    ServiceRegistry registry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    TransactionService transactionService = registry.getTransactionService();
    NodeService nodeService = registry.getNodeService();
    SearchService searchService = registry.getSearchService();
    NamespaceService namespaceService = registry.getNamespaceService();
    AuthenticationContext authenticationContext = (AuthenticationContext) ctx.getBean("authenticationContext");
    // repo bootstrap code for our client
    UserTransaction tx = null;
    NodeRef companySpaceNodeRef = null;
    try {
        tx = transactionService.getUserTransaction();
        tx.begin();
        authenticationContext.setSystemUserAsCurrentUser();
        // get and setup the initial store ref and root path from config
        StoreRef storeRef = Repository.getStoreRef(servletContext);
        // get root path
        String rootPath = Application.getRootPath(servletContext);
        // Extract company space id and store it in the Application object
        companySpaceNodeRef = Repository.getCompanyRoot(nodeService, searchService, namespaceService, storeRef, rootPath);
        Application.setCompanyRootId(companySpaceNodeRef.getId());
        // commit the transaction
        tx.commit();
    } catch (Throwable e) {
        // rollback the transaction
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
        }
        logger.error("Failed to initialise ", e);
        throw new AlfrescoRuntimeException("Failed to initialise ", e);
    } finally {
        try {
            authenticationContext.clearCurrentSecurityContext();
        } catch (Exception ex) {
        }
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) StoreRef(org.alfresco.service.cmr.repository.StoreRef) AuthenticationContext(org.alfresco.repo.security.authentication.AuthenticationContext) TransactionService(org.alfresco.service.transaction.TransactionService) NodeService(org.alfresco.service.cmr.repository.NodeService) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) WebApplicationContext(org.springframework.web.context.WebApplicationContext) NodeRef(org.alfresco.service.cmr.repository.NodeRef) NamespaceService(org.alfresco.service.namespace.NamespaceService) SearchService(org.alfresco.service.cmr.search.SearchService) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) ServiceRegistry(org.alfresco.service.ServiceRegistry)

Example 35 with NodeService

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

NodeService (org.alfresco.service.cmr.repository.NodeService)53 NodeRef (org.alfresco.service.cmr.repository.NodeRef)36 QName (org.alfresco.service.namespace.QName)15 ChildAssociationRef (org.alfresco.service.cmr.repository.ChildAssociationRef)11 ResponseWriter (javax.faces.context.ResponseWriter)10 IOException (java.io.IOException)8 UserTransaction (javax.transaction.UserTransaction)8 ServiceRegistry (org.alfresco.service.ServiceRegistry)8 DictionaryService (org.alfresco.service.cmr.dictionary.DictionaryService)8 Serializable (java.io.Serializable)7 HashMap (java.util.HashMap)7 FileFolderService (org.alfresco.service.cmr.model.FileFolderService)7 PermissionService (org.alfresco.service.cmr.security.PermissionService)7 PersonService (org.alfresco.service.cmr.security.PersonService)7 SearchService (org.alfresco.service.cmr.search.SearchService)6 ArrayList (java.util.ArrayList)5 ResourceBundle (java.util.ResourceBundle)5 FileInfo (org.alfresco.service.cmr.model.FileInfo)5 Path (org.alfresco.service.cmr.repository.Path)5 TransactionService (org.alfresco.service.transaction.TransactionService)5