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.owasp.dependencycheck.xml.pom.PomUtils.java

/**
 * Retrieves the specified POM from a jar file and converts it to a Model.
 *
 * @param path the path to the pom.xml file within the jar file
 * @param jar the jar file to extract the pom from
 * @return returns an object representation of the POM
 * @throws AnalysisException is thrown if there is an exception extracting
 * or parsing the POM {@link Model} object
 *//*  w ww.j  a va 2 s . c  o  m*/
public static Model readPom(String path, JarFile jar) throws AnalysisException {
    final ZipEntry entry = jar.getEntry(path);
    Model model = null;
    if (entry != null) { //should never be null
        //noinspection CaughtExceptionImmediatelyRethrown
        try {
            final PomParser parser = new PomParser();
            model = parser.parse(jar.getInputStream(entry));
            if (model == null) {
                throw new AnalysisException(String.format("Unable to parse pom '%s/%s'", jar.getName(), path));
            }
        } catch (AnalysisException ex) {
            throw ex;
        } catch (SecurityException ex) {
            LOGGER.warn("Unable to parse pom '{}' in jar '{}'; invalid signature", path, jar.getName());
            LOGGER.debug("", ex);
            throw new AnalysisException(ex);
        } catch (IOException ex) {
            LOGGER.warn("Unable to parse pom '{}' in jar '{}' (IO Exception)", path, jar.getName());
            LOGGER.debug("", ex);
            throw new AnalysisException(ex);
        } catch (Throwable ex) {
            LOGGER.warn("Unexpected error during parsing of the pom '{}' in jar '{}'", path, jar.getName());
            LOGGER.debug("", ex);
            throw new AnalysisException(ex);
        }
    }
    return model;
}

From source file:com.aliyun.odps.local.common.utils.ArchiveUtils.java

@SuppressWarnings("rawtypes")
public static void unJar(File jarFile, File toDir) throws IOException {
    JarFile jar = new JarFile(jarFile);
    try {/*  w w w.  ja v a 2 s  .c o  m*/
        Enumeration entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream in = jar.getInputStream(entry);
                try {
                    File file = new File(toDir, entry.getName());
                    if (!file.getParentFile().mkdirs()) {
                        if (!file.getParentFile().isDirectory()) {
                            throw new IOException("Mkdirs failed to create " + file.getParentFile().toString());
                        }
                    }
                    OutputStream out = new FileOutputStream(file);
                    try {
                        byte[] buffer = new byte[8192];
                        int i;
                        while ((i = in.read(buffer)) != -1) {
                            out.write(buffer, 0, i);
                        }
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
            }
        }
    } finally {
        jar.close();
    }
}

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

/**
 * Expands a jar file into a given directory, given the jar file and the
 * directory into which the contents should be written.
 * //from w  ww  . j av  a 2  s.co m
 * @throw IOException Upon error expanding the Jar file
 */
public static void expandJar(JarFile jarFile, File root) throws IOException {
    /*
     * Loop through each entry, fetchs its input stream, and write to an
     * output stream for the file.
     */
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements() == true) {
        JarEntry entry = entries.nextElement();
        InputStream is = jarFile.getInputStream(entry);
        String entryName = entry.getName();

        /* 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);
        FileOutputStream os = new FileOutputStream(file);
        byte[] b = new byte[CHUNK_SIZE];
        while (true) {
            int len = is.read(b);
            if (len == -1) {
                break;
            }
            os.write(b, 0, len);
        }
        is.close();
        os.close();
    }
}

From source file:org.phenotips.variantstore.shared.ResourceManager.java

/**
 * Copy resources recursively from a folder specified by source in a jar file specified by jarPath
 * to a destination folder on the filesystem dest.
 *
 * @param jarPath the jar file/*from  ww w.  java  2  s.com*/
 * @param source  the folder on the filesystem
 * @param dest    the destination
 * @throws IOException
 */
private static void copyResourcesFromJar(Path jarPath, Path source, Path dest) throws IOException {
    JarFile jar = new JarFile(jarPath.toFile());

    for (JarEntry entry : Collections.list(jar.entries())) {

        if (entry.getName().startsWith(source.toString())) {
            if (entry.isDirectory()) {
                Files.createDirectory(dest.resolve(entry.getName()));
            } else {
                Files.copy(jar.getInputStream(entry), dest.resolve(entry.getName()));
            }
        }

    }
}

From source file:net.fabricmc.loader.FabricLoader.java

protected static ModInfo[] getJarMods(File f) {
    try {//from w w  w  .  j a v  a 2s  . c o m
        JarFile jar = new JarFile(f);
        ZipEntry entry = jar.getEntry("mod.json");
        if (entry != null) {
            try (InputStream in = jar.getInputStream(entry)) {
                return getMods(in);
            }
        }

    } catch (Exception e) {
        LOGGER.error("Unable to load mod from %s", f.getName());
        e.printStackTrace();
    }

    return new ModInfo[0];
}

From source file:Main.java

static boolean isTheUpdateForMe(File path) {

    JarFile jar;
    try {//  w w w .j  a  v  a 2s  . co  m
        jar = new JarFile(path);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        return false;
    }

    ZipEntry entry = jar.getEntry("system/build.prop");
    final String myDevice = "ro.product.device=" + Build.DEVICE;
    boolean finded = false;

    if (entry != null) {
        try {
            InputStreamReader bi = new InputStreamReader(jar.getInputStream(entry));

            BufferedReader br = new BufferedReader(bi);

            String line;
            Pattern p = Pattern.compile(myDevice);
            do {
                line = br.readLine();
                if (line == null) {
                    break;
                }

                Matcher m = p.matcher(line);
                if (m.find()) {
                    finded = true;
                    break;
                }
            } while (true);

            bi.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }
    try {
        jar.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return finded;
}

From source file:org.primeframework.mvc.util.ClassClasspathResolver.java

/**
 * Attempts to load the JarEntry into a ClassReader.
 *
 * @param jar      The JAR file that the entry is in.
 * @param jarFile  The JAR file used to get the InputStream to the entry.
 * @param jarEntry The JAR entry to load.
 * @return The ClassReader and never null.
 * @throws IOException If the JarEntry doesn't point to a valid class.
 *///from  w  ww.j  a  v a  2s.  co  m
public static ClassReader load(File jar, JarFile jarFile, JarEntry jarEntry) throws IOException {
    try {
        return new ClassReader(jarFile.getInputStream(jarEntry));
    } catch (IOException e) {
        throw new IOException(
                "Error parsing class file at [" + jar.getAbsolutePath() + "!/" + jarEntry.getName() + "]", e);
    }
}

From source file:org.reprap.configuration.store.ConfigurationInitializer.java

private static void copyJarTree(final URL source, final File target) throws IOException {
    final JarURLConnection jarConnection = (JarURLConnection) source.openConnection();
    final String prefix = jarConnection.getEntryName();
    final JarFile jarFile = jarConnection.getJarFile();
    for (final JarEntry jarEntry : Collections.list(jarFile.entries())) {
        final String entryName = jarEntry.getName();
        if (entryName.startsWith(prefix)) {
            if (!jarEntry.isDirectory()) {
                final String fileName = StringUtils.removeStart(entryName, prefix);
                final InputStream fileStream = jarFile.getInputStream(jarEntry);
                try {
                    FileUtils.copyInputStreamToFile(fileStream, new File(target, fileName));
                } finally {
                    fileStream.close();/*from ww  w  . j  av a  2s  . c  o  m*/
                }
            }
        }
    }
}

From source file:com.jhash.oimadmin.Utils.java

public static String readFileInJar(JarFile jarFile, JarEntry file) {
    StringBuilder readFileData = new StringBuilder();
    try (BufferedReader jarFileInputStream = new BufferedReader(
            new InputStreamReader(jarFile.getInputStream(file)))) {
        String readLine;/*from  w ww  .  j  a  v  a2 s  . c o  m*/
        while ((readLine = jarFileInputStream.readLine()) != null) {
            readFileData.append(readLine);
            readFileData.append(System.lineSeparator());
        }
    } catch (Exception exception) {
        throw new OIMAdminException("Failed to read file " + file + " in jar file " + jarFile.getName(),
                exception);
    }
    return readFileData.toString();
}

From source file:com.kantenkugel.discordbot.moduleutils.DocParser.java

private static void parse() {
    LOG.info("Parsing source-file");
    try {/*from  w  w w. java 2  s  . c o m*/
        JarFile file = new JarFile(LOCAL_SRC_PATH.toFile());
        file.stream().filter(entry -> !entry.isDirectory() && entry.getName().startsWith(JDA_CODE_BASE)
                && entry.getName().endsWith(".java")).forEach(entry -> {
                    try {
                        parse(entry.getName(), file.getInputStream(entry));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
        LOG.info("Done parsing source-file");
    } catch (IOException e) {
        LOG.log(e);
    }
}