Example usage for java.util.jar JarFile getInputStream

List of usage examples for java.util.jar JarFile getInputStream

Introduction

In this page you can find the example usage for java.util.jar JarFile getInputStream.

Prototype

public synchronized InputStream getInputStream(ZipEntry ze) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:org.commonjava.web.test.fixture.JarKnockouts.java

public static File rewriteJar(final File source, final File targetDir, final Set<JarKnockouts> jarKnockouts)
        throws IOException {
    final JarKnockouts allKnockouts = new JarKnockouts();
    for (final JarKnockouts jk : jarKnockouts) {
        allKnockouts.knockoutPaths(jk.getKnockedOutPaths());
    }/*ww w .j  a v a 2s. c om*/

    targetDir.mkdirs();
    final File target = new File(targetDir, source.getName());

    JarFile in = null;
    JarOutputStream out = null;
    try {
        in = new JarFile(source);

        final BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(target));
        out = new JarOutputStream(fos, in.getManifest());

        final Enumeration<JarEntry> entries = in.entries();
        while (entries.hasMoreElements()) {
            final JarEntry entry = entries.nextElement();
            if (!allKnockouts.knockout(entry.getName())) {
                final InputStream stream = in.getInputStream(entry);
                out.putNextEntry(entry);
                copy(stream, out);
                out.closeEntry();
            }
        }
    } finally {
        closeQuietly(out);
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
            }
        }
    }

    return target;
}

From source file:org.lilyproject.lilyservertestfw.ConfUtil.java

public static void copyFromJar(File confDir, String confResourcePath, JarURLConnection jarConnection)
        throws IOException {
    JarFile jarFile = jarConnection.getJarFile();
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (entry.getName().startsWith(confResourcePath)) {
            String fileName = StringUtils.removeStart(entry.getName(), confResourcePath);
            if (entry.isDirectory()) {
                File subDir = new File(confDir, fileName);
                subDir.mkdirs();// ww w .  jav a 2s  . c o  m
            } else {
                InputStream entryInputStream = null;
                try {
                    entryInputStream = jarFile.getInputStream(entry);
                    FileUtils.copyInputStreamToFile(entryInputStream, new File(confDir, fileName));
                } finally {
                    if (entryInputStream != null) {
                        entryInputStream.close();
                    }
                }
            }
        }
    }
}

From source file:com.arcusys.liferay.vaadinplugin.util.ControlPanelPortletUtil.java

/**
 * Extracts the jarEntry from the jarFile to the target directory.
 *
 * @param jarFile//from www .  j  a  va2s  .c om
 * @param jarEntry
 * @param targetDir
 * @return true if extraction was successful, false otherwise
 */
public static boolean extractJarEntry(JarFile jarFile, JarEntry jarEntry, String targetDir) {
    boolean extractSuccessful = false;
    File file = new File(targetDir);
    if (!file.exists()) {
        file.mkdir();
    }
    if (jarEntry != null) {
        InputStream inputStream = null;
        try {
            inputStream = jarFile.getInputStream(jarEntry);
            file = new File(targetDir + jarEntry.getName());
            if (jarEntry.isDirectory()) {
                file.mkdir();
            } else {
                int size;
                byte[] buffer = new byte[2048];

                FileOutputStream fileOutputStream = new FileOutputStream(file);
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream,
                        buffer.length);

                try {
                    while ((size = inputStream.read(buffer, 0, buffer.length)) != -1) {
                        bufferedOutputStream.write(buffer, 0, size);
                    }
                    bufferedOutputStream.flush();
                } finally {
                    bufferedOutputStream.close();
                }
            }
            extractSuccessful = true;
        } catch (Exception e) {
            log.warn(e);
        } finally {
            close(inputStream);
        }
    }
    return extractSuccessful;
}

From source file:eu.stratosphere.yarn.Utils.java

public static void copyJarContents(String prefix, String pathToJar) throws IOException {
    LOG.info("Copying jar (location: " + pathToJar + ") to prefix " + prefix);

    JarFile jar = null;
    jar = new JarFile(pathToJar);
    Enumeration<JarEntry> enumr = jar.entries();
    byte[] bytes = new byte[1024];
    while (enumr.hasMoreElements()) {
        JarEntry entry = enumr.nextElement();
        if (entry.getName().startsWith(prefix)) {
            if (entry.isDirectory()) {
                File cr = new File(entry.getName());
                cr.mkdirs();/*from w w w  . j a v  a2s  .  c o m*/
                continue;
            }
            InputStream inStream = jar.getInputStream(entry);
            File outFile = new File(entry.getName());
            if (outFile.exists()) {
                throw new RuntimeException("File unexpectedly exists");
            }
            FileOutputStream outputStream = new FileOutputStream(outFile);
            int read = 0;
            while ((read = inStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
            inStream.close();
            outputStream.close();
        }
    }
    jar.close();
}

From source file:ClassFileUtilities.java

private static void computeClassDependencies(InputStream is, Set classpath, Set done, Set result, boolean rec)
        throws IOException {

    Iterator it = getClassDependencies(is).iterator();
    while (it.hasNext()) {
        String s = (String) it.next();
        if (!done.contains(s)) {
            done.add(s);//from  w w w  .  j a  va  2s.co m

            Iterator cpit = classpath.iterator();
            while (cpit.hasNext()) {
                InputStream depis = null;
                String path = null;
                Object cpEntry = cpit.next();
                if (cpEntry instanceof JarFile) {
                    JarFile jarFile = (JarFile) cpEntry;
                    String classFileName = s + ".class";
                    ZipEntry ze = jarFile.getEntry(classFileName);
                    if (ze != null) {
                        path = jarFile.getName() + '!' + classFileName;
                        depis = jarFile.getInputStream(ze);
                    }
                } else {
                    path = ((String) cpEntry) + '/' + s + ".class";
                    File f = new File(path);
                    if (f.isFile()) {
                        depis = new FileInputStream(f);
                    }
                }

                if (depis != null) {
                    result.add(path);

                    if (rec) {
                        computeClassDependencies(depis, classpath, done, result, rec);
                    }
                }
            }
        }
    }
}

From source file:org.trianacode.taskgraph.util.ExtensionFinder.java

public static Map<Class, Set<Object>> getProviders(List<Class> providers, File file) {
    log.debug("searching for providers:" + file.getAbsolutePath());
    //        System.out.println("*** Looking for extensions in : " + file.getAbsolutePath());
    Map<Class, Set<Object>> ret = new HashMap<Class, Set<Object>>();
    if (file.isDirectory()) {
        File meta = new File(file, "META-INF");
        if (meta.exists()) {
            File services = new File(meta, "services");
            if (services.exists()) {
                for (Class provider : providers) {
                    File prov = new File(services, provider.getName());
                    if (prov.exists()) {

                        List<Object> impls = null;
                        try {
                            BufferedReader reader = new BufferedReader(
                                    new InputStreamReader(new FileInputStream(prov)));
                            String line;
                            impls = new ArrayList<Object>();
                            List<String> done = new ArrayList<String>();
                            while ((line = reader.readLine()) != null) {
                                log.debug("got next service provider:" + line);
                                log.debug("*** Found : " + line);
                                try {
                                    if (!done.contains(line)) {
                                        Class cls = ClassLoaders.forName(line);
                                        if (provider.isAssignableFrom(cls)) {
                                            Object p = cls.newInstance();
                                            impls.add(p);
                                        }
                                        done.add(line);
                                    }/* w ww .  j a  v  a  2s .c om*/
                                } catch (Exception e1) {
                                    log.debug("Exception thrown trying to load service provider class " + line
                                            + ":" + FileUtils.formatThrowable(e1));
                                }
                            }
                        } catch (IOException e) {
                            log.debug("error thrown while reading file:" + e.getMessage());
                        }
                        if (impls.size() > 0) {
                            Set<Object> exist = ret.get(provider);
                            if (exist == null) {
                                exist = new HashSet<Object>();
                            }
                            exist.addAll(impls);
                            ret.put(provider, exist);
                        }
                    }
                }
            }
        }
        File[] children = file.listFiles(new FilenameFilter() {
            public boolean accept(File file, String s) {
                if (s.endsWith(".jar")) {
                    return true;
                }
                return false;
            }
        });
        if (children != null) {
            for (File child : children) {
                Map<Class, Set<Object>> map = getProviders(providers, child);
                for (Class aClass : map.keySet()) {
                    Set<Object> objs = ret.get(aClass);
                    if (objs == null) {
                        ret.put(aClass, map.get(aClass));
                    } else {
                        objs.addAll(map.get(aClass));
                        ret.put(aClass, objs);
                    }
                }
            }
        }
    } else {
        if (file.getName().endsWith(".jar")) {
            try {
                JarFile jf = new JarFile(file);
                ZipEntry entry = jf.getEntry("META-INF/services/");
                if (entry != null) {
                    for (Class provider : providers) {
                        ZipEntry e = jf.getEntry("META-INF/services/" + provider.getName());
                        if (e != null) {
                            InputStream zin = jf.getInputStream(e);
                            BufferedReader reader = new BufferedReader(new InputStreamReader(zin));
                            String line;
                            List<Object> impls = new ArrayList<Object>();
                            List<String> done = new ArrayList<String>();
                            while ((line = reader.readLine()) != null) {
                                log.debug("got next service provider:" + line);
                                // check if the class is in this jar
                                ZipEntry sp = jf.getEntry(line.replace(".", "/") + ".class");
                                if (sp != null) {
                                    try {
                                        if (!done.contains(line)) {
                                            Class cls = ClassLoaders.forName(line);
                                            if (provider.isAssignableFrom(cls)) {
                                                Object prov = cls.newInstance();
                                                impls.add(prov);
                                            }
                                            done.add(line);
                                        }
                                    } catch (Exception e1) {
                                        e1.printStackTrace();
                                        log.debug("Exception thrown trying to load service provider class "
                                                + line, e1);
                                    }
                                }
                            }
                            if (impls.size() > 0) {
                                Set<Object> exist = ret.get(provider);
                                if (exist == null) {
                                    exist = new HashSet<Object>();
                                }
                                exist.addAll(impls);
                                ret.put(provider, exist);
                            }
                        }
                    }
                }
            } catch (IOException e) {
                log.debug("Exception thrown trying to load service providers from file " + file, e);
            }
        }

    }
    return ret;
}

From source file:com.wordnik.swagger.codegen.util.FileUtil.java

public static boolean copyJarResourcesRecursively(final File destDir, final JarURLConnection jarConnection)
        throws IOException {

    final JarFile jarFile = jarConnection.getJarFile();

    for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
        final JarEntry entry = e.nextElement();
        if (entry.getName().startsWith(jarConnection.getEntryName())) {
            final String filename = StringUtils.removeStart(entry.getName(), //
                    jarConnection.getEntryName());

            final File f = new File(destDir, filename);
            if (!entry.isDirectory()) {
                final InputStream entryInputStream = jarFile.getInputStream(entry);
                if (!FileUtil.copyStream(entryInputStream, f)) {
                    return false;
                }// ww w.  ja  va 2  s . c  o  m
                entryInputStream.close();
            } else {
                if (!FileUtil.ensureDirectoryExists(f)) {
                    throw new IOException("Could not create directory: " + f.getAbsolutePath());
                }
            }
        }
    }
    return true;
}

From source file:com.enderville.enderinstaller.util.InstallScript.java

/**
 * Unpacks all the contents of the old minecraft.jar to the temp directory.
 *
 * @param tmpdir The temp directory to unpack to.
 * @param mcjar The location of the old minecraft.jar
 * @throws IOException/*from  w  ww .  jav a2  s .  co m*/
 */
public static void unpackMCJar(File tmpdir, File mcjar) throws IOException {
    byte[] dat = new byte[4 * 1024];
    JarFile jar = new JarFile(mcjar);
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String name = entry.getName();
        //This gets rid of META-INF if it exists.
        if (name.startsWith("META-INF")) {
            continue;
        }
        InputStream in = jar.getInputStream(entry);
        File dest = new File(FilenameUtils.concat(tmpdir.getPath(), name));
        if (entry.isDirectory()) {
            //I don't think this actually happens
            LOGGER.warn("Found a directory while iterating over jar.");
            dest.mkdirs();
        } else if (!dest.getParentFile().exists()) {
            if (!dest.getParentFile().mkdirs()) {
                throw new IOException("Couldn't create directory for " + name);
            }
        }
        FileOutputStream out = new FileOutputStream(dest);
        int len = -1;
        while ((len = in.read(dat)) > 0) {
            out.write(dat, 0, len);
        }
        out.flush();
        out.close();
        in.close();
    }
}

From source file:ro.agrade.jira.qanda.utils.ResourceUtils.java

/**
 * Gets an entry in the JAR. It's your responsability to close the input
 * stream, as usually/*from  ww w  . j av  a 2  s .  com*/
 * @param jar the jar file
 * @param jarEntryName the jar entry name
 * @return the input stream, or null if no entry is found in the file
 * @throws IOException if the jar is invalid
 */
public static InputStream getJarInputStream(JarFile jar, String jarEntryName) throws IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("Searching in JAR >>%s<<, entry >>%s<<", jar.getName(), jarEntryName));
    }
    JarEntry je = jar.getJarEntry(jarEntryName);
    if (je == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("No such entry [%s] in JAR >>%s<<", jarEntryName, jar.getName()));
        }
        return null;
    }
    return jar.getInputStream(je);
}

From source file:net.sf.keystore_explorer.crypto.jcepolicy.JcePolicyUtil.java

/**
 * Get a JCE policy's details.//from   w w  w .ja  v  a2s  .com
 *
 * @param jcePolicy
 *            JCE policy
 * @return Policy details
 * @throws CryptoException
 *             If there was a problem getting the policy details
 */
public static String getPolicyDetails(JcePolicy jcePolicy) throws CryptoException {
    try {
        StringWriter sw = new StringWriter();

        File file = getJarFile(jcePolicy);

        // if there is no policy file at all, return empty string
        if (!file.exists()) {
            return "";
        }

        JarFile jar = new JarFile(file);

        Enumeration<JarEntry> jarEntries = jar.entries();

        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();

            String entryName = jarEntry.getName();

            if (!jarEntry.isDirectory() && entryName.endsWith(".policy")) {
                sw.write(entryName + ":\n\n");

                InputStreamReader isr = null;
                try {
                    isr = new InputStreamReader(jar.getInputStream(jarEntry));
                    CopyUtil.copy(isr, sw);
                } finally {
                    IOUtils.closeQuietly(isr);
                }

                sw.write('\n');
            }
        }

        return sw.toString();
    } catch (IOException ex) {
        throw new CryptoException(
                MessageFormat.format(res.getString("NoGetPolicyDetails.exception.message"), jcePolicy), ex);
    }
}