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:net.sf.keystore_explorer.crypto.signing.JarSigner.java

private static String getDigestManifestAttrs(JarFile jar, JarEntry jarEntry, DigestType digestType)
        throws IOException, CryptoException {

    InputStream jis = null;/*w  ww  .j  av a 2  s .  c  om*/

    try {
        // Get input stream to JAR entry's content
        jis = jar.getInputStream(jarEntry);

        // Get the digest of content in Base64
        byte[] md = DigestUtil.getMessageDigest(jis, digestType);
        byte[] md64 = Base64.encode(md);
        String md64Str = new String(md64);

        // Write manifest entries for JARs digest
        StringBuilder sbManifestEntry = new StringBuilder();
        sbManifestEntry.append(createAttributeText(NAME_ATTR, jarEntry.getName()));
        sbManifestEntry.append(CRLF);
        sbManifestEntry
                .append(createAttributeText(MessageFormat.format(DIGEST_ATTR, digestType.jce()), md64Str));
        sbManifestEntry.append(CRLF);
        sbManifestEntry.append(CRLF);

        return sbManifestEntry.toString();
    } finally {
        IOUtils.closeQuietly(jis);
    }
}

From source file:JarUtil.java

/**
 * Extracts the given jar-file to the specified directory. The target
 * directory will be cleaned before the jar-file will be extracted.
 * //ww w. j a  v a  2 s. c  o m
 * @param jarFile
 *            The jar file which should be unpacked
 * @param targetDir
 *            The directory to which the jar-content should be extracted.
 * @throws FileNotFoundException
 *             when the jarFile does not exist
 * @throws IOException
 *             when a file could not be written or the jar-file could not
 *             read.
 */
public static void unjar(File jarFile, File targetDir) throws FileNotFoundException, IOException {
    // clear target directory:
    if (targetDir.exists()) {
        targetDir.delete();
    }
    // create new target directory:
    targetDir.mkdirs();
    // read jar-file:
    String targetPath = targetDir.getAbsolutePath() + File.separatorChar;
    byte[] buffer = new byte[1024 * 1024];
    JarFile input = new JarFile(jarFile, false, ZipFile.OPEN_READ);
    Enumeration<JarEntry> enumeration = input.entries();
    for (; enumeration.hasMoreElements();) {
        JarEntry entry = enumeration.nextElement();
        if (!entry.isDirectory()) {
            // do not copy anything from the package cache:
            if (entry.getName().indexOf("package cache") == -1) {
                String path = targetPath + entry.getName();
                File file = new File(path);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                FileOutputStream out = new FileOutputStream(file);
                InputStream in = input.getInputStream(entry);
                int read;
                while ((read = in.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                }
                in.close();
                out.close();
            }
        }
    }

}

From source file:org.openmrs.module.SqlDiffFileParser.java

/**
 * Get the diff map. Return a sorted map&lt;version, sql statements&gt;
 *
 * @return SortedMap&lt;String, String&gt;
 * @throws ModuleException/*  ww w  . jav a 2s . c  o m*/
 */
public static SortedMap<String, String> getSqlDiffs(Module module) throws ModuleException {
    if (module == null) {
        throw new ModuleException("Module cannot be null");
    }

    SortedMap<String, String> map = new TreeMap<String, String>(new VersionComparator());

    InputStream diffStream = null;

    // get the diff stream
    JarFile jarfile = null;
    try {
        try {
            jarfile = new JarFile(module.getFile());
        } catch (IOException e) {
            throw new ModuleException("Unable to get jar file", module.getName(), e);
        }

        diffStream = ModuleUtil.getResourceFromApi(jarfile, module.getModuleId(), module.getVersion(),
                SQLDIFF_CHANGELOG_FILENAME);
        if (diffStream == null) {
            // Try the old way. Loading from the root of the omod
            ZipEntry diffEntry = jarfile.getEntry(SQLDIFF_CHANGELOG_FILENAME);
            if (diffEntry == null) {
                log.debug("No sqldiff.xml found for module: " + module.getName());
                return map;
            } else {
                try {
                    diffStream = jarfile.getInputStream(diffEntry);
                } catch (IOException e) {
                    throw new ModuleException("Unable to get sql diff file stream", module.getName(), e);
                }
            }
        }

        try {
            // turn the diff stream into an xml document
            Document diffDoc = null;
            try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                db.setEntityResolver(new EntityResolver() {

                    @Override
                    public InputSource resolveEntity(String publicId, String systemId)
                            throws SAXException, IOException {
                        // When asked to resolve external entities (such as a DTD) we return an InputSource
                        // with no data at the end, causing the parser to ignore the DTD.
                        return new InputSource(new StringReader(""));
                    }
                });
                diffDoc = db.parse(diffStream);
            } catch (Exception e) {
                throw new ModuleException("Error parsing diff sqldiff.xml file", module.getName(), e);
            }

            Element rootNode = diffDoc.getDocumentElement();

            String diffVersion = rootNode.getAttribute("version");

            if (!validConfigVersions().contains(diffVersion)) {
                throw new ModuleException("Invalid config version: " + diffVersion, module.getModuleId());
            }

            NodeList diffNodes = getDiffNodes(rootNode, diffVersion);

            if (diffNodes != null && diffNodes.getLength() > 0) {
                int i = 0;
                while (i < diffNodes.getLength()) {
                    Element el = (Element) diffNodes.item(i++);
                    String version = getElement(el, diffVersion, "version");
                    String sql = getElement(el, diffVersion, "sql");
                    map.put(version, sql);
                }
            }
        } catch (ModuleException e) {
            if (diffStream != null) {
                try {
                    diffStream.close();
                } catch (IOException io) {
                    log.error("Error while closing config stream for module: " + module.getModuleId(), io);
                }
            }

            // rethrow the moduleException
            throw e;
        }

    } finally {
        try {
            if (jarfile != null) {
                jarfile.close();
            }
        } catch (IOException e) {
            log.warn("Unable to close jarfile: " + jarfile.getName());
        }
    }
    return map;
}

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

private static String getPomVaadinVersion(JarFile jarFile) {
    try {/*from  www  .j  a v  a2 s.  c o m*/
        JarEntry pomEntry = null;

        // find pom.xml file in META-INF/maven and sub folders
        Enumeration<JarEntry> enumerator = jarFile.entries();
        while (enumerator.hasMoreElements()) {
            JarEntry entry = enumerator.nextElement();
            if (entry.getName().startsWith("META-INF/maven/") && entry.getName().endsWith("/pom.xml")) {
                pomEntry = entry;
                break;
            }
        }

        // read project version from pom.xml
        if (pomEntry != null) {
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(jarFile.getInputStream(pomEntry));
            NodeList children = document.getDocumentElement().getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                Node node = children.item(i + 1);
                if (node.getNodeName().equals("version")) {
                    return node.getTextContent();
                }
            }
        }
        return null;
    } catch (Exception exception) {
        return null;
    }
}

From source file:org.colombbus.tangara.FileUtils.java

public static int extractJar(File jar, File directory) {
    JarEntry entry = null;//ww w  . jav  a2  s  . c  o m
    File currentFile = null;
    BufferedInputStream input = null;
    JarFile jarFile = null;
    int filesCount = 0;
    try {
        jarFile = new JarFile(jar);
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            entry = entries.nextElement();
            currentFile = new File(directory, entry.getName());
            if (entry.isDirectory()) {
                currentFile.mkdir();
            } else {
                currentFile.createNewFile();
                input = new BufferedInputStream(jarFile.getInputStream(entry));
                copyFile(input, currentFile);
                input.close();
                filesCount++;
            }
        }
    } catch (IOException e) {
        LOG.error("Error extracting JAR file " + jar.getAbsolutePath(), e);
    } finally {
        try {
            if (input != null) {
                input.close();
            }
            if (jarFile != null) {
                jarFile.close();
            }
        } catch (IOException e) {
        }
    }
    return filesCount;
}

From source file:org.schemaspy.util.ResourceWriter.java

/**
 * Copies resources from the jar file of the current thread and extract it
 * to the destination path.// www. ja  v  a  2s  .  c  om
 *
 * @param jarConnection
 * @param destPath destination file or directory
 */
private static void copyJarResourceToPath(JarURLConnection jarConnection, File destPath, FileFilter filter) {
    try {
        JarFile jarFile = jarConnection.getJarFile();
        String jarConnectionEntryName = jarConnection.getEntryName();

        /**
         * Iterate all entries in the jar file.
         */
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName + "/")) {
                String filename = jarEntryName.substring(jarConnectionEntryName.length());
                File currentFile = new File(destPath, filename);

                if (jarEntry.isDirectory()) {
                    FileUtils.forceMkdir(currentFile);
                } else {
                    if (filter == null || filter.accept(currentFile)) {
                        InputStream is = jarFile.getInputStream(jarEntry);
                        OutputStream out = FileUtils.openOutputStream(currentFile);
                        IOUtils.copy(is, out);
                        is.close();
                        out.close();
                    }
                }
            }
        }
    } catch (IOException e) {
        LOGGER.warn(e.getMessage(), e);
    }
}

From source file:net.sourceforge.lept4j.util.LoadLibs.java

/**
 * Copies resources from the jar file of the current thread and extract it
 * to the destination directory./*w  w w  .ja v  a  2  s .c  o  m*/
 *
 * @param jarConnection
 * @param destDir
 */
static void copyJarResourceToDirectory(JarURLConnection jarConnection, File destDir) {
    try {
        JarFile jarFile = jarConnection.getJarFile();
        String jarConnectionEntryName = jarConnection.getEntryName() + "/";

        /**
         * Iterate all entries in the jar file.
         */
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {
                String filename = jarEntryName.substring(jarConnectionEntryName.length());
                File currentFile = new File(destDir, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    currentFile.deleteOnExit();
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        logger.log(Level.WARNING, e.getMessage(), e);
    }
}

From source file:net.sourceforge.tess4j.util.LoadLibs.java

/**
 * Copies resources from the jar file of the current thread and extract it
 * to the destination path./*  w w  w  .j a va 2s  .  c  o m*/
 *
 * @param jarConnection
 * @param destPath destination file or directory
 */
static void copyJarResourceToPath(JarURLConnection jarConnection, File destPath) {
    try {
        JarFile jarFile = jarConnection.getJarFile();
        String jarConnectionEntryName = jarConnection.getEntryName();

        /**
         * Iterate all entries in the jar file.
         */
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {
                String filename = jarEntryName.substring(jarConnectionEntryName.length());
                File currentFile = new File(destPath, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    currentFile.deleteOnExit();
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:org.codehaus.mojo.license.osgi.AboutFileLicenseResolver.java

private String readContent(JarFile jarFile, ZipEntry entry) throws IOException {
    InputStream inputStream = jarFile.getInputStream(entry);
    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8.name());
    return writer.toString();
}

From source file:com.amalto.core.query.SystemStorageTest.java

private static Collection<String> getConfigFiles() throws Exception {
    URL data = InitDBUtil.class.getResource("data"); //$NON-NLS-1$
    List<String> result = new ArrayList<String>();
    if ("jar".equals(data.getProtocol())) { //$NON-NLS-1$
        JarURLConnection connection = (JarURLConnection) data.openConnection();
        JarEntry entry = connection.getJarEntry();
        JarFile file = connection.getJarFile();
        Enumeration<JarEntry> entries = file.entries();
        while (entries.hasMoreElements()) {
            JarEntry e = entries.nextElement();
            if (e.getName().startsWith(entry.getName()) && !e.isDirectory()) {
                result.add(IOUtils.toString(file.getInputStream(e)));
            }/* ww w.  j  a v a  2 s  .  c om*/
        }
    } else {
        Collection<File> files = FileUtils.listFiles(new File(data.toURI()), new IOFileFilter() {

            @Override
            public boolean accept(File file) {
                return true;
            }

            @Override
            public boolean accept(File file, String s) {
                return true;
            }
        }, new IOFileFilter() {

            @Override
            public boolean accept(File file) {
                return !".svn".equals(file.getName()); //$NON-NLS-1$
            }

            @Override
            public boolean accept(File file, String s) {
                return !".svn".equals(file.getName()); //$NON-NLS-1$
            }
        });
        for (File f : files) {
            result.add(IOUtils.toString(new FileInputStream(f)));
        }
    }
    return result;
}