1 /*
2  * Copyright (C) 2017 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 
15 package com.google.common.util.concurrent;
16 
17 import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH;
18 import static com.google.common.base.StandardSystemProperty.PATH_SEPARATOR;
19 
20 import com.google.common.base.Splitter;
21 import com.google.common.collect.ImmutableList;
22 import java.io.File;
23 import java.net.MalformedURLException;
24 import java.net.URL;
25 import java.net.URLClassLoader;
26 
27 // TODO(b/65488446): Make this a public API.
28 /** Utility method to parse the system class path. */
29 final class ClassPathUtil {
ClassPathUtil()30   private ClassPathUtil() {}
31 
32   /**
33    * Returns the URLs in the class path specified by the {@code java.class.path} {@linkplain
34    * System#getProperty system property}.
35    */
36   // TODO(b/65488446): Make this a public API.
parseJavaClassPath()37   static URL[] parseJavaClassPath() {
38     ImmutableList.Builder<URL> urls = ImmutableList.builder();
39     for (String entry : Splitter.on(PATH_SEPARATOR.value()).split(JAVA_CLASS_PATH.value())) {
40       try {
41         try {
42           urls.add(new File(entry).toURI().toURL());
43         } catch (SecurityException e) { // File.toURI checks to see if the file is a directory
44           urls.add(new URL("file", null, new File(entry).getAbsolutePath()));
45         }
46       } catch (MalformedURLException e) {
47         AssertionError error = new AssertionError("malformed class path entry: " + entry);
48         error.initCause(e);
49         throw error;
50       }
51     }
52     return urls.build().toArray(new URL[0]);
53   }
54 
55   /** Returns the URLs in the class path. */
getClassPathUrls()56   static URL[] getClassPathUrls() {
57     return ClassPathUtil.class.getClassLoader() instanceof URLClassLoader
58         ? ((URLClassLoader) ClassPathUtil.class.getClassLoader()).getURLs()
59         : parseJavaClassPath();
60   }
61 }
62