Search in sources :

Example 36 with FacesContext

use of javax.faces.context.FacesContext in project acs-community-packaging by Alfresco.

the class ImportDialog method getFileName.

/**
 * @return Returns the name of the file
 */
public String getFileName() {
    // try and retrieve the file and filename from the file upload bean
    // representing the file we previously uploaded.
    FacesContext ctx = FacesContext.getCurrentInstance();
    FileUploadBean fileBean = (FileUploadBean) ctx.getExternalContext().getSessionMap().get(FileUploadBean.FILE_UPLOAD_BEAN_NAME);
    if (fileBean != null) {
        this.fileName = fileBean.getFileName();
        this.file = fileBean.getFile();
    }
    return this.fileName;
}
Also used : FacesContext(javax.faces.context.FacesContext) FileUploadBean(org.alfresco.web.bean.FileUploadBean)

Example 37 with FacesContext

use of javax.faces.context.FacesContext in project acs-community-packaging by Alfresco.

the class CategoryBrowserPluginBean method retrieveChildren.

/**
 * Retrieves the child folders for the noderef given in the 'noderef' parameter and caches the nodes against the area
 * in the 'area' parameter.
 */
public void retrieveChildren() throws IOException {
    FacesContext context = FacesContext.getCurrentInstance();
    ResponseWriter out = context.getResponseWriter();
    UserTransaction tx = null;
    try {
        tx = Repository.getUserTransaction(context, true);
        tx.begin();
        Map params = context.getExternalContext().getRequestParameterMap();
        String nodeRefStr = (String) params.get("nodeRef");
        // work out which list to cache the nodes in
        Map<String, TreeNode> currentNodes = getNodesMap();
        if (nodeRefStr != null && currentNodes != null) {
            // get the given node's details
            NodeRef parentNodeRef = new NodeRef(nodeRefStr);
            TreeNode parentNode = currentNodes.get(parentNodeRef.toString());
            parentNode.setExpanded(true);
            if (logger.isDebugEnabled())
                logger.debug("retrieving children for noderef: " + parentNodeRef);
            // remove any existing children as the latest ones will be added
            // below
            parentNode.removeChildren();
            // get all the child folder objects for the parent
            List<ChildAssociationRef> childRefs = this.getNodeService().getChildAssocs(parentNodeRef, ContentModel.ASSOC_SUBCATEGORIES, RegexQNamePattern.MATCH_ALL);
            List<TreeNode> sortedNodes = new ArrayList<TreeNode>();
            for (ChildAssociationRef ref : childRefs) {
                NodeRef nodeRef = ref.getChildRef();
                logger.debug("retrieving child : " + nodeRef);
                // build the XML representation of the child node
                TreeNode childNode = createTreeNode(nodeRef);
                parentNode.addChild(childNode);
                currentNodes.put(childNode.getNodeRef(), childNode);
                sortedNodes.add(childNode);
            }
            // order the tree nodes by the tree label
            if (sortedNodes.size() > 1) {
                QuickSort sorter = new QuickSort(sortedNodes, "name", true, IDataContainer.SORT_CASEINSENSITIVE);
                sorter.sort();
            }
            // generate the XML representation
            StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><nodes>");
            for (TreeNode childNode : sortedNodes) {
                xml.append(childNode.toXML());
            }
            xml.append("</nodes>");
            // send the generated XML back to the tree
            out.write(xml.toString());
            if (logger.isDebugEnabled())
                logger.debug("returning XML: " + xml.toString());
        }
        // commit the transaction
        tx.commit();
    } catch (Throwable err) {
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) FacesContext(javax.faces.context.FacesContext) ArrayList(java.util.ArrayList) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) IOException(java.io.IOException) NodeRef(org.alfresco.service.cmr.repository.NodeRef) QuickSort(org.alfresco.web.data.QuickSort) ResponseWriter(javax.faces.context.ResponseWriter) TreeNode(org.alfresco.web.ui.repo.component.UITree.TreeNode) HashMap(java.util.HashMap) Map(java.util.Map)

Example 38 with FacesContext

use of javax.faces.context.FacesContext 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 39 with FacesContext

use of javax.faces.context.FacesContext in project acs-community-packaging by Alfresco.

the class MySpacesBean method createSpace.

@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML)
public void createSpace() throws Exception {
    FacesContext fc = FacesContext.getCurrentInstance();
    ResponseWriter out = fc.getResponseWriter();
    Map<String, String> requestMap = fc.getExternalContext().getRequestParameterMap();
    String path = (String) requestMap.get("path");
    String name = (String) requestMap.get("name");
    String title = (String) requestMap.get("title");
    String description = (String) requestMap.get("description");
    if (logger.isDebugEnabled())
        logger.debug("MySpacesBean.createSpace() path=" + path + " name=" + name + " title=" + title + " description=" + description);
    try {
        if (path != null && name != null) {
            NodeRef containerRef = FileUploadBean.pathToNodeRef(fc, path);
            if (containerRef != null) {
                NodeService nodeService = Repository.getServiceRegistry(fc).getNodeService();
                FileFolderService ffService = Repository.getServiceRegistry(fc).getFileFolderService();
                FileInfo folderInfo = ffService.create(containerRef, name, ContentModel.TYPE_FOLDER);
                if (logger.isDebugEnabled())
                    logger.debug("Created new folder: " + folderInfo.getNodeRef().toString());
                // apply the uifacets aspect - icon, title and description properties
                Map<QName, Serializable> uiFacetsProps = new HashMap<QName, Serializable>(4, 1.0f);
                uiFacetsProps.put(ApplicationModel.PROP_ICON, CreateSpaceWizard.DEFAULT_SPACE_ICON_NAME);
                uiFacetsProps.put(ContentModel.PROP_TITLE, title);
                uiFacetsProps.put(ContentModel.PROP_DESCRIPTION, description);
                nodeService.addAspect(folderInfo.getNodeRef(), ApplicationModel.ASPECT_UIFACETS, uiFacetsProps);
                out.write("OK: " + folderInfo.getNodeRef().toString());
            }
        }
    } catch (FileExistsException ferr) {
        out.write("ERROR: A file with that name already exists.");
    } catch (Throwable err) {
        out.write("ERROR: " + err.getMessage());
    }
}
Also used : FacesContext(javax.faces.context.FacesContext) Serializable(java.io.Serializable) HashMap(java.util.HashMap) QName(org.alfresco.service.namespace.QName) NodeService(org.alfresco.service.cmr.repository.NodeService) FileFolderService(org.alfresco.service.cmr.model.FileFolderService) NodeRef(org.alfresco.service.cmr.repository.NodeRef) FileInfo(org.alfresco.service.cmr.model.FileInfo) ResponseWriter(javax.faces.context.ResponseWriter) FileExistsException(org.alfresco.service.cmr.model.FileExistsException)

Example 40 with FacesContext

use of javax.faces.context.FacesContext in project acs-community-packaging by Alfresco.

the class NavigatorPluginBean method nodeCollapsed.

/**
 * Sets the state of the node given in the 'nodeRef' parameter to collapsed
 */
public void nodeCollapsed() throws IOException {
    FacesContext context = FacesContext.getCurrentInstance();
    ResponseWriter out = context.getResponseWriter();
    Map params = context.getExternalContext().getRequestParameterMap();
    String nodeRefStr = (String) params.get("nodeRef");
    String area = (String) params.get("area");
    if (logger.isDebugEnabled())
        logger.debug("nodeCollapsed: area = " + area + ", nodeRef = " + nodeRefStr);
    // work out which list to cache the nodes in
    Map<String, TreeNode> currentNodes = getNodesMapForArea(area);
    if (nodeRefStr != null && currentNodes != null) {
        TreeNode treeNode = currentNodes.get(nodeRefStr);
        if (treeNode != null) {
            treeNode.setExpanded(false);
            // we need to return something for the client to be happy!
            out.write("<ok/>");
            if (logger.isDebugEnabled())
                logger.debug("Set node " + treeNode + " to collapsed state");
        }
    }
}
Also used : FacesContext(javax.faces.context.FacesContext) ResponseWriter(javax.faces.context.ResponseWriter) TreeNode(org.alfresco.web.ui.repo.component.UITree.TreeNode) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

FacesContext (javax.faces.context.FacesContext)361 NodeRef (org.alfresco.service.cmr.repository.NodeRef)61 Node (org.alfresco.web.bean.repository.Node)44 UserTransaction (javax.transaction.UserTransaction)43 ArrayList (java.util.ArrayList)33 HashMap (java.util.HashMap)28 IOException (java.io.IOException)27 InvalidNodeRefException (org.alfresco.service.cmr.repository.InvalidNodeRefException)27 ExternalContext (javax.faces.context.ExternalContext)26 SelectItem (javax.faces.model.SelectItem)26 QName (org.alfresco.service.namespace.QName)25 FacesMessage (javax.faces.application.FacesMessage)24 ChildAssociationRef (org.alfresco.service.cmr.repository.ChildAssociationRef)22 Map (java.util.Map)21 ResourceBundle (java.util.ResourceBundle)20 HttpServletResponse (javax.servlet.http.HttpServletResponse)19 MapNode (org.alfresco.web.bean.repository.MapNode)18 UIViewRoot (javax.faces.component.UIViewRoot)17 HttpServletRequest (javax.servlet.http.HttpServletRequest)16 Serializable (java.io.Serializable)15