View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2012-2025 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
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   * Sources in file system.
17   *
18   * If you have some resources in files, just configure your
19   * XSL with this "sources":
20   *
21   * <pre> XSL xsl = new XSLDocument(input).with(
22   *   new FileSources("/tmp/my-resources")
23   * );</pre>
24   *
25   * @since 0.18
26   */
27  @EqualsAndHashCode(of = "path")
28  public final class FileSources implements Sources {
29  
30      /**
31       * Directory.
32       */
33      private final transient File path;
34  
35      /**
36       * Public ctor.
37       */
38      public FileSources() {
39          this("");
40      }
41  
42      /**
43       * Public ctor.
44       * @param dir Directory
45       */
46      public FileSources(final String dir) {
47          this(new File(dir));
48      }
49  
50      /**
51       * Public ctor.
52       * @param dir Directory
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  }