Java Code Examples for org.alfresco.service.cmr.repository.ContentWriter#getReader()

The following examples show how to use org.alfresco.service.cmr.repository.ContentWriter#getReader() . 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: AbstractMetadataExtracterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testZeroLengthFile() throws Exception
{
    MetadataExtracter extractor = getExtracter();
    File file = TempFileProvider.createTempFile(getName(), ".bin");
    ContentWriter writer = new FileContentWriter(file);
    writer.getContentOutputStream().close();
    ContentReader reader = writer.getReader();
    // Try the zero length file against all supported mimetypes.
    // Note: Normally the reader would need to be fetched for each access, but we need to be sure
    // that the content is not accessed on the reader AT ALL.
    PropertyMap properties = new PropertyMap();
    List<String> mimetypes = mimetypeMap.getMimetypes();
    for (String mimetype : mimetypes)
    {
        if (!extractor.isSupported(mimetype))
        {
            // Not interested
            continue;
        }
        reader.setMimetype(mimetype);
        extractor.extract(reader, properties);
        assertEquals("There should not be any new properties", 0, properties.size());
    }
}
 
Example 2
Source File: AbstractWritableContentStoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testReadAndWriteStreamByPush() throws Exception
{
    ContentWriter writer = getWriter();

    String content = "Some Random Content";
    // get the content output stream
    OutputStream os = writer.getContentOutputStream();
    os.write(content.getBytes());
    assertFalse("Stream has not been closed", writer.isClosed());
    // close the stream and check again
    os.close();
    assertTrue("Stream close not detected", writer.isClosed());
    
    // pull the content from a stream
    ContentReader reader = writer.getReader();
    InputStream is = reader.getContentInputStream();
    byte[] buffer = new byte[100];
    int count = is.read(buffer);
    assertEquals("No content read", content.length(), count);
    is.close();
    String check = new String(buffer, 0, count);
    
    assertEquals("Write out of and read into files failed", content, check);
}
 
Example 3
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 4
Source File: PoiHssfContentTransformerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 5
Source File: AbstractWritableContentStoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 6
Source File: FullTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 7
Source File: LocalSynchronousTransformClientIntegrationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void checkTransform(String testFileName, String targetMimetype, Map<String, String> actualOptions, boolean expectedToPass)
{
    if (expectedToPass)
    {
        NodeRef sourceNode = transactionService.getRetryingTransactionHelper().doInTransaction(() ->
                createContentNodeFromQuickFile(testFileName));
        ContentReader reader = contentService.getReader(sourceNode, PROP_CONTENT);
        ContentWriter writer = contentService.getTempWriter();
        writer.setMimetype(targetMimetype);
        synchronousTransformClient.transform(reader, writer, actualOptions, null, sourceNode);

        ContentReader transformReader = writer.getReader();
        String content = transformReader == null ? null : transformReader.getContentString();
        content = content == null || content.isEmpty() ? null : content;
        assertNotNull("The synchronous transform resulted in no content", content);
    }
}
 
Example 8
Source File: AbstractWritableContentStoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 9
Source File: AbstractWritableContentStoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Check that a reader is immutable, i.e. that a reader fetched before a
 * write doesn't suddenly become aware of the content once it has been written.
 */
@Test
public void testReaderImmutability()
{
    ContentWriter writer = getWriter();
    
    ContentReader readerBeforeWrite = writer.getReader();
    assertNotNull(readerBeforeWrite);
    assertFalse(readerBeforeWrite.exists());
    
    // Write some content
    writer.putContent("Content for testReaderImmutability");
    assertFalse("Reader's state changed after write", readerBeforeWrite.exists());
    try
    {
        readerBeforeWrite.getContentString();
        fail("Reader's state changed after write");
    }
    catch (ContentIOException e)
    {
        // Expected
    }
    
    // A new reader should work
    ContentReader readerAfterWrite = writer.getReader();
    assertTrue("New reader after write should be directed to new content", readerAfterWrite.exists());
}
 
Example 10
Source File: AbstractWritableContentStoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testReadAndWriteFile() throws Exception
{
    ContentWriter writer = getWriter();
    
    File sourceFile = TempFileProvider.createTempFile("testReadAndWriteFile", ".txt");
    sourceFile.deleteOnExit();
    // dump some content into the temp file
    String content = "ABC";
    FileOutputStream os = new FileOutputStream(sourceFile);
    os.write(content.getBytes());
    os.flush();
    os.close();
    
    // put our temp file's content
    writer.putContent(sourceFile);
    assertTrue("Stream close not detected", writer.isClosed());
    
    // create a sink temp file
    File sinkFile = TempFileProvider.createTempFile("testReadAndWriteFile", ".txt");
    sinkFile.deleteOnExit();
    
    // get the content into our temp file
    ContentReader reader = writer.getReader();
    reader.getContent(sinkFile);
    
    // read the sink file manually
    FileInputStream is = new FileInputStream(sinkFile);
    byte[] buffer = new byte[100];
    int count = is.read(buffer);
    assertEquals("No content read", 3, count);
    is.close();
    String check = new String(buffer, 0, count);
    
    assertEquals("Write out of and read into files failed", content, check);
}
 
Example 11
Source File: AbstractWritableContentStoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * The simplest test.  Write a string and read it again, checking that we receive the same values.
 * If the resource accessed by {@link #getReader(String)} and {@link #getWriter()} is not the same, then
 * values written and read won't be the same.
 */
@Test
public void testWriteAndReadString() throws Exception
{
    ContentWriter writer = getWriter();
    
    String content = "ABC";
    writer.putContent(content);
    assertTrue("Stream close not detected", writer.isClosed());

    ContentReader reader = writer.getReader();
    String check = reader.getContentString();
    assertTrue("Read and write may not share same resource", check.length() > 0);
    assertEquals("Write and read didn't work", content, check);
}
 
Example 12
Source File: FileContentReader.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Checks the existing reader provided and replaces it with a reader onto some
 * fake content if required.  If the existing reader is invalid, an debug message
 * will be logged under this classname category.
 * <p>
 * It is a convenience method that clients can use to cheaply get a reader that
 * is valid, regardless of whether the initial reader is valid.
 * 
 * @param existingReader a potentially invalid reader or null
 * @param msgTemplate the template message that will used to format the final <i>fake</i> content
 * @param args arguments to put into the <i>fake</i> content
 * @return Returns a the existing reader or a new reader onto some generated text content
 */
public static ContentReader getSafeContentReader(ContentReader existingReader, String msgTemplate, Object ... args)
{
    ContentReader reader = existingReader;
    if (existingReader == null || !existingReader.exists())
    {
        // the content was never written to the node or the underlying content is missing
        String fakeContent = MessageFormat.format(msgTemplate, args);
        
        // log it
        if (logger.isDebugEnabled())
        {
            logger.debug(fakeContent);
        }
        
        // fake the content
        File tempFile = TempFileProvider.createTempFile("getSafeContentReader_", ".txt");
        ContentWriter writer = new FileContentWriter(tempFile);
        writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        writer.setEncoding("UTF-8");
        writer.putContent(fakeContent);
        // grab the reader from the temp writer
        reader = writer.getReader();
    }
    // done
    if (logger.isDebugEnabled())
    {
        logger.debug("Created safe content reader: \n" +
                "   existing reader: " + existingReader + "\n" +
                "   safe reader: " + reader);
    }
    return reader;
}
 
Example 13
Source File: AbstractWritableContentStoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testMimetypAndEncodingAndLocale() throws Exception
{
    ContentWriter writer = getWriter();
    // set mimetype and encoding
    writer.setMimetype("text/plain");
    writer.setEncoding("UTF-16");
    writer.setLocale(Locale.CHINESE);
    
    // create a UTF-16 string
    String content = "A little bit o' this and a little bit o' that";
    byte[] bytesUtf16 = content.getBytes("UTF-16");
    // write the bytes directly to the writer
    OutputStream os = writer.getContentOutputStream();
    os.write(bytesUtf16);
    os.close();
    
    // now get a reader from the writer
    ContentReader reader = writer.getReader();
    assertEquals("Writer -> Reader content URL mismatch", writer.getContentUrl(), reader.getContentUrl());
    assertEquals("Writer -> Reader mimetype mismatch", writer.getMimetype(), reader.getMimetype());
    assertEquals("Writer -> Reader encoding mismatch", writer.getEncoding(), reader.getEncoding());
    assertEquals("Writer -> Reader locale mismatch", writer.getLocale(), reader.getLocale());
    
    // now get the string directly from the reader
    String contentCheck = reader.getContentString();     // internally it should have taken care of the encoding
    assertEquals("Encoding and decoding of strings failed", content, contentCheck);
}
 
Example 14
Source File: StringExtractingContentTransformerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Writes some content using the mimetype and encoding specified.
 *
 * @param mimetype String
 * @param encoding String
 * @return Returns a reader onto the newly written content
 */
private ContentReader writeContent(String mimetype, String encoding)
{
    ContentWriter writer = new FileContentWriter(getTempFile());
    writer.setMimetype(mimetype);
    writer.setEncoding(encoding);
    // put content
    writer.putContent(SOME_CONTENT);
    // return a reader onto the new content
    return writer.getReader();
}
 
Example 15
Source File: ImageMagickContentTransformerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected long transform(String sourceMimetype, String targetMimetype, TransformationOptions options) throws IOException
{
    long size = -1;
    String[] quickFiles = getQuickFilenames(sourceMimetype);
    for (String quickFile : quickFiles)
    {
        String sourceExtension = quickFile.substring(quickFile.lastIndexOf('.')+1);
        String targetExtension = mimetypeService.getExtension(targetMimetype);
        
        // 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 + "_",
                "." + targetExtension);
        ContentWriter targetWriter = new FileContentWriter(targetFile);
        
        // do the transformation
        sourceReader.setMimetype(sourceMimetype);
        targetWriter.setMimetype(targetMimetype);
        transformer.transform(sourceReader.getReader(), targetWriter, options);
        ContentReader targetReader = targetWriter.getReader();
        size = targetReader.getSize();
        assertTrue(size > 0);
    }
    return size;
}
 
Example 16
Source File: OpenCmisLocalTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void DISABLED_testBasicFileOps()
{
    Repository repository = getRepository("admin", "admin");
    Session session = repository.createSession();
    Folder rootFolder = session.getRootFolder();
    // create folder
    Map<String,String> folderProps = new HashMap<String, String>();
    {
        folderProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
        folderProps.put(PropertyIds.NAME, getName() + "-" + GUID.generate());
    }
    Folder folder = rootFolder.createFolder(folderProps, null, null, null, session.getDefaultContext());
    
    Map<String, String> fileProps = new HashMap<String, String>();
    {
        fileProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
        fileProps.put(PropertyIds.NAME, "mydoc-" + GUID.generate() + ".txt");
    }
    ContentStreamImpl fileContent = new ContentStreamImpl();
    {
        ContentWriter writer = new FileContentWriter(TempFileProvider.createTempFile(getName(), ".txt"));
        writer.putContent("Ipsum and so on");
        ContentReader reader = writer.getReader();
        fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        fileContent.setStream(reader.getContentInputStream());
    }
    folder.createDocument(fileProps, fileContent, VersioningState.MAJOR);
}
 
Example 17
Source File: AbstractWritableContentStoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testClosedState() throws Exception
{
    ContentWriter writer = getWriter();
    ContentReader readerBeforeWrite = writer.getReader();
    
    // check that streams are not flagged as closed
    assertFalse("Reader stream should not be closed", readerBeforeWrite.isClosed());
    assertFalse("Writer stream should not be closed", writer.isClosed());
    
    // write some stuff
    writer.putContent("ABC");
    // check that the write has been closed
    assertTrue("Writer stream should be closed", writer.isClosed());
    
    // check that we can get a reader from the writer
    ContentReader readerAfterWrite = writer.getReader();
    assertNotNull("No reader given by closed writer", readerAfterWrite);
    assertFalse("Before-content reader should not be affected by content updates", readerBeforeWrite.isClosed());
    assertFalse("After content reader should not be closed", readerAfterWrite.isClosed());
    
    // check that the instance is new each time
    ContentReader newReaderA = writer.getReader();
    ContentReader newReaderB = writer.getReader();
    assertFalse("Reader must always be a new instance", newReaderA == newReaderB);
    
    // check that the readers refer to the same URL
    assertEquals("Readers should refer to same URL",
            readerBeforeWrite.getContentUrl(), readerAfterWrite.getContentUrl());
    
    // read their content
    try
    {
        readerBeforeWrite.getContentString();
    }
    catch (Throwable e)
    {
        // The content doesn't exist for this reader
    }
    String contentCheck = readerAfterWrite.getContentString();
    assertEquals("Incorrect content", "ABC", contentCheck);
    
    // check closed state of readers
    assertFalse("Before-content reader stream should not be closed", readerBeforeWrite.isClosed());
    assertTrue("After-content reader should be closed after reading", readerAfterWrite.isClosed());
}
 
Example 18
Source File: TestCMIS.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
  public void testALF19320() throws Exception
  {
      final TestNetwork network1 = getTestFixture().getRandomNetwork();

      String username = "user" + System.currentTimeMillis();
PersonInfo personInfo = new PersonInfo(username, username, username, TEST_PASSWORD, null, null, null, null, null, null, null);
      TestPerson person1 = network1.createUser(personInfo);
      String person1Id = person1.getId();

      final String siteName = "site" + System.currentTimeMillis();

      TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef>()
      {
          @Override
          public NodeRef doWork() throws Exception
          {
              SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PRIVATE);
              TestSite site = repoService.createSite(null, siteInfo);

              String name = GUID.generate();
		NodeRef folderNodeRef = repoService.createFolder(site.getContainerNodeRef(DOCUMENT_LIBRARY_CONTAINER_NAME), name);
              return folderNodeRef;
          }
      }, person1Id, network1.getId());

      // Create a document...
      publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));
CmisSession cmisSession = publicApiClient.createPublicApiCMISSession(Binding.atom, CMIS_VERSION_10, AlfrescoObjectFactoryImpl.class.getName());
      AlfrescoFolder docLibrary = (AlfrescoFolder)cmisSession.getObjectByPath("/Sites/" + siteName + "/documentLibrary");
      Map<String, String> properties = new HashMap<String, String>();
      {
          // create a document with 2 aspects
          properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document,P:cm:titled,P:cm:author");
          properties.put(PropertyIds.NAME, "mydoc-" + GUID.generate() + ".txt");
      }
      ContentStreamImpl fileContent = new ContentStreamImpl();
      {
          ContentWriter writer = new FileContentWriter(TempFileProvider.createTempFile(GUID.generate(), ".txt"));
          writer.putContent("Ipsum and so on");
          ContentReader reader = writer.getReader();
          fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
          fileContent.setStream(reader.getContentInputStream());
      }
      
      AlfrescoDocument doc = (AlfrescoDocument)docLibrary.createDocument(properties, fileContent, VersioningState.MAJOR);
      String versionLabel = doc.getVersionLabel();
assertEquals(CMIS_VERSION_10, versionLabel);

      AlfrescoDocument doc1 = (AlfrescoDocument)doc.getObjectOfLatestVersion(false);
      String versionLabel1 = doc1.getVersionLabel();
assertEquals(CMIS_VERSION_10, versionLabel1);
  }
 
Example 19
Source File: AbstractWritableContentStoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Checks that the various methods of obtaining a reader are supported.
 */
@Test
public synchronized void testGetReader() throws Exception
{
    ContentStore store = getStore();
    ContentWriter writer = store.getWriter(ContentStore.NEW_CONTENT_CONTEXT);
    String contentUrl = writer.getContentUrl();
    
    // Check that a reader is available from the store
    ContentReader readerFromStoreBeforeWrite = store.getReader(contentUrl);
    assertNotNull("A reader must always be available from the store", readerFromStoreBeforeWrite);
    
    // check that a reader is available from the writer
    ContentReader readerFromWriterBeforeWrite = writer.getReader();
    assertNotNull("A reader must always be available from the writer", readerFromWriterBeforeWrite);
    
    String content = "Content for testGetReader";
    
    // write some content
    long before = System.currentTimeMillis();
    this.wait(1000L);
    writer.setMimetype("text/plain");
    writer.setEncoding("UTF-8");
    writer.setLocale(Locale.CHINESE);
    writer.putContent(content);
    this.wait(1000L);
    long after = System.currentTimeMillis();
    
    // get a reader from the store
    ContentReader readerFromStore = store.getReader(contentUrl);
    assertNotNull(readerFromStore);
    assertTrue(readerFromStore.exists());
    // Store-provided readers don't have context other than URLs
    // assertEquals(writer.getContentData(), readerFromStore.getContentData());
    assertEquals(content, readerFromStore.getContentString());
    
    // get a reader from the writer
    ContentReader readerFromWriter = writer.getReader();
    assertNotNull(readerFromWriter);
    assertTrue(readerFromWriter.exists());
    assertEquals(writer.getContentData(), readerFromWriter.getContentData());
    assertEquals(content, readerFromWriter.getContentString());
    
    // get another reader from the reader
    ContentReader readerFromReader = readerFromWriter.getReader();
    assertNotNull(readerFromReader);
    assertTrue(readerFromReader.exists());
    assertEquals(writer.getContentData(), readerFromReader.getContentData());
    assertEquals(content, readerFromReader.getContentString());
    
    // check that the length is correct
    int length = content.getBytes(writer.getEncoding()).length;
    assertEquals("Reader content length is incorrect", length, readerFromWriter.getSize());

    // check that the last modified time is correct
    long modifiedTimeCheck = readerFromWriter.getLastModified();

    // On some versionms of Linux (e.g. Centos) this test won't work as the 
    // modified time accuracy is only to the second.
    long beforeSeconds = before/1000L;
    long afterSeconds = after/1000L;
    long modifiedTimeCheckSeconds = modifiedTimeCheck/1000L;

    assertTrue("Reader last modified is incorrect", beforeSeconds <= modifiedTimeCheckSeconds);
    assertTrue("Reader last modified is incorrect", modifiedTimeCheckSeconds <= afterSeconds);
}
 
Example 20
Source File: BaseContentNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @param length      Length of the character stream to return, or -1 for all
 * 
 * @return the binary content stream converted to text using any available transformer
 *         if fails to convert then null will be returned
 */
public String getContentAsText(int length)
{
    String result = null;
    
    if (MimetypeMap.MIMETYPE_TEXT_PLAIN.equals(getMimetype()))
    {
        result = getContentMaxLength(length);
    }
    else
    {
        // get the content reader
        ContentService contentService = services.getContentService();
        SynchronousTransformClient synchronousTransformClient = services.getSynchronousTransformClient();
        NodeRef nodeRef = getNodeRef();
        ContentReader reader = contentService.getReader(nodeRef, property);
        if (reader == null)
        {
            return ""; // Caller of this method returns "" if there is an IOException
        }
        
        // get the writer and set it up for text convert
        ContentWriter writer = contentService.getTempWriter();
        writer.setMimetype("text/plain"); 
        writer.setEncoding(reader.getEncoding());
        
        TransformationOptions options = new TransformationOptions();
        options.setSourceNodeRef(nodeRef);

        // try and transform the content
        try
        {
            try
            {
                synchronousTransformClient.transform(reader, writer, Collections.emptyMap(), null, nodeRef);

                ContentReader resultReader = writer.getReader();
                if (resultReader != null && reader.exists())
                {
                    if (length != -1)
                    {
                        result = resultReader.getContentString(length);
                    }
                    else
                    {
                        result = resultReader.getContentString();
                    }
                }
            }
            catch (UnsupportedTransformationException ignore)
            {
            }
        }
        catch (NoTransformerException|UnsupportedTransformationException| ContentIOException e)
        {
            // ignore
        }
    }
    return result;
}