Java Code Examples for java.net.JarURLConnection#getJarFile()

The following examples show how to use java.net.JarURLConnection#getJarFile() . 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: DalClassScanner.java    From dal with Apache License 2.0 6 votes vote down vote up
private void findClasses(List<Class<?>> classList, String packageName, URL url, boolean recursive) throws Throwable {
        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
        JarFile jarFile = jarURLConnection.getJarFile();
        Enumeration<JarEntry> jarEntries = jarFile.entries();
//        jarCount.incrementAndGet();
//        LOGGER.info("Scanning jar: " + jarFile.getName());
        while (jarEntries.hasMoreElements()) {
            try {
                JarEntry jarEntry = jarEntries.nextElement();
                String jarEntryName = jarEntry.getName();
                String jarEntryClassName = getClassName(jarEntryName);
                if (jarEntryClassName != null) {
                    String jarEntryPackageName = getPackageName(jarEntryClassName);
                    if (jarEntryPackageName.equals(packageName) ||
                            (recursive && jarEntryPackageName.startsWith(packageName))) {
                        tryAddClass(classList, jarEntryClassName);
                    }
                }
            } catch (Throwable t) {
                LOGGER.warn(t.getMessage(), t);
            }
        }
    }
 
Example 2
Source File: ResourceReader.java    From emissary with Apache License 2.0 6 votes vote down vote up
/**
 * Find resources for the specified class from the Jar URL This finds resources at multiple levels at ones. For example
 * if you pass in emissary.util.Version.class with the ".cfg" suffix, you could get back resources that are located at
 * emissary/util/Version.cfg and emissary/util/Version/foo.cfg in the list.
 * 
 * @param c the class
 * @param url the jar url
 * @param suffix the ending suffix of desired resources
 * @return list of resources found
 */
public List<String> getJarResourcesFor(Class<?> c, URL url, String suffix) {
    List<String> results = new ArrayList<String>();
    try {
        JarURLConnection jc = (JarURLConnection) url.openConnection();
        JarFile jf = jc.getJarFile();
        String cmatch = getResourceName(c);
        for (Enumeration<JarEntry> entries = jf.entries(); entries.hasMoreElements();) {
            JarEntry entry = entries.nextElement();
            String name = entry.getName();
            if (name.startsWith(cmatch) && name.endsWith(suffix)) {
                results.add(name);
            }
        }
        logger.debug("Found {} jar resources for {}", results.size(), cmatch);
    } catch (IOException ex) {
        logger.warn("Cannot get jar url connection to {}", url, ex);
    }
    return results;
}
 
Example 3
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 4
Source File: WellKnowns.java    From libreveris with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static JarFile getJarFile ()
{
    try {
        String rn = WellKnowns.class.getName()
                .replace('.', '/')
                    + ".class";
        Enumeration<URL> en = WellKnowns.class.getClassLoader()
                .getResources(rn);

        if (en.hasMoreElements()) {
            URL url = en.nextElement();

            // url = jar:http://audiveris.kenai.com/jnlp/audiveris.jar!/omr/WellKnowns.class
            JarURLConnection urlcon = (JarURLConnection) (url.openConnection());
            JarFile jarFile = urlcon.getJarFile();

            return jarFile;
        }
    } catch (Exception ex) {
        System.out.print("Error getting jar file " + ex);
    }

    return null;
}
 
Example 5
Source File: TemplateUtil.java    From Vert.X-generator with MIT License 5 votes vote down vote up
/**
 * 将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));
			}
		}
	}

}
 
Example 6
Source File: SingleJarDownloader.java    From maple-ir with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void download() throws IOException {
	URL url = null;
	JarURLConnection connection = (JarURLConnection) (url = new URL(jarInfo.formattedURL())).openConnection();
	JarFile jarFile = connection.getJarFile();
	Enumeration<JarEntry> entries = jarFile.entries();
	contents = new LocateableJarContents<>(url);
	
	Map<String, ClassNode> map = new HashMap<>();
	
	while (entries.hasMoreElements()) {
		JarEntry entry = entries.nextElement();
		byte[] bytes = read(jarFile.getInputStream(entry));
		if (entry.getName().endsWith(".class")) {
			C cn = factory.create(bytes, entry.getName());
			if(!map.containsKey(cn.getName())) {
				contents.getClassContents().add(cn);
			} else {
				throw new IllegalStateException("duplicate: " + cn.getName());
			}
			
			//if(cn.name.equals("org/xmlpull/v1/XmlPullParser")) {
			//	System.out.println("SingleJarDownloader.download() " +entry.getName() + " " + bytes.length);
			//}
		} else {
			JarResource resource = new JarResource(entry.getName(), bytes);
			contents.getResourceContents().add(resource);
		}
	}
}
 
Example 7
Source File: BaseDirContext.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 8
Source File: ReflectUtils.java    From festival with Apache License 2.0 5 votes vote down vote up
/**
 * 根据包名获取Class
 *
 * @param packageName 包名
 * @return 返回一个Class集合,如果包名为null或者空字符串,则返回空集合
 */
public static Set<Class<?>> getClasses(String packageName) {
    if (packageName == null || "".equals(packageName)) {
        return Collections.emptySet();
    }
    //将包名改为相对路径
    String packagePath = packageName.replace(".", "/");
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Set<Class<?>> classes = new HashSet<>();
    try {
        //扫描包路径,返回资源的枚举
        Enumeration<URL> dirs = classLoader.getResources(packagePath);
        while (dirs.hasMoreElements()) {
            URL fileUrl = dirs.nextElement();
            String filePath = fileUrl.getPath();
            //判断资源类型
            if (FILE_PROTOCOL.equals(fileUrl.getProtocol())) {
                //处理文件类型的Class
                classes.addAll(getClassesByFilePath(filePath, packagePath));
            } else if (JAR_PROTOCOL.equals(fileUrl.getProtocol())) {
                //处理Jar包中的Class
                JarURLConnection jarURLConnection = (JarURLConnection) fileUrl.openConnection();
                JarFile jarFile = jarURLConnection.getJarFile();
                classes.addAll(getClassesByJar(jarFile));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return classes;
}
 
Example 9
Source File: JarIndexLocation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
InputStream getInputStream() throws IOException {
	if (this.jarFile == null) {
		JarURLConnection connection = (JarURLConnection) this.localUrl.openConnection();
		this.jarFile = connection.getJarFile();
		this.jarEntry = connection.getJarEntry();
	}
	if (this.jarFile == null || this.jarEntry == null)
		return null;
	return this.jarFile.getInputStream(this.jarEntry);
}
 
Example 10
Source File: ClassUtil0.java    From PeonyFramwork with Apache License 2.0 5 votes vote down vote up
/**
 * 第三方Jar类库的引用。<br/>
 *
 * @throws IOException
 */
static void findClassName(List<Class<?>> clazzList, String pkgName, URL url, boolean isRecursive, Class<?> superClass) throws IOException {
    JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
    JarFile jarFile = jarURLConnection.getJarFile();
    logger.debug("jarFile:" + jarFile.getName());
    Enumeration<JarEntry> jarEntries = jarFile.entries();
    while (jarEntries.hasMoreElements()) {
        JarEntry jarEntry = jarEntries.nextElement();
        String jarEntryName = jarEntry.getName(); // 类似:sun/security/internal/interfaces/TlsMasterSecret.class  
        String clazzName = jarEntryName.replace("/", ".");
        int endIndex = clazzName.lastIndexOf(".");
        String prefix = null;
        if (endIndex > 0) {
            String prefix_name = clazzName.substring(0, endIndex);
            endIndex = prefix_name.lastIndexOf(".");
            if (endIndex > 0) {
                prefix = prefix_name.substring(0, endIndex);
            }
        }
        if (prefix != null && jarEntryName.endsWith(".class")) {
            if (prefix.equals(pkgName)) {
                logger.debug("jar entryName:" + jarEntryName);
                addClassName(clazzList, clazzName, superClass);
            } else if (isRecursive && prefix.startsWith(pkgName)) {
                // 遍历子包名:子类  
                logger.debug("jar entryName:" + jarEntryName + " isRecursive:" + isRecursive);
                addClassName(clazzList, clazzName, superClass);
            }
        }
    }
}
 
Example 11
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 12
Source File: JarURLResource.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 13
Source File: JarIndexLocation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean exists() {
	try {
		if (this.jarFile == null) {
			JarURLConnection connection = (JarURLConnection) this.localUrl.openConnection();
			JarFile file = connection.getJarFile();
			if (file == null)
				return false;
			file.close();
		}
	} catch (IOException e) {
		return false;
	}
	return true;
}
 
Example 14
Source File: PackageScanner.java    From Summer with MIT License 4 votes vote down vote up
public List<Class<?>> scan(String packagename) throws IOException, ClassNotFoundException {
	if (!StringUtils.isEmpty(packagename)) {

		Enumeration<URL> urls = Thread.currentThread().getContextClassLoader()
				.getResources(packagename.replaceAll("\\.", "/"));

		List<Class<?>> classList = new ArrayList<Class<?>>();
		while (urls.hasMoreElements()) {
			URL url = urls.nextElement();

			String protocl = url.getProtocol();
			if (FILE_PROTOCL.equals(protocl)) {
				String packagePath = url.getPath().replaceAll("%20", " ");
				addClass(classList, packagePath, packagename);
			} else if (JAR_PROTOCL.equals(protocl)) {

				JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
				JarFile jarFile = jarURLConnection.getJarFile();
				Enumeration<JarEntry> jarEntrys = jarFile.entries();
				while (jarEntrys.hasMoreElements()) {

					JarEntry jarEntry = jarEntrys.nextElement();
					String jarEntryName = jarEntry.getName();
					if (jarEntryName.equals(CLASS_SUFFIX)) {
						String className = jarEntryName.substring(0, jarEntryName.indexOf(".")).replaceAll("/",
								".");
						Class<?> cls = Class.forName(className, true,
								Thread.currentThread().getContextClassLoader());

						if (checkAdd(cls)) {
							classList.add(cls);
						}
					}

				}
			}
		}

		return classList;
	}

	return null;
}
 
Example 15
Source File: DeleteTempJar.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void realMain(String args[]) throws Exception
{
    final File zf = File.createTempFile("deletetemp", ".jar");
    zf.deleteOnExit();
    try (FileOutputStream fos = new FileOutputStream(zf);
         JarOutputStream jos = new JarOutputStream(fos))
    {
        JarEntry je = new JarEntry("entry");
        jos.putNextEntry(je);
        jos.write("hello, world".getBytes("ASCII"));
    }

    HttpServer server = HttpServer.create(
            new InetSocketAddress((InetAddress) null, 0), 0);
    HttpContext context = server.createContext("/",
        new HttpHandler() {
            public void handle(HttpExchange e) {
                try (FileInputStream fis = new FileInputStream(zf)) {
                    e.sendResponseHeaders(200, zf.length());
                    OutputStream os = e.getResponseBody();
                    byte[] buf = new byte[1024];
                    int count = 0;
                    while ((count = fis.read(buf)) != -1) {
                        os.write(buf, 0, count);
                    }
                } catch (Exception ex) {
                    unexpected(ex);
                } finally {
                    e.close();
                }
            }
        });
    server.start();

    URL url = new URL("jar:http://localhost:"
                      + new Integer(server.getAddress().getPort()).toString()
                      + "/deletetemp.jar!/");
    JarURLConnection c = (JarURLConnection)url.openConnection();
    JarFile f = c.getJarFile();
    check(f.getEntry("entry") != null);
    System.out.println(f.getName());
    server.stop(0);
}
 
Example 16
Source File: FileUrlJar.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
public FileUrlJar(URL url) throws IOException {
    JarURLConnection jarConn = (JarURLConnection) url.openConnection();
    jarConn.setUseCaches(false);
    jarFile = jarConn.getJarFile();
}
 
Example 17
Source File: DeleteTempJar.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void realMain(String args[]) throws Exception
{
    final File zf = File.createTempFile("deletetemp", ".jar");
    zf.deleteOnExit();
    try (FileOutputStream fos = new FileOutputStream(zf);
         JarOutputStream jos = new JarOutputStream(fos))
    {
        JarEntry je = new JarEntry("entry");
        jos.putNextEntry(je);
        jos.write("hello, world".getBytes("ASCII"));
    }

    HttpServer server = HttpServer.create(
            new InetSocketAddress((InetAddress) null, 0), 0);
    HttpContext context = server.createContext("/",
        new HttpHandler() {
            public void handle(HttpExchange e) {
                try (FileInputStream fis = new FileInputStream(zf)) {
                    e.sendResponseHeaders(200, zf.length());
                    OutputStream os = e.getResponseBody();
                    byte[] buf = new byte[1024];
                    int count = 0;
                    while ((count = fis.read(buf)) != -1) {
                        os.write(buf, 0, count);
                    }
                } catch (Exception ex) {
                    unexpected(ex);
                } finally {
                    e.close();
                }
            }
        });
    server.start();

    URL url = new URL("jar:http://localhost:"
                      + new Integer(server.getAddress().getPort()).toString()
                      + "/deletetemp.jar!/");
    JarURLConnection c = (JarURLConnection)url.openConnection();
    JarFile f = c.getJarFile();
    check(f.getEntry("entry") != null);
    System.out.println(f.getName());
    server.stop(0);
}
 
Example 18
Source File: DeleteTempJar.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void realMain(String args[]) throws Exception
{
    final File zf = File.createTempFile("deletetemp", ".jar");
    zf.deleteOnExit();
    try (FileOutputStream fos = new FileOutputStream(zf);
         JarOutputStream jos = new JarOutputStream(fos))
    {
        JarEntry je = new JarEntry("entry");
        jos.putNextEntry(je);
        jos.write("hello, world".getBytes("ASCII"));
    }

    HttpServer server = HttpServer.create(
            new InetSocketAddress((InetAddress) null, 0), 0);
    HttpContext context = server.createContext("/",
        new HttpHandler() {
            public void handle(HttpExchange e) {
                try (FileInputStream fis = new FileInputStream(zf)) {
                    e.sendResponseHeaders(200, zf.length());
                    OutputStream os = e.getResponseBody();
                    byte[] buf = new byte[1024];
                    int count = 0;
                    while ((count = fis.read(buf)) != -1) {
                        os.write(buf, 0, count);
                    }
                } catch (Exception ex) {
                    unexpected(ex);
                } finally {
                    e.close();
                }
            }
        });
    server.start();

    URL url = new URL("jar:http://localhost:"
                      + new Integer(server.getAddress().getPort()).toString()
                      + "/deletetemp.jar!/");
    JarURLConnection c = (JarURLConnection)url.openConnection();
    JarFile f = c.getJarFile();
    check(f.getEntry("entry") != null);
    System.out.println(f.getName());
    server.stop(0);
}
 
Example 19
Source File: JarSignatureVerifier.java    From multiapps-controller with Apache License 2.0 4 votes vote down vote up
private JarFile openJarFile(URL jarFileUrl) throws IOException {
    JarURLConnection connection = (JarURLConnection) toJarUrl(jarFileUrl).openConnection();
    return connection.getJarFile();
}
 
Example 20
Source File: DeleteTempJar.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void realMain(String args[]) throws Exception
{
    final File zf = File.createTempFile("deletetemp", ".jar");
    zf.deleteOnExit();
    try (FileOutputStream fos = new FileOutputStream(zf);
         JarOutputStream jos = new JarOutputStream(fos))
    {
        JarEntry je = new JarEntry("entry");
        jos.putNextEntry(je);
        jos.write("hello, world".getBytes("ASCII"));
    }

    HttpServer server = HttpServer.create(
            new InetSocketAddress((InetAddress) null, 0), 0);
    HttpContext context = server.createContext("/",
        new HttpHandler() {
            public void handle(HttpExchange e) {
                try (FileInputStream fis = new FileInputStream(zf)) {
                    e.sendResponseHeaders(200, zf.length());
                    OutputStream os = e.getResponseBody();
                    byte[] buf = new byte[1024];
                    int count = 0;
                    while ((count = fis.read(buf)) != -1) {
                        os.write(buf, 0, count);
                    }
                } catch (Exception ex) {
                    unexpected(ex);
                } finally {
                    e.close();
                }
            }
        });
    server.start();

    URL url = new URL("jar:http://localhost:"
                      + new Integer(server.getAddress().getPort()).toString()
                      + "/deletetemp.jar!/");
    JarURLConnection c = (JarURLConnection)url.openConnection();
    JarFile f = c.getJarFile();
    check(f.getEntry("entry") != null);
    System.out.println(f.getName());
    server.stop(0);
}