Example usage for java.util.jar JarInputStream getNextJarEntry

List of usage examples for java.util.jar JarInputStream getNextJarEntry

Introduction

In this page you can find the example usage for java.util.jar JarInputStream getNextJarEntry.

Prototype

public JarEntry getNextJarEntry() throws IOException 

Source Link

Document

Reads the next JAR file entry and positions the stream at the beginning of the entry data.

Usage

From source file:org.diffkit.common.DKUnjar.java

/**
 * closes inputStream_ at the end/*w  ww  . ja v a  2s  .c  o  m*/
 */
public static void unjar(JarInputStream inputStream_, File outputDir_) throws IOException {
    DKValidate.notNull(inputStream_, outputDir_);
    if (!outputDir_.isDirectory())
        throw new RuntimeException(String.format("directory does not exist->%s", outputDir_));

    JarEntry entry = null;
    while ((entry = inputStream_.getNextJarEntry()) != null) {
        File outFile = new File(outputDir_, entry.getName());
        OutputStream outStream = new BufferedOutputStream(new FileOutputStream(outFile));
        DKStreamUtil.copy(inputStream_, outStream);
        outStream.flush();
        outStream.close();
    }
    inputStream_.close();
}

From source file:com.dragome.callbackevictor.serverside.utils.RewritingUtils.java

public static boolean rewriteJar(final JarInputStream pInput, final ResourceTransformer transformer,
        final JarOutputStream pOutput, final Matcher pMatcher) throws IOException {

    boolean changed = false;

    while (true) {
        final JarEntry entry = pInput.getNextJarEntry();

        if (entry == null) {
            break;
        }/*  w  w  w  . j av a 2 s  .co m*/

        if (entry.isDirectory()) {
            pOutput.putNextEntry(new JarEntry(entry));
            continue;
        }

        final String name = entry.getName();

        pOutput.putNextEntry(new JarEntry(name));

        if (name.endsWith(".class")) {
            if (pMatcher.isMatching(name)) {

                if (log.isDebugEnabled()) {
                    log.debug("transforming " + name);
                }

                final byte[] original = toByteArray(pInput);

                byte[] transformed = transformer.transform(original);

                pOutput.write(transformed);

                changed |= transformed.length != original.length;

                continue;
            }
        } else if (name.endsWith(".jar") || name.endsWith(".ear") || name.endsWith(".zip")
                || name.endsWith(".war")) {

            changed |= rewriteJar(new JarInputStream(pInput), transformer, new JarOutputStream(pOutput),
                    pMatcher);

            continue;
        }

        int length = copy(pInput, pOutput);

        log.debug("copied " + name + "(" + length + ")");
    }

    pInput.close();
    pOutput.close();

    return changed;
}

From source file:bs.java

private static void loadable(String filename) {
    File file = new File(filename);

    JarInputStream is;
    try {//from w  ww.  j  a  v a  2  s .  c  o  m
        ClassLoader loader = URLClassLoader.newInstance(new URL[] { file.toURI().toURL() });
        is = new JarInputStream(new FileInputStream(file));
        JarEntry entry;
        while ((entry = is.getNextJarEntry()) != null) {
            if (entry.getName().endsWith(".class") && !entry.getName().contains("/")) {
                Class<?> cls = Class.forName(FilenameUtils.removeExtension(entry.getName()), false, loader);
                for (Class<?> i : cls.getInterfaces()) {
                    if (i.equals(Loadable.class)) {
                        Loadable l = (Loadable) cls.newInstance();
                        Bs.addModule(l);
                    }
                }
            }
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

From source file:com.threecrickets.jygments.grammar.Lexer.java

public static Lexer getForFileName(String fileName) throws ResolutionException {
    if (lexerMap.isEmpty()) {
        try {//from w ww  .java2s  .  c o m
            File jarFile = new File(Jygments.class.getProtectionDomain().getCodeSource().getLocation().toURI());
            JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile));
            try {
                for (JarEntry jarEntry = jarInputStream
                        .getNextJarEntry(); jarEntry != null; jarEntry = jarInputStream.getNextJarEntry()) {
                    if (jarEntry.getName().endsWith(".json")) {
                        String lexerName = jarEntry.getName();
                        // strip off the .json
                        lexerName = lexerName.substring(0, lexerName.length() - 5);
                        Lexer lexer = Lexer.getByFullName(lexerName);
                        for (String filename : lexer.filenames)
                            if (filename.startsWith("*."))
                                lexerMap.put(filename.substring(filename.lastIndexOf('.')), lexer);
                    }
                }
            } finally {
                jarInputStream.close();
            }
        } catch (URISyntaxException x) {
            throw new ResolutionException(x);
        } catch (FileNotFoundException x) {
            throw new ResolutionException(x);
        } catch (IOException x) {
            throw new ResolutionException(x);
        }
    }

    return lexerMap.get(fileName.substring(fileName.lastIndexOf('.')));
}

From source file:net.ftb.util.FileUtils.java

/**
 * deletes the META-INF//w  ww.j av  a  2  s . c  o  m
 */
public static void killMetaInf() {
    File inputFile = new File(Settings.getSettings().getInstallPath() + "/" + ModPack.getSelectedPack().getDir()
            + "/minecraft/bin", "minecraft.jar");
    File outputTmpFile = new File(Settings.getSettings().getInstallPath() + "/"
            + ModPack.getSelectedPack().getDir() + "/minecraft/bin", "minecraft.jar.tmp");
    try {
        JarInputStream input = new JarInputStream(new FileInputStream(inputFile));
        JarOutputStream output = new JarOutputStream(new FileOutputStream(outputTmpFile));
        JarEntry entry;

        while ((entry = input.getNextJarEntry()) != null) {
            if (entry.getName().contains("META-INF")) {
                continue;
            }
            output.putNextEntry(entry);
            byte buffer[] = new byte[1024];
            int amo;
            while ((amo = input.read(buffer, 0, 1024)) != -1) {
                output.write(buffer, 0, amo);
            }
            output.closeEntry();
        }

        input.close();
        output.close();

        if (!inputFile.delete()) {
            Logger.logError("Failed to delete Minecraft.jar.");
            return;
        }
        outputTmpFile.renameTo(inputFile);
    } catch (FileNotFoundException e) {
        Logger.logError("Error while killing META-INF", e);
    } catch (IOException e) {
        Logger.logError("Error while killing META-INF", e);
    }
}

From source file:fll.xml.XMLUtils.java

/**
 * Get all challenge descriptors build into the software.
 *///  w  w w.j ava 2  s.  c  o  m
public static Collection<URL> getAllKnownChallengeDescriptorURLs() {
    final String baseDir = "fll/resources/challenge-descriptors/";

    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    final URL directory = classLoader.getResource(baseDir);
    if (null == directory) {
        LOGGER.warn("base dir for challenge descriptors not found");
        return Collections.emptyList();
    }

    final Collection<URL> urls = new LinkedList<URL>();
    if ("file".equals(directory.getProtocol())) {
        try {
            final URI uri = directory.toURI();
            final File fileDir = new File(uri);
            final File[] files = fileDir.listFiles();
            if (null != files) {
                for (final File file : files) {
                    if (file.getName().endsWith(".xml")) {
                        try {
                            final URL fileUrl = file.toURI().toURL();
                            urls.add(fileUrl);
                        } catch (final MalformedURLException e) {
                            LOGGER.error("Unable to convert file to URL: " + file.getAbsolutePath(), e);
                        }
                    }
                }
            }
        } catch (final URISyntaxException e) {
            LOGGER.error("Unable to convert URL to URI: " + e.getMessage(), e);
        }
    } else if (directory.getProtocol().equals("jar")) {
        final CodeSource src = XMLUtils.class.getProtectionDomain().getCodeSource();
        if (null != src) {
            final URL jar = src.getLocation();

            JarInputStream zip = null;
            try {
                zip = new JarInputStream(jar.openStream());

                JarEntry ze = null;
                while ((ze = zip.getNextJarEntry()) != null) {
                    final String entryName = ze.getName();
                    if (entryName.startsWith(baseDir) && entryName.endsWith(".xml")) {
                        // add 1 to baseDir to skip past the path separator
                        final String challengeName = entryName.substring(baseDir.length());

                        // check that the file really exists and turn it into a URL
                        final URL challengeUrl = classLoader.getResource(baseDir + challengeName);
                        if (null != challengeUrl) {
                            urls.add(challengeUrl);
                        } else {
                            // TODO could write the resource out to a temporary file if
                            // needed
                            // then mark the file as delete on exit
                            LOGGER.warn("URL doesn't exist for " + baseDir + challengeName + " entry: "
                                    + entryName);
                        }
                    }
                }

                zip.close();
            } catch (final IOException e) {
                LOGGER.error("Error reading jar file at: " + jar.toString(), e);
            } finally {
                IOUtils.closeQuietly(zip);
            }

        } else {
            LOGGER.warn("Null code source in protection domain, cannot get challenge descriptors");
        }
    } else {
        throw new UnsupportedOperationException("Cannot list files for URL " + directory);

    }

    return urls;

}

From source file:WarUtil.java

/**
 * WAR???????????//from   w w  w.  j a  va2  s.com
 * 
 * @param warFile
 * @param directory
 * @throws IOException
 */
public static void extractWar(File warFile, File directory) throws IOException {
    try {
        long timestamp = warFile.lastModified();
        File warModifiedTimeFile = new File(directory, LAST_MODIFIED_FILE);
        long lastModified = readLastModifiled(warModifiedTimeFile);

        if (timestamp == lastModified) {
            //      log.info("war file " + warFile.getName() + " not modified.");
            return;
        }
        if (directory.exists()) {
            //         IOUtil.forceRemoveDirectory(directory);
            directory.mkdir();
        }

        //         log.info("war extract start. warfile=" + warFile.getName());

        JarInputStream jin = new JarInputStream(new BufferedInputStream(new FileInputStream(warFile)));
        JarEntry entry = null;

        while ((entry = jin.getNextJarEntry()) != null) {
            File file = new File(directory, entry.getName());

            if (entry.isDirectory()) {
                if (!file.exists()) {
                    file.mkdirs();
                }
            } else {
                File dir = new File(file.getParent());
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                FileOutputStream fout = null;
                try {
                    fout = new FileOutputStream(file);
                    ResourceUtil.copyStream(jin, fout);
                } finally {
                    fout.flush();
                    fout.close();
                    fout = null;
                }

                if (entry.getTime() >= 0) {
                    file.setLastModified(entry.getTime());
                }
            }
        }

        writeLastModifiled(warModifiedTimeFile, timestamp);

        //log.info("war extract success. lastmodified=" + timestamp);
    } catch (IOException ioe) {
        //log.info("war extract fail.");
        throw ioe;
    }
}

From source file:ArchiveUtil.java

/**
 * Extracts the file {@code archive} to the target dir {@code targetDir} and deletes the 
 * files extracted upon jvm exit if the flag {@code deleteOnExit} is true.
 *//*from ww  w  .j  a  v  a 2 s  .c om*/
public static boolean extract(URL archive, File targetDir, boolean deleteOnExit) throws IOException {
    String archiveStr = archive.toString();
    String jarEntry = null;
    int idx = archiveStr.indexOf("!/");
    if (idx != -1) {
        if (!archiveStr.startsWith("jar:") && archiveStr.length() == idx + 2)
            return false;
        archive = new URL(archiveStr.substring(4, idx));
        jarEntry = archiveStr.substring(idx + 2);
    } else if (!isSupported(archiveStr))
        return false;

    JarInputStream jis = new JarInputStream(archive.openConnection().getInputStream());
    if (!targetDir.exists())
        targetDir.mkdirs();
    JarEntry entry = null;
    while ((entry = jis.getNextJarEntry()) != null) {
        String entryName = entry.getName();
        File entryFile = new File(targetDir, entryName);
        if (!entry.isDirectory()) {
            if (jarEntry == null || entryName.startsWith(jarEntry)) {
                if (!entryFile.exists() || entryFile.lastModified() != entry.getTime())
                    extractEntry(entryFile, jis, entry, deleteOnExit);
            }
        }
    }
    try {
        jis.close();
    } catch (Exception e) {
    }
    return true;
}

From source file:org.bimserver.plugins.VirtualFile.java

public static VirtualFile fromJar(InputStream inputStream) throws IOException {
    VirtualFile result = new VirtualFile();
    JarInputStream jarInputStream = new JarInputStream(inputStream);
    JarEntry jarEntry = jarInputStream.getNextJarEntry();
    while (jarEntry != null) {
        String n = jarEntry.getName();
        n = n.replace("/", File.separator);
        n = n.replace("\\", File.separator);
        VirtualFile newFile = result.createFile(n);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        IOUtils.copy(jarInputStream, byteArrayOutputStream);
        newFile.setData(byteArrayOutputStream.toByteArray());
        jarEntry = jarInputStream.getNextJarEntry();
    }// www  . j  a  va 2s . c  o m
    return result;
}

From source file:org.springframework.data.hadoop.mapreduce.ExecutionUtils.java

private static boolean isLegacyJar(Resource jar) throws IOException {
    JarInputStream jis = new JarInputStream(jar.getInputStream());
    JarEntry entry = null;//w ww.  j  a v a 2 s.  c om
    try {
        while ((entry = jis.getNextJarEntry()) != null) {
            String name = entry.getName();
            if (name.startsWith("lib/") //|| name.startsWith("classes/")
            ) {
                return true;
            }
        }
    } finally {
        IOUtils.closeStream(jis);
    }
    return false;
}