Search in sources :

Example 36 with NodeService

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

the class UploadContentServlet method doPut.

/**
 * @see javax.servlet.http.HttpServlet#doPut(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    if (logger.isDebugEnabled() == true) {
        String queryString = req.getQueryString();
        logger.debug("Authenticating request to URL: " + req.getRequestURI() + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
    }
    AuthenticationStatus status = servletAuthenticate(req, res, false);
    if (status == AuthenticationStatus.Failure || status == AuthenticationStatus.Guest) {
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }
    // Tokenise the URI
    String uri = req.getRequestURI();
    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();
    // skip servlet name
    t.nextToken();
    // get or calculate the noderef and filename to download as
    NodeRef nodeRef = null;
    String filename = null;
    QName propertyQName = null;
    if (tokenCount == 2) {
        // filename is the only token
        filename = t.nextToken();
    } else if (tokenCount == 4 || tokenCount == 5) {
        // assume 'workspace' or other NodeRef based protocol for remaining URL
        // elements
        StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
        String id = t.nextToken();
        // build noderef from the appropriate URL elements
        nodeRef = new NodeRef(storeRef, id);
        if (tokenCount == 5) {
            // filename is last remaining token
            filename = t.nextToken();
        }
        // get qualified of the property to get content from - default to
        // ContentModel.PROP_CONTENT
        propertyQName = ContentModel.PROP_CONTENT;
        String property = req.getParameter(ARG_PROPERTY);
        if (property != null && property.length() != 0) {
            propertyQName = QName.createQName(property);
        }
    } else {
        logger.debug("Upload URL did not contain all required args: " + uri);
        res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);
        return;
    }
    // get the services we need to retrieve the content
    ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
    ContentService contentService = serviceRegistry.getContentService();
    PermissionService permissionService = serviceRegistry.getPermissionService();
    MimetypeService mimetypeService = serviceRegistry.getMimetypeService();
    NodeService nodeService = serviceRegistry.getNodeService();
    InputStream is = req.getInputStream();
    BufferedInputStream inputStream = new BufferedInputStream(is);
    // Sort out the mimetype
    String mimetype = req.getParameter(ARG_MIMETYPE);
    if (mimetype == null || mimetype.length() == 0) {
        mimetype = MIMETYPE_OCTET_STREAM;
        if (filename != null) {
            MimetypeService mimetypeMap = serviceRegistry.getMimetypeService();
            int extIndex = filename.lastIndexOf('.');
            if (extIndex != -1) {
                String ext = filename.substring(extIndex + 1);
                mimetype = mimetypeService.getMimetype(ext);
            }
        }
    }
    // Get the encoding
    String encoding = req.getParameter(ARG_ENCODING);
    if (encoding == null || encoding.length() == 0) {
        // Get the encoding
        ContentCharsetFinder charsetFinder = mimetypeService.getContentCharsetFinder();
        Charset charset = charsetFinder.getCharset(inputStream, mimetype);
        encoding = charset.name();
    }
    // Get the locale
    Locale locale = I18NUtil.parseLocale(req.getParameter(ARG_LOCALE));
    if (locale == null) {
        locale = I18NUtil.getContentLocale();
        if (nodeRef != null) {
            ContentData contentData = (ContentData) nodeService.getProperty(nodeRef, propertyQName);
            if (contentData != null) {
                locale = contentData.getLocale();
            }
        }
    }
    if (logger.isDebugEnabled()) {
        if (nodeRef != null) {
            logger.debug("Found NodeRef: " + nodeRef.toString());
        }
        logger.debug("For property: " + propertyQName);
        logger.debug("File name: " + filename);
        logger.debug("Mimetype: " + mimetype);
        logger.debug("Encoding: " + encoding);
        logger.debug("Locale: " + locale);
    }
    // Check that the user has the permissions to write the content
    if (permissionService.hasPermission(nodeRef, PermissionService.WRITE_CONTENT) == AccessStatus.DENIED) {
        if (logger.isDebugEnabled() == true) {
            logger.debug("User does not have permissions to wrtie content for NodeRef: " + nodeRef.toString());
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Returning 403 Forbidden error...");
        }
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    // Try and get the content writer
    ContentWriter writer = contentService.getWriter(nodeRef, propertyQName, true);
    if (writer == null) {
        if (logger.isDebugEnabled() == true) {
            logger.debug("Content writer cannot be obtained for NodeRef: " + nodeRef.toString());
        }
        res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);
        return;
    }
    // Set the mimetype, encoding and locale
    writer.setMimetype(mimetype);
    writer.setEncoding(encoding);
    if (locale != null) {
        writer.setLocale(locale);
    }
    // Stream the content into the repository
    writer.putContent(inputStream);
    if (logger.isDebugEnabled() == true) {
        logger.debug("Content details: " + writer.getContentData().toString());
    }
    // Set return status
    res.getWriter().write(writer.getContentData().toString());
    res.flushBuffer();
    if (logger.isDebugEnabled() == true) {
        logger.debug("UploadContentServlet done");
    }
}
Also used : Locale(java.util.Locale) StoreRef(org.alfresco.service.cmr.repository.StoreRef) QName(org.alfresco.service.namespace.QName) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) NodeService(org.alfresco.service.cmr.repository.NodeService) ContentCharsetFinder(org.alfresco.repo.content.encoding.ContentCharsetFinder) Charset(java.nio.charset.Charset) ContentService(org.alfresco.service.cmr.repository.ContentService) PermissionService(org.alfresco.service.cmr.security.PermissionService) NodeRef(org.alfresco.service.cmr.repository.NodeRef) StringTokenizer(java.util.StringTokenizer) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) ContentData(org.alfresco.service.cmr.repository.ContentData) BufferedInputStream(java.io.BufferedInputStream) MimetypeService(org.alfresco.service.cmr.repository.MimetypeService) ServiceRegistry(org.alfresco.service.ServiceRegistry)

Example 37 with NodeService

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

the class CancelWorkflowEvaluator method evaluate.

/**
 * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node)
 */
public boolean evaluate(Node node) {
    boolean result = false;
    FacesContext context = FacesContext.getCurrentInstance();
    // get the task from the node
    WorkflowTask task = (WorkflowTask) node.getProperties().get("workflowTask");
    if (task != null) {
        NodeRef initiator = task.path.instance.initiator;
        if (initiator != null) {
            // find the current username
            User user = Application.getCurrentUser(context);
            String currentUserName = user.getUserName();
            // get the username of the initiator
            NodeService nodeSvc = Repository.getServiceRegistry(context).getNodeService();
            String userName = (String) nodeSvc.getProperty(initiator, ContentModel.PROP_USERNAME);
            // if the current user started the workflow allow the cancel action
            if (currentUserName.equals(userName)) {
                result = true;
            }
        }
    }
    return result;
}
Also used : FacesContext(javax.faces.context.FacesContext) NodeRef(org.alfresco.service.cmr.repository.NodeRef) User(org.alfresco.web.bean.repository.User) NodeService(org.alfresco.service.cmr.repository.NodeService) WorkflowTask(org.alfresco.service.cmr.workflow.WorkflowTask)

Example 38 with NodeService

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

the class Repository method getNamePathEx.

/**
 * Resolve a Path by converting each element into its display NAME attribute.
 * Note: This method resolves path regardless access permissions.
 * Fixes the UI part of the ETWOONE-214 and ETWOONE-238 issues
 *
 * @param path       Path to convert
 * @param separator  Separator to user between path elements
 * @param prefix     To prepend to the path
 *
 * @return Path converted using NAME attribute on each element
 */
public static String getNamePathEx(FacesContext context, final Path path, final NodeRef rootNode, final String separator, final String prefix) {
    String result = null;
    RetryingTransactionHelper transactionHelper = getRetryingTransactionHelper(context);
    transactionHelper.setMaxRetries(1);
    final NodeService runtimeNodeService = (NodeService) FacesContextUtils.getRequiredWebApplicationContext(context).getBean("nodeService");
    result = transactionHelper.doInTransaction(new RetryingTransactionCallback<String>() {

        public String execute() throws Throwable {
            return getNamePath(runtimeNodeService, path, rootNode, separator, prefix);
        }
    });
    return result;
}
Also used : RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback) NodeService(org.alfresco.service.cmr.repository.NodeService)

Example 39 with NodeService

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

the class User method getUserPreferencesRef.

/**
 * Get or create the node used to store user preferences.
 * Utilises the 'configurable' aspect on the Person linked to this user.
 */
synchronized NodeRef getUserPreferencesRef(WebApplicationContext context) {
    final ServiceRegistry registry = (ServiceRegistry) context.getBean("ServiceRegistry");
    final NodeService nodeService = registry.getNodeService();
    final SearchService searchService = registry.getSearchService();
    final NamespaceService namespaceService = registry.getNamespaceService();
    final TransactionService txService = registry.getTransactionService();
    final ConfigurableService configurableService = (ConfigurableService) context.getBean("ConfigurableService");
    RetryingTransactionHelper txnHelper = registry.getTransactionService().getRetryingTransactionHelper();
    return txnHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>() {

        public NodeRef execute() throws Throwable {
            NodeRef prefRef = null;
            NodeRef person = getPerson();
            if (nodeService.hasAspect(person, ApplicationModel.ASPECT_CONFIGURABLE) == false) {
                // if the repository is in read-only mode just return null
                if (txService.isReadOnly()) {
                    return null;
                } else {
                    // create the configuration folder for this Person node
                    configurableService.makeConfigurable(person);
                }
            }
            // target of the assoc is the configurations folder ref
            NodeRef configRef = configurableService.getConfigurationFolder(person);
            if (configRef == null) {
                throw new IllegalStateException("Unable to find associated 'configurations' folder for node: " + person);
            }
            String xpath = NamespaceService.APP_MODEL_PREFIX + ":" + "preferences";
            List<NodeRef> nodes = searchService.selectNodes(configRef, xpath, null, namespaceService, false);
            if (nodes.size() == 1) {
                prefRef = nodes.get(0);
            } else {
                // create the preferences Node for this user (if repo is not read-only)
                if (txService.isReadOnly() == false) {
                    ChildAssociationRef childRef = nodeService.createNode(configRef, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.APP_MODEL_1_0_URI, "preferences"), ContentModel.TYPE_CMOBJECT);
                    prefRef = childRef.getChildRef();
                }
            }
            return prefRef;
        }
    }, txService.isReadOnly());
}
Also used : TransactionService(org.alfresco.service.transaction.TransactionService) RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) NodeService(org.alfresco.service.cmr.repository.NodeService) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) NodeRef(org.alfresco.service.cmr.repository.NodeRef) NamespaceService(org.alfresco.service.namespace.NamespaceService) SearchService(org.alfresco.service.cmr.search.SearchService) List(java.util.List) ServiceRegistry(org.alfresco.service.ServiceRegistry) ConfigurableService(org.alfresco.repo.configuration.ConfigurableService)

Example 40 with NodeService

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

the class NodePathLinkRenderer method buildPathAsSingular.

/**
 * Return the path with the entire path as a single clickable link
 *
 * @param context        FacesContext
 * @param component      UIComponent to get display attribute from
 * @param path           Node Path to use
 *
 * @return the entire path as a single clickable link
 */
private String buildPathAsSingular(FacesContext context, UIComponent component, Path path, boolean showLeaf, boolean disabled) {
    StringBuilder buf = new StringBuilder(512);
    NodeService nodeService = getNodeService(context);
    PermissionService permissionService = getPermissionService(context);
    NodeRef lastElementRef = null;
    int size = (showLeaf ? path.size() : path.size() - 1);
    int lastElementPos = (showLeaf ? path.size() - 1 : path.size() - 2);
    for (int i = 0; i < size; i++) {
        Path.Element element = path.get(i);
        String elementString = null;
        if (element instanceof Path.ChildAssocElement) {
            ChildAssociationRef elementRef = ((Path.ChildAssocElement) element).getRef();
            if (elementRef.getParentRef() != null) {
                String name = null;
                if (permissionService.hasPermission(elementRef.getChildRef(), PermissionService.READ) == AccessStatus.ALLOWED) {
                    // use the name property if we are allowed access to it
                    elementString = nodeService.getProperty(elementRef.getChildRef(), ContentModel.PROP_NAME).toString();
                } else {
                    // revert to using QName if not
                    elementString = elementRef.getQName().getLocalName();
                }
            }
            if (i == lastElementPos) {
                lastElementRef = elementRef.getChildRef();
            }
        } else {
            elementString = element.getElementString();
        }
        if (elementString != null) {
            buf.append("/");
            buf.append(elementString);
        }
    }
    if (disabled == false && lastElementRef != null) {
        return renderPathElement(context, component, lastElementRef, buf.toString());
    } else {
        return buf.toString();
    }
}
Also used : PermissionService(org.alfresco.service.cmr.security.PermissionService) Path(org.alfresco.service.cmr.repository.Path) UINodePath(org.alfresco.web.ui.repo.component.UINodePath) NodeRef(org.alfresco.service.cmr.repository.NodeRef) NodeService(org.alfresco.service.cmr.repository.NodeService) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef)

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