Search in sources :

Example 26 with JarURLConnection

use of java.net.JarURLConnection in project atlasmap by atlasmap.

the class AtlasUtil method findClassesFromJar.

protected static List<Class<?>> findClassesFromJar(URL jarFileUrl) {
    List<Class<?>> classNames = new ArrayList<Class<?>>();
    JarURLConnection connection = null;
    try {
        connection = (JarURLConnection) jarFileUrl.openConnection();
    } catch (IOException e) {
        LOG.warn(String.format("Unable to load classes from jar file=%s msg=%s", jarFileUrl, e.getMessage()), e);
        return classNames;
    }
    try (ZipInputStream zip = new ZipInputStream(new FileInputStream(new File(connection.getJarFileURL().toURI())))) {
        for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
            if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
                String className = entry.getName().replace('/', '.');
                className = className.substring(0, className.length() - ".class".length());
                ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                if (classLoader == null) {
                    classLoader = AtlasUtil.class.getClassLoader();
                }
                try {
                    Class<?> clazz = Class.forName(className, false, classLoader);
                    classNames.add(clazz);
                } catch (ClassNotFoundException e) {
                    LOG.warn(String.format("Unable to load class=%s from jar file=%s msg=%s", className, jarFileUrl, e.getMessage()), e);
                }
            }
        }
    } catch (URISyntaxException | IOException e) {
        LOG.warn(String.format("Unable to load classes from jar file=%s msg=%s", jarFileUrl, e.getMessage()), e);
    }
    return classNames;
}
Also used : JarURLConnection(java.net.JarURLConnection) ZipEntry(java.util.zip.ZipEntry) ArrayList(java.util.ArrayList) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) FileInputStream(java.io.FileInputStream) ZipInputStream(java.util.zip.ZipInputStream) File(java.io.File)

Example 27 with JarURLConnection

use of java.net.JarURLConnection in project Payara by payara.

the class InstallRootBuilderUtil method buildInstallRoot.

public static void buildInstallRoot(String installRoot) throws Exception {
    ClassLoader cl = InstallRootBuilderUtil.class.getClassLoader();
    String resourceName = resourceroot + "lib/";
    URL resource = cl.getResource(resourceName);
    URLConnection urlConn = resource.openConnection();
    if (urlConn instanceof JarURLConnection) {
        JarFile jarFile = ((JarURLConnection) urlConn).getJarFile();
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String entryName = entry.getName();
            if (entryName.indexOf(resourceName) != -1 && !entryName.endsWith("/")) {
                copy(cl.getResourceAsStream(entryName), installRoot, entryName.substring(entryName.indexOf(resourceName) + resourceroot.length()));
            }
        }
        jarFile.close();
    }
}
Also used : JarURLConnection(java.net.JarURLConnection) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) URL(java.net.URL) URLConnection(java.net.URLConnection) JarURLConnection(java.net.JarURLConnection)

Example 28 with JarURLConnection

use of java.net.JarURLConnection in project geronimo-xbean by apache.

the class ResourceFinder method findResource.

private URL findResource(String resourceName, URL... search) {
    for (int i = 0; i < search.length; i++) {
        URL currentUrl = search[i];
        if (currentUrl == null) {
            continue;
        }
        try {
            String protocol = currentUrl.getProtocol();
            if (protocol.equals("jar")) {
                /*
                    * If the connection for currentUrl or resURL is
                    * used, getJarFile() will throw an exception if the
                    * entry doesn't exist.
                    */
                URL jarURL = ((JarURLConnection) currentUrl.openConnection()).getJarFileURL();
                JarFile jarFile;
                JarURLConnection juc;
                try {
                    juc = (JarURLConnection) new URL("jar", "", jarURL.toExternalForm() + "!/").openConnection();
                    jarFile = juc.getJarFile();
                } catch (IOException e) {
                    // Don't look for this jar file again
                    search[i] = null;
                    throw e;
                }
                try {
                    juc = (JarURLConnection) new URL("jar", "", jarURL.toExternalForm() + "!/").openConnection();
                    jarFile = juc.getJarFile();
                    String entryName;
                    if (currentUrl.getFile().endsWith("!/")) {
                        entryName = resourceName;
                    } else {
                        String file = currentUrl.getFile();
                        int sepIdx = file.lastIndexOf("!/");
                        if (sepIdx == -1) {
                            // Invalid URL, don't look here again
                            search[i] = null;
                            continue;
                        }
                        sepIdx += 2;
                        StringBuffer sb = new StringBuffer(file.length() - sepIdx + resourceName.length());
                        sb.append(file.substring(sepIdx));
                        sb.append(resourceName);
                        entryName = sb.toString();
                    }
                    if (entryName.equals("META-INF/") && jarFile.getEntry("META-INF/MANIFEST.MF") != null) {
                        return targetURL(currentUrl, "META-INF/MANIFEST.MF");
                    }
                    if (jarFile.getEntry(entryName) != null) {
                        return targetURL(currentUrl, resourceName);
                    }
                } finally {
                    if (!juc.getUseCaches()) {
                        try {
                            jarFile.close();
                        } catch (Exception e) {
                        }
                    }
                }
            } else if (protocol.equals("file")) {
                String baseFile = currentUrl.getFile();
                String host = currentUrl.getHost();
                int hostLength = 0;
                if (host != null) {
                    hostLength = host.length();
                }
                StringBuffer buf = new StringBuffer(2 + hostLength + baseFile.length() + resourceName.length());
                if (hostLength > 0) {
                    buf.append("//").append(host);
                }
                // baseFile should always ends with '/'
                buf.append(baseFile);
                if (!baseFile.endsWith("/")) {
                    buf.append("/");
                }
                String fixedResName = resourceName;
                // Do not create a UNC path, i.e. \\host
                while (fixedResName.startsWith("/") || fixedResName.startsWith("\\")) {
                    fixedResName = fixedResName.substring(1);
                }
                buf.append(fixedResName);
                String filename = buf.toString();
                File file = new File(filename);
                File file2 = new File(decode(filename));
                if (file.exists() || file2.exists()) {
                    return targetURL(currentUrl, fixedResName);
                }
            } else {
                URL resourceURL = targetURL(currentUrl, resourceName);
                URLConnection urlConnection = resourceURL.openConnection();
                try {
                    urlConnection.getInputStream().close();
                } catch (SecurityException e) {
                    return null;
                }
                // So check for the return code;
                if (!resourceURL.getProtocol().equals("http")) {
                    return resourceURL;
                }
                int code = ((HttpURLConnection) urlConnection).getResponseCode();
                if (code >= 200 && code < 300) {
                    return resourceURL;
                }
            }
        } catch (MalformedURLException e) {
        // Keep iterating through the URL list
        } catch (IOException e) {
        } catch (SecurityException e) {
        }
    }
    return null;
}
Also used : MalformedURLException(java.net.MalformedURLException) JarURLConnection(java.net.JarURLConnection) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarFile(java.util.jar.JarFile) File(java.io.File) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) JarURLConnection(java.net.JarURLConnection)

Example 29 with JarURLConnection

use of java.net.JarURLConnection in project checker-framework by typetools.

the class AnnotationClassLoader method loadBundledAnnotationClasses.

/**
 * Loads the set of annotation classes in the qual directory of a checker shipped with the
 * Checker Framework.
 */
private void loadBundledAnnotationClasses() {
    // if there's no resourceURL, then there's nothing we can load
    if (resourceURL == null) {
        return;
    }
    // retrieve the fully qualified class names of the annotations
    Set<String> annotationNames;
    // see whether the resource URL has a protocol of jar or file
    if (resourceURL.getProtocol().contentEquals("jar")) {
        // if the checker class file is contained within a jar, then the
        // resource URL for the qual directory will have the protocol
        // "jar". This means the whole checker is loaded as a jar file.
        JarFile jarFile = null;
        // open up that jar file and extract annotation class names
        try {
            JarURLConnection connection = (JarURLConnection) resourceURL.openConnection();
            jarFile = connection.getJarFile();
        } catch (IOException e) {
            ErrorReporter.errorAbort("AnnotationClassLoader: cannot open the Jar file " + resourceURL.getFile());
        }
        // get class names inside the jar file within the particular package
        annotationNames = getBundledAnnotationNamesFromJar(jarFile);
    } else if (resourceURL.getProtocol().contentEquals("file")) {
        // if the checker class file is found within the file system itself
        // within some directory (usually development build directories),
        // then process the package as a file directory in the file system
        // and load the annotations contained in the qual directory
        // open up the directory
        File packageDir = new File(resourceURL.getFile());
        annotationNames = getAnnotationNamesFromDirectory(packageName + DOT, resourceURL.getFile(), packageDir);
    } else {
        // We do not support a resource URL with any other protocols, so create an empty set.
        annotationNames = Collections.emptySet();
    }
    supportedBundledAnnotationClasses.addAll(loadAnnotationClasses(annotationNames));
}
Also used : JarURLConnection(java.net.JarURLConnection) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 30 with JarURLConnection

use of java.net.JarURLConnection in project cuba by cuba-platform.

the class StaticContentController method lookupNoCache.

protected LookupResult lookupNoCache(HttpServletRequest req) {
    final String path = getPath(req);
    if (isForbidden(path))
        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
    ServletContext context = req.getSession().getServletContext();
    final URL url;
    try {
        url = context.getResource(path);
    } catch (MalformedURLException e) {
        return new Error(HttpServletResponse.SC_BAD_REQUEST, "Malformed path");
    }
    if (url == null)
        return new Error(HttpServletResponse.SC_NOT_FOUND, "Not found");
    final String mimeType = getMimeType(path);
    final String realpath = context.getRealPath(path);
    if (realpath != null) {
        // Try as an ordinary file
        File f = new File(realpath);
        if (!f.isFile())
            return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
        else {
            return createLookupResult(req, f.lastModified(), mimeType, (int) f.length(), acceptsDeflate(req), url);
        }
    } else {
        try {
            // Try as a JAR Entry
            final ZipEntry ze = ((JarURLConnection) url.openConnection()).getJarEntry();
            if (ze != null) {
                if (ze.isDirectory())
                    return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
                else
                    return createLookupResult(req, ze.getTime(), mimeType, (int) ze.getSize(), acceptsDeflate(req), url);
            } else
                // Unexpected?
                return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), url);
        } catch (ClassCastException e) {
            // Unknown resource type
            return createLookupResult(req, -1, mimeType, -1, acceptsDeflate(req), url);
        } catch (IOException e) {
            return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) JarURLConnection(java.net.JarURLConnection) ZipEntry(java.util.zip.ZipEntry) ServletContext(javax.servlet.ServletContext) IOException(java.io.IOException) File(java.io.File) URL(java.net.URL)

Aggregations

JarURLConnection (java.net.JarURLConnection)222 URL (java.net.URL)160 JarFile (java.util.jar.JarFile)129 IOException (java.io.IOException)120 JarEntry (java.util.jar.JarEntry)105 File (java.io.File)92 URLConnection (java.net.URLConnection)89 ArrayList (java.util.ArrayList)32 InputStream (java.io.InputStream)27 MalformedURLException (java.net.MalformedURLException)25 URISyntaxException (java.net.URISyntaxException)21 Enumeration (java.util.Enumeration)17 Manifest (java.util.jar.Manifest)16 FileInputStream (java.io.FileInputStream)12 CodeSource (java.security.CodeSource)12 LinkedHashSet (java.util.LinkedHashSet)11 URI (java.net.URI)10 Attributes (java.util.jar.Attributes)10 ZipEntry (java.util.zip.ZipEntry)9 FileNotFoundException (java.io.FileNotFoundException)8