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.apache.jasper.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.
 *
 * @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
 *//*from   w w w  .j a  v  a  2s.  c  o m*/
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 implicit map entry only if its uri is not already
                // present in the map
                if (uri != null && mappings.get(uri) == null) {
                    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:hotbeans.support.JarFileHotBeanModuleLoader.java

/**
 * Extracts all the files in the module jar file, including nested jar files. The reason for extracting the complete
 * contents of the jar file (and not just the nested jar files) is to make sure the module jar file isn't locked, and
 * thus may be deleted./*  w  w  w  .  j av  a 2s . co  m*/
 */
private void extractLibs() throws IOException {
    if (logger.isDebugEnabled())
        logger.debug("Extracting module jar file '" + moduleJarFile + "'.");

    JarFile jarFile = new JarFile(this.moduleJarFile);
    Enumeration entries = jarFile.entries();
    JarEntry entry;
    String entryName;
    File extractedFile = null;
    FileOutputStream extractedFileOutputStream;

    while (entries.hasMoreElements()) {
        entry = (JarEntry) entries.nextElement();
        if ((entry != null) && (!entry.isDirectory())) {
            entryName = entry.getName();
            if (entryName != null) {
                // if( logger.isDebugEnabled() ) logger.debug("Extracting '" + entryName + "'.");

                // Copy nested jar file to temp dir
                extractedFile = new File(this.tempDir, entryName);
                extractedFile.getParentFile().mkdirs();

                extractedFileOutputStream = new FileOutputStream(extractedFile);
                FileCopyUtils.copy(jarFile.getInputStream(entry), extractedFileOutputStream);
                extractedFileOutputStream = null;

                if ((entryName.startsWith(LIB_PATH)) && (entryName.toLowerCase().endsWith(".jar"))) {
                    // Register nested jar file in "class path"
                    super.addURL(extractedFile.toURI().toURL());
                }
            }
        }
    }

    jarFile.close();
    jarFile = null;

    super.addURL(tempDir.toURI().toURL()); // Add temp dir as class path (note that this must be added after all the
                                           // files have been extracted)

    if (logger.isDebugEnabled())
        logger.debug("Done extracting module jar file '" + moduleJarFile + "'.");
}

From source file:org.hyperic.hq.plugin.websphere.WebsphereProductPlugin.java

private File runtimeJarHack(File file) throws Exception {
    String tmp = System.getProperty("java.io.tmpdir"); //agent/tmp
    File newJar = new File(tmp, file.getName());
    if (newJar.exists()) {
        return newJar;
    }// www. j  a v a  2  s . c o  m
    log.debug("Creating " + newJar);
    JarFile jar = new JarFile(file);
    JarOutputStream os = new JarOutputStream(new FileOutputStream(newJar));
    byte[] buffer = new byte[1024];
    try {
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            int n;
            JarEntry entry = e.nextElement();

            if (entry.getName().startsWith("org/apache/commons/logging/")) {
                continue;
            }
            InputStream entryStream = jar.getInputStream(entry);

            os.putNextEntry(entry);
            while ((n = entryStream.read(buffer)) != -1) {
                os.write(buffer, 0, n);
            }
            entryStream.close();
        }
    } finally {
        jar.close();
        os.close();
    }
    return newJar;
}

From source file:org.kitesdk.data.hbase.tool.SchemaTool.java

/**
 * Gets the list of HBase Common Avro schema strings from a directory in the
 * Jar. It recursively searches the directory in the jar to find files that
 * end in .avsc to locate thos strings.//from www  .j av a 2 s  .  co  m
 * 
 * @param jarPath
 *          The path to the jar to search
 * @param directoryPath
 *          The directory in the jar to find avro schema strings
 * @return The list of schema strings.
 */
private List<String> getSchemaStringsFromJar(String jarPath, String directoryPath) {
    LOG.info("Getting schema strings in: " + directoryPath + ", from jar: " + jarPath);
    JarFile jar;
    try {
        jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new DatasetException(e);
    } catch (IOException e) {
        throw new DatasetException(e);
    }
    Enumeration<JarEntry> entries = jar.entries();
    List<String> schemaStrings = new ArrayList<String>();
    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        if (jarEntry.getName().startsWith(directoryPath) && jarEntry.getName().endsWith(".avsc")) {
            LOG.info("Found schema: " + jarEntry.getName());
            InputStream inputStream;
            try {
                inputStream = jar.getInputStream(jarEntry);
            } catch (IOException e) {
                throw new DatasetException(e);
            }
            String schemaString = AvroUtils.inputStreamToString(inputStream);
            schemaStrings.add(schemaString);
        }
    }
    return schemaStrings;
}

From source file:com.taobao.android.builder.tools.multidex.FastMultiDexer.java

@Override
public Collection<File> repackageJarList(Collection<File> files) throws IOException {

    List<String> mainDexList = getMainDexList(files);

    List<File> jarList = new ArrayList<>();
    List<File> folderList = new ArrayList<>();
    for (File file : files) {
        if (file.isDirectory()) {
            folderList.add(file);/*from   w  w w  .  jav a 2  s .c o  m*/
        } else {
            jarList.add(file);
        }
    }

    File dir = new File(appVariantContext.getScope().getGlobalScope().getIntermediatesDir(),
            "fastmultidex/" + appVariantContext.getVariantName());
    FileUtils.deleteDirectory(dir);
    dir.mkdirs();

    if (!folderList.isEmpty()) {
        File mergedJar = new File(dir, "jarmerging/combined.jar");
        mergedJar.getParentFile().mkdirs();
        mergedJar.delete();
        mergedJar.createNewFile();
        JarMerger jarMerger = new JarMerger(mergedJar);
        for (File folder : folderList) {
            jarMerger.addFolder(folder);
        }
        jarMerger.close();
        if (mergedJar.length() > 0) {
            jarList.add(mergedJar);
        }
    }

    List<File> result = new ArrayList<>();
    File maindexJar = new File(dir, "fastmaindex.jar");

    JarOutputStream mainJarOuputStream = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(maindexJar)));
    for (File jar : jarList) {
        File outJar = new File(dir, FileNameUtils.getUniqueJarName(jar) + ".jar");
        result.add(outJar);
        JarFile jarFile = new JarFile(jar);
        JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar)));
        Enumeration<JarEntry> jarFileEntries = jarFile.entries();
        while (jarFileEntries.hasMoreElements()) {
            JarEntry ze = jarFileEntries.nextElement();
            String pathName = ze.getName();
            if (mainDexList.contains(pathName)) {
                copyStream(jarFile.getInputStream(ze), mainJarOuputStream, ze, pathName);
            } else {
                copyStream(jarFile.getInputStream(ze), jos, ze, pathName);
            }
        }
        jarFile.close();
        IOUtils.closeQuietly(jos);
    }
    IOUtils.closeQuietly(mainJarOuputStream);

    Collections.sort(result, new NameComparator());

    result.add(0, maindexJar);

    return result;
}

From source file:org.jtheque.modules.impl.ModuleLoader.java

/**
 * Read the config of the module./*from   ww  w  . ja va 2  s .  c  o  m*/
 *
 * @param file The file of the module.
 *
 * @return The module resources.
 *
 * @throws IOException If an error occurs during Jar File reading.
 * @throws org.jtheque.modules.ModuleException
 *                     If the config cannot be read.
 */
private ModuleResources readConfig(File file) throws IOException, ModuleException {
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(file);

        ZipEntry configEntry = jarFile.getEntry("module.xml");

        if (configEntry == null) {
            return new ModuleResources(CollectionUtils.<ImageResource>emptyList(),
                    CollectionUtils.<I18NResource>emptyList(), CollectionUtils.<Resource>emptyList());
        }

        ModuleResources resources = importConfig(jarFile.getInputStream(configEntry));

        //Install necessary resources before installing the bundle
        for (Resource resource : resources.getResources()) {
            if (resource != null) {
                resourceService.installResource(resource);
            }
        }

        return resources;
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
}

From source file:com.cloudera.cdk.data.hbase.tool.SchemaTool.java

/**
 * Gets the list of HBase Common Avro schema strings from a directory in the
 * Jar. It recursively searches the directory in the jar to find files that
 * end in .avsc to locate thos strings./*from   w  w w  .  j  av a2 s .c  o  m*/
 * 
 * @param jarPath
 *          The path to the jar to search
 * @param directoryPath
 *          The directory in the jar to find avro schema strings
 * @return The list of schema strings.
 */
private List<String> getSchemaStringsFromJar(String jarPath, String directoryPath) {
    LOG.info("Getting schema strings in: " + directoryPath + ", from jar: " + jarPath);
    JarFile jar;
    try {
        jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new HBaseCommonException(e);
    } catch (IOException e) {
        throw new HBaseCommonException(e);
    }
    Enumeration<JarEntry> entries = jar.entries();
    List<String> schemaStrings = new ArrayList<String>();
    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        if (jarEntry.getName().startsWith(directoryPath) && jarEntry.getName().endsWith(".avsc")) {
            LOG.info("Found schema: " + jarEntry.getName());
            InputStream inputStream;
            try {
                inputStream = jar.getInputStream(jarEntry);
            } catch (IOException e) {
                throw new HBaseCommonException(e);
            }
            String schemaString = AvroUtils.inputStreamToString(inputStream);
            schemaStrings.add(schemaString);
        }
    }
    return schemaStrings;
}

From source file:org.apache.archiva.rest.services.DefaultBrowseService.java

@Override
public ArtifactContent getArtifactContentText(String groupId, String artifactId, String version,
        String classifier, String type, String path, String repositoryId) throws ArchivaRestServiceException {
    List<String> selectedRepos = getSelectedRepos(repositoryId);
    try {/*from  w ww  .j av a 2s  .  c  o  m*/
        for (String repoId : selectedRepos) {

            ManagedRepositoryContent managedRepositoryContent = repositoryContentFactory
                    .getManagedRepositoryContent(repoId);
            ArchivaArtifact archivaArtifact = new ArchivaArtifact(groupId, artifactId, version, classifier,
                    StringUtils.isEmpty(type) ? "jar" : type, repoId);
            File file = managedRepositoryContent.toFile(archivaArtifact);
            if (!file.exists()) {
                log.debug("file: {} not exists for repository: {} try next repository", file, repoId);
                continue;
            }
            if (StringUtils.isNotBlank(path)) {
                // zip entry of the path -> path must a real file entry of the archive
                JarFile jarFile = new JarFile(file);
                ZipEntry zipEntry = jarFile.getEntry(path);
                try (InputStream inputStream = jarFile.getInputStream(zipEntry)) {
                    return new ArtifactContent(IOUtils.toString(inputStream), repoId);
                } finally {
                    closeQuietly(jarFile);
                }
            }
            return new ArtifactContent(FileUtils.readFileToString(file), repoId);
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new ArchivaRestServiceException(e.getMessage(),
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e);
    } catch (RepositoryNotFoundException e) {
        log.error(e.getMessage(), e);
        throw new ArchivaRestServiceException(e.getMessage(),
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e);
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
        throw new ArchivaRestServiceException(e.getMessage(),
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e);
    }
    log.debug("artifact: {}:{}:{}:{}:{} not found", groupId, artifactId, version, classifier, type);
    // 404 ?
    return new ArtifactContent();
}

From source file:org.jdesktop.wonderland.modules.service.PendingManager.java

/**
 * Takes a base directory (which must exist and be readable) and expands
 * the contents of the archive module into that directory given the
 * URL of the module encoded as a jar file
 * /*  w w  w.j  a  v a 2s  .c  o m*/
 * @param root The base directory in which the module is expanded
 * @throw IOException Upon error
 */
private void expand(File root, File jar) throws IOException {
    /*
     * Loop through each entry, fetch its input stream, and write to an
     * output stream for the file.
     */
    JarFile jarFile = new JarFile(jar);
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements() == true) {
        /* Fetch the next entry, its name is the relative file name */
        JarEntry entry = entries.nextElement();
        String entryName = entry.getName();
        long size = entry.getSize();

        /* Don't expand anything that beings with META-INF */
        if (entryName.startsWith("META-INF") == true) {
            continue;
        }

        /* Ignore if it is a directory, then create it */
        if (entryName.endsWith("/") == true) {
            File file = new File(root, entryName);
            file.mkdirs();
            continue;
        }

        /* Write out to a file in 'root' */
        File file = new File(root, entryName);
        InputStream jis = jarFile.getInputStream(entry);
        FileOutputStream os = new FileOutputStream(file);
        byte[] b = new byte[PendingManager.CHUNK_SIZE];
        long read = 0;
        while (read < size) {
            int len = jis.read(b);
            if (len == -1) {
                break;
            }
            read += len;
            os.write(b, 0, len);
        }
        jis.close();
        os.close();
    }
}

From source file:com.egreen.tesla.server.api.component.Component.java

private void init() throws FileNotFoundException, IOException, ConfigurationException {

    //Init url/*from w  ww .  j ava  2  s  .  co  m*/
    this.jarFile = new URL("jar", "", "file:" + file.getAbsolutePath() + "!/");

    final FileInputStream fileInputStream = new FileInputStream(file);
    JarInputStream jarFile = new JarInputStream(fileInputStream);
    JarFile jf = new JarFile(file);

    setConfiguraton(jf);//Configuration load

    jf.getEntry(TESLAR_WIDGET_MAINIFIESTXML);

    JarEntry jarEntry;

    while (true) {
        jarEntry = jarFile.getNextJarEntry();
        if (jarEntry == null) {
            break;
        }
        if (jarEntry.getName().endsWith(".class") && !jarEntry.getName().contains("$")) {
            final String JarNameClass = jarEntry.getName().replaceAll("/", "\\.");
            String className = JarNameClass.replace(".class", "");
            LOGGER.info(className);
            controllerClassMapper.put(className, className);

        } else if (jarEntry.getName().startsWith("webapp")) {
            final String JarNameClass = jarEntry.getName();
            LOGGER.info(JarNameClass);
            saveEntry(jf.getInputStream(jarEntry), JarNameClass);
        }
    }
}