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.hyperic.hq.product.server.session.ProductPluginDeployer.java

private void unpackJar(File pluginJarFile, File destDir, String prefix) throws Exception {

    JarFile jar = null;
    try {/*from w  ww  .  ja v a 2s.  c om*/
        jar = new JarFile(pluginJarFile);
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            JarEntry entry = e.nextElement();
            String name = entry.getName();

            if (name.startsWith(prefix)) {
                name = name.substring(prefix.length());
                if (name.length() == 0) {
                    continue;
                }
                File file = new File(destDir, name);
                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    FileUtil.copyStream(jar.getInputStream(entry), new FileOutputStream(file));
                }
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        if (jar != null)
            jar.close();
    }
}

From source file:com.evolveum.midpoint.provisioning.ucf.impl.ConnectorFactoryIcfImpl.java

/**
 * Test if provided file is connector bundle
 * /*from   www. j av  a  2 s  .co  m*/
 * @param file
 *            tested file
 * @return boolean
 */
private Boolean isThisJarFileBundle(File file) {
    // Startup tests
    if (null == file) {
        throw new IllegalArgumentException("No file is providied for bundle test.");
    }

    // Skip all processing if it is not a file
    if (!file.isFile()) {
        LOGGER.debug("This {} is not a file", file.getAbsolutePath());
        return false;
    }

    Properties prop = new Properties();
    JarFile jar = null;
    // Open jar file
    try {
        jar = new JarFile(file);
    } catch (IOException ex) {
        LOGGER.debug("Unable to read jar file: " + file.getAbsolutePath() + " [" + ex.getMessage() + "]");
        return false;
    }

    // read jar file
    InputStream is;
    try {
        JarEntry entry = new JarEntry("META-INF/MANIFEST.MF");
        is = jar.getInputStream(entry);
    } catch (IOException ex) {
        LOGGER.debug("Unable to fine MANIFEST.MF in jar file: " + file.getAbsolutePath() + " ["
                + ex.getMessage() + "]");
        return false;
    }

    // Parse jar file
    try {
        prop.load(is);
    } catch (IOException ex) {
        LOGGER.debug("Unable to parse jar file: " + file.getAbsolutePath() + " [" + ex.getMessage() + "]");
        return false;
    } catch (NullPointerException ex) {
        LOGGER.debug("Unable to parse jar file: " + file.getAbsolutePath() + " [" + ex.getMessage() + "]");
        return false;
    }

    // Test if it is a connector
    if (null != prop.get("ConnectorBundle-Name")) {
        LOGGER.info("Discovered ICF bundle in JAR: " + prop.get("ConnectorBundle-Name") + " version: "
                + prop.get("ConnectorBundle-Version"));
        return true;
    }

    LOGGER.debug("Provided file {} is not iCF bundle jar", file.getAbsolutePath());
    return false;
}

From source file:org.apache.tomcat.maven.plugin.tomcat7.run.AbstractExecWarMojo.java

/**
 * Copy the contents of a jar file to another archive
 *
 * @param file The input jar file/*w  ww  .ja va2s . c  o  m*/
 * @param os   The output archive
 * @throws IOException
 */
protected void extractJarToArchive(JarFile file, ArchiveOutputStream os, String[] excludes) throws IOException {
    Enumeration<? extends JarEntry> entries = file.entries();
    while (entries.hasMoreElements()) {
        JarEntry j = entries.nextElement();

        if (excludes != null && excludes.length > 0) {
            for (String exclude : excludes) {
                if (SelectorUtils.match(exclude, j.getName())) {
                    continue;
                }
            }
        }

        if (StringUtils.equalsIgnoreCase(j.getName(), "META-INF/MANIFEST.MF")) {
            continue;
        }
        os.putArchiveEntry(new JarArchiveEntry(j.getName()));
        IOUtils.copy(file.getInputStream(j), os);
        os.closeArchiveEntry();
    }
    if (file != null) {
        file.close();
    }
}

From source file:org.tinygroup.jspengine.compiler.TldLocationsCache.java

/**
 * Scans the given JarURLConnection for TLD files located in META-INF (or a
 * subdirectory of it), adding an implicit map entry to the taglib map for
 * any TLD that has a <uri> element.
 * /*w w w  .  ja  v  a 2s  .  c o m*/
 * @param conn
 *            The JarURLConnection to the JAR file to scan
 * @param ignore
 *            true if any exceptions raised when processing the given JAR
 *            should be ignored, false otherwise
 */
private void scanJar(JarURLConnection conn, boolean ignore) throws JasperException {

    JarFile jarFile = null;
    String resourcePath = conn.getJarFileURL().toString();
    try {
        if (redeployMode) {
            conn.setUseCaches(false);
        }
        jarFile = conn.getJarFile();
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            String name = entry.getName();
            if (!name.startsWith("META-INF/"))
                continue;
            if (!name.endsWith(".tld"))
                continue;
            InputStream stream = jarFile.getInputStream(entry);
            try {
                String uri = getUriFromTld(resourcePath, stream);
                // Add map entry.
                // Override existing entries as we move higher
                // up in the classloader delegation chain.
                if (uri != null && (mappings.get(uri) == null || systemUris.contains(uri)
                        || (systemUrisJsf.contains(uri) && !useMyFaces))) {
                    mappings.put(uri, new String[] { resourcePath, name });
                }
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (Throwable t) {
                        // do nothing
                    }
                }
            }
        }
    } catch (Exception ex) {
        if (!redeployMode) {
            // if not in redeploy mode, close the jar in case of an error
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        }
        if (!ignore) {
            throw new JasperException(ex);
        }
    } finally {
        if (redeployMode) {
            // if in redeploy mode, always close the jar
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        }
    }
}

From source file:edu.stanford.muse.email.JarDocCache.java

public Map<Integer, Document> getAllHeaders(String prefix) throws IOException, ClassNotFoundException {
    Map<Integer, Document> result = new LinkedHashMap<Integer, Document>();
    JarFile jarFile = null;
    String fname = baseDir + File.separator + prefix + ".headers";
    try {// w  w w.j av a2s.c  o  m
        jarFile = new JarFile(fname);
    } catch (Exception e) {
        log.info("No Jar file exists: " + fname);
    }
    if (jarFile == null)
        return result;

    Enumeration<JarEntry> entries = jarFile.entries();
    String suffix = ".header";
    while (entries.hasMoreElements()) {
        JarEntry je = entries.nextElement();
        String s = je.getName();
        if (!s.endsWith(suffix))
            continue;
        String idx_str = s.substring(0, s.length() - suffix.length());
        int index = -1;
        try {
            index = Integer.parseInt(idx_str);
        } catch (Exception e) {
            log.error("Funny file in header: " + index);
        }

        ObjectInputStream ois = new ObjectInputStream(jarFile.getInputStream(je));
        Document ed = (Document) ois.readObject();
        ois.close();
        result.put(index, ed);
    }
    return result;
}

From source file:com.stacksync.desktop.Environment.java

public void copyResourcesFromJar(JarURLConnection jarConnection, File destDir) {

    try {//from   w w  w  .ja  va  2 s .co m
        JarFile jarFile = jarConnection.getJarFile();

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

            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();
            String jarConnectionEntryName = jarConnection.getEntryName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {

                String filename = jarEntryName.startsWith(jarConnectionEntryName)
                        ? jarEntryName.substring(jarConnectionEntryName.length())
                        : jarEntryName;
                File currentFile = new File(destDir, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        // TODO add logger
        e.printStackTrace();
    }

}

From source file:org.dbmaintain.script.repository.impl.ArchiveScriptLocation.java

protected SortedSet<Script> loadScriptsFromJar(final JarFile jarFile, String subPath) {
    SortedSet<Script> scripts = new TreeSet<Script>();
    for (Enumeration<JarEntry> jarEntries = jarFile.entries(); jarEntries.hasMoreElements();) {
        final JarEntry jarEntry = jarEntries.nextElement();
        String fileName = jarEntry.getName();
        if (LOCATION_PROPERTIES_FILENAME.equals(fileName) || !isScriptFileName(fileName)) {
            continue;
        }/*from w  w  w.  ja va  2  s. c om*/

        String relativeScriptName = jarEntry.getName();
        if (subPath != null) {
            if (!fileName.startsWith(subPath)) {
                continue;
            }
            relativeScriptName = relativeScriptName.substring(subPath.length());
        }
        ScriptContentHandle scriptContentHandle = new ScriptContentHandle(scriptEncoding,
                ignoreCarriageReturnsWhenCalculatingCheckSum) {
            @Override
            protected InputStream getScriptInputStream() {
                try {
                    return jarFile.getInputStream(jarEntry);
                } catch (IOException e) {
                    throw new DbMaintainException("Error while reading jar entry " + jarEntry, e);
                }
            }
        };
        Long fileLastModifiedAt = jarEntry.getTime();
        Script script = scriptFactory.createScriptWithContent(relativeScriptName, fileLastModifiedAt,
                scriptContentHandle);
        scripts.add(script);
    }
    return scripts;
}

From source file:org.apache.nifi.web.server.JettyServer.java

/**
 * Returns the extension in the specified WAR using the specified path.
 *
 * @param war war/*from  ww w  . ja  va2 s  . c  o m*/
 * @param path path
 * @return extensions
 */
private List<String> getWarExtensions(final File war, final String path) {
    List<String> processorTypes = new ArrayList<>();

    // load the jar file and attempt to find the nifi-processor entry
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(war);
        JarEntry jarEntry = jarFile.getJarEntry(path);

        // ensure the nifi-processor entry was found
        if (jarEntry != null) {
            // get an input stream for the nifi-processor configuration file
            try (final BufferedReader in = new BufferedReader(
                    new InputStreamReader(jarFile.getInputStream(jarEntry)))) {

                // read in each configured type
                String rawProcessorType;
                while ((rawProcessorType = in.readLine()) != null) {
                    // extract the processor type
                    final String processorType = extractComponentType(rawProcessorType);
                    if (processorType != null) {
                        processorTypes.add(processorType);
                    }
                }
            }
        }
    } catch (IOException ioe) {
        logger.warn("Unable to inspect {} for a custom processor UI.", new Object[] { war, ioe });
    } finally {
        IOUtils.closeQuietly(jarFile);
    }

    return processorTypes;
}

From source file:com.migratebird.script.repository.impl.ArchiveScriptLocation.java

protected SortedSet<Script> loadScriptsFromJar(final JarFile jarFile, String subPath) {
    SortedSet<Script> scripts = new TreeSet<Script>();
    for (Enumeration<JarEntry> jarEntries = jarFile.entries(); jarEntries.hasMoreElements();) {
        final JarEntry jarEntry = jarEntries.nextElement();
        String fileName = jarEntry.getName();
        if (LOCATION_PROPERTIES_FILENAME.equals(fileName) || !isScriptFileName(fileName)) {
            continue;
        }//from ww w.  j  a  v  a 2 s  . co  m

        String relativeScriptName = jarEntry.getName();
        if (subPath != null) {
            if (!fileName.startsWith(subPath)) {
                continue;
            }
            relativeScriptName = relativeScriptName.substring(subPath.length());
        }
        ScriptContentHandle scriptContentHandle = new ScriptContentHandle(scriptEncoding,
                ignoreCarriageReturnsWhenCalculatingCheckSum) {
            @Override
            protected InputStream getScriptInputStream() {
                try {
                    return jarFile.getInputStream(jarEntry);
                } catch (IOException e) {
                    throw new MigrateBirdException("Error while reading jar entry " + jarEntry, e);
                }
            }
        };
        Long fileLastModifiedAt = jarEntry.getTime();
        Script script = scriptFactory.createScriptWithContent(relativeScriptName, fileLastModifiedAt,
                scriptContentHandle);
        scripts.add(script);
    }
    return scripts;
}

From source file:org.tobarsegais.webapp.ServletContextListenerImpl.java

public void contextInitialized(ServletContextEvent sce) {
    ServletContext application = sce.getServletContext();
    Map<String, String> bundles = new HashMap<String, String>();
    Map<String, Toc> contents = new LinkedHashMap<String, Toc>();
    List<IndexEntry> keywords = new ArrayList<IndexEntry>();
    Directory index = new RAMDirectory();
    Analyzer analyzer = new StandardAnalyzer(LUCENE_VERSON);
    IndexWriterConfig indexWriterConfig = new IndexWriterConfig(LUCENE_VERSON, analyzer);
    IndexWriter indexWriter;/*from  ww w . j a  v  a  2 s.  co m*/
    try {
        indexWriter = new IndexWriter(index, indexWriterConfig);
    } catch (IOException e) {
        application.log("Cannot create search index. Search will be unavailable.", e);
        indexWriter = null;
    }
    for (String path : (Set<String>) application.getResourcePaths(BUNDLE_PATH)) {
        if (path.endsWith(".jar")) {
            String key = path.substring("/WEB-INF/bundles/".length(), path.lastIndexOf(".jar"));
            application.log("Parsing " + path);
            URLConnection connection = null;
            try {
                URL url = new URL("jar:" + application.getResource(path) + "!/");
                connection = url.openConnection();
                if (!(connection instanceof JarURLConnection)) {
                    application.log(path + " is not a jar file, ignoring");
                    continue;
                }
                JarURLConnection jarConnection = (JarURLConnection) connection;
                JarFile jarFile = jarConnection.getJarFile();
                Manifest manifest = jarFile.getManifest();
                if (manifest != null) {
                    String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
                    if (symbolicName != null) {
                        int i = symbolicName.indexOf(';');
                        if (i != -1) {
                            symbolicName = symbolicName.substring(0, i);
                        }
                        bundles.put(symbolicName, key);
                        key = symbolicName;
                    }
                }

                JarEntry pluginEntry = jarFile.getJarEntry("plugin.xml");
                if (pluginEntry == null) {
                    application.log(path + " does not contain a plugin.xml file, ignoring");
                    continue;
                }
                Plugin plugin = Plugin.read(jarFile.getInputStream(pluginEntry));

                Extension tocExtension = plugin.getExtension("org.eclipse.help.toc");
                if (tocExtension == null || tocExtension.getFile("toc") == null) {
                    application.log(path + " does not contain a 'org.eclipse.help.toc' extension, ignoring");
                    continue;
                }
                JarEntry tocEntry = jarFile.getJarEntry(tocExtension.getFile("toc"));
                if (tocEntry == null) {
                    application.log(path + " is missing the referenced toc: " + tocExtension.getFile("toc")
                            + ", ignoring");
                    continue;
                }
                Toc toc;
                try {
                    toc = Toc.read(jarFile.getInputStream(tocEntry));
                } catch (IllegalStateException e) {
                    application.log("Could not parse " + path + " due to " + e.getMessage(), e);
                    continue;
                }
                contents.put(key, toc);

                Extension indexExtension = plugin.getExtension("org.eclipse.help.index");
                if (indexExtension != null && indexExtension.getFile("index") != null) {
                    JarEntry indexEntry = jarFile.getJarEntry(indexExtension.getFile("index"));
                    if (indexEntry != null) {
                        try {
                            keywords.addAll(Index.read(key, jarFile.getInputStream(indexEntry)).getChildren());
                        } catch (IllegalStateException e) {
                            application.log("Could not parse " + path + " due to " + e.getMessage(), e);
                        }
                    } else {
                        application.log(
                                path + " is missing the referenced index: " + indexExtension.getFile("index"));
                    }

                }
                application.log(path + " successfully parsed and added as " + key);
                if (indexWriter != null) {
                    application.log("Indexing content of " + path);
                    Set<String> files = new HashSet<String>();
                    Stack<Iterator<? extends TocEntry>> stack = new Stack<Iterator<? extends TocEntry>>();
                    stack.push(Collections.singleton(toc).iterator());
                    while (!stack.empty()) {
                        Iterator<? extends TocEntry> cur = stack.pop();
                        if (cur.hasNext()) {
                            TocEntry entry = cur.next();
                            stack.push(cur);
                            if (!entry.getChildren().isEmpty()) {
                                stack.push(entry.getChildren().iterator());
                            }
                            String file = entry.getHref();
                            if (file == null) {
                                continue;
                            }
                            int hashIndex = file.indexOf('#');
                            if (hashIndex != -1) {
                                file = file.substring(0, hashIndex);
                            }
                            if (files.contains(file)) {
                                // already indexed
                                // todo work out whether to just pull the section
                                continue;
                            }
                            Document document = new Document();
                            document.add(new Field("title", entry.getLabel(), Field.Store.YES,
                                    Field.Index.ANALYZED));
                            document.add(new Field("href", key + "/" + entry.getHref(), Field.Store.YES,
                                    Field.Index.NO));
                            JarEntry docEntry = jarFile.getJarEntry(file);
                            if (docEntry == null) {
                                // ignore missing file
                                continue;
                            }
                            InputStream inputStream = null;
                            try {
                                inputStream = jarFile.getInputStream(docEntry);
                                org.jsoup.nodes.Document docDoc = Jsoup.parse(IOUtils.toString(inputStream));
                                document.add(new Field("contents", docDoc.body().text(), Field.Store.NO,
                                        Field.Index.ANALYZED));
                                indexWriter.addDocument(document);
                            } finally {
                                IOUtils.closeQuietly(inputStream);
                            }
                        }
                    }
                }
            } catch (XMLStreamException e) {
                application.log("Could not parse " + path + " due to " + e.getMessage(), e);
            } catch (MalformedURLException e) {
                application.log("Could not parse " + path + " due to " + e.getMessage(), e);
            } catch (IOException e) {
                application.log("Could not parse " + path + " due to " + e.getMessage(), e);
            } finally {
                if (connection instanceof HttpURLConnection) {
                    // should never be the case, but we should try to be sure
                    ((HttpURLConnection) connection).disconnect();
                }
            }
        }
    }
    if (indexWriter != null) {
        try {
            indexWriter.close();
        } catch (IOException e) {
            application.log("Cannot create search index. Search will be unavailable.", e);
        }
        application.setAttribute("index", index);
    }

    application.setAttribute("toc", Collections.unmodifiableMap(contents));
    application.setAttribute("keywords", new Index(keywords));
    application.setAttribute("bundles", Collections.unmodifiableMap(bundles));
    application.setAttribute("analyzer", analyzer);
    application.setAttribute("contentsQueryParser", new QueryParser(LUCENE_VERSON, "contents", analyzer));
}