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.lpe.common.util.system.LpeSystemUtils.java

/**
 * Extracts a file/folder identified by the URL that resides in the
 * classpath, into the destiation folder.
 * //from  www .  ja v a2 s . co  m
 * @param url
 *            URL of the JAR file
 * @param dirOfInterest
 *            the name of the directory of interest
 * @param dest
 *            destination folder
 * 
 * @throws IOException
 *             ...
 * @throws URISyntaxException
 *             ...
 */
public static void extractJARtoTemp(URL url, String dirOfInterest, String dest)
        throws IOException, URISyntaxException {
    if (!url.getProtocol().equals("jar")) {
        throw new IllegalArgumentException("Cannot locate the JAR file.");
    }

    // create a temp lib directory
    File tempJarDirFile = new File(dest);
    if (!tempJarDirFile.exists()) {
        boolean ok = tempJarDirFile.mkdir();
        if (!ok) {
            logger.warn("Could not create directory {}", tempJarDirFile.getAbsolutePath());
        }

    } else {
        FileUtils.cleanDirectory(tempJarDirFile);
    }

    String urlStr = url.getFile();
    // if (urlStr.startsWith("jar:file:") || urlStr.startsWith("jar:") ||
    // urlStr.startsWith("file:")) {
    // urlStr = urlStr.replaceFirst("jar:", "");
    // urlStr = urlStr.replaceFirst("file:", "");
    // }
    if (urlStr.contains("!")) {
        final int endIndex = urlStr.indexOf("!");
        urlStr = urlStr.substring(0, endIndex);
    }

    URI uri = new URI(urlStr);

    final File jarFile = new File(uri);

    logger.debug("Unpacking jar file {}...", jarFile.getAbsolutePath());

    java.util.jar.JarFile jar = null;
    InputStream is = null;
    OutputStream fos = null;
    try {
        jar = new JarFile(jarFile);
        java.util.Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            java.util.jar.JarEntry file = (JarEntry) entries.nextElement();

            String destFileName = dest + File.separator + file.getName();
            if (destFileName.indexOf(dirOfInterest + File.separator) < 0
                    && destFileName.indexOf(dirOfInterest + "/") < 0) {
                continue;
            }

            logger.debug("unpacking {}...", file.getName());

            java.io.File f = new java.io.File(destFileName);
            if (file.isDirectory()) { // if its a directory, create it
                boolean ok = f.mkdir();
                if (!ok) {
                    logger.warn("Could not create directory {}", f.getAbsolutePath());
                }
                continue;
            }
            is = new BufferedInputStream(jar.getInputStream(file));
            fos = new BufferedOutputStream(new FileOutputStream(f));

            LpeStreamUtils.pipe(is, fos);
        }

        logger.debug("Unpacking jar file done.");
    } catch (IOException e) {
        throw e;
    } finally {
        if (jar != null) {
            jar.close();
        }
        if (fos != null) {
            fos.close();
        }
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.lnicholls.galleon.app.AppDescriptor.java

public AppDescriptor(File jar) throws IOException, AppException {
    mJar = jar;/*  w  w  w.j  a v  a2s. c  om*/

    JarFile zipFile = new JarFile(jar);
    Enumeration entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        String name = entry.getName();
        if (name.toUpperCase().equals(JarFile.MANIFEST_NAME)) {
            InputStream in = null;
            try {
                in = zipFile.getInputStream(entry);
                Manifest manifest = new Manifest(in);
                Attributes attributes = manifest.getMainAttributes();
                if (attributes.getValue("Main-Class") != null) {
                    mClassName = (String) attributes.getValue("Main-Class");
                    if (attributes.getValue("HME-Arguments") != null)
                        mArguments = (String) attributes.getValue("HME-Arguments");
                    if (attributes.getValue(TITLE) != null)
                        mTitle = (String) attributes.getValue(TITLE);
                    if (attributes.getValue(RELEASE_DATE) != null)
                        mReleaseDate = (String) attributes.getValue(RELEASE_DATE);
                    if (attributes.getValue(DESCRIPTION) != null)
                        mDescription = (String) attributes.getValue(DESCRIPTION);
                    if (attributes.getValue(DOCUMENTATION) != null)
                        mDocumentation = (String) attributes.getValue(DOCUMENTATION);
                    if (attributes.getValue(AUTHOR_NAME) != null)
                        mAuthorName = (String) attributes.getValue(AUTHOR_NAME);
                    if (attributes.getValue(AUTHOR_EMAIL) != null)
                        mAuthorEmail = (String) attributes.getValue(AUTHOR_EMAIL);
                    if (attributes.getValue(AUTHOR_HOMEPAGE) != null)
                        mAuthorHomepage = (String) attributes.getValue(AUTHOR_HOMEPAGE);
                    if (attributes.getValue(VERSION) != null)
                        mVersion = (String) attributes.getValue(VERSION);
                    if (attributes.getValue(CONFIGURATION) != null)
                        mConfiguration = (String) attributes.getValue(CONFIGURATION);
                    if (attributes.getValue(CONFIGURATION_PANEL) != null)
                        mConfigurationPanel = (String) attributes.getValue(CONFIGURATION_PANEL);
                    if (attributes.getValue(TAGS) != null)
                        mTags = (String) attributes.getValue(TAGS);
                }

                if (mTitle == null) {
                    mTitle = jar.getName().substring(0, jar.getName().indexOf('.'));
                }
            } catch (Exception ex) {
                Tools.logException(AppDescriptor.class, ex, "Cannot get descriptor: " + jar.getAbsolutePath());
            } finally {
                if (in != null) {
                    try {
                        in.close();
                        in = null;
                    } catch (Exception ex) {
                    }
                }
            }
            break;
        }
    }
    zipFile.close();
}

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

/**
 * @param scriptLocation The location of the jar file, not null
 * @return The properties as a properties map
 *///from w  w  w  . j  a  va2  s  .c o m
@Override
protected Properties getCustomProperties(File scriptLocation) {
    InputStream configurationInputStream = null;
    try {
        JarFile jarFile = createJarFile(scriptLocation);
        ZipEntry configurationEntry = jarFile.getEntry(LOCATION_PROPERTIES_FILENAME);
        if (configurationEntry == null) {
            // no custom config found in meta-inf folder, skipping
            return null;
        }
        Properties configuration = new Properties();
        configurationInputStream = jarFile.getInputStream(configurationEntry);
        configuration.load(configurationInputStream);
        return configuration;
    } catch (IOException e) {
        throw new MigrateBirdException("Error while reading configuration file " + LOCATION_PROPERTIES_FILENAME
                + " from jar file " + scriptLocation, e);
    } finally {
        closeQuietly(configurationInputStream);
    }
}

From source file:com.qcadoo.plugin.internal.descriptorparser.DefaultPluginDescriptorParser.java

@Override
public InternalPlugin parse(final File file) {
    JarFile jarFile = null;
    try {//from ww  w  . j ava  2 s  .  co m
        LOG.info("Parsing descriptor for:" + file.getAbsolutePath());

        boolean ignoreModules = true;

        jarFile = new JarFile(file);

        JarEntry descriptorEntry = findDescriptorEntry(jarFile.entries(), file.getAbsolutePath());

        return parse(jarFile.getInputStream(descriptorEntry), ignoreModules, file.getName());
    } catch (IOException e) {
        throw new PluginException("Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath(),
                e);
    } catch (Exception e) {
        throw new PluginException(e.getMessage(), e);
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {
                throw new PluginException(
                        "Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath(), e);
            }
        }
    }
}

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

/**
 * Load resource from a jar inside a jar.
 * /*from   ww  w .j  a v a  2  s. c om*/
 * @param outerJarFile jar file that contains a jar file
 * @param innerJarFileLocation inner jar file location relative to the outer jar
 * @param resource path to a resource relative to the inner jar
 * @return resource from the inner jar as an input stream or <code>null</code> if resource cannot be loaded
 */
private static InputStream getResourceFromInnerJar(JarFile outerJarFile, String innerJarFileLocation,
        String resource) {
    File tempFile = null;
    FileOutputStream tempOut = null;
    JarFile innerJarFile = null;
    InputStream innerInputStream = null;
    try {
        tempFile = File.createTempFile("tempFile", "jar");
        tempOut = new FileOutputStream(tempFile);
        ZipEntry innerJarFileEntry = outerJarFile.getEntry(innerJarFileLocation);
        if (innerJarFileEntry != null) {
            IOUtils.copy(outerJarFile.getInputStream(innerJarFileEntry), tempOut);
            innerJarFile = new JarFile(tempFile);
            ZipEntry targetEntry = innerJarFile.getEntry(resource);
            if (targetEntry != null) {
                // clone InputStream to make it work after the innerJarFile is closed
                innerInputStream = innerJarFile.getInputStream(targetEntry);
                byte[] byteArray = IOUtils.toByteArray(innerInputStream);
                return new ByteArrayInputStream(byteArray);
            }
        }
    } catch (IOException e) {
        log.error("Unable to get '" + resource + "' from '" + innerJarFileLocation + "' of '"
                + outerJarFile.getName() + "'", e);
    } finally {
        IOUtils.closeQuietly(tempOut);
        IOUtils.closeQuietly(innerInputStream);

        // close inner jar file before attempting to delete temporary file
        try {
            if (innerJarFile != null) {
                innerJarFile.close();
            }
        } catch (IOException e) {
            log.warn("Unable to close inner jarfile: " + innerJarFile, e);
        }

        // delete temporary file
        if (tempFile != null && !tempFile.delete()) {
            log.warn("Could not delete temporary jarfile: " + tempFile);
        }
    }
    return null;
}

From source file:com.eviware.soapui.plugins.JarClassLoader.java

private void addLibrariesIn(JarFile jarFile) throws IOException {
    if (containsLibraries(jarFile)) {
        File libDirectory = Tools.createTemporaryDirectory();
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            if (isLibrary(jarEntry)) {
                String fileName = jarEntry.getName().substring(LIB_PREFIX.length());
                File outputFile = new File(libDirectory, fileName);
                FileUtils.copyInputStreamToFile(jarFile.getInputStream(jarEntry), outputFile);
                this.addURL(outputFile.toURI().toURL());
            }// w  w w  .jav a2  s.  c  om
        }
    }
}

From source file:javadepchecker.Main.java

/**
 * Scan jar for classes to be processed by ASM
 *
 * @param jar jar file to be processed//from www.j  a  v a 2s.  c  o  m
 * @throws IOException
 */
public void processJar(JarFile jar) throws IOException {
    Collections.list(jar.entries()).stream()
            .filter((JarEntry entry) -> (!entry.isDirectory() && entry.getName().endsWith("class")))
            .forEach((JarEntry entry) -> {
                InputStream is = null;
                try {
                    Main.this.mCurrent.add(entry.getName());
                    is = jar.getInputStream(entry);
                    new ClassReader(is).accept(Main.this, 0);
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
}

From source file:com.krikelin.spotifysource.AppInstaller.java

protected void extractJar(String destDir, String jarFile) throws IOException {
    File destination = new File(destDir);
    java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile);
    java.util.Enumeration<JarEntry> enu = jar.entries();
    while (enu.hasMoreElements()) {
        try {/*from www  . ja v a 2  s .  c  o  m*/
            java.util.jar.JarEntry file = (java.util.jar.JarEntry) enu.nextElement();
            java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());
            if (file.isDirectory()) { // if its a directory, create it
                f.mkdir();
                continue;
            }
            java.io.InputStream is = jar.getInputStream(file); // get the input stream
            if (!(destination.exists())) {
                destination.createNewFile();
            }

            java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
            while (is.available() > 0) { // write contents of 'is' to 'fos'
                fos.write(is.read());
            }
            fos.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.taobao.android.apatch.MergePatch.java

private void fillManifest(Attributes main) throws IOException {
    JarFile jarFile;
    Manifest manifest;/*from w  ww. j  a  va  2  s . c  om*/
    StringBuffer fromBuffer = new StringBuffer();
    StringBuffer toBuffer = new StringBuffer();
    String from;
    String to;
    String name;
    // String classes;
    for (File file : patchs) {
        jarFile = new JarFile(file);
        JarEntry dexEntry = jarFile.getJarEntry("META-INF/PATCH.MF");
        manifest = new Manifest(jarFile.getInputStream(dexEntry));
        Attributes attributes = manifest.getMainAttributes();

        from = attributes.getValue("From-File");
        if (fromBuffer.length() > 0) {
            fromBuffer.append(',');
        }
        fromBuffer.append(from);
        to = attributes.getValue("To-File");
        if (toBuffer.length() > 0) {
            toBuffer.append(',');
        }
        toBuffer.append(to);

        name = attributes.getValue("Patch-Name");
        // classes = attributes.getValue(name + "-Patch-Classes");
        main.putValue(name + "-Patch-Classes", attributes.getValue(name + "-Patch-Classes"));
        main.putValue(name + "-Prepare-Classes", attributes.getValue(name + "-Prepare-Classes"));
        main.putValue(name + "-Used-Methods", attributes.getValue(name + "-Used-Methods"));
        main.putValue(name + "-Modified-Classes", attributes.getValue(name + "-Modified-Classes"));
        main.putValue(name + "-Used-Classes", attributes.getValue(name + "-Used-Classes"));
        main.putValue(name + "-add-classes", attributes.getValue(name + "-add-classes"));

    }
    main.putValue("From-File", fromBuffer.toString());
    main.putValue("To-File", toBuffer.toString());
}

From source file:com.palantir.gerrit.gerritci.servlets.JobsServlet.java

/**
 * Creates a new job on the specified Jenkins server with the specified name and configuration,
 * or updates the job with the specified name if it already exists on the server.
 *
 * @param jsc The Jenkins server to add the new job to.
 * @param name The name of the job to add.
 * @param type The JobType of the job to add.
 * @param params The configuration parameters for the new job.
 * @throws IOException// w ww  .  ja  va2 s. c o m
 * @throws RuntimeException if the job wasn't created for other reasons.
 */
public void createOrUpdateJob(JenkinsServerConfiguration jsc, String name, JobType type,
        Map<String, Object> params) throws IOException {
    JenkinsServer server = JenkinsProvider.getJenkinsServer(jsc);
    VelocityContext velocityContext = new VelocityContext(params);
    StringWriter writer = new StringWriter();
    JarFile jarFile = new JarFile(sitePaths.plugins_dir.getAbsoluteFile() + File.separator + "gerrit-ci.jar");
    if (params.get("junitEnabled").toString().equals("false")) {
        params.put("junitPath", "");
    }
    IOUtils.copy(jarFile.getInputStream(jarFile.getEntry("templates" + type.getTemplate())), writer);
    String jobTemplate = writer.toString();
    writer = new StringWriter();
    IOUtils.copy(jarFile.getInputStream(jarFile.getEntry("scripts/prebuild-commands.sh")), writer);
    // We must escape special characters as this will be rendered into XML
    String prebuildScript = writer.toString().replace("&", "&amp;").replace(">", "&gt;").replace("<", "&lt;");
    params.put("cleanCommands", prebuildScript);
    StringWriter xmlWriter = new StringWriter();
    Velocity.evaluate(velocityContext, xmlWriter, "", jobTemplate);
    String jobXml = xmlWriter.toString();
    jarFile.close();
    if (JenkinsProvider.jobExists(jsc, name)) {
        try {
            server.updateJob(name, jobXml, false);
        } catch (IOException e) {
            throw new RuntimeException(String.format("Failed to update Jenkins job: %s", name), e);
        }
    } else {
        try {
            server.createJob(name, jobXml, false);
        } catch (IOException e) {
            throw new RuntimeException(String.format("Failed to create Jenkins job: %s", name), e);
        }
    }
}