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.InputStream;
8   import javax.xml.transform.Source;
9   import javax.xml.transform.TransformerException;
10  import javax.xml.transform.stream.StreamSource;
11  import lombok.EqualsAndHashCode;
12  
13  /**
14   * Sources in classpath.
15   * @since 0.9
16   */
17  @EqualsAndHashCode(of = "prefix")
18  public final class ClasspathSources implements Sources {
19  
20      /**
21       * Pattern to compose resource.
22       */
23      private static final String PATTERN = "%s%s";
24  
25      /**
26       * Prefix.
27       */
28      private final transient String prefix;
29  
30      /**
31       * Public ctor.
32       */
33      public ClasspathSources() {
34          this("");
35      }
36  
37      /**
38       * Public ctor.
39       * @param type Start with this type
40       */
41      public ClasspathSources(final Class<?> type) {
42          this(
43              String.format(
44                  "/%s/",
45                  type.getPackage().getName().replace(".", "/")
46              )
47          );
48      }
49  
50      /**
51       * Public ctor.
52       * @param pfx Classpath prefix
53       */
54      public ClasspathSources(final String pfx) {
55          this.prefix = pfx;
56      }
57  
58      @Override
59      @SuppressWarnings("PMD.CloseResource")
60      public Source resolve(final String href, final String base)
61          throws TransformerException {
62          InputStream stream = this.getClass().getResourceAsStream(
63              String.format(ClasspathSources.PATTERN, this.prefix, href)
64          );
65          if (stream == null) {
66              final InputStream fallback = this.getClass().getResourceAsStream(
67                  String.format(ClasspathSources.PATTERN, base, href)
68              );
69              if (fallback == null) {
70                  throw new TransformerException(
71                      String.format(
72                          "Resource \"%s\" not found in classpath with prefix \"%s\" and base \"%s\"",
73                          href, this.prefix, base
74                      )
75                  );
76              }
77              stream = fallback;
78          }
79          return new StreamSource(stream);
80      }
81  }