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

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.util.Optional;

public class PathRelativeFileReader implements FileReader {
    public static FileReader relativeTo(Optional<Path> path) {
        return new PathRelativeFileReader(path);
    }

    private final Optional<Path> path;

    private PathRelativeFileReader(Optional<Path> path) {
        this.path = path;
    }

    @Override
    public InputStream getInputStream(String uri) throws IOException {
        try {
            Optional<URI> absoluteUri = asAbsoluteUri(uri);
            if (absoluteUri.isPresent()) {
                return open(absoluteUri.get());
            } else if (path.isPresent()) {
                return open(path.get().toUri().resolve(uri));
            } else {
                throw new IOException("path of document is unknown, but is required for relative URI");
            }
        } catch (IOException exception) {
            throw new IOException("could not open external image '" + uri + "': " + exception.getMessage());
        }
    }

    private static InputStream open(URI uri) throws IOException {
        return uri.toURL().openStream();
    }

    private static Optional<URI> asAbsoluteUri(String uriString) {
        try {
            URI uri = new URI(uriString);
            return uri.isAbsolute() ? Optional.of(uri) : Optional.empty();
        } catch (URISyntaxException exception) {
            return Optional.empty();
        }
    }
}