org.alfresco.service.cmr.repository.ContentWriter

Here are the examples of the java api class org.alfresco.service.cmr.repository.ContentWriter taken from open source projects.

1. RoutingContentServiceTest#testConcurrentWritesNoTxn()

Project: community-edition
File: RoutingContentServiceTest.java
/**
     * Checks that multiple writes can occur to the same node outside of any transactions.
     * <p>
     * It is only when the streams are closed that the node is updated.
     */
public void testConcurrentWritesNoTxn() throws Exception {
    // ensure that the transaction is ended - ofcourse, we need to force a commit
    txn.commit();
    txn = null;
    ContentWriter writer1 = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    ContentWriter writer2 = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    ContentWriter writer3 = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    writer1.putContent("writer1 wrote this");
    writer2.putContent("writer2 wrote this");
    writer3.putContent("writer3 wrote this");
    // get the content
    ContentReader reader = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    String contentCheck = reader.getContentString();
    assertEquals("Content check failed", "writer3 wrote this", contentCheck);
}

2. RuntimeExecutableContentTransformerTest#testCopyCommand()

Project: community-edition
File: RuntimeExecutableContentTransformerTest.java
public void testCopyCommand() throws Exception {
    String content = "<A><B></B></A>";
    // create the source
    File sourceFile = TempFileProvider.createTempFile(getName() + "_", ".txt");
    ContentWriter tempWriter = new FileContentWriter(sourceFile);
    tempWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    tempWriter.putContent(content);
    ContentReader reader = tempWriter.getReader();
    // create the target
    File targetFile = TempFileProvider.createTempFile(getName() + "_", ".xml");
    ContentWriter writer = new FileContentWriter(targetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_XML);
    // do the transformation
    // no options on the copy
    transformer.transform(reader, writer);
    // make sure that the content was copied over
    ContentReader checkReader = writer.getReader();
    String checkContent = checkReader.getContentString();
    assertEquals("Content not copied", content, checkContent);
}

3. RoutingContentServiceTest#testSimpleNonTempWriter()

Project: community-edition
File: RoutingContentServiceTest.java
/**
     * Check that a valid writer into the content store can be retrieved and used.
     */
public void testSimpleNonTempWriter() throws Exception {
    ContentWriter writer = contentService.getWriter(null, null, false);
    assertNotNull("Writer should not be null", writer);
    assertNotNull("Content URL should not be null", writer.getContentUrl());
    // write some content
    writer.putContent(SOME_CONTENT);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.setEncoding("UTF-16");
    writer.setLocale(Locale.CHINESE);
    // set the content property manually
    nodeService.setProperty(contentNodeRef, ContentModel.PROP_CONTENT, writer.getContentData());
    // get the reader
    ContentReader reader = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertNotNull("Reader should not be null", reader);
    assertNotNull("Content URL should not be null", reader.getContentUrl());
    assertEquals("Content Encoding was not set", "UTF-16", reader.getEncoding());
    assertEquals("Content Locale was not set", Locale.CHINESE, reader.getLocale());
}

4. XmlMetadataExtracterTest#testDITAFileWithoutDoctype()

Project: community-edition
File: XmlMetadataExtracterTest.java
public void testDITAFileWithoutDoctype() throws Exception {
    // Munge the file to skip the doctype
    ContentReader reader = getReader(FILE_DITA_FILE);
    assertTrue(reader.exists());
    String contents = reader.getContentString();
    String noDocType = contents.replaceAll("<!DOCTYPE.*?>", "");
    File tmp = File.createTempFile("alfresco", ".xml");
    tmp.deleteOnExit();
    ContentWriter w = new FileContentWriter(tmp);
    w.setEncoding(reader.getEncoding());
    w.setMimetype(reader.getMimetype());
    w.putContent(noDocType);
    // Now test extraction
    doTestDITAFile(w.getReader());
}

5. FullTest#writeToCacheWithExistingReader()

Project: community-edition
File: FullTest.java
@Test
public void writeToCacheWithExistingReader() {
    ContentWriter oldWriter = store.getWriter(ContentContext.NULL_CONTEXT);
    oldWriter.putContent("Old content for " + getClass().getSimpleName());
    ContentReader existingReader = oldWriter.getReader();
    // Write through the caching content store - cache during the process.
    final String proposedUrl = FileContentStore.createNewFileStoreUrl();
    ContentWriter writer = store.getWriter(new ContentContext(existingReader, proposedUrl));
    final String content = makeContent();
    writer.putContent(content);
    assertEquals("Writer should have correct URL", proposedUrl, writer.getContentUrl());
    assertFalse("Old and new writers must have different URLs", oldWriter.getContentUrl().equals(writer.getContentUrl()));
    ContentReader reader = store.getReader(writer.getContentUrl());
    assertEquals("Reader and writer should have same URLs", writer.getContentUrl(), reader.getContentUrl());
    assertEquals("Reader should get correct content", content, reader.getContentString());
}

6. AbstractWritableContentStoreTest#testStringTruncation()

Project: community-edition
File: AbstractWritableContentStoreTest.java
@Test
public void testStringTruncation() throws Exception {
    String content = "1234567890";
    ContentWriter writer = getWriter();
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    // shorter format i.t.o. bytes used
    writer.setEncoding("UTF-8");
    // write the content
    writer.putContent(content);
    // get a reader - get it in a larger format i.t.o. bytes
    ContentReader reader = writer.getReader();
    String checkContent = reader.getContentString(5);
    assertEquals("Truncated strings don't match", "12345", checkContent);
}

7. CompareMimeTypeEvaluatorTest#testContentPropertyComparisons()

Project: community-edition
File: CompareMimeTypeEvaluatorTest.java
public void testContentPropertyComparisons() {
    ActionConditionImpl condition = new ActionConditionImpl(GUID.generate(), ComparePropertyValueEvaluator.NAME);
    // What happens if you do this and the node has no content set yet !!
    // Add some content to the node reference
    ContentWriter contentWriter = this.contentService.getWriter(this.nodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setEncoding("UTF-8");
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    contentWriter.putContent("This is some test content.");
    // Test matching the mimetype
    condition.setParameterValue(ComparePropertyValueEvaluator.PARAM_VALUE, MimetypeMap.MIMETYPE_TEXT_PLAIN);
    assertTrue(this.evaluator.evaluate(condition, this.nodeRef));
    condition.setParameterValue(ComparePropertyValueEvaluator.PARAM_VALUE, MimetypeMap.MIMETYPE_HTML);
    assertFalse(this.evaluator.evaluate(condition, this.nodeRef));
}

8. FolderEmailMessageHandler#writeSpace()

Project: community-edition
File: FolderEmailMessageHandler.java
/**
     * This method writes space as a content. We need this space because rules doesn't proceed documents with empty content. We need rule processing for command email messages with
     * empty body.
     * 
     * @param nodeRef Reference to the parent node
     */
private void writeSpace(NodeRef nodeRef) {
    if (log.isDebugEnabled()) {
        log.debug("Write space string");
    }
    ContentService contentService = getContentService();
    ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.setEncoding("UTF-8");
    writer.putContent(" ");
}

9. VirtualizationIntegrationTest#createContent()

Project: community-edition
File: VirtualizationIntegrationTest.java
protected ChildAssociationRef createContent(NodeRef parent, final String name, String contentString, String mimeType, String encoding) {
    ChildAssociationRef nodeAssoc = createTypedNode(parent, name, ContentModel.TYPE_CONTENT);
    NodeRef child = nodeAssoc.getChildRef();
    ContentWriter writer = contentService.getWriter(child, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(mimeType);
    writer.setEncoding(encoding);
    writer.putContent(contentString);
    return nodeAssoc;
}

10. VirtualizationIntegrationTest#createContent()

Project: community-edition
File: VirtualizationIntegrationTest.java
protected ChildAssociationRef createContent(NodeRef parent, final String name, InputStream stream, String mimeType, String encoding, QName nodeType) {
    ChildAssociationRef nodeAssoc = createTypedNode(parent, name, nodeType);
    NodeRef child = nodeAssoc.getChildRef();
    ContentWriter writer = contentService.getWriter(child, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(mimeType);
    writer.setEncoding(encoding);
    writer.putContent(stream);
    return nodeAssoc;
}

11. UserUsageTest#addTextContent()

Project: community-edition
File: UserUsageTest.java
private NodeRef addTextContent(NodeRef folderRef, String name, String textData, boolean custom) {
    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), (custom == true ? customType : ContentModel.TYPE_CONTENT), contentProps);
    NodeRef content = association.getChildRef();
    nodesToDelete.add(content);
    ContentWriter writer = contentService.getWriter(content, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.setEncoding("UTF-8");
    writer.putContent(textData);
    return content;
}

12. ThumbnailServiceImplTest#createCorruptedContent()

Project: community-edition
File: ThumbnailServiceImplTest.java
private NodeRef createCorruptedContent(NodeRef parentFolder) throws IOException {
    // The below pdf file has been truncated such that it is identifiable as a PDF but otherwise corrupt.
    File corruptPdfFile = AbstractContentTransformerTest.loadNamedQuickTestFile("quickCorrupt.pdf");
    assertNotNull("Failed to load required test file.", corruptPdfFile);
    Map<QName, Serializable> props = new HashMap<QName, Serializable>();
    props.put(ContentModel.PROP_NAME, "corrupt.pdf");
    NodeRef node = this.secureNodeService.createNode(parentFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "quickCorrupt.pdf"), ContentModel.TYPE_CONTENT, props).getChildRef();
    secureNodeService.setProperty(node, ContentModel.PROP_CONTENT, new ContentData(null, MimetypeMap.MIMETYPE_PDF, 0L, null));
    ContentWriter writer = contentService.getWriter(node, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
    writer.setEncoding("UTF-8");
    writer.putContent(corruptPdfFile);
    return node;
}

13. ThumbnailServiceImplTest#createOriginalContent()

Project: community-edition
File: ThumbnailServiceImplTest.java
/**
     * This method creates a node under the specified folder whose content is
     * taken from the quick file corresponding to the specified MIME type.
     * 
     * @param parentFolder
     * @param mimetype
     * @return
     * @throws IOException
     */
private NodeRef createOriginalContent(NodeRef parentFolder, String mimetype) throws IOException {
    String ext = this.mimetypeMap.getExtension(mimetype);
    File origFile = AbstractContentTransformerTest.loadQuickTestFile(ext);
    Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
    props.put(ContentModel.PROP_NAME, "origional." + ext);
    NodeRef node = this.secureNodeService.createNode(parentFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "original." + ext), ContentModel.TYPE_CONTENT, props).getChildRef();
    ContentWriter writer = this.contentService.getWriter(node, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(mimetype);
    writer.setEncoding("UTF-8");
    writer.putContent(origFile);
    return node;
}

14. RenditionServiceIntegrationTest#createFreeMarkerNode()

Project: community-edition
File: RenditionServiceIntegrationTest.java
private NodeRef createFreeMarkerNode(NodeRef companyHome) {
    NodeRef fmNode = createContentNode(companyHome, "testFreeMarkerNode");
    nodeService.setProperty(fmNode, ContentModel.PROP_CONTENT, new ContentData(null, MimetypeMap.MIMETYPE_TEXT_PLAIN, 0L, null));
    URL url = getClass().getResource(FM_TEMPLATE);
    assertNotNull("The url is null", url);
    File templateFile = new File(url.getFile());
    assertTrue("The template file does not exist", templateFile.exists());
    ContentWriter fmWriter = contentService.getWriter(fmNode, ContentModel.PROP_CONTENT, true);
    fmWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    fmWriter.setEncoding("UTF-8");
    fmWriter.putContent(templateFile);
    return fmNode;
}

15. MultiUserRenditionTest#createPdfDocumentAsCurrentlyAuthenticatedUser()

Project: community-edition
File: MultiUserRenditionTest.java
private NodeRef createPdfDocumentAsCurrentlyAuthenticatedUser(final String nodeName) {
    Map<QName, Serializable> props = new HashMap<QName, Serializable>();
    props.put(ContentModel.PROP_NAME, nodeName);
    NodeRef result = nodeService.createNode(testFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, nodeName), ContentModel.TYPE_CONTENT, props).getChildRef();
    File file = loadQuickPdfFile();
    // Set the content
    ContentWriter writer = contentService.getWriter(result, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
    writer.setEncoding("UTF-8");
    writer.putContent(file);
    return result;
}

16. MessageServiceImplTest#addMessageResource()

Project: community-edition
File: MessageServiceImplTest.java
private void addMessageResource(NodeRef rootNodeRef, String name, InputStream resourceStream) throws Exception {
    Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>();
    contentProps.put(ContentModel.PROP_NAME, name);
    ChildAssociationRef association = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, 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(resourceStream);
    resourceStream.close();
}

17. DictionaryModelTypeTest#createActiveModel()

Project: community-edition
File: DictionaryModelTypeTest.java
private NodeRef createActiveModel(String contentFile) {
    PropertyMap properties = new PropertyMap(1);
    properties.put(ContentModel.PROP_MODEL_ACTIVE, true);
    NodeRef modelNode = this.nodeService.createNode(this.rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(NamespaceService.ALFRESCO_URI, "dictionaryModels"), ContentModel.TYPE_DICTIONARY_MODEL, properties).getChildRef();
    assertNotNull(modelNode);
    ContentWriter contentWriter = this.contentService.getWriter(modelNode, ContentModel.PROP_CONTENT, true);
    contentWriter.setEncoding("UTF-8");
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_XML);
    contentWriter.putContent(Thread.currentThread().getContextClassLoader().getResourceAsStream(contentFile));
    return modelNode;
}

18. GetChildrenCannedQueryTest#createContent()

Project: community-edition
File: GetChildrenCannedQueryTest.java
private NodeRef createContent(NodeRef parentNodeRef, QName childAssocType, String fileName, QName contentType) throws IOException {
    Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
    properties.put(ContentModel.PROP_NAME, fileName);
    properties.put(ContentModel.PROP_TITLE, fileName + " my title");
    properties.put(ContentModel.PROP_DESCRIPTION, fileName + " my description");
    NodeRef nodeRef = nodeService.getChildByName(parentNodeRef, childAssocType, fileName);
    if (nodeRef != null) {
        nodeService.deleteNode(nodeRef);
    }
    nodeRef = nodeService.createNode(parentNodeRef, childAssocType, QName.createQName(fileName), contentType, properties).getChildRef();
    ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(mimetypeService.guessMimetype(fileName));
    writer.putContent("my text content");
    return nodeRef;
}

19. GetChildrenCannedQueryTest#createContent()

Project: community-edition
File: GetChildrenCannedQueryTest.java
private NodeRef createContent(NodeRef parentNodeRef, String fileName, QName contentType) throws IOException {
    Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
    properties.put(ContentModel.PROP_NAME, fileName);
    properties.put(ContentModel.PROP_TITLE, fileName + " my title");
    properties.put(ContentModel.PROP_DESCRIPTION, fileName + " my description");
    NodeRef nodeRef = nodeService.getChildByName(parentNodeRef, ContentModel.ASSOC_CONTAINS, fileName);
    if (nodeRef != null) {
        nodeService.deleteNode(nodeRef);
    }
    nodeRef = nodeService.createNode(parentNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName(fileName), contentType, properties).getChildRef();
    ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(mimetypeService.guessMimetype(fileName));
    writer.putContent("my text content");
    return nodeRef;
}

20. FileFolderServiceImplTest#testAlf6560MimetypeSetting()

Project: community-edition
File: FileFolderServiceImplTest.java
public void testAlf6560MimetypeSetting() throws Exception {
    FileInfo fileInfo = fileFolderService.create(workingRootNodeRef, "Something.html", ContentModel.TYPE_CONTENT);
    NodeRef fileNodeRef = fileInfo.getNodeRef();
    // Write the content but without setting the mimetype
    ContentWriter writer = fileFolderService.getWriter(fileNodeRef);
    writer.putContent("CONTENT");
    ContentReader reader = fileFolderService.getReader(fileNodeRef);
    assertEquals("Mimetype was not automatically set", MimetypeMap.MIMETYPE_HTML, reader.getMimetype());
    // Now ask for encoding too
    writer = fileFolderService.getWriter(fileNodeRef);
    writer.guessEncoding();
    OutputStream out = writer.getContentOutputStream();
    out.write("<html><body>hallå världen</body></html>".getBytes("UnicodeBig"));
    out.close();
    reader = fileFolderService.getReader(fileNodeRef);
    assertEquals("Mimetype was not automatically set", MimetypeMap.MIMETYPE_HTML, reader.getMimetype());
    assertEquals("Encoding was not automatically set", "UTF-16BE", reader.getEncoding());
}

21. RoutingContentServiceTest#testUnknownMimetype()

Project: community-edition
File: RoutingContentServiceTest.java
/**
     * Check that the system is able to handle the uploading of content with an unknown mimetype.
     * The unknown mimetype should be preserved, but treated just like an octet stream.
     */
public void testUnknownMimetype() throws Exception {
    String bogusMimetype = "text/bamboozle";
    // get a writer onto the node
    ContentWriter writer = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(bogusMimetype);
    // write something in
    writer.putContent(SOME_CONTENT);
    // commit the transaction to ensure that it goes in OK
    txn.commit();
    // so far, so good
    ContentReader reader = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertNotNull("Should be able to get reader", reader);
    assertEquals("Unknown mimetype was changed", bogusMimetype, reader.getMimetype());
}

22. ReplicatingContentStoreTest#testTargetContentUrlExists()

Project: community-edition
File: ReplicatingContentStoreTest.java
public void testTargetContentUrlExists() {
    replicatingStore.setOutbound(true);
    replicatingStore.setInbound(false);
    // pick a secondary store and write some content to it
    ContentStore secondaryStore = secondaryStores.get(2);
    ContentWriter secondaryWriter = secondaryStore.getWriter(ContentContext.NULL_CONTEXT);
    secondaryWriter.putContent("Content for secondary");
    String secondaryContentUrl = secondaryWriter.getContentUrl();
    // Now write to the primary store
    ContentWriter replicatingWriter = replicatingStore.getWriter(new ContentContext(null, secondaryContentUrl));
    String replicatingContent = "Content for primary";
    try {
        replicatingWriter.putContent(replicatingContent);
        fail("Replication should fail when the secondary store already has the content");
    } catch (ContentIOException e) {
    }
}

23. AbstractWritableContentStoreTest#testWriteStreamListener()

Project: community-edition
File: AbstractWritableContentStoreTest.java
/**
     * Checks that the writer can have a listener attached
     */
@Test
public void testWriteStreamListener() throws Exception {
    ContentWriter writer = getWriter();
    // has to be final
    final boolean[] streamClosed = new boolean[] { false };
    ContentStreamListener listener = new ContentStreamListener() {

        public void contentStreamClosed() throws ContentIOException {
            streamClosed[0] = true;
        }
    };
    writer.addListener(listener);
    // write some content
    writer.putContent("ABC");
    // check that the listener was called
    assertTrue("Write stream listener was not called for the stream close", streamClosed[0]);
}

24. ContentMetadataExtracterTest#testUnknownProperties()

Project: community-edition
File: ContentMetadataExtracterTest.java
public void testUnknownProperties() {
    MetadataExtracterRegistry registry = (MetadataExtracterRegistry) applicationContext.getBean("metadataExtracterRegistry");
    TestUnknownMetadataExtracter extracterUnknown = new TestUnknownMetadataExtracter();
    extracterUnknown.setRegistry(registry);
    extracterUnknown.register();
    // Now add some content with a binary mimetype
    ContentWriter cw = this.contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    cw.setMimetype(MimetypeMap.MIMETYPE_BINARY);
    cw.putContent("Content for " + getName());
    ActionImpl action = new ActionImpl(null, ID, SetPropertyValueActionExecuter.NAME, null);
    executer.execute(action, this.nodeRef);
    // The unkown properties should be present
    Serializable prop1 = nodeService.getProperty(nodeRef, PROP_UNKNOWN_1);
    Serializable prop2 = nodeService.getProperty(nodeRef, PROP_UNKNOWN_2);
    assertNotNull("Unknown property is null", prop1);
    assertNotNull("Unknown property is null", prop2);
}

25. EMLTransformerTest#testHtmlSpecialCharsToText()

Project: community-edition
File: EMLTransformerTest.java
/**
     * Test transforming a valid eml with a html part containing html special characters to text
     */
public void testHtmlSpecialCharsToText() throws Exception {
    File emlSourceFile = loadQuickTestFile("htmlChars.eml");
    File txtTargetFile = TempFileProvider.createTempFile("test6", ".txt");
    ContentReader reader = new FileContentReader(emlSourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_RFC822);
    ContentWriter writer = new FileContentWriter(txtTargetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    transformer.transform(reader, writer);
    ContentReader reader2 = new FileContentReader(txtTargetFile);
    reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    String contentStr = reader2.getContentString();
    assertTrue(!contentStr.contains(HTML_SPACE_SPECIAL_CHAR));
}

26. EMLTransformerTest#testRFC822NestedAlternativeToText()

Project: community-edition
File: EMLTransformerTest.java
/**
     * Test transforming a valid eml with nested mimetype multipart/alternative to text
     */
public void testRFC822NestedAlternativeToText() throws Exception {
    File emlSourceFile = loadQuickTestFile("nested.alternative.eml");
    File txtTargetFile = TempFileProvider.createTempFile("test5", ".txt");
    ContentReader reader = new FileContentReader(emlSourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_RFC822);
    ContentWriter writer = new FileContentWriter(txtTargetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    transformer.transform(reader, writer);
    ContentReader reader2 = new FileContentReader(txtTargetFile);
    reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    String contentStr = reader2.getContentString();
    assertTrue(contentStr.contains(QUICK_EML_NESTED_ALTERNATIVE_CONTENT));
}

27. EMLTransformerTest#testRFC822AlternativeToText()

Project: community-edition
File: EMLTransformerTest.java
/**
     * Test transforming a valid eml with minetype multipart/alternative to text
     */
public void testRFC822AlternativeToText() throws Exception {
    File emlSourceFile = loadQuickTestFile("alternative.eml");
    File txtTargetFile = TempFileProvider.createTempFile("test4", ".txt");
    ContentReader reader = new FileContentReader(emlSourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_RFC822);
    ContentWriter writer = new FileContentWriter(txtTargetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    transformer.transform(reader, writer);
    ContentReader reader2 = new FileContentReader(txtTargetFile);
    reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    String contentStr = reader2.getContentString();
    assertTrue(contentStr.contains(QUICK_EML_ALTERNATIVE_CONTENT));
}

28. EMLTransformerTest#testRFC822WithAttachmentToText()

Project: community-edition
File: EMLTransformerTest.java
/**
     * Test transforming a valid eml with an attachment to text; attachment should be ignored
     */
public void testRFC822WithAttachmentToText() throws Exception {
    File emlSourceFile = loadQuickTestFile("attachment.eml");
    File txtTargetFile = TempFileProvider.createTempFile("test3", ".txt");
    ContentReader reader = new FileContentReader(emlSourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_RFC822);
    ContentWriter writer = new FileContentWriter(txtTargetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    transformer.transform(reader, writer);
    ContentReader reader2 = new FileContentReader(txtTargetFile);
    reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    String contentStr = reader2.getContentString();
    assertTrue(contentStr.contains(QUICK_EML_WITH_ATTACHMENT_CONTENT));
    assertTrue(!contentStr.contains(QUICK_EML_ATTACHMENT_CONTENT));
}

29. EMLTransformerTest#testNonAsciiRFC822ToText()

Project: community-edition
File: EMLTransformerTest.java
/**
     * Test transforming a non-ascii eml file to text
     */
public void testNonAsciiRFC822ToText() throws Exception {
    File emlSourceFile = loadQuickTestFile("spanish.eml");
    File txtTargetFile = TempFileProvider.createTempFile("test2", ".txt");
    ContentReader reader = new FileContentReader(emlSourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_RFC822);
    ContentWriter writer = new FileContentWriter(txtTargetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    transformer.transform(reader, writer);
    ContentReader reader2 = new FileContentReader(txtTargetFile);
    reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    String contentStr = reader2.getContentString();
    assertTrue(contentStr.contains(QUICK_EML_CONTENT_SPANISH_UNICODE));
}

30. EMLTransformerTest#testRFC822ToText()

Project: community-edition
File: EMLTransformerTest.java
/**
     * Test transforming a valid eml file to text
     */
public void testRFC822ToText() throws Exception {
    File emlSourceFile = loadQuickTestFile("eml");
    File txtTargetFile = TempFileProvider.createTempFile("test", ".txt");
    ContentReader reader = new FileContentReader(emlSourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_RFC822);
    ContentWriter writer = new FileContentWriter(txtTargetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    transformer.transform(reader, writer);
    ContentReader reader2 = new FileContentReader(txtTargetFile);
    reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    assertTrue(reader2.getContentString().contains(QUICK_EML_CONTENT));
}

31. RoutingContentServiceTest#testOnContentReadPolicy()

Project: community-edition
File: RoutingContentServiceTest.java
public void testOnContentReadPolicy() {
    // Register interest in the content read event for a versionable node
    this.policyComponent.bindClassBehaviour(QName.createQName(NamespaceService.ALFRESCO_URI, "onContentRead"), ContentModel.ASPECT_VERSIONABLE, new JavaBehaviour(this, "onContentReadBehaviourTest"));
    // First check that the policy is not fired when the versionable aspect is not present
    this.contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertFalse(this.readPolicyFired);
    // Write some content and check that the policy is still not fired
    ContentWriter contentWriter2 = this.contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter2.putContent("content update two");
    this.contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertFalse(this.readPolicyFired);
    // Now check that the policy is fired when the versionable aspect is present
    this.nodeService.addAspect(this.contentNodeRef, ContentModel.ASPECT_VERSIONABLE, null);
    this.contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertTrue(this.readPolicyFired);
}

32. RoutingContentServiceTest#testSimpleWrite()

Project: community-edition
File: RoutingContentServiceTest.java
/**
	 * Tests simple writes that don't automatically update the node content URL
	 */
public void testSimpleWrite() throws Exception {
    // get a writer to an arbitrary node
    // no updating of URL
    ContentWriter writer = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, false);
    assertNotNull("Writer should not be null", writer);
    // put some content
    writer.putContent(SOME_CONTENT);
    // get the reader for the node
    ContentReader reader = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertNull("No reader should yet be available for the node", reader);
}

33. RoutingContentServiceTest#testGetRawReader()

Project: community-edition
File: RoutingContentServiceTest.java
public void testGetRawReader() throws Exception {
    ContentReader reader = contentService.getRawReader("test://non-existence");
    assertNotNull("A reader is expected with content URL referencing no content", reader);
    assertFalse("Reader should not have any content", reader.exists());
    // Now write something
    ContentWriter writer = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, false);
    writer.putContent("ABC from " + getName());
    // Try again
    String contentUrl = writer.getContentUrl();
    reader = contentService.getRawReader(contentUrl);
    assertNotNull("Expected reader for live, raw content", reader);
    assertEquals("Content sizes don't match", writer.getSize(), reader.getSize());
}

34. ReplicatingContentStoreTest#testInboundReplication()

Project: community-edition
File: ReplicatingContentStoreTest.java
public void testInboundReplication() throws Exception {
    replicatingStore.setInbound(false);
    // pick a secondary store and write some content to it
    ContentStore secondaryStore = secondaryStores.get(2);
    ContentWriter writer = secondaryStore.getWriter(ContentContext.NULL_CONTEXT);
    writer.putContent(SOME_CONTENT);
    String contentUrl = writer.getContentUrl();
    // get a reader from the replicating store
    ContentReader reader = replicatingStore.getReader(contentUrl);
    assertTrue("Reader must have been found in secondary store", reader.exists());
    // set inbound replication on and repeat
    replicatingStore.setInbound(true);
    reader = replicatingStore.getReader(contentUrl);
    // this time, it must have been replicated to the primary store
    checkForReplication(true, false, contentUrl, SOME_CONTENT);
}

35. ReplicatingContentStoreTest#testAsyncOutboundReplication()

Project: community-edition
File: ReplicatingContentStoreTest.java
public void testAsyncOutboundReplication() throws Exception {
    ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
    replicatingStore.setOutbound(true);
    replicatingStore.setOutboundThreadPoolExecutor(tpe);
    // write some content
    ContentWriter writer = getWriter();
    writer.putContent(SOME_CONTENT);
    String contentUrl = writer.getContentUrl();
    // wait for a second
    synchronized (this) {
        this.wait(1000L);
    }
    checkForReplication(false, true, contentUrl, SOME_CONTENT);
    // check for outbound deletes
    replicatingStore.delete(contentUrl);
    checkForUrl(contentUrl, false);
}

36. ReplicatingContentStoreTest#testOutboundReplication()

Project: community-edition
File: ReplicatingContentStoreTest.java
public void testOutboundReplication() throws Exception {
    replicatingStore.setOutbound(true);
    // write some content
    ContentWriter writer = getWriter();
    writer.putContent(SOME_CONTENT);
    String contentUrl = writer.getContentUrl();
    checkForReplication(false, true, contentUrl, SOME_CONTENT);
    // check for outbound deletes
    replicatingStore.delete(contentUrl);
    checkForUrl(contentUrl, false);
}

37. AggregatingContentStoreTest#testDelete()

Project: community-edition
File: AggregatingContentStoreTest.java
public void testDelete() throws Exception {
    // write some content
    ContentWriter writer = getWriter();
    writer.putContent(SOME_CONTENT);
    String contentUrl = writer.getContentUrl();
    ContentReader reader = primaryStore.getReader(contentUrl);
    assertTrue("Content was not in the primary store", reader.exists());
    assertEquals("The content was incorrect", SOME_CONTENT, reader.getContentString());
    getStore().delete(contentUrl);
    checkForUrl(contentUrl, false);
}

38. FullTest#writeToCacheWithContentContext()

Project: community-edition
File: FullTest.java
@Test
public void writeToCacheWithContentContext() {
    // Write through the caching content store - cache during the process.
    final String proposedUrl = FileContentStore.createNewFileStoreUrl();
    ContentWriter writer = store.getWriter(new ContentContext(null, proposedUrl));
    final String content = makeContent();
    writer.putContent(content);
    assertEquals("Writer should have correct URL", proposedUrl, writer.getContentUrl());
    ContentReader reader = store.getReader(writer.getContentUrl());
    assertEquals("Reader and writer should have same URLs", writer.getContentUrl(), reader.getContentUrl());
    assertEquals("Reader should get correct content", content, reader.getContentString());
}

39. FullTest#canUseCachingContentStore()

Project: community-edition
File: FullTest.java
@Test
public void canUseCachingContentStore() {
    // Write through the caching content store - cache during the process.
    ContentWriter writer = store.getWriter(ContentContext.NULL_CONTEXT);
    final String content = makeContent();
    writer.putContent(content);
    ContentReader reader = store.getReader(writer.getContentUrl());
    assertEquals("Reader and writer should have same URLs", writer.getContentUrl(), reader.getContentUrl());
    assertEquals("Reader should get correct content", content, reader.getContentString());
}

40. CachingContentStoreTest#quotaManagerCanVetoInboundCaching()

Project: community-edition
File: CachingContentStoreTest.java
@Test
public // When attempting to perform write-through caching, i.e. cacheOnInbound = true
void quotaManagerCanVetoInboundCaching() {
    cachingStore = new CachingContentStore(backingStore, cache, true);
    QuotaManagerStrategy quota = mock(QuotaManagerStrategy.class);
    cachingStore.setQuota(quota);
    ContentContext ctx = ContentContext.NULL_CONTEXT;
    ContentWriter backingStoreWriter = mock(ContentWriter.class);
    when(backingStore.getWriter(ctx)).thenReturn(backingStoreWriter);
    when(quota.beforeWritingCacheFile(0L)).thenReturn(false);
    ContentWriter returnedWriter = cachingStore.getWriter(ctx);
    assertSame("Should be writing direct to backing store", backingStoreWriter, returnedWriter);
    verify(quota, never()).afterWritingCacheFile(anyLong());
}

41. CachingContentStoreSpringTest#testStoreWillRecoverFromDeletedCacheFile()

Project: community-edition
File: CachingContentStoreSpringTest.java
public void testStoreWillRecoverFromDeletedCacheFile() {
    final String content = "Content for " + getName() + " test.";
    // Write some content to the backing store.
    ContentWriter writer = backingStore.getWriter(ContentContext.NULL_CONTEXT);
    writer.putContent(content);
    final String contentUrl = writer.getContentUrl();
    // Read content using the CachingContentStore - will cause content to be cached.
    String retrievedContent = store.getReader(contentUrl).getContentString();
    assertEquals(content, retrievedContent);
    // Remove the cached disk file
    File cacheFile = new File(cache.getCacheFilePath(contentUrl));
    cacheFile.delete();
    assertTrue("Cached content should have been deleted", !cacheFile.exists());
    // Should still be able to ask for this content, even though the cache file was
    // deleted and the record of the cache is still in the in-memory cache/lookup.
    String contentAfterDelete = store.getReader(contentUrl).getContentString();
    assertEquals(content, contentAfterDelete);
}

42. CachingContentStoreSpringTest#testStoreWillReadFromCacheWhenAvailable()

Project: community-edition
File: CachingContentStoreSpringTest.java
public void testStoreWillReadFromCacheWhenAvailable() {
    final String content = "Content for " + getName() + " test.";
    // Write some content to the backing store.
    ContentWriter writer = backingStore.getWriter(ContentContext.NULL_CONTEXT);
    writer.putContent(content);
    final String contentUrl = writer.getContentUrl();
    // Read content using the CachingContentStore - will cause content to be cached.
    String retrievedContent = store.getReader(contentUrl).getContentString();
    assertEquals(content, retrievedContent);
    // Remove the original content from the backing store.
    backingStore.delete(contentUrl);
    assertFalse("Original content should have been deleted", backingStore.exists(contentUrl));
    // The cached version is still available.
    String contentAfterDelete = store.getReader(contentUrl).getContentString();
    assertEquals(content, contentAfterDelete);
}

43. AbstractWritableContentStoreTest#testReadAndWriteStreamByPull()

Project: community-edition
File: AbstractWritableContentStoreTest.java
@Test
public void testReadAndWriteStreamByPull() throws Exception {
    ContentWriter writer = getWriter();
    String content = "ABC";
    // put the content using a stream
    InputStream is = new ByteArrayInputStream(content.getBytes());
    writer.putContent(is);
    assertTrue("Stream close not detected", writer.isClosed());
    // get the content using a stream
    ByteArrayOutputStream os = new ByteArrayOutputStream(100);
    ContentReader reader = writer.getReader();
    reader.getContent(os);
    byte[] bytes = os.toByteArray();
    String check = new String(bytes);
    assertEquals("Write out and read in using streams failed", content, check);
}

44. AbstractWritableContentStoreTest#testWriteAndReadString()

Project: community-edition
File: AbstractWritableContentStoreTest.java
/**
     * The simplest test.  Write a string and read it again, checking that we receive the same values.
     * If the resource accessed by {@link #getReader(String)} and {@link #getWriter()} is not the same, then
     * values written and read won't be the same.
     */
@Test
public void testWriteAndReadString() throws Exception {
    ContentWriter writer = getWriter();
    String content = "ABC";
    writer.putContent(content);
    assertTrue("Stream close not detected", writer.isClosed());
    ContentReader reader = writer.getReader();
    String check = reader.getContentString();
    assertTrue("Read and write may not share same resource", check.length() > 0);
    assertEquals("Write and read didn't work", content, check);
}

45. AbstractWritableContentStoreTest#testDeleteSimple()

Project: community-edition
File: AbstractWritableContentStoreTest.java
@Test
public void testDeleteSimple() throws Exception {
    ContentStore store = getStore();
    ContentWriter writer = getWriter();
    writer.putContent("Content for testDeleteSimple");
    String contentUrl = writer.getContentUrl();
    assertTrue("Content must now exist", store.exists(contentUrl));
    try {
        store.delete(contentUrl);
    } catch (UnsupportedOperationException e) {
        logger.warn("Store test testDeleteSimple not possible on " + store.getClass().getName());
        return;
    }
    assertFalse("Content must now be removed", store.exists(contentUrl));
}

46. AbstractWritableContentStoreTest#testSimpleUse()

Project: community-edition
File: AbstractWritableContentStoreTest.java
/**
     * Get a writer and write a little bit of content before reading it.
     */
@Test
public void testSimpleUse() {
    ContentStore store = getStore();
    String content = "Content for testSimpleUse";
    ContentWriter writer = store.getWriter(ContentStore.NEW_CONTENT_CONTEXT);
    assertNotNull("Writer may not be null", writer);
    // Ensure that the URL is available
    String contentUrlBefore = writer.getContentUrl();
    assertNotNull("Content URL may not be null for unused writer", contentUrlBefore);
    assertTrue("URL is not valid: " + contentUrlBefore, AbstractContentStore.isValidContentUrl(contentUrlBefore));
    // Write something
    writer.putContent(content);
    String contentUrlAfter = writer.getContentUrl();
    assertTrue("URL is not valid: " + contentUrlBefore, AbstractContentStore.isValidContentUrl(contentUrlAfter));
    assertEquals("The content URL may not change just because the writer has put content", contentUrlBefore, contentUrlAfter);
    // Get the readers
    ContentReader reader = store.getReader(contentUrlBefore);
    assertNotNull("Reader from store is null", reader);
    assertEquals(reader.getContentUrl(), writer.getContentUrl());
    String checkContent = reader.getContentString();
    assertEquals("Content is different", content, checkContent);
}

47. BlogIntegrationServiceSystemTest#testUpdatePost()

Project: community-edition
File: BlogIntegrationServiceSystemTest.java
public void testUpdatePost() {
    // Create the blog details
    BlogDetails blogDetails = BlogDetails.createBlogDetails(this.nodeService, this.blogDetailsNodeRef);
    // Post and publish the content contained on the node
    this.blogService.newPost(blogDetails, this.nodeRef, ContentModel.PROP_CONTENT, PUBLISH);
    // Edit the title and content of the node
    this.nodeService.setProperty(this.nodeRef, ContentModel.PROP_TITLE, MODIFIED_TITLE);
    ContentWriter contentWriter = this.contentService.getWriter(this.nodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.putContent(MODIFIED_POST_CONTENT);
    // Update the post
    this.blogService.updatePost(this.nodeRef, ContentModel.PROP_CONTENT, PUBLISH);
// Check the updated meta-data .... TODO
}

48. AccessAuditorTest#test09OnContentUpdate()

Project: community-edition
File: AccessAuditorTest.java
@Test
public final void test09OnContentUpdate() throws Exception {
    ContentWriter writer = serviceRegistry.getContentService().getWriter(content1, ContentModel.TYPE_CONTENT, true);
    writer.putContent("The cow jumped over the moon.");
    txn.commit();
    txn = null;
    assertEquals(1, auditMapList.size());
    Map<String, Serializable> auditMap = auditMapList.get(0);
    // TODO Should be UPDATE CONTENT
    assertEquals("UPDATE CONTENT", auditMap.get("action"));
    assertContains("updateContent", auditMap.get("sub-actions"));
    assertContains("updateNodeProperties", auditMap.get("sub-actions"));
    assertEquals("/cm:homeFolder/cm:folder1/cm:content1", auditMap.get("path"));
    assertEquals("cm:content", auditMap.get("type"));
}

49. AccessAuditorTest#newContent()

Project: community-edition
File: AccessAuditorTest.java
private static NodeRef newContent(NodeRef parent, String name) {
    PropertyMap propertyMap0 = new PropertyMap();
    propertyMap0.put(ContentModel.PROP_CONTENT, new ContentData(null, "text/plain", 0L, "UTF-16", Locale.ENGLISH));
    NodeRef content = nodeService.createNode(parent, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name), ContentModel.TYPE_CONTENT, propertyMap0).getChildRef();
    ContentWriter writer = serviceRegistry.getContentService().getWriter(content, ContentModel.TYPE_CONTENT, true);
    writer.putContent("The cat sat on the mat.");
    return content;
}

50. IncomingImapMessage#writeContent()

Project: community-edition
File: IncomingImapMessage.java
/**
     * Writes the content of incoming message into Alfresco repository.
     * 
     * @throws MessagingException
     */
private void writeContent() throws MessagingException {
    ContentWriter writer = serviceRegistry.getContentService().getWriter(messageFileInfo.getNodeRef(), ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_RFC822);
    try {
        OutputStream outputStream = writer.getContentOutputStream();
        wrappedMessage.writeTo(outputStream);
        outputStream.close();
        // it is not used any more and it is available to GC (to avoid memory leak with byte[] MimeMessage.content field)
        wrappedMessage = null;
        this.contentReader = serviceRegistry.getContentService().getReader(messageFileInfo.getNodeRef(), ContentModel.PROP_CONTENT);
    } catch (ContentIOException e) {
        throw new MessagingException(e.getMessage(), e);
    } catch (IOException e) {
        throw new MessagingException(e.getMessage(), e);
    }
}

51. RepoStore#updateDocument()

Project: community-edition
File: RepoStore.java
/* (non-Javadoc)
     * @see org.alfresco.web.scripts.Store#updateDocument(java.lang.String, java.lang.String)
     */
public void updateDocument(String documentPath, String content) throws IOException {
    String[] pathElements = documentPath.split("/");
    // get parent folder
    NodeRef parentRef;
    if (pathElements.length == 1) {
        parentRef = getBaseNodeRef();
    } else {
        parentRef = findNodeRef(documentPath.substring(0, documentPath.lastIndexOf('/')));
    }
    // update file
    String fileName = pathElements[pathElements.length - 1];
    if (fileService.searchSimple(parentRef, fileName) == null) {
        throw new IOException("Document " + documentPath + " does not exists");
    }
    FileInfo fileInfo = fileService.create(parentRef, fileName, ContentModel.TYPE_CONTENT);
    ContentWriter writer = fileService.getWriter(fileInfo.getNodeRef());
    writer.putContent(content);
}

52. LockMethod#createNode()

Project: community-edition
File: LockMethod.java
/**
     * @see org.alfresco.repo.webdav.LockMethod#createNode(org.alfresco.service.cmr.repository.NodeRef, java.lang.String, org.alfresco.service.namespace.QName)
     */
@Override
protected FileInfo createNode(NodeRef parentNodeRef, String name, QName typeQName) {
    FileInfo lockNodeInfo = super.createNode(parentNodeRef, name, ContentModel.TYPE_CONTENT);
    ContentWriter writer = getFileFolderService().getWriter(lockNodeInfo.getNodeRef());
    writer.putContent("");
    if (getNodeService().hasAspect(lockNodeInfo.getNodeRef(), ContentModel.ASPECT_AUTHOR) == false) {
        getNodeService().addAspect(lockNodeInfo.getNodeRef(), ContentModel.ASPECT_AUTHOR, null);
    }
    getNodeService().setProperty(lockNodeInfo.getNodeRef(), ContentModel.PROP_AUTHOR, getAuthenticationService().getCurrentUserName());
    return lockNodeInfo;
}

53. SolrContentStoreTest#delete()

Project: community-edition
File: SolrContentStoreTest.java
@Test
public void delete() throws Exception {
    SolrContentStore store = new SolrContentStore(rootStr);
    ContentContext ctx = createContentContext("abc");
    String url = ctx.getContentUrl();
    ContentWriter writer = store.getWriter(ctx);
    writer.putContent("Content goes here.");
    // Check the reader
    ContentReader reader = store.getReader(url);
    Assert.assertNotNull(reader);
    Assert.assertTrue(reader.exists());
    // Delete
    store.delete(url);
    reader = store.getReader(url);
    Assert.assertNotNull(reader);
    Assert.assertFalse(reader.exists());
    // Delete when already gone; should just not fail
    store.delete(url);
}

54. SolrContentStoreTest#contentByStream()

Project: community-edition
File: SolrContentStoreTest.java
@Test
public void contentByStream() throws Exception {
    SolrContentStore store = new SolrContentStore(rootStr);
    ContentContext ctx = createContentContext("abc");
    ContentWriter writer = store.getWriter(ctx);
    byte[] bytes = new byte[] { 1, 7, 13 };
    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    writer.putContent(bis);
    // Now get the reader
    ContentReader reader = store.getReader(ctx.getContentUrl());
    ByteArrayOutputStream bos = new ByteArrayOutputStream(3);
    reader.getContent(bos);
    Assert.assertEquals(bytes[0], bos.toByteArray()[0]);
    Assert.assertEquals(bytes[1], bos.toByteArray()[1]);
    Assert.assertEquals(bytes[2], bos.toByteArray()[2]);
}

55. HomeFolderProviderSynchronizerTest#createContent()

Project: community-edition
File: HomeFolderProviderSynchronizerTest.java
private NodeRef createContent(String parentPath, String name) throws Exception {
    NodeRef parent = createFolder(parentPath);
    PropertyMap propertyMap = new PropertyMap();
    propertyMap.put(ContentModel.PROP_CONTENT, new ContentData(null, "text/plain", 0L, "UTF-16", Locale.ENGLISH));
    propertyMap.put(ContentModel.PROP_NAME, name);
    NodeRef content = nodeService.createNode(parent, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name), ContentModel.TYPE_CONTENT, propertyMap).getChildRef();
    ContentWriter writer = contentService.getWriter(content, ContentModel.TYPE_CONTENT, true);
    writer.putContent("The cat sat on the mat.");
    // System.out.println(NodeStoreInspector.dumpNode(nodeService, rootNodeRef));
    return content;
}

56. AbstractMultilingualTestCases#createContent()

Project: community-edition
File: AbstractMultilingualTestCases.java
protected NodeRef createContent(String name) {
    NodeRef contentNodeRef = fileFolderService.create(folderNodeRef, name, ContentModel.TYPE_CONTENT).getNodeRef();
    // add some content
    ContentWriter contentWriter = fileFolderService.getWriter(contentNodeRef);
    contentWriter.putContent("ABC");
    // done
    return contentNodeRef;
}

57. PoiHssfContentTransformerTest#testCsvOutput()

Project: community-edition
File: PoiHssfContentTransformerTest.java
public void testCsvOutput() throws Exception {
    File sourceFile = AbstractContentTransformerTest.loadQuickTestFile("xls");
    ContentReader sourceReader = new FileContentReader(sourceFile);
    File targetFile = TempFileProvider.createTempFile(getClass().getSimpleName() + "_" + getName() + "_xls_", ".csv");
    ContentWriter targetWriter = new FileContentWriter(targetFile);
    sourceReader.setMimetype(MimetypeMap.MIMETYPE_EXCEL);
    targetWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_CSV);
    transformer.transform(sourceReader, targetWriter);
    ContentReader targetReader = targetWriter.getReader();
    String checkContent = targetReader.getContentString();
    additionalContentCheck(MimetypeMap.MIMETYPE_EXCEL, MimetypeMap.MIMETYPE_TEXT_CSV, checkContent);
}

58. PdfBoxContentTransformerTest#pdfToTextTransform()

Project: community-edition
File: PdfBoxContentTransformerTest.java
private void pdfToTextTransform(String filename, String sourceMimetype, String targetMimetype) throws IOException {
    ContentWriter targetWriter = null;
    String sourceExtension = filename.substring(filename.lastIndexOf('.') + 1);
    String targetExtension = mimetypeService.getExtension(targetMimetype);
    File sourceFile = AbstractContentTransformerTest.loadNamedQuickTestFile(filename);
    ContentReader sourceReader = new FileContentReader(sourceFile);
    AbstractContentTransformer2 transformer = (AbstractContentTransformer2) getTransformer(sourceMimetype, targetMimetype);
    // make a writer for the target file
    File targetFile = TempFileProvider.createTempFile(getClass().getSimpleName() + "_" + getName() + "_" + sourceExtension + "_", "." + targetExtension);
    targetWriter = new FileContentWriter(targetFile);
    // do the transformation
    sourceReader.setMimetype(sourceMimetype);
    targetWriter.setMimetype(targetMimetype);
    transformer.transform(sourceReader.getReader(), targetWriter);
}

59. OpenOfficeContentTransformerTest#testEmptyHtmlToEmptyPdf()

Project: community-edition
File: OpenOfficeContentTransformerTest.java
/**
     * ALF-219. Transforamtion from .html to .pdf for empty file.
     * @throws Exception
     */
public void testEmptyHtmlToEmptyPdf() throws Exception {
    if (!worker.isAvailable()) {
        // no connection
        return;
    }
    URL url = this.getClass().getClassLoader().getResource("misc/empty.html");
    assertNotNull("URL was unexpectedly null", url);
    File htmlSourceFile = new File(url.getFile());
    assertTrue("Test file does not exist.", htmlSourceFile.exists());
    File pdfTargetFile = TempFileProvider.createTempFile(getName() + "-target-", ".pdf");
    ContentReader reader = new FileContentReader(htmlSourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_HTML);
    ContentWriter writer = new FileContentWriter(pdfTargetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
    transformer.transform(reader, writer);
}

60. OpenOfficeContentTransformerTest#testHtmlToPdf()

Project: community-edition
File: OpenOfficeContentTransformerTest.java
/**
     * Test what is up with HTML to PDF
     */
public void testHtmlToPdf() throws Exception {
    if (!worker.isAvailable()) {
        // no connection
        return;
    }
    File htmlSourceFile = loadQuickTestFile("html");
    File pdfTargetFile = TempFileProvider.createTempFile(getName() + "-target-", ".pdf");
    ContentReader reader = new FileContentReader(htmlSourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_HTML);
    ContentWriter writer = new FileContentWriter(pdfTargetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
    transformer.transform(reader, writer);
}

61. MailContentTransformerTest#testNonUnicodeChineseMsgToText()

Project: community-edition
File: MailContentTransformerTest.java
/**
     * Test transforming a chinese non-unicode msg file to
     *  text
     */
public void testNonUnicodeChineseMsgToText() throws Exception {
    File msgSourceFile = loadQuickTestFile("chinese.msg");
    File txtTargetFile = TempFileProvider.createTempFile(getName() + "-target-2", ".txt");
    ContentReader reader = new FileContentReader(msgSourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_OUTLOOK_MSG);
    ContentWriter writer = new FileContentWriter(txtTargetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    transformer.transform(reader, writer);
    ContentReader reader2 = new FileContentReader(txtTargetFile);
    reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    // Check the quick text
    String text = reader2.getContentString();
    assertTrue(text.contains(QUICK_CONTENT));
    // Now check the non quick parts came out ok
    assertTrue(text.contains("(???)"));
    assertTrue(text.contains("???? )"));
}

62. MailContentTransformerTest#testUnicodeMsgToText()

Project: community-edition
File: MailContentTransformerTest.java
/**
     * Test transforming a valid unicode msg file to text
     */
public void testUnicodeMsgToText() throws Exception {
    File msgSourceFile = loadQuickTestFile("unicode.msg");
    File txtTargetFile = TempFileProvider.createTempFile(getName() + "-target-2", ".txt");
    ContentReader reader = new FileContentReader(msgSourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_OUTLOOK_MSG);
    ContentWriter writer = new FileContentWriter(txtTargetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    transformer.transform(reader, writer);
    ContentReader reader2 = new FileContentReader(txtTargetFile);
    reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    assertTrue(reader2.getContentString().contains(QUICK_CONTENT));
}

63. MailContentTransformerTest#testMsgToText()

Project: community-edition
File: MailContentTransformerTest.java
/**
     * Test transforming a valid msg file to text
     */
public void testMsgToText() throws Exception {
    File msgSourceFile = loadQuickTestFile("msg");
    File txtTargetFile = TempFileProvider.createTempFile(getName() + "-target-1", ".txt");
    ContentReader reader = new FileContentReader(msgSourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_OUTLOOK_MSG);
    ContentWriter writer = new FileContentWriter(txtTargetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    transformer.transform(reader, writer);
    ContentReader reader2 = new FileContentReader(txtTargetFile);
    reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    assertTrue(reader2.getContentString().contains(QUICK_CONTENT));
}

64. AbstractMetadataExtracterTest#testZeroLengthFile()

Project: community-edition
File: AbstractMetadataExtracterTest.java
public void testZeroLengthFile() throws Exception {
    MetadataExtracter extractor = getExtracter();
    File file = TempFileProvider.createTempFile(getName(), ".bin");
    ContentWriter writer = new FileContentWriter(file);
    writer.getContentOutputStream().close();
    ContentReader reader = writer.getReader();
    // Try the zero length file against all supported mimetypes.
    // Note: Normally the reader would need to be fetched for each access, but we need to be sure
    // that the content is not accessed on the reader AT ALL.
    PropertyMap properties = new PropertyMap();
    List<String> mimetypes = mimetypeMap.getMimetypes();
    for (String mimetype : mimetypes) {
        if (!extractor.isSupported(mimetype)) {
            // Not interested
            continue;
        }
        reader.setMimetype(mimetype);
        extractor.extract(reader, properties);
        assertEquals("There should not be any new properties", 0, properties.size());
    }
}

65. FileContentStoreTest#testConcurrentWriteDetection()

Project: community-edition
File: FileContentStoreTest.java
/**
     * Checks that the store disallows concurrent writers to be issued to the same URL.
     */
@SuppressWarnings("unused")
@Test
public void testConcurrentWriteDetection() throws Exception {
    ByteBuffer buffer = ByteBuffer.wrap("Something".getBytes());
    ContentStore store = getStore();
    ContentContext firstContentCtx = ContentStore.NEW_CONTENT_CONTEXT;
    ContentWriter firstWriter = store.getWriter(firstContentCtx);
    String contentUrl = firstWriter.getContentUrl();
    ContentContext secondContentCtx = new ContentContext(null, contentUrl);
    try {
        ContentWriter secondWriter = store.getWriter(secondContentCtx);
        fail("Store must disallow more than one writer onto the same content URL: " + store);
    } catch (ContentExistsException e) {
    }
}

66. AbstractWritableContentStoreTest#testReadAndWriteStreamByPush()

Project: community-edition
File: AbstractWritableContentStoreTest.java
@Test
public void testReadAndWriteStreamByPush() throws Exception {
    ContentWriter writer = getWriter();
    String content = "Some Random Content";
    // get the content output stream
    OutputStream os = writer.getContentOutputStream();
    os.write(content.getBytes());
    assertFalse("Stream has not been closed", writer.isClosed());
    // close the stream and check again
    os.close();
    assertTrue("Stream close not detected", writer.isClosed());
    // pull the content from a stream
    ContentReader reader = writer.getReader();
    InputStream is = reader.getContentInputStream();
    byte[] buffer = new byte[100];
    int count = is.read(buffer);
    assertEquals("No content read", content.length(), count);
    is.close();
    String check = new String(buffer, 0, count);
    assertEquals("Write out of and read into files failed", content, check);
}

67. FileFolderServiceImpl#getWriter()

Project: community-edition
File: FileFolderServiceImpl.java
@Override
public ContentWriter getWriter(NodeRef nodeRef) {
    FileInfo fileInfo = toFileInfo(nodeRef, false);
    if (fileInfo.isFolder()) {
        throw new InvalidTypeException("Unable to get a content writer for a folder: " + fileInfo);
    }
    final ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    // of the ContentData.
    if (writer.getMimetype() == null) {
        final String name = fileInfo.getName();
        writer.guessMimetype(name);
    }
    // Done
    return writer;
}

68. SolrContentStoreTest#getWriter()

Project: community-edition
File: SolrContentStoreTest.java
@Test
public void getWriter() {
    SolrContentStore store = new SolrContentStore(rootStr);
    ContentContext ctx = createContentContext("abc");
    ContentWriter writer = store.getWriter(ctx);
    String url = writer.getContentUrl();
    Assert.assertNotNull(url);
    Assert.assertEquals("URL of the context does not match the writer URL. ", ctx.getContentUrl(), url);
}

69. RuleTriggerTest#testOnContentUpdateTrigger()

Project: community-edition
File: RuleTriggerTest.java
public void testOnContentUpdateTrigger() {
    TestRuleType nodeCreate = createTestRuleType(ON_CREATE_NODE_TRIGGER);
    assertFalse(nodeCreate.rulesTriggered);
    NodeRef nodeRef = this.nodeService.createNode(this.rootNodeRef, ContentModel.ASSOC_CHILDREN, ContentModel.ASSOC_CHILDREN, ContentModel.TYPE_CONTENT).getChildRef();
    assertTrue(nodeCreate.rulesTriggered);
    TestRuleType contentCreate = createTestRuleType(ON_CONTENT_CREATE_TRIGGER);
    TestRuleType contentUpdate = createTestRuleType(ON_PROPERTY_UPDATE_TRIGGER);
    assertFalse(contentCreate.rulesTriggered);
    assertFalse(contentUpdate.rulesTriggered);
    // Try and trigger the type
    ContentWriter contentWriter = this.contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    contentWriter.setEncoding("UTF-8");
    contentWriter.putContent("some content");
    // Check to see if the rule type has been triggered
    assertTrue(contentCreate.rulesTriggered);
    assertFalse(contentUpdate.rulesTriggered);
    // Try and trigger the type (again)
    contentCreate.rulesTriggered = false;
    assertFalse(contentCreate.rulesTriggered);
    ContentWriter contentWriter2 = this.contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    contentWriter2.setEncoding("UTF-8");
    contentWriter2.putContent("more content some content");
    // Check to see if the rule type has been triggered
    assertTrue(contentCreate.rulesTriggered);
    assertFalse("Content update must not fire if the content was created in the same txn.", contentUpdate.rulesTriggered);
    // Terminate the transaction
    setComplete();
    endTransaction();
    contentCreate.rulesTriggered = false;
    // Try and trigger the type (again)
    ContentWriter contentWriter3 = this.contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter3.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    contentWriter3.setEncoding("UTF-8");
    contentWriter3.putContent("Yet content some content");
    // Check to see if the rule type has been triggered
    assertFalse("Content create should not be fired on an update in a new txn", contentCreate.rulesTriggered);
    assertTrue("Content update must not fire if the content was created in the same txn.", contentUpdate.rulesTriggered);
}

70. RuleTriggerTest#testOnContentCreateTrigger()

Project: community-edition
File: RuleTriggerTest.java
public void testOnContentCreateTrigger() {
    TestRuleType nodeCreate = createTestRuleType(ON_CREATE_NODE_TRIGGER);
    assertFalse(nodeCreate.rulesTriggered);
    NodeRef nodeRef = this.nodeService.createNode(this.rootNodeRef, ContentModel.ASSOC_CHILDREN, ContentModel.ASSOC_CHILDREN, ContentModel.TYPE_CONTENT).getChildRef();
    assertTrue(nodeCreate.rulesTriggered);
    // Terminate the transaction
    setComplete();
    endTransaction();
    startNewTransaction();
    TestRuleType contentCreate = createTestRuleType(ON_CONTENT_CREATE_TRIGGER);
    assertFalse(contentCreate.rulesTriggered);
    // Try and trigger the type
    ContentWriter contentWriter = this.contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    contentWriter.setEncoding("UTF-8");
    contentWriter.putContent("some content");
    // Check to see if the rule type has been triggered
    assertTrue(contentCreate.rulesTriggered);
    // Try and trigger the type (again)
    contentCreate.rulesTriggered = false;
    assertFalse(contentCreate.rulesTriggered);
    ContentWriter contentWriter2 = this.contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    contentWriter2.setEncoding("UTF-8");
    contentWriter2.putContent("some content");
    // Check to see if the rule type has been triggered
    assertFalse(contentCreate.rulesTriggered);
}

71. FormServiceImplTest#onSetUpInTransaction()

Project: community-edition
File: FormServiceImplTest.java
/**
     * Called during the transaction setup
     */
@SuppressWarnings("deprecation")
@Override
protected void onSetUpInTransaction() throws Exception {
    super.onSetUpInTransaction();
    // Get the required services
    this.formService = (FormService) this.applicationContext.getBean("FormService");
    this.namespaceService = (NamespaceService) this.applicationContext.getBean("NamespaceService");
    this.scriptService = (ScriptService) this.applicationContext.getBean("ScriptService");
    PersonService personService = (PersonService) this.applicationContext.getBean("PersonService");
    this.contentService = (ContentService) this.applicationContext.getBean("ContentService");
    this.workflowService = (WorkflowService) this.applicationContext.getBean("WorkflowService");
    MutableAuthenticationService mutableAuthenticationService = (MutableAuthenticationService) applicationContext.getBean("AuthenticationService");
    this.personManager = new TestPersonManager(mutableAuthenticationService, personService, nodeService);
    // create users
    personManager.createPerson(USER_ONE);
    personManager.createPerson(USER_TWO);
    // Do the tests as userOne
    personManager.setUser(USER_ONE);
    String guid = GUID.generate();
    NodeRef rootNode = this.nodeService.getRootNode(new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore"));
    Map<QName, Serializable> folderProps = new HashMap<QName, Serializable>(1);
    this.folderName = "testFolder" + guid;
    folderProps.put(ContentModel.PROP_NAME, this.folderName);
    this.folder = this.nodeService.createNode(rootNode, ContentModel.ASSOC_CHILDREN, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "testFolder" + guid), ContentModel.TYPE_FOLDER, folderProps).getChildRef();
    // Create a node
    Map<QName, Serializable> docProps = new HashMap<QName, Serializable>(1);
    this.documentName = "testDocument" + guid + ".txt";
    docProps.put(ContentModel.PROP_NAME, this.documentName);
    this.document = this.nodeService.createNode(this.folder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "testDocument" + guid + ".txt"), ContentModel.TYPE_CONTENT, docProps).getChildRef();
    // create a node to use as target of association
    docProps.put(ContentModel.PROP_NAME, "associatedDocument" + guid + ".txt");
    this.associatedDoc = this.nodeService.createNode(this.folder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "associatedDocument" + guid + ".txt"), ContentModel.TYPE_CONTENT, docProps).getChildRef();
    // create a node to use as a 2nd child node of the folder
    docProps.put(ContentModel.PROP_NAME, "childDocument" + guid + ".txt");
    this.childDoc = this.nodeService.createNode(this.folder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "childDocument" + guid + ".txt"), ContentModel.TYPE_CONTENT, docProps).getChildRef();
    // add some content to the nodes
    ContentWriter writer = this.contentService.getWriter(this.document, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(VALUE_MIMETYPE);
    writer.setEncoding(VALUE_ENCODING);
    writer.putContent(VALUE_CONTENT);
    ContentWriter writer2 = this.contentService.getWriter(this.associatedDoc, ContentModel.PROP_CONTENT, true);
    writer2.setMimetype(VALUE_MIMETYPE);
    writer2.setEncoding(VALUE_ENCODING);
    writer2.putContent(VALUE_ASSOC_CONTENT);
    // add standard titled aspect
    Map<QName, Serializable> aspectProps = new HashMap<QName, Serializable>(2);
    aspectProps.put(ContentModel.PROP_TITLE, VALUE_TITLE);
    aspectProps.put(ContentModel.PROP_DESCRIPTION, VALUE_DESCRIPTION);
    this.nodeService.addAspect(this.document, ContentModel.ASPECT_TITLED, aspectProps);
    // add emailed aspect (has multiple value field)
    aspectProps = new HashMap<QName, Serializable>(5);
    aspectProps.put(ContentModel.PROP_ORIGINATOR, VALUE_ORIGINATOR);
    aspectProps.put(ContentModel.PROP_ADDRESSEE, VALUE_ADDRESSEE);
    List<String> addressees = new ArrayList<String>(2);
    addressees.add(VALUE_ADDRESSEES1);
    addressees.add(VALUE_ADDRESSEES2);
    aspectProps.put(ContentModel.PROP_ADDRESSEES, (Serializable) addressees);
    aspectProps.put(ContentModel.PROP_SUBJECT, VALUE_SUBJECT);
    aspectProps.put(ContentModel.PROP_SENTDATE, VALUE_SENT_DATE);
    this.nodeService.addAspect(this.document, ContentModel.ASPECT_EMAILED, aspectProps);
    // add referencing aspect (has association)
    aspectProps.clear();
    this.nodeService.addAspect(document, ContentModel.ASPECT_REFERENCING, aspectProps);
    this.nodeService.createAssociation(this.document, this.associatedDoc, ContentModel.ASSOC_REFERENCES);
}

72. CheckOutCheckInServiceImplTest#initTestData()

Project: community-edition
File: CheckOutCheckInServiceImplTest.java
private void initTestData() {
    authenticationComponent.setSystemUserAsCurrentUser();
    // Create the store and get the root node reference
    this.storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
    this.rootNodeRef = nodeService.getRootNode(storeRef);
    // Create the node used for tests
    ChildAssociationRef childAssocRef = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("test"), ContentModel.TYPE_CONTENT);
    this.nodeRef = childAssocRef.getChildRef();
    nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_TITLED, null);
    nodeService.setProperty(this.nodeRef, ContentModel.PROP_NAME, TEST_VALUE_NAME);
    nodeService.setProperty(this.nodeRef, PROP2_QNAME, TEST_VALUE_2);
    // Add the initial content to the node
    ContentWriter contentWriter = this.contentService.getWriter(this.nodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype("text/plain");
    contentWriter.setEncoding("UTF-8");
    contentWriter.putContent(CONTENT_1);
    // Add the lock and version aspects to the created node
    nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_VERSIONABLE, null);
    nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_LOCKABLE, null);
    // Create and authenticate the user
    this.userName = "cociTest" + GUID.generate();
    TestWithUserUtils.createUser(this.userName, PWD, this.rootNodeRef, this.nodeService, this.authenticationService);
    TestWithUserUtils.authenticateUser(this.userName, PWD, this.rootNodeRef, this.authenticationService);
    this.userNodeRef = TestWithUserUtils.getCurrentUser(this.authenticationService);
    permissionService.setPermission(this.rootNodeRef, this.userName, PermissionService.ALL_PERMISSIONS, true);
    permissionService.setPermission(this.nodeRef, this.userName, PermissionService.ALL_PERMISSIONS, true);
    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, "file")).getChildRef();
    contentWriter = this.contentService.getWriter(fileNodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype("text/plain");
    contentWriter.setEncoding("UTF-8");
    contentWriter.putContent(CONTENT_1);
}

73. ThumbnailServiceTest#setUp()

Project: community-edition
File: ThumbnailServiceTest.java
@Override
protected void setUp() throws Exception {
    super.setUp();
    this.fileFolderService = (FileFolderService) getServer().getApplicationContext().getBean("FileFolderService");
    this.contentService = (ContentService) getServer().getApplicationContext().getBean("ContentService");
    this.repositoryHelper = (Repository) getServer().getApplicationContext().getBean("repositoryHelper");
    this.authenticationService = (MutableAuthenticationService) getServer().getApplicationContext().getBean("AuthenticationService");
    this.personService = (PersonService) getServer().getApplicationContext().getBean("PersonService");
    try {
        this.transactionService = (TransactionServiceImpl) getServer().getApplicationContext().getBean("transactionComponent");
    } catch (ClassCastException e) {
        throw new AlfrescoRuntimeException("The ThumbnailServiceTest needs direct access to the TransactionServiceImpl");
    }
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
    this.testRoot = this.repositoryHelper.getCompanyHome();
    // Get test content
    InputStream pdfStream = ThumbnailServiceTest.class.getClassLoader().getResourceAsStream("org/alfresco/repo/web/scripts/thumbnail/test_doc.pdf");
    assertNotNull(pdfStream);
    InputStream jpgStream = ThumbnailServiceTest.class.getClassLoader().getResourceAsStream("org/alfresco/repo/web/scripts/thumbnail/test_image.jpg");
    assertNotNull(jpgStream);
    String guid = GUID.generate();
    // Create new nodes and set test content
    FileInfo fileInfoPdf = this.fileFolderService.create(this.testRoot, "test_doc" + guid + ".pdf", ContentModel.TYPE_CONTENT);
    this.pdfNode = fileInfoPdf.getNodeRef();
    ContentWriter contentWriter = this.contentService.getWriter(fileInfoPdf.getNodeRef(), ContentModel.PROP_CONTENT, true);
    contentWriter.setEncoding("UTF-8");
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_PDF);
    contentWriter.putContent(pdfStream);
    FileInfo fileInfoJpg = this.fileFolderService.create(this.testRoot, "test_image" + guid + ".jpg", ContentModel.TYPE_CONTENT);
    this.jpgNode = fileInfoJpg.getNodeRef();
    contentWriter = this.contentService.getWriter(fileInfoJpg.getNodeRef(), ContentModel.PROP_CONTENT, true);
    contentWriter.setEncoding("UTF-8");
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_IMAGE_JPEG);
    contentWriter.putContent(jpgStream);
}

74. SiteServiceImplTest#createTestSiteWithContent()

Project: community-edition
File: SiteServiceImplTest.java
/**
     * Creates a site with a simple content tree within it.
     * The content looks like
     * <pre>
     * [site] {siteShortName}
     *    |
     *    --- [siteContainer] {componentId}
     *          |
     *          --- [cm:content] fileFolderPrefix + "file.txt"
     *          |
     *          |-- [folder] fileFolderPrefix + "folder"
     *                  |
     *                  |-- [cm:content] fileFolderPrefix + "fileInFolder.txt"
     *                  |
     *                  |-- [folder] fileFolderPrefix + "subfolder"
     *                         |
     *                         |-- [cm:content] fileFolderPrefix + "fileInSubfolder.txt"
     * </pre>
     * 
     * @param siteShortName short name for the site
     * @param componentId the component id for the container
     * @param visibility visibility for the site.
     * @param fileFolderPrefix a prefix String to put on all folders/files created.
     */
private SiteInfo createTestSiteWithContent(String siteShortName, String componentId, SiteVisibility visibility, String fileFolderPrefix) {
    // Create a public site
    SiteInfo siteInfo = this.siteService.createSite(TEST_SITE_PRESET, siteShortName, TEST_TITLE, TEST_DESCRIPTION, visibility);
    NodeRef siteContainer = this.siteService.createContainer(siteShortName, componentId, ContentModel.TYPE_FOLDER, null);
    FileInfo fileInfo = this.fileFolderService.create(siteContainer, fileFolderPrefix + "file.txt", ContentModel.TYPE_CONTENT);
    ContentWriter writer = this.fileFolderService.getWriter(fileInfo.getNodeRef());
    writer.putContent("Just some old content that doesn't mean anything");
    FileInfo folder1Info = this.fileFolderService.create(siteContainer, fileFolderPrefix + "folder", ContentModel.TYPE_FOLDER);
    FileInfo fileInfo2 = this.fileFolderService.create(folder1Info.getNodeRef(), fileFolderPrefix + "fileInFolder.txt", ContentModel.TYPE_CONTENT);
    ContentWriter writer2 = this.fileFolderService.getWriter(fileInfo2.getNodeRef());
    writer2.putContent("Just some old content that doesn't mean anything");
    FileInfo folder2Info = this.fileFolderService.create(folder1Info.getNodeRef(), fileFolderPrefix + "subfolder", ContentModel.TYPE_FOLDER);
    FileInfo fileInfo3 = this.fileFolderService.create(folder2Info.getNodeRef(), fileFolderPrefix + "fileInSubfolder.txt", ContentModel.TYPE_CONTENT);
    ContentWriter writer3 = this.fileFolderService.getWriter(fileInfo3.getNodeRef());
    writer3.putContent("Just some old content that doesn't mean anything");
    return siteInfo;
}

75. SiteServiceImplMoreTest#testSiteRolesPersmissionsToDeleteWorkingCopy()

Project: community-edition
File: SiteServiceImplMoreTest.java
/**
     * MNT-16043: Site Owner and Site Manager can delete working copy, 
     * Site Collaborator cannot
     * 
     * @throws Exception
     */
@Test
public void testSiteRolesPersmissionsToDeleteWorkingCopy() throws Exception {
    final String userSiteOwner = "UserSiteOwner";
    final String userSiteManager = "UserSiteManager";
    final String userSiteCollaborator = "UserSiteCollaborator";
    final String userPrefix = "delete-locked-file";
    // create the users
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>() {

        public Void execute() throws Throwable {
            createUser(userSiteOwner, userPrefix);
            createUser(userSiteManager, userPrefix);
            createUser(userSiteCollaborator, userPrefix);
            return null;
        }
    });
    final String siteShortName = userPrefix + "Site" + System.currentTimeMillis();
    final String dummyContent = "Just some old content that doesn't mean anything";
    // Create site
    final TestSiteAndMemberInfo testSiteAndMemberInfo = perMethodTestSites.createTestSiteWithUserPerRole(siteShortName, "sitePreset", SiteVisibility.PUBLIC, userSiteOwner);
    // create 1 file into the site as the owner of the site
    AUTHENTICATION_COMPONENT.setCurrentUser(userSiteOwner);
    NodeRef siteContainer = SITE_SERVICE.createContainer(siteShortName, "doclib", ContentModel.TYPE_FOLDER, null);
    final FileInfo fileInfo1 = FILE_FOLDER_SERVICE.create(siteContainer, "fileInfo1.txt", ContentModel.TYPE_CONTENT);
    ContentWriter writer1 = FILE_FOLDER_SERVICE.getWriter(fileInfo1.getNodeRef());
    writer1.putContent(dummyContent);
    final FileInfo fileInfo2 = FILE_FOLDER_SERVICE.create(siteContainer, "fileInfo2.txt", ContentModel.TYPE_CONTENT);
    ContentWriter writer2 = FILE_FOLDER_SERVICE.getWriter(fileInfo2.getNodeRef());
    writer2.putContent(dummyContent);
    final FileInfo fileInfo3 = FILE_FOLDER_SERVICE.create(siteContainer, "fileInfo3.txt", ContentModel.TYPE_CONTENT);
    ContentWriter writer3 = FILE_FOLDER_SERVICE.getWriter(fileInfo2.getNodeRef());
    writer3.putContent(dummyContent);
    // Site Manager - can delete working copy but cannot delete the original
    // locked file
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>() {

        public Void execute() throws Throwable {
            // lock a file as userOwner
            NodeRef workingCopy = COCI_SERVICE.checkout(fileInfo1.getNodeRef());
            assertNotNull(workingCopy);
            // make userSiteManager a member of the site
            SITE_SERVICE.setMembership(siteShortName, userSiteManager, SiteModel.SITE_MANAGER);
            // make sure we are running as userSiteManager
            AUTHENTICATION_COMPONENT.setCurrentUser(userSiteManager);
            // try delete locked file by owner
            try {
                NODE_SERVICE.deleteNode(fileInfo1.getNodeRef());
                fail("Cannot perform operation since the node" + fileInfo1.getNodeRef() + " is locked");
            } catch (NodeLockedException ex) {
            }
            // simulate delete from Share - delete the working copy
            NODE_SERVICE.deleteNode(workingCopy);
            return null;
        }
    });
    // Site Owner - can delete working copy but cannot delete the original
    // locked file
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>() {

        public Void execute() throws Throwable {
            AUTHENTICATION_COMPONENT.setCurrentUser(userSiteOwner);
            // lock a file as userOwner
            NodeRef workingCopy = COCI_SERVICE.checkout(fileInfo2.getNodeRef());
            assertNotNull(workingCopy);
            try {
                NODE_SERVICE.deleteNode(fileInfo2.getNodeRef());
                fail("Cannot perform operation since the node" + fileInfo1.getNodeRef() + " is locked");
            } catch (NodeLockedException ex) {
            }
            NODE_SERVICE.deleteNode(workingCopy);
            return null;
        }
    });
    // Site COLLABORATOR - cannot delete working copy or original file
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>() {

        public Void execute() throws Throwable {
            // lock a file as userOwner
            AUTHENTICATION_COMPONENT.setCurrentUser(userSiteOwner);
            NodeRef workingCopy = COCI_SERVICE.checkout(fileInfo3.getNodeRef());
            assertNotNull(workingCopy);
            // make userSiteCollaborator a member of the site
            SITE_SERVICE.setMembership(siteShortName, userSiteCollaborator, SiteModel.SITE_COLLABORATOR);
            // make sure we are running as userSiteManager
            AUTHENTICATION_COMPONENT.setCurrentUser(userSiteCollaborator);
            try {
                NODE_SERVICE.deleteNode(fileInfo3.getNodeRef());
                fail("You do not have the appropriate permissions to perform this operation");
            } catch (AccessDeniedException ex) {
            }
            // try delete locked file by owner
            try {
                NODE_SERVICE.deleteNode(workingCopy);
                fail("You do not have the appropriate permissions to perform this operation");
            } catch (AccessDeniedException ex) {
            }
            return null;
        }
    });
    AUTHENTICATION_COMPONENT.setCurrentUser(userSiteOwner);
    // Delete the site
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Void>() {

        public Void execute() throws Throwable {
            AUTHENTICATION_COMPONENT.getCurrentUserName();
            SITE_SERVICE.deleteSite(siteShortName);
            return null;
        }
    });
}

76. RoutingContentServiceTest#testConcurrentWritesWithSingleTxn()

Project: community-edition
File: RoutingContentServiceTest.java
public void testConcurrentWritesWithSingleTxn() throws Exception {
    // want to operate in a user transaction
    txn.commit();
    txn = null;
    UserTransaction txn = getUserTransaction();
    txn.begin();
    txn.setRollbackOnly();
    ContentWriter writer1 = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    ContentWriter writer2 = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    ContentWriter writer3 = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    writer1.putContent("writer1 wrote this");
    writer2.putContent("writer2 wrote this");
    writer3.putContent("writer3 wrote this");
    // get the content
    ContentReader reader = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    String contentCheck = reader.getContentString();
    assertEquals("Content check failed", "writer3 wrote this", contentCheck);
    try {
        txn.commit();
        fail("Transaction has been marked for rollback");
    } catch (RollbackException e) {
    }
    // rollback and check that the content has 'disappeared'
    txn.rollback();
    // need a new transaction
    txn = getUserTransaction();
    txn.begin();
    txn.setRollbackOnly();
    reader = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertNull("Transaction was rolled back - no content should be visible", reader);
    txn.rollback();
}

77. RoutingContentServiceTest#testOnContentUpdatePolicy()

Project: community-edition
File: RoutingContentServiceTest.java
/**
	 * Tests that the content update policy firs correctly
	 */
public void testOnContentUpdatePolicy() {
    // Register interest in the content update event for a versionable node
    this.policyComponent.bindClassBehaviour(QName.createQName(NamespaceService.ALFRESCO_URI, "onContentUpdate"), ContentModel.ASPECT_VERSIONABLE, new JavaBehaviour(this, "onContentUpdateBehaviourTest"));
    // First check that the policy is not fired when the versionable aspect is not present
    ContentWriter contentWriter = this.contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.putContent("content update one");
    assertFalse(this.policyFired);
    this.newContent = false;
    // Now check that the policy is fired when the versionable aspect is present
    this.nodeService.addAspect(this.contentNodeRef, ContentModel.ASPECT_VERSIONABLE, null);
    ContentWriter contentWriter2 = this.contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter2.putContent("content update two");
    assertTrue(this.policyFired);
    this.policyFired = false;
    // Check that the policy is not fired when using a non updating content writer
    ContentWriter contentWriter3 = this.contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, false);
    contentWriter3.putContent("content update three");
    assertFalse(this.policyFired);
}

78. GuessMimetypeTest#testAppleMimetype()

Project: community-edition
File: GuessMimetypeTest.java
public void testAppleMimetype() throws Exception {
    String content = "This is some content";
    String fileName = "._myfile.pdf";
    retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>() {

        @Override
        public Object execute() throws Throwable {
            AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
            Map<QName, Serializable> properties = new HashMap<QName, Serializable>(13);
            properties.put(ContentModel.PROP_NAME, (Serializable) "test.txt");
            nodeRef = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{test}testnode"), ContentModel.TYPE_CONTENT).getChildRef();
            return null;
        }
    });
    ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    writer.putContent(content);
    writer.guessMimetype(fileName);
    assertEquals(MimetypeMap.MIMETYPE_APPLEFILE, writer.getMimetype());
    fileName = "myfile.pdf";
    retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Object>() {

        @Override
        public Object execute() throws Throwable {
            AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
            Map<QName, Serializable> properties = new HashMap<QName, Serializable>(13);
            properties.put(ContentModel.PROP_NAME, (Serializable) "test.txt");
            nodeRef = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{test}testnode"), ContentModel.TYPE_CONTENT).getChildRef();
            return null;
        }
    });
    ContentWriter writer2 = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    content = "This is other content";
    writer2.putContent(content);
    writer2.guessMimetype(fileName);
    assertNotSame(MimetypeMap.MIMETYPE_APPLEFILE, writer2.getMimetype());
}

79. RoutingContentServiceTest#testRollbackCleanup_ALF2890()

Project: community-edition
File: RoutingContentServiceTest.java
/**
     * Ensure that content URLs outside of a transaction are not touched on rollback.
     */
public void testRollbackCleanup_ALF2890() throws Exception {
    ContentWriter updatingWriter = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    updatingWriter.putContent("STEP 1");
    txn.commit();
    txn = null;
    ContentReader readerStep1 = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertEquals("Incorrect content", "STEP 1", readerStep1.getContentString());
    ContentWriter simpleWriter = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, false);
    simpleWriter.putContent("STEP 2");
    readerStep1 = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertEquals("Incorrect content", "STEP 1", readerStep1.getContentString());
    // Update the content
    nodeService.setProperty(contentNodeRef, ContentModel.PROP_CONTENT, simpleWriter.getContentData());
    ContentReader readerStep2 = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertEquals("Incorrect content", "STEP 2", readerStep2.getContentString());
    simpleWriter = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, false);
    simpleWriter.putContent("STEP 3");
    ContentReader readerStep3 = simpleWriter.getReader();
    assertEquals("Incorrect content", "STEP 3", readerStep3.getContentString());
    readerStep2 = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertEquals("Incorrect content", "STEP 2", readerStep2.getContentString());
    // Now get a ex-transaction writer but set the content property in a failing transaction
    // Notice that we have already written "STEP 3" to an underlying binary
    final ContentData simpleWriterData = simpleWriter.getContentData();
    RetryingTransactionCallback<Void> failToSetPropCallback = new RetryingTransactionCallback<Void>() {

        public Void execute() throws Throwable {
            nodeService.setProperty(contentNodeRef, ContentModel.PROP_CONTENT, simpleWriterData);
            throw new RuntimeException("aaa");
        }
    };
    try {
        transactionService.getRetryingTransactionHelper().doInTransaction(failToSetPropCallback);
    } catch (RuntimeException e) {
        if (!e.getMessage().equals("aaa")) {
            throw e;
        }
    }
    // The writer data should not have been cleaned up
    readerStep3 = simpleWriter.getReader();
    assertTrue("Content was cleaned up when it originated outside of the transaction", readerStep3.exists());
    assertEquals("Incorrect content", "STEP 3", readerStep3.getContentString());
    // The node's content must be unchanged
    readerStep2 = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertEquals("Incorrect content", "STEP 2", readerStep2.getContentString());
    // Test that rollback cleanup works for writers fetched in the same transaction
    final ContentReader[] readers = new ContentReader[1];
    RetryingTransactionCallback<Void> rollbackCallback = new RetryingTransactionCallback<Void>() {

        public Void execute() throws Throwable {
            ContentWriter writer = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
            writer.putContent("UNLUCKY CONTENT");
            ContentReader reader = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
            assertEquals("Incorrect content", "UNLUCKY CONTENT", reader.getContentString());
            assertEquals("Incorrect content", "UNLUCKY CONTENT", writer.getReader().getContentString());
            readers[0] = reader;
            throw new RuntimeException("aaa");
        }
    };
    try {
        transactionService.getRetryingTransactionHelper().doInTransaction(rollbackCallback);
    } catch (RuntimeException e) {
        if (!e.getMessage().equals("aaa")) {
            throw e;
        }
    }
    // Make sure that the content has been cleaned up
    assertFalse("Content was not cleaned up after having been created in-transaction", readers[0].exists());
}

80. RoutingContentServiceTest#testTransformation()

Project: community-edition
File: RoutingContentServiceTest.java
public void testTransformation() throws Exception {
    // commit node so that threads can see node
    txn.commit();
    txn = null;
    UserTransaction txn = getUserTransaction();
    txn.begin();
    txn.setRollbackOnly();
    // get a regular writer
    ContentWriter writer = contentService.getTempWriter();
    writer.setMimetype("text/xml");
    // write some stuff
    String content = "<blah></blah>";
    writer.putContent(content);
    // get a reader onto the content
    ContentReader reader = writer.getReader();
    // get a new writer for the transformation
    writer = contentService.getTempWriter();
    // no such conversion possible
    writer.setMimetype("audio/x-wav");
    try {
        contentService.transform(reader, writer);
        fail("Transformation attempted with invalid mimetype");
    } catch (NoTransformerException e) {
    }
    // at this point, the transaction is unusable
    txn.rollback();
    txn = getUserTransaction();
    txn.begin();
    txn.setRollbackOnly();
    writer.setMimetype("text/plain");
    ContentTransformer transformer = contentService.getTransformer(reader.getMimetype(), writer.getMimetype());
    assertNotNull("Expected a valid transformer", transformer);
    contentService.transform(reader, writer);
    // get the content from the writer
    reader = writer.getReader();
    assertEquals("Mimetype of target reader incorrect", writer.getMimetype(), reader.getMimetype());
    String contentCheck = reader.getContentString();
    assertEquals("Content check failed", content, contentCheck);
    txn.rollback();
}

81. RoutingContentServiceTest#testWriteToNodeWithoutAnyContentProperties()

Project: community-edition
File: RoutingContentServiceTest.java
public void testWriteToNodeWithoutAnyContentProperties() throws Exception {
    // previously, the node was populated with the mimetype, etc
    // check that the write has these
    ContentWriter writer = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, writer.getMimetype());
    assertEquals("UTF-16", writer.getEncoding());
    assertEquals(Locale.CHINESE, writer.getLocale());
    // now remove the content property from the node
    nodeService.setProperty(contentNodeRef, ContentModel.PROP_CONTENT, null);
    writer = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    assertNull(writer.getMimetype());
    assertEquals("UTF-8", writer.getEncoding());
    assertEquals(Locale.getDefault(), writer.getLocale());
    // now set it on the writer
    writer.setMimetype("text/plain");
    writer.setEncoding("UTF-16");
    writer.setLocale(Locale.FRENCH);
    String content = "The quick brown fox ...";
    writer.putContent(content);
    // the properties should have found their way onto the node
    ContentData contentData = (ContentData) nodeService.getProperty(contentNodeRef, ContentModel.PROP_CONTENT);
    assertEquals("metadata didn't get onto node", writer.getContentData(), contentData);
    // check that the reader's metadata is set
    ContentReader reader = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertEquals("Metadata didn't get set on reader", writer.getContentData(), reader.getContentData());
}

82. AbstractWritableContentStoreTest#testGetReader()

Project: community-edition
File: AbstractWritableContentStoreTest.java
/**
     * Checks that the various methods of obtaining a reader are supported.
     */
@Test
public synchronized void testGetReader() throws Exception {
    ContentStore store = getStore();
    ContentWriter writer = store.getWriter(ContentStore.NEW_CONTENT_CONTEXT);
    String contentUrl = writer.getContentUrl();
    // Check that a reader is available from the store
    ContentReader readerFromStoreBeforeWrite = store.getReader(contentUrl);
    assertNotNull("A reader must always be available from the store", readerFromStoreBeforeWrite);
    // check that a reader is available from the writer
    ContentReader readerFromWriterBeforeWrite = writer.getReader();
    assertNotNull("A reader must always be available from the writer", readerFromWriterBeforeWrite);
    String content = "Content for testGetReader";
    // write some content
    long before = System.currentTimeMillis();
    this.wait(1000L);
    writer.setMimetype("text/plain");
    writer.setEncoding("UTF-8");
    writer.setLocale(Locale.CHINESE);
    writer.putContent(content);
    this.wait(1000L);
    long after = System.currentTimeMillis();
    // get a reader from the store
    ContentReader readerFromStore = store.getReader(contentUrl);
    assertNotNull(readerFromStore);
    assertTrue(readerFromStore.exists());
    // Store-provided readers don't have context other than URLs
    // assertEquals(writer.getContentData(), readerFromStore.getContentData());
    assertEquals(content, readerFromStore.getContentString());
    // get a reader from the writer
    ContentReader readerFromWriter = writer.getReader();
    assertNotNull(readerFromWriter);
    assertTrue(readerFromWriter.exists());
    assertEquals(writer.getContentData(), readerFromWriter.getContentData());
    assertEquals(content, readerFromWriter.getContentString());
    // get another reader from the reader
    ContentReader readerFromReader = readerFromWriter.getReader();
    assertNotNull(readerFromReader);
    assertTrue(readerFromReader.exists());
    assertEquals(writer.getContentData(), readerFromReader.getContentData());
    assertEquals(content, readerFromReader.getContentString());
    // check that the length is correct
    int length = content.getBytes(writer.getEncoding()).length;
    assertEquals("Reader content length is incorrect", length, readerFromWriter.getSize());
    // check that the last modified time is correct
    long modifiedTimeCheck = readerFromWriter.getLastModified();
    // On some versionms of Linux (e.g. Centos) this test won't work as the 
    // modified time accuracy is only to the second.
    long beforeSeconds = before / 1000L;
    long afterSeconds = after / 1000L;
    long modifiedTimeCheckSeconds = modifiedTimeCheck / 1000L;
    assertTrue("Reader last modified is incorrect", beforeSeconds <= modifiedTimeCheckSeconds);
    assertTrue("Reader last modified is incorrect", modifiedTimeCheckSeconds <= afterSeconds);
}

83. TransferReporterImpl#writeDestinationReport()

Project: community-edition
File: TransferReporterImpl.java
/*
     */
public NodeRef writeDestinationReport(String transferName, TransferTarget target, File tempFile) {
    String title = transferName + "_destination";
    String description = "Transfer Destination Report - target: " + target.getName();
    String name = title + ".xml";
    logger.debug("writing destination transfer report " + title);
    logger.debug("parent node ref " + target.getNodeRef());
    Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
    properties.put(ContentModel.PROP_NAME, name);
    properties.put(ContentModel.PROP_TITLE, title);
    properties.put(ContentModel.PROP_DESCRIPTION, description);
    ChildAssociationRef ref = nodeService.createNode(target.getNodeRef(), ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name), TransferModel.TYPE_TRANSFER_REPORT_DEST, properties);
    ContentWriter writer = contentService.getWriter(ref.getChildRef(), ContentModel.PROP_CONTENT, true);
    writer.setLocale(Locale.getDefault());
    writer.setMimetype(MimetypeMap.MIMETYPE_XML);
    writer.setEncoding(DEFAULT_ENCODING);
    writer.putContent(tempFile);
    logger.debug("written " + name + ", " + ref.getChildRef());
    return ref.getChildRef();
}

84. RuleServiceImplTest#testOutBoundRuleTriggerForPendingDelete()

Project: community-edition
File: RuleServiceImplTest.java
/**
     * Test for MNT-11695
     */
public void testOutBoundRuleTriggerForPendingDelete() throws Exception {
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();
    // Create 1 folder with 2 folders inside
    NodeRef parentFolderNodeRef = this.nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("parentnode" + GUID.generate()), ContentModel.TYPE_FOLDER).getChildRef();
    NodeRef folder1NodeRef = this.nodeService.createNode(parentFolderNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("parentnode" + GUID.generate()), ContentModel.TYPE_FOLDER).getChildRef();
    NodeRef folder2NodeRef = this.nodeService.createNode(parentFolderNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("parentnode" + GUID.generate()), ContentModel.TYPE_FOLDER).getChildRef();
    // Create rule for folder1
    Rule testRule = new Rule();
    testRule.setRuleTypes(Collections.singletonList(RuleType.OUTBOUND));
    testRule.setTitle("RuleServiceTest" + GUID.generate());
    testRule.setDescription(DESCRIPTION);
    testRule.applyToChildren(true);
    Action action = this.actionService.createAction(CopyActionExecuter.NAME);
    action.setParameterValue(CopyActionExecuter.PARAM_DESTINATION_FOLDER, folder2NodeRef);
    testRule.setAction(action);
    this.ruleService.saveRule(folder1NodeRef, testRule);
    assertNotNull("Rule was not saved", testRule.getNodeRef());
    QName actionedQName = QName.createQName("actioneduponnode" + GUID.generate());
    // New node
    NodeRef actionedUponNodeRef = this.nodeService.createNode(folder1NodeRef, ContentModel.ASSOC_CHILDREN, actionedQName, ContentModel.TYPE_CONTENT).getChildRef();
    ContentWriter writer = this.contentService.getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true);
    writer.setMimetype("text/plain");
    writer.putContent("TestContent");
    txn.commit();
    // Remove the parent folder
    txn = transactionService.getUserTransaction();
    txn.begin();
    try {
        nodeService.deleteNode(parentFolderNodeRef);
    } catch (Exception e) {
        fail("The nodes should be deleted without errors, but exception was thrown: " + e);
    }
    txn.commit();
    txn = transactionService.getUserTransaction();
    txn.begin();
    assertFalse("The folder should be deleted.", nodeService.exists(parentFolderNodeRef));
    txn.commit();
    // Now test move action
    txn = transactionService.getUserTransaction();
    txn.begin();
    // Create 1 folder with 2 folders inside
    parentFolderNodeRef = this.nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("parentnode" + GUID.generate()), ContentModel.TYPE_FOLDER).getChildRef();
    folder1NodeRef = this.nodeService.createNode(parentFolderNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("parentnode" + GUID.generate()), ContentModel.TYPE_FOLDER).getChildRef();
    folder2NodeRef = this.nodeService.createNode(parentFolderNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("parentnode" + GUID.generate()), ContentModel.TYPE_FOLDER).getChildRef();
    // Create rule for folder1
    testRule = new Rule();
    testRule.setRuleTypes(Collections.singletonList(RuleType.OUTBOUND));
    testRule.setTitle("RuleServiceTest" + GUID.generate());
    testRule.setDescription(DESCRIPTION);
    testRule.applyToChildren(true);
    action = this.actionService.createAction(MoveActionExecuter.NAME);
    action.setParameterValue(CopyActionExecuter.PARAM_DESTINATION_FOLDER, folder2NodeRef);
    testRule.setAction(action);
    this.ruleService.saveRule(folder1NodeRef, testRule);
    assertNotNull("Rule was not saved", testRule.getNodeRef());
    actionedQName = QName.createQName("actioneduponnode" + GUID.generate());
    // New node
    actionedUponNodeRef = this.nodeService.createNode(folder1NodeRef, ContentModel.ASSOC_CHILDREN, actionedQName, ContentModel.TYPE_CONTENT).getChildRef();
    writer = this.contentService.getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true);
    writer.setMimetype("text/plain");
    writer.putContent("TestContent");
    txn.commit();
    // Remove the parent folder
    txn = transactionService.getUserTransaction();
    txn.begin();
    try {
        nodeService.deleteNode(parentFolderNodeRef);
    } catch (Exception e) {
        fail("The nodes should be deleted without errors, but exception was thrown: " + e);
    }
    txn.commit();
    txn = transactionService.getUserTransaction();
    txn.begin();
    assertFalse("The folder should be deleted.", nodeService.exists(parentFolderNodeRef));
    txn.commit();
}

85. StringExtractingContentTransformerTest#writeContent()

Project: community-edition
File: StringExtractingContentTransformerTest.java
/**
     * Writes some content using the mimetype and encoding specified.
     * 
     * @param mimetype String
     * @param encoding String
     * @return Returns a reader onto the newly written content
     */
private ContentReader writeContent(String mimetype, String encoding) {
    ContentWriter writer = new FileContentWriter(getTempFile());
    writer.setMimetype(mimetype);
    writer.setEncoding(encoding);
    // put content
    writer.putContent(SOME_CONTENT);
    // return a reader onto the new content
    return writer.getReader();
}

86. CreateTopicDialog#finishImpl()

Project: community-edition
File: CreateTopicDialog.java
@Override
protected String finishImpl(FacesContext context, String outcome) throws Exception {
    super.finishImpl(context, outcome);
    // do topic specific processing
    // get the node ref of the node that will contain the content
    NodeRef containerNodeRef = this.createdNode;
    // create a unique file name for the message content
    String fileName = ForumsBean.createPostFileName();
    FileInfo fileInfo = this.getFileFolderService().create(containerNodeRef, fileName, ForumModel.TYPE_POST);
    NodeRef postNodeRef = fileInfo.getNodeRef();
    if (logger.isDebugEnabled())
        logger.debug("Created post node with filename: " + fileName);
    // apply the titled aspect - title and description
    Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>(3, 1.0f);
    titledProps.put(ContentModel.PROP_TITLE, fileName);
    this.getNodeService().addAspect(postNodeRef, ContentModel.ASPECT_TITLED, titledProps);
    if (logger.isDebugEnabled())
        logger.debug("Added titled aspect with properties: " + titledProps);
    Map<QName, Serializable> editProps = new HashMap<QName, Serializable>(1, 1.0f);
    editProps.put(ApplicationModel.PROP_EDITINLINE, true);
    this.getNodeService().addAspect(postNodeRef, ApplicationModel.ASPECT_INLINEEDITABLE, editProps);
    if (logger.isDebugEnabled())
        logger.debug("Added inlineeditable aspect with properties: " + editProps);
    // get a writer for the content and put the file
    ContentWriter writer = getContentService().getWriter(postNodeRef, ContentModel.PROP_CONTENT, true);
    // set the mimetype and encoding
    writer.setMimetype(Repository.getMimeTypeForFileName(context, fileName));
    writer.setEncoding("UTF-8");
    writer.putContent(Utils.replaceLineBreaks(this.message, false));
    return outcome;
}

87. ImportDialog#addFileToRepository()

Project: community-edition
File: ImportDialog.java
/**
    * 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;
}

88. UploadContentServlet#doPut()

Project: community-edition
File: UploadContentServlet.java
/**
     * @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");
    }
}

89. VersionServiceImplTest#testScriptNodeRevert()

Project: community-edition
File: VersionServiceImplTest.java
/**
     * Test reverting from Share
     */
@SuppressWarnings("unused")
public void testScriptNodeRevert() {
    CheckOutCheckInService checkOutCheckIn = (CheckOutCheckInService) applicationContext.getBean("checkOutCheckInService");
    // Create a versionable node
    NodeRef versionableNode = createNewVersionableNode();
    NodeRef checkedOut = checkOutCheckIn.checkout(versionableNode);
    Version versionC1 = createVersion(checkedOut);
    // Create a new, first proper version
    ContentWriter contentWriter = this.contentService.getWriter(checkedOut, ContentModel.PROP_CONTENT, true);
    assertNotNull(contentWriter);
    contentWriter.putContent(UPDATED_CONTENT_1);
    nodeService.setProperty(checkedOut, PROP_1, VALUE_1);
    checkOutCheckIn.checkin(checkedOut, null, contentWriter.getContentUrl(), false);
    Version version1 = createVersion(versionableNode);
    checkedOut = checkOutCheckIn.checkout(versionableNode);
    // Create another new version
    contentWriter = this.contentService.getWriter(checkedOut, ContentModel.PROP_CONTENT, true);
    assertNotNull(contentWriter);
    contentWriter.putContent(UPDATED_CONTENT_2);
    nodeService.setProperty(checkedOut, PROP_1, VALUE_2);
    checkOutCheckIn.checkin(checkedOut, null, contentWriter.getContentUrl(), false);
    Version version2 = createVersion(versionableNode);
    checkedOut = checkOutCheckIn.checkout(versionableNode);
    // Check we're now up to two versions
    // (The version created on the working copy doesn't count)
    VersionHistory history = versionService.getVersionHistory(versionableNode);
    assertEquals(version2.getVersionLabel(), history.getHeadVersion().getVersionLabel());
    assertEquals(version2.getVersionedNodeRef(), history.getHeadVersion().getVersionedNodeRef());
    assertEquals(2, history.getAllVersions().size());
    Version[] versions = history.getAllVersions().toArray(new Version[2]);
    assertEquals("0.2", versions[0].getVersionLabel());
    assertEquals("0.1", versions[1].getVersionLabel());
    // Add yet another version
    contentWriter = this.contentService.getWriter(checkedOut, ContentModel.PROP_CONTENT, true);
    assertNotNull(contentWriter);
    contentWriter.putContent(UPDATED_CONTENT_3);
    nodeService.setProperty(checkedOut, PROP_1, VALUE_3);
    checkOutCheckIn.checkin(checkedOut, null, contentWriter.getContentUrl(), false);
    Version version3 = createVersion(versionableNode);
    // Verify that the version labels are as we expect them to be
    history = versionService.getVersionHistory(versionableNode);
    assertEquals(version3.getVersionLabel(), history.getHeadVersion().getVersionLabel());
    assertEquals(version3.getVersionedNodeRef(), history.getHeadVersion().getVersionedNodeRef());
    assertEquals(3, history.getAllVersions().size());
    versions = history.getAllVersions().toArray(new Version[3]);
    assertEquals("0.3", versions[0].getVersionLabel());
    assertEquals("0.2", versions[1].getVersionLabel());
    assertEquals("0.1", versions[2].getVersionLabel());
    // Create a ScriptNode as used in Share
    ServiceRegistry services = applicationContext.getBean(ServiceRegistry.class);
    ScriptNode scriptNode = new ScriptNode(versionableNode, services);
    assertEquals("0.3", nodeService.getProperty(scriptNode.getNodeRef(), ContentModel.PROP_VERSION_LABEL));
    assertEquals(VALUE_3, nodeService.getProperty(scriptNode.getNodeRef(), PROP_1));
    // Revert to version2
    // The content and properties will be the same as on Version 2, but we'll
    //  actually be given a new version number for it
    ScriptNode newNode = scriptNode.revert("History", false, version2.getVersionLabel());
    ContentReader contentReader = this.contentService.getReader(newNode.getNodeRef(), ContentModel.PROP_CONTENT);
    assertNotNull(contentReader);
    assertEquals(UPDATED_CONTENT_2, contentReader.getContentString());
    assertEquals(VALUE_2, nodeService.getProperty(newNode.getNodeRef(), PROP_1));
    // Will be a new version though - TODO Is this correct?
    assertEquals("0.4", nodeService.getProperty(newNode.getNodeRef(), ContentModel.PROP_VERSION_LABEL));
    // Revert to version1
    newNode = scriptNode.revert("History", false, version1.getVersionLabel());
    contentReader = this.contentService.getReader(newNode.getNodeRef(), ContentModel.PROP_CONTENT);
    assertNotNull(contentReader);
    assertEquals(UPDATED_CONTENT_1, contentReader.getContentString());
    assertEquals(VALUE_1, nodeService.getProperty(newNode.getNodeRef(), PROP_1));
    // Will be a new version though - TODO Is this correct?
    assertEquals("0.5", nodeService.getProperty(newNode.getNodeRef(), ContentModel.PROP_VERSION_LABEL));
    // All done
    setComplete();
    try {
        endTransaction();
    } catch (Throwable e) {
        fail("Transaction failed: " + e);
    }
}

90. VersionServiceImplTest#createComment()

Project: community-edition
File: VersionServiceImplTest.java
/**
     * This method was taken from the CommmentServiceImpl on the cloud branch
     * 
     * TODO: When this is merged to HEAD, please remove this method and use the one in CommmentServiceImpl
     */
private NodeRef createComment(final NodeRef discussableNode, String title, String comment, boolean suppressRollups) {
    if (comment == null) {
        throw new IllegalArgumentException("Must provide a non-null comment");
    }
    // This is what happens within e.g. comment.put.json.js when comments are submitted via the REST API.
    if (!nodeService.hasAspect(discussableNode, ForumModel.ASPECT_DISCUSSABLE)) {
        nodeService.addAspect(discussableNode, ForumModel.ASPECT_DISCUSSABLE, null);
    }
    if (!nodeService.hasAspect(discussableNode, ForumModel.ASPECT_COMMENTS_ROLLUP) && !suppressRollups) {
        nodeService.addAspect(discussableNode, ForumModel.ASPECT_COMMENTS_ROLLUP, null);
    }
    // Forum node is created automatically by DiscussableAspect behaviour.
    NodeRef forumNode = nodeService.getChildAssocs(discussableNode, ForumModel.ASSOC_DISCUSSION, QName.createQName(NamespaceService.FORUMS_MODEL_1_0_URI, "discussion")).get(0).getChildRef();
    final List<ChildAssociationRef> existingTopics = nodeService.getChildAssocs(forumNode, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "Comments"));
    NodeRef topicNode = null;
    if (existingTopics.isEmpty()) {
        Map<QName, Serializable> props = new HashMap<QName, Serializable>(1, 1.0f);
        props.put(ContentModel.PROP_NAME, "Comments");
        topicNode = nodeService.createNode(forumNode, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "Comments"), ForumModel.TYPE_TOPIC, props).getChildRef();
    } else {
        topicNode = existingTopics.get(0).getChildRef();
    }
    NodeRef postNode = nodeService.createNode(topicNode, ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS, ForumModel.TYPE_POST).getChildRef();
    nodeService.setProperty(postNode, ContentModel.PROP_CONTENT, new ContentData(null, MimetypeMap.MIMETYPE_TEXT_PLAIN, 0L, null));
    nodeService.setProperty(postNode, ContentModel.PROP_TITLE, title);
    ContentWriter writer = contentService.getWriter(postNode, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_HTML);
    writer.setEncoding("UTF-8");
    writer.putContent(comment);
    return postNode;
}

91. VersionServiceImplTest#addComment()

Project: community-edition
File: VersionServiceImplTest.java
private NodeRef addComment(NodeRef nr, String comment, boolean suppressRollups) {
    // This is what happens within e.g. comment.put.json.js when comments are submitted via the REST API.
    if (!nodeService.hasAspect(nr, ForumModel.ASPECT_DISCUSSABLE)) {
        nodeService.addAspect(nr, ForumModel.ASPECT_DISCUSSABLE, null);
    }
    if (!nodeService.hasAspect(nr, ForumModel.ASPECT_COMMENTS_ROLLUP) && !suppressRollups) {
        nodeService.addAspect(nr, ForumModel.ASPECT_COMMENTS_ROLLUP, null);
    }
    // Forum node is created automatically by DiscussableAspect behaviour.
    NodeRef forumNode = nodeService.getChildAssocs(nr, ForumModel.ASSOC_DISCUSSION, QName.createQName(NamespaceService.FORUMS_MODEL_1_0_URI, "discussion")).get(0).getChildRef();
    final List<ChildAssociationRef> existingTopics = nodeService.getChildAssocs(forumNode, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "Comments"));
    NodeRef topicNode = null;
    if (existingTopics.isEmpty()) {
        topicNode = nodeService.createNode(forumNode, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "Comments"), ForumModel.TYPE_TOPIC).getChildRef();
    } else {
        topicNode = existingTopics.get(0).getChildRef();
    }
    NodeRef postNode = nodeService.createNode(topicNode, ContentModel.ASSOC_CONTAINS, QName.createQName("comment" + System.currentTimeMillis()), ForumModel.TYPE_POST).getChildRef();
    nodeService.setProperty(postNode, ContentModel.PROP_CONTENT, new ContentData(null, MimetypeMap.MIMETYPE_TEXT_PLAIN, 0L, null));
    ContentWriter writer = contentService.getWriter(postNode, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.setEncoding("UTF-8");
    writer.putContent(comment);
    return postNode;
}

92. UserUsageTrackingComponentTest#addTextContent()

Project: community-edition
File: UserUsageTrackingComponentTest.java
private NodeRef addTextContent(NodeRef spaceRef, String fileName, String textData) {
    Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>();
    contentProps.put(ContentModel.PROP_NAME, fileName);
    ChildAssociationRef association = nodeService.createNode(spaceRef, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, fileName), ContentModel.TYPE_CONTENT, contentProps);
    NodeRef content = association.getChildRef();
    // add titled aspect (for Web Client display)
    Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>();
    titledProps.put(ContentModel.PROP_TITLE, fileName);
    titledProps.put(ContentModel.PROP_DESCRIPTION, fileName);
    this.nodeService.addAspect(content, ContentModel.ASPECT_TITLED, titledProps);
    ContentWriter writer = contentService.getWriter(content, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.setEncoding("UTF-8");
    writer.putContent(textData);
    return content;
}

93. UserUsageTest#updateTextContent()

Project: community-edition
File: UserUsageTest.java
private void updateTextContent(NodeRef contentRef, String textData) {
    ContentWriter writer = contentService.getWriter(contentRef, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.setEncoding("UTF-8");
    writer.putContent(textData);
}

94. MultiTDemoTest#addContent()

Project: community-edition
File: MultiTDemoTest.java
private NodeRef addContent(NodeRef spaceRef, String name, InputStream is, String mimeType) {
    Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>();
    contentProps.put(ContentModel.PROP_NAME, name);
    ChildAssociationRef association = nodeService.createNode(spaceRef, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name), ContentModel.TYPE_CONTENT, contentProps);
    NodeRef content = association.getChildRef();
    // add titled aspect (for Web Client display)
    Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>();
    titledProps.put(ContentModel.PROP_TITLE, name);
    titledProps.put(ContentModel.PROP_DESCRIPTION, name);
    this.nodeService.addAspect(content, ContentModel.ASPECT_TITLED, titledProps);
    ContentWriter writer = contentService.getWriter(content, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(mimeType);
    writer.setEncoding("UTF-8");
    writer.putContent(is);
    return content;
}

95. MultiTDemoTest#addContent()

Project: community-edition
File: MultiTDemoTest.java
private NodeRef addContent(NodeRef spaceRef, String name, String textData, String mimeType) {
    Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>();
    contentProps.put(ContentModel.PROP_NAME, name);
    ChildAssociationRef association = nodeService.createNode(spaceRef, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name), ContentModel.TYPE_CONTENT, contentProps);
    NodeRef content = association.getChildRef();
    // add titled aspect (for Web Client display)
    Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>();
    titledProps.put(ContentModel.PROP_TITLE, name);
    titledProps.put(ContentModel.PROP_DESCRIPTION, name);
    this.nodeService.addAspect(content, ContentModel.ASPECT_TITLED, titledProps);
    ContentWriter writer = contentService.getWriter(content, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(mimeType);
    writer.setEncoding("UTF-8");
    writer.putContent(textData);
    return content;
}

96. XSLTProcessorTest#createXmlFile()

Project: community-edition
File: XSLTProcessorTest.java
private FileInfo createXmlFile(NodeRef folder, String content) {
    String name = GUID.generate();
    FileInfo testXmlFile = fileFolderService.create(folder, name + ".xml", ContentModel.TYPE_CONTENT);
    ContentWriter writer = contentService.getWriter(testXmlFile.getNodeRef(), ContentModel.PROP_CONTENT, true);
    writer.setMimetype("text/xml");
    writer.setEncoding("UTF-8");
    writer.putContent(content);
    return testXmlFile;
}

97. SubscriptionServiceActivitiesTest#addTextContent()

Project: community-edition
File: SubscriptionServiceActivitiesTest.java
protected NodeRef addTextContent(String siteId, String name) {
    String textData = name;
    String mimeType = MimetypeMap.MIMETYPE_TEXT_PLAIN;
    Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>();
    contentProps.put(ContentModel.PROP_NAME, name);
    // ensure that the Document Library folder is pre-created so that test code can start creating content straight away.
    // At the time of writing V4.1 does not create this folder automatically, but Thor does
    NodeRef parentRef = siteService.getContainer(siteId, SiteService.DOCUMENT_LIBRARY);
    if (parentRef == null) {
        parentRef = siteService.createContainer(siteId, SiteService.DOCUMENT_LIBRARY, ContentModel.TYPE_FOLDER, null);
    }
    ChildAssociationRef association = nodeService.createNode(parentRef, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name), ContentModel.TYPE_CONTENT, contentProps);
    NodeRef content = association.getChildRef();
    // add titled aspect (for Web Client display)
    Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>();
    titledProps.put(ContentModel.PROP_TITLE, name);
    titledProps.put(ContentModel.PROP_DESCRIPTION, name);
    nodeService.addAspect(content, ContentModel.ASPECT_TITLED, titledProps);
    ContentWriter writer = contentService.getWriter(content, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(mimeType);
    writer.setEncoding("UTF-8");
    writer.putContent(textData);
    activityService.postActivity("org.alfresco.documentlibrary.file-added", siteId, "documentlibrary", content, name, ContentModel.PROP_CONTENT, parentRef);
    return content;
}

98. RuleServiceIntegrationTest#addContentToNode()

Project: community-edition
File: RuleServiceIntegrationTest.java
/**
     * Adds content to a given node. 
     * <p>
     * Used to trigger rules of type of incomming.
     * 
     * @param nodeRef  the node reference
     */
private void addContentToNode(NodeRef nodeRef) {
    ContentWriter contentWriter = CONTENT_SERVICE.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    contentWriter.setEncoding("UTF-8");
    assertNotNull(contentWriter);
    contentWriter.putContent(STANDARD_TEXT_CONTENT + System.currentTimeMillis());
}

99. RuleServiceImplTest#testCyclicAsyncRules()

Project: community-edition
File: RuleServiceImplTest.java
public void testCyclicAsyncRules() throws Exception {
    NodeRef nodeRef = createNewNode(this.rootNodeRef);
    // Create the first rule
    Map<String, Serializable> conditionProps = new HashMap<String, Serializable>();
    conditionProps.put(ComparePropertyValueEvaluator.PARAM_VALUE, "*.jpg");
    Map<String, Serializable> actionProps = new HashMap<String, Serializable>();
    actionProps.put(ImageTransformActionExecuter.PARAM_MIME_TYPE, MimetypeMap.MIMETYPE_IMAGE_GIF);
    actionProps.put(ImageTransformActionExecuter.PARAM_DESTINATION_FOLDER, nodeRef);
    actionProps.put(ImageTransformActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CHILDREN);
    actionProps.put(ImageTransformActionExecuter.PARAM_ASSOC_QNAME, ContentModel.ASSOC_CHILDREN);
    Rule rule = new Rule();
    rule.setRuleType(this.ruleType.getName());
    rule.setTitle("Convert from *.jpg to *.gif");
    rule.setExecuteAsynchronously(true);
    Action action = this.actionService.createAction(ImageTransformActionExecuter.NAME);
    action.setParameterValues(actionProps);
    ActionCondition actionCondition = this.actionService.createActionCondition(ComparePropertyValueEvaluator.NAME);
    actionCondition.setParameterValues(conditionProps);
    action.addActionCondition(actionCondition);
    rule.setAction(action);
    // Create the next rule
    Map<String, Serializable> conditionProps2 = new HashMap<String, Serializable>();
    conditionProps2.put(ComparePropertyValueEvaluator.PARAM_VALUE, "*.gif");
    Map<String, Serializable> actionProps2 = new HashMap<String, Serializable>();
    actionProps2.put(ImageTransformActionExecuter.PARAM_MIME_TYPE, MimetypeMap.MIMETYPE_IMAGE_JPEG);
    actionProps2.put(ImageTransformActionExecuter.PARAM_DESTINATION_FOLDER, nodeRef);
    actionProps2.put(ImageTransformActionExecuter.PARAM_ASSOC_QNAME, ContentModel.ASSOC_CHILDREN);
    Rule rule2 = new Rule();
    rule2.setRuleType(this.ruleType.getName());
    rule2.setTitle("Convert from *.gif to *.jpg");
    rule2.setExecuteAsynchronously(true);
    Action action2 = this.actionService.createAction(ImageTransformActionExecuter.NAME);
    action2.setParameterValues(actionProps2);
    ActionCondition actionCondition2 = this.actionService.createActionCondition(ComparePropertyValueEvaluator.NAME);
    actionCondition2.setParameterValues(conditionProps2);
    action2.addActionCondition(actionCondition2);
    rule2.setAction(action2);
    // Save the rules
    this.ruleService.saveRule(nodeRef, rule);
    this.ruleService.saveRule(nodeRef, rule);
    // Now create new content
    NodeRef contentNode = this.nodeService.createNode(nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{test}testnode"), ContentModel.TYPE_CONTENT).getChildRef();
    this.nodeService.setProperty(contentNode, ContentModel.PROP_NAME, "myFile.jpg");
    File file = AbstractContentTransformerTest.loadQuickTestFile("jpg");
    ContentWriter writer = this.contentService.getWriter(contentNode, ContentModel.PROP_CONTENT, true);
    writer.setEncoding("UTF-8");
    writer.setMimetype(MimetypeMap.MIMETYPE_IMAGE_JPEG);
    writer.putContent(file);
    setComplete();
    endTransaction();
//final NodeRef finalNodeRef = nodeRef;
// Check to see what has happened
//        ActionServiceImplTest.postAsyncActionTest(
//                this.transactionService,
//                10000, 
//                10, 
//                new AsyncTest()
//                {
//                    public boolean executeTest() 
//                    {
//                        List<ChildAssociationRef> assocs = RuleServiceImplTest.this.nodeService.getChildAssocs(finalNodeRef);
//                        for (ChildAssociationRef ref : assocs)
//                        {
//                            NodeRef child = ref.getChildRef();
//                            System.out.println("Child name: " + RuleServiceImplTest.this.nodeService.getProperty(child, ContentModel.PROP_NAME));
//                        }
//                        
//                        return true;
//                    };
//                });
}

100. RuleServiceCoverageTest#addContentToNode()

Project: community-edition
File: RuleServiceCoverageTest.java
/**
     * Adds content to a given node. 
     * <p>
     * Used to trigger rules of type of incomming.
     * 
     * @param nodeRef  the node reference
     */
private void addContentToNode(NodeRef nodeRef) {
    ContentWriter contentWriter = this.contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    contentWriter.setEncoding("UTF-8");
    assertNotNull(contentWriter);
    contentWriter.putContent(STANDARD_TEXT_CONTENT + System.currentTimeMillis());
}