001/*
002 * (C) Copyright 2002-20012 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Antoine Taillefer
016 */
017package org.nuxeo.ecm.diff.content.converters;
018
019import java.io.IOException;
020import java.io.Serializable;
021import java.util.Map;
022
023import org.apache.commons.lang.StringUtils;
024import org.nuxeo.ecm.core.api.Blob;
025import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
026import org.nuxeo.ecm.core.convert.api.ConversionException;
027import org.nuxeo.ecm.core.convert.api.ConverterNotRegistered;
028
029/**
030 * Text converter for content diff.
031 * <p>
032 * Uses the "any2text" converter.
033 *
034 * @author Antoine Taillefer (ataillefer@nuxeo.com)
035 * @since 5.6
036 */
037public class ContentDiffTextConverter extends AbstractContentDiffConverter {
038
039    private static final String ANY_2_TEXT_CONVERTER_NAME = "any2text";
040
041    public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters) throws ConversionException {
042
043        BlobHolder convertedBlobHolder = convert(ANY_2_TEXT_CONVERTER_NAME, blobHolder, parameters);
044
045        String convertedBlobString = null;
046        try {
047            Blob convertedBlob = convertedBlobHolder.getBlob();
048            if (convertedBlob != null) {
049                convertedBlobString = convertedBlob.getString();
050            }
051        } catch (IOException e) {
052            throw new ConversionException("Error while getting converted blob string.");
053        }
054        if (StringUtils.isEmpty(convertedBlobString)) {
055            // Converted blob is an empty string, this means no text
056            // converter was found (see FullTextConverter). Throw
057            // appropriate exception.
058            String srcMimeType = null;
059            Blob blob = blobHolder.getBlob();
060            if (blob != null) {
061                srcMimeType = blob.getMimeType();
062            }
063            throw new ConverterNotRegistered(String.format("for sourceMimeType = %s, destinationMimeType = text/plain",
064                    srcMimeType));
065        }
066        return convertedBlobHolder;
067    }
068
069}