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

The following examples show how to use org.alfresco.service.cmr.repository.ContentWriter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FileFolderServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public ContentWriter getWriter(NodeRef nodeRef)
{
    FileInfo fileInfo = toFileInfo(nodeRef, false);
    if (fileInfo.isFolder())
    {
        throw new InvalidTypeException("Unable to get a content writer for a folder: " + fileInfo);
    }
    final ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    // Ensure that a mimetype is set based on the filename (ALF-6560)
    // This has been removed from the create code in 3.4 to prevent insert-update behaviour
    // of the ContentData.
    if (writer.getMimetype() == null)
    {
        final String name = fileInfo.getName();
        writer.guessMimetype(name);
    }
    // Done
    return writer;
}
 
Example #2
Source File: EMLTransformerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 #3
Source File: DictionaryModelTypeTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private NodeRef createActiveModel(String contentFile)
{
    PropertyMap properties = new PropertyMap(1);
    properties.put(ContentModel.PROP_MODEL_ACTIVE, true);
    NodeRef modelNode = this.nodeService.createNode(
             this.rootNodeRef,
             ContentModel.ASSOC_CHILDREN,
             QName.createQName(NamespaceService.ALFRESCO_URI, "dictionaryModels"),
             ContentModel.TYPE_DICTIONARY_MODEL,
             properties).getChildRef();
     assertNotNull(modelNode);

     ContentWriter contentWriter = this.contentService.getWriter(modelNode, ContentModel.PROP_CONTENT, true);
     contentWriter.setEncoding("UTF-8");
     contentWriter.setMimetype(MimetypeMap.MIMETYPE_XML);
     contentWriter.putContent(Thread.currentThread().getContextClassLoader().getResourceAsStream(contentFile));
     return modelNode;
}
 
Example #4
Source File: ScriptNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private ScriptNode transformImage(String mimetype, final String options, NodeRef destination)
{
    ParameterCheck.mandatoryString("Mimetype", mimetype);
    final NodeRef sourceNodeRef = nodeRef;
    
    // the delegate definition for transforming an image
    Transformer transformer = new AbstractTransformer()
    {
        protected void doTransform(SynchronousTransformClient synchronousTransformClient, ContentReader reader, ContentWriter writer)
        {
            Map<String, String> actualOptions = new HashMap<>(1);
            if (options != null || !options.trim().isEmpty())
            {
                actualOptions.put(ImageTransformationOptions.OPT_COMMAND_OPTIONS, options);
            }
            transformNodeRef(synchronousTransformClient, reader, writer, actualOptions, sourceNodeRef);
        }
    };
    
    return transformNode(transformer, mimetype, destination);
}
 
Example #5
Source File: ThumbnailServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private NodeRef createCorruptedContent(NodeRef parentFolder) throws IOException
{
    // The below pdf file has been truncated such that it is identifiable as a PDF but otherwise corrupt.
    File corruptPdfFile = AbstractContentTransformerTest.loadNamedQuickTestFile("quickCorrupt.pdf");
    assertNotNull("Failed to load required test file.", corruptPdfFile);

    Map<QName, Serializable> props = new HashMap<QName, Serializable>();
    props.put(ContentModel.PROP_NAME, "corrupt.pdf");
    NodeRef node = this.secureNodeService.createNode(parentFolder, ContentModel.ASSOC_CONTAINS,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "quickCorrupt.pdf"),
            ContentModel.TYPE_CONTENT, props).getChildRef();

    secureNodeService.setProperty(node, ContentModel.PROP_CONTENT, new ContentData(null,
                MimetypeMap.MIMETYPE_PDF, 0L, null));
    ContentWriter writer = contentService.getWriter(node, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
    writer.setEncoding("UTF-8");
    writer.putContent(corruptPdfFile);
    
    return node;
}
 
Example #6
Source File: RuntimeExecutableContentTransformerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testCopyCommand() throws Exception
{
    String content = "<A><B></B></A>";
    // create the source
    File sourceFile = TempFileProvider.createTempFile(getName() + "_", ".txt");
    ContentWriter tempWriter = new FileContentWriter(sourceFile);
    tempWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    tempWriter.putContent(content);
    ContentReader reader = tempWriter.getReader(); 
    // create the target
    File targetFile = TempFileProvider.createTempFile(getName() + "_", ".xml");
    ContentWriter writer = new FileContentWriter(targetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_XML);
    
    // do the transformation
    transformer.transform(reader, writer);   // no options on the copy
    
    // make sure that the content was copied over
    ContentReader checkReader = writer.getReader();
    String checkContent = checkReader.getContentString();
    assertEquals("Content not copied", content, checkContent);
}
 
Example #7
Source File: TestCMIS.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
private NodeRef makeRenditionNode(NodeRef parent, String title, String name, String mimetype)
  {
      Map<QName, Serializable> props = new HashMap<QName, Serializable>();
      props.put(ContentModel.PROP_NAME, name);
      props.put(ContentModel.PROP_TITLE, title);
      QName assocQName = QName.createQName(NamespaceService.RENDITION_MODEL_1_0_URI, name);
      ChildAssociationRef assoc = nodeService.createNode(parent, RenditionModel.ASSOC_RENDITION,
          assocQName, ContentModel.TYPE_THUMBNAIL, props);
      NodeRef childRef = assoc.getChildRef();

      if (!nodeService.hasAspect(parent, RenditionModel.ASPECT_RENDITIONED))
      {
          nodeService.addAspect(parent, RenditionModel.ASPECT_RENDITIONED, null);
      }

      ContentWriter writer = contentService.getWriter(childRef, ContentModel.PROP_CONTENT, true);
      writer.setMimetype(mimetype);
      writer.setEncoding("UTF-8");
writer.putContent("Dummy "+name+" content");

      return childRef;
  }
 
Example #8
Source File: EMLTransformerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Test transforming a valid eml with nested mimetype multipart/alternative to text
 */
public void testRFC822NestedAlternativeToText() throws Exception
{
    File emlSourceFile = loadQuickTestFile("nested.alternative.eml");
    File txtTargetFile = TempFileProvider.createTempFile("test5", ".txt");
    ContentReader reader = new FileContentReader(emlSourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_RFC822);
    ContentWriter writer = new FileContentWriter(txtTargetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);

    transformer.transform(reader, writer);

    ContentReader reader2 = new FileContentReader(txtTargetFile);
    reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    String contentStr = reader2.getContentString();
    assertTrue(contentStr.contains(QUICK_EML_NESTED_ALTERNATIVE_CONTENT));
}
 
Example #9
Source File: CompressingContentWriter.java    From alfresco-simple-content-stores with Apache License 2.0 6 votes vote down vote up
protected CompressingContentWriter(final String contentUrl, final ContentContext context, final ContentStore temporaryContentStore,
        final ContentWriter backingWriter, final String compressionType, final Collection<String> mimetypesToCompress)
{
    super(backingWriter.getContentUrl() != null ? backingWriter.getContentUrl() : context.getContentUrl(),
            context.getExistingContentReader());

    ParameterCheck.mandatory("context", context);
    ParameterCheck.mandatory("temporaryContentStore", temporaryContentStore);
    ParameterCheck.mandatory("backingWriter", backingWriter);

    this.context = context;
    this.temporaryContentStore = temporaryContentStore;
    this.backingWriter = backingWriter;

    this.compressionType = compressionType;
    this.mimetypesToCompress = mimetypesToCompress;

    // we are the first real listener (DoGuessingOnCloseListener always is first)
    super.addListener(this);

    final ContentContext temporaryContext = new ContentContext(context.getExistingContentReader(), null);
    this.temporaryWriter = this.temporaryContentStore.getWriter(temporaryContext);
}
 
Example #10
Source File: QuickShareRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
private NodeRef createTestFile(final NodeRef parent, final String name, final File quickFile)
{
	return transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
            props.put(ContentModel.PROP_NAME, name);
            ChildAssociationRef result = nodeService.createNode(parent,
                                                    ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS,
                                                    ContentModel.TYPE_CONTENT, props);
            
            NodeRef nodeRef = result.getChildRef();
            ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(TEST_MIMETYPE_JPEG);
            writer.putContent(quickFile);
            
            return nodeRef;
        }
    });
}
 
Example #11
Source File: CachingContentStoreSpringTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testStoreWillReadFromCacheWhenAvailable()
{
    final String content = "Content for " + getName() + " test.";
    
    // Write some content to the backing store.
    ContentWriter writer = backingStore.getWriter(ContentContext.NULL_CONTEXT);
    writer.putContent(content);
    final String contentUrl = writer.getContentUrl();
    
    // Read content using the CachingContentStore - will cause content to be cached.
    String retrievedContent = store.getReader(contentUrl).getContentString();
    assertEquals(content, retrievedContent);
    
    // Remove the original content from the backing store.
    backingStore.delete(contentUrl);
    assertFalse("Original content should have been deleted", backingStore.exists(contentUrl));
    
    // The cached version is still available.
    String contentAfterDelete = store.getReader(contentUrl).getContentString();
    assertEquals(content, contentAfterDelete);
}
 
Example #12
Source File: ActivitiWorkflowServiceIntegrationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Deploy as a normal content node, then switch the type to bpm:workflowDefinition.
 * <p>
 * This should not be allowed to happen if you are non-admin.
 */
private WorkflowDefinition createContentAndSwitchToWorkflow(String processName, String resource, NodeRef parent)
{
    InputStream input = getInputStream(resource);

    ChildAssociationRef childAssoc = nodeService.createNode(
            parent,
            ContentModel.ASSOC_CONTAINS,
            QName.createQName(NamespaceService.CONTENT_MODEL_PREFIX, "test"),
            ContentModel.TYPE_CONTENT,
            null);
    NodeRef workflowNode = childAssoc.getChildRef();

    ContentWriter writer = serviceRegistry.getContentService().getWriter(workflowNode, ContentModel.PROP_CONTENT, true);
    writer.putContent(input);
    
    // Now change to WorkflowModel.TYPE_WORKFLOW_DEF
    nodeService.setType(workflowNode, WorkflowModel.TYPE_WORKFLOW_DEF);
    // Activate it
    nodeService.setProperty(workflowNode, WorkflowModel.PROP_WORKFLOW_DEF_DEPLOYED, true);

    return workflowService.getDefinitionByName(processName);
}
 
Example #13
Source File: StringExtractingContentTransformer.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void transformRemote(RemoteTransformerClient remoteTransformerClient, ContentReader reader,
                               ContentWriter writer, TransformationOptions options, String sourceMimetype,
                               String targetMimetype, String sourceExtension, String targetExtension,
                               String targetEncoding) throws Exception
{
    String sourceEncoding = reader.getEncoding();
    long timeoutMs = options.getTimeoutMs();

    remoteTransformerClient.request(reader, writer, sourceMimetype, sourceExtension, targetExtension,
            timeoutMs, logger,
            "transformName", "string",
            "sourceMimetype", sourceMimetype,
            "targetMimetype", targetMimetype,
            "targetExtension", targetExtension,
            SOURCE_ENCODING, sourceEncoding,
            TARGET_ENCODING, targetEncoding);

}
 
Example #14
Source File: TextToPdfContentTransformer.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void transformRemote(RemoteTransformerClient remoteTransformerClient, ContentReader reader,
                               ContentWriter writer, TransformationOptions options, String sourceMimetype,
                               String targetMimetype, String sourceExtension, String targetExtension,
                               String targetEncoding) throws Exception
{
    String sourceEncoding = reader.getEncoding();
    long timeoutMs = options.getTimeoutMs();

    TransformationOptionLimits limits = getLimits(reader, writer, options);
    TransformationOptionPair pageLimits = limits.getPagesPair();
    int pageLimit = (int)pageLimits.getValue();

    remoteTransformerClient.request(reader, writer, sourceMimetype, sourceExtension, targetExtension,
            timeoutMs, logger,
            "transformName", "textToPdf",
            "sourceMimetype", sourceMimetype,
            "targetMimetype", targetMimetype,
            "targetExtension", targetExtension,
            SOURCE_ENCODING, sourceEncoding,
            "pageLimit", String.valueOf(pageLimit));
}
 
Example #15
Source File: AbstractWritableContentStoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Checks that the writer can have a listener attached
 */
@Test
public void testWriteStreamListener() throws Exception
{
    ContentWriter writer = getWriter();
    
    final boolean[] streamClosed = new boolean[] {false};  // has to be final
    ContentStreamListener listener = new ContentStreamListener()
    {
        public void contentStreamClosed() throws ContentIOException
        {
            streamClosed[0] = true;
        }
    };
    writer.addListener(listener);
    
    // write some content
    writer.putContent("ABC");
    
    // check that the listener was called
    assertTrue("Write stream listener was not called for the stream close", streamClosed[0]);
}
 
Example #16
Source File: ArchiveContentTransformer.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void transformRemote(RemoteTransformerClient remoteTransformerClient, ContentReader reader,
                               ContentWriter writer, TransformationOptions options,
                               String sourceMimetype, String targetMimetype,
                               String sourceExtension, String targetExtension,
                               String targetEncoding) throws Exception
{
    long timeoutMs = options.getTimeoutMs();
    boolean recurse = includeContents;
    if(options.getIncludeEmbedded() != null)
    {
        recurse = options.getIncludeEmbedded();
    }
    remoteTransformerClient.request(reader, writer, sourceMimetype, sourceExtension, targetExtension,
            timeoutMs, logger,
            "transformName", "Archive",
            "includeContents", Boolean.toString(recurse),
            "sourceMimetype", sourceMimetype,
            "sourceExtension", sourceExtension,
            "targetMimetype", targetMimetype,
            TARGET_ENCODING, targetEncoding);
}
 
Example #17
Source File: PdfBoxContentTransformer.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void transformRemote(RemoteTransformerClient remoteTransformerClient, ContentReader reader,
                               ContentWriter writer, TransformationOptions options,
                               String sourceMimetype, String targetMimetype,
                               String sourceExtension, String targetExtension,
                               String targetEncoding) throws Exception
{
    long timeoutMs = options.getTimeoutMs();
    String notExtractBookmarksText = null;

    if (!extractBookmarksText)
    {
        notExtractBookmarksText = Boolean.TRUE.toString();
    }

    remoteTransformerClient.request(reader, writer, sourceMimetype, sourceExtension, targetExtension,
            timeoutMs, logger,
            "transformName", "PdfBox",
            "notExtractBookmarksText", notExtractBookmarksText,
            "sourceMimetype", sourceMimetype,
            "targetMimetype", targetMimetype,
            "targetExtension", targetExtension,
            TARGET_ENCODING, targetEncoding);
}
 
Example #18
Source File: PeopleImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Write the description to a content file and store the content URL in
 * ContentModel.PROP_PERSONDESC
 * 
 * @param description
 * @param nodeRef
 */
private void savePersonDescription(final String description, final NodeRef nodeRef)
{
    AuthenticationUtil.runAsSystem(new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            if (description != null)
            {
                ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_PERSONDESC, true);
                writer.putContent(description);
            }
            else
            {
                nodeService.setProperty(nodeRef, ContentModel.PROP_PERSONDESC, null);
            }
            return null;
        }
    });
}
 
Example #19
Source File: FullTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 #20
Source File: MediaWikiContentTransformer.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 #21
Source File: ContentServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Test getReader
 */
@Test
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 #22
Source File: BinaryPassThroughContentTransformer.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void transformInternal(ContentReader reader,
        ContentWriter writer, TransformationOptions options)
        throws Exception
{
    // just stream it
    writer.putContent(reader.getContentInputStream());
    
}
 
Example #23
Source File: RoutingContentServiceTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Tests that the content update policy firs correctly
 */
public void testOnContentUpdatePolicy()
{
	// Register interest in the content update event for a versionable node
	this.policyComponent.bindClassBehaviour(
               QName.createQName(NamespaceService.ALFRESCO_URI, "onContentUpdate"),
			ContentModel.ASPECT_VERSIONABLE,
			new JavaBehaviour(this, "onContentUpdateBehaviourTest"));
	
	// First check that the policy is not fired when the versionable aspect is not present
	ContentWriter contentWriter = this.contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
	contentWriter.putContent("content update one");
	assertFalse(this.policyFired);
       
       this.newContent = false;
	
	// Now check that the policy is fired when the versionable aspect is present
	this.nodeService.addAspect(this.contentNodeRef, ContentModel.ASPECT_VERSIONABLE, null);
	ContentWriter contentWriter2 = this.contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
	contentWriter2.putContent("content update two");
	assertTrue(this.policyFired);
	this.policyFired = false;
	
	// Check that the policy is not fired when using a non updating content writer
	ContentWriter contentWriter3 = this.contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, false);
	contentWriter3.putContent("content update three");
	assertFalse(this.policyFired);
}
 
Example #24
Source File: AdminUiTransformerDebug.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public NodeRef createSourceNode(String extension, String sourceMimetype)
{
    // Create a content node which will serve as test data for our transformations.
    RetryingTransactionHelper.RetryingTransactionCallback<NodeRef> makeNodeCallback = new RetryingTransactionHelper.RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            // Create a source node loaded with a quick file.
            URL url = loadQuickTestFile(extension);
            URI uri = url.toURI();
            File sourceFile = new File(uri);

            final NodeRef companyHome = getRepositoryHelper().getCompanyHome();

            Map<QName, Serializable> props = new HashMap<QName, Serializable>();
            String localName = "TestTransform." + extension;
            props.put(ContentModel.PROP_NAME, localName);
            NodeRef node = nodeService.createNode(
                    companyHome,
                    ContentModel.ASSOC_CONTAINS,
                    QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, localName),
                    ContentModel.TYPE_CONTENT,
                    props).getChildRef();

            ContentWriter writer = getContentService().getWriter(node, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(sourceMimetype);
            writer.setEncoding("UTF-8");
            writer.putContent(sourceFile);

            return node;
        }
    };
    NodeRef contentNodeRef = getTransactionService().getRetryingTransactionHelper().doInTransaction(makeNodeCallback);
    this.nodesToDeleteAfterTest.add(contentNodeRef);
    return contentNodeRef;
}
 
Example #25
Source File: AlfrescoEnviroment.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public ContentWriter getWriter(NodeRef nodeRef, QName propertyQName, boolean update)
            throws InvalidNodeRefException, InvalidTypeException
{
    return apiFacet.getContentService().getWriter(nodeRef,
                                                  propertyQName,
                                                  update);
}
 
Example #26
Source File: ScriptNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Set the content stream from another content object.
 *  
 * @param content  ScriptContent to set
 */
public void write(Content content)
{
    ContentService contentService = services.getContentService();
    ContentWriter writer = contentService.getWriter(nodeRef, this.property, true);
    writer.setMimetype(content.getMimetype());
    writer.setEncoding(content.getEncoding());
    writer.putContent(content.getInputStream());

    // update cached variables after putContent()
    updateContentData(true);
}
 
Example #27
Source File: OOoContentTransformerHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void transformRemote(ContentReader reader, ContentWriter writer, TransformationOptions options,
                               String sourceMimetype, String sourceExtension,
                               String targetMimetype, String targetExtension) throws IllegalAccessException
{
    long timeoutMs = options.getTimeoutMs();
    Log logger = getLogger();
    remoteTransformerClient.request(reader, writer, sourceMimetype, sourceExtension, targetExtension,
            timeoutMs, logger,
            "transformName", "libreoffice",
            "sourceMimetype", sourceMimetype,
            "sourceExtension", sourceExtension,
            "targetMimetype", targetMimetype);
}
 
Example #28
Source File: FileContentStore.java    From alfresco-simple-content-stores with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected ContentWriter getWriterInternal(final ContentReader existingContentReader, final String newContentUrl)
{
    String contentUrl = null;
    try
    {
        if (newContentUrl == null)
        {
            contentUrl = this.createNewFileStoreUrl();
        }
        else
        {
            contentUrl = ContentUrlUtils.checkAndReplaceWildcardProtocol(newContentUrl, this.protocol);
        }

        final File file = this.createNewFile(contentUrl);
        final FileContentWriterImpl writer = new FileContentWriterImpl(file, contentUrl, existingContentReader);

        if (this.contentLimitProvider != null)
        {
            writer.setContentLimitProvider(this.contentLimitProvider);
        }

        writer.setAllowRandomAccess(this.allowRandomAccess);

        LOGGER.debug("Created content writer: \n   writer: {}", writer);
        return writer;
    }
    catch (final Throwable e)
    {
        LOGGER.error("Error creating writer for {}", contentUrl, e);
        throw new ContentIOException("Failed to get writer for URL: " + contentUrl, e);
    }
}
 
Example #29
Source File: ImapServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 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 #30
Source File: AbstractEmailMessageHandler.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Write content to the node from InputStream.
 * 
 * @param nodeRef Target node.
 * @param content Content stream.
 * @param mimetype MIME content type.
 * @param encoding Encoding. Can be null for text based content, n which case the best guess.
 */
protected void writeContent(NodeRef nodeRef, InputStream content, String mimetype, String encoding)
{
    InputStream bis = new BufferedInputStream(content, 4092);

    // Only guess the encoding if it has not been supplied
    if (encoding == null)
    {
        if (mimetypeService.isText(mimetype))
        {
            ContentCharsetFinder charsetFinder = mimetypeService.getContentCharsetFinder();
            encoding = charsetFinder.getCharset(bis, mimetype).name();
        }
        else
        {
            encoding = "UTF-8";
        }
    }
    
    if (log.isDebugEnabled())
    {
        log.debug("Write content (MimeType=\"" + mimetype + "\", Encoding=\"" + encoding + "\"");
    }
    
    
    ContentService contentService = getContentService();
    ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(mimetype);
    writer.setEncoding(encoding);
    writer.putContent(bis);
}