Search in sources :

Example 61 with ContentWriter

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

the class TestCMIS method testVersioningUsingUpdateProperties.

/**
 * Test that updating properties does automatically create a new version if
 * <b>autoVersion</b>, <b>initialVersion</b> and <b>autoVersionOnUpdateProps</b> are TRUE
 */
@Test
public void testVersioningUsingUpdateProperties() throws Exception {
    final TestNetwork network1 = getTestFixture().getRandomNetwork();
    String username = "user" + System.currentTimeMillis();
    PersonInfo personInfo = new PersonInfo(username, username, username, "password", null, null, null, null, null, null, null);
    TestPerson person1 = network1.createUser(personInfo);
    String person1Id = person1.getId();
    final String siteName = "site" + System.currentTimeMillis();
    TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef>() {

        @Override
        public NodeRef doWork() throws Exception {
            SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PRIVATE);
            TestSite site = repoService.createSite(null, siteInfo);
            String name = GUID.generate();
            NodeRef folderNodeRef = repoService.createFolder(site.getContainerNodeRef("documentLibrary"), name);
            return folderNodeRef;
        }
    }, person1Id, network1.getId());
    // Create a document...
    publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));
    CmisSession cmisSession = publicApiClient.createPublicApiCMISSession(Binding.atom, "1.0", AlfrescoObjectFactoryImpl.class.getName());
    AlfrescoFolder docLibrary = (AlfrescoFolder) cmisSession.getObjectByPath("/Sites/" + siteName + "/documentLibrary");
    Map<String, String> properties = new HashMap<String, String>();
    {
        properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
        properties.put(PropertyIds.NAME, "mydoc-" + GUID.generate() + ".txt");
    }
    ContentStreamImpl fileContent = new ContentStreamImpl();
    {
        ContentWriter writer = new FileContentWriter(TempFileProvider.createTempFile(GUID.generate(), ".txt"));
        writer.putContent("Ipsum and so on");
        ContentReader reader = writer.getReader();
        fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        fileContent.setStream(reader.getContentInputStream());
    }
    AlfrescoDocument doc = (AlfrescoDocument) docLibrary.createDocument(properties, fileContent, VersioningState.MAJOR);
    String versionLabel = doc.getVersionLabel();
    String nodeRefStr = doc.getPropertyValue(NodeRefProperty.NodeRefPropertyId).toString();
    final NodeRef nodeRef = new NodeRef(nodeRefStr);
    TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef>() {

        @Override
        public NodeRef doWork() throws Exception {
            // ensure autoversioning is enabled
            assertTrue(nodeService.hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE));
            Map<QName, Serializable> versionProperties = new HashMap<QName, Serializable>();
            versionProperties.put(ContentModel.PROP_AUTO_VERSION, true);
            versionProperties.put(ContentModel.PROP_INITIAL_VERSION, true);
            versionProperties.put(ContentModel.PROP_AUTO_VERSION_PROPS, true);
            nodeService.addProperties(nodeRef, versionProperties);
            return null;
        }
    }, person1Id, network1.getId());
    // ...and check that updating its properties creates a new minor version...
    properties = new HashMap<String, String>();
    {
        properties.put(PropertyIds.DESCRIPTION, GUID.generate());
    }
    AlfrescoDocument doc1 = (AlfrescoDocument) doc.getObjectOfLatestVersion(false).updateProperties(properties);
    doc1 = (AlfrescoDocument) doc.getObjectOfLatestVersion(false);
    String versionLabel1 = doc1.getVersionLabel();
    assertTrue(Double.parseDouble(versionLabel) < Double.parseDouble(versionLabel1));
    // ...and check that updating its content creates a new version
    fileContent = new ContentStreamImpl();
    {
        ContentWriter writer = new FileContentWriter(TempFileProvider.createTempFile(GUID.generate(), ".txt"));
        writer.putContent("Ipsum and so on and so on");
        ContentReader reader = writer.getReader();
        fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        fileContent.setStream(reader.getContentInputStream());
    }
    doc1.setContentStream(fileContent, true);
    AlfrescoDocument doc2 = (AlfrescoDocument) doc1.getObjectOfLatestVersion(false);
    String versionLabel2 = doc2.getVersionLabel();
    assertTrue("Set content stream should create a new version automatically", Double.parseDouble(versionLabel1) < Double.parseDouble(versionLabel2));
    assertTrue("It should be latest version : " + versionLabel2, doc2.isLatestVersion());
    doc2.deleteContentStream();
    AlfrescoDocument doc3 = (AlfrescoDocument) doc2.getObjectOfLatestVersion(false);
    String versionLabel3 = doc3.getVersionLabel();
    assertTrue("Delete content stream should create a new version automatically", Double.parseDouble(versionLabel1) < Double.parseDouble(versionLabel3));
    assertTrue("It should be latest version : " + versionLabel3, doc3.isLatestVersion());
}
Also used : ContentStreamImpl(org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl) AlfrescoDocument(org.alfresco.cmis.client.AlfrescoDocument) Serializable(java.io.Serializable) HashMap(java.util.HashMap) NodeRef(org.alfresco.service.cmr.repository.NodeRef) SiteInformation(org.alfresco.rest.api.tests.RepoService.SiteInformation) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) AlfrescoObjectFactoryImpl(org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl) CmisSession(org.alfresco.rest.api.tests.client.PublicApiClient.CmisSession) TestSite(org.alfresco.rest.api.tests.RepoService.TestSite) QName(org.alfresco.service.namespace.QName) AlfrescoFolder(org.alfresco.cmis.client.AlfrescoFolder) FileContentWriter(org.alfresco.repo.content.filestore.FileContentWriter) ContentReader(org.alfresco.service.cmr.repository.ContentReader) CmisUpdateConflictException(org.apache.chemistry.opencmis.commons.exceptions.CmisUpdateConflictException) CmisConstraintException(org.apache.chemistry.opencmis.commons.exceptions.CmisConstraintException) CmisPermissionDeniedException(org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException) CmisInvalidArgumentException(org.apache.chemistry.opencmis.commons.exceptions.CmisInvalidArgumentException) PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) CmisObjectNotFoundException(org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) FileContentWriter(org.alfresco.repo.content.filestore.FileContentWriter) TestNetwork(org.alfresco.rest.api.tests.RepoService.TestNetwork) TestPerson(org.alfresco.rest.api.tests.RepoService.TestPerson) Map(java.util.Map) MimetypeMap(org.alfresco.repo.content.MimetypeMap) HashMap(java.util.HashMap) VersionableAspectTest(org.alfresco.repo.version.VersionableAspectTest) Test(org.junit.Test)

Example 62 with ContentWriter

use of org.alfresco.service.cmr.repository.ContentWriter in project records-management by Alfresco.

the class RecordsManagementAuditServiceImpl method fileAuditTrailAsRecord.

/**
 * {@inheritDoc}
 */
@Override
public NodeRef fileAuditTrailAsRecord(RecordsManagementAuditQueryParameters params, NodeRef destination, ReportFormat format) {
    ParameterCheck.mandatory("params", params);
    ParameterCheck.mandatory("destination", destination);
    // NOTE: the underlying RM services will check all the remaining pre-conditions
    NodeRef record = null;
    // get the audit trail for the provided parameters
    File auditTrail = this.getAuditTrailFile(params, format);
    if (logger.isDebugEnabled()) {
        logger.debug("Filing audit trail in file " + auditTrail.getAbsolutePath() + " as a record in record folder: " + destination);
    }
    try {
        Map<QName, Serializable> properties = new HashMap<QName, Serializable>(1);
        properties.put(ContentModel.PROP_NAME, auditTrail.getName());
        // file the audit log as an undeclared record
        record = this.nodeService.createNode(destination, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, QName.createValidLocalName(auditTrail.getName())), ContentModel.TYPE_CONTENT, properties).getChildRef();
        // Set the content
        ContentWriter writer = this.contentService.getWriter(record, ContentModel.PROP_CONTENT, true);
        writer.setMimetype(format == ReportFormat.HTML ? MimetypeMap.MIMETYPE_HTML : MimetypeMap.MIMETYPE_JSON);
        writer.setEncoding("UTF-8");
        writer.putContent(auditTrail);
    } finally {
        if (logger.isDebugEnabled()) {
            logger.debug("Audit trail report saved to temporary file: " + auditTrail.getAbsolutePath());
        } else {
            auditTrail.delete();
        }
    }
    return record;
}
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) File(java.io.File)

Example 63 with ContentWriter

use of org.alfresco.service.cmr.repository.ContentWriter in project records-management by Alfresco.

the class ApplyDodCertModelFixesGet method writeCustomContentModel.

private void writeCustomContentModel(M2Model deserializedModel) {
    ContentWriter writer = this.contentService.getWriter(RM_CUSTOM_MODEL_NODE_REF, ContentModel.TYPE_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_XML);
    writer.setEncoding("UTF-8");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    deserializedModel.toXML(baos);
    String updatedModelXml;
    try {
        updatedModelXml = baos.toString("UTF-8");
        writer.putContent(updatedModelXml);
    // putContent closes all resources.
    // so we don't have to.
    } catch (UnsupportedEncodingException uex) {
        throw new AlfrescoRuntimeException("Exception when writing custom model xml.", uex);
    }
}
Also used : ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 64 with ContentWriter

use of org.alfresco.service.cmr.repository.ContentWriter in project records-management by Alfresco.

the class FilePlanComponentsApiUtils method writeContent.

/**
 * Write content to file
 *
 * @param nodeRef  the node to write the content to
 * @param fileName  the name of the file (used for guessing the file's mimetype)
 * @param stream  the input stream to write
 * @param guessEncoding  whether to guess stream encoding
 */
public 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) ContentIOException(org.alfresco.service.cmr.repository.ContentIOException) IOException(java.io.IOException) NodeLockedException(org.alfresco.service.cmr.lock.NodeLockedException) ContentIOException(org.alfresco.service.cmr.repository.ContentIOException) ContentQuotaException(org.alfresco.service.cmr.usage.ContentQuotaException)

Example 65 with ContentWriter

use of org.alfresco.service.cmr.repository.ContentWriter in project records-management by Alfresco.

the class CommonRMTestUtils method createRecord.

/**
 * Helper method to create a record in a record folder.
 *
 * @param recordFolder      record folder
 * @param name              name of record
 * @param properties        properties of the record
 * @param content           content of the record
 * @return {@link NodeRef}  record node reference
 */
public NodeRef createRecord(NodeRef recordFolder, String name, Map<QName, Serializable> properties, String mimetype, InputStream content) {
    // Create the record
    NodeRef record = createRecordImpl(recordFolder, name, properties);
    // Set the content
    ContentWriter writer = contentService.getWriter(record, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(mimetype);
    writer.setEncoding("UTF-8");
    writer.putContent(content);
    return record;
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter)

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