001/*
002 * Copyright (C) 2012 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.reflect;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH;
020import static com.google.common.base.StandardSystemProperty.PATH_SEPARATOR;
021import static java.util.logging.Level.WARNING;
022
023import com.google.common.annotations.VisibleForTesting;
024import com.google.common.base.CharMatcher;
025import com.google.common.base.Splitter;
026import com.google.common.collect.FluentIterable;
027import com.google.common.collect.ImmutableList;
028import com.google.common.collect.ImmutableMap;
029import com.google.common.collect.ImmutableSet;
030import com.google.common.io.ByteSource;
031import com.google.common.io.CharSource;
032import com.google.common.io.Resources;
033import java.io.File;
034import java.io.IOException;
035import java.net.MalformedURLException;
036import java.net.URISyntaxException;
037import java.net.URL;
038import java.net.URLClassLoader;
039import java.nio.charset.Charset;
040import java.util.Enumeration;
041import java.util.HashSet;
042import java.util.LinkedHashMap;
043import java.util.Map;
044import java.util.NoSuchElementException;
045import java.util.Set;
046import java.util.jar.Attributes;
047import java.util.jar.JarEntry;
048import java.util.jar.JarFile;
049import java.util.jar.Manifest;
050import java.util.logging.Logger;
051import org.jspecify.annotations.Nullable;
052
053/**
054 * Scans the source of a {@link ClassLoader} and finds all loadable classes and resources.
055 *
056 * <h2>Prefer alternatives to classpath scanning</h2>
057 *
058 * <p>Runtime classpath scanning is expensive because it traverses the entire transitive classpath,
059 * which can cause performance issues such as startup latency regressions. (It also does not support
060 * Android.) Before scanning the classpath at runtime, consider whether your use case can be solved
061 * with compile-time or static mechanisms:
062 *
063 * <ul>
064 *   <li>Compile-time service registration / annotation processors (e.g., {@code @AutoService})
065 *   <li>Dependency injection (e.g., Dagger, Guice)
066 *   <li>Explicit static registries or configuration
067 *   <li>Compile-time classpath scanning, such as <a
068 *       href="https://github.com/classgraph/classgraph/wiki/Build-Time-Scanning">that of
069 *       ClassGraph</a>, but compile-time scanning is likewise costly, so prefer the other options
070 *       when possible
071 * </ul>
072 *
073 * <h2>Limitations of {@code ClassPath} (for those who do need classpath scanning)</h2>
074 *
075 * <ul>
076 *   <li>It looks only for files and JARs in URLs available from {@link URLClassLoader} instances or
077 *       the {@linkplain ClassLoader#getSystemClassLoader() system class loader}. This means it does
078 *       not look for classes in the <i>module path</i> or in <a
079 *       href="https://github.com/classgraph/classgraph/wiki/Classpath-specification-mechanisms">other
080 *       environments</a>. If you need to scan one of those locations, consider <a
081 *       href="https://github.com/classgraph/classgraph/wiki">ClassGraph</a>.
082 *   <li>Like all of Guava, it is less battle-tested under Windows and other non-Linux systems. We
083 *       have gotten <a href="https://github.com/google/guava/issues/2130">a report of a specific
084 *       bug under Windows</a>.
085 *   <li>It <a href="https://github.com/google/guava/issues/2712">returns only one resource for a
086 *       given path</a>, even if resources with that path appear in multiple jars or directories.
087 *   <li>It <a href="https://github.com/google/guava/issues/3349">uses heuristics to guess at which
088 *       classes are nested and which are not</a>.
089 * </ul>
090 *
091 * <h2>{@code ClassPath} and symlinks</h2>
092 *
093 * <p>In the case of directory classloaders, symlinks are supported but cycles are not traversed.
094 * This guarantees discovery of each <em>unique</em> loadable resource. However, not all possible
095 * aliases for resources on cyclic paths will be listed.
096 *
097 * @author Ben Yu
098 * @since 14.0
099 */
100public final class ClassPath {
101  private static final Logger logger = Logger.getLogger(ClassPath.class.getName());
102
103  /** Separator for the Class-Path manifest attribute value in jar files. */
104  private static final Splitter CLASS_PATH_ATTRIBUTE_SEPARATOR =
105      Splitter.on(" ").omitEmptyStrings();
106
107  private static final String CLASS_FILE_NAME_EXTENSION = ".class";
108
109  private final ImmutableSet<ResourceInfo> resources;
110
111  private ClassPath(ImmutableSet<ResourceInfo> resources) {
112    this.resources = resources;
113  }
114
115  /**
116   * Returns a {@code ClassPath} representing all classes and resources loadable from {@code
117   * classloader} and its ancestor class loaders.
118   *
119   * <p><b>Warning:</b> {@code ClassPath} can find classes and resources only from:
120   *
121   * <ul>
122   *   <li>{@link URLClassLoader} instances' {@code file:} URLs
123   *   <li>the {@linkplain ClassLoader#getSystemClassLoader() system class loader}. To search the
124   *       system class loader even when it is not a {@link URLClassLoader} (as in Java 9), {@code
125   *       ClassPath} searches the files from the {@code java.class.path} system property.
126   * </ul>
127   *
128   * @throws IOException if the attempt to read class path resources (jar files or directories)
129   *     failed.
130   */
131  public static ClassPath from(ClassLoader classloader) throws IOException {
132    ImmutableSet<LocationInfo> locations = locationsFrom(classloader);
133
134    // Add all locations to the scanned set so that in a classpath [jar1, jar2], where jar1 has a
135    // manifest with Class-Path pointing to jar2, we won't scan jar2 twice.
136    Set<File> scanned = new HashSet<>();
137    for (LocationInfo location : locations) {
138      scanned.add(location.file());
139    }
140
141    // Scan all locations
142    ImmutableSet.Builder<ResourceInfo> builder = ImmutableSet.builder();
143    for (LocationInfo location : locations) {
144      builder.addAll(location.scanResources(scanned));
145    }
146    return new ClassPath(builder.build());
147  }
148
149  /**
150   * Returns all resources loadable from the current class path, including the class files of all
151   * loadable classes but excluding the "META-INF/MANIFEST.MF" file.
152   */
153  public ImmutableSet<ResourceInfo> getResources() {
154    return resources;
155  }
156
157  /**
158   * Returns all classes loadable from the current class path.
159   *
160   * @since 16.0
161   */
162  public ImmutableSet<ClassInfo> getAllClasses() {
163    return FluentIterable.from(resources).filter(ClassInfo.class).toSet();
164  }
165
166  /**
167   * Returns all top level classes loadable from the current class path. Note that "top-level-ness"
168   * is determined heuristically by class name (see {@link ClassInfo#isTopLevel}).
169   */
170  public ImmutableSet<ClassInfo> getTopLevelClasses() {
171    return FluentIterable.from(resources)
172        .filter(ClassInfo.class)
173        .filter(ClassInfo::isTopLevel)
174        .toSet();
175  }
176
177  /** Returns all top level classes whose package name is {@code packageName}. */
178  public ImmutableSet<ClassInfo> getTopLevelClasses(String packageName) {
179    checkNotNull(packageName);
180    ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder();
181    for (ClassInfo classInfo : getTopLevelClasses()) {
182      if (classInfo.getPackageName().equals(packageName)) {
183        builder.add(classInfo);
184      }
185    }
186    return builder.build();
187  }
188
189  /**
190   * Returns all top level classes whose package name is {@code packageName} or starts with {@code
191   * packageName} followed by a '.'.
192   */
193  public ImmutableSet<ClassInfo> getTopLevelClassesRecursive(String packageName) {
194    checkNotNull(packageName);
195    String packagePrefix = packageName + '.';
196    ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder();
197    for (ClassInfo classInfo : getTopLevelClasses()) {
198      if (classInfo.getName().startsWith(packagePrefix)) {
199        builder.add(classInfo);
200      }
201    }
202    return builder.build();
203  }
204
205  /**
206   * Represents a class path resource that can be either a class file or any other resource file
207   * loadable from the class path.
208   *
209   * @since 14.0
210   */
211  public static class ResourceInfo {
212    private final File file;
213    private final String resourceName;
214
215    final ClassLoader loader;
216
217    static ResourceInfo of(File file, String resourceName, ClassLoader loader) {
218      if (resourceName.endsWith(CLASS_FILE_NAME_EXTENSION)) {
219        return new ClassInfo(file, resourceName, loader);
220      } else {
221        return new ResourceInfo(file, resourceName, loader);
222      }
223    }
224
225    ResourceInfo(File file, String resourceName, ClassLoader loader) {
226      this.file = checkNotNull(file);
227      this.resourceName = checkNotNull(resourceName);
228      this.loader = checkNotNull(loader);
229    }
230
231    /**
232     * Returns the url identifying the resource.
233     *
234     * <p>See {@link ClassLoader#getResource}
235     *
236     * @throws NoSuchElementException if the resource cannot be loaded through the class loader,
237     *     despite physically existing in the class path.
238     */
239    public final URL url() {
240      URL url = loader.getResource(resourceName);
241      if (url == null) {
242        throw new NoSuchElementException(resourceName);
243      }
244      return url;
245    }
246
247    /**
248     * Returns a {@link ByteSource} view of the resource from which its bytes can be read.
249     *
250     * @throws NoSuchElementException if the resource cannot be loaded through the class loader,
251     *     despite physically existing in the class path.
252     * @since 20.0
253     */
254    public final ByteSource asByteSource() {
255      return Resources.asByteSource(url());
256    }
257
258    /**
259     * Returns a {@link CharSource} view of the resource from which its bytes can be read as
260     * characters decoded with the given {@code charset}.
261     *
262     * @throws NoSuchElementException if the resource cannot be loaded through the class loader,
263     *     despite physically existing in the class path.
264     * @since 20.0
265     */
266    public final CharSource asCharSource(Charset charset) {
267      return Resources.asCharSource(url(), charset);
268    }
269
270    /** Returns the fully qualified name of the resource. Such as "com/mycomp/foo/bar.txt". */
271    public final String getResourceName() {
272      return resourceName;
273    }
274
275    /** Returns the file that includes this resource. */
276    final File getFile() {
277      return file;
278    }
279
280    @Override
281    public final int hashCode() {
282      return resourceName.hashCode();
283    }
284
285    @Override
286    public final boolean equals(@Nullable Object obj) {
287      if (obj instanceof ResourceInfo) {
288        ResourceInfo that = (ResourceInfo) obj;
289        return resourceName.equals(that.resourceName) && loader == that.loader;
290      }
291      return false;
292    }
293
294    // Do not change this arbitrarily. We rely on it for sorting ResourceInfo.
295    @Override
296    public String toString() {
297      return resourceName;
298    }
299  }
300
301  /**
302   * Represents a class that can be loaded through {@link #load}.
303   *
304   * @since 14.0
305   */
306  public static final class ClassInfo extends ResourceInfo {
307    private final String className;
308
309    ClassInfo(File file, String resourceName, ClassLoader loader) {
310      super(file, resourceName, loader);
311      this.className = getClassName(resourceName);
312    }
313
314    /**
315     * Returns the package name of the class, without attempting to load the class.
316     *
317     * <p>Behaves similarly to {@code class.getPackage().}{@link Package#getName() getName()} but
318     * does not require the class (or package) to be loaded.
319     *
320     * <p>But note that this method may behave differently for a class in the default package: For
321     * such classes, this method always returns an empty string. But under some version of Java,
322     * {@code class.getPackage().getName()} produces a {@code NullPointerException} because {@code
323     * class.getPackage()} returns {@code null}.
324     */
325    public String getPackageName() {
326      return Reflection.getPackageName(className);
327    }
328
329    /**
330     * Returns the simple name of the underlying class as given in the source code.
331     *
332     * <p>Behaves similarly to {@link Class#getSimpleName()} but does not require the class to be
333     * loaded.
334     *
335     * <p>But note that this class uses heuristics to identify the simple name. See a related
336     * discussion in <a href="https://github.com/google/guava/issues/3349">issue 3349</a>.
337     */
338    public String getSimpleName() {
339      int lastDollarSign = lastNestedClassSeparator();
340      if (lastDollarSign != -1) {
341        String innerClassName = className.substring(lastDollarSign + 1);
342        // local and anonymous classes are prefixed with number (1,2,3...), anonymous classes are
343        // entirely numeric whereas local classes have the user supplied name as a suffix
344        return CharMatcher.inRange('0', '9').trimLeadingFrom(innerClassName);
345      }
346      String packageName = getPackageName();
347      if (packageName.isEmpty()) {
348        return className;
349      }
350
351      // Since this is a top level class, its simple name is always the part after package name.
352      return className.substring(packageName.length() + 1);
353    }
354
355    /**
356     * Returns the fully qualified name of the class.
357     *
358     * <p>Behaves identically to {@link Class#getName()} but does not require the class to be
359     * loaded.
360     */
361    public String getName() {
362      return className;
363    }
364
365    /**
366     * Returns true if the class name "looks to be" top level (not nested), that is, it includes no
367     * isolated '$' in the name other than at the beginning or end of the simple name (as in
368     * generated classes like {@code $AutoValue_Foo} or {@code $$AutoValue_Foo}). This method may
369     * return false for a top-level class that's intentionally named with a '$' character elsewhere.
370     * If this is a concern, you could use {@link #load} and then check on the loaded {@link Class}
371     * object instead.
372     *
373     * @since 30.1
374     */
375    public boolean isTopLevel() {
376      return lastNestedClassSeparator() == -1;
377    }
378
379    /**
380     * Returns the index of the last '$' that "looks to be" a nested-class separator, or -1 if there
381     * is none. Leading, trailing, and repeated '$' characters in the part of the name after the
382     * package are ignored, since they are commonly part of the names of generated top-level
383     * classes.
384     */
385    private int lastNestedClassSeparator() {
386      for (int i = className.length() - 2; i >= 1; i--) {
387        char a = className.charAt(i - 1);
388        char b = className.charAt(i);
389        char c = className.charAt(i + 1);
390        if (a == '.' || b == '.' || c == '.') {
391          return -1;
392        }
393        if (a != '$' && b == '$' && c != '$') {
394          return i;
395        }
396      }
397      return -1;
398    }
399
400    /**
401     * Loads (but doesn't link or initialize) the class.
402     *
403     * @throws LinkageError when there were errors in loading classes that this class depends on.
404     *     For example, {@link NoClassDefFoundError}.
405     */
406    public Class<?> load() {
407      try {
408        return loader.loadClass(className);
409      } catch (ClassNotFoundException e) {
410        // Shouldn't happen, since the class name is read from the class path.
411        throw new IllegalStateException(e);
412      }
413    }
414
415    @Override
416    public String toString() {
417      return className;
418    }
419  }
420
421  /**
422   * Returns all locations that {@code classloader} and parent loaders load classes and resources
423   * from. Callers can {@linkplain LocationInfo#scanResources scan} individual locations selectively
424   * or even in parallel.
425   */
426  static ImmutableSet<LocationInfo> locationsFrom(ClassLoader classloader) {
427    ImmutableSet.Builder<LocationInfo> builder = ImmutableSet.builder();
428    for (Map.Entry<File, ClassLoader> entry : getClassPathEntries(classloader).entrySet()) {
429      builder.add(new LocationInfo(entry.getKey(), entry.getValue()));
430    }
431    return builder.build();
432  }
433
434  /**
435   * Represents a single location (a directory or a jar file) in the class path and is responsible
436   * for scanning resources from this location.
437   */
438  static final class LocationInfo {
439    final File home;
440    private final ClassLoader classloader;
441
442    LocationInfo(File home, ClassLoader classloader) {
443      this.home = checkNotNull(home);
444      this.classloader = checkNotNull(classloader);
445    }
446
447    /** Returns the file this location is from. */
448    public File file() {
449      return home;
450    }
451
452    /** Scans this location and returns all scanned resources. */
453    public ImmutableSet<ResourceInfo> scanResources() throws IOException {
454      return scanResources(new HashSet<File>());
455    }
456
457    /**
458     * Scans this location and returns all scanned resources.
459     *
460     * <p>This file and jar files from "Class-Path" entry in the scanned manifest files will be
461     * added to {@code scannedFiles}.
462     *
463     * <p>A file will be scanned at most once even if specified multiple times by one or multiple
464     * jar files' "Class-Path" manifest entries. Particularly, if a jar file from the "Class-Path"
465     * manifest entry is already in {@code scannedFiles}, either because it was scanned earlier, or
466     * it was intentionally added to the set by the caller, it will not be scanned again.
467     *
468     * <p>Note that when you call {@code location.scanResources(scannedFiles)}, the location will
469     * always be scanned even if {@code scannedFiles} already contains it.
470     */
471    public ImmutableSet<ResourceInfo> scanResources(Set<File> scannedFiles) throws IOException {
472      ImmutableSet.Builder<ResourceInfo> builder = ImmutableSet.builder();
473      scannedFiles.add(home);
474      scan(home, scannedFiles, builder);
475      return builder.build();
476    }
477
478    private void scan(File file, Set<File> scannedUris, ImmutableSet.Builder<ResourceInfo> builder)
479        throws IOException {
480      try {
481        if (!file.exists()) {
482          return;
483        }
484      } catch (SecurityException e) {
485        logger.warning("Cannot access " + file + ": " + e);
486        // TODO(emcmanus): consider whether to log other failure cases too.
487        return;
488      }
489      if (file.isDirectory()) {
490        scanDirectory(file, builder);
491      } else {
492        scanJar(file, scannedUris, builder);
493      }
494    }
495
496    private void scanJar(
497        File file, Set<File> scannedUris, ImmutableSet.Builder<ResourceInfo> builder)
498        throws IOException {
499      JarFile jarFile;
500      try {
501        jarFile = new JarFile(file);
502      } catch (IOException e) {
503        // Not a jar file
504        return;
505      }
506      try {
507        for (File path : getClassPathFromManifest(file, jarFile.getManifest())) {
508          // We only scan each file once independent of the classloader that file might be
509          // associated with.
510          if (scannedUris.add(path.getCanonicalFile())) {
511            scan(path, scannedUris, builder);
512          }
513        }
514        scanJarFile(jarFile, builder);
515      } finally {
516        try {
517          jarFile.close();
518        } catch (IOException ignored) { // similar to try-with-resources, but don't fail scanning
519        }
520      }
521    }
522
523    private void scanJarFile(JarFile file, ImmutableSet.Builder<ResourceInfo> builder) {
524      Enumeration<JarEntry> entries = file.entries();
525      while (entries.hasMoreElements()) {
526        JarEntry entry = entries.nextElement();
527        if (entry.isDirectory() || entry.getName().equals(JarFile.MANIFEST_NAME)) {
528          continue;
529        }
530        builder.add(ResourceInfo.of(new File(file.getName()), entry.getName(), classloader));
531      }
532    }
533
534    private void scanDirectory(File directory, ImmutableSet.Builder<ResourceInfo> builder)
535        throws IOException {
536      Set<File> currentPath = new HashSet<>();
537      currentPath.add(directory.getCanonicalFile());
538      scanDirectory(directory, "", currentPath, builder);
539    }
540
541    /**
542     * Recursively scan the given directory, adding resources for each file encountered. Symlinks
543     * which have already been traversed in the current tree path will be skipped to eliminate
544     * cycles; otherwise symlinks are traversed.
545     *
546     * @param directory the root of the directory to scan
547     * @param packagePrefix resource path prefix inside {@code classloader} for any files found
548     *     under {@code directory}
549     * @param currentPath canonical files already visited in the current directory tree path, for
550     *     cycle elimination
551     */
552    private void scanDirectory(
553        File directory,
554        String packagePrefix,
555        Set<File> currentPath,
556        ImmutableSet.Builder<ResourceInfo> builder)
557        throws IOException {
558      File[] files = directory.listFiles();
559      if (files == null) {
560        logger.warning("Cannot read directory " + directory);
561        // IO error, just skip the directory
562        return;
563      }
564      for (File f : files) {
565        String name = f.getName();
566        if (f.isDirectory()) {
567          File deref = f.getCanonicalFile();
568          if (currentPath.add(deref)) {
569            scanDirectory(deref, packagePrefix + name + "/", currentPath, builder);
570            currentPath.remove(deref);
571          }
572        } else {
573          String resourceName = packagePrefix + name;
574          if (!resourceName.equals(JarFile.MANIFEST_NAME)) {
575            builder.add(ResourceInfo.of(f, resourceName, classloader));
576          }
577        }
578      }
579    }
580
581    @Override
582    public boolean equals(@Nullable Object obj) {
583      if (obj instanceof LocationInfo) {
584        LocationInfo that = (LocationInfo) obj;
585        return home.equals(that.home) && classloader.equals(that.classloader);
586      }
587      return false;
588    }
589
590    @Override
591    public int hashCode() {
592      return home.hashCode();
593    }
594
595    @Override
596    public String toString() {
597      return home.toString();
598    }
599  }
600
601  /**
602   * Returns the class path URIs specified by the {@code Class-Path} manifest attribute, according
603   * to <a
604   * href="https://docs.oracle.com/en/java/javase/27/docs/specs/jar/jar.html#main-attributes">JAR
605   * File Specification</a>. If {@code manifest} is null, it means the jar file has no manifest, and
606   * an empty set will be returned.
607   */
608  @VisibleForTesting
609  static ImmutableSet<File> getClassPathFromManifest(File jarFile, @Nullable Manifest manifest) {
610    if (manifest == null) {
611      return ImmutableSet.of();
612    }
613    ImmutableSet.Builder<File> builder = ImmutableSet.builder();
614    String classpathAttribute =
615        manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH.toString());
616    if (classpathAttribute != null) {
617      for (String path : CLASS_PATH_ATTRIBUTE_SEPARATOR.split(classpathAttribute)) {
618        URL url;
619        try {
620          url = getClassPathEntry(jarFile, path);
621        } catch (MalformedURLException e) {
622          // Ignore bad entry
623          logger.warning("Invalid Class-Path entry: " + path);
624          continue;
625        }
626        if (url.getProtocol().equals("file")) {
627          builder.add(toFile(url));
628        }
629      }
630    }
631    return builder.build();
632  }
633
634  @VisibleForTesting
635  static ImmutableMap<File, ClassLoader> getClassPathEntries(ClassLoader classloader) {
636    LinkedHashMap<File, ClassLoader> entries = new LinkedHashMap<>();
637    // Search parent first, since it's the order ClassLoader#loadClass() uses.
638    ClassLoader parent = classloader.getParent();
639    if (parent != null) {
640      entries.putAll(getClassPathEntries(parent));
641    }
642    for (URL url : getClassLoaderUrls(classloader)) {
643      if (url.getProtocol().equals("file")) {
644        File file = toFile(url);
645        if (!entries.containsKey(file)) {
646          entries.put(file, classloader);
647        }
648      }
649    }
650    return ImmutableMap.copyOf(entries);
651  }
652
653  private static ImmutableList<URL> getClassLoaderUrls(ClassLoader classloader) {
654    if (classloader instanceof URLClassLoader) {
655      return ImmutableList.copyOf(((URLClassLoader) classloader).getURLs());
656    }
657    if (classloader.equals(ClassLoader.getSystemClassLoader())) {
658      return parseJavaClassPath();
659    }
660    return ImmutableList.of();
661  }
662
663  /**
664   * Returns the URLs in the class path specified by the {@code java.class.path} {@linkplain
665   * System#getProperty system property}.
666   */
667  @VisibleForTesting // TODO(b/65488446): Make this a public API.
668  static ImmutableList<URL> parseJavaClassPath() {
669    ImmutableList.Builder<URL> urls = ImmutableList.builder();
670    for (String entry : Splitter.on(PATH_SEPARATOR.value()).split(JAVA_CLASS_PATH.value())) {
671      try {
672        try {
673          urls.add(new File(entry).toURI().toURL());
674        } catch (SecurityException e) { // File.toURI checks to see if the file is a directory
675          urls.add(new URL("file", null, new File(entry).getAbsolutePath()));
676        }
677      } catch (MalformedURLException e) {
678        logger.log(WARNING, "malformed classpath entry: " + entry, e);
679      }
680    }
681    return urls.build();
682  }
683
684  /**
685   * Returns the absolute uri of the Class-Path entry value as specified in <a
686   * href="https://docs.oracle.com/en/java/javase/27/docs/specs/jar/jar.html#main-attributes">JAR
687   * File Specification</a>. Even though the specification only talks about relative urls, absolute
688   * urls are actually supported too (for example, in Maven surefire plugin).
689   */
690  @VisibleForTesting
691  static URL getClassPathEntry(File jarFile, String path) throws MalformedURLException {
692    return new URL(jarFile.toURI().toURL(), path);
693  }
694
695  @VisibleForTesting
696  static String getClassName(String filename) {
697    int classNameEnd = filename.length() - CLASS_FILE_NAME_EXTENSION.length();
698    return filename.substring(0, classNameEnd).replace('/', '.');
699  }
700
701  // TODO(benyu): Try java.nio.file.Paths#get() when Guava drops JDK 6 support.
702  @VisibleForTesting
703  static File toFile(URL url) {
704    checkArgument(url.getProtocol().equals("file"));
705    try {
706      return new File(url.toURI()); // Accepts escaped characters like %20.
707    } catch (URISyntaxException e) { // URL.toURI() doesn't escape chars.
708      return new File(url.getPath()); // Accepts non-escaped chars like space.
709    }
710  }
711}