View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2026 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.qulice.errorprone;
6   
7   import com.jcabi.log.Logger;
8   import java.io.File;
9   import java.net.URISyntaxException;
10  import java.net.URL;
11  import java.util.Optional;
12  
13  /**
14   * A classpath entry behind a {@code file:} URL, with its percent-encoding
15   * undone.
16   *
17   * <p>{@link URL#getPath()} hands back the encoded path component, so a jar
18   * living under a directory whose name contains a space or any other
19   * URL-reserved character keeps its {@code %20} and the forked {@code javac}
20   * finds no file by that name. Going through {@link java.net.URI} turns the
21   * escapes back into the characters that are really on disk. URLs of any
22   * other protocol point at nothing local and resolve to nothing.</p>
23   *
24   * @since 1.0
25   */
26  final class Unencoded {
27  
28      /**
29       * URL of a classpath entry.
30       */
31      private final URL url;
32  
33      /**
34       * Constructor.
35       *
36       * @param url URL of a classpath entry
37       */
38      Unencoded(final URL url) {
39          this.url = url;
40      }
41  
42      /**
43       * Absolute path of the file this URL points at.
44       *
45       * @return The path, or empty if the URL is not a local file
46       */
47      Optional<String> path() {
48          Optional<String> path = Optional.empty();
49          if ("file".equals(this.url.getProtocol())) {
50              try {
51                  path = Optional.of(
52                      new File(this.url.toURI()).getAbsolutePath()
53                  );
54              } catch (final URISyntaxException | IllegalArgumentException ex) {
55                  Logger.debug(
56                      this, "Cannot resolve %s: %s", this.url, ex.getMessage()
57                  );
58              }
59          }
60          return path;
61      }
62  }