Build the nested classloader containing the OSGi framework, and the log provider.

@param urlList
@param verifyJarProperty
@return
341216
protected ClassLoader buildClassLoader(final List<URL> urlList, String verifyJarProperty) {
        if (libertyBoot) {
            // for liberty boot we just use the class loader that loaded this class
            return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                @Override
                public ClassLoader run() {
                    return getClass().getClassLoader();
                }
            });
        }
        final boolean verifyJar;
        if (System.getSecurityManager() == null) {
            // do not perform verification if SecurityManager is not installed
            // unless explicitly enabled.
            verifyJar = "true".equalsIgnoreCase(verifyJarProperty);
        } else {
            // always perform verification if SecurityManager is installed.
            verifyJar = true;
        }

        enableJava2SecurityIfSet(this.bootProps, urlList);

        ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {

            @Override
            public ClassLoader run() {
                ClassLoader parent = getClass().getClassLoader();
                URL[] urls = urlList.toArray(new URL[urlList.size()]);
                if (verifyJar) {
                    return new BootstrapChildFirstURLClassloader(urls, parent);
                } else {
                    try {
                        return new BootstrapChildFirstJarClassloader(urls, parent);
                    } catch (RuntimeException e) {
                        // fall back to URLClassLoader in case something went wrong
                        return new BootstrapChildFirstURLClassloader(urls, parent);
                    }
                }
            }

        });

        return loader;
    }
564814
@Override
    public List<URL> getJarFileUrls() {
        List<URL> urls = new ArrayList<>();
        for (String url : persistenceUnitXml.getJarFile()) {
            try {
                urls.add(new URL(url));
            } catch (MalformedURLException e) {
                LOGGER.error("Cannot create an URL object from {}", url, e);
            }
        }
        return urls;
    }
617060
protected static void loadProvider(final URL url, final ClassLoader cl) {
        try {
            final Properties props = PropertiesUtil.loadClose(url.openStream(), url);
            if (validVersion(props.getProperty(API_VERSION))) {
                final Provider provider = new Provider(props, url, cl);
                PROVIDERS.add(provider);
                LOGGER.debug("Loaded Provider {}", provider);
            }
        } catch (final IOException e) {
            LOGGER.error("Unable to open {}", url, e);
        }
    }
776223
protected String verifyAndWriteCatalogJar(CatalogChangeResult ccr)
    {
        String procedureName = "@VerifyCatalogAndWriteJar";

        CompletableFuture<Map<Integer,ClientResponse>> cf =
                callNTProcedureOnAllHosts(procedureName, ccr.catalogBytes, ccr.encodedDiffCommands,
                        ccr.catalogHash, ccr.deploymentBytes);

        Map<Integer, ClientResponse> resultMapByHost = null;
        String err;

        long timeoutSeconds = VerifyCatalogAndWriteJar.TIMEOUT;
        hostLog.info("Max timeout setting for VerifyCatalogAndWriteJar is " + timeoutSeconds + " seconds");

        try {
            Stopwatch sw = Stopwatch.createStarted();
            long elapsed = 0;
            while ((elapsed = sw.elapsed(TimeUnit.SECONDS)) < (timeoutSeconds)) {
                resultMapByHost = cf.getNow(null);
                if (resultMapByHost != null) {
                    sw.stop();
                    break;
                }

                if (elapsed < 5) {
                    // do not log under 5 seconds and sleep for 100 milliseconds
                    Thread.sleep(100);
                    continue;
                }
                hostLog.info(elapsed + " seconds has elapsed but " + procedureName + " is still wait for remote response."
                        + "The max timeout value is " + timeoutSeconds + " seconds.");
                Thread.sleep(TimeUnit.SECONDS.toMillis(5));
            }
        } catch (Exception e) {
            err = procedureName + " run everywhere call failed: " + e.getMessage();
            hostLog.info(err + ", " + com.google_voltpatches.common.base.Throwables.getStackTraceAsString(e));
            return err;
        }

        if (resultMapByHost == null) {
            err = "An invocation of procedure " + procedureName + " on all hosts timed out.";
            hostLog.info(err);
            return err;
        }

        for (Entry<Integer, ClientResponse> entry : resultMapByHost.entrySet()) {
            if (entry.getValue().getStatus() != ClientResponseImpl.SUCCESS) {
                err = "The response from host " + entry.getKey().toString() +
                      " for " + procedureName + " returned failures: " + entry.getValue().getStatusString();
                compilerLog.info(err);

                // hide the internal NT-procedure @VerifyCatalogAndWriteJar from the client message
                return err;
            }
        }

        return null;
    }
574721
public synchronized JarFile getNestedJarFile(JarEntryData sourceEntry)
            throws IOException {
        try {
            if (sourceEntry.nestedJar == null) {
                sourceEntry.nestedJar = createJarFileFromEntry(sourceEntry);
            }
            return sourceEntry.nestedJar;
        } catch (IOException ex) {
            throw new IOException(
                    "Unable to open nested jar file '" + sourceEntry.getName() + "'", ex);
        }
    }
924325
@Override
    public String getClassLoaderIdentifier(ClassLoader classloader) throws IllegalArgumentException {
        // Disable for bundles, because the bundle id can change across instances of the server,
        // meaning the identifier would not be reliable
        if (classloader instanceof ThreadContextClassLoader && !(classloader instanceof ThreadContextClassLoaderForBundles)) {
            return ((ThreadContextClassLoader) classloader).getKey();
        } else {
            return null;
        }
    }
1281630
public static Map<String, Version> identify(ClassLoader classLoader) {
        if (classLoader == null) {
            classLoader = PlatformDependent.getContextClassLoader();
        }

        // Collect all properties.
        Properties props = new Properties();
        try {
            Enumeration<URL> resources = classLoader.getResources("META-INF/io.netty.versions.properties");
            while (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                InputStream in = url.openStream();
                try {
                    props.load(in);
                } finally {
                    try {
                        in.close();
                    } catch (Exception ignore) {
                        // Ignore.
                    }
                }
            }
        } catch (Exception ignore) {
            // Not critical. Just ignore.
        }

        // Collect all artifactIds.
        Set<String> artifactIds = new HashSet<String>();
        for (Object o: props.keySet()) {
            String k = (String) o;

            int dotIndex = k.indexOf('.');
            if (dotIndex <= 0) {
                continue;
            }

            String artifactId = k.substring(0, dotIndex);

            // Skip the entries without required information.
            if (!props.containsKey(artifactId + PROP_VERSION) ||
                !props.containsKey(artifactId + PROP_BUILD_DATE) ||
                !props.containsKey(artifactId + PROP_COMMIT_DATE) ||
                !props.containsKey(artifactId + PROP_SHORT_COMMIT_HASH) ||
                !props.containsKey(artifactId + PROP_LONG_COMMIT_HASH) ||
                !props.containsKey(artifactId + PROP_REPO_STATUS)) {
                continue;
            }

            artifactIds.add(artifactId);
        }

        Map<String, Version> versions = new TreeMap<String, Version>();
        for (String artifactId: artifactIds) {
            versions.put(
                    artifactId,
                    new Version(
                            artifactId,
                            props.getProperty(artifactId + PROP_VERSION),
                            parseIso8601(props.getProperty(artifactId + PROP_BUILD_DATE)),
                            parseIso8601(props.getProperty(artifactId + PROP_COMMIT_DATE)),
                            props.getProperty(artifactId + PROP_SHORT_COMMIT_HASH),
                            props.getProperty(artifactId + PROP_LONG_COMMIT_HASH),
                            props.getProperty(artifactId + PROP_REPO_STATUS)));
        }

        return versions;
    }
945058
private JarFile getJarFile(String jarFileUrl) throws IOException {
        if (jarFileUrl.startsWith("file:")) {
            try {
                final URI uri = new URI(jarFileUrl.replaceAll(" ", "\\%20"));
                final String jarFileName = uri.getSchemeSpecificPart();
                logger.info("Creating new JarFile based on URI-scheme filename: {}", jarFileName);
                return new JarFile(jarFileName);
            } catch (URISyntaxException ex) {
                // Fallback for URLs that are not valid URIs (should hardly ever
                // happen).
                final String jarFileName = jarFileUrl.substring("file:".length());
                logger.info("Creating new JarFile based on alternative filename: {}", jarFileName);
                return new JarFile(jarFileName);
            }
        } else {
            logger.info("Creating new JarFile based on URI (with '!/'): {}", jarFileUrl);
            return new JarFile(jarFileUrl);
        }
    }
308826
URLClassLoader createUrlClassLoader(
            final List<String> classpathElements,
            final ClassLoader contextClassLoader)
            throws MojoExecutionException {
        try {
            final URL[] urls = new URL[classpathElements.size()];
            int i = 0;
            for (final String classpathElement : classpathElements) {
                urls[i++] = new File(classpathElement).toURI().toURL();
            }
            return URLClassLoader.newInstance(urls, contextClassLoader);
        } catch (final MalformedURLException e) {
            throw new MojoExecutionException("Unable to instantiate class loader", e);
        }
    }
607629
private ClassSignature loadClassFromJigsaw(String classname) throws IOException {
    if (method_Class_getModule == null || method_Module_getName == null) {
      return null; // not Jigsaw Module System
    }
    
    final Class<?> clazz;
    final String moduleName;
    try {
      clazz = Class.forName(classname, false, loader);
      final Object module = method_Class_getModule.invoke(clazz);
      moduleName = (String) method_Module_getName.invoke(module);
    } catch (Exception e) {
      return null; // not found
    }
    
    return new ClassSignature(clazz, AsmUtils.isRuntimeModule(moduleName));
  }
219718
public ClassLoader getSiteClassLoader (int siteId)
        throws IOException
    {
        // synchronize on the lock to ensure that only one thread per site
        // is concurrently executing
        synchronized (getLock(siteId)) {
            // see if we've already got one
            ClassLoader loader = _loaders.get(siteId);

            // create one if we've not
            if (loader == null) {
                final SiteResourceBundle bundle = getBundle(siteId);
                if (bundle == null) {
                    // no bundle... no classloader.
                    return null;
                }

                loader = AccessController.doPrivileged(new PrivilegedAction<SiteClassLoader>() {
                    public SiteClassLoader run () {
                        return new SiteClassLoader(bundle);
                    }
                });
                _loaders.put(siteId, loader);
            }

            return loader;
        }
    }
141181
@SuppressFBWarnings("DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED") // TODO: clarify and use service loader instead
    public static TerminalFactory loadTerminalFactory(String jar, String classname, String type, String arg) throws NoSuchAlgorithmException {
        try {
            // To support things like host:port pairs, urldecode the arguments component if provided
            if (arg != null) {
                arg = URLDecoder.decode(arg, "UTF-8");
            }
            final TerminalFactory tf;
            final Class<?> cls; // XXX: stricter type
            if (jar != null) {
                // Specify class loader
                URLClassLoader loader = new URLClassLoader(new URL[]{new File(jar).toURI().toURL()}, TerminalManager.class.getClassLoader());
                // Load custom provider
                cls = Class.forName(classname, true, loader);
            } else {
                // Load provider
                cls = Class.forName(classname);
            }
            Provider p = (Provider) cls.getConstructor().newInstance();
            tf = TerminalFactory.getInstance(type == null ? "PC/SC" : type, arg, p);
            return tf;
        } catch (UnsupportedEncodingException | MalformedURLException | ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
            throw new NoSuchAlgorithmException("Could not load " + classname + ": " + e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            if (e.getCause() != null) {
                Class<?> cause = e.getCause().getClass();
                if (cause.equals(java.lang.UnsupportedOperationException.class)) {
                    throw new NoSuchAlgorithmException(e.getCause().getMessage());
                }
                if (cause.equals(java.lang.UnsatisfiedLinkError.class)) {
                    throw new NoSuchAlgorithmException(e.getCause().getMessage());
                }
            }
            throw e;
        }
    }
1147362
public static ImmutableSet<File> findJarFiles(ClassLoader first, ClassLoader... rest)
      throws IOException {
    Scanner scanner = new Scanner();
    Map<URI, ClassLoader> map = Maps.newLinkedHashMap();
    for (ClassLoader classLoader : Lists.asList(first, rest)) {
      map.putAll(getClassPathEntries(classLoader));
    }
    for (Map.Entry<URI, ClassLoader> entry : map.entrySet()) {
      scanner.scan(entry.getKey(), entry.getValue());
    }
    return scanner.jarFiles();
  }
143421
public static URL[] getClassPathJars(final Bundle bundle) {
		final List<URL> urls = new ArrayList<>();
		final String bundleClasspath = (String) bundle.getHeaders().get(
				"Bundle-ClassPath");
		if (bundleClasspath != null) {
			String[] segments = bundleClasspath.split(",");
			for (String segment : segments) {
				final URL url = bundle.getEntry(segment);
				if (url != null) {
					if (url.toExternalForm().endsWith("jar")) {
						LOG.debug("Using url: " + url);
						try {
							URL jarUrl = new URL("jar:" + url.toExternalForm()
									+ "!/");
							urls.add(jarUrl);
						} catch (MalformedURLException ignore) {
							LOG.debug(ignore.getMessage());
						}
					}
				}
			}
		}
		LOG.debug("Bundle-ClassPath URLs: " + urls);
		// adds the depending bundles to the "classloader" space
		urls.addAll(getLocationsOfBundlesInClassSpace(bundle));

		return urls.toArray(new URL[urls.size()]);
	}
109028
public static URL extractJarURL(URL url) throws IOException {
        JarURLConnection connection = (JarURLConnection) url.openConnection();
        return connection.getJarFileURL();
    }
868383
public static TomcatServiceBuilder forClassPath(Class<?> clazz, String docBaseOrJarRoot) {
        requireNonNull(clazz, "clazz");
        requireNonNull(docBaseOrJarRoot, "docBaseOrJarRoot");

        final ProtectionDomain pd = clazz.getProtectionDomain();
        if (pd == null) {
            throw new IllegalArgumentException(clazz + " does not have a protection domain.");
        }
        final CodeSource cs = pd.getCodeSource();
        if (cs == null) {
            throw new IllegalArgumentException(clazz + " does not have a code source.");
        }
        final URL url = cs.getLocation();
        if (url == null) {
            throw new IllegalArgumentException(clazz + " does not have a location.");
        }

        if (!"file".equalsIgnoreCase(url.getProtocol())) {
            throw new IllegalArgumentException(clazz + " is not on a file system: " + url);
        }

        File f;
        try {
            f = new File(url.toURI());
        } catch (URISyntaxException ignored) {
            f = new File(url.getPath());
        }

        if (TomcatUtil.isZip(f.toPath())) {
            return new TomcatServiceBuilder(f.toPath(), docBaseOrJarRoot);
        }

        f = fileSystemDocBase(f, docBaseOrJarRoot);

        if (!f.isDirectory()) {
            throw new IllegalArgumentException(f + " is not a directory.");
        }

        return forFileSystem(f.toPath());
    }
119881
public static URLClassLoader getURLClassLoader(final File pluginDir,
      List<String> extLibClassPaths,
      ClassLoader parentLoader) {
    final File libDir = new File(pluginDir, LIBRARY_FOLDER_NAME);
    if (libDir.exists() && libDir.isDirectory()) {
      final File[] files = libDir.listFiles();
      final ArrayList<URL> urls = getUrls(files);

      if (extLibClassPaths != null) {
        for (final String extLibClassPath : extLibClassPaths) {
          try {
            final File extLibFile = new File(pluginDir, extLibClassPath);
            if (extLibFile.exists()) {
              if (extLibFile.isDirectory()) {
                // extLibFile is a directory; load all the files in the
                // directory.
                final File[] extLibFiles = extLibFile.listFiles();
                urls.addAll(getUrls(extLibFiles));
              } else {
                final URL url = extLibFile.toURI().toURL();
                urls.add(url);
              }
            } else {
              logger.error(
                  "External library path not found. path = " + extLibFile.getAbsolutePath()
              );
              continue;
            }
          } catch (final MalformedURLException e) {
            logger.error(
                "Invalid External library path. path = " + extLibClassPath + " dir = " + pluginDir,
                e
            );
          }
        }
      }
      return new URLClassLoader(urls.toArray(new URL[urls.size()]), parentLoader);
    } else {
      logger.error("Library path not found. path = " + libDir);
      return null;
    }
  }