Java Code Examples for org.alfresco.service.cmr.repository.ContentWriter

The following are top voted examples for showing how to use org.alfresco.service.cmr.repository.ContentWriter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: alfresco-repository   File: FullTest.java   Source Code and License 7 votes vote down vote up
@Test
public void canGuessMimeType()
{
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    
    ContentService contentService = (ContentService) ctx.getBean("ContentService");
    NodeService nodeService = (NodeService) ctx.getBean("NodeService");
    StoreRef storeRef = nodeService.createStore("workspace", getClass().getName()+UUID.randomUUID());
    NodeRef rootNodeRef = nodeService.getRootNode(storeRef);
    NodeRef nodeRef = nodeService.createNode(
                rootNodeRef,
                ContentModel.ASSOC_CHILDREN,
                QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, getClass().getSimpleName()),
                ContentModel.TYPE_CONTENT).getChildRef();

    ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    // Pre-condition of test is that we're testing with a potentially problematic BackingStoreAwareCacheWriter
    // rather than a FileContentWriter, which we would expect to work.
    assertTrue(writer instanceof BackingStoreAwareCacheWriter);
    
    String content = "This is some content";
    writer.putContent(content);
    writer.guessMimetype("myfile.txt");
    
    assertEquals("text/plain", writer.getMimetype());
}
 
Example 2
Project: alfresco-repository   File: RoutingContentServiceTest.java   Source Code and License 6 votes vote down vote up
/**
 * 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());
}
 
Example 3
Project: alfresco-repository   File: AbstractWritableContentStoreTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 4
Project: alfresco-repository   File: RoutingContentStoreTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGeneralUse()
{
    for (int i = 0 ; i < 20; i++)
    {
        ContentContext contentContext = new ContentContext(null, null);
        ContentWriter writer = routingStore.getWriter(contentContext);
        String content = "This was generated by " + this.getClass().getName() + "#testGeneralUse number " + i;
        writer.putContent(content);
        // Check that it exists
        String contentUrl = writer.getContentUrl();
        checkForContent(contentUrl, content);
        
        // Now go direct to the routing store and check that it is able to find the appropriate URLs
        ContentReader reader = routingStore.getReader(contentUrl);
        assertNotNull("Null reader returned", reader);
        assertTrue("Reader should be onto live content", reader.exists());
    }
}
 
Example 5
Project: alfresco-repository   File: UserUsageTest.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 6
Project: alfresco-repository   File: AccessAuditorTest.java   Source Code and License 6 votes vote down vote up
@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);
    assertEquals("UPDATE CONTENT", auditMap.get("action")); // TODO Should be UPDATE CONTENT
    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"));
}
 
Example 7
Project: alfresco-repository   File: AbstractWritableContentStoreTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testStringTruncation() throws Exception
{
    String content = "1234567890";
    
    ContentWriter writer = getWriter();
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.setEncoding("UTF-8");  // shorter format i.t.o. bytes used
    // 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);
}
 
Example 8
Project: alfresco-repository   File: AggregatingContentStoreTest.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * This implementation creates some content in the store and returns the new content URL.
 */
protected String getExistingContentUrl()
{
    ContentWriter writer = getWriter();
    writer.putContent("Content for getExistingContentUrl");
    return writer.getContentUrl();
}
 
Example 9
Project: alfresco-repository   File: ContentServiceImplTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test getWriter
 */
public void testGetWriter()
{
    // Create a new versionable node
    NodeRef versionableNode = createNewVersionableNode();
    
    // Create a new version
    Version version = createVersion(versionableNode, this.versionProperties);
    
    // Get writer is not supported by the version content service
    try
    {
        ContentWriter contentWriter = this.contentService.getWriter(
                version.getFrozenStateNodeRef(),
                ContentModel.PROP_CONTENT,
                true);
        contentWriter.putContent("bobbins");
        fail("This operation is not supported.");
    }
    catch (Exception exception)
    {
        // An exception should be raised
    }
}
 
Example 10
Project: alfresco-repository   File: MediaWikiContentTransformerTest.java   Source Code and License 6 votes vote down vote up
public void testMediaWikiToHTML() throws Exception
{
   File input = TempFileProvider.createTempFile("mediaWikiTest", ".mw");
   FileOutputStream fos = new FileOutputStream(input);
   fos.write(WIKI_TEXT.getBytes());
   fos.close();
   
   File output = TempFileProvider.createTempFile("mediaWikiTest", ".htm");
   
   ContentReader contentReader = new FileContentReader(input);
   contentReader.setMimetype(MimetypeMap.MIMETYPE_TEXT_MEDIAWIKI);
   contentReader.setEncoding("UTF-8");
   
   ContentWriter contentWriter = new FileContentWriter(output);
   contentWriter.setMimetype(MimetypeMap.MIMETYPE_HTML);
   contentWriter.setEncoding("UTF-8");
   
   transformer.transform(contentReader, contentWriter);
   
   String line = null;
   BufferedReader reader = new BufferedReader(new FileReader(output));
   while ((line = reader.readLine()) != null) 
   {
       System.out.println(line);
   }
}
 
Example 11
Project: alfresco-repository   File: ActionServiceImpl2Test.java   Source Code and License 6 votes vote down vote up
private File loadAndAddQuickFileAsManager(final NodeRef nodeRef, final String quickFileName, final String mimeType)
        throws IOException
{
    final File file = AbstractContentTransformerTest.loadNamedQuickTestFile(quickFileName);

    if (file == null) { return null; }

    // Set authentication to SiteManager and add a file
    AuthenticationUtil.setFullyAuthenticatedUser(testSiteAndMemberInfo.siteManager);
    transactionHelper.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            nodeService.setProperty(nodeRef, ContentModel.PROP_NAME, quickFileName);

            ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(mimeType);
            writer.setEncoding("UTF-8");
            writer.putContent(file);

            return null;
        }
    });

    return file;
}
 
Example 12
Project: alfresco-repository   File: AbstractContentTransformer2.java   Source Code and License 6 votes vote down vote up
/**
 * Convenience method to check the transformability of a transformation
 * 
 * @param reader    content reader
 * @param writer    content writer
 * @param options   transformation options
 * @throws AlfrescoRuntimeException if the the transformation isn't supported
 */
protected void checkTransformable(ContentReader reader, ContentWriter writer, TransformationOptions options)
{
    String sourceMimetype = getMimetype(reader);
    String targetMimetype = getMimetype(writer);
    long sourceSize = reader.getSize();
    boolean transformable = isTransformable(sourceMimetype, sourceSize, targetMimetype, options);
    if (transformable == false)
    {
        // This method is only called once a transformer has been selected, so it should be able to
        // handle the mimetypes but might not be able to handle all the limits as it might be part of
        // of a complex (compound) transformer. So report the max size if set.
        long maxSourceSizeKBytes = getMaxSourceSizeKBytes(sourceMimetype, targetMimetype, options);
        boolean sizeOkay = maxSourceSizeKBytes < 0 || (maxSourceSizeKBytes > 0 && sourceSize <= maxSourceSizeKBytes*1024);
        AlfrescoRuntimeException e = new UnsupportedTransformationException("Unsupported transformation: " +
                getBeanName()+' '+sourceMimetype+" to "+targetMimetype+' '+
                (sizeOkay
                ? ""
                : transformerDebug.fileSize(sourceSize)+" > "+ transformerDebug.fileSize(maxSourceSizeKBytes*1024)));
        throw transformerDebug.setCause(e);
    }
    // it all checks out OK
}
 
Example 13
Project: alfresco-repository   File: VirtualizationIntegrationTest.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 14
Project: alfresco-repository   File: EMLTransformerTest.java   Source Code and License 6 votes vote down vote up
/**
 * 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));
}
 
Example 15
Project: alfresco-repository   File: FullTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 16
Project: alfresco-repository   File: RoutingContentServiceTest.java   Source Code and License 6 votes vote down vote up
/**
 * 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());
}
 
Example 17
Project: alfresco-repository   File: AbstractWritableContentStoreTest.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 18
Project: alfresco-remote-api   File: RepoService.java   Source Code and License 6 votes vote down vote up
public NodeRef addUserDescription(final String personId, final TestNetwork network, final String personDescription)
{
	return AuthenticationUtil.runAsSystem(new RunAsWork<NodeRef>()
	{
		//@Override
		public NodeRef doWork() throws Exception
		{
			NodeRef userRef = personService.getPersonOrNull(personId);
			if (userRef == null)
			{
				throw new AuthenticationException("User name does not exist: " + personId);
			}

			ContentWriter writer = contentService.getWriter(userRef, ContentModel.PROP_PERSONDESC, true);
			writer.setMimetype(MimetypeMap.MIMETYPE_HTML);
			writer.putContent(personDescription);

			log("Updated person description " + personId + (network != null ? " in network " + network : ""));
			return userRef;
		}
	});
}
 
Example 19
Project: alfresco-repository   File: AbstractWritableContentStoreTest.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 20
Project: alfresco-repository   File: ImapServiceImplTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test attachment extraction with a TNEF message
 * @throws Exception
 */
public void testAttachmentExtraction() throws Exception
{
    AuthenticationUtil.setRunAsUserSystem();
    /**
     * Load a TNEF message
     */
    ClassPathResource fileResource = new ClassPathResource("imap/test-tnef-message.eml");
    assertNotNull("unable to find test resource test-tnef-message.eml", fileResource);
    InputStream is = new FileInputStream(fileResource.getFile());
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()), is);

    NodeRef companyHomeNodeRef = findCompanyHomeNodeRef();

    FileInfo f1 = fileFolderService.create(companyHomeNodeRef, "ImapServiceImplTest", ContentModel.TYPE_FOLDER);
    FileInfo f2 = fileFolderService.create(f1.getNodeRef(), "test-tnef-message.eml", ContentModel.TYPE_CONTENT);
    
    ContentWriter writer = fileFolderService.getWriter(f2.getNodeRef());
    writer.putContent(new FileInputStream(fileResource.getFile()));
    
    imapService.extractAttachments(f2.getNodeRef(), message);

    List<AssociationRef> targetAssocs = nodeService.getTargetAssocs(f2.getNodeRef(), ImapModel.ASSOC_IMAP_ATTACHMENTS_FOLDER);
    assertTrue("attachment folder is found", targetAssocs.size() == 1);
    NodeRef attachmentFolderRef = targetAssocs.get(0).getTargetRef();
    
    assertNotNull(attachmentFolderRef);

    List<FileInfo> files = fileFolderService.listFiles(attachmentFolderRef);
    assertTrue("three files not found", files.size() == 3);

}
 
Example 21
Project: alfresco-repository   File: FileContentStoreTest.java   Source Code and License 6 votes vote down vote up
/**
 * 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)
    {
        // expected
    }
}
 
Example 22
Project: alfresco-repository   File: ScriptNode.java   Source Code and License 6 votes vote down vote up
/**
 * Delete the content stream
 */
public void delete()
{
    ContentService contentService = services.getContentService();
    ContentWriter writer = contentService.getWriter(nodeRef, this.property, true);
    OutputStream output = writer.getContentOutputStream();
    try
    {
        output.close();
    }
    catch (IOException e)
    {
        // NOTE: fall-through
    }
    writer.setMimetype(null);
    writer.setEncoding(null);
    
    // update cached variables after putContent()
    updateContentData(true);
}
 
Example 23
Project: alfresco-repository   File: FailoverContentTransformerTest.java   Source Code and License 6 votes vote down vote up
@Override
protected void transformInternal(ContentReader reader,
        ContentWriter writer, TransformationOptions options)
        throws Exception
{
    // Do not actually perform any transformation. The test above is only interested in whether
    // an exception is thrown and handled.
    if (logger.isInfoEnabled())
    {
        logger.info(springBeanName + " is attempting a transformation");
    }

    reader.getContentString();
    
    if (alwaysFail)
    {
        throw new AlfrescoRuntimeException("Test code intentionally failed method call.");
    }
    else
    {
        return;
    }
}
 
Example 24
Project: alfresco-remote-api   File: RepoService.java   Source Code and License 5 votes vote down vote up
public NodeRef createDocument(final NodeRef parentNodeRef, final String name, final String content)
  {
NodeRef nodeRef = fileFolderService.create(parentNodeRef, name, ContentModel.TYPE_CONTENT).getNodeRef();
ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
writer.putContent(content);

return nodeRef;
  }
 
Example 25
Project: alfresco-repository   File: XSLTRenderingEngineTest.java   Source Code and License 5 votes vote down vote up
private FileInfo createXmlFile(NodeRef folder, String filename, String content)
{
    FileInfo testXmlFile = fileFolderService.create(folder, filename, 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;
}
 
Example 26
Project: alfresco-repository   File: SlowContentStore.java   Source Code and License 5 votes vote down vote up
@Override
protected ContentWriter getWriterInternal(ContentReader existingContentReader, String newContentUrl)
{
    if (newContentUrl == null)
        newContentUrl = FileContentStore.createNewFileStoreUrl() + ".slow";
    
    return new SlowWriter(newContentUrl, existingContentReader);
}
 
Example 27
Project: alfresco-repository   File: RoutingContentServiceTest.java   Source Code and License 5 votes vote down vote up
/**
 * Checks what happens when the physical content disappears
 */
public void testMissingContent() throws Exception
{
    File tempFile = TempFileProvider.createTempFile(getName(), ".txt");
    
    ContentWriter writer = new FileContentWriter(tempFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.setEncoding("UTF-8");
    writer.putContent("What about the others?  Buckwheats!");
    // check
    assertTrue("File does not exist", tempFile.exists());
    assertTrue("File not written to", tempFile.length() > 0);
    
    // update the node with this new info 
    ContentData contentData = writer.getContentData();
    nodeService.setProperty(contentNodeRef, ContentModel.PROP_CONTENT, contentData);
    
    // delete the content
    tempFile.delete();
    assertFalse("File not deleted", tempFile.exists());
    
    // now attempt to get the reader for the node
    ContentReader reader = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertFalse("Reader should indicate that content is missing", reader.exists());
    
    // check the indexing doesn't spank everthing
    txn.commit();
    txn = null;

    // cleanup
    txn = getUserTransaction();
    txn.begin();
    nodeService.deleteNode(contentNodeRef);
    txn.commit();
    txn = null;
}
 
Example 28
Project: alfresco-repository   File: UpdateAuditTemplatePatch.java   Source Code and License 5 votes vote down vote up
private void makeCopy(NodeRef nodeRef)
{
    InputStream resource = getClass().getClassLoader().getResourceAsStream(fileName);
    if (resource != null)
    {
        ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
        writer.setEncoding("UTF-8");
        writer.setMimetype(TEXT_CONTENT_MIMETYPE);
        writer.putContent(resource);
    }
    else throw new PatchException("Resource '"+fileName+"' not found");
}
 
Example 29
Project: alfresco-repository   File: FixTemplatePatch.java   Source Code and License 5 votes vote down vote up
private void updateContent(NodeRef nodeRef)
{
    // Make versionable
    nodeService.addAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE, null);
    
    // Update content
    InputStream is = this.getClass().getClassLoader().getResourceAsStream(source);
    if (is != null)
    {
        ContentWriter contentWriter = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
        contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        contentWriter.setEncoding("UTF-8");
        contentWriter.putContent(is);
    }
}
 
Example 30
Project: alfresco-repository   File: ContentTransformerRegistryTest.java   Source Code and License 5 votes vote down vote up
/**
 * Just notches up some average times
 */
public void transformInternal(
        ContentReader reader,
        ContentWriter writer,
        TransformationOptions options) throws Exception
{
    // just update the transformation time
    super.recordTime(sourceMimetype, targetMimetype, transformationTime);
}
 
Example 31
Project: alfresco-repository   File: LocalContentServiceHelper.java   Source Code and License 5 votes vote down vote up
@Override
public void updateContent(final NodeRef downloadNode, final File archiveFile) throws ContentIOException, FileNotFoundException, IOException
{
    //RunAsSystem to mimic clustered behavior, and bypass quotas when using S3 storage.
    AuthenticationUtil.runAsSystem(new RunAsWork<Object>()
    {
        @Override
        public Object doWork() throws Exception
        {
            ContentWriter writer = contentService.getWriter(downloadNode, ContentModel.PROP_CONTENT, true);
            FileCopyUtils.copy(new FileInputStream(archiveFile), writer.getContentOutputStream());
            return null;
        }
    });
}
 
Example 32
Project: alfresco-repository   File: RepoPrimaryManifestProcessorImpl.java   Source Code and License 5 votes vote down vote up
/**
 * @param nodeToUpdate NodeRef
 * @param contentProps Map<QName, Serializable>
 * @return true if any content property has been updated for the needToUpdate node
 */
private boolean writeContent(NodeRef nodeToUpdate, Map<QName, Serializable> contentProps)
{
    boolean contentUpdated = false;
    File stagingDir = getStagingFolder();
    for (Map.Entry<QName, Serializable> contentEntry : contentProps.entrySet())
    {
        ContentData contentData = (ContentData) contentEntry.getValue();
        String contentUrl = contentData.getContentUrl();
        if(contentUrl == null || contentUrl.isEmpty())
        {
            log.debug("content data is null or empty:" + nodeToUpdate);
            ContentData cd = new ContentData(null, null, 0, null);
            nodeService.setProperty(nodeToUpdate, contentEntry.getKey(), cd);
            contentUpdated = true;
        }
        else
        {
            String fileName = TransferCommons.URLToPartName(contentUrl);
            File stagedFile = new File(stagingDir, fileName);
            if (!stagedFile.exists())
            {
                error(MSG_REFERENCED_CONTENT_FILE_MISSING);
            }
            ContentWriter writer = contentService.getWriter(nodeToUpdate, contentEntry.getKey(), true);
            writer.setEncoding(contentData.getEncoding());
            writer.setMimetype(contentData.getMimetype());
            writer.setLocale(contentData.getLocale());
            writer.putContent(stagedFile);
            contentUpdated = true;
        }
    }
    return contentUpdated;
}
 
Example 33
Project: alfresco-repository   File: TransferSummaryReportImpl.java   Source Code and License 5 votes vote down vote up
protected Writer createUnderlyingLogWriter(String transferId)
{
    if (reportFile == null)
    {
        reportFile = createTransferRecord(transferId);
    }
    ContentWriter contentWriter = contentService.getWriter(reportFile, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_XML);
    contentWriter.setEncoding("UTF-8");
    return Channels.newWriter(contentWriter.getWritableChannel(), "UTF-8");
}
 
Example 34
Project: alfresco-repository   File: CopyServiceImplTest.java   Source Code and License 5 votes vote down vote up
/**
 * https://issues.alfresco.com/jira/browse/ALF-17549
 */
public void testALF17549() throws Exception
{
    permissionService.setPermission(rootNodeRef, USER_1, PermissionService.COORDINATOR, true);

    AuthenticationUtil.setRunAsUser(USER_1);

    String sourceName = "sourceNode.txt";
    Map<QName, Serializable> props = new HashMap<QName, Serializable>();

    props.put(ContentModel.PROP_NAME, sourceName);

    NodeRef sourceNodeRef = nodeService.createNode(this.rootNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}" + sourceName), ContentModel.TYPE_CONTENT, props)
            .getChildRef();

    ContentWriter writer = contentService.getWriter(sourceNodeRef, ContentModel.PROP_CONTENT, true);
    writer.setEncoding("UTF-8");
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.putContent("This is sample text content for unit test.");

    NodeRef targetNodeRef = nodeService.createNode(this.rootNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}targetNode"), ContentModel.TYPE_FOLDER)
            .getChildRef();

    List<ChildAssociationRef> childAssoc = nodeService.getChildAssocs(targetNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}sourceNode.html"));

    assertEquals(0, childAssoc.size());

    Action action = this.actionService.createAction(TransformActionExecuter.NAME);

    action.setParameterValue(TransformActionExecuter.PARAM_MIME_TYPE, MimetypeMap.MIMETYPE_HTML);
    action.setParameterValue(TransformActionExecuter.PARAM_DESTINATION_FOLDER, targetNodeRef);
    action.setParameterValue(TransformActionExecuter.PARAM_ASSOC_QNAME, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "copy"));
    action.setParameterValue(TransformActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CONTAINS);
    actionService.executeAction(action, sourceNodeRef);

    childAssoc = nodeService.getChildAssocs(targetNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}sourceNode.html"));

    assertEquals(1, childAssoc.size());
}
 
Example 35
Project: alfresco-repository   File: AbstractRenderingEngine.java   Source Code and License 5 votes vote down vote up
public ContentWriter makeContentWriter()
{
    ContentWriter contentWriter = contentService.getWriter(getDestinationNode(), renditionContentProperty, true);
    String mimetype = getTargetMimeType(this);
    contentWriter.setMimetype(mimetype);
    String encoding = getTargetEncoding(this);
    contentWriter.setEncoding(encoding);
    return contentWriter;
}
 
Example 36
Project: alfresco-repository   File: VersionServiceImplTest.java   Source Code and License 5 votes vote down vote up
private NodeRef addComment(NodeRef nr, String comment, boolean suppressRollups)
{
    // There is no CommentService, so we have to create the node structure by hand.
    // 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;
}
 
Example 37
Project: alfresco-repository   File: XSLTProcessorTest.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 38
Project: alfresco-repository   File: TikaPoweredContainerExtractor.java   Source Code and License 5 votes vote down vote up
@Override
public void handle(String filename, MediaType mediaType,
      InputStream stream) {
   // Do we want it?
   if(acceptTypes == null || acceptTypes.contains(mediaType)) 
   {
      // Ensure we have a filename
      if(filename == null) 
      {
         anonymousCount++;
         filename = "embedded"+anonymousCount+"."+mediaType.getSubtype();
      }
      
      logger.info("Extracting embedded " + mediaType +  " entry " + filename);
      
      // Save it
      Map<QName,Serializable> properties = new HashMap<QName,Serializable>();
      properties.put(ContentModel.PROP_NAME, filename);
      NodeRef node = nodeService.createNode(
            folder,
            ContentModel.ASSOC_CONTAINS,
            QName.createQName(filename),
            ContentModel.TYPE_CONTENT,
            properties
      ).getChildRef();
      
      ContentWriter writer = contentService.getWriter(
            node, ContentModel.PROP_CONTENT, true
      );
      writer.setMimetype(mediaType.toString());
      writer.putContent(stream);
   }
   else
   {
      logger.info("Skipping embedded " + mediaType +  " entry " + filename);
   }
}
 
Example 39
Project: alfresco-repository   File: ComparePropertyValueEvaluatorTest.java   Source Code and License 5 votes vote down vote up
public void testContentPropertyComparisons()
{
    ActionConditionImpl condition = new ActionConditionImpl(GUID.generate(), ComparePropertyValueEvaluator.NAME);
    condition.setParameterValue(ComparePropertyValueEvaluator.PARAM_PROPERTY, ContentModel.PROP_CONTENT);
    
    // 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_CONTENT_PROPERTY, ContentPropertyName.MIME_TYPE.toString());
    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));
    
    // Test matching the encoding
    condition.setParameterValue(ComparePropertyValueEvaluator.PARAM_CONTENT_PROPERTY, ContentPropertyName.ENCODING.toString());
    condition.setParameterValue(ComparePropertyValueEvaluator.PARAM_VALUE, "UTF-8");
    assertTrue(this.evaluator.evaluate(condition, this.nodeRef));
    condition.setParameterValue(ComparePropertyValueEvaluator.PARAM_VALUE, "UTF-16");
    assertFalse(this.evaluator.evaluate(condition, this.nodeRef));
    
    // Test comparision to the size of the content
    condition.setParameterValue(ComparePropertyValueEvaluator.PARAM_CONTENT_PROPERTY, ContentPropertyName.SIZE.toString());
    condition.setParameterValue(ComparePropertyValueEvaluator.PARAM_OPERATION, ComparePropertyValueOperation.LESS_THAN.toString());
    condition.setParameterValue(ComparePropertyValueEvaluator.PARAM_VALUE, 50);
    assertTrue(this.evaluator.evaluate(condition, this.nodeRef));
    condition.setParameterValue(ComparePropertyValueEvaluator.PARAM_VALUE, 2);
    assertFalse(this.evaluator.evaluate(condition, this.nodeRef));
    
    
}
 
Example 40
Project: alfresco-repository   File: AbstractWritableContentStoreTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testMimetypAndEncodingAndLocale() throws Exception
{
    ContentWriter writer = getWriter();
    // set mimetype and encoding
    writer.setMimetype("text/plain");
    writer.setEncoding("UTF-16");
    writer.setLocale(Locale.CHINESE);
    
    // create a UTF-16 string
    String content = "A little bit o' this and a little bit o' that";
    byte[] bytesUtf16 = content.getBytes("UTF-16");
    // write the bytes directly to the writer
    OutputStream os = writer.getContentOutputStream();
    os.write(bytesUtf16);
    os.close();
    
    // now get a reader from the writer
    ContentReader reader = writer.getReader();
    assertEquals("Writer -> Reader content URL mismatch", writer.getContentUrl(), reader.getContentUrl());
    assertEquals("Writer -> Reader mimetype mismatch", writer.getMimetype(), reader.getMimetype());
    assertEquals("Writer -> Reader encoding mismatch", writer.getEncoding(), reader.getEncoding());
    assertEquals("Writer -> Reader locale mismatch", writer.getLocale(), reader.getLocale());
    
    // now get the string directly from the reader
    String contentCheck = reader.getContentString();     // internally it should have taken care of the encoding
    assertEquals("Encoding and decoding of strings failed", content, contentCheck);
}
 
Example 41
Project: alfresco-repository   File: StringExtractingContentTransformerTest.java   Source Code and License 5 votes vote down vote up
/**
 * 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();
}
 
Example 42
Project: alfresco-repository   File: AbstractWritableContentStoreTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests random access reading
 * <p>
 * Only executes if the reader implements {@link RandomAccessContent}.
 */
@Test
public void testRandomAccessRead() throws Exception
{
    ContentWriter writer = getWriter();
    // put some content
    String content = "ABC";
    byte[] bytes = content.getBytes();
    writer.putContent(content);
    ContentReader reader = writer.getReader();
    
    FileChannel fileChannel = reader.getFileChannel();
    assertNotNull("No channel given", fileChannel);
    
    // check that no other content access is allowed
    try
    {
        reader.getReadableChannel();
        fail("Second channel access allowed");
    }
    catch (RuntimeException e)
    {
        // expected
    }
    
    // read the content
    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
    int count = fileChannel.read(buffer);
    assertEquals("Incorrect number of bytes read", bytes.length, count);
    // transfer back to array
    buffer.rewind();
    buffer.get(bytes);
    String checkContent = new String(bytes);
    assertEquals("Content read failure", content, checkContent);
    fileChannel.close();
}
 
Example 43
Project: alfresco-repository   File: AccessAuditorTest.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 44
Project: alfresco-repository   File: MultiTDemoTest.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 45
Project: alfresco-repository   File: FullTest.java   Source Code and License 5 votes vote down vote up
@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());
}
 
Example 46
Project: alfresco-repository   File: MediaWikiContentTransformer.java   Source Code and License 5 votes vote down vote up
/**
  * @see org.alfresco.repo.content.transform.AbstractContentTransformer2#transformInternal(org.alfresco.service.cmr.repository.ContentReader, org.alfresco.service.cmr.repository.ContentWriter, org.alfresco.service.cmr.repository.TransformationOptions)
  */
public void transformInternal(ContentReader reader, ContentWriter writer,  TransformationOptions options)
        throws Exception
{
    String imageURL = "{$image}";
    String pageURL = "${title}";
    
    // If we have context about the destination of the transformation then use it
    if (options.getTargetNodeRef() != null)
    {
        NodeRef parentNodeRef = this.nodeService.getPrimaryParent(options.getTargetNodeRef()).getParentRef();
        
        StringBuffer folderPath = new StringBuffer(256);
        List<FileInfo> fileInfos = this.fileFolderService.getNamePath(null, parentNodeRef);
        for (FileInfo fileInfo : fileInfos)
        {
            folderPath.append(fileInfo.getName()).append("/");
        }
        
        pageURL = "/alfresco/d/d?path=" + folderPath + "${title}.html";
        imageURL = "/alfresco/d/d?path=" + folderPath + "Images/${image}";
    }
    
    // Create the wikiModel and set the title and image link URL's
    AlfrescoWikiModel wikiModel = new AlfrescoWikiModel(imageURL, pageURL);
    
    // Render the wiki content as HTML
    writer.putContent(wikiModel.render(reader.getContentString()));
}
 
Example 47
Project: alfresco-repository   File: AggregatingContentStoreTest.java   Source Code and License 5 votes vote down vote up
public void testAddContent() throws Exception
{
    ContentWriter writer = getWriter();
    writer.putContent(SOME_CONTENT);
    String contentUrl = writer.getContentUrl();
    
    checkForUrl(contentUrl, true);
}
 
Example 48
Project: alfresco-repository   File: TemporaryNodes.java   Source Code and License 5 votes vote down vote up
/**
 * This method creates a cm:content NodeRef whose content is taken from the named Alfresco 'quick' file and adds it to the internal
 * list of NodeRefs to be tidied up by the rule.
 * This method will be run in its own transaction and will be run with the specified user as the fully authenticated user,
 * thus ensuring the named user is the cm:creator of the new node.
 *
 * @param quickFileName the file name of the quick file - will also be the cm:name of the new node.
 * @param parentNode the parent node
 * @param nodeCreator the username of the person who will create the node
 * @return the newly created NodeRef.
 * @since 4.1.4
 */
public NodeRef createQuickFileByName(final String quickFileName, final NodeRef parentNode, final String nodeCreator)
{
    final MimetypeMap mimetypeService = (MimetypeMap) appContextRule.getApplicationContext().getBean("mimetypeService");
    final RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) appContextRule.getApplicationContext().getBean("retryingTransactionHelper");
    
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(nodeCreator);
    
    NodeRef newNodeRef = transactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            final NodeRef result = createNode(quickFileName, parentNode, ContentModel.TYPE_CONTENT);
            
            File quickFile = AbstractContentTransformerTest.loadNamedQuickTestFile(quickFileName);
            
            ContentService contentService = appContextRule.getApplicationContext().getBean("contentService", ContentService.class);
            ContentWriter writer = contentService.getWriter(result, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(mimetypeService.guessMimetype(quickFileName));
            writer.setEncoding("UTF-8");
            writer.putContent(quickFile);
            
            return result;
        }
    });
    
    AuthenticationUtil.popAuthentication();
    
    this.temporaryNodeRefs.add(newNodeRef);
    return newNodeRef;
}
 
Example 49
Project: alfresco-repository   File: CMMDownloadTestUtil.java   Source Code and License 5 votes vote down vote up
public synchronized void cleanup()
{
    if (isExtFolderCreated)
    {
        transactionHelper.doInTransaction(new RetryingTransactionCallback<Void>()
        {
            @Override
            public Void execute() throws Throwable
            {
                nodeService.deleteNode(extensionsNodeRef);
                return null;
            }
        });

        logger.info("Deleted 'cm:extensions' folder within the 'app:company_home/st:sites/cm:surf-config");
    }
    else if (originalShareExtFile != null)
    {
        transactionHelper.doInTransaction(new RetryingTransactionCallback<Void>()
        {
            @Override
            public Void execute() throws Throwable
            {
                ContentWriter writer = contentService.getWriter(sharePersistedExtNodeRef, ContentModel.PROP_CONTENT, true);
                writer.setMimetype(MimetypeMap.MIMETYPE_XML);
                writer.setEncoding("UTF-8");
                writer.putContent(originalShareExtFile); // put back the original extension file
                return null;
            }
        });

        logger.info("Reverted default-persisted-extension.xml content.");
    }

    if (originalShareExtFile != null)
    {
        originalShareExtFile.delete();
    }
}
 
Example 50
Project: alfresco-remote-api   File: GetMethodRegressionTest.java   Source Code and License 5 votes vote down vote up
private void createTestContent(NodeRef parentNode, int documentsAmount)
{
    for (int i = 0; i < documentsAmount; i++)
    {
        String testDocumentName = String.format(TEST_DOCUMENT_NAME_PATTERN, i, System.currentTimeMillis());
        FileInfo testDocument = fileFolderService.create(parentNode, testDocumentName, ContentModel.TYPE_CONTENT);
        ContentWriter writer = fileFolderService.getWriter(testDocument.getNodeRef());
        writer.putContent(String.format(TEXT_DOCUMENT_CONTENT_PATTERN, testDocumentName));
        writer.setMimetype(TEST_MIMETYPE);
        writer.setEncoding(TEST_ENCODING);
    }
}
 
Example 51
Project: alfresco-repository   File: CachingContentStoreSpringTest.java   Source Code and License 5 votes vote down vote up
public void testBackingStoreBehavesLikeCenteraContentStore()
{
    String content1 = "test content 1";
    String content2 = "test content 2";
    
    // create backing store that behaves like centera content store, i.e. contentUrl is known only after content is written
    centeraLikeBackingStore = new TestCenteraLikeContentStore(ctx,
            TempFileProvider.getTempDir().getAbsolutePath() +
            File.separatorChar +
            getName() + "_centera");
    
    // create caching content store with centera like backing store
    store = new CachingContentStore(centeraLikeBackingStore, cache, true);
    
    ContentWriter writer1 = store.getWriter(new ContentContext(null, null));
    // for centera like backing content store all writers have the same content url before content was written
    assertEquals(TestCenteraLikeContentWriter.UNKNOWN_ID, writer1.getContentData().getContentUrl());
    writer1.putContent(content1);
    // after content was written into the backing store, content url should change
    assertNotSame(TestCenteraLikeContentWriter.UNKNOWN_ID, writer1.getContentData().getContentUrl());
    
    // get another writer
    ContentWriter writer2 = store.getWriter(new ContentContext(null, null));
    // for centera like backing content store all writers have the same content url before content was written
    assertEquals(TestCenteraLikeContentWriter.UNKNOWN_ID, writer2.getContentData().getContentUrl());
    writer2.putContent(content2);
    // after content was written into the backing store, content url should change
    assertNotSame(TestCenteraLikeContentWriter.UNKNOWN_ID, writer2.getContentData().getContentUrl());
    
    // writers should have different content urls
    assertNotSame(writer1.getContentData().getContentUrl(), writer2.getContentData().getContentUrl());
    
    ContentReader reader = store.getReader(writer1.getContentData().getContentUrl());
    
    assertEquals(content1, reader.getContentString());
}
 
Example 52
Project: alfresco-repository   File: FileFolderServiceImplTest.java   Source Code and License 5 votes vote down vote up
public void testGetReaderWriter() throws Exception
{
    // testing a failure
    txn.commit();
    txn = transactionService.getUserTransaction();
    txn.begin();

    FileInfo dirInfo = getByName(NAME_L0_FOLDER_A, true);

    UserTransaction rollbackTxn = null;
    try
    {
        rollbackTxn = transactionService.getNonPropagatingUserTransaction();
        rollbackTxn.begin();
        fileFolderService.getWriter(dirInfo.getNodeRef());
        fail("Failed to detect content write to folder");
    }
    catch (RuntimeException e)
    {
        // expected
    }
    finally
    {
        rollbackTxn.rollback();
    }

    FileInfo fileInfo = getByName(NAME_L1_FILE_A, false);

    ContentWriter writer = fileFolderService.getWriter(fileInfo.getNodeRef());
    assertNotNull("Writer is null", writer);
    // write some content
    String content = "ABC";
    writer.putContent(content);
    // read the content
    ContentReader reader = fileFolderService.getReader(fileInfo.getNodeRef());
    assertNotNull("Reader is null", reader);
    String checkContent = reader.getContentString();
    assertEquals("Content mismatch", content, checkContent);
}
 
Example 53
Project: alfresco-repository   File: ContentStoreCleanerScalabilityRunner.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a writer to a thread-unique file.  It's always the same file per thread so you must
 * use and close the writer before getting another.
 */
@Override
protected ContentWriter getWriterInternal(ContentReader existingContentReader, String newContentUrl)
{
    File file = hammeredFile.get();
    if (file == null)
    {
        file = TempFileProvider.createTempFile("NullContentStore", ".txt");
        hammeredFile.set(file);
    }
    return new FileContentWriter(file);
}
 
Example 54
Project: alfresco-repository   File: DeletedContentBackupCleanerListener.java   Source Code and License 5 votes vote down vote up
public void beforeDelete(ContentStore sourceStore, String contentUrl) throws ContentIOException
{
    if (store.isContentUrlSupported(contentUrl))
    {
        ContentContext context = new ContentContext(null, contentUrl);
        ContentReader reader = sourceStore.getReader(contentUrl);
        if (!reader.exists())
        {
            // Nothing to copy over
            return;
        }
        // write the content into the target store
        ContentWriter writer = store.getWriter(context);
        // copy across
        writer.putContent(reader);
        // done
        if (logger.isDebugEnabled())
        {
            logger.debug(
                    "Moved content before deletion: \n" +
                    "   URL:    " + contentUrl + "\n" +
                    "   Source: " + sourceStore + "\n" +
                    "   Target: " + store);
        }
    }
    else
    {
        if (logger.isDebugEnabled())
        {
            logger.debug(
                    "Content cannot be moved during deletion.  A backup will not be made: \n" +
                    "   URL:    " + contentUrl + "\n" +
                    "   Source: " + sourceStore + "\n" +
                    "   Target: " + store);
        }
    }
}
 
Example 55
Project: alfresco-repository   File: RoutingContentServiceTest.java   Source Code and License 5 votes vote down vote up
public WriteThread(ContentWriter writer, String content)
{
    this.writer = writer;
    this.content = content;
    isWaiting = false;
    isDone = false;
    error = null;
}
 
Example 56
Project: alfresco-remote-api   File: TestPeople.java   Source Code and License 5 votes vote down vote up
private NodeRef createAvatarDirect(NodeRef personRef, File avatarFile)
{
    // create new avatar node
    nodeService.addAspect(personRef, ContentModel.ASPECT_PREFERENCES, null);
    ChildAssociationRef assoc = nodeService.createNode(
            personRef,
            ContentModel.ASSOC_PREFERENCE_IMAGE,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "origAvatar"),
            ContentModel.TYPE_CONTENT);
    final NodeRef avatarRef = assoc.getChildRef();

    // JSF client compatibility?
    nodeService.createAssociation(personRef, avatarRef, ContentModel.ASSOC_AVATAR);

    // upload the avatar content
    ContentService contentService = applicationContext.getBean("ContentService", ContentService.class);
    ContentWriter writer = contentService.getWriter(avatarRef, ContentModel.PROP_CONTENT, true);
    writer.guessMimetype(avatarFile.getName());
    writer.putContent(avatarFile);

    Rendition avatarR = new Rendition();
    avatarR.setId("avatar");
    Renditions renditions = applicationContext.getBean("Renditions", Renditions.class);
    renditions.createRendition(avatarRef.getId(), avatarR, false, null);

    return avatarRef;
}
 
Example 57
Project: alfresco-repository   File: RoutingContentServiceTest.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 58
Project: alfresco-repository   File: ContentServiceImplTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test getReader
 */
public void testGetReader()
{
    // Create a new versionable node
    NodeRef versionableNode = createNewVersionableNode();
    
    // Create a new version
    Version version = createVersion(versionableNode, this.versionProperties);
    NodeRef versionNodeRef = version.getFrozenStateNodeRef();
		
    // Get the content reader for the frozen node
    ContentReader contentReader = this.contentService.getReader(versionNodeRef, ContentModel.PROP_CONTENT);
    assertNotNull(contentReader);
    assertEquals(TEST_CONTENT, contentReader.getContentString());
    
    // Now update the content and verison again
    ContentWriter contentWriter = this.contentService.getWriter(versionableNode, ContentModel.PROP_CONTENT, true);
    assertNotNull(contentWriter);
    contentWriter.putContent(UPDATED_CONTENT);        
    Version version2 = createVersion(versionableNode, this.versionProperties);
    NodeRef version2NodeRef = version2.getFrozenStateNodeRef();
		
    // Get the content reader for the new verisoned content
    ContentReader contentReader2 = this.contentService.getReader(version2NodeRef, ContentModel.PROP_CONTENT);
    assertNotNull(contentReader2);
    assertEquals(UPDATED_CONTENT, contentReader2.getContentString());
}
 
Example 59
Project: alfresco-repository   File: RefreshTagScopeActionExecuter.java   Source Code and License 5 votes vote down vote up
/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.action.Action, org.alfresco.service.cmr.repository.NodeRef)
 */
@Override
protected void executeImpl(final Action action, final NodeRef actionedUponNodeRef)
{
    if (this.nodeService.exists(actionedUponNodeRef) == true &&
        this.nodeService.hasAspect(actionedUponNodeRef, ContentModel.ASPECT_TAGSCOPE) == true)
    {
        // Run the update as the system user
        AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
        {
            @SuppressWarnings("unchecked")
            public Object doWork() throws Exception
            {
                // Create a new list of tag details
                List<TagDetails> tags = new ArrayList<TagDetails>(10);
                
                // Count the tags found in all the (primary) children of the node
                countTags(actionedUponNodeRef, tags);
                
                // Order the list
                Collections.sort(tags);
                
                // Write new content back to tag scope
                String tagContent = TaggingServiceImpl.tagDetailsToString(tags);
                if(tagContent.length() > 0)
                {
                	// Write out tag content only if non-zero in size
                 ContentWriter contentWriter = contentService.getWriter(actionedUponNodeRef, ContentModel.PROP_TAGSCOPE_CACHE, true);
                 contentWriter.setEncoding("UTF-8");
                 contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
                 contentWriter.putContent(tagContent);
                }

                return null;
            }
            
        }, AuthenticationUtil.getSystemUserName());                      
    }
}
 
Example 60
Project: alfresco-repository   File: ArchiveContentTransformerTest.java   Source Code and License 5 votes vote down vote up
public void testArchiveToPdf() throws Exception
{
    String sourceMimetype = MimetypeMap.MIMETYPE_ZIP;
    String targetMimetype = MimetypeMap.MIMETYPE_PDF;

    // force Transformers subsystem to start (this will also load the ContentTransformerRegistry - including complex/dynamic pipelines)
    // note: a call to contentService.getTransformer would also do this .. even if transformer cannot be found (returned as null)
    ChildApplicationContextFactory transformersSubsystem = (ChildApplicationContextFactory) ctx.getBean("Transformers");
    transformersSubsystem.start();

    assertNotNull(registry.getTransformer("transformer.complex.ArchiveToPdf"));

    // note: txt -> pdf currently uses OpenOffice/LibreOffice
    if (! isOpenOfficeWorkerAvailable())
    {
        // no connection
        System.err.println("ooWorker not available - skipping testArchiveToPdf !!");
        return;
    }

    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
    ContentTransformer transformer = serviceRegistry.getContentService().getTransformer(sourceMimetype, targetMimetype);
    assertNotNull(transformer);

    String sourceExtension = mimetypeService.getExtension(sourceMimetype);
    String targetExtension = mimetypeService.getExtension(targetMimetype);

    File zipSourceFile = loadQuickTestFile("zip");
    ContentReader sourceReader = new FileContentReader(zipSourceFile);

    // make a writer for the target file
    File targetFile = TempFileProvider.createTempFile(getClass().getSimpleName() + "_"
            + getName() + "_" + sourceExtension + "_", "." + targetExtension);
    ContentWriter targetWriter = new FileContentWriter(targetFile);

    // do the transformation
    sourceReader.setMimetype(sourceMimetype);
    targetWriter.setMimetype(targetMimetype);
    transformer.transform(sourceReader.getReader(), targetWriter);

    ContentReader targetReader = new FileContentReader(targetFile);
    assertTrue(targetReader.getSize() > 0);
}