Example usage for java.util.jar JarInputStream JarInputStream

List of usage examples for java.util.jar JarInputStream JarInputStream

Introduction

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

Prototype

public JarInputStream(InputStream in) throws IOException 

Source Link

Document

Creates a new JarInputStream and reads the optional manifest.

Usage

From source file:gov.nih.nci.restgen.util.JarHelper.java

/**
 * Given an InputStream on a jar file, unjars the contents into the given
 * directory./*from   w ww.  ja  v a 2s.co m*/
 */
public void unjar(InputStream in, File destDir) throws IOException {
    BufferedOutputStream dest = null;
    JarInputStream jis = new JarInputStream(in);
    JarEntry entry;
    while ((entry = jis.getNextJarEntry()) != null) {
        if (entry.isDirectory()) {
            File dir = new File(destDir, entry.getName());
            dir.mkdir();
            if (entry.getTime() != -1)
                dir.setLastModified(entry.getTime());
            continue;
        }
        int count;
        byte data[] = new byte[BUFFER_SIZE];
        File destFile = new File(destDir, entry.getName());
        if (mVerbose) {
            //System.out.println("unjarring " + destFile + " from " + entry.getName());
        }
        FileOutputStream fos = new FileOutputStream(destFile);
        dest = new BufferedOutputStream(fos, BUFFER_SIZE);
        while ((count = jis.read(data, 0, BUFFER_SIZE)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
        if (entry.getTime() != -1)
            destFile.setLastModified(entry.getTime());
    }
    jis.close();
}

From source file:org.drools.guvnor.server.contenthandler.soa.JarFileContentHandler.java

private String getClassesFromJar(AssetItem assetItem) throws IOException {
    Map<String, String> nonCollidingImports = new HashMap<String, String>();
    String assetPackageName = assetItem.getModuleName();

    //Setup class-loader to check for class visibility
    JarInputStream cljis = new JarInputStream(assetItem.getBinaryContentAttachment());
    List<JarInputStream> jarInputStreams = new ArrayList<JarInputStream>();
    jarInputStreams.add(cljis);/*from   w  w w  .  ja va 2s. c  o m*/
    ClassLoaderBuilder clb = new ClassLoaderBuilder(jarInputStreams);
    ClassLoader cl = clb.buildClassLoader();

    //Reset stream to read classes
    JarInputStream jis = new JarInputStream(assetItem.getBinaryContentAttachment());
    JarEntry entry = null;

    //Get Class names from JAR, only the first occurrence of a given Class leaf name will be inserted. Thus 
    //"org.apache.commons.lang.NumberUtils" will be imported but "org.apache.commons.lang.math.NumberUtils"
    //will not, assuming it follows later in the JAR structure.
    while ((entry = jis.getNextJarEntry()) != null) {
        if (!entry.isDirectory()) {
            if (entry.getName().endsWith(".class") && entry.getName().indexOf('$') == -1
                    && !entry.getName().endsWith("package-info.class")) {
                String fullyQualifiedName = convertPathToName(entry.getName());
                if (isClassVisible(cl, fullyQualifiedName, assetPackageName)) {
                    String leafName = getLeafName(fullyQualifiedName);
                    if (!nonCollidingImports.containsKey(leafName)) {
                        nonCollidingImports.put(leafName, fullyQualifiedName);
                    }
                }
            }
        }
    }

    //Build list of classes
    StringBuffer classes = new StringBuffer();
    for (String value : nonCollidingImports.values()) {
        classes.append(value + "\n");
    }

    return classes.toString();
}

From source file:ezbake.frack.submitter.util.JarUtilTest.java

@Test
public void addFileToJar() throws IOException {
    File tmpDir = new File("jarUtilTest");
    try {/*from   w  w w. java  2 s.c  om*/
        tmpDir.mkdirs();

        // Push the example jar to a file
        byte[] testJar = IOUtils.toByteArray(this.getClass().getResourceAsStream("/example.jar"));
        File jarFile = new File(tmpDir, "example.jar");
        BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(jarFile));
        os.write(testJar);
        os.close();

        // Push the test content to a file
        byte[] testContent = IOUtils.toByteArray(this.getClass().getResourceAsStream("/test.txt"));
        String stringTestContent = new String(testContent);
        File testFile = new File(tmpDir, "test.txt");
        os = new BufferedOutputStream(new FileOutputStream(testFile));
        os.write(testContent);
        os.close();

        assertTrue(jarFile.exists());
        assertTrue(testFile.exists());

        // Add the new file to the jar
        File newJar = JarUtil.addFilesToJar(jarFile, Lists.newArrayList(testFile));
        assertTrue("New jar file exists", newJar.exists());
        assertTrue("New jar is a file", newJar.isFile());

        // Roll through the entries of the new jar and
        JarInputStream is = new JarInputStream(new FileInputStream(newJar));
        JarEntry entry = is.getNextJarEntry();
        boolean foundNewFile = false;
        String content = "";
        while (entry != null) {
            String name = entry.getName();
            if (name.endsWith("test.txt")) {
                foundNewFile = true;
                byte[] buffer = new byte[1];
                while ((is.read(buffer)) > 0) {
                    content += new String(buffer);
                }
                break;
            }
            entry = is.getNextJarEntry();
        }
        is.close();
        assertTrue("New file was in repackaged jar", foundNewFile);
        assertEquals("Content of added file is the same as the retrieved new file", stringTestContent, content);
    } finally {
        FileUtils.deleteDirectory(tmpDir);
    }
}

From source file:ArchiveUtil.java

/**
 * Extracts the file {@code archive} to the target dir {@code targetDir} and deletes the 
 * files extracted upon jvm exit if the flag {@code deleteOnExit} is true.
 *//*w  w  w. j av  a  2s.  c o m*/
public static boolean extract(URL archive, File targetDir, boolean deleteOnExit) throws IOException {
    String archiveStr = archive.toString();
    String jarEntry = null;
    int idx = archiveStr.indexOf("!/");
    if (idx != -1) {
        if (!archiveStr.startsWith("jar:") && archiveStr.length() == idx + 2)
            return false;
        archive = new URL(archiveStr.substring(4, idx));
        jarEntry = archiveStr.substring(idx + 2);
    } else if (!isSupported(archiveStr))
        return false;

    JarInputStream jis = new JarInputStream(archive.openConnection().getInputStream());
    if (!targetDir.exists())
        targetDir.mkdirs();
    JarEntry entry = null;
    while ((entry = jis.getNextJarEntry()) != null) {
        String entryName = entry.getName();
        File entryFile = new File(targetDir, entryName);
        if (!entry.isDirectory()) {
            if (jarEntry == null || entryName.startsWith(jarEntry)) {
                if (!entryFile.exists() || entryFile.lastModified() != entry.getTime())
                    extractEntry(entryFile, jis, entry, deleteOnExit);
            }
        }
    }
    try {
        jis.close();
    } catch (Exception e) {
    }
    return true;
}

From source file:JarHelper.java

/**
 * Given an InputStream on a jar file, unjars the contents into the given
 * directory.//from  www  .j  a  v  a2s . c o  m
 */
public void unjar(InputStream in, File destDir) throws IOException {
    BufferedOutputStream dest = null;
    JarInputStream jis = new JarInputStream(in);
    JarEntry entry;
    while ((entry = jis.getNextJarEntry()) != null) {
        if (entry.isDirectory()) {
            File dir = new File(destDir, entry.getName());
            dir.mkdir();
            if (entry.getTime() != -1)
                dir.setLastModified(entry.getTime());
            continue;
        }
        int count;
        byte data[] = new byte[BUFFER_SIZE];
        File destFile = new File(destDir, entry.getName());
        if (mVerbose)
            System.out.println("unjarring " + destFile + " from " + entry.getName());
        FileOutputStream fos = new FileOutputStream(destFile);
        dest = new BufferedOutputStream(fos, BUFFER_SIZE);
        while ((count = jis.read(data, 0, BUFFER_SIZE)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
        if (entry.getTime() != -1)
            destFile.setLastModified(entry.getTime());
    }
    jis.close();
}

From source file:com.thoughtworks.go.util.NestedJarClassLoader.java

private URL[] enumerateJar(URL urlOfJar) {
    LOGGER.debug("Enumerating jar: {}", urlOfJar);
    List<URL> urls = new ArrayList<>();
    urls.add(urlOfJar);//w w  w  .j a va  2s. c o  m
    try {
        JarInputStream jarStream = new JarInputStream(urlOfJar.openStream());
        JarEntry entry;
        while ((entry = jarStream.getNextJarEntry()) != null) {
            if (!entry.isDirectory() && entry.getName().endsWith(".jar")) {
                urls.add(expandJarAndReturnURL(jarStream, entry));
            }
        }
    } catch (IOException e) {
        LOGGER.error("Failed to enumerate jar {}", urlOfJar, e);
    }
    return urls.toArray(new URL[0]);
}

From source file:org.bimserver.plugins.JarClassLoader.java

private void loadSubJars(byte[] byteArray) {
    try {/*from  w  w w.  j  a  v  a  2s . co  m*/
        JarInputStream jarInputStream = new JarInputStream(new ByteArrayInputStream(byteArray));
        JarEntry entry = jarInputStream.getNextJarEntry();
        while (entry != null) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            IOUtils.copy(jarInputStream, byteArrayOutputStream);
            map.put(entry.getName(), byteArrayOutputStream.toByteArray());
            entry = jarInputStream.getNextJarEntry();
        }
        jarInputStream.close();
    } catch (IOException e) {
        LOGGER.error("", e);
    }
}

From source file:com.dragome.callbackevictor.serverside.utils.RewritingUtils.java

public static boolean rewriteJar(final JarInputStream pInput, final ResourceTransformer transformer,
        final JarOutputStream pOutput, final Matcher pMatcher) throws IOException {

    boolean changed = false;

    while (true) {
        final JarEntry entry = pInput.getNextJarEntry();

        if (entry == null) {
            break;
        }/*from   w ww .  ja v a2s .co  m*/

        if (entry.isDirectory()) {
            pOutput.putNextEntry(new JarEntry(entry));
            continue;
        }

        final String name = entry.getName();

        pOutput.putNextEntry(new JarEntry(name));

        if (name.endsWith(".class")) {
            if (pMatcher.isMatching(name)) {

                if (log.isDebugEnabled()) {
                    log.debug("transforming " + name);
                }

                final byte[] original = toByteArray(pInput);

                byte[] transformed = transformer.transform(original);

                pOutput.write(transformed);

                changed |= transformed.length != original.length;

                continue;
            }
        } else if (name.endsWith(".jar") || name.endsWith(".ear") || name.endsWith(".zip")
                || name.endsWith(".war")) {

            changed |= rewriteJar(new JarInputStream(pInput), transformer, new JarOutputStream(pOutput),
                    pMatcher);

            continue;
        }

        int length = copy(pInput, pOutput);

        log.debug("copied " + name + "(" + length + ")");
    }

    pInput.close();
    pOutput.close();

    return changed;
}

From source file:ru.codeinside.adm.ui.UploadDeployer.java

private void checkSupportInterface(Upload.SucceededEvent event, String supportedInterface) throws Exception {
    if (!event.getFilename().endsWith(".jar")) {
        throw new Exception("? jar ");
    }//w  ww  .  j a  v  a2 s . co m
    JarInputStream jarStream = null;
    try {
        jarStream = new JarInputStream(new ByteArrayInputStream(fileData));
        if (!isOsgiComponent(jarStream)) {
            throw new Exception("? osgi ");
        }
        if (!hasApiServer(supportedInterface, jarStream)) {
            throw new Exception("?  ? [" + supportedInterface + "]");
        }
    } finally {
        if (jarStream != null) {
            jarStream.close();
        }
    }
}

From source file:petascope.util.IOUtil.java

public static List<String> filesInJarDir(String jarDir) {
    List<String> ret = new ArrayList<String>();
    JarInputStream jfile = null;//from  ww w.jav a2 s. c  o m
    try {
        // path to the jar
        String jarPath = IOUtil.class.getResource("").getPath();
        jarPath = jarPath.substring(0, jarPath.indexOf("!"));

        File file = new File(new URI(jarPath));
        jfile = new JarInputStream(new FileInputStream(file));
        JarEntry entry = null;
        do {
            try {
                entry = jfile.getNextJarEntry();
                if (entry == null) {
                    continue;
                }
                String sentry = entry.toString();
                if (("/" + sentry).contains(jarDir) && !sentry.endsWith("/")) {
                    ret.add(sentry);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } while (entry != null);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            jfile.close();
        } catch (Exception ex) {
        }
        return ret;
    }
}