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

The following are top voted examples for showing how to use org.alfresco.service.cmr.repository.ContentReader. 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: CIFSContentComparatorTest.java   View source code 7 votes vote down vote up
/**
 * Open and close of a project file changes certain header properties.
 * Test File 1 has been opened and closed.
 * @throws Exception
 */
public void testProjectTrivialDiffProjectFiles() throws Exception
{
    CIFSContentComparator contentComparator = new CIFSContentComparator();
    contentComparator.init();
    
    ClassPathResource file0Resource = new ClassPathResource("filesys/ContentComparatorTest0.mpp");
    assertNotNull("unable to find test resource filesys/ContentComparatorTest0.mpp", file0Resource);
    
    ClassPathResource file1Resource = new ClassPathResource("filesys/ContentComparatorTest1.mpp");
    assertNotNull("unable to find test resource filesys/ContentComparatorTest1.mpp", file1Resource);
            
    /**
     * Compare trivially different project files, should ignore trivial differences and be equal 
     */
    {
        File file0 = file0Resource.getFile();
        File file1 = file1Resource.getFile();

        ContentReader reader = new FileContentReader(file0);
        reader.setMimetype("application/vnd.ms-project");
        reader.setEncoding("UTF-8");
        boolean result = contentComparator.isContentEqual(reader, file1);
        assertTrue("compare trivially different project file, should be equal", result);
    }
}
 
Example 2
Project: alfresco-remote-api   File: MoveMethod.java   View source code 7 votes vote down vote up
private void copyContentOnly(FileInfo sourceFileInfo, FileInfo destFileInfo, FileFolderService fileFolderService) throws WebDAVServerException
{
	ContentService contentService = getContentService();
    ContentReader reader = contentService.getReader(sourceFileInfo.getNodeRef(), ContentModel.PROP_CONTENT);
    if (reader == null)
    {
        // There is no content for the node if it is a folder
        if (!sourceFileInfo.isFolder())
        {
            // Non-folders should have content available.
            logger.error("Unable to get ContentReader for source node " + sourceFileInfo.getNodeRef());
            throw new WebDAVServerException(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    else
    {
        ContentWriter contentWriter = contentService.getWriter(destFileInfo.getNodeRef(), ContentModel.PROP_CONTENT, true);
        contentWriter.putContent(reader);
    }
}
 
Example 3
Project: alfresco-object-storage-connectors   File: ObjectStorageContentStore.java   View source code 6 votes vote down vote up
@Override
public ContentReader getReader(String contentUrl) {
	if (logger.isDebugEnabled()) {
		logger.debug(String.format("Content Reader for %s", contentUrl));
	}

	// Use pool of locks - which one is determined by a hash of the URL.
	// This will stop the content from being read/cached multiple times from
	// the backing store
	// when it should only be read once - cached versions should be returned
	// after that.
	ReadLock readLock = readWriteLock(contentUrl).readLock();
	readLock.lock();
	try {
		return this.objectStorageService.getReader(contentUrl);
	} catch (IOException e) {
		logger.error(e.getMessage(), e);
	} finally {
		readLock.unlock();
	}

	return null;
}
 
Example 4
Project: alfresco-remote-api   File: CommentsImpl.java   View source code 6 votes vote down vote up
private Comment toComment(NodeRef nodeRef, NodeRef commentNodeRef, List<String> include)
  {
      Map<QName, Serializable> nodeProps = nodeService.getProperties(commentNodeRef);

      ContentReader reader = contentService.getReader(commentNodeRef, ContentModel.PROP_CONTENT);
      if(reader != null)
      {
       String content = reader.getContentString();
       nodeProps.put(Comment.PROP_COMMENT_CONTENT, content);
       nodeProps.remove(ContentModel.PROP_CONTENT);
      }


      Map<String, Boolean> map = commentService.getCommentPermissions(nodeRef, commentNodeRef);
      boolean canEdit = map.get(CommentService.CAN_EDIT);
      boolean canDelete =  map.get(CommentService.CAN_DELETE);

Person createdBy = people.getPerson((String) nodeProps.get(ContentModel.PROP_CREATOR), include);
nodeProps.put(Comment.PROP_COMMENT_CREATED_BY, createdBy);

Person modifiedBy = people.getPerson((String) nodeProps.get(ContentModel.PROP_MODIFIER), include);
nodeProps.put(Comment.PROP_COMMENT_MODIFIED_BY, modifiedBy);

      Comment comment = new Comment(commentNodeRef.getId(), nodeProps, canEdit, canDelete);
      return comment;
  }
 
Example 5
Project: alfresco-repository   File: XmlMetadataExtracterTest.java   View source code 6 votes vote down vote up
public void testXmlMetadataExtracter() throws Exception
{
    // Load the example files
    ContentReader alfrescoModelReader = getReader(FILE_ALFRESCO_MODEL);
    assertTrue(alfrescoModelReader.exists());
    ContentReader eclipseProjectReader = getReader(FILE_ECLIPSE_PROJECT);
    assertTrue(eclipseProjectReader.exists());
    
    // Pass the Alfresco Model xml to the extractor
    PropertyMap checkAlfrescoModelProperties = new PropertyMap();
    xmlMetadataExtracter.extract(alfrescoModelReader, checkAlfrescoModelProperties);
    // Check the values
    assertEquals("Gavin Cornwell", getPropertyValue(checkAlfrescoModelProperties, ContentModel.PROP_AUTHOR));
    assertEquals("fm:forummodel",  getPropertyValue(checkAlfrescoModelProperties, ContentModel.PROP_TITLE));
    assertEquals("Forum Model",    getPropertyValue(checkAlfrescoModelProperties, ContentModel.PROP_DESCRIPTION));

    // Pass the Eclipse Project xml to the extractor
    PropertyMap checkEclipseProjectProperties = new PropertyMap();
    xmlMetadataExtracter.extract(eclipseProjectReader, checkEclipseProjectProperties);
    // Check the values
    assertEquals("Repository",    getPropertyValue(checkEclipseProjectProperties, ContentModel.PROP_TITLE));
    assertEquals("JavaCC Nature", getPropertyValue(checkEclipseProjectProperties, ContentModel.PROP_DESCRIPTION));
}
 
Example 6
Project: alfresco-remote-api   File: RepoStore.java   View source code 6 votes vote down vote up
public long lastModified(final String documentPath) throws IOException
{
    return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Long>()
    {
        public Long doWork() throws Exception
        {
            return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Long>()
            {
                public Long execute() throws Exception
                {
                    ContentReader reader = contentService.getReader(
                            findNodeRef(documentPath), ContentModel.PROP_CONTENT);
                    return reader.getLastModified();
                }
            }, true, false);
        }
    }, AuthenticationUtil.getSystemUserName());            
}
 
Example 7
Project: alfresco-repository   File: HTMLRenderingEngine.java   View source code 6 votes vote down vote up
@Override
protected void render(RenderingContext context)
{
    ContentReader contentReader = context.makeContentReader();
    String sourceMimeType = contentReader.getMimetype();
    
    // Check that Tika supports the supplied file
    AutoDetectParser p = new AutoDetectParser(tikaConfig);
    MediaType sourceMediaType = MediaType.parse(sourceMimeType);
    if(! p.getParsers().containsKey(sourceMediaType))
    {
       throw new RenditionServiceException(
             "Source mime type of " + sourceMimeType + 
             " is not supported by Tika for HTML conversions"
       );
    }
    
    // Make the HTML Version using Tika
    // This will also extract out any images as found
    generateHTML(p, context);
}
 
Example 8
Project: alfresco-repository   File: OpenOfficeContentTransformerTest.java   View source code 6 votes vote down vote up
/**
 * ALF-219. Transforamtion from .html to .pdf for empty file.
 * @throws Exception
 */
public void testEmptyHtmlToEmptyPdf() throws Exception
{
    if (!isOpenOfficeWorkerAvailable())
    {
        // no connection
        System.err.println("ooWorker not available - skipping testEmptyHtmlToEmptyPdf !!");
        return;
    }
    URL url = this.getClass().getClassLoader().getResource("misc/empty.html");
    assertNotNull("URL was unexpectedly null", url);

    File htmlSourceFile = new File(url.getFile());
    assertTrue("Test file does not exist.", htmlSourceFile.exists());
    
    File pdfTargetFile = TempFileProvider.createTempFile(getName() + "-target-", ".pdf");
    
    ContentReader reader = new FileContentReader(htmlSourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_HTML);
    ContentWriter writer = new FileContentWriter(pdfTargetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
    
    transformer.transform(reader, writer);
}
 
Example 9
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 10
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 11
Project: alfresco-repository   File: EMLTransformerTest.java   View source code 6 votes vote down vote up
/**
 * Test transforming a valid eml file to text
 */
public void testRFC822ToText() throws Exception
{
    File emlSourceFile = loadQuickTestFile("eml");
    File txtTargetFile = TempFileProvider.createTempFile("test", ".txt");
    ContentReader reader = new FileContentReader(emlSourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_RFC822);
    ContentWriter writer = new FileContentWriter(txtTargetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);

    transformer.transform(reader, writer);

    ContentReader reader2 = new FileContentReader(txtTargetFile);
    reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    assertTrue(reader2.getContentString().contains(QUICK_EML_CONTENT));
}
 
Example 12
Project: alfresco-repository   File: ScriptNode.java   View source code 6 votes vote down vote up
private ScriptNode transformDocument(String mimetype, NodeRef destination)
{
    ParameterCheck.mandatoryString("Mimetype", mimetype);
    ParameterCheck.mandatory("Destination Node", destination);
    final NodeRef sourceNodeRef = nodeRef;
    
    // the delegate definition for transforming a document
    Transformer transformer = new AbstractTransformer()
    {
        protected void doTransform(ContentService contentService,
            ContentReader reader, ContentWriter writer)
        {
            TransformationOptions options = new TransformationOptions();
            options.setSourceNodeRef(sourceNodeRef);
            contentService.transform(reader, writer, options);
        }
    };
    
    return transformNode(transformer, mimetype, destination);
}
 
Example 13
Project: alfresco-repository   File: AbstractContentTransformer2.java   View source code 6 votes vote down vote up
private void strictMimetypeCheck(ContentReader reader, TransformationOptions options, String sourceMimetype)
    throws UnsupportedTransformationException
{
    if (strictMimeTypeCheck && depth.get() == 1)
    {
        String differentType = getMimetypeService().getMimetypeIfNotMatches(reader.getReader());

        if (!transformerConfig.strictMimetypeCheck(sourceMimetype, differentType))
        {
            String fileName = transformerDebug.getFileName(options, true, 0);
            String readerSourceMimetype = reader.getMimetype();
            String message = "Transformation of ("+fileName+
                ") has not taken place because the declared mimetype ("+
                readerSourceMimetype+") does not match the detected mimetype ("+
                differentType+").";
            logger.warn(message);
            throw new UnsupportedTransformationException(message);
        }
    }
}
 
Example 14
Project: alfresco-repository   File: AbstractContentWriter.java   View source code 6 votes vote down vote up
/**
 * @see ContentReader#getContentInputStream()
 * @see #putContent(InputStream) 
 */
public void putContent(ContentReader reader) throws ContentIOException
{
    try
    {
        // get the stream to read from
        InputStream is = reader.getContentInputStream();
        // put the content
        putContent(is);
    }
    catch (Throwable e)
    {
        throw new ContentIOException("Failed to copy reader content to writer: \n" +
                "   writer: " + this + "\n" +
                "   source reader: " + reader,
                e);
    }
}
 
Example 15
Project: alfresco-repository   File: MetadataExtracterLimitsTest.java   View source code 6 votes vote down vote up
@Override
protected Map<String, Serializable> extractRaw(ContentReader reader) throws Throwable
{
    Map<String, Serializable> properties = new HashMap<String, Serializable>(10);
    long startTime = (new Date()).getTime();
    boolean done = false;
    int i = 0;
    try
    {
        while(!done)
        {
            Thread.sleep(50); // working hard
            long extractTime = (new Date()).getTime() - startTime;
            properties.put("key" + i, extractTime);
            i++;
            done = extractTime > delay;
        }
        properties.put("a", "value1");
    }
    catch (InterruptedException e)
    {
        // Asked to stop
        return null;
    }
    return properties;
}
 
Example 16
Project: alfresco-repository   File: MailContentTransformerTest.java   View source code 6 votes vote down vote up
/**
 * Test transforming a valid unicode msg file to text
 */
public void testUnicodeMsgToText() throws Exception
{
    File msgSourceFile = loadQuickTestFile("unicode.msg");
    File txtTargetFile = TempFileProvider.createTempFile(getName() + "-target-2", ".txt");
    ContentReader reader = new FileContentReader(msgSourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_OUTLOOK_MSG);
    ContentWriter writer = new FileContentWriter(txtTargetFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    
    transformer.transform(reader, writer);
    
    ContentReader reader2 = new FileContentReader(txtTargetFile);
    reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    assertTrue(reader2.getContentString().contains(QUICK_CONTENT));
}
 
Example 17
Project: alfresco-repository   File: ScriptNode.java   View source code 6 votes vote down vote up
public Reader getReader()
{
    ContentService contentService = services.getContentService();
    ContentReader reader = contentService.getReader(nodeRef, property);
    
    if (reader != null && reader.exists())
    {
        try
        {
            return (contentData.getEncoding() == null) ? new InputStreamReader(reader.getContentInputStream()) : new InputStreamReader(reader.getContentInputStream(), contentData.getEncoding());
        }
        catch (IOException e)
        {
            // NOTE: fall-through
        }
    }
    return null;
}
 
Example 18
Project: alfresco-repository   File: ContentCacheImpl.java   View source code 6 votes vote down vote up
@Override
public boolean put(String contentUrl, ContentReader source)
{
    File tempFile = createCacheFile();
    
    // Copy the content from the source into a cache file
    if (source.getSize() > 0L)
    {
        source.getContent(tempFile);
        File cacheFile = renameTempToActive(tempFile);
        // Add a record of the cached file to the in-memory cache.
        recordCacheEntries(contentUrl, cacheFile);
        return true;
    }

    return false;
}
 
Example 19
Project: alfresco-repository   File: PoiHssfContentTransformerTest.java   View source code 6 votes vote down vote up
public void testCsvOutput() throws Exception
{
   File sourceFile = AbstractContentTransformerTest.loadQuickTestFile("xls");
   ContentReader sourceReader = new FileContentReader(sourceFile);

   File targetFile = TempFileProvider.createTempFile(
         getClass().getSimpleName() + "_" + getName() + "_xls_",
         ".csv");
   ContentWriter targetWriter = new FileContentWriter(targetFile);
   
   sourceReader.setMimetype(MimetypeMap.MIMETYPE_EXCEL);
   targetWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_CSV);
   transformer.transform(sourceReader, targetWriter);
   
   ContentReader targetReader = targetWriter.getReader();
   String checkContent = targetReader.getContentString();
   
   additionalContentCheck(
         MimetypeMap.MIMETYPE_EXCEL, 
         MimetypeMap.MIMETYPE_TEXT_CSV, 
         checkContent
   );
}
 
Example 20
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 21
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 22
Project: alfresco-repository   File: AbstractContentTransformerTest.java   View source code 6 votes vote down vote up
/**
 * Writes the supplied text out to a temporary file, and opens
 *  a content reader onto it. 
 */
protected static ContentReader buildContentReader(String text, Charset encoding)
    throws IOException
{
    File tmpFile = TempFileProvider.createTempFile("AlfrescoTest_", ".txt");
    FileOutputStream out = new FileOutputStream(tmpFile);
    OutputStreamWriter wout = new OutputStreamWriter(out, encoding);
    wout.write(text);
    wout.close();
    out.close();
    
    ContentReader reader = new FileContentReader(tmpFile);
    reader.setEncoding(encoding.displayName());
    reader.setMimetype("text/plain");
    return reader;
}
 
Example 23
Project: alfresco-repository   File: PoiMetadataExtracterTest.java   View source code 6 votes vote down vote up
/**
 * Test for MNT-577: Alfresco is running 100% CPU for over 10 minutes while extracting metadata for Word office document
 * 
 * @throws Exception
 */
public void testFootnotesLimitParameterUsingLarge() throws Exception
{
    PoiMetadataExtracter extractor = (PoiMetadataExtracter) getExtracter();

    File sourceFile = AbstractContentTransformerTest.loadNamedQuickTestFile(PROBLEM_FOOTNOTES_DOCUMENT_NAME);
    ContentReader sourceReader = new FileContentReader(sourceFile);
    sourceReader.setMimetype(MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING);

    // Just let the extractor do the job...
    extractor.setPoiFootnotesLimit(LARGE_FOOTNOTES_LIMIT);
    extractor.afterPropertiesSet();
    Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
    long startTime = System.currentTimeMillis();
    extractor.extract(sourceReader, properties);
    extractionTimeWithLargeFootnotesLimit = System.currentTimeMillis() - startTime;

    assertExtractedProperties(properties);
    if (extractionTimeWithDefaultFootnotesLimit != null)
    {
        assertTrue("The second metadata extraction operation must be longer!", extractionTimeWithLargeFootnotesLimit > extractionTimeWithDefaultFootnotesLimit);
    }
}
 
Example 24
Project: alfresco-repository   File: AbstractContentTransformerLimitsTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws Exception
{
    ApplicationContext ctx = MiscContextTestSuite.getMinimalContext();
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    MimetypeService mimetypeService = serviceRegistry.getMimetypeService();
    TransformerDebug transformerDebug = (TransformerDebug) ctx.getBean("transformerDebug");
    TransformerConfig transformerConfig = (TransformerConfig) ctx.getBean("transformerConfig");

    transformer = new AbstractContentTransformer2()
    {
        @Override
        public boolean isTransformableMimetype(String sourceMimetype, String targetMimetype,
                TransformationOptions options)
        {
            return false;
        }

        @Override
        protected void transformInternal(ContentReader reader, ContentWriter writer,
                TransformationOptions options) throws Exception
        {
        }
    };
    transformer.setMimetypeService(mimetypeService);
    transformer.setTransformerDebug(transformerDebug);
    transformer.setTransformerConfig(transformerConfig);
    transformer.setBeanName("transformer.test"+System.currentTimeMillis()%100000);
    
    limits = new TransformationOptionLimits();
    options = new TransformationOptions();
}
 
Example 25
Project: alfresco-object-storage-connectors   File: CephContentWriter.java   View source code 5 votes vote down vote up
@Override
protected ContentReader createReader() {
	try {
		return new CephContentReader(rados, pool, locator);
	} catch (IOException e) {
		throw new ContentIOException(e.getMessage(), e);
	}
}
 
Example 26
Project: alfresco-repository   File: CachingContentStoreTest.java   View source code 5 votes vote down vote up
@Test
public void spoofedGetReader()
{
    cachingStore = new CachingContentStore(backingStore, cache, true);
    String url = SpoofedTextContentReader.createContentUrl(Locale.ENGLISH, 0L, 1024L);
    ContentReader reader = cachingStore.getReader(url);
    assertTrue(reader.exists());
    assertEquals(1024, reader.getSize());
    verify(backingStore, never()).getReader(anyString());
}
 
Example 27
Project: alfresco-remote-api   File: RepoStore.java   View source code 5 votes vote down vote up
public Reader getReader()
{
    ContentReader reader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
    try
    {
        return new InputStreamReader(getInputStream(), reader.getEncoding());
    }
    catch (UnsupportedEncodingException e)
    {
        throw new AlfrescoRuntimeException("Unsupported Encoding", e);
    }
}
 
Example 28
Project: alfresco-repository   File: ContentServiceImpl.java   View source code 5 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.repository.ContentService#isTransformable(org.alfresco.service.cmr.repository.ContentReader, org.alfresco.service.cmr.repository.ContentWriter, org.alfresco.service.cmr.repository.TransformationOptions)
 */
public boolean isTransformable(ContentReader reader, ContentWriter writer, TransformationOptions options)
{
 // check that source and target mimetypes are available
    String sourceMimetype = reader.getMimetype();
    if (sourceMimetype == null)
    {
        throw new AlfrescoRuntimeException("The content reader mimetype must be set: " + reader);
    }
    String targetMimetype = writer.getMimetype();
    if (targetMimetype == null)
    {
        throw new AlfrescoRuntimeException("The content writer mimetype must be set: " + writer);
    }
    
    long sourceSize = reader.getSize();
    try
    {
        // look for a transformer
        transformerDebug.pushAvailable(reader.getContentUrl(), sourceMimetype, targetMimetype, options);
        List<ContentTransformer> transformers = getActiveTransformers(sourceMimetype, sourceSize, targetMimetype, options);
        transformerDebug.availableTransformers(transformers, sourceSize, options, "ContentService.isTransformable(...)");
        
        return transformers.size() > 0; 
    }
    finally
    {
        transformerDebug.popAvailable();
    }
}
 
Example 29
Project: alfresco-repository   File: StringExtractingContentTransformerTest.java   View source code 5 votes vote down vote up
/**
 * Generate a large file and then transform it using the text extractor.
 * We are not creating super-large file (1GB) in order to test the transform
 * as it takes too long to create the file in the first place.  Rather,
 * this test can be used during profiling to ensure that memory is not
 * being consumed.
 */
public void testLargeFileStreaming() throws Exception
{
    File sourceFile = TempFileProvider.createTempFile(getName(), ".txt");
    
    int chars = 1000000;  // a million characters should do the trick
    Random random = new Random();
    
    Writer charWriter = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(sourceFile)));
    for (int i = 0; i < chars; i++)
    {
        char next = (char)(random.nextDouble() * 93D + 32D);
        charWriter.write(next);
    }
    charWriter.close();
    
    // get a reader and a writer
    ContentReader reader = new FileContentReader(sourceFile);
    reader.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    
    File outputFile = TempFileProvider.createTempFile(getName(), ".txt");
    ContentWriter writer = new FileContentWriter(outputFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    
    // transform
    transformer.transform(reader, writer);
    
    // delete files
    sourceFile.delete();
    outputFile.delete();
}
 
Example 30
Project: alfresco-object-storage-connectors   File: OpenIOContentReader.java   View source code 5 votes vote down vote up
@Override
protected ContentReader createReader() {
	if (logger.isDebugEnabled()) {
		logger.debug("Called createReader for contentUrl -> " + getContentUrl());
	}
	return new OpenIOContentReader(this.client, this.oioUrl);
}
 
Example 31
Project: alfresco-repository   File: FailoverUnsupportedSubtransformerTest.java   View source code 5 votes vote down vote up
public void testExcelToPdfConversion() throws Exception
{
    String[] quickFiles = getQuickFilenames(sourceMimeType);
    for (String quickFile : quickFiles)
    {
        String sourceExtension = quickFile.substring(quickFile.lastIndexOf('.') + 1);

        // is there a test file for this conversion?
        File sourceFile = AbstractContentTransformerTest.loadNamedQuickTestFile(quickFile);
        if (sourceFile == null)
        {
            continue; // no test file available for that extension
        }
        ContentReader sourceReader = new FileContentReader(sourceFile);

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

        // do the transformation
        sourceReader.setMimetype(sourceMimeType);
        targetWriter.setMimetype(targetMimeType);
        try
        {
            transformer.transform(sourceReader.getReader(), targetWriter);
        }
        catch (ContentIOException e)
        {
            // all transformers expected to fail for password protected MS office document
        }
        
        if (transformer.getTriggered().getValue())
        {
            org.junit.Assert.fail("final AbstractContentTransformer2.transform was called for html2pdf");
        }
    }
}
 
Example 32
Project: alfresco-repository   File: TransformerPropertyGetterTest.java   View source code 5 votes vote down vote up
private void normalTest(boolean isAvailable)
{
    AbstractContentTransformer2 simple = new AbstractContentTransformer2() {
        @Override
        protected void transformInternal(ContentReader reader, ContentWriter writer,
                TransformationOptions options) throws Exception
        {
        }};
    simple.setBeanName("transformer.exampleSimple");
    
    when(transformerRegistry.getAllTransformers()).thenReturn(Arrays.asList(new ContentTransformer[] {(ContentTransformer)simple}));
    if (isAvailable)
    {
        when(transformerRegistry.getTransformers()).thenReturn(Arrays.asList(new ContentTransformer[] {(ContentTransformer)simple}));
    }

    String actual = new TransformerPropertyGetter(false, transformerProperties,
            mimetypeService, transformerRegistry, transformerLog, transformerDebugLog).toString();
    
    assertEquals("# LOG and DEBUG history sizes\n" +
            "# ===========================\n" +
            "# Use small values as these logs are held in memory. 0 to disable.\n" +
            "# transformer.log.entries=0\n" +
            "# transformer.debug.entries=0\n" +
            "\n" +
            "# Transformers without extra configuration settings\n" +
            "# =================================================\n" +
            "\n" +
            "# exampleSimple\n" +
            "# -------------\n" +
            (isAvailable ? "" : "# content.transformer.exampleSimple.available=false\n"), actual);
}
 
Example 33
Project: alfresco-repository   File: XMLUtil.java   View source code 5 votes vote down vote up
/** utility function for parsing xml */
public static Document parse(final NodeRef nodeRef,
                             final ContentService contentService)
   throws SAXException,
   IOException
{
   final ContentReader contentReader = 
      contentService.getReader(nodeRef, ContentModel.TYPE_CONTENT);
   final InputStream in = contentReader.getContentInputStream();
   return XMLUtil.parse(in);
}
 
Example 34
Project: alfresco-repository   File: DictionaryRepositoryBootstrap.java   View source code 5 votes vote down vote up
/**
 * Create a M2Model from a dictionary model node
 * 
 * @param nodeRef   the dictionary model node reference
 * @return          the M2Model
 */
public M2Model createM2Model(NodeRef nodeRef)
{
    M2Model model = null;
    ContentReader contentReader = this.contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
    if (contentReader != null)
    {
        if (contentReader instanceof EmptyContentReader)
        {
            // belts-and-braces
            logger.error("Failed to create model (due to EmptyContentReader): "+nodeRef);
        }
        else
        {
            InputStream is = null;
            try
            {
                is = contentReader.getContentInputStream();
                model = M2Model.createModel(is);
            }
            finally
            {
                if (is != null)
                {
                    try
                    {
                        is.close();
                    }
                    catch (IOException e)
                    {
                        logger.error("Failed to close input stream for " + nodeRef);
                    }
                }
            }
        }
    }
    // TODO should we inactivate the model node and put the error somewhere??
    return model;
}
 
Example 35
Project: alfresco-repository   File: EMLTransformerTest.java   View source code 5 votes vote down vote up
/**
 * Test transforming a valid eml file to pdf using complex transformer ("Rfc822ToPdf") - eg. for HTML5 preview
 */
public void testRFC822ToPdf() throws Exception
{
    String sourceMimetype = MimetypeMap.MIMETYPE_RFC822;
    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.Rfc822ToPdf"));

    // note: txt -> pdf currently uses OpenOffice/LibreOffice
    if (! isOpenOfficeWorkerAvailable())
    {
        // no connection
        System.err.println("ooWorker available - skipping testRFC822ToPdf !!");
        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 emlSourceFile = loadQuickTestFile("eml");
    ContentReader sourceReader = new FileContentReader(emlSourceFile);

    // 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);
}
 
Example 36
Project: alfresco-remote-api   File: GetMethod.java   View source code 5 votes vote down vote up
protected void readContent(FileInfo realNodeInfo, ContentReader reader) throws IOException,
            WebDAVServerException
{
    try
    {
        attemptReadContent(realNodeInfo, reader);                
    }
    catch (final Throwable e)
    {
        boolean logAsError = true;
        Throwable t = e;
        // MNT-8989: Traverse the exception cause hierarchy, if we find a SocketException at fault,
        // assume this is a dropped connection and do not log a stack trace.
        int levels = 0;
        while (t.getCause() != null)
        {
            if (t == t.getCause() || ++levels == MAX_RECURSE_ERROR_STACK)
            {
                // Avoid infinite loops.
                break;
            }
            t = t.getCause();
            if (t instanceof SocketException || t.getClass().getSimpleName().equals("ClientAbortException"))
            {
                logAsError = false;
            }
        }
        
        if (logAsError && logger.isErrorEnabled())
        {
            // Only log at ERROR level when not a SocketException as underlying cause.
            logger.error("Error while reading content", e);
        }
        else if (logger.isDebugEnabled())
        {
            // Log other errors at DEBUG level.
            logger.debug("Error while reading content", e);                
        }
        
        // Note no cause parameter supplied - avoid logging stack trace elsewhere.
        throw new WebDAVServerException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
 
Example 37
Project: alfresco-repository   File: AbstractRenderingEngine.java   View source code 5 votes vote down vote up
public ContentReader makeContentReader()
{
    QName srcContentProp = getParamWithDefault(PARAM_SOURCE_CONTENT_PROPERTY, DEFAULT_CONTENT_PROPERTY);
    ContentReader contentReader = contentService.getReader(sourceNode, srcContentProp);
    if (contentReader == null || !contentReader.exists())
    {
        throw new UnimportantTransformException(CONTENT_READER_NOT_FOUND_MESSAGE);
    }
    return contentReader;
}
 
Example 38
Project: alfresco-repository   File: RoutingContentServiceTest.java   View source code 5 votes vote down vote up
public void testNullReaderForNullUrl() throws Exception
{
    // set the property, but with a null URL
    ContentData contentData = new ContentData(null, null, 0L, null);
    nodeService.setProperty(contentNodeRef, ContentModel.PROP_CONTENT, contentData);

    // get the reader
    ContentReader reader = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertNull("Reader must be null if the content URL is null", reader);
}
 
Example 39
Project: alfresco-repository   File: DownloadServiceIntegrationTest.java   View source code 5 votes vote down vote up
private Set<String> getEntries(final NodeRef downloadNode)
{
    return TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Set<String>>()
    {

        @Override
        public Set<String> execute() throws Throwable
        {
            Set<String> entryNames = new TreeSet<String>();
            ContentReader reader = CONTENT_SERVICE.getReader(downloadNode, ContentModel.PROP_CONTENT);
            ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(reader.getContentInputStream());
            try 
            {
                ZipArchiveEntry zipEntry = zipInputStream.getNextZipEntry();
                while (zipEntry != null)
                {
                    String name = zipEntry.getName();
                    entryNames.add(name);
                    zipEntry = zipInputStream.getNextZipEntry();
                }
            }
            finally
            {
                zipInputStream.close();
            }
            return entryNames;
        }
    });
}
 
Example 40
Project: alfresco-remote-api   File: HttpRangeProcessor.java   View source code 5 votes vote down vote up
/**
 * Process a range header for a WebScriptResponse - handles single and multiple range requests.
 * 
 * @param res the webscript response
 * @param reader the content reader
 * @param range the byte range
 * @param ref the content NodeRef
 * @param property the content property
 * @param mimetype the content mimetype
 * @param userAgent the user agent string
 * @return whether or not the range could be processed
 * @throws IOException
 */
public boolean processRange(WebScriptResponse res, ContentReader reader, String range,
      NodeRef ref, QName property, String mimetype, String userAgent)
   throws IOException
{
   // test for multiple byte ranges present in header
   if (range.indexOf(',') == -1)
   {
      return processSingleRange(res, reader, range, mimetype);
   }
   else
   {
      return processMultiRange(res, range, ref, property, mimetype, userAgent);
   }
}