Search in sources :

Example 1 with ServiceRegistry

use of org.alfresco.service.ServiceRegistry in project acs-community-packaging by Alfresco.

the class FileUploadBean method uploadFile.

/**
 * Ajax method to upload file content. A multi-part form is required as the input.
 *
 * "return-page" = javascript to execute on return from the upload request
 * "currentPath" = the cm:name based server path to upload the content into
 * and the file item content.
 *
 * @throws Exception
 */
@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML)
public void uploadFile() throws Exception {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext externalContext = fc.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setHeaderEncoding("UTF-8");
    List<FileItem> fileItems = upload.parseRequest(request);
    FileUploadBean bean = new FileUploadBean();
    String currentPath = null;
    String filename = null;
    String returnPage = null;
    File file = null;
    for (FileItem item : fileItems) {
        if (item.isFormField() && item.getFieldName().equals("return-page")) {
            returnPage = item.getString();
        } else if (item.isFormField() && item.getFieldName().equals("currentPath")) {
            currentPath = URLDecoder.decode(item.getString());
        } else {
            filename = FilenameUtils.getName(item.getName());
            file = TempFileProvider.createTempFile("alfresco", ".upload");
            item.write(file);
        }
    }
    if (logger.isDebugEnabled())
        logger.debug("Ajax file upload request: " + filename + " to path: " + currentPath + " return page: " + returnPage);
    try {
        if (file != null && currentPath != null && currentPath.length() != 0) {
            NodeRef containerRef = pathToNodeRef(fc, currentPath);
            if (containerRef != null) {
                // Guess the mimetype
                String mimetype = Repository.getMimeTypeForFileName(fc, filename);
                // Now guess the encoding
                String encoding = "UTF-8";
                InputStream is = null;
                try {
                    is = new BufferedInputStream(new FileInputStream(file));
                    encoding = Repository.guessEncoding(fc, is, mimetype);
                } catch (Throwable e) {
                    // Bad as it is, it's not terminal
                    logger.error("Failed to guess character encoding of file: " + file, e);
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (Throwable e) {
                        }
                    }
                }
                // Try and extract metadata from the file
                ContentReader cr = new FileContentReader(file);
                cr.setMimetype(mimetype);
                // create properties for content type
                String author = null;
                String title = null;
                String description = null;
                Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>(5, 1.0f);
                if (Repository.extractMetadata(fc, cr, contentProps)) {
                    author = (String) (contentProps.get(ContentModel.PROP_AUTHOR));
                    title = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_TITLE));
                    description = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_DESCRIPTION));
                }
                // default the title to the file name if not set
                if (title == null) {
                    title = filename;
                }
                ServiceRegistry services = Repository.getServiceRegistry(fc);
                FileInfo fileInfo = services.getFileFolderService().create(containerRef, filename, ContentModel.TYPE_CONTENT);
                NodeRef fileNodeRef = fileInfo.getNodeRef();
                // set the author aspect
                if (author != null) {
                    Map<QName, Serializable> authorProps = new HashMap<QName, Serializable>(1, 1.0f);
                    authorProps.put(ContentModel.PROP_AUTHOR, author);
                    services.getNodeService().addAspect(fileNodeRef, ContentModel.ASPECT_AUTHOR, authorProps);
                }
                // apply the titled aspect - title and description
                Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>(2, 1.0f);
                titledProps.put(ContentModel.PROP_TITLE, title);
                titledProps.put(ContentModel.PROP_DESCRIPTION, description);
                services.getNodeService().addAspect(fileNodeRef, ContentModel.ASPECT_TITLED, titledProps);
                // get a writer for the content and put the file
                ContentWriter writer = services.getContentService().getWriter(fileNodeRef, ContentModel.PROP_CONTENT, true);
                writer.setMimetype(mimetype);
                writer.setEncoding(encoding);
                writer.putContent(file);
            }
        }
    } catch (Exception e) {
        returnPage = returnPage.replace("${UPLOAD_ERROR}", e.getMessage());
    } finally {
        if (file != null) {
            logger.debug("delete temporary file:" + file.getPath());
            // Delete the temporary file
            file.delete();
        }
    }
    Document result = XMLUtil.newDocument();
    Element htmlEl = result.createElement("html");
    result.appendChild(htmlEl);
    Element bodyEl = result.createElement("body");
    htmlEl.appendChild(bodyEl);
    Element scriptEl = result.createElement("script");
    bodyEl.appendChild(scriptEl);
    scriptEl.setAttribute("type", "text/javascript");
    Node scriptText = result.createTextNode(returnPage);
    scriptEl.appendChild(scriptText);
    if (logger.isDebugEnabled()) {
        logger.debug("File upload request complete.");
    }
    ResponseWriter out = fc.getResponseWriter();
    XMLUtil.print(result, out);
}
Also used : FacesContext(javax.faces.context.FacesContext) Serializable(java.io.Serializable) HashMap(java.util.HashMap) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) HttpServletRequest(javax.servlet.http.HttpServletRequest) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileContentReader(org.alfresco.repo.content.filestore.FileContentReader) FileInfo(org.alfresco.service.cmr.model.FileInfo) BufferedInputStream(java.io.BufferedInputStream) ExternalContext(javax.faces.context.ExternalContext) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) QName(org.alfresco.service.namespace.QName) FileContentReader(org.alfresco.repo.content.filestore.FileContentReader) ContentReader(org.alfresco.service.cmr.repository.ContentReader) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileInputStream(java.io.FileInputStream) FileItem(org.apache.commons.fileupload.FileItem) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) ResponseWriter(javax.faces.context.ResponseWriter) ServiceRegistry(org.alfresco.service.ServiceRegistry) File(java.io.File)

Example 2 with ServiceRegistry

use of org.alfresco.service.ServiceRegistry in project acs-community-packaging by Alfresco.

the class TemplateMailHelperBean method notifyUser.

/**
 * Send an email notification to the specified User authority
 *
 * @param person     Person node representing the user
 * @param node       Node they are invited too
 * @param from       From text message
 * @param roleText   The role display label for the user invite notification
 */
public void notifyUser(NodeRef person, NodeRef node, final String from, String roleText) {
    final String to = (String) this.getNodeService().getProperty(person, ContentModel.PROP_EMAIL);
    if (to != null && to.length() != 0) {
        String body = this.body;
        if (this.usingTemplate != null) {
            FacesContext fc = FacesContext.getCurrentInstance();
            // use template service to format the email
            NodeRef templateRef = new NodeRef(Repository.getStoreRef(), this.usingTemplate);
            ServiceRegistry services = Repository.getServiceRegistry(fc);
            Map<String, Object> model = DefaultModelHelper.buildDefaultModel(services, Application.getCurrentUser(fc), templateRef);
            model.put("role", roleText);
            model.put("space", node);
            // object to allow client urls to be generated in emails
            model.put("url", new BaseTemplateContentServlet.URLHelper(fc));
            model.put("msg", new I18NMessageMethod());
            model.put("document", node);
            if (nodeService.getType(node).equals(ContentModel.TYPE_CONTENT)) {
                NodeRef parentNodeRef = nodeService.getParentAssocs(node).get(0).getParentRef();
                if (parentNodeRef == null) {
                    throw new IllegalArgumentException("Parent folder doesn't exists for node: " + node);
                }
                model.put("space", parentNodeRef);
            }
            model.put("shareUrl", UrlUtil.getShareUrl(services.getSysAdminParams()));
            body = services.getTemplateService().processTemplate("freemarker", templateRef.toString(), model);
        }
        this.finalBody = body;
        MimeMessagePreparator mailPreparer = new MimeMessagePreparator() {

            public void prepare(MimeMessage mimeMessage) throws MessagingException {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setTo(to);
                message.setSubject(subject);
                message.setText(finalBody, MailActionExecuter.isHTML(finalBody));
                message.setFrom(from);
            }
        };
        if (logger.isDebugEnabled())
            logger.debug("Sending notification email to: " + to + "\n...with subject:\n" + subject + "\n...with body:\n" + body);
        try {
            // Send the message
            this.getMailSender().send(mailPreparer);
        } catch (Throwable e) {
            // don't stop the action but let admins know email is not getting sent
            logger.error("Failed to send email to " + to, e);
        }
    }
}
Also used : FacesContext(javax.faces.context.FacesContext) MimeMessagePreparator(org.springframework.mail.javamail.MimeMessagePreparator) I18NMessageMethod(org.alfresco.repo.template.I18NMessageMethod) BaseTemplateContentServlet(org.alfresco.web.app.servlet.BaseTemplateContentServlet) MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper) NodeRef(org.alfresco.service.cmr.repository.NodeRef) MimeMessage(javax.mail.internet.MimeMessage) ServiceRegistry(org.alfresco.service.ServiceRegistry)

Example 3 with ServiceRegistry

use of org.alfresco.service.ServiceRegistry in project acs-community-packaging by Alfresco.

the class WorkspaceClipboardItem method paste.

/**
 * @see org.alfresco.web.bean.clipboard.ClipboardItem#paste(javax.faces.context.FacesContext, java.lang.String, int)
 */
public boolean paste(final FacesContext fc, String viewId, final int action) {
    final ServiceRegistry serviceRegistry = getServiceRegistry();
    final RetryingTransactionHelper retryingTransactionHelper = serviceRegistry.getTransactionService().getRetryingTransactionHelper();
    if (super.canCopyToViewId(viewId) || WORKSPACE_PASTE_VIEW_ID.equals(viewId) || FORUMS_PASTE_VIEW_ID.equals(viewId) || FORUM_PASTE_VIEW_ID.equals(viewId)) {
        NavigationBean navigator = (NavigationBean) FacesHelper.getManagedBean(fc, NavigationBean.BEAN_NAME);
        final NodeRef destRef = new NodeRef(Repository.getStoreRef(), navigator.getCurrentNodeId());
        final DictionaryService dd = serviceRegistry.getDictionaryService();
        final NodeService nodeService = serviceRegistry.getNodeService();
        final FileFolderService fileFolderService = serviceRegistry.getFileFolderService();
        final CopyService copyService = serviceRegistry.getCopyService();
        final MultilingualContentService multilingualContentService = serviceRegistry.getMultilingualContentService();
        final boolean isPrimaryParent;
        final ChildAssociationRef assocRef;
        if (getParent() == null) {
            assocRef = nodeService.getPrimaryParent(getNodeRef());
            isPrimaryParent = true;
        } else {
            NodeRef parentNodeRef = getParent();
            List<ChildAssociationRef> assocList = nodeService.getParentAssocs(getNodeRef());
            ChildAssociationRef foundRef = null;
            if (assocList != null) {
                for (ChildAssociationRef assocListEntry : assocList) {
                    if (parentNodeRef.equals(assocListEntry.getParentRef())) {
                        foundRef = assocListEntry;
                        break;
                    }
                }
            }
            assocRef = foundRef;
            isPrimaryParent = parentNodeRef.equals(nodeService.getPrimaryParent(getNodeRef()).getParentRef());
        }
        // initial name to attempt the copy of the item with
        String name = getName();
        String translationPrefix = "";
        if (action == UIClipboardShelfItem.ACTION_PASTE_LINK) {
            // copy as link was specifically requested by the user
            String linkTo = Application.getMessage(fc, MSG_LINK_TO);
            name = linkTo + ' ' + name;
        }
        // Loop until we find a target name that doesn't exist
        for (; ; ) {
            try {
                final String currentTranslationPrefix = translationPrefix;
                final String currentName = name;
                // attempt each copy/paste in its own transaction
                retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Void>() {

                    public Void execute() throws Throwable {
                        if (getMode() == ClipboardStatus.COPY) {
                            if (action == UIClipboardShelfItem.ACTION_PASTE_LINK) {
                                // LINK operation
                                if (logger.isDebugEnabled())
                                    logger.debug("Attempting to link node ID: " + getNodeRef() + " into node: " + destRef.toString());
                                // create the node using the nodeService (can only use FileFolderService for content)
                                if (checkExists(currentName + LINK_NODE_EXTENSION, destRef) == false) {
                                    Map<QName, Serializable> props = new HashMap<QName, Serializable>(2, 1.0f);
                                    String newName = currentName + LINK_NODE_EXTENSION;
                                    props.put(ContentModel.PROP_NAME, newName);
                                    props.put(ContentModel.PROP_LINK_DESTINATION, getNodeRef());
                                    if (dd.isSubClass(getType(), ContentModel.TYPE_CONTENT)) {
                                        // create File Link node
                                        ChildAssociationRef childRef = nodeService.createNode(destRef, ContentModel.ASSOC_CONTAINS, QName.createQName(assocRef.getQName().getNamespaceURI(), newName), ApplicationModel.TYPE_FILELINK, props);
                                        // apply the titled aspect - title and description
                                        Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>(2, 1.0f);
                                        titledProps.put(ContentModel.PROP_TITLE, currentName);
                                        titledProps.put(ContentModel.PROP_DESCRIPTION, currentName);
                                        nodeService.addAspect(childRef.getChildRef(), ContentModel.ASPECT_TITLED, titledProps);
                                    } else {
                                        // create Folder link node
                                        ChildAssociationRef childRef = nodeService.createNode(destRef, ContentModel.ASSOC_CONTAINS, assocRef.getQName(), ApplicationModel.TYPE_FOLDERLINK, props);
                                        // apply the uifacets aspect - icon, title and description props
                                        Map<QName, Serializable> uiFacetsProps = new HashMap<QName, Serializable>(4, 1.0f);
                                        uiFacetsProps.put(ApplicationModel.PROP_ICON, "space-icon-link");
                                        uiFacetsProps.put(ContentModel.PROP_TITLE, currentName);
                                        uiFacetsProps.put(ContentModel.PROP_DESCRIPTION, currentName);
                                        nodeService.addAspect(childRef.getChildRef(), ApplicationModel.ASPECT_UIFACETS, uiFacetsProps);
                                    }
                                }
                            } else {
                                // COPY operation
                                if (logger.isDebugEnabled())
                                    logger.debug("Attempting to copy node: " + getNodeRef() + " into node ID: " + destRef.toString());
                                // first check that we are not attempting to copy a duplicate into the same parent
                                if (destRef.equals(assocRef.getParentRef()) && currentName.equals(getName())) {
                                    // manually change the name if this occurs
                                    throw new FileExistsException(destRef, currentName);
                                }
                                if (dd.isSubClass(getType(), ContentModel.TYPE_CONTENT) || dd.isSubClass(getType(), ContentModel.TYPE_FOLDER)) {
                                    // copy the file/folder
                                    fileFolderService.copy(getNodeRef(), destRef, currentName);
                                } else if (dd.isSubClass(getType(), ContentModel.TYPE_MULTILINGUAL_CONTAINER)) {
                                    // copy the mlContainer and its translations
                                    multilingualContentService.copyTranslationContainer(getNodeRef(), destRef, currentTranslationPrefix);
                                } else {
                                    // copy the node
                                    if (checkExists(currentName, destRef) == false) {
                                        copyService.copyAndRename(getNodeRef(), destRef, ContentModel.ASSOC_CONTAINS, assocRef.getQName(), true);
                                    }
                                }
                            }
                        } else {
                            // MOVE operation
                            if (logger.isDebugEnabled())
                                logger.debug("Attempting to move node: " + getNodeRef() + " into node ID: " + destRef.toString());
                            if (dd.isSubClass(getType(), ContentModel.TYPE_CONTENT) || dd.isSubClass(getType(), ContentModel.TYPE_FOLDER)) {
                                // move the file/folder
                                fileFolderService.moveFrom(getNodeRef(), getParent(), destRef, currentName);
                            } else if (dd.isSubClass(getType(), ContentModel.TYPE_MULTILINGUAL_CONTAINER)) {
                                // copy the mlContainer and its translations
                                multilingualContentService.moveTranslationContainer(getNodeRef(), destRef);
                            } else {
                                if (isPrimaryParent) {
                                    // move the node
                                    nodeService.moveNode(getNodeRef(), destRef, ContentModel.ASSOC_CONTAINS, assocRef.getQName());
                                } else {
                                    nodeService.removeChild(getParent(), getNodeRef());
                                    nodeService.addChild(destRef, getNodeRef(), assocRef.getTypeQName(), assocRef.getQName());
                                }
                            }
                        }
                        return null;
                    }
                });
                // We got here without error, so no need to loop with a new name
                break;
            } catch (FileExistsException fileExistsErr) {
                // If mode is COPY, have another go around the loop with a new name
                if (getMode() == ClipboardStatus.COPY) {
                    String copyOf = Application.getMessage(fc, MSG_COPY_OF);
                    name = copyOf + ' ' + name;
                    translationPrefix = copyOf + ' ' + translationPrefix;
                } else {
                    // we should not rename an item when it is being moved - so exit
                    throw fileExistsErr;
                }
            }
        }
        return true;
    } else {
        return false;
    }
}
Also used : MultilingualContentService(org.alfresco.service.cmr.ml.MultilingualContentService) Serializable(java.io.Serializable) RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) QName(org.alfresco.service.namespace.QName) NodeService(org.alfresco.service.cmr.repository.NodeService) FileFolderService(org.alfresco.service.cmr.model.FileFolderService) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) CopyService(org.alfresco.service.cmr.repository.CopyService) NodeRef(org.alfresco.service.cmr.repository.NodeRef) DictionaryService(org.alfresco.service.cmr.dictionary.DictionaryService) NavigationBean(org.alfresco.web.bean.NavigationBean) ServiceRegistry(org.alfresco.service.ServiceRegistry) HashMap(java.util.HashMap) Map(java.util.Map) FileExistsException(org.alfresco.service.cmr.model.FileExistsException)

Example 4 with ServiceRegistry

use of org.alfresco.service.ServiceRegistry in project acs-community-packaging by Alfresco.

the class UIMimeTypeSelector method createList.

/**
 * Creates the list of SelectItem components to represent the list
 * of MIME types the user can select from
 *
 * @return List of SelectItem components
 */
protected List<SelectItem> createList() {
    List<SelectItem> items = new ArrayList<SelectItem>(80);
    ServiceRegistry registry = Repository.getServiceRegistry(FacesContext.getCurrentInstance());
    MimetypeService mimetypeService = registry.getMimetypeService();
    // get the mime type display names
    Map<String, String> mimeTypes = mimetypeService.getDisplaysByMimetype();
    for (String mimeType : mimeTypes.keySet()) {
        items.add(new SelectItem(mimeType, mimeTypes.get(mimeType)));
    }
    // make sure the list is sorted by the values
    QuickSort sorter = new QuickSort(items, "label", true, IDataContainer.SORT_CASEINSENSITIVE);
    sorter.sort();
    return items;
}
Also used : QuickSort(org.alfresco.web.data.QuickSort) SelectItem(javax.faces.model.SelectItem) MimetypeService(org.alfresco.service.cmr.repository.MimetypeService) ArrayList(java.util.ArrayList) ServiceRegistry(org.alfresco.service.ServiceRegistry)

Example 5 with ServiceRegistry

use of org.alfresco.service.ServiceRegistry in project acs-community-packaging by Alfresco.

the class AdvancedSearchDialog method getContentFormats.

/**
 * @return Returns a list of content formats to allow the user to select from
 */
public List<SelectItem> getContentFormats() {
    if ((properties.getContentFormats() == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance()))) {
        properties.setContentFormats(new ArrayList<SelectItem>(80));
        ServiceRegistry registry = Repository.getServiceRegistry(FacesContext.getCurrentInstance());
        MimetypeService mimetypeService = registry.getMimetypeService();
        // get the mime type display names
        Map<String, String> mimeTypes = mimetypeService.getDisplaysByMimetype();
        for (String mimeType : mimeTypes.keySet()) {
            properties.getContentFormats().add(new SelectItem(mimeType, mimeTypes.get(mimeType)));
        }
        // make sure the list is sorted by the values
        QuickSort sorter = new QuickSort(properties.getContentFormats(), "label", true, IDataContainer.SORT_CASEINSENSITIVE);
        sorter.sort();
        // add the "All Formats" constant marker at the top of the list (default selection)
        properties.getContentFormats().add(0, new SelectItem("", Application.getMessage(FacesContext.getCurrentInstance(), MSG_ALL_FORMATS)));
    }
    return properties.getContentFormats();
}
Also used : QuickSort(org.alfresco.web.data.QuickSort) SelectItem(javax.faces.model.SelectItem) MimetypeService(org.alfresco.service.cmr.repository.MimetypeService) ServiceRegistry(org.alfresco.service.ServiceRegistry)

Aggregations

ServiceRegistry (org.alfresco.service.ServiceRegistry)32 NodeRef (org.alfresco.service.cmr.repository.NodeRef)17 NodeService (org.alfresco.service.cmr.repository.NodeService)8 FacesContext (javax.faces.context.FacesContext)7 MimetypeService (org.alfresco.service.cmr.repository.MimetypeService)6 QName (org.alfresco.service.namespace.QName)6 StringTokenizer (java.util.StringTokenizer)5 Serializable (java.io.Serializable)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 SelectItem (javax.faces.model.SelectItem)4 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)4 ContentService (org.alfresco.service.cmr.repository.ContentService)4 ContentWriter (org.alfresco.service.cmr.repository.ContentWriter)4 StoreRef (org.alfresco.service.cmr.repository.StoreRef)4 PermissionService (org.alfresco.service.cmr.security.PermissionService)4 TransactionService (org.alfresco.service.transaction.TransactionService)4 QuickSort (org.alfresco.web.data.QuickSort)4 SocketException (java.net.SocketException)3 ArrayList (java.util.ArrayList)3