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

The following examples show how to use org.alfresco.service.cmr.repository.ContentReader#getContent() . 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: ContentCacheImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public boolean put(String contentUrl, ContentReader source)
{
    File tempFile = createCacheFile();
    
    // Copy the content from the source into a cache file
    if (source.getSize() > 0L)
    {
        source.getContent(tempFile);
        File cacheFile = renameTempToActive(tempFile);
        // Add a record of the cached file to the in-memory cache.
        recordCacheEntries(contentUrl, cacheFile);
        return true;
    }

    return false;
}
 
Example 2
Source File: JodConverterMetadataExtracterWorker.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
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();
}
 
Example 3
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 4
Source File: OOoContentTransformerHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Populates a file with the content in the reader.
 */
public void saveContentInFile(String sourceMimetype, ContentReader reader, File file) throws ContentIOException
{
    String encoding = reader.getEncoding();
    if (encodeAsUtf8(sourceMimetype, encoding))
    {
        saveContentInUtf8File(reader, file);
    }
    else
    {
        reader.getContent(file);
    }
}
 
Example 5
Source File: HtmlParserContentTransformer.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void transformLocal(ContentReader reader, ContentWriter writer, TransformationOptions options)
        throws Exception
{

    // We can only work from a file
    File htmlFile = TempFileProvider.createTempFile("HtmlParserContentTransformer_", ".html");
    reader.getContent(htmlFile);

    // Fetch the encoding of the HTML, as set in the ContentReader
    // This will default to 'UTF-8' if not specifically set
    String encoding = reader.getEncoding();

    // Create the extractor
    EncodingAwareStringBean extractor = new EncodingAwareStringBean();
    extractor.setCollapse(false);
    extractor.setLinks(false);
    extractor.setReplaceNonBreakingSpaces(false);
    extractor.setURL(htmlFile, encoding);
    // get the text
    String text = extractor.getStrings();
    // write it to the writer
    writer.putContent(text);

    // Tidy up
    htmlFile.delete();
}
 
Example 6
Source File: ThumbnailServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testCreateRenditionThumbnailFromPdfPage2() throws Exception
{
    ImageTransformationOptions options = new ImageTransformationOptions();
    PagedSourceOptions pagedSourceOptions = new PagedSourceOptions();
    pagedSourceOptions.setStartPageNumber(new Integer(2));
    pagedSourceOptions.setEndPageNumber(new Integer(2));
    options.addSourceOptions(pagedSourceOptions);
    
    ThumbnailDefinition thumbnailDefinition = new ThumbnailDefinition(MimetypeMap.MIMETYPE_PDF, options, "doclib_2");
    thumbnailService.getThumbnailRegistry().addThumbnailDefinition(thumbnailDefinition);

    checkTransformer();

    NodeRef pdfOrig = createOriginalContent(this.folder, MimetypeMap.MIMETYPE_PDF);

    NodeRef thumbnail0 = this.thumbnailService.createThumbnail(pdfOrig, ContentModel.PROP_CONTENT,
                MimetypeMap.MIMETYPE_IMAGE_JPEG, thumbnailDefinition.getTransformationOptions(), "doclib_2");
    assertNotNull(thumbnail0);
    checkRenditioned(pdfOrig, Collections.singletonList(new ExpectedAssoc(RegexQNamePattern.MATCH_ALL, "doclib_2", 1)));
    checkRendition("doclib_2", thumbnail0);
    
    // Check the length
    File tempFile = TempFileProvider.createTempFile("thumbnailServiceImplTest", ".jpg");
    ContentReader reader = this.contentService.getReader(thumbnail0, ContentModel.PROP_CONTENT);
    
    long size = reader.getSize();
    reader.getContent(tempFile);
    assertTrue("Page 2 should be blank and less than 4500 bytes. It was "+size+" bytes. tempFile="+tempFile.getPath(), size < 4500);
}
 
Example 7
Source File: ThumbnailServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void outputThumbnailTempContentLocation(NodeRef thumbnail, String ext, String message) throws IOException
{
    File tempFile = TempFileProvider.createTempFile("thumbnailServiceImplTest", "." + ext);
    ContentReader reader = this.contentService.getReader(thumbnail, ContentModel.PROP_CONTENT);
    reader.getContent(tempFile);
    System.out.println(message + ": " + tempFile.getPath());
}
 
Example 8
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 9
Source File: GetMethod.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void attemptReadContent(FileInfo realNodeInfo, ContentReader reader) throws IOException
{
    if (byteRanges != null && byteRanges.startsWith(RANGE_HEADER_UNIT_SPECIFIER))
    {
        HttpRangeProcessor rangeProcessor = new HttpRangeProcessor(getContentService());
        String userAgent = m_request.getHeader(WebDAV.HEADER_USER_AGENT);
        
        if (m_returnContent)
        {
            m_davHelper.publishReadEvent(realNodeInfo, reader.getMimetype(), reader.getSize(), byteRanges.substring(6), reader.getEncoding());
            rangeProcessor.processRange(
                    m_response,
                    reader,
                    byteRanges.substring(6),
                    realNodeInfo.getNodeRef(),
                    ContentModel.PROP_CONTENT,
                    reader.getMimetype(),
                    userAgent);
        }
    }
    else
    {
            if (m_returnContent)
            {
            // there is content associated with the node
            m_response.setHeader(WebDAV.HEADER_CONTENT_LENGTH, Long.toString(reader.getSize()));
            m_response.setHeader(WebDAV.HEADER_CONTENT_TYPE, reader.getMimetype());
            m_davHelper.publishReadEvent(realNodeInfo, reader.getMimetype(), reader.getSize(), null, reader.getEncoding());
            // copy the content to the response output stream
            reader.getContent(m_response.getOutputStream());
        }
    }
}
 
Example 10
Source File: RuntimeExecutableContentTransformerWorker.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Converts the source and target content to temporary files with the
 * correct extensions for the mimetype that they map to.
 * 
 */
public final void transform(
        ContentReader reader,
        ContentWriter writer,
        TransformationOptions options) throws Exception
{
    // get mimetypes
    String sourceMimetype = getMimetype(reader);
    String targetMimetype = getMimetype(writer);
    
    // get the extensions to use
    String sourceExtension = getMimetypeService().getExtension(sourceMimetype);
    String targetExtension = getMimetypeService().getExtension(targetMimetype);
    if (sourceExtension == null || targetExtension == null)
    {
        throw new AlfrescoRuntimeException("Unknown extensions for mimetypes: \n" +
                "   source mimetype: " + sourceMimetype + "\n" +
                "   source extension: " + sourceExtension + "\n" +
                "   target mimetype: " + targetMimetype + "\n" +
                "   target extension: " + targetExtension);
    }
    
    // create required temp files
    File sourceFile = TempFileProvider.createTempFile(
            getClass().getSimpleName() + "_source_",
            "." + sourceExtension);
    File targetFile = TempFileProvider.createTempFile(
            getClass().getSimpleName() + "_target_",
            "." + targetExtension);
    
    Map<String, String> properties = new HashMap<String, String>(5);
    // copy options over
    Map<String, Object> optionsMap = options.toMap();
    for (Map.Entry<String, Object> entry : optionsMap.entrySet())
    {
        String key = entry.getKey();
        Object value = entry.getValue();
        properties.put(key, (value == null ? null : value.toString()));
    }
    // add the source and target properties
    properties.put(VAR_SOURCE, sourceFile.getAbsolutePath());
    properties.put(VAR_TARGET, targetFile.getAbsolutePath());
    properties.put(VAR_PAGE_RANGE, "0-"+(options.getPageLimit() >=0 ? options.getPageLimit() : ""));
    
    // pull reader file into source temp file
    reader.getContent(sourceFile);

    // execute the transformation command
    long timeoutMs = options.getTimeoutMs();
    ExecutionResult result = null;
    try
    {
        result = transformCommand.execute(properties, timeoutMs);
    }
    catch (Throwable e)
    {
        throw new ContentIOException("Transformation failed during command execution: \n" + transformCommand, e);
    }
    
    // check
    if (!result.getSuccess())
    {
        throw new ContentIOException("Transformation failed - status indicates an error: \n" + result);
    }
    
    // check that the file was created
    if (!targetFile.exists())
    {
        throw new ContentIOException("Transformation failed - target file doesn't exist: \n" + result);
    }
    // copy the target file back into the repo
    writer.putContent(targetFile);
    
    // done
    if (logger.isDebugEnabled())
    {
        logger.debug("Transformation completed: \n" +
                "   source: " + reader + "\n" +
                "   target: " + writer + "\n" +
                "   options: " + options + "\n" +
                "   result: \n" + result);
    }
}
 
Example 11
Source File: OOXMLThumbnailContentTransformer.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected void transformInternal(ContentReader reader,
                                 ContentWriter writer,
                                 TransformationOptions options) throws Exception
{
    final String sourceMimetype = reader.getMimetype();
    final String sourceExtension = getMimetypeService().getExtension(sourceMimetype);
    final String targetMimetype = writer.getMimetype();
    
    
    if (log.isDebugEnabled())
    {
        StringBuilder msg = new StringBuilder();
        msg.append("Transforming from ").append(sourceMimetype)
           .append(" to ").append(targetMimetype);
        log.debug(msg.toString());
    }
    
    
    OPCPackage pkg = null;
    try 
    {
        File ooxmlTempFile = TempFileProvider.createTempFile(this.getClass().getSimpleName() + "_ooxml", sourceExtension);
        reader.getContent(ooxmlTempFile);
        
        // Load the file
        pkg = OPCPackage.open(ooxmlTempFile.getPath());
        
        // Does it have a thumbnail?
        PackageRelationshipCollection rels = 
            pkg.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL);
        if (rels.size() > 0)
        {
            // Get the thumbnail part
            PackageRelationship tRel = rels.getRelationship(0);
            PackagePart tPart = pkg.getPart(tRel);
            
            // Write it to the target
            InputStream tStream = tPart.getInputStream();
            writer.putContent( tStream );
            tStream.close();
        }
        else
        {
            log.debug("No thumbnail present in " + reader.toString());
            throw new UnimportantTransformException(NO_THUMBNAIL_PRESENT_IN_FILE + targetMimetype);
        }
    } 
    catch (IOException e) 
    {
       throw new AlfrescoRuntimeException("Unable to transform " + sourceExtension + " file.", e);
    }
    finally
    {
        if (pkg != null)
        {
            pkg.close();
        }
    }
}
 
Example 12
Source File: AlfrescoPdfRendererContentTransformerWorker.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void transformLocal(ContentReader reader, ContentWriter writer, TransformationOptions options,
                            String sourceMimetype, String targetMimetype,
                            String sourceExtension, String targetExtension) throws Exception
{
    // create required temp files
    File sourceFile = TempFileProvider.createTempFile(getClass().getSimpleName() + "_source_", "." + sourceExtension);
    File targetFile = TempFileProvider.createTempFile(getClass().getSimpleName() + "_target_", "." + targetExtension);

    // pull reader file into source temp file
    reader.getContent(sourceFile);

    Map<String, String> properties = new HashMap<String, String>(5);
    // set properties
    if (options instanceof ImageTransformationOptions)
    {
        ImageTransformationOptions imageOptions = (ImageTransformationOptions) options;
        ImageResizeOptions resizeOptions = imageOptions.getResizeOptions();
        String commandOptions = imageOptions.getCommandOptions();
        if (commandOptions == null)
        {
            commandOptions = "";
        }
        if(resizeOptions != null)
        {
            if (resizeOptions.getHeight() > -1)
            {
                commandOptions += " --height=" + resizeOptions.getHeight();
            }
            if (resizeOptions.getWidth() > -1)
            {
                commandOptions += " --width=" + resizeOptions.getWidth();
            }
            if (resizeOptions.getAllowEnlargement())
            {
                commandOptions += " --allow-enlargement";
            }
            if (resizeOptions.isMaintainAspectRatio())
            {
                commandOptions += " --maintain-aspect-ratio";
            }
        }
        commandOptions += " --page=" + getSourcePageRange(imageOptions, sourceMimetype, targetMimetype);

        properties.put(KEY_OPTIONS, commandOptions);
    }

    properties.put(VAR_SOURCE, sourceFile.getAbsolutePath());
    properties.put(VAR_TARGET, targetFile.getAbsolutePath());

    // execute the statement
    long timeoutMs = options.getTimeoutMs();
    RuntimeExec.ExecutionResult result = executer.execute(properties, timeoutMs);
    if (result.getExitValue() != 0 && result.getStdErr() != null && result.getStdErr().length() > 0)
    {
        throw new ContentIOException("Failed to perform alfresco-pdf-renderer transformation: \n" + result);
    }
    // success
    if (logger.isDebugEnabled())
    {
        logger.debug("alfresco-pdf-renderer executed successfully: \n" + executer);
    }

    // check that the file was created
    if (!targetFile.exists() || targetFile.length() == 0)
    {
        throw new ContentIOException("alfresco-pdf-renderer transformation failed to write output file");
    }

    // upload the output image
    writer.putContent(targetFile);
}