Search in sources :

Example 16 with ContentWriter

use of org.alfresco.service.cmr.repository.ContentWriter in project alfresco-remote-api by Alfresco.

the class NodesImpl method writeContent.

private void writeContent(NodeRef nodeRef, String fileName, InputStream stream, boolean guessEncoding) {
    try {
        ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
        String mimeType = mimetypeService.guessMimetype(fileName);
        if ((mimeType != null) && (!mimeType.equals(MimetypeMap.MIMETYPE_BINARY))) {
            // quick/weak guess based on file extension
            writer.setMimetype(mimeType);
        } else {
            // stronger guess based on file stream
            writer.guessMimetype(fileName);
        }
        InputStream is = null;
        if (guessEncoding) {
            is = new BufferedInputStream(stream);
            is.mark(1024);
            writer.setEncoding(guessEncoding(is, mimeType, false));
            try {
                is.reset();
            } catch (IOException ioe) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Failed to reset stream after trying to guess encoding: " + ioe.getMessage());
                }
            }
        } else {
            is = stream;
        }
        writer.putContent(is);
    } catch (ContentQuotaException cqe) {
        throw new InsufficientStorageException();
    } catch (ContentLimitViolationException clv) {
        throw new RequestEntityTooLargeException(clv.getMessage());
    } catch (ContentIOException cioe) {
        if (cioe.getCause() instanceof NodeLockedException) {
            throw (NodeLockedException) cioe.getCause();
        }
        throw cioe;
    }
}
Also used : ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) InsufficientStorageException(org.alfresco.rest.framework.core.exceptions.InsufficientStorageException) ContentLimitViolationException(org.alfresco.repo.content.ContentLimitViolationException) RequestEntityTooLargeException(org.alfresco.rest.framework.core.exceptions.RequestEntityTooLargeException) IOException(java.io.IOException) ContentIOException(org.alfresco.service.cmr.repository.ContentIOException) NodeLockedException(org.alfresco.service.cmr.lock.NodeLockedException) ContentIOException(org.alfresco.service.cmr.repository.ContentIOException) ContentQuotaException(org.alfresco.service.cmr.usage.ContentQuotaException)

Example 17 with ContentWriter

use of org.alfresco.service.cmr.repository.ContentWriter in project alfresco-remote-api by Alfresco.

the class MoveMethod method copyContentOnly.

private void copyContentOnly(FileInfo sourceFileInfo, FileInfo destFileInfo, FileFolderService fileFolderService) throws WebDAVServerException {
    ContentService contentService = getContentService();
    ContentReader reader = contentService.getReader(sourceFileInfo.getNodeRef(), ContentModel.PROP_CONTENT);
    if (reader == null) {
        // There is no content for the node if it is a folder
        if (!sourceFileInfo.isFolder()) {
            // Non-folders should have content available.
            logger.error("Unable to get ContentReader for source node " + sourceFileInfo.getNodeRef());
            throw new WebDAVServerException(HttpServletResponse.SC_NOT_FOUND);
        }
    } else {
        ContentWriter contentWriter = contentService.getWriter(destFileInfo.getNodeRef(), ContentModel.PROP_CONTENT, true);
        contentWriter.putContent(reader);
    }
}
Also used : ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) ContentReader(org.alfresco.service.cmr.repository.ContentReader) ContentService(org.alfresco.service.cmr.repository.ContentService)

Example 18 with ContentWriter

use of org.alfresco.service.cmr.repository.ContentWriter in project alfresco-remote-api by Alfresco.

the class NodeContentGet method execute.

/**
 * @param req WebScriptRequest
 * @param res WebScriptResponse
 * @throws IOException
 */
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
    ContentReader textReader = null;
    Exception transformException = null;
    String nodeIDString = req.getParameter("nodeId");
    if (nodeIDString == null) {
        throw new WebScriptException("nodeID parameter is required for GetNodeContent");
    }
    long nodeId = Long.valueOf(nodeIDString).longValue();
    String propertyQName = req.getParameter("propertyQName");
    QName propertyName = null;
    if (propertyQName == null) {
        propertyName = ContentModel.PROP_CONTENT;
    } else {
        propertyName = QName.createQName(propertyQName);
    }
    Pair<Long, NodeRef> pair = nodeDAO.getNodePair(nodeId);
    if (pair == null) {
        // If the node does not exists we treat it as if it has no content
        // We could be trying to update the content of a node in the index that has been deleted.
        res.setStatus(HttpStatus.SC_NO_CONTENT);
        return;
    }
    NodeRef nodeRef = pair.getSecond();
    // check If-Modified-Since header and set Last-Modified header as appropriate
    Date modified = (Date) nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIED);
    // May be null - if so treat as just changed
    if (modified == null) {
        modified = new Date();
    }
    long modifiedSince = -1;
    String modifiedSinceStr = req.getHeader("If-Modified-Since");
    if (modifiedSinceStr != null) {
        try {
            modifiedSince = dateFormat.parse(modifiedSinceStr).getTime();
        } catch (Throwable e) {
            if (logger.isWarnEnabled()) {
                logger.warn("Browser sent badly-formatted If-Modified-Since header: " + modifiedSinceStr);
            }
        }
        if (modifiedSince > 0L) {
            // round the date to the ignore millisecond value which is not supplied by header
            long modDate = (modified.getTime() / 1000L) * 1000L;
            if (modDate <= modifiedSince) {
                res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }
        }
    }
    ContentReader reader = contentService.getReader(nodeRef, propertyName);
    if (reader == null) {
        res.setStatus(HttpStatus.SC_NO_CONTENT);
        return;
    }
    try {
        // get the transformer
        TransformationOptions options = new TransformationOptions();
        options.setUse("index");
        options.setSourceNodeRef(nodeRef);
        transformerDebug.pushAvailable(reader.getContentUrl(), reader.getMimetype(), MimetypeMap.MIMETYPE_TEXT_PLAIN, options);
        long sourceSize = reader.getSize();
        List<ContentTransformer> transformers = contentService.getActiveTransformers(reader.getMimetype(), sourceSize, MimetypeMap.MIMETYPE_TEXT_PLAIN, options);
        transformerDebug.availableTransformers(transformers, sourceSize, options, "SolrIndexer");
        if (transformers.isEmpty()) {
            res.setHeader(TRANSFORM_STATUS_HEADER, "noTransform");
            res.setStatus(HttpStatus.SC_NO_CONTENT);
            return;
        }
        ContentTransformer transformer = transformers.get(0);
        // Perform transformation catering for mimetype AND encoding
        ContentWriter writer = contentService.getTempWriter();
        writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        // Expect transformers to produce UTF-8
        writer.setEncoding("UTF-8");
        try {
            long start = System.currentTimeMillis();
            transformer.transform(reader, writer, options);
            long transformDuration = System.currentTimeMillis() - start;
            res.setHeader(TRANSFORM_DURATION_HEADER, String.valueOf(transformDuration));
        } catch (ContentIOException | UnsupportedTransformationException e) {
            transformException = e;
        }
        if (transformException == null) {
            // point the reader to the new-written content
            textReader = writer.getReader();
            // Check that the reader is a view onto something concrete
            if (textReader == null || !textReader.exists()) {
                transformException = new ContentIOException("The transformation did not write any content, yet: \n" + "   transformer:     " + transformer + "\n" + "   temp writer:     " + writer);
            }
        }
        if (transformException != null) {
            res.setHeader(TRANSFORM_STATUS_HEADER, "transformFailed");
            res.setHeader(TRANSFORM_EXCEPTION_HEADER, transformException.getMessage());
            res.setStatus(HttpStatus.SC_NO_CONTENT);
        } else {
            res.setStatus(HttpStatus.SC_OK);
            streamContentImpl(req, res, textReader, null, null, false, modified, String.valueOf(modified.getTime()), null, null);
        }
    } finally {
        transformerDebug.popAvailable();
    }
}
Also used : UnsupportedTransformationException(org.alfresco.repo.content.transform.UnsupportedTransformationException) QName(org.alfresco.service.namespace.QName) ContentReader(org.alfresco.service.cmr.repository.ContentReader) ContentIOException(org.alfresco.service.cmr.repository.ContentIOException) IOException(java.io.IOException) UnsupportedTransformationException(org.alfresco.repo.content.transform.UnsupportedTransformationException) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) Date(java.util.Date) ContentIOException(org.alfresco.service.cmr.repository.ContentIOException) TransformationOptions(org.alfresco.service.cmr.repository.TransformationOptions) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) ContentTransformer(org.alfresco.repo.content.transform.ContentTransformer)

Example 19 with ContentWriter

use of org.alfresco.service.cmr.repository.ContentWriter in project alfresco-remote-api by Alfresco.

the class CommentsPost method addComment.

/**
 * add the comment from json to given nodeRef
 *
 * @param nodeRef
 * @param json
 * @return
 */
private NodeRef addComment(NodeRef nodeRef, JSONObject json) {
    // fetch the parent to add the node to
    NodeRef commentsFolder = getOrCreateCommentsFolder(nodeRef);
    // get a unique name
    String name = getUniqueChildName("comment");
    // create the comment
    NodeRef commentNodeRef = nodeService.createNode(commentsFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, QName.createValidLocalName(name)), ForumModel.TYPE_POST).getChildRef();
    // fetch the title required to create a comment
    String title = getOrNull(json, JSON_KEY_TITLE);
    HashMap<QName, Serializable> props = new HashMap<QName, Serializable>(1, 1.0f);
    props.put(ContentModel.PROP_TITLE, title != null ? title : "");
    nodeService.addProperties(commentNodeRef, props);
    ContentWriter writer = contentService.getWriter(commentNodeRef, ContentModel.PROP_CONTENT, true);
    // fetch the content of a comment
    String contentString = getOrNull(json, JSON_KEY_CONTENT);
    writer.setMimetype(MimetypeMap.MIMETYPE_HTML);
    writer.putContent(contentString);
    return commentNodeRef;
}
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)

Example 20 with ContentWriter

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

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