Search in sources :

Example 96 with JarEntry

use of java.util.jar.JarEntry in project lombok by rzwitserloot.

the class DelombokApp method loadDelombok.

public static Class<?> loadDelombok(List<String> args) throws Exception {
    //tools.jar is probably not on the classpath. We're going to try and find it, and then load the rest via a ClassLoader that includes tools.jar.
    final File toolsJar = findToolsJar();
    if (toolsJar == null) {
        String examplePath = "/path/to/tools.jar";
        if (File.separator.equals("\\"))
            examplePath = "C:\\path\\to\\tools.jar";
        StringBuilder sb = new StringBuilder();
        for (String arg : args) {
            if (sb.length() > 0)
                sb.append(' ');
            if (arg.contains(" ")) {
                sb.append('"').append(arg).append('"');
            } else {
                sb.append(arg);
            }
        }
        System.err.printf("Can't find tools.jar. Rerun delombok as: java -cp lombok.jar%1$s%2$s lombok.core.Main delombok %3$s\n", File.pathSeparator, examplePath, sb.toString());
        return null;
    }
    // The jar file is used for the lifetime of the classLoader, therefore the lifetime of delombok.
    // Since we only read from it, not closing it should not be a problem.
    @SuppressWarnings({ "resource", "all" }) final JarFile toolsJarFile = new JarFile(toolsJar);
    ClassLoader loader = new ClassLoader(DelombokApp.class.getClassLoader()) {

        private Class<?> loadStreamAsClass(String name, boolean resolve, InputStream in) throws ClassNotFoundException {
            try {
                try {
                    byte[] b = new byte[65536];
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    while (true) {
                        int r = in.read(b);
                        if (r == -1)
                            break;
                        out.write(b, 0, r);
                    }
                    in.close();
                    byte[] data = out.toByteArray();
                    Class<?> c = defineClass(name, data, 0, data.length);
                    if (resolve)
                        resolveClass(c);
                    return c;
                } finally {
                    in.close();
                }
            } catch (Exception e2) {
                throw new ClassNotFoundException(name, e2);
            }
        }

        @Override
        protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            String rawName, altName;
            {
                String binName = name.replace(".", "/");
                rawName = binName + ".class";
                altName = binName + ".SCL.lombok";
            }
            JarEntry entry = toolsJarFile.getJarEntry(rawName);
            if (entry == null) {
                if (name.startsWith("lombok.")) {
                    InputStream res = getParent().getResourceAsStream(rawName);
                    if (res == null)
                        res = getParent().getResourceAsStream(altName);
                    return loadStreamAsClass(name, resolve, res);
                }
                return super.loadClass(name, resolve);
            }
            try {
                return loadStreamAsClass(name, resolve, toolsJarFile.getInputStream(entry));
            } catch (IOException e2) {
                throw new ClassNotFoundException(name, e2);
            }
        }

        @Override
        public URL getResource(String name) {
            JarEntry entry = toolsJarFile.getJarEntry(name);
            if (entry == null)
                return super.getResource(name);
            try {
                return new URL("jar:file:" + toolsJar.getAbsolutePath() + "!" + name);
            } catch (MalformedURLException ignore) {
                return null;
            }
        }

        @Override
        public Enumeration<URL> getResources(final String name) throws IOException {
            JarEntry entry = toolsJarFile.getJarEntry(name);
            final Enumeration<URL> parent = super.getResources(name);
            if (entry == null)
                return super.getResources(name);
            return new Enumeration<URL>() {

                private boolean first = false;

                @Override
                public boolean hasMoreElements() {
                    return !first || parent.hasMoreElements();
                }

                @Override
                public URL nextElement() {
                    if (!first) {
                        first = true;
                        try {
                            return new URL("jar:file:" + toolsJar.getAbsolutePath() + "!" + name);
                        } catch (MalformedURLException ignore) {
                            return parent.nextElement();
                        }
                    }
                    return parent.nextElement();
                }
            };
        }
    };
    return loader.loadClass("lombok.delombok.Delombok");
}
Also used : MalformedURLException(java.net.MalformedURLException) Enumeration(java.util.Enumeration) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) URL(java.net.URL) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 97 with JarEntry

use of java.util.jar.JarEntry in project jadx by skylot.

the class FileUtils method addFileToJar.

public static void addFileToJar(JarOutputStream jar, File source, String entryName) throws IOException {
    BufferedInputStream in = null;
    try {
        JarEntry entry = new JarEntry(entryName);
        entry.setTime(source.lastModified());
        jar.putNextEntry(entry);
        in = new BufferedInputStream(new FileInputStream(source));
        copyStream(in, jar);
        jar.closeEntry();
    } finally {
        close(in);
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) JarEntry(java.util.jar.JarEntry) FileInputStream(java.io.FileInputStream)

Example 98 with JarEntry

use of java.util.jar.JarEntry in project jstorm by alibaba.

the class Utils method unJar.

/*
     * Unpack matching files from a jar. Entries inside the jar that do
     * not match the given pattern will be skipped.
     *
     * @param jarFile the .jar file to unpack
     * @param toDir the destination directory into which to unpack the jar
     */
public static void unJar(File jarFile, File toDir) throws IOException {
    JarFile jar = new JarFile(jarFile);
    try {
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            final JarEntry entry = entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream in = jar.getInputStream(entry);
                try {
                    File file = new File(toDir, entry.getName());
                    ensureDirectory(file.getParentFile());
                    OutputStream out = new FileOutputStream(file);
                    try {
                        copyBytes(in, out, 8192);
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
            }
        }
    } finally {
        jar.close();
    }
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) ObjectInputStream(java.io.ObjectInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) TarArchiveInputStream(org.apache.commons.compress.archivers.tar.TarArchiveInputStream) FileInputStream(java.io.FileInputStream) ClassLoaderObjectInputStream(org.apache.commons.io.input.ClassLoaderObjectInputStream) InputStream(java.io.InputStream) GZIPOutputStream(java.util.zip.GZIPOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) RandomAccessFile(java.io.RandomAccessFile) JarFile(java.util.jar.JarFile) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Example 99 with JarEntry

use of java.util.jar.JarEntry in project camel by apache.

the class FatJarPackageScanClassResolver method doLoadJarClassEntries.

protected List<String> doLoadJarClassEntries(InputStream stream, String urlPath, boolean inspectNestedJars, boolean closeStream) {
    List<String> entries = new ArrayList<String>();
    JarInputStream jarStream = null;
    try {
        jarStream = new JarInputStream(stream);
        JarEntry entry;
        while ((entry = jarStream.getNextJarEntry()) != null) {
            String name = entry.getName();
            if (name != null) {
                name = name.trim();
                if (!entry.isDirectory() && name.endsWith(".class")) {
                    entries.add(cleanupSpringbootClassName(name));
                } else if (inspectNestedJars && !entry.isDirectory() && isSpringbootNestedJar(name)) {
                    String nestedUrl = urlPath + "!/" + name;
                    log.trace("Inspecting nested jar: {}", nestedUrl);
                    List<String> nestedEntries = doLoadJarClassEntries(jarStream, nestedUrl, false, false);
                    entries.addAll(nestedEntries);
                }
            }
        }
    } catch (IOException ioe) {
        log.warn("Cannot search jar file '" + urlPath + " due to an IOException: " + ioe.getMessage(), ioe);
    } finally {
        if (closeStream) {
            // stream is left open when scanning nested jars, otherwise the fat jar stream gets closed
            IOHelper.close(jarStream, urlPath, log);
        }
    }
    return entries;
}
Also used : JarInputStream(java.util.jar.JarInputStream) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) IOException(java.io.IOException) JarEntry(java.util.jar.JarEntry)

Example 100 with JarEntry

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

the class Main method configureClassLoader.

protected void configureClassLoader() throws CommandLineParsingException {
    final List<URL> urls = new ArrayList<URL>();
    if (this.classpath != null) {
        String[] classpath;
        if (isWindows()) {
            classpath = this.classpath.split(";");
        } else {
            classpath = this.classpath.split(":");
        }
        Logger logger = LogFactory.getInstance().getLog();
        for (String classpathEntry : classpath) {
            File classPathFile = new File(classpathEntry);
            if (!classPathFile.exists()) {
                throw new CommandLineParsingException(classPathFile.getAbsolutePath() + " does not exist");
            }
            try {
                if (classpathEntry.endsWith(".war")) {
                    addWarFileClasspathEntries(classPathFile, urls);
                } else if (classpathEntry.endsWith(".ear")) {
                    JarFile earZip = new JarFile(classPathFile);
                    Enumeration<? extends JarEntry> entries = earZip.entries();
                    while (entries.hasMoreElements()) {
                        JarEntry entry = entries.nextElement();
                        if (entry.getName().toLowerCase().endsWith(".jar")) {
                            File jar = extract(earZip, entry);
                            URL newUrl = new URL("jar:" + jar.toURI().toURL() + "!/");
                            urls.add(newUrl);
                            logger.debug("Adding '" + newUrl + "' to classpath");
                            jar.deleteOnExit();
                        } else if (entry.getName().toLowerCase().endsWith("war")) {
                            File warFile = extract(earZip, entry);
                            addWarFileClasspathEntries(warFile, urls);
                        }
                    }
                } else {
                    URL newUrl = new File(classpathEntry).toURI().toURL();
                    logger.debug("Adding '" + newUrl + "' to classpath");
                    urls.add(newUrl);
                }
            } catch (Exception e) {
                throw new CommandLineParsingException(e);
            }
        }
    }
    if (includeSystemClasspath) {
        classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {

            @Override
            public URLClassLoader run() {
                return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader());
            }
        });
    } else {
        classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {

            @Override
            public URLClassLoader run() {
                return new URLClassLoader(urls.toArray(new URL[urls.size()]), null);
            }
        });
    }
    ServiceLocator.getInstance().setResourceAccessor(new ClassLoaderResourceAccessor(classLoader));
    Thread.currentThread().setContextClassLoader(classLoader);
}
Also used : Logger(liquibase.logging.Logger) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) URL(java.net.URL) ParseException(java.text.ParseException) PrivilegedAction(java.security.PrivilegedAction) URLClassLoader(java.net.URLClassLoader) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) JarFile(java.util.jar.JarFile)

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