Java Code Examples for org.alfresco.service.cmr.repository.ContentReader#exists()

The following examples show how to use org.alfresco.service.cmr.repository.ContentReader#exists() . 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: AbstractRenderingEngine.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 2
Source File: AggregatingContentStore.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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();
    }     
}
 
Example 3
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 4
Source File: FileWipingContentCleanerListener.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void beforeDelete(ContentStore sourceStore, String contentUrl) throws ContentIOException
{
    // First check if the content is present at all
    ContentReader reader = sourceStore.getReader(contentUrl);
    if (reader != null && reader.exists())
    {
        // Call to implementation's shred
        if (logger.isDebugEnabled())
        {
            logger.debug(
                    "About to shread: \n" +
                    "   URL:    " + contentUrl + "\n" +
                    "   Source: " + sourceStore);
        }
        try
        {
            shred(reader);
        }
        catch (Throwable e)
        {
            logger.error(
                    "Content shredding failed: \n" +
                    "   URL:    " + contentUrl + "\n" +
                    "   Source: " + sourceStore + "\n" +
                    "   Reader: " + reader,
                    e);
        }
    }
    else
    {
        logger.error(
                "Content no longer exists.  Unable to shred: \n" +
                "   URL:    " + contentUrl + "\n" +
                "   Source: " + sourceStore);
    }
}
 
Example 5
Source File: DeletedContentBackupCleanerListener.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void beforeDelete(ContentStore sourceStore, String contentUrl) throws ContentIOException
{
    if (store.isContentUrlSupported(contentUrl))
    {
        ContentContext context = new ContentContext(null, contentUrl);
        ContentReader reader = sourceStore.getReader(contentUrl);
        if (!reader.exists())
        {
            // Nothing to copy over
            return;
        }
        // write the content into the target store
        ContentWriter writer = store.getWriter(context);
        // copy across
        writer.putContent(reader);
        // done
        if (logger.isDebugEnabled())
        {
            logger.debug(
                    "Moved content before deletion: \n" +
                    "   URL:    " + contentUrl + "\n" +
                    "   Source: " + sourceStore + "\n" +
                    "   Target: " + store);
        }
    }
    else
    {
        if (logger.isDebugEnabled())
        {
            logger.debug(
                    "Content cannot be moved during deletion.  A backup will not be made: \n" +
                    "   URL:    " + contentUrl + "\n" +
                    "   Source: " + sourceStore + "\n" +
                    "   Target: " + store);
        }
    }
}
 
Example 6
Source File: AbstractContentStore.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Simple implementation that uses the
 * {@link ContentReader#exists() reader's exists} method as its implementation.
 * Override this method if a more efficient implementation is possible.
 */
@Override
public boolean exists(String contentUrl)
{
    ContentReader reader = getReader(contentUrl);
    return reader.exists();
}
 
Example 7
Source File: RhinoScriptProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.repository.ScriptProcessor#execute(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.namespace.QName, java.util.Map)
 */
public Object execute(NodeRef nodeRef, QName contentProp, Map<String, Object> model)
{
    try
    {
        if (this.services.getNodeService().exists(nodeRef) == false)
        {
            throw new AlfrescoRuntimeException("Script Node does not exist: " + nodeRef);
        }
        
        if (contentProp == null)
        {
            contentProp = ContentModel.PROP_CONTENT;
        }
        ContentReader cr = this.services.getContentService().getReader(nodeRef, contentProp);
        if (cr == null || cr.exists() == false)
        {
            throw new AlfrescoRuntimeException("Script Node content not found: " + nodeRef);
        }
        
        // compile the script based on the node content
        Script script;
        Context cx = Context.enter();
        try
        {
            script = cx.compileString(resolveScriptImports(cr.getContentString()), nodeRef.toString(), 1, null);
        }
        finally
        {
            Context.exit();
        }
        
        return executeScriptImpl(script, model, false, nodeRef.toString());
    }
    catch (Throwable err)
    {
        throw new ScriptException("Failed to execute script '" + nodeRef.toString() + "': " + err.getMessage(), err);
    }
}
 
Example 8
Source File: ContentStoreCleanerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void checkForExistence(Set<String> urls, boolean mustExist)
{
    for (String url : urls)
    {
        ContentReader rawReader = contentService.getRawReader(url);
        if (mustExist && !rawReader.exists())
        {
            fail("Content URL should have existed but did not: " + url);
        }
        else if (!mustExist && rawReader.exists())
        {
            fail("Content URL should not have existed but did: " + url);
        }
    }
}
 
Example 9
Source File: LegacySynchronousTransformClient.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void transform(ContentReader reader, ContentWriter writer, Map<String, String> actualOptions,
                      String transformName, NodeRef sourceNodeRef)
{
    String renditionName = TransformDefinition.convertToRenditionName(transformName);
    try
    {
        TransformationOptions options = converter.getTransformationOptions(renditionName, actualOptions);
        options.setSourceNodeRef(sourceNodeRef);

        if (null == reader || !reader.exists())
        {
            throw new IllegalArgumentException("sourceNodeRef "+sourceNodeRef+" has no content.");
        }

        if (logger.isDebugEnabled())
        {
            logger.debug(TRANSFORM + "requested " + renditionName);
        }

        // We don't obtain the Legacy transformer and then call its transform method as they unlike Local and
        // Transform Service transforms automatically fail over to the next highest priority. This was not done
        // for the newer transforms, as a fail over can always be defined and that makes it simpler to understand
        // what is going on.
        transform(reader, writer, options);

        if (logger.isDebugEnabled())
        {
            logger.debug(TRANSFORM + "created " + renditionName);
        }
    }
    catch (Exception e)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug(TRANSFORM + "failed " + renditionName, e);
        }
        throw e;
    }
}
 
Example 10
Source File: RepoStore.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private boolean isContentPresent(NodeRef nodeRef)
{
    ContentReader reader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT); 
    if ((reader != null && reader.exists()))
    {
        return true;
    }
    return false;
}
 
Example 11
Source File: SavedSearchResultsMap.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see org.alfresco.repo.template.BaseTemplateMap#get(java.lang.Object)
 */
public Object get(Object key)
{
    String search = null;
    
    if (key != null && key.toString().length() != 0)
    {
        // read the Saved Search XML on the specified node - and get the Lucene search from it
        try
        {
            NodeRef ref = new NodeRef(key.toString());
            
            ContentReader content = services.getContentService().getReader(ref, ContentModel.PROP_CONTENT);
            if (content != null && content.exists())
            {
                // get the root element
                SAXReader reader = new SAXReader();
                Document document = reader.read(new StringReader(content.getContentString()));
                Element rootElement = document.getRootElement();
                
                Element queryElement = rootElement.element(ELEMENT_QUERY);
                if (queryElement != null)
                {
                    search = queryElement.getText();
                }
            }
        }
        catch (Throwable err)
        {
            throw new AlfrescoRuntimeException("Failed to find or load saved Search: " + key, err);
        }
    }
    
    // execute the search
    return query(search);
}
 
Example 12
Source File: BaseContentNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @return the content stream
 */
public String getContent()
{
    ContentService contentService = services.getContentService();
    ContentReader reader = contentService.getReader(getNodeRef(), property);
    
    return (reader != null && reader.exists()) ? reader.getContentString() : "";
}
 
Example 13
Source File: BaseContentNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @return the content stream to the specified maximum length in characters
 */
public String getContentMaxLength(int length)
{
    ContentService contentService = services.getContentService();
    ContentReader reader = contentService.getReader(getNodeRef(), property);
    
    return (reader != null && reader.exists()) ? reader.getContentString(length) : "";
}
 
Example 14
Source File: ContentStreamer.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Streams the content on a given node's content property to the response of the web script.
 *
 * @param req            Request
 * @param res            Response
 * @param nodeRef        The node reference
 * @param propertyQName  The content property name
 * @param attach         Indicates whether the content should be streamed as an attachment or not
 * @param attachFileName Optional file name to use when attach is <code>true</code>
 * @throws IOException
 */
public void streamContent(WebScriptRequest req,
            WebScriptResponse res,
            NodeRef nodeRef,
            QName propertyQName,
            boolean attach,
            String attachFileName,
            Map<String, Object> model) throws IOException
{
    if (logger.isDebugEnabled())
        logger.debug("Retrieving content from node ref " + nodeRef.toString() + " (property: " + propertyQName.toString() + ") (attach: " + attach + ")");

    // TODO
    // This was commented out to accomadate records management permissions.  We need to review how we cope with this
    // hard coded permission checked.

    // check that the user has at least READ_CONTENT access - else redirect to the login page
    //        if (permissionService.hasPermission(nodeRef, PermissionService.READ_CONTENT) == AccessStatus.DENIED)
    //        {
    //            throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN, "Permission denied");
    //        }

    // check If-Modified-Since header and set Last-Modified header as appropriate
    Date modified = (Date) nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIED);
    if (modified != null)
    {
        long modifiedSince = -1;
        String modifiedSinceStr = req.getHeader("If-Modified-Since");
        if (modifiedSinceStr != null)
        {
            try
            {
                modifiedSince = dateFormat.parse(modifiedSinceStr).getTime();
            }
            catch (Throwable e)
            {
                if (logger.isInfoEnabled())
                    logger.info("Browser sent badly-formatted If-Modified-Since header: " + modifiedSinceStr);
            }

            if (modifiedSince > 0L)
            {
                // round the date to the ignore millisecond value which is not supplied by header
                long modDate = (modified.getTime() / 1000L) * 1000L;
                if (modDate <= modifiedSince)
                {
                    res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return;
                }
            }
        }
    }

    // get the content reader
    ContentReader reader = contentService.getReader(nodeRef, propertyQName);
    if (reader == null || !reader.exists())
    {
        throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to locate content for node ref " + nodeRef + " (property: " + propertyQName.toString() + ")");
    }

    // Stream the content
    streamContentImpl(req, res, reader, nodeRef, propertyQName, attach, modified, modified == null ? null : Long.toString(modified.getTime()), attachFileName, model);
}
 
Example 15
Source File: EncryptingContentStore.java    From alfresco-simple-content-stores with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public ContentWriter getWriter(final ContentContext context)
{
    final ContentReader existingContentReader;

    final String contentUrl = context.getContentUrl();
    if (contentUrl != null && this.isContentUrlSupported(contentUrl) && this.exists(contentUrl))
    {
        final ContentReader reader = this.getReader(contentUrl);
        if (reader != null && reader.exists())
        {
            existingContentReader = reader;
        }
        else
        {
            existingContentReader = null;
        }
    }
    else
    {
        existingContentReader = null;
    }

    final ContentWriter backingWriter = super.getWriter(context);

    final Key key = this.createNewKey();
    final EncryptingContentWriterFacade facadeWriter = new EncryptingContentWriterFacade(backingWriter, context, key,
            existingContentReader);

    facadeWriter.addListener(() -> {
        final byte[] keyBytes = key.getEncoded();
        final ByteBuffer dkBuffer = ByteBuffer.wrap(keyBytes);

        EncryptedKey eKey;
        try
        {
            // allocate twice as many bytes for buffer then we actually expect
            // min expectation: master key size in bits / 8
            // key-dependant expectation: key byte count + buffer => rounded up to next power of 2
            final int masterKeyMinBlockSize = EncryptingContentStore.this.masterKeySize / 8;

            final int keyBlockOverhead = 42; // (RSA with default SHA-1)
            int expectedKeyBlockSize = dkBuffer.capacity() + keyBlockOverhead;
            if (Integer.highestOneBit(expectedKeyBlockSize) != Integer.lowestOneBit(expectedKeyBlockSize))
            {
                // round up to next power of two
                expectedKeyBlockSize = Integer.highestOneBit(expectedKeyBlockSize) << 1;
            }

            final ByteBuffer ekBuffer = ByteBuffer.allocateDirect(Math.max(masterKeyMinBlockSize, expectedKeyBlockSize) * 2);
            try (final ByteBufferByteChannel ekChannel = new ByteBufferByteChannel(ekBuffer))
            {
                try (final EncryptingWritableByteChannel dkChannel = new EncryptingWritableByteChannel(ekChannel,
                        EncryptingContentStore.this.masterPublicKey))
                {
                    dkChannel.write(dkBuffer);
                }
            }

            ekBuffer.flip();

            eKey = new EncryptedKey(EncryptingContentStore.this.masterKeyStoreId, EncryptingContentStore.this.masterKeyAlias,
                    key.getAlgorithm(), ekBuffer);
        }
        catch (final IOException e)
        {
            LOGGER.error("Error storing symmetric content encryption key", e);
            throw new ContentIOException("Error storing symmetric content encryption key", e);
        }

        // can't create content URL entity directly so create via ContentData
        final Pair<Long, ContentData> contentDataPair = EncryptingContentStore.this.contentDataDAO
                .createContentData(facadeWriter.getContentData());

        final ContentUrlKeyEntity contentUrlKeyEntity = new ContentUrlKeyEntity();
        contentUrlKeyEntity.setUnencryptedFileSize(Long.valueOf(facadeWriter.getSize()));
        contentUrlKeyEntity.setEncryptedKey(eKey);

        EncryptingContentStore.this.contentDataDAO.updateContentUrlKey(contentDataPair.getSecond().getContentUrl(),
                contentUrlKeyEntity);
    });

    return facadeWriter;
}
 
Example 16
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;
}
 
Example 17
Source File: AggregatingContentStore.java    From alfresco-simple-content-stores with Apache License 2.0 4 votes vote down vote up
@Override
public ContentReader getReader(final String contentUrl)
{
    ContentReader reader = null;
    boolean validReader = false;

    LOGGER.debug("Retrieving content reader for URL {}", contentUrl);

    if (this.primaryStore.isContentUrlSupported(contentUrl))
    {
        reader = this.primaryStore.getReader(contentUrl);
        validReader = reader != null && reader.exists();

        if (validReader)
        {
            LOGGER.debug("Content reader for URL {} retrieved from primary store", contentUrl);
        }
    }

    for (int idx = 0, max = this.secondaryStores.size(); idx < max && !validReader; idx++)
    {
        final ContentStore store = this.secondaryStores.get(idx);
        if (store.isContentUrlSupported(contentUrl))
        {
            reader = store.getReader(contentUrl);

            validReader = reader != null && reader.exists();
            if (validReader)
            {
                LOGGER.debug("Content reader for URL {} retrieved from secondary store #{}", contentUrl, idx + 1);
            }
        }
    }

    if (!validReader)
    {
        LOGGER.debug("No content reader with existing content found for URL {}", contentUrl);
    }

    return reader;
}
 
Example 18
Source File: ScriptNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public InputStream getInputStream()
{
    ContentService contentService = services.getContentService();
    ContentReader reader = contentService.getReader(nodeRef, property);
    return (reader != null && reader.exists()) ? reader.getContentInputStream() : null;
}
 
Example 19
Source File: ScriptNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public String getContent()
{
    ContentService contentService = services.getContentService();
    ContentReader reader = contentService.getReader(nodeRef, property);
    return (reader != null && reader.exists()) ? reader.getContentString() : "";
}
 
Example 20
Source File: HttpAlfrescoStore.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void doTest(ApplicationContext ctx, String baseUrl, String contentUrl) throws Exception
{
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    TransactionService transactionService = serviceRegistry.getTransactionService();
    AuthenticationService authenticationService = serviceRegistry.getAuthenticationService();
    // Construct the store
    HttpAlfrescoStore store = new HttpAlfrescoStore();
    store.setTransactionService(transactionService);
    store.setAuthenticationService(authenticationService);
    store.setBaseHttpUrl(baseUrl);
    
    // Now test
    System.out.println(
            "   Retrieving reader for URL " + contentUrl);
    ContentReader reader = store.getReader(contentUrl);
    System.out.println(
            "   Retrieved reader for URL " + contentUrl);
    // Check if the content exists
    boolean exists = reader.exists();
    if (!exists)
    {
        System.out.println(
                "   Content doesn't exist: " + contentUrl);
        return;
    }
    else
    {
        System.out.println(
                "   Content exists: " + contentUrl);
    }
    // Get the content data
    ContentData contentData = reader.getContentData();
    System.out.println(
            "   Retrieved content data: " + contentData);
    
    // Now get the content
    ByteBuffer buffer = ByteBuffer.allocate((int)reader.getSize());
    FileChannel channel = reader.getFileChannel();
    try
    {
        int count = channel.read(buffer);
        if (count != reader.getSize())
        {
            System.err.println("The number of bytes read was " + count + " but expected " + reader.getSize());
            return;
        }
    }
    finally
    {
        channel.close();
    }
}