Search in sources :

Example 11 with ContentWriter

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

the class GetMethodRegressionTest method createTestContent.

private void createTestContent(NodeRef parentNode, int documentsAmount) {
    for (int i = 0; i < documentsAmount; i++) {
        String testDocumentName = String.format(TEST_DOCUMENT_NAME_PATTERN, i, System.currentTimeMillis());
        FileInfo testDocument = fileFolderService.create(parentNode, testDocumentName, ContentModel.TYPE_CONTENT);
        ContentWriter writer = fileFolderService.getWriter(testDocument.getNodeRef());
        writer.putContent(String.format(TEXT_DOCUMENT_CONTENT_PATTERN, testDocumentName));
        writer.setMimetype(TEST_MIMETYPE);
        writer.setEncoding(TEST_ENCODING);
    }
}
Also used : ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) FileInfo(org.alfresco.service.cmr.model.FileInfo)

Example 12 with ContentWriter

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

the class UnlockMethodTest method setUpPreconditionForCheckedOutTest.

/**
 * Set up preconditions for unlock a checked out node
 */
protected void setUpPreconditionForCheckedOutTest() throws Exception {
    appContext = ApplicationContextHelper.getApplicationContext(new String[] { "classpath:alfresco/application-context.xml", "classpath:alfresco/web-scripts-application-context.xml", "classpath:alfresco/remote-api-context.xml" });
    // Set the services
    this.cociService = (CheckOutCheckInService) appContext.getBean("checkOutCheckInService");
    this.contentService = (ContentService) appContext.getBean("contentService");
    this.authenticationService = (MutableAuthenticationService) appContext.getBean("authenticationService");
    this.permissionService = (PermissionService) appContext.getBean("permissionService");
    this.transactionService = (TransactionService) appContext.getBean("TransactionService");
    this.nodeService = (NodeService) appContext.getBean("NodeService");
    // Authenticate as system to create initial test data set
    this.authenticationComponent = (AuthenticationComponent) appContext.getBean("authenticationComponent");
    this.authenticationComponent.setSystemUserAsCurrentUser();
    RetryingTransactionCallback<Void> createTestFileCallback = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            // Create the store and get the root node reference
            storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, TEST_STORE_IDENTIFIER);
            if (!nodeService.exists(storeRef)) {
                storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, TEST_STORE_IDENTIFIER);
            }
            rootNodeRef = nodeService.getRootNode(storeRef);
            // Create and authenticate the user
            userName = "webdavUnlockTest" + GUID.generate();
            TestWithUserUtils.createUser(userName, PWD, rootNodeRef, nodeService, authenticationService);
            permissionService.setPermission(rootNodeRef, userName, PermissionService.ALL_PERMISSIONS, true);
            TestWithUserUtils.authenticateUser(userName, PWD, rootNodeRef, authenticationService);
            userNodeRef = TestWithUserUtils.getCurrentUser(authenticationService);
            // create test file in test folder
            folderNodeRef = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("test"), ContentModel.TYPE_FOLDER, Collections.<QName, Serializable>singletonMap(ContentModel.PROP_NAME, "folder")).getChildRef();
            fileNodeRef = nodeService.createNode(folderNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("test"), ContentModel.TYPE_CONTENT, Collections.<QName, Serializable>singletonMap(ContentModel.PROP_NAME, TEST_FILE_NAME)).getChildRef();
            ContentWriter contentWriter = contentService.getWriter(fileNodeRef, ContentModel.PROP_CONTENT, true);
            contentWriter.setMimetype("text/plain");
            contentWriter.setEncoding("UTF-8");
            contentWriter.putContent(CONTENT_1);
            // Check out test file
            fileWorkingCopyNodeRef = cociService.checkout(fileNodeRef);
            assertNotNull(fileWorkingCopyNodeRef);
            assertEquals(userNodeRef, nodeService.getProperty(fileNodeRef, ContentModel.PROP_LOCK_OWNER));
            return null;
        }
    };
    this.transactionService.getRetryingTransactionHelper().doInTransaction(createTestFileCallback);
}
Also used : StoreRef(org.alfresco.service.cmr.repository.StoreRef) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback)

Example 13 with ContentWriter

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

the class PersonServiceTest method addTextContent.

private NodeRef addTextContent(NodeRef folderRef, String name, String textData) {
    Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>();
    contentProps.put(ContentModel.PROP_NAME, name);
    ChildAssociationRef association = nodeService.createNode(folderRef, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name), ContentModel.TYPE_CONTENT, contentProps);
    NodeRef content = association.getChildRef();
    ContentWriter writer = contentService.getWriter(content, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.setEncoding("UTF-8");
    writer.putContent(textData);
    return content;
}
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 14 with ContentWriter

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

the class DownloadRestApiTest method createNodeWithTextContent.

public NodeRef createNodeWithTextContent(NodeRef parentNode, String nodeCmName, QName nodeType, String ownerUserName, String content) {
    NodeRef nodeRef = createNode(parentNode, nodeCmName, nodeType, ownerUserName);
    // If there is any content, add it.
    if (content != null) {
        ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
        writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        writer.setEncoding("UTF-8");
        writer.putContent(content);
    }
    return nodeRef;
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter)

Example 15 with ContentWriter

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

the class PutMethod method executeImpl.

/**
 * Execute the WebDAV request
 *
 * @exception WebDAVServerException
 */
protected void executeImpl() throws WebDAVServerException, Exception {
    if (logger.isDebugEnabled()) {
        String path = getPath();
        String userName = getDAVHelper().getAuthenticationService().getCurrentUserName();
        logger.debug("Put node: \n" + "     user: " + userName + "\n" + "     path: " + path + "\n" + "noContent: " + noContent);
    }
    FileFolderService fileFolderService = getFileFolderService();
    // Get the status for the request path
    LockInfo nodeLockInfo = null;
    try {
        contentNodeInfo = getNodeForPath(getRootNodeRef(), getPath());
        // make sure that we are not trying to use a folder
        if (contentNodeInfo.isFolder()) {
            throw new WebDAVServerException(HttpServletResponse.SC_BAD_REQUEST);
        }
        nodeLockInfo = checkNode(contentNodeInfo);
        // 'Unhide' nodes hidden by us and behave as though we created them
        NodeRef contentNodeRef = contentNodeInfo.getNodeRef();
        if (fileFolderService.isHidden(contentNodeRef) && !getDAVHelper().isRenameShuffle(getPath())) {
            fileFolderService.setHidden(contentNodeRef, false);
            created = true;
        }
    } catch (FileNotFoundException e) {
        // the file doesn't exist - create it
        String[] paths = getDAVHelper().splitPath(getPath());
        try {
            FileInfo parentNodeInfo = getNodeForPath(getRootNodeRef(), paths[0]);
            // create file
            contentNodeInfo = getDAVHelper().createFile(parentNodeInfo, paths[1]);
            created = true;
        } catch (FileNotFoundException ee) {
            // bad path
            throw new WebDAVServerException(HttpServletResponse.SC_CONFLICT);
        } catch (FileExistsException ee) {
            // ALF-7079 fix, retry: it looks like concurrent access (file not found but file exists)
            throw new ConcurrencyFailureException("Concurrent access was detected.", ee);
        }
    }
    String userName = getDAVHelper().getAuthenticationService().getCurrentUserName();
    LockInfo lockInfo = getDAVLockService().getLockInfo(contentNodeInfo.getNodeRef());
    if (lockInfo != null) {
        if (lockInfo.isLocked() && !lockInfo.getOwner().equals(userName)) {
            if (logger.isDebugEnabled()) {
                String path = getPath();
                String owner = lockInfo.getOwner();
                logger.debug("Node locked: path=[" + path + "], owner=[" + owner + "], current user=[" + userName + "]");
            }
            // Indicate that the resource is locked
            throw new WebDAVServerException(WebDAV.WEBDAV_SC_LOCKED);
        }
    }
    // ALF-16808: We disable the versionable aspect if we are overwriting
    // empty content because it's probably part of a compound operation to
    // create a new single version
    boolean disabledVersioning = false;
    try {
        // Disable versioning if we are overwriting an empty file with content
        NodeRef nodeRef = contentNodeInfo.getNodeRef();
        ContentData contentData = (ContentData) getNodeService().getProperty(nodeRef, ContentModel.PROP_CONTENT);
        if ((contentData == null || contentData.getSize() == 0) && getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE)) {
            getDAVHelper().getPolicyBehaviourFilter().disableBehaviour(nodeRef, ContentModel.ASPECT_VERSIONABLE);
            disabledVersioning = true;
        }
        // Access the content
        ContentWriter writer = fileFolderService.getWriter(contentNodeInfo.getNodeRef());
        // set content properties
        writer.guessMimetype(contentNodeInfo.getName());
        writer.guessEncoding();
        // Get the input stream from the request data
        InputStream is = m_request.getInputStream();
        // Write the new data to the content node
        writer.putContent(is);
        // - the node does not have any content (zero length binaries included)
        if (nodeLockInfo != null && nodeLockInfo.isExclusive() && !(ContentData.hasContent(contentData) && contentData.getSize() > 0)) {
            getNodeService().addAspect(contentNodeInfo.getNodeRef(), ContentModel.ASPECT_NO_CONTENT, null);
        }
        // Ask for the document metadata to be extracted
        Action extract = getActionService().createAction(ContentMetadataExtracter.EXECUTOR_NAME);
        if (extract != null) {
            extract.setExecuteAsynchronously(false);
            getActionService().executeAction(extract, contentNodeInfo.getNodeRef());
        }
        // from the original specified in the request, update it.
        if (m_strContentType == null || !m_strContentType.equals(writer.getMimetype())) {
            String oldMimeType = m_strContentType;
            m_strContentType = writer.getMimetype();
            if (logger.isDebugEnabled()) {
                logger.debug("Mimetype originally specified as " + oldMimeType + ", now guessed to be " + m_strContentType);
            }
        }
        // Record the uploaded file's size
        fileSize = writer.getSize();
        // Set the response status, depending if the node existed or not
        m_response.setStatus(created ? HttpServletResponse.SC_CREATED : HttpServletResponse.SC_NO_CONTENT);
    } catch (AccessDeniedException e) {
        throw new WebDAVServerException(HttpServletResponse.SC_FORBIDDEN, e);
    } catch (Throwable e) {
        // we are about to give up
        if (noContent && RetryingTransactionHelper.extractRetryCause(e) == null) {
            // remove the 0 bytes content if save operation failed or was cancelled
            final NodeRef nodeRef = contentNodeInfo.getNodeRef();
            getTransactionService().getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<String>() {

                public String execute() throws Throwable {
                    getNodeService().deleteNode(nodeRef);
                    if (logger.isDebugEnabled()) {
                        logger.debug("Put failed. DELETE  " + getPath());
                    }
                    return null;
                }
            }, false, false);
        }
        throw new WebDAVServerException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    } finally {
        if (disabledVersioning) {
            getDAVHelper().getPolicyBehaviourFilter().enableBehaviour(contentNodeInfo.getNodeRef(), ContentModel.ASPECT_VERSIONABLE);
        }
    }
    postActivity();
}
Also used : Action(org.alfresco.service.cmr.action.Action) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) InputStream(java.io.InputStream) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) FileFolderService(org.alfresco.service.cmr.model.FileFolderService) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) ContentData(org.alfresco.service.cmr.repository.ContentData) FileInfo(org.alfresco.service.cmr.model.FileInfo) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback) ConcurrencyFailureException(org.springframework.dao.ConcurrencyFailureException) FileExistsException(org.alfresco.service.cmr.model.FileExistsException)

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