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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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);
}