1
2
3
4
5 package com.jcabi.xml;
6
7 import java.io.File;
8 import java.io.IOException;
9 import java.nio.file.Files;
10 import javax.xml.transform.Source;
11 import javax.xml.transform.TransformerException;
12 import javax.xml.transform.stream.StreamSource;
13 import lombok.EqualsAndHashCode;
14
15
16
17
18
19
20
21
22
23
24
25
26
27 @EqualsAndHashCode(of = "path")
28 public final class FileSources implements Sources {
29
30
31
32
33 private final transient File path;
34
35
36
37
38 public FileSources() {
39 this("");
40 }
41
42
43
44
45
46 public FileSources(final String dir) {
47 this(new File(dir));
48 }
49
50
51
52
53
54 public FileSources(final File dir) {
55 this.path = dir;
56 }
57
58 @Override
59 public Source resolve(final String href, final String base)
60 throws TransformerException {
61 File file = new File(this.path, href);
62 if (!file.exists()) {
63 if (base == null) {
64 file = new File(href);
65 } else {
66 file = new File(new File(base), href);
67 }
68 if (!file.exists()) {
69 throw new TransformerException(
70 String.format(
71 "File \"%s\" not found in \"%s\" and in base \"%s\"",
72 href, this.path, base
73 )
74 );
75 }
76 }
77 try {
78 return new StreamSource(Files.newInputStream(file.toPath()));
79 } catch (final IOException ex) {
80 throw new TransformerException(
81 String.format("Can't read from file '%s'", file),
82 ex
83 );
84 }
85 }
86 }