aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/zwobble/mammoth/internal/docx/NotesXmlReader.java
blob: 235535e9a0a7411e92b96fa801bb288fdb64ef39 (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
package org.zwobble.mammoth.internal.docx;

import org.zwobble.mammoth.internal.documents.Note;
import org.zwobble.mammoth.internal.documents.NoteType;
import org.zwobble.mammoth.internal.results.InternalResult;
import org.zwobble.mammoth.internal.xml.XmlElement;

import java.util.List;

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

public class NotesXmlReader {
    public static NotesXmlReader footnote(BodyXmlReader bodyReader) {
        return new NotesXmlReader(bodyReader, "footnote", NoteType.FOOTNOTE);
    }

    public static NotesXmlReader endnote(BodyXmlReader bodyReader) {
        return new NotesXmlReader(bodyReader, "endnote", NoteType.ENDNOTE);
    }

    private final BodyXmlReader bodyReader;
    private final String tagName;
    private final NoteType noteType;

    private NotesXmlReader(BodyXmlReader bodyReader, String tagName, NoteType noteType) {
        this.bodyReader = bodyReader;
        this.tagName = tagName;
        this.noteType = noteType;
    }

    public InternalResult<List<Note>> readElement(XmlElement element) {
        Iterable<XmlElement> elements = filter(element.findChildren("w:" + tagName), this::isNoteElement);
        return InternalResult.flatMap(elements, this::readNoteElement);
    }

    private boolean isNoteElement(XmlElement element) {
        return element.getAttributeOrNone("w:type")
            .map(type -> !isSeparatorType(type))
            .orElse(true);
    }

    private boolean isSeparatorType(String type) {
        return type.equals("continuationSeparator") || type.equals("separator");
    }

    private InternalResult<Note> readNoteElement(XmlElement element) {
        return bodyReader.readElements(element.children())
            .toResult()
            .map(children -> new Note(
                noteType,
                element.getAttribute("w:id"),
                children));
    }
}