Search in sources :

Example 36 with AlfrescoRuntimeException

use of org.alfresco.error.AlfrescoRuntimeException in project acs-community-packaging by Alfresco.

the class CreateDiscussionDialog method createTopic.

// ------------------------------------------------------------------------------
// Helper methods
/**
 * Creates a topic for the node with the given id
 *
 * @param id The id of the node to discuss
 */
protected void createTopic(final String id) {
    RetryingTransactionCallback<NodeRef> createTopicCallback = new RetryingTransactionCallback<NodeRef>() {

        public NodeRef execute() throws Throwable {
            NodeRef forumNodeRef = null;
            discussingNodeRef = new NodeRef(Repository.getStoreRef(), id);
            if (getNodeService().hasAspect(discussingNodeRef, ForumModel.ASPECT_DISCUSSABLE)) {
                throw new AlfrescoRuntimeException("createDiscussion called for an object that already has a discussion!");
            }
            // Add the discussable aspect
            getNodeService().addAspect(discussingNodeRef, ForumModel.ASPECT_DISCUSSABLE, null);
            // The discussion aspect create the necessary child
            List<ChildAssociationRef> destChildren = getNodeService().getChildAssocs(discussingNodeRef, ForumModel.ASSOC_DISCUSSION, RegexQNamePattern.MATCH_ALL);
            // Take the first one
            if (destChildren.size() == 0) {
                // Drop the aspect and recreate it.  This should not happen, but just in case ...
                getNodeService().removeAspect(discussingNodeRef, ForumModel.ASPECT_DISCUSSABLE);
                getNodeService().addAspect(discussingNodeRef, ForumModel.ASPECT_DISCUSSABLE, null);
                // The discussion aspect create the necessary child
                destChildren = getNodeService().getChildAssocs(discussingNodeRef, ForumModel.ASSOC_DISCUSSION, RegexQNamePattern.MATCH_ALL);
            }
            if (destChildren.size() == 0) {
                throw new AlfrescoRuntimeException("The discussable aspect behaviour is not creating a topic");
            } else {
                // We just take the first one
                ChildAssociationRef discussionAssoc = destChildren.get(0);
                forumNodeRef = discussionAssoc.getChildRef();
            }
            if (logger.isDebugEnabled())
                logger.debug("created forum for content: " + discussingNodeRef.toString());
            return forumNodeRef;
        }
    };
    FacesContext context = FacesContext.getCurrentInstance();
    NodeRef forumNodeRef = null;
    try {
        forumNodeRef = getTransactionService().getRetryingTransactionHelper().doInTransaction(createTopicCallback, false);
    } catch (InvalidNodeRefException refErr) {
        Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] { id }));
        throw new AbortProcessingException("Invalid node reference");
    } catch (Throwable e) {
        Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_GENERIC), e.getMessage()), e);
        ReportedException.throwIfNecessary(e);
    }
    // finally setup the context for the forum we just created
    if (forumNodeRef != null) {
        this.browseBean.clickSpace(forumNodeRef);
    }
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) FacesContext(javax.faces.context.FacesContext) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback) AbortProcessingException(javax.faces.event.AbortProcessingException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) InvalidNodeRefException(org.alfresco.service.cmr.repository.InvalidNodeRefException) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef)

Example 37 with AlfrescoRuntimeException

use of org.alfresco.error.AlfrescoRuntimeException in project acs-community-packaging by Alfresco.

the class WorkflowUtil method reject.

/**
 * Execute the Reject step for the Simple Workflow on a node.
 *
 * @param ref           NodeRef to the node with the workflow
 * @param nodeService   NodeService instance
 * @param copyService   CopyService instance
 *
 * @throws AlfrescoRuntimeException
 */
public static void reject(NodeRef ref, NodeService nodeService, CopyService copyService) throws AlfrescoRuntimeException {
    Node docNode = new Node(ref);
    if (docNode.hasAspect(ApplicationModel.ASPECT_SIMPLE_WORKFLOW) == false) {
        throw new AlfrescoRuntimeException("Cannot reject a node that is not part of a workflow.");
    }
    // get the simple workflow aspect properties
    Map<String, Object> props = docNode.getProperties();
    String rejectStep = (String) props.get(ApplicationModel.PROP_REJECT_STEP.toString());
    Boolean rejectMove = (Boolean) props.get(ApplicationModel.PROP_REJECT_MOVE.toString());
    NodeRef rejectFolder = (NodeRef) props.get(ApplicationModel.PROP_REJECT_FOLDER.toString());
    if (rejectStep == null && rejectMove == null && rejectFolder == null) {
        throw new AlfrescoRuntimeException("The workflow does not have a reject step defined.");
    }
    // first we need to take off the simpleworkflow aspect
    nodeService.removeAspect(ref, ApplicationModel.ASPECT_SIMPLE_WORKFLOW);
    if (rejectMove != null && rejectMove.booleanValue()) {
        // move the document to the specified folder
        String qname = QName.createValidLocalName(docNode.getName());
        nodeService.moveNode(ref, rejectFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, qname));
    } else {
        // copy the document to the specified folder
        String name = docNode.getName();
        String qname = QName.createValidLocalName(name);
        NodeRef newNode = copyService.copy(ref, rejectFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, qname), true);
        // the copy service does not copy the name of the node so we
        // need to update the property on the copied item
        nodeService.setProperty(newNode, ContentModel.PROP_NAME, name);
    }
    if (logger.isDebugEnabled()) {
        String movedCopied = rejectMove ? "moved" : "copied";
        logger.debug("Node has been rejected and " + movedCopied + " to folder with id of " + rejectFolder.getId());
    }
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) Node(org.alfresco.web.bean.repository.Node) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException)

Example 38 with AlfrescoRuntimeException

use of org.alfresco.error.AlfrescoRuntimeException in project acs-community-packaging by Alfresco.

the class WorkflowUtil method approve.

/**
 * Execute the Approve step for the Simple Workflow on a node.
 *
 * @param ref           NodeRef to the node with the workflow
 * @param nodeService   NodeService instance
 * @param copyService   CopyService instance
 *
 * @throws AlfrescoRuntimeException
 */
public static void approve(final NodeRef ref, final NodeService nodeService, final CopyService copyService) throws AlfrescoRuntimeException {
    Node docNode = new Node(ref);
    if (docNode.hasAspect(ApplicationModel.ASPECT_SIMPLE_WORKFLOW) == false) {
        throw new AlfrescoRuntimeException("Cannot approve a node that is not part of a workflow.");
    }
    // get the simple workflow aspect properties
    Map<String, Object> props = docNode.getProperties();
    Boolean approveMove = (Boolean) props.get(ApplicationModel.PROP_APPROVE_MOVE.toString());
    NodeRef approveFolder = (NodeRef) props.get(ApplicationModel.PROP_APPROVE_FOLDER.toString());
    if (approveMove.booleanValue()) {
        // first we need to take off the simpleworkflow aspect
        nodeService.removeAspect(ref, ApplicationModel.ASPECT_SIMPLE_WORKFLOW);
        // move the node to the specified folder
        String qname = QName.createValidLocalName(docNode.getName());
        nodeService.moveNode(ref, approveFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, qname));
    } else {
        // first we need to take off the simpleworkflow aspect
        // NOTE: run as system to allow Consumers to copy an item
        AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>() {

            public String doWork() throws Exception {
                nodeService.removeAspect(ref, ApplicationModel.ASPECT_SIMPLE_WORKFLOW);
                return null;
            }
        }, AuthenticationUtil.getSystemUserName());
        // copy the node to the specified folder
        String name = docNode.getName();
        String qname = QName.createValidLocalName(name);
        NodeRef newNode = copyService.copy(ref, approveFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, qname), true);
        // the copy service does not copy the name of the node so we
        // need to update the property on the copied item
        nodeService.setProperty(newNode, ContentModel.PROP_NAME, name);
    }
    if (logger.isDebugEnabled()) {
        String movedCopied = approveMove ? "moved" : "copied";
        logger.debug("Node has been approved and " + movedCopied + " to folder with id of " + approveFolder.getId());
    }
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) AuthenticationUtil(org.alfresco.repo.security.authentication.AuthenticationUtil) Node(org.alfresco.web.bean.repository.Node) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException)

Example 39 with AlfrescoRuntimeException

use of org.alfresco.error.AlfrescoRuntimeException in project acs-community-packaging by Alfresco.

the class ActionsConfigElement method combine.

/**
 * @see org.springframework.extensions.config.element.ConfigElementAdapter#combine(org.springframework.extensions.config.ConfigElement)
 */
public ConfigElement combine(ConfigElement configElement) {
    ActionsConfigElement newElement = (ActionsConfigElement) configElement;
    ActionsConfigElement combinedElement = new ActionsConfigElement();
    // add the existing action definitions
    combinedElement.actionDefs.putAll(this.actionDefs);
    // overwrite any existing action definitions i.e. don't combine
    combinedElement.actionDefs.putAll(newElement.actionDefs);
    // add the existing action groups
    Map<String, ActionGroup> combinedActionGroups = new HashMap<String, ActionGroup>(this.actionGroups.size());
    try {
        for (ActionGroup group : this.actionGroups.values()) {
            combinedActionGroups.put(group.getId(), (ActionGroup) group.clone());
        }
    } catch (CloneNotSupportedException e) {
        throw new AlfrescoRuntimeException("clone() required on ActionGroup class.", e);
    }
    combinedElement.actionGroups = combinedActionGroups;
    // any new action groups with the same name must be combined
    for (ActionGroup newGroup : newElement.actionGroups.values()) {
        if (combinedElement.actionGroups.containsKey(newGroup.getId())) {
            // there is already a group with this id, combine it with the new one
            ActionGroup combinedGroup = combinedElement.actionGroups.get(newGroup.getId());
            if (newGroup.ShowLink != combinedGroup.ShowLink) {
                combinedGroup.ShowLink = newGroup.ShowLink;
            }
            if (newGroup.Style != null) {
                combinedGroup.Style = newGroup.Style;
            }
            if (newGroup.StyleClass != null) {
                combinedGroup.StyleClass = newGroup.StyleClass;
            }
            // add all the actions from the new group to the combined one
            for (String actionRef : newGroup.getAllActions()) {
                combinedGroup.addAction(actionRef);
            }
            // add all the hidden actions from the new group to the combined one
            for (String actionRef : newGroup.getHiddenActions()) {
                combinedGroup.hideAction(actionRef);
            }
        } else {
            // it's a new group so just add it
            combinedElement.actionGroups.put(newGroup.getId(), newGroup);
        }
    }
    return combinedElement;
}
Also used : HashMap(java.util.HashMap) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException)

Example 40 with AlfrescoRuntimeException

use of org.alfresco.error.AlfrescoRuntimeException in project acs-community-packaging by Alfresco.

the class UploadFileServlet method service.

/**
 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String uploadId = null;
    String returnPage = null;
    final RequestContext requestContext = new ServletRequestContext(request);
    boolean isMultipart = ServletFileUpload.isMultipartContent(requestContext);
    try {
        AuthenticationStatus status = servletAuthenticate(request, response);
        if (status == AuthenticationStatus.Failure) {
            return;
        }
        if (!isMultipart) {
            throw new AlfrescoRuntimeException("This servlet can only be used to handle file upload requests, make" + "sure you have set the enctype attribute on your form to multipart/form-data");
        }
        if (logger.isDebugEnabled())
            logger.debug("Uploading servlet servicing...");
        FacesContext context = FacesContext.getCurrentInstance();
        Map<Object, Object> session = context.getExternalContext().getSessionMap();
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        // ensure that the encoding is handled correctly
        upload.setHeaderEncoding("UTF-8");
        List<FileItem> fileItems = upload.parseRequest(request);
        FileUploadBean bean = new FileUploadBean();
        for (FileItem item : fileItems) {
            if (item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase("return-page")) {
                    returnPage = item.getString();
                } else if (item.getFieldName().equalsIgnoreCase("upload-id")) {
                    uploadId = item.getString();
                }
            } else {
                String filename = item.getName();
                if (filename != null && filename.length() != 0) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Processing uploaded file: " + filename);
                    }
                    // ADB-41: Ignore non-existent files i.e. 0 byte streams.
                    if (allowZeroByteFiles() == true || item.getSize() > 0) {
                        // workaround a bug in IE where the full path is returned
                        // IE is only available for Windows so only check for the Windows path separator
                        filename = FilenameUtils.getName(filename);
                        final File tempFile = TempFileProvider.createTempFile("alfresco", ".upload");
                        item.write(tempFile);
                        bean.setFile(tempFile);
                        bean.setFileName(filename);
                        bean.setFilePath(tempFile.getAbsolutePath());
                        if (logger.isDebugEnabled()) {
                            logger.debug("Temp file: " + tempFile.getAbsolutePath() + " size " + tempFile.length() + " bytes created from upload filename: " + filename);
                        }
                    } else {
                        if (logger.isWarnEnabled())
                            logger.warn("Ignored file '" + filename + "' as there was no content, this is either " + "caused by uploading an empty file or a file path that does not exist on the client.");
                    }
                }
            }
        }
        session.put(FileUploadBean.getKey(uploadId), bean);
        if (bean.getFile() == null && uploadId != null && logger.isWarnEnabled()) {
            logger.warn("no file uploaded for upload id: " + uploadId);
        }
        if (returnPage == null || returnPage.length() == 0) {
            throw new AlfrescoRuntimeException("return-page parameter has not been supplied");
        }
        JSONObject json;
        try {
            json = new JSONObject(returnPage);
            if (json.has("id") && json.has("args")) {
                // finally redirect
                if (logger.isDebugEnabled()) {
                    logger.debug("Sending back javascript response " + returnPage);
                }
                response.setContentType(MimetypeMap.MIMETYPE_HTML);
                response.setCharacterEncoding("utf-8");
                // work-around for WebKit protection against embedded javascript on POST body response
                response.setHeader("X-XSS-Protection", "0");
                final PrintWriter out = response.getWriter();
                out.println("<html><body><script type=\"text/javascript\">");
                out.println("window.parent.upload_complete_helper(");
                out.println("'" + json.getString("id") + "'");
                out.println(", ");
                out.println(json.getJSONObject("args"));
                out.println(");");
                out.println("</script></body></html>");
                out.close();
            }
        } catch (JSONException e) {
            // finally redirect
            if (logger.isDebugEnabled())
                logger.debug("redirecting to: " + returnPage);
            response.sendRedirect(returnPage);
        }
        if (logger.isDebugEnabled())
            logger.debug("upload complete");
    } catch (Throwable error) {
        handleUploadException(request, response, error, returnPage);
    }
}
Also used : FacesContext(javax.faces.context.FacesContext) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) JSONException(org.json.JSONException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) JSONObject(org.json.JSONObject) FileUploadBean(org.alfresco.web.bean.FileUploadBean) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) JSONObject(org.json.JSONObject) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) RequestContext(org.apache.commons.fileupload.RequestContext) File(java.io.File) PrintWriter(java.io.PrintWriter)

Aggregations

AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)197 NodeRef (org.alfresco.service.cmr.repository.NodeRef)79 QName (org.alfresco.service.namespace.QName)39 HashMap (java.util.HashMap)38 IOException (java.io.IOException)32 ArrayList (java.util.ArrayList)31 JSONException (org.json.JSONException)23 ChildAssociationRef (org.alfresco.service.cmr.repository.ChildAssociationRef)22 Serializable (java.io.Serializable)20 M2Model (org.alfresco.repo.dictionary.M2Model)18 JSONObject (org.json.JSONObject)15 Date (java.util.Date)14 Map (java.util.Map)12 FacesContext (javax.faces.context.FacesContext)12 InputStream (java.io.InputStream)10 RetryingTransactionCallback (org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback)10 SiteInfo (org.alfresco.service.cmr.site.SiteInfo)10 JSONArray (org.json.JSONArray)10 List (java.util.List)8 FileNotFoundException (org.alfresco.service.cmr.model.FileNotFoundException)8