java.net.JarURLConnection Java Examples

The following examples show how to use java.net.JarURLConnection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Gpr.java    From BigDataScript with Apache License 2.0 7 votes vote down vote up
/**
 * Return a time-stamp showing When was the JAR file
 * created OR when was a class compiled
 */
public static String compileTimeStamp(Class<?> cl) {
	try {
		String resName = cl.getName().replace('.', '/') + ".class";
		URLConnection conn = ClassLoader.getSystemResource(resName).openConnection();

		long epoch = 0;
		if (conn instanceof JarURLConnection) {
			// Is it a JAR file? Get manifest time
			epoch = ((JarURLConnection) conn).getJarFile().getEntry("META-INF/MANIFEST.MF").getTime();
		} else {
			// Regular file? Get file compile time
			epoch = conn.getLastModified();
		}

		// Format as timestamp
		Date epochDate = new Date(epoch);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		return df.format(epochDate);
	} catch (Exception e) {
		return null;
	}
}
 
Example #2
Source File: DefaultClassNameScaner.java    From sumk with Apache License 2.0 6 votes vote down vote up
private void findClassInJar(Collection<String> classNameList, URL url, String packagePath) throws IOException {
	JarFile jarFile = null;
	try {

		URLConnection conn = url.openConnection();
		if (!JarURLConnection.class.isInstance(conn)) {
			Logs.system().error("the connection of {} is {}", url.getPath(), conn.getClass().getName());
			SumkException.throwException(25345643, conn.getClass().getName() + " is not JarURLConnection");
		}
		jarFile = ((JarURLConnection) conn).getJarFile();
		Enumeration<JarEntry> jarEntryEnum = jarFile.entries();
		while (jarEntryEnum.hasMoreElements()) {
			String entityName = jarEntryEnum.nextElement().getName();
			if (entityName.startsWith("/")) {
				entityName = entityName.substring(1);
			}
			if (entityName.startsWith(packagePath)) {
				addClz(classNameList, entityName);
			}
		}
	} finally {
		if (jarFile != null) {
			jarFile.close();
		}
	}
}
 
Example #3
Source File: ExternalLibrary.java    From bytecode-viewer with GNU General Public License v3.0 6 votes vote down vote up
@Override
public JarContents<ClassNode> load() throws IOException {
    JarContents<ClassNode> contents = new JarContents<ClassNode>();

    JarURLConnection con = (JarURLConnection) getLocation().openConnection();
    JarFile jar = con.getJarFile();

    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        byte[] bytes = read(jar.getInputStream(entry));
        if (entry.getName().endsWith(".class")) {
            ClassNode cn = create(bytes);
            contents.getClassContents().add(cn);
        } else {
            JarResource resource = new JarResource(entry.getName(), bytes);
            contents.getResourceContents().add(resource);
        }
    }

    return contents;
}
 
Example #4
Source File: ClassUtil.java    From fastquery with Apache License 2.0 6 votes vote down vote up
private static String findJarClassInterface(String packageName, List<Class<?>> classes, String packageDirName, URL url) throws IOException {
	JarFile jar = ((JarURLConnection) url.openConnection()).getJarFile();
	Enumeration<JarEntry> entries = jar.entries();
	while (entries.hasMoreElements()) {
		JarEntry entry = entries.nextElement();
		String name = entry.getName();
		if (name.charAt(0) == '/') { // 如果是以/开头的
			name = name.substring(1);// 获取后面的字符串
		}
		// 如果前半部分和定义的包名相同
		if (name.startsWith(packageDirName)) {
			int lastIndex = name.lastIndexOf('/');
			if (lastIndex != -1) { // 如果以"/"结尾,就是是一个包
				// 获取包名 把"/"替换成"."
				packageName = name.substring(0, lastIndex).replace('/', '.');
			}
			// 如果是一个.class文件,而且不是目录
			if (lastIndex != -1 && name.endsWith(".class") && !entry.isDirectory()) {
				String className = packageName + '.' + name.substring(packageName.length() + 1, name.length() - 6);
				putInterface(className, classes);
			}
		}
	}
	return packageName;
}
 
Example #5
Source File: Configuration.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
private XMLStreamReader parse(URL url, boolean restricted)
		throws IOException, XMLStreamException {
	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(connection.getInputStream(), url.toString(), restricted);
}
 
Example #6
Source File: ClassPathScanner.java    From validator-web with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #7
Source File: PackageInternalsFinder.java    From arthas with Apache License 2.0 6 votes vote down vote up
private List<JavaFileObject> processJar(URL packageFolderURL) {
    List<JavaFileObject> result = new ArrayList<JavaFileObject>();
    try {
        String jarUri = packageFolderURL.toExternalForm().substring(0, packageFolderURL.toExternalForm().lastIndexOf("!/"));

        JarURLConnection jarConn = (JarURLConnection) packageFolderURL.openConnection();
        String rootEntryName = jarConn.getEntryName();
        int rootEnd = rootEntryName.length() + 1;

        Enumeration<JarEntry> entryEnum = jarConn.getJarFile().entries();
        while (entryEnum.hasMoreElements()) {
            JarEntry jarEntry = entryEnum.nextElement();
            String name = jarEntry.getName();
            if (name.startsWith(rootEntryName) && name.indexOf('/', rootEnd) == -1 && name.endsWith(CLASS_FILE_EXTENSION)) {
                URI uri = URI.create(jarUri + "!/" + name);
                String binaryName = name.replaceAll("/", ".");
                binaryName = binaryName.replaceAll(CLASS_FILE_EXTENSION + "$", "");

                result.add(new CustomJavaFileObject(binaryName, uri));
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Wasn't able to open " + packageFolderURL + " as a jar file", e);
    }
    return result;
}
 
Example #8
Source File: TomcatClasspathScanHandler.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public Vfs.Dir createDir(final URL url) throws Exception {
    URLConnection urlConnection = url.openConnection();
    Class<?> theClass = warURLConnectionClass.get();
    if (urlConnection.getClass().equals(theClass)) {
        Object wrappedJarUrlConnection = getValue(
                makeAccessible(
                        theClass.getDeclaredField("wrappedJarUrlConnection")
                ),
                urlConnection
        );
        if (wrappedJarUrlConnection instanceof JarURLConnection) {
            return new ZipDir(((JarURLConnection) wrappedJarUrlConnection).getJarFile());
        }
    }
    return null;
}
 
Example #9
Source File: PluginListenersBootStrap.java    From DataLink with Apache License 2.0 6 votes vote down vote up
private static List<Class<?>> getClassesFromJar(URL url, String basePack) throws IOException, ClassNotFoundException {
    List<Class<?>> classes = new ArrayList<>();

    JarURLConnection connection = (JarURLConnection) url.openConnection();
    if (connection != null) {
        JarFile jarFile = connection.getJarFile();
        if (jarFile != null) {
            //得到该jar文件下面的类实体
            Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
            while (jarEntryEnumeration.hasMoreElements()) {
                JarEntry entry = jarEntryEnumeration.nextElement();
                String jarEntryName = entry.getName();
                //这里我们需要过滤不是class文件和不在basePack包名下的类
                if (jarEntryName.contains(".class") && jarEntryName.replaceAll("/", ".").startsWith(basePack)) {
                    String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replace("/", ".");
                    Class cls = Class.forName(className);
                    classes.add(cls);
                }
            }
        }
    }

    return classes;
}
 
Example #10
Source File: JarURLConnectionUseCaches.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #11
Source File: Configuration.java    From flink with Apache License 2.0 6 votes vote down vote up
private XMLStreamReader parse(URL url, boolean restricted)
		throws IOException, XMLStreamException {
	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(connection.getInputStream(), url.toString(), restricted);
}
 
Example #12
Source File: PackageUtil.java    From DesignPatterns with Apache License 2.0 6 votes vote down vote up
/**
 * scan the all class file in the package
 *
 * @param pkg
 * @return
 */
public static Set<Class<?>> getClzFromPkg(String pkg) {
    Set<Class<?>> classes = new LinkedHashSet<>();

    String pkgDirName = pkg.replace('.', '/');
    try {
        Enumeration<URL> urls = PackageUtil.class.getClassLoader().getResources(pkgDirName);
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            String protocol = url.getProtocol();
            if ("file".equals(protocol)) {//
                String filePath = URLDecoder.decode(url.getFile(), Constants.ENCODING_UTF8);//
                findClassesByFile(pkg, filePath, classes);
            } else if ("jar".equals(protocol)) {//
                JarFile jar = ((JarURLConnection) url.openConnection()).getJarFile();
                findClassesByJar(pkg, jar, classes);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return classes;
}
 
Example #13
Source File: PackageUtility.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
public PackageScanner(final String... packageNames) {
    for (String packageName : packageNames) {
        try {
            final String packageDirectory = packageName.replace('.', '/');
            final Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(packageDirectory);
            while (urls.hasMoreElements()) {
                final URL url = urls.nextElement();
                if ("file".equals(url.getProtocol())) {
                    final File directory = new File(url.getPath());
                    if (!directory.isDirectory()) {
                        throw new RuntimeException("package:[" + packageName + "] is not directory");
                    }
                    clazzCollection.addAll(PackageUtility.scanClassByDirectory(packageName, directory));
                } else if ("jar".equals(url.getProtocol())) {
                    final JarFile jar = ((JarURLConnection) url.openConnection()).getJarFile();
                    clazzCollection.addAll(PackageUtility.scanClassByJar(packageName, jar));
                }
            }
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }
}
 
Example #14
Source File: ClassPathScanner.java    From validator-web with Apache License 2.0 6 votes vote down vote up
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();
            }
        }
    }
}
 
Example #15
Source File: ConfigurableClassLoader.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private InputStream getInputStream(final URL resource) throws IOException {
    final URLConnection urlc = resource.openConnection();
    final InputStream is = urlc.getInputStream();
    if (JarURLConnection.class.isInstance(urlc)) {
        final JarURLConnection juc = JarURLConnection.class.cast(urlc);
        final JarFile jar = juc.getJarFile();
        synchronized (closeables) {
            if (!closeables.containsKey(jar)) {
                closeables.put(jar, null);
            }
        }
    } else if (urlc.getClass().getName().equals("sun.net.www.protocol.file.FileURLConnection")) {
        synchronized (closeables) {
            closeables.put(is, null);
        }
    }
    return is;
}
 
Example #16
Source File: JarURLConnectionUseCaches.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #17
Source File: FileHelper.java    From mcaselector with MIT License 5 votes vote down vote up
public static Attributes getManifestAttributes() throws IOException {
	String className = FileHelper.class.getSimpleName() + ".class";
	String classPath = FileHelper.class.getResource(className).toString();
	if (!classPath.startsWith("jar")) {
		throw new IOException("application not running in jar file");
	}
	URL url = new URL(classPath);
	JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
	Manifest manifest = jarConnection.getManifest();
	return manifest.getMainAttributes();
}
 
Example #18
Source File: ClassUtil.java    From doodle with Apache License 2.0 5 votes vote down vote up
/**
 * 获取包下类集合
 *
 * @param basePackage 包的路径
 * @return 类集合
 */
public static Set<Class<?>> getPackageClass(String basePackage) {
    URL url = getClassLoader()
            .getResource(basePackage.replace(".", "/"));
    if (null == url) {
        throw new RuntimeException("无法获取项目路径文件");
    }

    try {
        if (url.getProtocol().equalsIgnoreCase(FILE_PROTOCOL)) {
            File file = new File(url.getFile());
            Path basePath = file.toPath();
            return Files.walk(basePath)
                    .filter(path -> path.toFile().getName().endsWith(".class"))
                    .map(path -> getClassByPath(path, basePath, basePackage))
                    .collect(Collectors.toSet());
        } else if (url.getProtocol().equalsIgnoreCase(JAR_PROTOCOL)) {
            // 若在 jar 包中,则解析 jar 包中的 entry
            JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
            return jarURLConnection.getJarFile()
                    .stream()
                    .filter(jarEntry -> jarEntry.getName().endsWith(".class"))
                    .map(ClassUtil::getClassByJar)
                    .collect(Collectors.toSet());
        }
        return Collections.emptySet();
    } catch (IOException e) {
        log.error("load package error", e);
        throw new RuntimeException(e);
    }
}
 
Example #19
Source File: VersionProvider.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String readVersionFromManifest() {
	try {
		final URLConnection jarConnection = getLocationOfClass().openConnection();
		if ( !(jarConnection instanceof JarURLConnection) ) {
			return null;
		}
		final JarURLConnection conn = (JarURLConnection) jarConnection;
		final Manifest mf = conn.getManifest();
		final Attributes atts = mf.getMainAttributes();
		return atts.getValue( "Implementation-Version" );
	} catch ( final IOException e ) {
		return null;
	}
}
 
Example #20
Source File: Misc.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static boolean urlExists(URL url) {
    try {
        URLConnection connection = url.openConnection();
        if ( connection instanceof JarURLConnection ) {
            JarURLConnection jarURLConnection = (JarURLConnection)connection;
            URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {
                                                                         jarURLConnection.getJarFileURL()});
            try { return urlClassLoader.findResource(jarURLConnection.getEntryName())!=null;
            }
            finally {
                if ( urlClassLoader instanceof Closeable ) {
                    ((Closeable)urlClassLoader).close();
                }
            }
        }
        InputStream is = null;
        try {
            is = url.openStream();
        }
        finally {
            if ( is!=null ) {
                is.close();
            }
        }
        return is!=null;
    }
    catch (IOException ioe) { return false;
    }
}
 
Example #21
Source File: Main.java    From javamelody with Apache License 2.0 5 votes vote down vote up
private static File whoAmIFromJnlp() throws Exception {
	final URL classFile = Main.class.getClassLoader().getResource("Main.class");
	final JarFile jf = ((JarURLConnection) classFile.openConnection()).getJarFile();
	final Field f = ZipFile.class.getDeclaredField("name");
	f.setAccessible(true);
	return new File((String) f.get(jf));
}
 
Example #22
Source File: Misc.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static boolean urlExists(URL url) {
        try {
            URLConnection connection = url.openConnection();
            if ( connection instanceof JarURLConnection ) {
                JarURLConnection jarURLConnection = (JarURLConnection)connection;
                URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {
jarURLConnection.getJarFileURL()});
                try {
                    return urlClassLoader.findResource(jarURLConnection.getEntryName())!=null;
                }
                finally {
                    if ( urlClassLoader instanceof Closeable ) {
                        ((Closeable)urlClassLoader).close();
                    }
                }
            }
            InputStream is = null;
            try {
                is = url.openStream();
                }
            finally {
                if ( is!=null ) {
                    is.close();
                }
            }
            return is!=null;
        }
        catch (IOException ioe) {
            return false;
        }
    }
 
Example #23
Source File: RoutineLoaderImpl.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public JarFile openSQLJJarFile(Session session, TableName jarName) throws IOException {
    SQLJJar sqljJar = ais(session).getSQLJJar(jarName);
    if (sqljJar == null)
        throw new NoSuchSQLJJarException(jarName);
    URL jarURL = new URL("jar:" + sqljJar.getURL() + "!/");
    return ((JarURLConnection)jarURL.openConnection()).getJarFile();
}
 
Example #24
Source File: Misc.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static boolean urlExists(URL url) {
        try {
            URLConnection connection = url.openConnection();
            if ( connection instanceof JarURLConnection ) {
                JarURLConnection jarURLConnection = (JarURLConnection)connection;
                URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {
                                                                             jarURLConnection.getJarFileURL()
});
                try { return urlClassLoader.findResource(jarURLConnection.getEntryName())!=null; }
                finally {
                    if ( urlClassLoader instanceof Closeable ) {
                        ((Closeable)urlClassLoader).close();
                    }
                }
            }
            InputStream is = null;
            try {
                is = url.openStream();
            }
            finally {
                if ( is!=null ) {
                    is.close();
                }
            }
            return is!=null;
        }
        catch (IOException ioe) { return false; }
    }
 
Example #25
Source File: PackageInternalsFinder.java    From light with Apache License 2.0 5 votes vote down vote up
private List<JavaFileObject> processJar(URL packageFolderURL) {
	List<JavaFileObject> result = new ArrayList<JavaFileObject>();
	try {
		String jarUri = packageFolderURL.toExternalForm().split("!")[0];

		JarURLConnection jarConn = (JarURLConnection) packageFolderURL
				.openConnection();
		String rootEntryName = jarConn.getEntryName();
		int rootEnd = rootEntryName.length() + 1;

		Enumeration<JarEntry> entryEnum = jarConn.getJarFile().entries();
		while (entryEnum.hasMoreElements()) {
			JarEntry jarEntry = entryEnum.nextElement();
			String name = jarEntry.getName();
			if (name.startsWith(rootEntryName)
					&& name.indexOf('/', rootEnd) == -1
					&& name.endsWith(CLASS_FILE_EXTENSION)) {
				URI uri = URI.create(jarUri + "!/" + name);
				String binaryName = name.replaceAll("/", ".");
				binaryName = binaryName.replaceAll(CLASS_FILE_EXTENSION
						+ "$", "");

				result.add(new CustomJavaFileObject(binaryName, uri));
			}
		}
	} catch (Exception e) {
		throw new RuntimeException("Wasn't able to open "
				+ packageFolderURL + " as a jar file", e);
	}
	return result;
}
 
Example #26
Source File: URLClassPath.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
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;
                }
            }
        }
    }
}
 
Example #27
Source File: MultiReleaseJarURLConnection.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private boolean readAndCompare(URL url, String match) throws Exception {
    boolean result;
    // necessary to do it this way, instead of openStream(), so we can
    // close underlying JarFile, otherwise windows can't delete the file
    URLConnection conn = url.openConnection();
    try (InputStream is = conn.getInputStream()) {
        byte[] bytes = is.readAllBytes();
        result = (new String(bytes)).contains(match);
    }
    if (conn instanceof JarURLConnection) {
        ((JarURLConnection)conn).getJarFile().close();
    }
    return result;
}
 
Example #28
Source File: ClassReader.java    From netstrap with Apache License 2.0 5 votes vote down vote up
/**
 * 从jar包读取class
 */
private static void readClassFromJar(URL url, String packageName, List<Class<?>> classes) throws IOException, ClassNotFoundException {
    JarFile jar = ((JarURLConnection) url.openConnection()).getJarFile();
    // 从此jar包 得到一个枚举类
    Enumeration<JarEntry> entries = jar.entries();
    // 同样的进行循环迭代
    while (entries.hasMoreElements()) {
        // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
        JarEntry entry = entries.nextElement();
        String name = entry.getName();
        // 如果是以/开头的
        if (name.charAt(0) == '/') {
            // 获取后面的字符串
            name = name.substring(1);
        }

        if (name.endsWith(".class") && !entry.isDirectory()) {
            name = name.replace("/", ".").substring(0, name.length() - 6);
            if (name.startsWith(packageName)) {
                Class<?> clz = Class.forName(name);
                if (!classes.contains(clz)) {
                    classes.add(clz);
                }
            }
        }
    }
}
 
Example #29
Source File: ModuleInstaller.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private String getCurrentJarPath() {
    String path = null;
    try {
        URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation();
        JarURLConnection connection = (JarURLConnection) url.openConnection();
        JarFile jarFile = connection.getJarFile();
        path = jarFile.getName();
    } catch (IOException e) {
        logger.severe(e.getMessage());
    }
    return path;
}
 
Example #30
Source File: URLClassPath.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private JarFile getJarFile(URL url) throws IOException {
    // Optimize case where url refers to a local jar file
    if (isOptimizable(url)) {
        FileURLMapper p = new FileURLMapper (url);
        if (!p.exists()) {
            throw new FileNotFoundException(p.getPath());
        }
        return checkJar(new JarFile(p.getPath()));
    }
    URLConnection uc = getBaseURL().openConnection();
    uc.setRequestProperty(USER_AGENT_JAVA_VERSION, JAVA_VERSION);
    JarFile jarFile = ((JarURLConnection)uc).getJarFile();
    return checkJar(jarFile);
}