freemarker.template.TemplateNumberModel#org.alfresco.service.cmr.repository.ContentIOException源码实例Demo

下面列出了freemarker.template.TemplateNumberModel#org.alfresco.service.cmr.repository.ContentIOException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * 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]);
}
 
/**
 * Populates a file with the content in the reader, but also converts the encoding to UTF-8.
 */
private void saveContentInUtf8File(ContentReader reader, File file)
{
    String encoding = reader.getEncoding();
    try
    {
        Reader in = new InputStreamReader(reader.getContentInputStream(), encoding);
        Writer out = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file)), "UTF-8");

        FileCopyUtils.copy(in, out);  // both streams are closed
    }
    catch (IOException e)
    {
        throw new ContentIOException("Failed to copy content to file and convert "+encoding+" to UTF-8: \n" +
                "   file: " + file,
                e);
    }
}
 
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());
}
 
/**
 *
 * {@inheritDoc}
 */
@Override
public boolean delete(final String contentUrl) throws ContentIOException
{
    boolean deleted = true;
    final List<ContentStore> stores = this.getAllStores();

    /*
     * This operation has to be performed on all the stores in order to maintain the
     * {@link ContentStore#exists(String)} contract.
     * Still need to apply the isContentUrlSupported guard though.
     */
    for (final ContentStore store : stores)
    {
        if (store.isContentUrlSupported(contentUrl) && store.isWriteSupported())
        {
            deleted &= store.delete(contentUrl);
        }
    }

    LOGGER.debug("Deleted content URL from stores: \n\tStores:  {}\n\tDeleted: {}", stores.size(), deleted);

    return deleted;
}
 
/**
 * {@inheritDoc}
 */
@Override
// same implementation as AbstractContentReader
public String getContentString() throws ContentIOException
{
    try
    {
        // read from the stream into a byte[]
        final InputStream is = this.getContentInputStream();
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        FileCopyUtils.copy(is, os); // both streams are closed
        final byte[] bytes = os.toByteArray();
        // get the encoding for the string
        final String encoding = this.getEncoding();
        // create the string from the byte[] using encoding if necessary
        final String systemEncoding = System.getProperty("file.encoding");
        final String content = (encoding == null) ? new String(bytes, systemEncoding) : new String(bytes, encoding);
        // done
        return content;
    }
    catch (final IOException e)
    {
        throw new ContentIOException("Failed to copy content to string: \n" + "   accessor: " + this, e);
    }
}
 
@Test(expected=RuntimeException.class)
// Check that exceptions raised by the backing store's putContent(ContentReader)
// aren't swallowed and can therefore cause the transaction to fail.
public void exceptionRaisedWhenCopyingTempToBackingStoreIsPropogatedCorrectly() 
    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);
    
    doThrow(new RuntimeException()).when(bsWriter).putContent(any(ContentReader.class));
    
    cachingStore.getWriter(ctx);
    
    // Get the stream listener and trigger it
    ArgumentCaptor<ContentStreamListener> arg = ArgumentCaptor.forClass(ContentStreamListener.class);
    verify(cacheWriter).addListener(arg.capture());
    // Simulate a stream close
    arg.getValue().contentStreamClosed();
}
 
/**
 * @see Channels#newOutputStream(java.nio.channels.WritableByteChannel)
 */
public OutputStream getContentOutputStream() throws ContentIOException
{
    try
    {
        WritableByteChannel channel = getWritableChannel();
        OutputStream is = new BufferedOutputStream(Channels.newOutputStream(channel));
        // done
        return is;
    }
    catch (Throwable e)
    {
        throw new ContentIOException("Failed to open stream onto channel: \n" +
                "   writer: " + this,
                e);
    }
}
 
/**
 * {@inheritDoc}
 */
@Override
public ContentReader getReader() throws ContentIOException
{
    final ContentReader reader;
    if (this.completedWrite)
    {
        reader = new DecryptingContentReaderFacade(super.getReader(), this.key, this.unencryptedSize);
    }
    else
    {
        reader = new EmptyContentReader(this.getContentUrl());
    }

    return reader;
}
 
/**
 * Executes an operation within a new content store context. Code in the provided operation can call
 * {@link #setContextAttribute(String, Object) setContextAttribute} and be sure no {@link IllegalStateException} will be thrown.
 *
 * @param <R>
 *            the return type of the operation to execute
 * @param operation
 *            the operation to execute
 * @return the result of the operation
 */
public static <R> R executeInNewContext(final ContentStoreOperation<R> operation)
{
    final Map<String, Object> oldMap = CONTEXT_ATTRIBUTES.get();
    final Map<String, Object> newMap = new HashMap<>();
    CONTEXT_ATTRIBUTES.set(newMap);
    try
    {
        LOGGER.trace("Running operation {} in new context", operation);
        final R result = operation.execute();
        return result;
    }
    catch (final Exception ex)
    {
        if (ex instanceof RuntimeException)
        {
            throw (RuntimeException) ex;
        }
        LOGGER.debug("Unhandled exception in content store context operation", ex);
        throw new ContentIOException("Unhandled error in content store operation", ex);
    }
    finally
    {
        LOGGER.trace("Leaving context");
        CONTEXT_ATTRIBUTES.set(oldMap);
    }
}
 
@Override
public InputStream getContentInputStream() throws ContentIOException
{
    InputStream result = delegatee.getContentInputStream();

    if (null == releaseableResource)
    {
        releaseableResource = result;
    }

    return result;
}
 
源代码11 项目: alfresco-repository   文件: CropContentMethod.java
/**
 * @see freemarker.template.TemplateMethodModel#exec(java.util.List)
 */
public Object exec(List args) throws TemplateModelException
{
    String result = null;
    
    if (args.size() == 2)
    {
        Object arg0 = args.get(0);
        Object arg1 = args.get(1);
        
        if (arg0 instanceof BeanModel && arg1 instanceof TemplateNumberModel)
        {
            Object wrapped = ((BeanModel)arg0).getWrappedObject();
            if (wrapped instanceof TemplateContentData)
            {
                int bytes = ((TemplateNumberModel)arg1).getAsNumber().intValue();
                
                try 
                {
            	    result = ((TemplateContentData)wrapped).getContentAsText(bytes);
                } 
                catch (ContentIOException e)
                {
                   logger.warn("unable to getContentAsText", e);
            	   /*
                    * Unable to extract content - return empty text instead.
                    * Probably here through a transformation failure.
                    * This method is called from FreeMarker so throwing the 
                    * exception causes problems.
                    */
                   result = "";
                }
            }
        }
    }
    
    return result != null ? result : "";
}
 
/**
 * Forwards the call directly to the first store in the list of stores.
 */
public ContentReader getReader(String contentUrl) throws ContentIOException
{
    if (primaryStore == null)
    {
        throw new AlfrescoRuntimeException("ReplicatingContentStore not initialised");
    }
    
    // get a read lock so that we are sure that no replication is underway
    readLock.lock();
    try
    {
        // get a reader from the primary store
        ContentReader primaryReader = primaryStore.getReader(contentUrl);
        
        // give it straight back if the content is there
        if (primaryReader.exists())
        {
            return primaryReader;
        }

        // the content is not in the primary reader so we have to go looking for it
        for (ContentStore store : secondaryStores)
        {
            ContentReader reader = store.getReader(contentUrl);
            if (reader.exists())
            {
                // found the content in a secondary store
                return reader;
            }
        }

        return primaryReader;
    }
    finally
    {
        readLock.unlock();
    }     
}
 
@Override
public ReadableByteChannel getReadableChannel() throws ContentIOException
{
    ReadableByteChannel result = delegatee.getReadableChannel();

    if (null == releaseableResource)
    {
        releaseableResource = result;
    }

    return result;
}
 
@Override
public void transform(ContentReader reader, ContentWriter writer, Map<String, String> actualOptions, String transformName, NodeRef sourceNodeRef)
{
    String sourceMimetype = reader.getMimetype();
    String targetMimetype = writer.getMimetype();
    if (sourceMimetype.equals(TEST_FAILING_MIME_TYPE) || targetMimetype.equals(TEST_FAILING_MIME_TYPE))
    {
        throw new ContentServiceTransientException("Transformation intentionally failed for test purposes.");
    }
    else if (sourceMimetype.equals(TEST_LONG_RUNNING_MIME_TYPE) || targetMimetype.equals(TEST_LONG_RUNNING_MIME_TYPE))
    {
        try
        {
            Thread.sleep(TEST_LONG_RUNNING_TRANSFORM_TIME);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        writer.putContent("SUCCESS");
    }
    else if (sourceMimetype.equals(TEST_USER_MIME_TYPE) || targetMimetype.equals(TEST_USER_MIME_TYPE))
    {
        String username = AuthenticationUtil.getFullyAuthenticatedUser();
        if (!EXPECTED_USER.equals(username))
        {
            throw new ContentIOException(
                    "Expected username '" + EXPECTED_USER + "' but found '" + username + "'");
        }
        writer.putContent("SUCCESS");
    }
    else
    {
        delegate.transform(reader, writer, actualOptions, transformName, sourceNodeRef);
    }
}
 
public final void transform(
        ContentReader reader,
        ContentWriter writer,
        Map<String, Object> options) throws ContentIOException
{
    this.transform(reader, writer, new TransformationOptions(options));
}
 
/**
 * {@inheritDoc}
 */
@Override
public ReadableByteChannel getReadableChannel() throws ContentIOException
{
    final ReadableByteChannel channel = super.getReadableChannel();
    final ReadableByteChannel eChannel = new DecryptingReadableByteChannel(channel, this.key);
    return eChannel;
}
 
/**
 * @see org.alfresco.repo.content.transform.ContentTransformer#transform(org.alfresco.service.cmr.repository.ContentReader, org.alfresco.service.cmr.repository.ContentWriter, org.alfresco.service.cmr.repository.TransformationOptions)
 */
public final void transform(ContentReader reader, ContentWriter writer, TransformationOptions options)
    throws ContentIOException
{
    Map<String, Object> optionsMap = options.toMap();
    transform(reader, writer, optionsMap);
}
 
/**
 * {@inheritDoc}
 */
@Override
public ContentReader getReader() throws ContentIOException
{
    this.ensureDelegate();
    return this.delegate.getReader();
}
 
源代码19 项目: alfresco-repository   文件: ContentCacheImpl.java
@Override
protected ContentReader createReader() throws ContentIOException
{
    FileContentReader reader = new FileContentReader(getFile(), getContentUrl());
    // TODO: what about reader.setAllowRandomAccess(this.allowRandomAccess); ? 
    return reader;
}
 
/**
 * {@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);
    }
}
 
源代码21 项目: alfresco-repository   文件: FileContentReader.java
@Override
protected ReadableByteChannel getDirectReadableChannel() throws ContentIOException
{
    try
    {
        // the file must exist
        if (!file.exists())
        {
            throw new IOException("File does not exist: " + file);
        }
        // create the channel
        ReadableByteChannel channel = null;
        if (allowRandomAccess)
        {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");  // won't create it
            channel = randomAccessFile.getChannel();
        }
        else
        {
            InputStream is = new FileInputStream(file);
            channel = Channels.newChannel(is);
        }
        // done
        if (logger.isDebugEnabled())
        {
            logger.debug("Opened read channel to file: \n" +
                    "   file: " + file + "\n" +
                    "   random-access: " + allowRandomAccess);
        }
        return channel;
    }
    catch (Throwable e)
    {
        throw new ContentIOException("Failed to open file channel: " + this, e);
    }
}
 
源代码22 项目: alfresco-repository   文件: FileContentStore.java
/**
 * Private: for Spring-constructed instances only.
 * 
 * @param rootDirectory
 *            the root under which files will be stored. The directory will be created if it does not exist.
 */
private FileContentStore(File rootDirectory)
{
    if (!rootDirectory.exists())
    {
        if (!rootDirectory.mkdirs())
        {
            throw new ContentIOException("Failed to create store root: " + rootDirectory, null);
        }
    }
    this.rootDirectory = rootDirectory.getAbsoluteFile();
    rootAbsolutePath = rootDirectory.getAbsolutePath();
    allowRandomAccess = true;
    readOnly = false;
}
 
源代码23 项目: alfresco-repository   文件: FileContentStore.java
/**
 * Creates a file for the specifically provided content URL.  The URL may
 * not already be in use.
 * <p>
 * The store prefix is stripped off the URL and the rest of the URL
 * used directly to create a file.
 * 
 * @param newContentUrl the specific URL to use, which may not be in use
 * @return Returns a new and unique file
 * @throws IOException
 *             if the file or parent directories couldn't be created or if the URL is already in use.
 * @throws UnsupportedOperationException
 *             if the store is read-only
 * 
 * @see #setReadOnly(boolean)
 */
/*package*/ File createNewFile(String newContentUrl) throws IOException
{
    if (readOnly)
    {
        throw new UnsupportedOperationException("This store is currently read-only: " + this);
    }
    
    File file = makeFile(newContentUrl);

    // create the directory, if it doesn't exist
    File dir = file.getParentFile();
    if (!dir.exists())
    {
        makeDirectory(dir);
    }
    
    // create a new, empty file
    boolean created = file.createNewFile();
    if (!created)
    {
        throw new ContentIOException(
                "When specifying a URL for new content, the URL may not be in use already. \n" +
                "   store: " + this + "\n" +
                "   new URL: " + newContentUrl);
    }
    
    // done
    return file;
}
 
源代码24 项目: alfresco-repository   文件: FileContentStore.java
/**
 * Synchronized and retrying directory creation.  Repeated attempts will be made to create the
 * directory, subject to a limit on the number of retries.
 * 
 * @param dir               the directory to create
 * @throws IOException      if an IO error occurs
 */
private synchronized void makeDirectory(File dir) throws IOException
{
    /*
     * Once in this method, the only contention will be from other file stores or processes.
     * This is OK as we have retrying to sort it out.
     */
    if (dir.exists())
    {
        // Beaten to it during synchronization
        return;
    }
    // 20 attempts with 20 ms wait each time
    for (int i = 0; i < 20; i++)
    {
        boolean created = dir.mkdirs();
        if (created)
        {
            // Successfully created
            return;
        }
        // Wait
        try { this.wait(20L); } catch (InterruptedException e) {}
        // Did it get created in the meantime
        if (dir.exists())
        {
            // Beaten to it while asleep
            return;
        }
    }
    // It still didn't succeed
    throw new ContentIOException("Failed to create directory for file storage: " +  dir);
}
 
源代码25 项目: alfresco-repository   文件: FileContentStore.java
private void ensureFileInContentStore(File file)
{
    String fileNormalizedAbsoultePath = FilenameUtils.normalize(file.getAbsolutePath());
    String rootNormalizedAbsolutePath = FilenameUtils.normalize(rootAbsolutePath);
    
    if (!fileNormalizedAbsoultePath.startsWith(rootNormalizedAbsolutePath))
    {
        throw new ContentIOException("Access to files outside of content store root is not allowed: " + file);
    }
}
 
@Deprecated
@Override
public void transform(ContentReader reader, ContentWriter writer, Map<String, Object> legacyOptionsMap)
        throws NoTransformerException, ContentIOException
{
    TransformationOptions transformationOptions = new TransformationOptions(legacyOptionsMap);
    Map<String, String> options = converter.getOptions(transformationOptions, null, null);
    synchronousTransformClient.transform(reader, writer, options, null, null);
}
 
源代码27 项目: alfresco-repository   文件: FileContentWriter.java
/**
 * The URL of the write is known from the start and this method contract states
 * that no consideration needs to be taken w.r.t. the stream state.
 */
@Override
protected ContentReader createReader() throws ContentIOException
{
    FileContentReader reader = new FileContentReader(this.file, getContentUrl());
    reader.setAllowRandomAccess(this.allowRandomAccess);
    return reader;
}
 
源代码28 项目: alfresco-repository   文件: FileContentWriter.java
@Override
protected WritableByteChannel getDirectWritableChannel() throws ContentIOException
{
    try
    {
        // we may not write to an existing file - EVER!!
        if (file.exists() && file.length() > 0)
        {
            throw new IOException("File exists - overwriting not allowed");
        }
        // create the channel
        WritableByteChannel channel = null;
        if (allowRandomAccess)
        {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");  // will create it
            channel = randomAccessFile.getChannel();
        }
        else
        {
            OutputStream os = new FileOutputStream(file);
            channel = Channels.newChannel(os);
        }
        // done
        if (logger.isDebugEnabled())
        {
            logger.debug("Opened write channel to file: \n" +
                    "   file: " + file + "\n" +
                    "   random-access: " + allowRandomAccess);
        }
        return channel;
    }
    catch (Throwable e)
    {
        throw new ContentIOException("Failed to open file channel: " + this, e);
    }
}
 
/**
 * {@inheritDoc}
 */
@Override
public void putContent(final InputStream is) throws ContentIOException
{
    try
    {
        final OutputStream os = this.getContentOutputStream();
        FileCopyUtils.copy(is, os);
    }
    catch (final IOException e)
    {
        LOGGER.error("Content writer {} failed to copy content from input stream", this, e);
        throw new ContentIOException("Failed to copy content from input stream: \n\twriter: " + this, e);
    }
}
 
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");
        }
    }
}