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

The following examples show how to use org.alfresco.service.cmr.repository.ContentReader#getMimetype() . 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: HTMLRenderingEngine.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void render(RenderingContext context)
{
    ContentReader contentReader = context.makeContentReader();
    String sourceMimeType = contentReader.getMimetype();
    
    // Check that Tika supports the supplied file
    AutoDetectParser p = new AutoDetectParser(tikaConfig);
    MediaType sourceMediaType = MediaType.parse(sourceMimeType);
    if(! p.getParsers().containsKey(sourceMediaType))
    {
       throw new RenditionServiceException(
             "Source mime type of " + sourceMimeType + 
             " is not supported by Tika for HTML conversions"
       );
    }
    
    // Make the HTML Version using Tika
    // This will also extract out any images as found
    generateHTML(p, context);
}
 
Example 2
Source File: AbstractLocalTransform.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void strictMimetypeCheck(ContentReader reader, NodeRef sourceNodeRef, String declaredMimetype)
{
    if (mimetypeService != null && strictMimeTypeCheck && depth.get() == 1)
    {
        String detectedMimetype = mimetypeService.getMimetypeIfNotMatches(reader.getReader());

        if (!strictMimetypeCheck(declaredMimetype, detectedMimetype))
        {
            Set<String> allowedMimetypes = strictMimetypeExceptions.get(declaredMimetype);
            if (allowedMimetypes != null && allowedMimetypes.contains(detectedMimetype))
            {
                String fileName = transformerDebug.getFileName(sourceNodeRef, true, 0);
                String readerSourceMimetype = reader.getMimetype();
                String message = "Transformation of ("+fileName+
                        ") has not taken place because the declared mimetype ("+
                        readerSourceMimetype+") does not match the detected mimetype ("+
                        detectedMimetype+").";
                log.warn(message);
                throw new UnsupportedTransformationException(message);
            }
        }
    }
}
 
Example 3
Source File: MimetypeMap.java    From alfresco-data-model with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Uses Tika to try to identify the mimetype of the file, falling back on
 * {@link #guessMimetype(String)} for an extension based one if Tika can't
 * help.
 */
public String guessMimetype(String filename, ContentReader reader)
{
    // ALF-10813: MimetypeMap.guessMimetype consumes 30% of file upload time
    // Let's only 'guess' if we need to
    if (reader != null && reader.getMimetype() != null && !reader.getMimetype().equals(MimetypeMap.MIMETYPE_BINARY))
    {
        // It was set to something other than the default.
        // Possibly someone used this method before (like the UI does) or
        // they just
        // know what their files are.
        return reader.getMimetype();
    }
    InputStream input = (reader != null ? reader.getContentInputStream() : null);
    return guessMimetype(filename, input);
}
 
Example 4
Source File: AbstractContentTransformer2.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void strictMimetypeCheck(ContentReader reader, TransformationOptions options, String sourceMimetype)
    throws UnsupportedTransformationException
{
    if (strictMimeTypeCheck && depth.get() == 1)
    {
        String differentType = getMimetypeService().getMimetypeIfNotMatches(reader.getReader());

        if (!transformerConfig.strictMimetypeCheck(sourceMimetype, differentType))
        {
            String fileName = ((LegacyTransformerDebug)transformerDebug).getFileName(options, true, 0);
            String readerSourceMimetype = reader.getMimetype();
            String message = "Transformation of ("+fileName+
                ") has not taken place because the declared mimetype ("+
                readerSourceMimetype+") does not match the detected mimetype ("+
                differentType+").";
            logger.warn(message);
            throw new UnsupportedTransformationException(message);
        }
    }
}
 
Example 5
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 6
Source File: ScriptNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Guess the mimetype for the given filename - uses the extension to match on system mimetype map
 */
public void guessMimetype(String filename)
{
    ContentService contentService = services.getContentService();
    ContentReader reader = contentService.getReader(nodeRef, property); 
    // MNT-12265 Browser sets a mimetype based on extension of file. But mimeType from browser can be
    // different as mapped in Alfresco for current extension. Therefore we need to guess a mimetype based on
    // map in Alfresco
    String typeByExt = services.getMimetypeService().guessMimetype(filename);
    if (reader != null && reader.getMimetype() != null && !typeByExt.equals(MimetypeMap.MIMETYPE_BINARY))
    {
        setMimetype(typeByExt);
    }
    else
    {
        setMimetype(services.getMimetypeService().guessMimetype(filename, reader));
    }
}
 
Example 7
Source File: BinaryProperty.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 8
Source File: AbstractTransformationRenderingEngine.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public TransformationCallable(ContentReader contentReader, String targetMimeType,
                              TransformationOptions transformationOptions, RenderingContext context, String initiatingUsername)
{
    this.contentReader = contentReader;
    this.targetMimeType = targetMimeType;
    String sourceMimetype = contentReader.getMimetype();
    this.options = converter.getOptions(transformationOptions, sourceMimetype, targetMimeType);
    this.context = context;
    this.initiatingUsername = initiatingUsername;
}
 
Example 9
Source File: ContentInfo.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void streamContentImpl(WebScriptRequest req, WebScriptResponse res, 
        ContentReader reader, NodeRef nodeRef, QName propertyQName, 
        boolean attach, Date modified, String eTag, String attachFileName)
        throws IOException
{
    delegate.setAttachment(req, res, attach, attachFileName);

    // establish mimetype
    String mimetype = reader.getMimetype();
    String extensionPath = req.getExtensionPath();
    if (mimetype == null || mimetype.length() == 0)
    {
        mimetype = MimetypeMap.MIMETYPE_BINARY;
        int extIndex = extensionPath.lastIndexOf('.');
        if (extIndex != -1)
        {
            String ext = extensionPath.substring(extIndex + 1);
            mimetype = mimetypeService.getMimetype(ext);
        }
    }

    // set mimetype for the content and the character encoding + length for the stream
    res.setContentType(mimetype);
    res.setContentEncoding(reader.getEncoding());
    res.setHeader("Content-Length", Long.toString(reader.getSize()));

    // set caching
    Cache cache = new Cache();
    cache.setNeverCache(false);
    cache.setMustRevalidate(true);
    cache.setMaxAge(0L);
    cache.setLastModified(modified);
    cache.setETag(eTag);
    res.setCache(cache);
}
 
Example 10
Source File: TestSynchronousTransformClient.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 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);
    }
}
 
Example 11
Source File: TransformActionExecuter.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Executed in a new transaction so that failures don't cause the entire transaction to rollback.
 */
protected void doTransform( Action ruleAction, 
                            NodeRef sourceNodeRef, ContentReader contentReader, 
                            NodeRef destinationNodeRef, ContentWriter contentWriter)    

{
    // transform - will throw NoTransformerException if there are no transformers
    TransformationOptions transformationOptions = newTransformationOptions(ruleAction, sourceNodeRef);
    transformationOptions.setTargetNodeRef(destinationNodeRef);
    String sourceMimetype = contentReader.getMimetype();
    Map<String, String> options = converter.getOptions(transformationOptions, sourceMimetype, contentWriter.getMimetype());
    synchronousTransformClient.transform(contentReader, contentWriter, options, null, sourceNodeRef);
}
 
Example 12
Source File: ContentTransformServiceAdaptor.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Deprecated
@Override
public boolean isTransformable(ContentReader reader, ContentWriter writer, TransformationOptions transformationOptions)
{
    String sourceMimetype = reader.getMimetype();
    long sourceSizeInBytes = reader.getSize();
    String contentUrl = reader.getContentUrl();
    String targetMimetype = writer.getMimetype();
    NodeRef sourceNodeRef = transformationOptions.getSourceNodeRef();
    Map<String, String> options = converter.getOptions(transformationOptions, null, null);
    return synchronousTransformClient.isSupported(sourceMimetype, sourceSizeInBytes, contentUrl, targetMimetype,
            options, null, sourceNodeRef);
}
 
Example 13
Source File: AbstractMappingMetadataExtracter.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Checks if the mimetype is supported.
 * 
 * @param reader the reader to check
 * @throws AlfrescoRuntimeException if the mimetype is not supported
 */
protected void checkIsSupported(ContentReader reader)
{
    String mimetype = reader.getMimetype();
    if (!isSupported(mimetype))
    {
        throw new AlfrescoRuntimeException(
                "Metadata extracter does not support mimetype: " + mimetype + "\n" +
                "   reader: " + reader + "\n" +
                "   supported: " + supportedMimetypes + "\n" +
                "   extracter: " + this);
    }
}
 
Example 14
Source File: ContentTransformServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Deprecated
public void transform(ContentReader reader, ContentWriter writer, TransformationOptions options)
        throws NoTransformerException, ContentIOException
{
    // check that source and target mimetypes are available
    if (reader == null)
    {
        throw new AlfrescoRuntimeException("The content reader must be set");
    }
    String sourceMimetype = reader.getMimetype();
    if (sourceMimetype == null)
    {
        throw new AlfrescoRuntimeException("The content reader mimetype must be set: " + reader);
    }
    String targetMimetype = writer.getMimetype();
    if (targetMimetype == null)
    {
        throw new AlfrescoRuntimeException("The content writer mimetype must be set: " + writer);
    }

    long sourceSize = reader.getSize();
    try
    {
        // look for a transformer
        transformerDebug.pushAvailable(reader.getContentUrl(), sourceMimetype, targetMimetype, options);
        List<ContentTransformer> transformers = getActiveTransformers(sourceMimetype, sourceSize, targetMimetype, options);
        transformerDebug.availableTransformers(transformers, sourceSize, options, "ContentService.transform(...)");

        int count = transformers.size();
        if (count == 0)
        {
            throw new NoTransformerException(sourceMimetype, targetMimetype);
        }

        if (count == 1 || !transformerFailover)
        {
            ContentTransformer transformer = transformers.size() == 0 ? null : transformers.get(0);
            transformer.transform(reader, writer, options);
        }
        else
        {
            failoverTransformers(reader, writer, options, targetMimetype, transformers);
        }
    }
    finally
    {
        if (transformerDebug.isEnabled())
        {
            transformerDebug.popAvailable();
            debugTransformations(sourceMimetype, targetMimetype, sourceSize, options);
        }
    }
}
 
Example 15
Source File: ContentTransformServiceAdaptor.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private NoTransformerException newNoTransformerException(ContentReader reader, ContentWriter writer)
{
    String sourceMimetype = reader == null ? "null" : reader.getMimetype();
    String targetMimetype = writer == null ? "null" : writer.getMimetype();
    return new NoTransformerException(sourceMimetype, targetMimetype);
}
 
Example 16
Source File: ContentMetadataEmbedder.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @see org.alfresco.repo.action.executer.ActionExecuter#execute(Action, NodeRef)
 */
public void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef)
{
    if (!nodeService.exists(actionedUponNodeRef))
    {
        // Node is gone
        return;
    }
    ContentReader reader = contentService.getReader(actionedUponNodeRef, ContentModel.PROP_CONTENT);
    // The reader may be null, e.g. for folders and the like
    if (reader == null || reader.getMimetype() == null)
    {
        if(logger.isDebugEnabled())
        {
            logger.debug("no content or mimetype - do nothing");
        }
        // No content to extract data from
        return;
    }
    String mimetype = reader.getMimetype();
    MetadataEmbedder embedder = metadataExtracterRegistry.getEmbedder(mimetype);
    if (embedder == null)
    {
        if(logger.isDebugEnabled())
        {
            logger.debug("no embedder for mimetype:" + mimetype);
        }
        // There is no embedder to use
        return;
    }
    
    ContentWriter writer = contentService.getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true);
    // The writer may be null, e.g. for folders and the like
    if (writer == null || writer.getMimetype() == null)
    {
        if(logger.isDebugEnabled())
        {
            logger.debug("no content or mimetype - do nothing");
        }
        // No content to embed data in
        return;
    }

    // Get all the node's properties
    Map<QName, Serializable> nodeProperties = nodeService.getProperties(actionedUponNodeRef);

    try
    {
        embedder.embed(nodeProperties, reader, writer);
    }
    catch (Throwable e)
    {
        // Extracters should attempt to handle all error conditions and embed
        // as much as they can.  If, however, one should fail, we don't want the
        // action itself to fail.  We absorb and report the exception here.
        if (logger.isDebugEnabled())
        {
            logger.debug(
                    "Metadata embedding failed: \n" +
                    "   Extracter: " + this + "\n" +
                    "   Node:      " + actionedUponNodeRef + "\n" +
                    "   Content:   " + writer,
                    e);
        }
        else
        {
            logger.warn(
                    "Metadata embedding failed (turn on DEBUG for full error): \n" +
                    "   Extracter: " + this + "\n" +
                    "   Node:      " + actionedUponNodeRef + "\n" +
                    "   Content:   " + writer + "\n" +
                    "   Failure:   " + e.getMessage());
        }
    }
}
 
Example 17
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 18
Source File: AbstractLocalTransform.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void retryWithDifferentMimetype(ContentReader reader, ContentWriter writer, String targetMimetype,
                                        Map<String, String> transformOptions, String renditionName,
                                        NodeRef sourceNodeRef, Throwable e)
{
    if (mimetypeService != null && localTransformServiceRegistry != null)
    {
        String differentType = mimetypeService.getMimetypeIfNotMatches(reader.getReader());
        if (differentType == null)
        {
            transformerDebug.debug("          Failed", e);
            throw new ContentIOException("Content conversion failed: \n" +
                    "   reader: " + reader + "\n" +
                    "   writer: " + writer + "\n" +
                    "   options: " + transformOptions,
                    e);
        }
        else
        {
            transformerDebug.debug("          Failed: Mimetype was '" + differentType + "'", e);
            String claimedMimetype = reader.getMimetype();

            if (retryTransformOnDifferentMimeType)
            {
                reader = reader.getReader();
                reader.setMimetype(differentType);
                long sourceSizeInBytes = reader.getSize();

                LocalTransform localTransform = localTransformServiceRegistry.getLocalTransform(
                        differentType, sourceSizeInBytes, targetMimetype, transformOptions, renditionName);
                if (localTransform == null)
                {
                    transformerDebug.debug("          Failed", e);
                    throw new ContentIOException("Content conversion failed: \n" +
                            "   reader: " + reader + "\n" +
                            "   writer: " + writer + "\n" +
                            "   options: " + transformOptions + "\n" +
                            "   claimed mime type: " + claimedMimetype + "\n" +
                            "   detected mime type: " + differentType + "\n" +
                            "   transformer not found" + "\n",
                            e
                    );
                }
                localTransform.transform(reader, writer, transformOptions, renditionName, sourceNodeRef);
            }
            else
            {
                throw new ContentIOException("Content conversion failed: \n" +
                        "   reader: " + reader + "\n" +
                        "   writer: " + writer + "\n" +
                        "   options: " + transformOptions + "\n" +
                        "   claimed mime type: " + claimedMimetype + "\n" +
                        "   detected mime type: " + differentType,
                        e
                );
            }
        }
    }
}
 
Example 19
Source File: AbstractLocalTransform.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void transform(ContentReader reader, ContentWriter writer, Map<String, String> transformOptions,
                      String renditionName, NodeRef sourceNodeRef)
{
    if (isAvailable())
    {
        String sourceMimetype = reader.getMimetype();
        String targetMimetype = writer.getMimetype();

        String sourceExtension = mimetypeService.getExtension(sourceMimetype);
        String targetExtension = mimetypeService.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);
        }

        transformOptions = getStrippedTransformOptions(transformOptions);
        transformWithDebug(reader, writer, transformOptions, renditionName, sourceNodeRef, sourceMimetype,
                targetMimetype, sourceExtension, targetExtension);

        if (log.isDebugEnabled())
        {
            log.debug("Local transformation completed: \n" +
                    "   source: " + reader + "\n" +
                    "   target: " + writer + "\n" +
                    "   options: " + transformOptions);
        }
    }
    else
    {
        if (log.isDebugEnabled())
        {
            transformOptions = getStrippedTransformOptions(transformOptions);
            log.debug("Local transformer not available: \n" +
                    "   source: " + reader + "\n" +
                    "   target: " + writer + "\n" +
                    "   options: " + transformOptions);
        }
    }
}