Java源码示例:org.alfresco.service.cmr.repository.ContentReader
示例1
public InputStream getLogInputStream(String transferId)
throws TransferException
{
NodeRef transferRecord = getTransferRecord(transferId);
ContentReader reader = contentService.getReader(transferRecord, ContentModel.PROP_CONTENT);
if(reader != null)
{
return reader.getContentInputStream();
}
else
{
return null;
}
}
示例2
/**
* Checks that multiple writes can occur to the same node outside of any transactions.
* <p>
* It is only when the streams are closed that the node is updated.
*/
public void testConcurrentWritesNoTxn() throws Exception
{
// ensure that the transaction is ended - ofcourse, we need to force a commit
txn.commit();
txn = null;
ContentWriter writer1 = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
ContentWriter writer2 = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
ContentWriter writer3 = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
writer1.putContent("writer1 wrote this");
writer2.putContent("writer2 wrote this");
writer3.putContent("writer3 wrote this");
// get the content
ContentReader reader = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
String contentCheck = reader.getContentString();
assertEquals("Content check failed", "writer3 wrote this", contentCheck);
}
示例3
/**
* @return Returns a valid reader from one of the stores otherwise
* a {@link EmptyContentReader} is returned.
*/
public ContentReader getReader(String contentUrl) throws ContentIOException
{
ContentStore store = selectReadStore(contentUrl);
if (store != null)
{
if (logger.isDebugEnabled())
{
logger.debug("Getting reader from store: \n" +
" Content URL: " + contentUrl + "\n" +
" Store: " + store);
}
return store.getReader(contentUrl);
}
else
{
if (logger.isDebugEnabled())
{
logger.debug("Getting empty reader for content URL: " + contentUrl);
}
return new EmptyContentReader(contentUrl);
}
}
示例4
@Deprecated
@Override
public void transform(ContentReader reader, ContentWriter writer, TransformationOptions transformationOptions)
throws NoTransformerException, ContentIOException
{
try
{
Map<String, String> options = converter.getOptions(transformationOptions, null, null);
synchronousTransformClient.transform(reader, writer, options, null, null);
}
catch (UnsupportedTransformationException ute)
{
throw newNoTransformerException(reader, writer);
}
catch (IllegalArgumentException iae)
{
if (iae.getMessage().contains("sourceNodeRef null has no content"))
{
throw newNoTransformerException(reader, writer);
}
throw new AlfrescoRuntimeException(iae.getMessage(), iae);
}
}
示例5
/**
* @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);
}
}
示例6
@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;
}
}
示例7
/**
* 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));
}
示例8
public void testXpathSelector() throws Exception
{
// Load the example files
ContentReader alfrescoModelReader = getReader(FILE_ALFRESCO_MODEL);
assertTrue(alfrescoModelReader.exists());
ContentReader eclipseProjectReader = getReader(FILE_ECLIPSE_PROJECT);
assertTrue(eclipseProjectReader.exists());
// Check with an alfresco model document
MetadataExtracter alfrescoModelExtracter = xpathMetadataExtracterSelector.getWorker(alfrescoModelReader);
assertNotNull("Failed to select correct extracter", alfrescoModelExtracter);
assertTrue("Incorrect extracter instance selected", alfrescoModelMetadataExtracter == alfrescoModelExtracter);
assertFalse("Read channel not closed", alfrescoModelReader.isChannelOpen());
// Check with an eclipse project document
MetadataExtracter eclipseProjectExtracter = xpathMetadataExtracterSelector.getWorker(eclipseProjectReader);
assertNotNull("Failed to select correct extracter", eclipseProjectExtracter);
assertTrue("Incorrect extracter instance selected", eclipseProjectMetadataExtracter == eclipseProjectExtracter);
assertFalse("Read channel not closed", eclipseProjectReader.isChannelOpen());
}
示例9
@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", "html",
"sourceMimetype", sourceMimetype,
"sourceExtension", sourceExtension,
"targetMimetype", targetMimetype,
SOURCE_ENCODING, sourceEncoding);
}
示例10
public Map<String, Serializable> extractRaw(ContentReader reader)
throws Throwable
{
String sourceMimetype = reader.getMimetype();
if (logger.isDebugEnabled())
{
StringBuilder msg = new StringBuilder();
msg.append("Extracting metadata content from ")
.append(sourceMimetype);
logger.debug(msg.toString());
}
// create temporary files to convert from and to
File tempFile = TempFileProvider.createTempFile(this.getClass()
.getSimpleName()
+ "-", "." + mimetypeService.getExtension(sourceMimetype));
// download the content from the source reader
reader.getContent(tempFile);
ResultsCallback callback = new ResultsCallback();
jodc.getOfficeManager().execute(new ExtractMetadataOfficeTask(tempFile, callback));
return callback.getResults();
}
示例11
public void testGetContentString_01()
{
// To URL
String url = SpoofedTextContentReader.createContentUrl(Locale.ENGLISH, 12345L, 56L, "harry");
// To Reader
ContentReader reader = new SpoofedTextContentReader(url);
String readerText = reader.getContentString();
assertEquals("harry have voice the from countered growth invited ", readerText);
// Cannot repeat
try
{
reader.getContentString();
fail("Should not be able to reread content.");
}
catch (ContentIOException e)
{
// Expected
}
// Get a new Reader
reader = reader.getReader();
// Get exactly the same text
assertEquals(readerText, reader.getContentString());
}
示例12
/**
* 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));
}
示例13
/**
* Does a comparison of the binaries associated with two readers. Several shortcuts are assumed to be valid:<br/>
* - if the readers are the same instance, then the binaries are the same<br/>
* - if the size field is different, then the binaries are different<br/>
* Otherwise the binaries are {@link EqualsHelper#binaryStreamEquals(InputStream, InputStream) compared}.
*
* @return Returns <tt>true</tt> if the underlying binaries are the same
* @throws ContentIOException
*/
public static boolean compareContentReaders(ContentReader left, ContentReader right) throws ContentIOException
{
if (left == right)
{
return true;
}
else if (left == null || right == null)
{
return false;
}
else if (left.getSize() != right.getSize())
{
return false;
}
InputStream leftIs = left.getContentInputStream();
InputStream rightIs = right.getContentInputStream();
try
{
return EqualsHelper.binaryStreamEquals(leftIs, rightIs);
}
catch (IOException e)
{
throw new ContentIOException(
"Failed to compare content reader streams: \n" +
" Left: " + left + "\n" +
" right: " + right);
}
}
示例14
protected DecompressingContentReader(final ContentReader delegate, final String compressionType,
final Collection<String> mimetypesToCompress, final long properSize)
{
super(delegate);
this.compressionType = compressionType;
this.mimetypesToCompress = mimetypesToCompress;
this.properSize = properSize;
}
示例15
@Override
public void transformInternal(ContentReader reader,
ContentWriter writer, TransformationOptions options)
throws Exception
{
triggered.setValue(true);
reader.getContentString();
// alwaysFail
throw new AlfrescoRuntimeException("Test code intentionally failed method call.");
}
示例16
public void testExtractAlfresocModel() throws Exception
{
// Load the example file
ContentReader reader = getReader(FILE_ALFRESCO_MODEL);
assertTrue(reader.exists());
// Pass it to the extracter
PropertyMap checkProperties = new PropertyMap();
alfrescoModelMetadataExtracter.extract(reader, checkProperties);
// Check the values
assertEquals("Gavin Cornwell", getPropertyValue(checkProperties, ContentModel.PROP_AUTHOR));
assertEquals("fm:forummodel", getPropertyValue(checkProperties, ContentModel.PROP_TITLE));
assertEquals("Forum Model", getPropertyValue(checkProperties, ContentModel.PROP_DESCRIPTION));
}
示例17
/**
* 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);
}
}
示例18
@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());
}
示例19
@Test
public void testImportXMLDocument() throws Exception
{
try
{
FileInfo file = createXmlFile(companyHome);
createXmlFile(companyHome, "TestTableXML.xml", testTableXml);
FileInfo testImportTable = createXmlFile(companyHome, "TestImportTableXML.xml", testImportTableXml);
RenditionDefinition def = renditionService.createRenditionDefinition(QName.createQName("Test"), XSLTRenderingEngine.NAME);
def.setParameterValue(XSLTRenderingEngine.PARAM_TEMPLATE_NODE, testImportTable.getNodeRef());
ChildAssociationRef rendition = renditionService.render(file.getNodeRef(), def);
assertNotNull(rendition);
ContentReader reader = contentService.getReader(rendition.getChildRef(), ContentModel.PROP_CONTENT);
assertNotNull(reader);
String output = reader.getContentString();
log.debug("XSLT Processor output: " + output);
Diff myDiff = new Diff("<html>\n<body>\n<h2>My CD Collection</h2>\n<table border=\"1\">\n<tr bgcolor=\"#9acd32\">\n<th>Title</th><th>Artist</th>\n</tr>\n<tr>\n<td></td><td></td>\n</tr>\n</table>\n</body>\n</html>\n", output);
assertTrue("Pieces of XML are similar " + myDiff, myDiff.similar());
}
catch (Exception ex)
{
log.error("Error!", ex);
fail();
}
}
示例20
protected Map<QName, Serializable> extractFromFile(File sourceFile, String mimetype) throws Exception
{
Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
// construct a reader onto the source file
ContentReader sourceReader = new FileContentReader(sourceFile);
sourceReader.setMimetype(mimetype);
getExtracter().extract(sourceReader, properties);
return properties;
}
示例21
/**
* This is the preferred constructor to use. Takes the properties from content reader that it needs.
* @param reader ContentReader
*/
public BinaryProperty(ContentReader reader)
{
super();
this.mimeType = reader.getMimetype();
this.encoding = reader.getEncoding();
this.length = reader.getSize();
this.locale = reader.getLocale();
}
示例22
@Test
public void getWriterWhenCacheOnInbound() throws ContentIOException, IOException
{
cachingStore = new CachingContentStore(backingStore, cache, true);
ContentContext ctx = ContentContext.NULL_CONTEXT;
ContentWriter bsWriter = mock(ContentWriter.class);
when(backingStore.getWriter(ctx)).thenReturn(bsWriter);
when(bsWriter.getContentUrl()).thenReturn("url");
ContentWriter cacheWriter = mock(ContentWriter.class);
when(cache.getWriter("url")).thenReturn(cacheWriter);
ContentReader readerFromCacheWriter = mock(ContentReader.class);
when(cacheWriter.getReader()).thenReturn(readerFromCacheWriter);
when(readerFromCacheWriter.exists()).thenReturn(true);
when(cacheWriter.getSize()).thenReturn(54321L);
QuotaManagerStrategy quota = mock(QuotaManagerStrategy.class);
cachingStore.setQuota(quota);
// Quota manager interceptor is fired.
when(quota.beforeWritingCacheFile(0L)).thenReturn(true);
cachingStore.getWriter(ctx);
// Check that a listener was attached to cacheWriter with the correct behaviour
ArgumentCaptor<ContentStreamListener> arg = ArgumentCaptor.forClass(ContentStreamListener.class);
verify(cacheWriter).addListener(arg.capture());
// Simulate a stream close
arg.getValue().contentStreamClosed();
// Check behaviour of the listener
verify(bsWriter).putContent(readerFromCacheWriter);
// Post caching quota manager hook is fired.
verify(quota).afterWritingCacheFile(54321L);
}
示例23
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);
}
示例24
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;
}
});
}
示例25
private PostInfo buildPost(NodeRef nodeRef, TopicInfo topic, String name, String preLoadedContents)
{
PostInfoImpl post = new PostInfoImpl(nodeRef, name, topic);
// Grab all the properties, we need the bulk of them anyway
Map<QName,Serializable> props = nodeService.getProperties(nodeRef);
// Start with the auditable properties
post.setCreator((String)props.get(ContentModel.PROP_CREATOR));
post.setModifier((String)props.get(ContentModel.PROP_MODIFIER));
post.setCreatedAt((Date)props.get(ContentModel.PROP_CREATED));
post.setModifiedAt((Date)props.get(ContentModel.PROP_MODIFIED));
post.setUpdatedAt((Date)props.get(ContentModel.PROP_UPDATED));
// Now do the discussion ones
post.setTitle((String)props.get(ContentModel.PROP_TITLE));
// Finally, do the content
String contents = preLoadedContents;
if (contents == null)
{
ContentReader reader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
if (reader != null)
{
contents = reader.getContentString();
}
}
post.setContents(contents);
// All done
return post;
}
示例26
private String runWithinTransaction(String sourceExtension, String targetExtension)
{
String targetMimetype = getMimetype(targetExtension, false);
String sourceMimetype = getMimetype(sourceExtension, true);
File tempFile = TempFileProvider.createTempFile(
"TestTransform_" + sourceExtension + "_", "." + targetExtension);
ContentWriter writer = new FileContentWriter(tempFile);
writer.setMimetype(targetMimetype);
NodeRef sourceNodeRef = null;
StringBuilder sb = new StringBuilder();
try
{
setStringBuilder(sb);
sourceNodeRef = createSourceNode(sourceExtension, sourceMimetype);
ContentReader reader = contentService.getReader(sourceNodeRef, ContentModel.PROP_CONTENT);
SynchronousTransformClient synchronousTransformClient = getSynchronousTransformClient();
Map<String, String> actualOptions = Collections.emptyMap();
synchronousTransformClient.transform(reader, writer, actualOptions, null, sourceNodeRef);
}
catch (Exception e)
{
logger.debug("Unexpected test transform error", e);
}
finally
{
setStringBuilder(null);
deleteSourceNode(sourceNodeRef);
}
return sb.toString();
}
示例27
public Map<String, Serializable> extractRaw(ContentReader reader) throws Throwable
{
Map<String, Serializable> rawMap = newRawMap();
rawMap.put("unknown1", new Integer(1));
rawMap.put("unknown2", "TWO");
return rawMap;
}
示例28
/**
* {@inheritDoc}
*/
@Override
public Map<String, Serializable> extractRaw(ContentReader reader) throws Throwable
{
Map<String, Serializable> rawProperties = newRawMap();
Map<String, Serializable> result = this.worker.extractRaw(reader);
for (Map.Entry<String, Serializable> entry : result.entrySet())
{
putRawValue(entry.getKey(), entry.getValue(), rawProperties);
}
return rawProperties;
}
示例29
/** {@inheritDoc} */
public ContentReader getRawReader(String contentUrl)
{
ContentReader reader = null;
try
{
reader = store.getReader(contentUrl);
}
catch (UnsupportedContentUrlException e)
{
// The URL is not supported, so we spoof it
reader = new EmptyContentReader(contentUrl);
}
if (reader == null)
{
throw new AlfrescoRuntimeException("ContentStore implementations may not return null ContentReaders");
}
// set extra data on the reader
reader.setMimetype(MimetypeMap.MIMETYPE_BINARY);
reader.setEncoding("UTF-8");
reader.setLocale(I18NUtil.getLocale());
// Done
if (logger.isDebugEnabled())
{
logger.debug(
"Direct request for reader: \n" +
" Content URL: " + contentUrl + "\n" +
" Reader: " + reader);
}
return reader;
}
示例30
@Test
public void putForZeroLengthFile()
{
ContentReader contentReader = Mockito.mock(ContentReader.class);
Mockito.when(contentReader.getSize()).thenReturn(0L);
boolean putResult = contentCache.put("", contentReader);
assertFalse("Zero length files should not be cached", putResult);
}