从URL中获取JarFile

@param url URL
@return JarFile
@since 4.1.5
768728
public static JarFile getJarFile(URL url) {
		try {
			JarURLConnection urlConnection = (JarURLConnection) url.openConnection();
			return urlConnection.getJarFile();
		} catch (IOException e) {
			throw new IORuntimeException(e);
		}
	}
1306647
public static Map<URLParts, String> splitURL(URL url) {
        Map<URLParts, String> urlParts = new HashMap<>();
        
        urlParts.put(URLParts.PROTOCOL, url.getProtocol());
        urlParts.put(URLParts.USERINFO, url.getUserInfo());
        urlParts.put(URLParts.AUTHORITY, url.getAuthority());
        urlParts.put(URLParts.HOST, url.getHost());
        urlParts.put(URLParts.PATH, url.getPath());
        urlParts.put(URLParts.QUERY, url.getQuery());
        urlParts.put(URLParts.FILENAME, url.getFile());
        urlParts.put(URLParts.REF, url.getRef());
        int port = url.getPort();
        if(port!=-1) {
            urlParts.put(URLParts.PORT, String.valueOf(port));
        }
        else {
            urlParts.put(URLParts.PORT, null);
        }
        
        return urlParts;
    }
76916
public static URL url(String url, URLStreamHandler handler) {
		Assert.notNull(url, "URL must not be null");

		// 兼容Spring的ClassPath路径
		if (url.startsWith(CLASSPATH_URL_PREFIX)) {
			url = url.substring(CLASSPATH_URL_PREFIX.length());
			return ClassLoaderUtil.getClassLoader().getResource(url);
		}

		try {
			return new URL(null, url, handler);
		} catch (MalformedURLException e) {
			// 尝试文件路径
			try {
				return new File(url).toURI().toURL();
			} catch (MalformedURLException ex2) {
				throw new UtilException(e);
			}
		}
	}
972428
@Pure
	@SuppressWarnings("checkstyle:npathcomplexity")
	public static File convertURLToFile(URL url) {
		URL theUrl = url;
		if (theUrl == null) {
			return null;
		}
		if (URISchemeType.RESOURCE.isURL(theUrl)) {
			theUrl = Resources.getResource(decodeHTMLEntities(theUrl.getFile()));
			if (theUrl == null) {
				theUrl = url;
			}
		}
		URI uri;
		try {
			// this is the step that can fail, and so
			// it should be this step that should be fixed
			uri = theUrl.toURI();
		} catch (URISyntaxException e) {
			// OK if we are here, then obviously the URL did
			// not comply with RFC 2396. This can only
			// happen if we have illegal unescaped characters.
			// If we have one unescaped character, then
			// the only automated fix we can apply, is to assume
			// all characters are unescaped.
			// If we want to construct a URI from unescaped
			// characters, then we have to use the component
			// constructors:
			try {
				uri = new URI(theUrl.getProtocol(), theUrl.getUserInfo(),
						theUrl.getHost(), theUrl.getPort(),
						decodeHTMLEntities(theUrl.getPath()),
						decodeHTMLEntities(theUrl.getQuery()),
						theUrl.getRef());
			} catch (URISyntaxException e1) {
				// The URL is broken beyond automatic repair
				throw new IllegalArgumentException(Locale.getString("E1", theUrl)); //$NON-NLS-1$
			}

		}
		if (uri != null && URISchemeType.FILE.isURI(uri)) {
			final String auth = uri.getAuthority();
			String path = uri.getPath();
			if (path == null) {
				path = uri.getRawPath();
			}
			if (path == null) {
				path = uri.getSchemeSpecificPart();
			}
			if (path == null) {
				path = uri.getRawSchemeSpecificPart();
			}
			if (path != null) {
				if (auth == null || "".equals(auth)) { //$NON-NLS-1$
					// absolute filename in URI
					path = decodeHTMLEntities(path);
				} else {
					// relative filename in URI, extract it directly
					path = decodeHTMLEntities(auth + path);
				}
				if (Pattern.matches("^" + Pattern.quote(URL_PATH_SEPARATOR) //$NON-NLS-1$
						+ "[a-zA-Z][:|].*$", path)) { //$NON-NLS-1$
					path = path.substring(URL_PATH_SEPARATOR.length());
				}
				return new File(path);
			}
		}
		throw new IllegalArgumentException(Locale.getString("E2", theUrl)); //$NON-NLS-1$
	}
607964
private File downloadTempFile(final String jarURL, final LogNode log) {
        final LogNode subLog = log == null ? null : log.log(jarURL, "Downloading URL " + jarURL);
        File tempFile;
        try {
            tempFile = makeTempFile(jarURL, /* onlyUseLeafname = */ true);
            final URL url = new URL(jarURL);
            try (InputStream inputStream = url.openStream()) {
                Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
            if (subLog != null) {
                subLog.addElapsedTime();
            }
        } catch (final IOException | SecurityException e) {
            if (subLog != null) {
                subLog.log("Could not download " + jarURL, e);
            }
            return null;
        }
        if (subLog != null) {
            subLog.log("Downloaded to temporary file " + tempFile);
            subLog.log("***** Note that it is time-consuming to scan jars at http(s) addresses, "
                    + "they must be downloaded for every scan, and the same jars must also be "
                    + "separately downloaded by the ClassLoader *****");
        }
        return tempFile;
    }
759594
private static URL getPersistenceRootUrl(URL url)
    {
        String f = url.getFile();
        f = parseFilePath(f);

        URL jarUrl = url;
        try
        {
            if (AllowedProtocol.isJarProtocol(url.getProtocol()))
            {
                jarUrl = new URL(f);
                if (jarUrl.getProtocol() != null
                        && AllowedProtocol.FILE.name().equals(jarUrl.getProtocol().toUpperCase())
                        && StringUtils.contains(f, " "))
                {
                    jarUrl = new File(f).toURI().toURL();
                }
            }
            else if (AllowedProtocol.isValidProtocol(url.getProtocol()))
            {
                if (StringUtils.contains(f, " "))
                {
                    jarUrl = new File(f).toURI().toURL();
                }
                else
                {
                    jarUrl = new File(f).toURL();
                }
            }
        }
        catch (MalformedURLException mex)
        {
            log.error("Error during getPersistenceRootUrl(), Caused by: {}.", mex);
            throw new IllegalArgumentException("Invalid jar URL[] provided!" + url);
        }

        return jarUrl;
    }
1215240
public URL applyOnURL(URL url) {
        if (url == null) {
            return url;
        }
        try {
            return new URL(applyOnURL(url.toString()));
        } catch (MalformedURLException e) {
            throw new RuntimeException("Cannot applyl query string to: " + url, e);
        }
    }
17635
public static String urlToString(URL url) {
        return Checker.isNull(url) ? "" : url.toString().replaceAll("file:" + (Checker.isWindows() ? "/?" : ""), "");
    }
265560
public static ManifestVersion of(final URL url)
	{
		final ManifestVersion version = new ManifestVersion();
		if (url != null)
		{
			URLConnection urlConnection = null;
			try
			{
				urlConnection = url.openConnection();
				version.setLastModified(LocalDateTime.ofInstant(
					Instant.ofEpochMilli(urlConnection.getLastModified()), ZoneId.systemDefault()));
				version.setManifest(new Manifest(urlConnection.getInputStream()));
				version
					.setTitle(version.getManifestAttribute(Attributes.Name.IMPLEMENTATION_TITLE));
				version.setVersion(
					version.getManifestAttribute(Attributes.Name.IMPLEMENTATION_VERSION));
			}
			catch (final IOException e)
			{
				throw new RuntimeException("Error while try to load manifest file from " + url, e);
			}
		}
		return version;
	}
182491
public static File jarFile(Class<?> clazz) throws IOException {
        return jarFile(classFileUrl(clazz), clazz.getName().replace('.', '/') + ".class");
    }
116810
private void findJarFile() throws IOException {
        if (getUseCaches()) {
            synchronized (jarCache) {
                jarFile = jarCache.get(jarFileURL);
            }
            if (jarFile == null) {
                JarFile jar = openJarFile();
                synchronized (jarCache) {
                    jarFile = jarCache.get(jarFileURL);
                    if (jarFile == null) {
                        jarCache.put(jarFileURL, jar);
                        jarFile = jar;
                    } else {
                        jar.close();
                    }
                }
            }
        } else {
            jarFile = openJarFile();
        }

        if (jarFile == null) {
            throw new IOException();
        }
    }
690511
public static URL simplifyJarPath( URL url ) {
		try {
			String segments[] = url.toString().split(".jar!/");
			String path = simplifyJarPath(segments[1]);
			return new URL(segments[0]+".jar!/"+path);
		} catch (IOException e) {
			return url;
		}
	}
433609
protected boolean isRarFile(URL url)
   {
      if (url != null && url.toExternalForm().endsWith(".rar") && !url.toExternalForm().startsWith("jar"))
         return true;

      return false;
   }
49111
public static byte[] loadBytes(URL url) {
        byte[] bytes = null;
        try {
            bytes = loadBytes(url.openStream());
        } catch (IOException ex) {
            // ex.printStackTrace();
        }
        return bytes;
    }
71107
private static URL getClassPathURL(String resourceName, URL resourceURL) {
    try {
      if ("file".equals(resourceURL.getProtocol())) {
        String path = resourceURL.getFile();
        // Compute the directory container the class.
        int endIdx = path.length() - resourceName.length();
        if (endIdx > 1) {
          // If it is not the root directory, return the end index to remove the trailing '/'.
          endIdx--;
        }
        return new URL("file", "", -1, path.substring(0, endIdx));
      }
      if ("jar".equals(resourceURL.getProtocol())) {
        String path = resourceURL.getFile();
        return URI.create(path.substring(0, path.indexOf("!/"))).toURL();
      }
    } catch (MalformedURLException e) {
      throw Throwables.propagate(e);
    }
    throw new IllegalStateException("Unsupported class URL: " + resourceURL);
  }
645892
public static JarFile createJar() throws IOException, URISyntaxException {
		URL location = faspmanager2.class.getProtectionDomain().getCodeSource().getLocation();
		return new JarFile(new File(location.toURI()));
	}
1223931
public static File extractAppFromURL(URL url) throws IOException {
    String fileName = url.toExternalForm().substring(url.toExternalForm().lastIndexOf('/') + 1);

    File tmpDir = createTmpDir("iosd");
    log.fine("tmpDir: " + tmpDir.getAbsolutePath());

    File downloadedFile = new File(tmpDir, fileName);
    FileUtils.copyURLToFile(url, downloadedFile);

    if (fileName.endsWith(".ipa"))
      return downloadedFile;
    
    unzip(downloadedFile, tmpDir);
    
    for (File file: tmpDir.listFiles()) {
      if (file.getName().endsWith(".app")) {
        return file;
      }
    }
    
    throw new WebDriverException("cannot extract .app/.ipa from " + url);
  }