public void testAddURLMethod() throws Exception { File jar = new File(getWorkDir(), "default-package-resource.jar"); TestFileUtils.writeZipFile(jar, "META-INF/MANIFEST.MF:Manifest-Version: 1.0\nfoo: bar\n\n", "package/re source++.txt:content"); JarClassLoader jcl = new JarClassLoader(Collections.<File>emptyList(), new ProxyClassLoader[0]); jcl.addURL(Utilities.toURI(jar).toURL()); URL url = jcl.getResource("package/re source++.txt"); assertTrue(url.toString(), url.toString().endsWith("default-package-resource.jar!/package/re%20source++.txt")); URLConnection conn = url.openConnection(); assertEquals(7, conn.getContentLength()); assertTrue(conn instanceof JarURLConnection); JarURLConnection jconn = (JarURLConnection) conn; assertEquals("package/re source++.txt", jconn.getEntryName()); assertEquals(Utilities.toURI(jar).toURL(), jconn.getJarFileURL()); assertEquals("bar", jconn.getMainAttributes().getValue("foo")); assertEquals(jar.getAbsolutePath(), jconn.getJarFile().getName()); }
private void implTestIfReachable(FileObject fo) throws Exception { URL urlFromMapper = URLMapper.findURL(fo, getURLType()); if (isNullURLExpected(urlFromMapper, fo)) return; assertNotNull(urlFromMapper); URLConnection fc = urlFromMapper.openConnection(); if (fc instanceof JarURLConnection && fo.isFolder()) return; InputStream ic = fc.getInputStream(); try { assertNotNull(ic); } finally { if (ic != null) ic.close(); } }
private Document parse(DocumentBuilder builder, URL url) throws IOException, SAXException { if (!quietmode) { if (LOG.isDebugEnabled()) { LOG.debug("parsing URL " + url); } } if (url == null) { return null; } URLConnection connection = url.openConnection(); if (connection instanceof JarURLConnection) { // Disable caching for JarURLConnection to avoid sharing JarFile // with other users. connection.setUseCaches(false); } return parse(builder, connection.getInputStream(), url.toString()); }
/** * 将jar里面的文件复制到模板文件夹 * * @param jarConn * @return * @throws IOException */ public static void jarCreateTemplate(JarURLConnection jarConn) throws IOException { try (JarFile jarFile = jarConn.getJarFile()) { Enumeration<JarEntry> entrys = jarFile.entries(); while (entrys.hasMoreElements()) { JarEntry entry = entrys.nextElement(); if (entry.getName().startsWith(jarConn.getEntryName()) && !entry.getName().endsWith("/")) { String fileName = entry.getName().replace(TEMPLATE_DIR + "/", ""); InputStream inpt = Thread.currentThread().getContextClassLoader() .getResourceAsStream(entry.getName()); Files.copy(inpt, Paths.get(TEMPLATE_DIR, fileName)); } } } }
/** * Private helper method. * * @param connection * the connection to the jar * @param pckgname * the package name to search for * @param classes * the current ArrayList of all classes. This method will simply * add new classes. * @throws ClassNotFoundException * if a file isn't loaded but still is in the jar file * @throws IOException * if it can't correctly read from the jar file. */ private static void checkJarFile(JarURLConnection connection, String pckgname, ArrayList<Class<?>> classes) throws ClassNotFoundException, IOException { final JarFile jarFile = connection.getJarFile(); final Enumeration<JarEntry> entries = jarFile.entries(); String name; for (JarEntry jarEntry = null; entries.hasMoreElements() && ((jarEntry = entries.nextElement()) != null);) { name = jarEntry.getName(); if (name.contains(".class")) { name = name.substring(0, name.length() - 6).replace('/', '.'); if (name.contains(pckgname)) { classes.add(Class.forName(name)); } } } }
private List<String> getClassesNamesInPackage(final URL url, String packageName) { final List<String> classes = new ArrayList<String>(); packageName = packageName.replaceAll("\\.", "/"); try { JarURLConnection juc = (JarURLConnection) url.openConnection(); JarFile jf = juc.getJarFile(); final Enumeration<JarEntry> entries = jf.entries(); while (entries.hasMoreElements()) { final JarEntry je = entries.nextElement(); if ((je.getName().startsWith(packageName)) && (je.getName().endsWith(".class"))) { classes.add(je.getName().replaceAll("/", "\\.") .replaceAll("\\.class", "")); } } jf.close(); jf = null; juc = null; System.gc(); } catch (final Exception e) { e.printStackTrace(); } return classes; }
private void testJarConnectionOn(Resource jar) throws Exception { String toString = jar.getURL().toExternalForm(); // force JarURLConnection String urlString = "jar:" + toString + "!/"; URL newURL = new URL(urlString); System.out.println(newURL); System.out.println(newURL.toExternalForm()); URLConnection con = newURL.openConnection(); System.out.println(con); System.out.println(con instanceof JarURLConnection); JarURLConnection jarCon = (JarURLConnection) con; JarFile jarFile = jarCon.getJarFile(); System.out.println(jarFile.getName()); Enumeration enm = jarFile.entries(); while (enm.hasMoreElements()) System.out.println(enm.nextElement()); }
private boolean isPluginJar(IFile file) { if( "jar".equals(file.getFileExtension()) ) { URI jarURI = URIUtil.toJarURI(file.getLocationURI(), JPFProject.MANIFEST_PATH); try { JarEntry jarFile = ((JarURLConnection) jarURI.toURL().openConnection()).getJarEntry(); return jarFile != null; } catch( IOException e ) { // Bad zip } } return false; }
private JarFile getJarFile(URL url) throws IOException { // Optimize case where url refers to a local jar file if (isOptimizable(url)) { //HACK //FileURLMapper p = new FileURLMapper (url); File p = new File(url.getPath()); if (!p.exists()) { throw new FileNotFoundException(p.getPath()); } return new JarFile (p.getPath()); } URLConnection uc = getBaseURL().openConnection(); uc.setRequestProperty(USER_AGENT_JAVA_VERSION, JAVA_VERSION); return ((JarURLConnection)uc).getJarFile(); }
/** * Copies resources to target folder. * * @param resourceUrl * @param targetPath * @return */ static void copyResources(URL resourceUrl, File targetPath) throws IOException { if (resourceUrl == null) { return; } URLConnection urlConnection = resourceUrl.openConnection(); /** * Copy resources either from inside jar or from project folder. */ if (urlConnection instanceof JarURLConnection) { copyJarResourceToPath((JarURLConnection) urlConnection, targetPath); } else { File file = new File(resourceUrl.getPath()); if (file.isDirectory()) { FileUtils.copyDirectory(file, targetPath); } else { FileUtils.copyFile(file, targetPath); } } }
private void checkJarFile(final ClassLoader classLoader, final URL url, final String pckgname) throws IOException { final JarURLConnection conn = (JarURLConnection) url.openConnection(); final JarFile jarFile = conn.getJarFile(); final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry jarEntry = entries.nextElement(); String name = jarEntry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6).replace('/', '.'); if (name.startsWith(pckgname)) { addClass(classLoader, name); } } } }
private static String getVersion() { try { String path = VDMJC.class.getName().replaceAll("\\.", "/"); URL url = VDMJC.class.getResource("/" + path + ".class"); JarURLConnection conn = (JarURLConnection)url.openConnection(); JarFile jar = conn.getJarFile(); Manifest mf = jar.getManifest(); String version = (String)mf.getMainAttributes().get(Attributes.Name.IMPLEMENTATION_VERSION); return version; } catch (Exception e) { return null; } }
private static String getVersion() { try { String path = VDMJ.class.getName().replaceAll("\\.", "/"); URL url = VDMJ.class.getResource("/" + path + ".class"); JarURLConnection conn = (JarURLConnection)url.openConnection(); JarFile jar = conn.getJarFile(); Manifest mf = jar.getManifest(); String version = (String)mf.getMainAttributes().get(Attributes.Name.IMPLEMENTATION_VERSION); return version; } catch (Exception e) { return null; } }
private static List<Class<?>> loadClassFromJarFile(URL url) { List<Class<?>> list = new LinkedList<>(); try { JarURLConnection connection = (JarURLConnection) url.openConnection(); JarFile jarFile = connection.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { String entryName = jarEntries.nextElement().getName(); if (entryName.endsWith(".class")) { list.add(loadClass(entryName.substring(0, entryName.length() - 6).replace("/", "."))); } } } catch (IOException e) { e.printStackTrace(); } return list; }
/** * {@inheritDoc} * * @see jp.co.future.uroborosql.store.SqlLoader#load() */ @Override public ConcurrentHashMap<String, String> load() { ConcurrentHashMap<String, String> loadedSqlMap = new ConcurrentHashMap<>(); try { Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(loadPath); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); File rootDir = new File(URLDecoder.decode(resource.getFile(), StandardCharsets.UTF_8.toString())); if (!rootDir.exists() || !rootDir.isDirectory()) { if ("jar".equalsIgnoreCase(resource.getProtocol())) { putAllIfAbsent(loadedSqlMap, load((JarURLConnection) resource.openConnection(), loadPath)); continue; } LOG.warn("Ignore because not directory.[{}]", rootDir.getAbsolutePath()); continue; } LOG.debug("Start loading SQL template.[{}]", rootDir.getAbsolutePath()); putAllIfAbsent(loadedSqlMap, load(new StringBuilder(), rootDir)); } } catch (IOException e) { throw new UroborosqlRuntimeException("Failed to load SQL template.", e); } if (loadedSqlMap.isEmpty()) { LOG.warn("SQL template could not be found."); LOG.warn("Returns an empty SQL cache."); } return loadedSqlMap; }
/** * Jar ファイル内の指定のフォルダパス以下にある .sqlファイルを読み込み SQL識別子をキーとしたSQL文のMapを返します * * @param jarUrlConnection Jarファイル内のURLコレクション * @param loadPath ロードパス * @return SQL識別子をキーとしたSQL文のMap */ private ConcurrentHashMap<String, String> load(final JarURLConnection jarUrlConnection, final String loadPath) throws IOException { LOG.debug("Loading the following SQL template.[{}]", jarUrlConnection); ConcurrentHashMap<String, String> sqlMap = new ConcurrentHashMap<>(); JarFile jarFile = jarUrlConnection.getJarFile(); Enumeration<JarEntry> jarEnum = jarFile.entries(); while (jarEnum.hasMoreElements()) { JarEntry jarEntry = jarEnum.nextElement(); String fileName = jarEntry.getName(); if (fileName.startsWith(loadPath) && fileName.toLowerCase().endsWith(fileExtension)) { String sql = trimSlash(read(new BufferedReader(new InputStreamReader(jarFile.getInputStream(jarEntry))))); fileName = fileName.substring(loadPath.length() + 1, fileName.length() - 4); sqlMap.put(fileName, sql); LOG.trace("SQL template loaded.[{}]", fileName); LOG.trace("Add SQL template. [{}],[{}]", fileName, sql); } } return sqlMap; }
public static void main( String[] args ) throws IOException { JarOutputStream out = new JarOutputStream( new FileOutputStream("usecache.jar")); out.putNextEntry(new JarEntry("test.txt")); out.write("Test txt file".getBytes()); out.closeEntry(); out.close(); URL url = new URL("jar:" + new File(".").toURI().toString() + "/usecache.jar!/test.txt"); JarURLConnection c1 = (JarURLConnection)url.openConnection(); c1.setDefaultUseCaches( false ); c1.setUseCaches( true ); c1.connect(); JarURLConnection c2 = (JarURLConnection)url.openConnection(); c2.setDefaultUseCaches( false ); c2.setUseCaches( true ); c2.connect(); c1.getInputStream().close(); c2.getInputStream().read(); c2.getInputStream().close(); }
public Set<Class<?>> findCandidateClasses(String basePackage) { Set<Class<?>> candidates = new LinkedHashSet<Class<?>>(); try { String packageSearchPath = basePackage.replace('.', '/'); ClassLoader classLoader = this.classLoader; if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } Enumeration<URL> resources = classLoader.getResources(packageSearchPath); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); if (logger.isTraceEnabled()) { logger.trace("Scanning " + resource); } if ("file".equals(resource.getProtocol())) { findClasses(candidates, classLoader, basePackage, resource.getFile()); } else if ("jar".equals(resource.getProtocol())) { findClasses(candidates, classLoader, packageSearchPath, (JarURLConnection) resource.openConnection()); } } } catch (IOException e) { throw new RuntimeException("I/O failure during classpath scanning", e); } return candidates; }
protected void findClasses(Set<Class<?>> classes, ClassLoader classLoader, String packageName, JarURLConnection connection) throws IOException { JarFile jarFile = connection.getJarFile(); if (jarFile == null) { return; } Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.endsWith(CLASS_SUFFIX) && name.startsWith(packageName)) { String className = name.replace('/', '.').replace(CLASS_SUFFIX, ""); try { Class<?> c = ClassUtils.forName(className, classLoader); classes.add(c); } catch (ClassNotFoundException e) { // ignore e.printStackTrace(); } } } }
private Reader getInputStream(URI url) throws IOException { final URLConnection urlConnection = url.toURL().openConnection(); urlConnection.setRequestProperty("User-Agent", getUserAgentString()); // Without this, the URLConnection will keep the backing Jar file open indefinitely // This will have a performance impact for Jar-backed `UriTextResource` instances if (urlConnection instanceof JarURLConnection) { urlConnection.setUseCaches(false); } urlConnection.connect(); String charset = extractCharacterEncoding(urlConnection.getContentType(), "utf-8"); return new InputStreamReader(urlConnection.getInputStream(), charset); }
/** * Returns path for the shipped code from the provided location. If location is plain file returns its absolute path * as string. If location is inside jar file, unpacks desired resource to the temporal location and returns path to * that location. * * @param rootName * name of shipped root to be located * @return the path pointing to the shipped code */ protected static String getShippedRuntimeCodePath(String rootName) { try { URL resourceUrl = getResource(rootName); final URLConnection connection = resourceUrl.openConnection(); if (connection instanceof JarURLConnection) { return recursivelyCopyContent((JarURLConnection) connection, rootName); } return new File(resourceUrl.toURI()).getCanonicalFile().getAbsolutePath().replace("\\", "\\\\"); } catch (final Exception e) { throw new RuntimeException("Error while getting shipped code path.", e); } }
/** * Unpacks desired folder structure from the JAR file into temporal location and returns that location absolute path * as string. * * @param connection * connection to the JAR file * @param rootName * name of the folder to be unpacked * @return absolute path to the temporarily unpacked folder * @throws IOException * for IO operations */ protected static String recursivelyCopyContent(JarURLConnection connection, String rootName) throws IOException { final File tempFolder = getTempFolder(); tempFolder.deleteOnExit(); final File rootFolder = new File(tempFolder, rootName); if (rootFolder.exists()) { FileDeleter.delete(rootFolder.toPath()); } checkState(rootFolder.mkdir(), "Error while creating folder for Node.js environment. " + rootFolder); checkState(rootFolder.isDirectory(), "Expected directory but got a file: " + rootFolder); rootFolder.deleteOnExit(); try (final JarFile jarFile = connection.getJarFile()) { for (final Enumeration<JarEntry> em = jarFile.entries(); em.hasMoreElements(); /**/) { final JarEntry entry = em.nextElement(); // Do not process anything which is not under desired root if (!entry.getName().startsWith(rootName)) { continue; } final String fileName = entry.getName();// .substring(connection.getEntryName().length()); final File newResource = new File(tempFolder, fileName); if (entry.isDirectory()) { if (!newResource.exists()) { checkState(newResource.mkdir(), "Error while creating new folder at: " + newResource); } } else { checkState(newResource.createNewFile(), "Error while creating new file at: " + newResource); try (final InputStream is = jarFile.getInputStream(entry)) { com.google.common.io.Files.copy(() -> is, newResource); } } newResource.deleteOnExit(); } } return rootFolder.getCanonicalFile().getAbsolutePath().replace("\\", "\\\\"); }
public void testJarURLConnection() throws Exception { File jar = new File(getWorkDir(), "default-package-resource.jar"); TestFileUtils.writeZipFile(jar, "META-INF/MANIFEST.MF:Manifest-Version: 1.0\nfoo: bar\n\n", "package/re source++.txt:content"); JarClassLoader jcl = new JarClassLoader(Collections.singletonList(jar), new ProxyClassLoader[0]); URL url = jcl.getResource("package/re source++.txt"); assertTrue(url.toString(), url.toString().endsWith("default-package-resource.jar!/package/re%20source++.txt")); URLConnection conn = url.openConnection(); assertEquals(7, conn.getContentLength()); assertTrue(conn instanceof JarURLConnection); JarURLConnection jconn = (JarURLConnection) conn; assertEquals("package/re source++.txt", jconn.getEntryName()); assertEquals(Utilities.toURI(jar).toURL(), jconn.getJarFileURL()); assertEquals("bar", jconn.getMainAttributes().getValue("foo")); assertEquals(jar.getAbsolutePath(), jconn.getJarFile().getName()); }
/** * @param packNames 要扫描的包 * @return Set */ public static Set<Class<?>> findFileClass(String... packNames) { Set<Class<?>> clazzs = new LinkedHashSet<Class<?>>(); for (String packName : packNames) { String packageDirName = packName.replace('.', '/'); Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); while (dirs.hasMoreElements()) { URL url = dirs.nextElement(); String protocol = url.getProtocol(); if ("file".equals(protocol)) { //扫描file包中的类 String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); getFileClass(packName, filePath, clazzs); } else if ("jar".equals(protocol)) { //扫描jar包中的类 JarFile jarFile = ((JarURLConnection) url.openConnection()).getJarFile(); getJarClass(jarFile, packageDirName, clazzs); } } } catch (Exception e) { e.getStackTrace(); } } return clazzs; }
@Override public void scan(JarURLConnection jarConn) throws IOException { URL url = jarConn.getURL(); URL resourceURL = jarConn.getJarFileURL(); Jar jar = null; InputStream is = null; WebXml fragment = new WebXml(); try { jar = JarFactory.newInstance(url); if (parseRequired || context.getXmlValidation()) { is = jar.getInputStream(FRAGMENT_LOCATION); } if (is == null) { // If there is no web-fragment.xml to process there is no // impact on distributable fragment.setDistributable(true); } else { InputSource source = new InputSource( "jar:" + resourceURL.toString() + "!/" + FRAGMENT_LOCATION); source.setByteStream(is); parseWebXml(source, fragment, true); } } finally { if (jar != null) { jar.close(); } fragment.setURL(url); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragment.setJarName(extractJarFileName(url)); fragments.put(fragment.getName(), fragment); } }
/** * Add a resources JAR. The contents of /META-INF/resources/ will be used if * a requested resource can not be found in the main context. */ public void addResourcesJar(URL url) { try { JarURLConnection conn = (JarURLConnection) url.openConnection(); JarFile jarFile = conn.getJarFile(); ZipEntry entry = jarFile.getEntry("/"); WARDirContext warDirContext = new WARDirContext(jarFile, new WARDirContext.Entry("/", entry)); warDirContext.loadEntries(); altDirContexts.add(warDirContext); } catch (IOException ioe) { log.warn(sm.getString("resources.addResourcesJarFail", url), ioe); } }
private NonClosingJarInputStream createJarInputStream() throws IOException { JarURLConnection jarConn = (JarURLConnection) url.openConnection(); URL resourceURL = jarConn.getJarFileURL(); URLConnection resourceConn = resourceURL.openConnection(); resourceConn.setUseCaches(false); return new NonClosingJarInputStream(resourceConn.getInputStream()); }
@Override public JarFile getJarFile() throws IOException { URL jarFileUrl = new URL("jar:" + jarUrl + "!/"); JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection(); conn.setUseCaches(false); conn.connect(); return conn.getJarFile(); }
public static boolean copyJarResourcesRecursively( final File destDir, final JarURLConnection jarConnection ) throws IOException { final JarFile jarFile = jarConnection.getJarFile(); for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements(); ) { final JarEntry entry = e.nextElement(); if (entry.getName().startsWith(jarConnection.getEntryName())) { final String filename = StringUtils.removeStart( entry.getName(), // jarConnection.getEntryName()); final File f = new File(destDir, filename); if (!entry.isDirectory()) { final InputStream entryInputStream = jarFile.getInputStream(entry); if (!FileUtils.copyStream(entryInputStream, f)) { return false; } entryInputStream.close(); } else { if (!FileUtils.ensureDirectoryExists(f)) { throw new IOException("Could not create directory: " + f.getAbsolutePath()); } } } } return true; }
public static boolean copyResourcesRecursively(final URL originUrl, final File destination) { try { final URLConnection urlConnection = originUrl.openConnection(); if (urlConnection instanceof JarURLConnection) { return FileUtils.copyJarResourcesRecursively(destination, (JarURLConnection) urlConnection); } else { return FileUtils.copyFilesRecusively(new File(originUrl.getPath()), destination); } } catch (final IOException e) { e.printStackTrace(); } return false; }
private String getJarVersion(final String jarUrl) { String version = null; try { final URL url = new URL("jar:" + jarUrl + "!/"); final JarURLConnection juc = (JarURLConnection) url .openConnection(); final JarFile jf = juc.getJarFile(); final Attributes attrs = jf.getManifest().getMainAttributes(); version = attrs.getValue("Manifest-Version"); } catch (final IOException e) { e.printStackTrace(); } return version; }
private Document parse(DocumentBuilder builder, URL url) throws IOException, SAXException { LOG.debug("parsing URL " + url); if (url == null) { return null; } URLConnection connection = url.openConnection(); if (connection instanceof JarURLConnection) { // Disable caching for JarURLConnection to avoid sharing JarFile // with other users. connection.setUseCaches(false); } return parse(builder, connection.getInputStream(), url.toString()); }
@Override public TaggedData connectTagged(URL url) throws Exception { URLConnection connection = url.openConnection(); if (connection instanceof JarURLConnection) { connection.setUseCaches(false); } return new TaggedData(connection, connection.getInputStream()); }
private void scanJars() throws Exception { ClassLoader webappLoader = Thread.currentThread().getContextClassLoader(); ClassLoader loader = webappLoader; while (loader != null) { if (loader instanceof URLClassLoader) { URL[] urls = ((URLClassLoader) loader).getURLs(); for (int i=0; i<urls.length; i++) { URLConnection conn = urls[i].openConnection(); if (conn instanceof JarURLConnection) { if (needScanJar(loader, webappLoader, ((JarURLConnection) conn).getJarFile().getName())) { scanJar((JarURLConnection) conn, true); } } else { String urlStr = urls[i].toString(); if (urlStr.startsWith(FILE_PROTOCOL) && urlStr.endsWith(JAR_FILE_SUFFIX) && needScanJar(loader, webappLoader, urlStr)) { URL jarURL = new URL("jar:" + urlStr + "!/"); scanJar((JarURLConnection) jarURL.openConnection(), true); } } } } loader = loader.getParent(); } }
/** * @see <a * href="http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html"http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html</a> * @see <a href= * "http://stackoverflow.com/questions/8014099/how-do-i-convert-a-jarfile-uri-to-the-path-of-jar-file">http://stackoverflow.com/questions/8014099/how-do-i-convert-a-jarfile-uri-to-the-path-of-jar-file</a> * @param clazz * @return * @throws URISyntaxException * @throws IOException */ private Optional<Artifact> resolveByResource(Class clazz) throws URISyntaxException, IOException { URL url = this.classLoader.getResource(clazz.getName().replaceAll("\\.", "/") + ".class"); if (url == null) { return Optional.empty(); } URI uri = url.toURI(); this.fileSystemsUp.add(FileSystemSynchronizer.INSTANCE.up(uri)); if (uri.getScheme().equals("jar")) { JarURLConnection connection = (JarURLConnection) uri.toURL().openConnection(); uri = connection.getJarFileURL().toURI(); } return this.find(Paths.get(uri).toAbsolutePath()); }
static void check(URL url) throws IOException { SecurityManager security = System.getSecurityManager(); if (security != null) { URLConnection urlConnection = url.openConnection(); Permission perm = urlConnection.getPermission(); if (perm != null) { try { security.checkPermission(perm); } catch (SecurityException se) { // fallback to checkRead/checkConnect for pre 1.2 // security managers if ((perm instanceof java.io.FilePermission) && perm.getActions().indexOf("read") != -1) { security.checkRead(perm.getName()); } else if ((perm instanceof java.net.SocketPermission) && perm.getActions().indexOf("connect") != -1) { URL locUrl = url; if (urlConnection instanceof JarURLConnection) { locUrl = ((JarURLConnection)urlConnection).getJarFileURL(); } security.checkConnect(locUrl.getHost(), locUrl.getPort()); } else { throw se; } } } } }
/** * 获取指定包下所有类 * * @param packageName * @return */ public static ArrayList<Class<?>> getClasses(String packageName) { ArrayList<Class<?>> classes = new ArrayList<>(); try { Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/")); while (urls.hasMoreElements()) { URL url = urls.nextElement(); if (url != null) { String protocol = url.getProtocol(); if (protocol.equals("file")) { String packagePath = url.getPath().replaceAll("%20", " "); addClass(classes, packagePath, packageName); } else if (protocol.equals("jar")) { JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection(); if (jarURLConnection != null) { JarFile jarFile = jarURLConnection.getJarFile(); if (jarFile != null) { Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String jarEntryName = jarEntry.getName(); if (jarEntryName.equals(".class")) { String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replaceAll("/", "."); doAddClass(classes, className); } } } } } } } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } return classes; }