Search in sources :

Example 86 with JarFile

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

the class ShadowClassLoader method getJarMemberSet.

/**
	 * Return a {@link Set} of members in the Jar identified by {@code absolutePathToJar}.
	 * 
	 * @param absolutePathToJar Cache key
	 * @return a Set with the Jar member-names
	 */
private Set<String> getJarMemberSet(String absolutePathToJar) {
    /*
		 * Note:
		 * Our implementation returns a HashSet. initialCapacity and loadFactor are carefully tweaked for speed and RAM optimization purposes.
		 * 
		 * Benchmark:
		 * The HashSet implementation is about 10% slower to build (only happens once) than the ArrayList.
		 * The HashSet with shiftBits = 1 was about 33 times(!) faster than the ArrayList for retrievals.
		 */
    try {
        //  (fast, but big)  0 <= shiftBits <= 5, say  (slower & compact)
        int shiftBits = 1;
        JarFile jar = new JarFile(absolutePathToJar);
        /*
			 * Find the first power of 2 >= JarSize (as calculated in HashSet constructor)
			 */
        int jarSizePower2 = Integer.highestOneBit(jar.size());
        if (jarSizePower2 != jar.size())
            jarSizePower2 <<= 1;
        if (jarSizePower2 == 0)
            jarSizePower2 = 1;
        Set<String> jarMembers = new HashSet<String>(jarSizePower2 >> shiftBits, 1 << shiftBits);
        try {
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry jarEntry = entries.nextElement();
                if (jarEntry.isDirectory())
                    continue;
                jarMembers.add(jarEntry.getName());
            }
        } catch (Exception ignore) {
        // ignored; if the jar can't be read, treating it as if the jar contains no classes is just what we want.
        } finally {
            jar.close();
        }
        return jarMembers;
    } catch (Exception newJarFileException) {
        return Collections.emptySet();
    }
}
Also used : JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HashSet(java.util.HashSet)

Example 87 with JarFile

use of java.util.jar.JarFile in project dbeaver by serge-rider.

the class DriverClassFindJob method findDriverClasses.

private void findDriverClasses(IProgressMonitor monitor, ClassLoader findCL, File libFile) {
    try {
        JarFile currentFile = new JarFile(libFile, false);
        monitor.beginTask(libFile.getName(), currentFile.size());
        for (Enumeration<?> e = currentFile.entries(); e.hasMoreElements(); ) {
            {
                if (monitor.isCanceled()) {
                    break;
                }
                JarEntry current = (JarEntry) e.nextElement();
                String fileName = current.getName();
                if (fileName.endsWith(CLASS_FILE_EXT) && !fileName.contains("$")) {
                    //$NON-NLS-1$ //$NON-NLS-2$
                    //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                    String className = fileName.replaceAll("/", ".").replace(CLASS_FILE_EXT, "");
                    monitor.subTask(className);
                    try {
                        if (implementsInterface(currentFile, current, 0)) {
                            driverClassNames.add(className);
                        }
                    } catch (Throwable e1) {
                    // do nothing
                    }
                    monitor.worked(1);
                }
            }
        }
        monitor.done();
    } catch (IOException e) {
        log.debug(e);
    }
}
Also used : IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry)

Example 88 with JarFile

use of java.util.jar.JarFile 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 89 with JarFile

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

the class EclipseLoaderPatcherTransplants method overrideLoadResult.

public static Class overrideLoadResult(ClassLoader original, String name, boolean resolve) throws ClassNotFoundException {
    try {
        Field shadowLoaderField = original.getClass().getField("lombok$shadowLoader");
        ClassLoader shadowLoader = (ClassLoader) shadowLoaderField.get(original);
        if (shadowLoader == null) {
            synchronized ("lombok$shadowLoader$globalLock".intern()) {
                shadowLoader = (ClassLoader) shadowLoaderField.get(original);
                if (shadowLoader == null) {
                    Class shadowClassLoaderClass = (Class) original.getClass().getField("lombok$shadowLoaderClass").get(null);
                    Class classLoaderClass = Class.forName("java.lang.ClassLoader");
                    String jarLoc = (String) original.getClass().getField("lombok$location").get(null);
                    if (shadowClassLoaderClass == null) {
                        JarFile jf = new JarFile(jarLoc);
                        InputStream in = null;
                        try {
                            ZipEntry entry = jf.getEntry("lombok/launch/ShadowClassLoader.class");
                            in = jf.getInputStream(entry);
                            byte[] bytes = new byte[65536];
                            int len = 0;
                            while (true) {
                                int r = in.read(bytes, len, bytes.length - len);
                                if (r == -1)
                                    break;
                                len += r;
                                if (len == bytes.length)
                                    throw new IllegalStateException("lombok.launch.ShadowClassLoader too large.");
                            }
                            in.close();
                            {
                                Class[] paramTypes = new Class[4];
                                paramTypes[0] = "".getClass();
                                paramTypes[1] = new byte[0].getClass();
                                paramTypes[2] = Integer.TYPE;
                                paramTypes[3] = paramTypes[2];
                                Method defineClassMethod = classLoaderClass.getDeclaredMethod("defineClass", paramTypes);
                                defineClassMethod.setAccessible(true);
                                shadowClassLoaderClass = (Class) defineClassMethod.invoke(original, new Object[] { "lombok.launch.ShadowClassLoader", bytes, new Integer(0), new Integer(len) });
                                original.getClass().getField("lombok$shadowLoaderClass").set(null, shadowClassLoaderClass);
                            }
                        } finally {
                            if (in != null)
                                in.close();
                            jf.close();
                        }
                    }
                    Class[] paramTypes = new Class[5];
                    paramTypes[0] = classLoaderClass;
                    paramTypes[1] = "".getClass();
                    paramTypes[2] = paramTypes[1];
                    paramTypes[3] = Class.forName("java.util.List");
                    paramTypes[4] = paramTypes[3];
                    Constructor constructor = shadowClassLoaderClass.getDeclaredConstructor(paramTypes);
                    constructor.setAccessible(true);
                    shadowLoader = (ClassLoader) constructor.newInstance(new Object[] { original, "lombok", jarLoc, Arrays.asList(new Object[] { "lombok." }), Arrays.asList(new Object[] { "lombok.patcher.Symbols" }) });
                    shadowLoaderField.set(original, shadowLoader);
                }
            }
        }
        if (resolve) {
            Class[] paramTypes = new Class[2];
            paramTypes[0] = "".getClass();
            paramTypes[1] = Boolean.TYPE;
            Method m = shadowLoader.getClass().getDeclaredMethod("loadClass", new Class[] { String.class, boolean.class });
            m.setAccessible(true);
            return (Class) m.invoke(shadowLoader, new Object[] { name, Boolean.TRUE });
        } else {
            return shadowLoader.loadClass(name);
        }
    } catch (Exception ex) {
        Throwable t = ex;
        if (t instanceof InvocationTargetException)
            t = t.getCause();
        if (t instanceof RuntimeException)
            throw (RuntimeException) t;
        if (t instanceof Error)
            throw (Error) t;
        throw new RuntimeException(t);
    }
}
Also used : InputStream(java.io.InputStream) Constructor(java.lang.reflect.Constructor) ZipEntry(java.util.zip.ZipEntry) Method(java.lang.reflect.Method) JarFile(java.util.jar.JarFile) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Field(java.lang.reflect.Field)

Example 90 with JarFile

use of java.util.jar.JarFile 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)

Aggregations

JarFile (java.util.jar.JarFile)509 File (java.io.File)289 JarEntry (java.util.jar.JarEntry)230 IOException (java.io.IOException)212 URL (java.net.URL)92 ZipEntry (java.util.zip.ZipEntry)92 InputStream (java.io.InputStream)90 Manifest (java.util.jar.Manifest)81 ZipFile (java.util.zip.ZipFile)74 FileOutputStream (java.io.FileOutputStream)71 Test (org.junit.Test)66 ArrayList (java.util.ArrayList)54 JarURLConnection (java.net.JarURLConnection)48 Attributes (java.util.jar.Attributes)43 JarOutputStream (java.util.jar.JarOutputStream)41 MalformedURLException (java.net.MalformedURLException)31 FileInputStream (java.io.FileInputStream)30 Support_PlatformFile (tests.support.Support_PlatformFile)26 Enumeration (java.util.Enumeration)24 HashSet (java.util.HashSet)20