Search in sources :

Example 41 with ContentWriter

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

the class ImportDialog method addFileToRepository.

/**
 * Adds the uploaded ACP/ZIP file to the repository
 *
 * @param context Faces context
 * @return NodeRef representing the ACP/ZIP file in the repository
 */
private NodeRef addFileToRepository(FacesContext context) {
    // set the name for the new node
    Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>(1);
    contentProps.put(ContentModel.PROP_NAME, this.fileName);
    // create the node to represent the zip file
    String assocName = QName.createValidLocalName(this.fileName);
    ChildAssociationRef assocRef = this.getNodeService().createNode(this.browseBean.getActionSpace().getNodeRef(), ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, assocName), ContentModel.TYPE_CONTENT, contentProps);
    NodeRef acpNodeRef = assocRef.getChildRef();
    // apply the titled aspect to behave in the web client
    String mimetype = this.getMimetypeService().guessMimetype(this.fileName);
    Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>(2, 1.0f);
    titledProps.put(ContentModel.PROP_TITLE, this.fileName);
    titledProps.put(ContentModel.PROP_DESCRIPTION, MimetypeMap.MIMETYPE_ACP.equals(mimetype) ? Application.getMessage(context, "import_acp_description") : Application.getMessage(context, "import_zip_description"));
    this.getNodeService().addAspect(acpNodeRef, ContentModel.ASPECT_TITLED, titledProps);
    // add the content to the node
    ContentWriter writer = this.getContentService().getWriter(acpNodeRef, ContentModel.PROP_CONTENT, true);
    writer.setEncoding("UTF-8");
    writer.setMimetype(mimetype);
    writer.putContent(this.file);
    return acpNodeRef;
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) Serializable(java.io.Serializable) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) HashMap(java.util.HashMap) QName(org.alfresco.service.namespace.QName) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef)

Example 42 with ContentWriter

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

the class ContentUpdateBean method updateFile.

/**
 * Ajax method to update file content. A multi-part form is required as the input.
 *
 * "return-page" = javascript to execute on return from the upload request
 * "nodeRef" = the nodeRef of the item to update the content of
 *
 * @throws Exception
 */
@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML)
public void updateFile() 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);
    String strNodeRef = null;
    String strFilename = null;
    String strReturnPage = null;
    File file = null;
    for (FileItem item : fileItems) {
        if (item.isFormField() && item.getFieldName().equals("return-page")) {
            strReturnPage = item.getString();
        } else if (item.isFormField() && item.getFieldName().equals("nodeRef")) {
            strNodeRef = item.getString();
        } else {
            strFilename = FilenameUtils.getName(item.getName());
            file = TempFileProvider.createTempFile("alfresco", ".upload");
            item.write(file);
        }
    }
    if (logger.isDebugEnabled())
        logger.debug("Ajax content update request: " + strFilename + " to nodeRef: " + strNodeRef + " return page: " + strReturnPage);
    try {
        if (file != null && strNodeRef != null && strNodeRef.length() != 0) {
            NodeRef nodeRef = new NodeRef(strNodeRef);
            if (nodeRef != null) {
                ServiceRegistry services = Repository.getServiceRegistry(fc);
                // get a writer for the content and put the file
                ContentWriter writer = services.getContentService().getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
                writer.putContent(file);
            }
        }
    } catch (Exception e) {
        strReturnPage = strReturnPage.replace("${UPLOAD_ERROR}", e.getMessage());
    }
    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(strReturnPage);
    scriptEl.appendChild(scriptText);
    if (logger.isDebugEnabled())
        logger.debug("Content update request complete.");
    ResponseWriter out = fc.getResponseWriter();
    XMLUtil.print(result, out);
}
Also used : FacesContext(javax.faces.context.FacesContext) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) HttpServletRequest(javax.servlet.http.HttpServletRequest) FileItem(org.apache.commons.fileupload.FileItem) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ResponseWriter(javax.faces.context.ResponseWriter) ExternalContext(javax.faces.context.ExternalContext) ServiceRegistry(org.alfresco.service.ServiceRegistry) File(java.io.File)

Example 43 with ContentWriter

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

the class CheckinCheckoutDialog method checkinFileOK.

/**
 * Action called upon completion of the Check In file page
 */
public String checkinFileOK(final FacesContext context, String outcome) {
    // NOTE: for checkin the document node _is_ the working document!
    final Node node = property.getDocument();
    if (node != null && (property.getCopyLocation().equals(CCProperties.COPYLOCATION_CURRENT) || (this.getFileName() != null && !this.getFileName().equals("")))) {
        try {
            RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(FacesContext.getCurrentInstance());
            RetryingTransactionCallback<Object> callback = new RetryingTransactionCallback<Object>() {

                public Object execute() throws Throwable {
                    if (logger.isDebugEnabled())
                        logger.debug("Trying to checkin content node Id: " + node.getId());
                    // we can either checkin the content from the current working copy node
                    // which would have been previously updated by the user
                    String contentUrl;
                    if (property.getCopyLocation().equals(CCProperties.COPYLOCATION_CURRENT)) {
                        ContentData contentData = (ContentData) node.getProperties().get(ContentModel.PROP_CONTENT);
                        contentUrl = (contentData == null ? null : contentData.getContentUrl());
                    } else // or specify a specific file as the content instead
                    {
                        // add the content to an anonymous but permanent writer location
                        // we can then retrieve the URL to the content to to be set on the node during checkin
                        ContentWriter writer = property.getContentService().getWriter(node.getNodeRef(), ContentModel.PROP_CONTENT, true);
                        // also update the mime type in case a different type of file is uploaded
                        String mimeType = Repository.getMimeTypeForFileName(context, property.getFileName());
                        writer.setMimetype(mimeType);
                        writer.putContent(property.getFile());
                        contentUrl = writer.getContentUrl();
                    }
                    if (contentUrl == null || contentUrl.length() == 0) {
                        throw new IllegalStateException("Content URL is empty for specified working copy content node!");
                    }
                    // add version history text to props
                    Map<String, Serializable> props = new HashMap<String, Serializable>(1, 1.0f);
                    props.put(Version.PROP_DESCRIPTION, property.getVersionNotes());
                    // set the flag for minor or major change
                    if (property.getMinorChange()) {
                        props.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
                    } else {
                        props.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
                    }
                    // perform the checkin
                    property.getVersionOperationsService().checkin(node.getNodeRef(), props, contentUrl, property.getKeepCheckedOut());
                    return null;
                }
            };
            txnHelper.doInTransaction(callback);
            outcome = AlfrescoNavigationHandler.CLOSE_DIALOG_OUTCOME;
            if (property.isWorkflowAction() == false) {
                outcome = outcome + AlfrescoNavigationHandler.OUTCOME_SEPARATOR + "browse";
            }
            // clear action context
            property.setDocument(null);
            resetState();
        } catch (Throwable err) {
            Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), MSG_ERROR_CHECKIN) + err.getMessage(), err);
            ReportedException.throwIfNecessary(err);
        }
    } else {
        logger.warn("WARNING: checkinFileOK called without a current Document!");
    }
    return outcome;
}
Also used : Serializable(java.io.Serializable) RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) HashMap(java.util.HashMap) Node(org.alfresco.web.bean.repository.Node) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) ContentData(org.alfresco.service.cmr.repository.ContentData) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback)

Example 44 with ContentWriter

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

the class CheckinCheckoutDialog method editInline.

/**
 * Action handler called to set the content of a node from an inline editing page.
 */
public String editInline(FacesContext context, String outcome) {
    final Node node = property.getDocument();
    if (node != null) {
        try {
            if (logger.isDebugEnabled())
                logger.debug("Trying to update content node Id: " + node.getId());
            // get an updating writer that we can use to modify the content on the current node
            ContentWriter writer = property.getContentService().getWriter(node.getNodeRef(), ContentModel.PROP_CONTENT, true);
            writer.putContent(property.getEditorOutput());
            // clean up and clear action context
            resetState();
            property.setDocument(null);
            property.setDocumentContent(null);
            property.setEditorOutput(null);
        } catch (Throwable err) {
            Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), MSG_ERROR_UPDATE) + err.getMessage());
            outcome = null;
            ReportedException.throwIfNecessary(err);
        }
    } else {
        logger.warn("WARNING: editInlineOK called without a current Document!");
    }
    return outcome;
}
Also used : ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) Node(org.alfresco.web.bean.repository.Node)

Example 45 with ContentWriter

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

Aggregations

ContentWriter (org.alfresco.service.cmr.repository.ContentWriter)76 NodeRef (org.alfresco.service.cmr.repository.NodeRef)50 HashMap (java.util.HashMap)31 Serializable (java.io.Serializable)22 QName (org.alfresco.service.namespace.QName)21 ContentReader (org.alfresco.service.cmr.repository.ContentReader)20 Test (org.junit.Test)18 FileContentWriter (org.alfresco.repo.content.filestore.FileContentWriter)14 InputStream (java.io.InputStream)13 AlfrescoDocument (org.alfresco.cmis.client.AlfrescoDocument)13 AlfrescoFolder (org.alfresco.cmis.client.AlfrescoFolder)13 VersionableAspectTest (org.alfresco.repo.version.VersionableAspectTest)13 TestNetwork (org.alfresco.rest.api.tests.RepoService.TestNetwork)13 CmisSession (org.alfresco.rest.api.tests.client.PublicApiClient.CmisSession)13 RequestContext (org.alfresco.rest.api.tests.client.RequestContext)13 ContentStreamImpl (org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl)13 TestPerson (org.alfresco.rest.api.tests.RepoService.TestPerson)12 CmisUpdateConflictException (org.apache.chemistry.opencmis.commons.exceptions.CmisUpdateConflictException)12 PublicApiException (org.alfresco.rest.api.tests.client.PublicApiException)11 CmisConstraintException (org.apache.chemistry.opencmis.commons.exceptions.CmisConstraintException)11