Search in sources :

Example 21 with JarEntry

use of java.util.jar.JarEntry in project hackpad by dropbox.

the class JarClassLoader method getJarPath.

private static String getJarPath() {
    if (jarPath != null) {
        return jarPath;
    }
    String classname = JarClassLoader.class.getName().replace('.', '/') + ".class";
    String classpath = System.getProperty("java.class.path");
    String[] classpaths = classpath.split(System.getProperty("path.separator"));
    for (int i = 0; i < classpaths.length; i++) {
        String path = classpaths[i];
        JarFile jarFile = null;
        JarEntry jarEntry = null;
        try {
            jarFile = new JarFile(path);
            jarEntry = findJarEntry(jarFile, classname);
        } catch (IOException ioe) {
        /* ignore */
        } finally {
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException ioe) {
                /* ignore */
                }
            }
        }
        if (jarEntry != null) {
            jarPath = path;
            break;
        }
    }
    return jarPath;
}
Also used : IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry)

Example 22 with JarEntry

use of java.util.jar.JarEntry in project dropwizard by dropwizard.

the class ResourceURL method getLastModified.

/**
     * Returns the last modified time for file:// and jar:// URLs.  This is slightly tricky for a couple of reasons:
     * 1) calling getConnection on a {@link URLConnection} to a file opens an {@link InputStream} to that file that
     * must then be closed — though this is not true for {@code URLConnection}s to jar resources
     * 2) calling getLastModified on {@link JarURLConnection}s returns the last modified time of the jar file, rather
     * than the file within
     *
     * @param resourceURL the URL to return the last modified time for
     * @return the last modified time of the resource, expressed as the number of milliseconds since the epoch, or 0
     * if there was a problem
     */
public static long getLastModified(URL resourceURL) {
    final String protocol = resourceURL.getProtocol();
    switch(protocol) {
        case "jar":
            try {
                final JarURLConnection jarConnection = (JarURLConnection) resourceURL.openConnection();
                final JarEntry entry = jarConnection.getJarEntry();
                return entry.getTime();
            } catch (IOException ignored) {
                return 0;
            }
        case "file":
            URLConnection connection = null;
            try {
                connection = resourceURL.openConnection();
                return connection.getLastModified();
            } catch (IOException ignored) {
                return 0;
            } finally {
                if (connection != null) {
                    try {
                        connection.getInputStream().close();
                    } catch (IOException ignored) {
                    // do nothing.
                    }
                }
            }
        default:
            throw new IllegalArgumentException("Unsupported protocol " + resourceURL.getProtocol() + " for resource " + resourceURL);
    }
}
Also used : JarURLConnection(java.net.JarURLConnection) IOException(java.io.IOException) JarEntry(java.util.jar.JarEntry) URLConnection(java.net.URLConnection) JarURLConnection(java.net.JarURLConnection)

Example 23 with JarEntry

use of java.util.jar.JarEntry in project jetty.project by eclipse.

the class AnnotationParser method parse.

/**
     * Parse classes in the supplied classloader. 
     * Only class files in jar files will be scanned.
     * 
     * @param handlers the handlers to look for classes in 
     * @param loader the classloader for the classes
     * @param visitParents if true, visit parent classloaders too
     * @param nullInclusive if true, an empty pattern means all names match, if false, none match
     * @throws Exception if unable to parse
     */
public void parse(final Set<? extends Handler> handlers, ClassLoader loader, boolean visitParents, boolean nullInclusive) throws Exception {
    if (loader == null)
        return;
    if (!(loader instanceof URLClassLoader))
        //can't extract classes?
        return;
    final MultiException me = new MultiException();
    JarScanner scanner = new JarScanner() {

        @Override
        public void processEntry(URI jarUri, JarEntry entry) {
            try {
                parseJarEntry(handlers, Resource.newResource(jarUri), entry);
            } catch (Exception e) {
                me.add(new RuntimeException("Error parsing entry " + entry.getName() + " from jar " + jarUri, e));
            }
        }
    };
    scanner.scan(null, loader, nullInclusive, visitParents);
    me.ifExceptionThrow();
}
Also used : URLClassLoader(java.net.URLClassLoader) JarEntry(java.util.jar.JarEntry) MultiException(org.eclipse.jetty.util.MultiException) JarScanner(org.eclipse.jetty.webapp.JarScanner) URI(java.net.URI) MultiException(org.eclipse.jetty.util.MultiException) IOException(java.io.IOException)

Example 24 with JarEntry

use of java.util.jar.JarEntry in project jetty.project by eclipse.

the class JarFileResource method exists.

/* ------------------------------------------------------------ */
/**
     * Returns true if the represented resource exists.
     */
@Override
public boolean exists() {
    if (_exists)
        return true;
    if (_urlString.endsWith("!/")) {
        String file_url = _urlString.substring(4, _urlString.length() - 2);
        try {
            return newResource(file_url).exists();
        } catch (Exception e) {
            LOG.ignore(e);
            return false;
        }
    }
    boolean check = checkConnection();
    // Is this a root URL?
    if (_jarUrl != null && _path == null) {
        // Then if it exists it is a directory
        _directory = check;
        return true;
    } else {
        // Can we find a file for it?
        boolean close_jar_file = false;
        JarFile jar_file = null;
        if (check)
            // Yes
            jar_file = _jarFile;
        else {
            // No - so lets look if the root entry exists.
            try {
                JarURLConnection c = (JarURLConnection) ((new URL(_jarUrl)).openConnection());
                c.setUseCaches(getUseCaches());
                jar_file = c.getJarFile();
                close_jar_file = !getUseCaches();
            } catch (Exception e) {
                LOG.ignore(e);
            }
        }
        // Do we need to look more closely?
        if (jar_file != null && _entry == null && !_directory) {
            // OK - we have a JarFile, lets look for the entry
            JarEntry entry = jar_file.getJarEntry(_path);
            if (entry == null) {
                // the entry does not exist
                _exists = false;
            } else if (entry.isDirectory()) {
                _directory = true;
                _entry = entry;
            } else {
                // Let's confirm is a file
                JarEntry directory = jar_file.getJarEntry(_path + '/');
                if (directory != null) {
                    _directory = true;
                    _entry = directory;
                } else {
                    // OK is a file
                    _directory = false;
                    _entry = entry;
                }
            }
        }
        if (close_jar_file && jar_file != null) {
            try {
                jar_file.close();
            } catch (IOException ioe) {
                LOG.ignore(ioe);
            }
        }
    }
    _exists = (_directory || _entry != null);
    return _exists;
}
Also used : JarURLConnection(java.net.JarURLConnection) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) URL(java.net.URL)

Example 25 with JarEntry

use of java.util.jar.JarEntry in project jetty.project by eclipse.

the class JarResource method copyTo.

/* ------------------------------------------------------------ */
@Override
public void copyTo(File directory) throws IOException {
    if (!exists())
        return;
    if (LOG.isDebugEnabled())
        LOG.debug("Extract " + this + " to " + directory);
    String urlString = this.getURL().toExternalForm().trim();
    int endOfJarUrl = urlString.indexOf("!/");
    int startOfJarUrl = (endOfJarUrl >= 0 ? 4 : 0);
    if (endOfJarUrl < 0)
        throw new IOException("Not a valid jar url: " + urlString);
    URL jarFileURL = new URL(urlString.substring(startOfJarUrl, endOfJarUrl));
    String subEntryName = (endOfJarUrl + 2 < urlString.length() ? urlString.substring(endOfJarUrl + 2) : null);
    boolean subEntryIsDir = (subEntryName != null && subEntryName.endsWith("/") ? true : false);
    if (LOG.isDebugEnabled())
        LOG.debug("Extracting entry = " + subEntryName + " from jar " + jarFileURL);
    URLConnection c = jarFileURL.openConnection();
    c.setUseCaches(false);
    try (InputStream is = c.getInputStream();
        JarInputStream jin = new JarInputStream(is)) {
        JarEntry entry;
        boolean shouldExtract;
        while ((entry = jin.getNextJarEntry()) != null) {
            String entryName = entry.getName();
            if ((subEntryName != null) && (entryName.startsWith(subEntryName))) {
                // is the subentry really a dir?
                if (!subEntryIsDir && subEntryName.length() + 1 == entryName.length() && entryName.endsWith("/"))
                    subEntryIsDir = true;
                //extract it.
                if (subEntryIsDir) {
                    //if it is a subdirectory we are looking for, then we
                    //are looking to extract its contents into the target
                    //directory. Remove the name of the subdirectory so
                    //that we don't wind up creating it too.
                    entryName = entryName.substring(subEntryName.length());
                    if (!entryName.equals("")) {
                        //the entry is
                        shouldExtract = true;
                    } else
                        shouldExtract = false;
                } else
                    shouldExtract = true;
            } else if ((subEntryName != null) && (!entryName.startsWith(subEntryName))) {
                //there is a particular entry we are looking for, and this one
                //isn't it
                shouldExtract = false;
            } else {
                //we are extracting everything
                shouldExtract = true;
            }
            if (!shouldExtract) {
                if (LOG.isDebugEnabled())
                    LOG.debug("Skipping entry: " + entryName);
                continue;
            }
            String dotCheck = entryName.replace('\\', '/');
            dotCheck = URIUtil.canonicalPath(dotCheck);
            if (dotCheck == null) {
                if (LOG.isDebugEnabled())
                    LOG.debug("Invalid entry: " + entryName);
                continue;
            }
            File file = new File(directory, entryName);
            if (entry.isDirectory()) {
                // Make directory
                if (!file.exists())
                    file.mkdirs();
            } else {
                // make directory (some jars don't list dirs)
                File dir = new File(file.getParent());
                if (!dir.exists())
                    dir.mkdirs();
                // Make file
                try (OutputStream fout = new FileOutputStream(file)) {
                    IO.copy(jin, fout);
                }
                // touch the file.
                if (entry.getTime() >= 0)
                    file.setLastModified(entry.getTime());
            }
        }
        if ((subEntryName == null) || (subEntryName != null && subEntryName.equalsIgnoreCase("META-INF/MANIFEST.MF"))) {
            Manifest manifest = jin.getManifest();
            if (manifest != null) {
                File metaInf = new File(directory, "META-INF");
                metaInf.mkdir();
                File f = new File(metaInf, "MANIFEST.MF");
                try (OutputStream fout = new FileOutputStream(f)) {
                    manifest.write(fout);
                }
            }
        }
    }
}
Also used : JarInputStream(java.util.jar.JarInputStream) FilterInputStream(java.io.FilterInputStream) JarInputStream(java.util.jar.JarInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) JarEntry(java.util.jar.JarEntry) Manifest(java.util.jar.Manifest) URL(java.net.URL) URLConnection(java.net.URLConnection) JarURLConnection(java.net.JarURLConnection) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Aggregations

JarEntry (java.util.jar.JarEntry)506 JarFile (java.util.jar.JarFile)238 File (java.io.File)188 IOException (java.io.IOException)167 InputStream (java.io.InputStream)116 JarOutputStream (java.util.jar.JarOutputStream)102 FileOutputStream (java.io.FileOutputStream)96 FileInputStream (java.io.FileInputStream)79 JarInputStream (java.util.jar.JarInputStream)76 URL (java.net.URL)70 ArrayList (java.util.ArrayList)55 Manifest (java.util.jar.Manifest)50 JarURLConnection (java.net.JarURLConnection)42 Test (org.junit.Test)34 ZipFile (java.util.zip.ZipFile)30 ZipEntry (java.util.zip.ZipEntry)29 OutputStream (java.io.OutputStream)26 HashSet (java.util.HashSet)26 BufferedInputStream (java.io.BufferedInputStream)21 ByteArrayInputStream (java.io.ByteArrayInputStream)20