aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/zwobble/mammoth/Mammoth.java
blob: c4252803b87cc21681665f0817713fd785212fa4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package org.zwobble.mammoth;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.zwobble.mammoth.xml.XmlElement;
import org.zwobble.mammoth.xml.XmlNodeVisitor;
import org.zwobble.mammoth.xml.XmlParser;
import org.zwobble.mammoth.xml.XmlTextNode;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableBiMap;

import static com.google.common.collect.Iterables.transform;

public class Mammoth {

    public static String convertToHtml(File file) {
        try (ZipFile zipFile = new ZipFile(file)) {
            ZipEntry entry = zipFile.getEntry("word/document.xml");
            XmlElement documentXml = parseXml(zipFile.getInputStream(entry));
            String text = extractText(documentXml);
            if (Strings.isNullOrEmpty(text)) {
                return "";
            } else {
                return "<p>" + text + "</p>";                
            }
        } catch (IOException e) {
            throw new UnsupportedOperationException("Should return a result of failure");   
        }
    }

    private static XmlElement parseXml(InputStream inputStream) {
        return new XmlParser(ImmutableBiMap.of()).parseStream(inputStream);
    }

    private static String extractText(XmlElement documentXml) {
        return documentXml.accept(new XmlNodeVisitor<String>() {
            @Override
            public String visit(XmlElement element) {
                return Joiner.on("").join(
                    transform(element.children(), child -> child.accept(this)));
            }

            @Override
            public String Visit(XmlTextNode textNode) {
                return textNode.getValue();
            }
        });
    }

}