001/*
002 * (C) Copyright 2006-2016 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 *
019 */
020package org.nuxeo.ecm.core.convert.plugins.text.extractors;
021
022import java.io.File;
023import java.io.FileInputStream;
024import java.io.IOException;
025import java.io.InputStream;
026import java.io.Serializable;
027import java.util.Map;
028
029import javax.swing.text.BadLocationException;
030import javax.swing.text.Document;
031import javax.swing.text.rtf.RTFEditorKit;
032
033import org.nuxeo.common.utils.FileUtils;
034import org.nuxeo.ecm.core.api.Blob;
035import org.nuxeo.ecm.core.api.Blobs;
036import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
037import org.nuxeo.ecm.core.convert.api.ConversionException;
038import org.nuxeo.ecm.core.convert.cache.SimpleCachableBlobHolder;
039import org.nuxeo.ecm.core.convert.extension.Converter;
040import org.nuxeo.ecm.core.convert.extension.ConverterDescriptor;
041import org.nuxeo.runtime.api.Framework;
042
043public class RTF2TextConverter implements Converter {
044
045    @Override
046    public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters) throws ConversionException {
047        File f = null;
048        try {
049            RTFEditorKit rtfParser = new RTFEditorKit();
050            Document document = rtfParser.createDefaultDocument();
051            rtfParser.read(blobHolder.getBlob().getStream(), document, 0);
052            String text = document.getText(0, document.getLength());
053            f = Framework.createTempFile("swing-rtf2text", ".txt");
054            FileUtils.writeFile(f, text);
055            Blob blob;
056            try (InputStream in = new FileInputStream(f)) {
057                blob = Blobs.createBlob(in, "text/plain");
058            }
059            return new SimpleCachableBlobHolder(blob);
060        } catch (IOException | BadLocationException e) {
061            throw new ConversionException("Error during Word2Text conversion", e);
062        } finally {
063            if (f != null) {
064                f.delete();
065            }
066        }
067    }
068
069    @Override
070    public void init(ConverterDescriptor descriptor) {
071    }
072
073}