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       * @param url URL of a classpath entry
36       */
37      Unencoded(final URL url) {
38          this.url = url;
39      }
40  
41      /**
42       * Absolute path of the file this URL points at.
43       * @return The path, or empty if the URL is not a local file
44       */
45      Optional<String> path() {
46          Optional<String> path = Optional.empty();
47          if ("file".equals(this.url.getProtocol())) {
48              try {
49                  path = Optional.of(
50                      new File(this.url.toURI()).getAbsolutePath()
51                  );
52              } catch (final URISyntaxException | IllegalArgumentException ex) {
53                  Logger.debug(
54                      this, "Cannot resolve %s: %s", this.url, ex.getMessage()
55                  );
56              }
57          }
58          return path;
59      }
60  }