Example usage for java.util.jar JarFile close

List of usage examples for java.util.jar JarFile close

Introduction

In this page you can find the example usage for java.util.jar JarFile close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP file.

Usage

From source file:ie.deri.unlp.javaservices.topicextraction.topicextractor.gate.TopicExtractorGate.java

/**
 * /*www  .  j  a  v a2s  .c  o  m*/
 * Extract a directory in a JAR on the classpath to an output folder.
 * 
 * Note: User's responsibility to ensure that the files are actually in a JAR.
 * 
 * @param classInJar A class in the JAR file which is on the classpath
 * @param resourceDirectory Path to resource directory in JAR
 * @param outputDirectory Directory to write to  
 * @return String containing the path to the outputDirectory
 * @throws IOException
 */
private static String extractDirectoryFromClasspathJAR(Class<?> classInJar, String resourceDirectory,
        String outputDirectory) throws IOException {

    resourceDirectory = StringUtils.strip(resourceDirectory, "\\/") + File.separator;

    URL jar = classInJar.getProtectionDomain().getCodeSource().getLocation();
    JarFile jarFile = new JarFile(new File(jar.getFile()));

    byte[] buf = new byte[1024];
    Enumeration<JarEntry> jarEntries = jarFile.entries();
    while (jarEntries.hasMoreElements()) {
        JarEntry jarEntry = jarEntries.nextElement();
        if (jarEntry.isDirectory() || !jarEntry.getName().startsWith(resourceDirectory)) {
            continue;
        }

        String outputFileName = FilenameUtils.concat(outputDirectory, jarEntry.getName());
        //Create directories if they don't exist
        new File(FilenameUtils.getFullPath(outputFileName)).mkdirs();

        //Write file
        FileOutputStream fileOutputStream = new FileOutputStream(outputFileName);
        int n;
        InputStream is = jarFile.getInputStream(jarEntry);
        while ((n = is.read(buf, 0, 1024)) > -1) {
            fileOutputStream.write(buf, 0, n);
        }
        is.close();
        fileOutputStream.close();
    }
    jarFile.close();

    String fullPath = FilenameUtils.concat(outputDirectory, resourceDirectory);
    return fullPath;
}

From source file:Main.java

static boolean isTheUpdateForMe(File path) {

    JarFile jar;
    try {/*from w ww  .  j  av  a2s  .  c o  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:UnpackedJarFile.java

public static void close(JarFile thing) {
    if (thing != null) {
        try {/*w  w  w  .  j a  va2 s.c  o  m*/
            thing.close();
        } catch (Exception ignored) {
        }
    }
}

From source file:org.wso2.carbon.integration.framework.utils.CodeCoverageUtils.java

private synchronized static void addEmmaDynamicImportPackage(String jarFilePath) throws IOException {
    if (!jarFilePath.endsWith(".jar")) {
        throw new IllegalArgumentException(
                "Jar file should have the extension .jar. " + jarFilePath + " is invalid");
    }/*from   w w  w  .  j  a  v a 2s  .c o  m*/
    JarFile jarFile = new JarFile(jarFilePath);
    Manifest manifest = jarFile.getManifest();
    if (manifest == null) {
        throw new IllegalArgumentException(jarFilePath + " does not contain a MANIFEST.MF file");
    }
    String fileSeparator = (File.separatorChar == '\\') ? "\\" : File.separator;
    String jarFileName = jarFilePath;
    if (jarFilePath.lastIndexOf(fileSeparator) != -1) {
        jarFileName = jarFilePath.substring(jarFilePath.lastIndexOf(fileSeparator) + 1);
    }
    ArchiveManipulator archiveManipulator;
    String tempExtractedDir;
    try {
        archiveManipulator = new ArchiveManipulator();
        tempExtractedDir = System.getProperty("basedir") + File.separator + "target" + File.separator
                + jarFileName.substring(0, jarFileName.lastIndexOf('.'));
        new ArchiveManipulatorUtil().extractFile(jarFilePath, tempExtractedDir);
    } finally {
        jarFile.close();
    }

    String dynamicImports = manifest.getMainAttributes().getValue("DynamicImport-Package");
    if (dynamicImports != null) {
        manifest.getMainAttributes().putValue("DynamicImport-Package", dynamicImports + ",com.vladium.*");
    } else {
        manifest.getMainAttributes().putValue("DynamicImport-Package", "com.vladium.*");
    }
    File newManifest = new File(
            tempExtractedDir + File.separator + "META-INF" + File.separator + "MANIFEST.MF");
    FileOutputStream manifestOut = null;
    try {
        manifestOut = new FileOutputStream(newManifest);
        manifest.write(manifestOut);
    } catch (IOException e) {
        log.error("Could not write content to new MANIFEST.MF file", e);
    } finally {
        if (manifestOut != null) {
            manifestOut.close();
        }
    }
    archiveManipulator.archiveDir(jarFilePath, tempExtractedDir);
    FileManipulator.deleteDir(tempExtractedDir);
}

From source file:org.jahia.configuration.modules.ModuleDeployer.java

private void copyDbScripts(File warFile, File targetDir) {
    JarFile war = null;
    try {//from   w  ww . jav  a 2s.com
        war = new JarFile(warFile);
        if (war.getJarEntry("META-INF/db") != null) {
            war.close();
            ZipUnArchiver unarch = new ZipUnArchiver(warFile);
            File tmp = new File(FileUtils.getTempDirectory(), String.valueOf(System.currentTimeMillis()));
            tmp.mkdirs();
            File destDir = new File(targetDir, "db/sql/schema");
            try {
                unarch.extract("META-INF/db", tmp);
                FileUtils.copyDirectory(new File(tmp, "META-INF/db"), destDir);
            } finally {
                FileUtils.deleteQuietly(tmp);
            }
            logger.info("Copied database scripts from " + warFile.getName() + " to " + destDir);
        }
    } catch (Exception e) {
        logger.error("Error copying database scripts for module " + warFile, e);
    } finally {
        if (war != null) {
            try {
                war.close();
            } catch (Exception e) {
                logger.warn("Unable to close the JAR file " + warFile, e);
            }
        }
    }
}

From source file:org.mule.util.JarUtils.java

public static LinkedHashMap readJarFileEntries(File jarFile) throws Exception {
    LinkedHashMap entries = new LinkedHashMap();
    JarFile jarFileWrapper = null;
    if (jarFile != null) {
        logger.debug("Reading jar entries from " + jarFile.getAbsolutePath());
        try {/*from   w  ww .j av a2s. co m*/
            jarFileWrapper = new JarFile(jarFile);
            Enumeration iter = jarFileWrapper.entries();
            while (iter.hasMoreElements()) {
                ZipEntry zipEntry = (ZipEntry) iter.nextElement();
                InputStream entryStream = jarFileWrapper.getInputStream(zipEntry);
                ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
                try {
                    IOUtils.copy(entryStream, byteArrayStream);
                    entries.put(zipEntry.getName(), byteArrayStream.toByteArray());
                    logger.debug("Read jar entry " + zipEntry.getName() + " from " + jarFile.getAbsolutePath());
                } finally {
                    byteArrayStream.close();
                }
            }
        } finally {
            if (jarFileWrapper != null) {
                try {
                    jarFileWrapper.close();
                } catch (Exception ignore) {
                    logger.debug(ignore);
                }
            }
        }
    }
    return entries;
}

From source file:org.pepstock.jem.node.NodeInfoUtility.java

/**
 * Extracts from manifest file the attribute passed by argument 
 * @param what name of attribute to get/*from www . j  a v a  2  s. com*/
 * @return attribute value or null, if doesn't exist
 */
public static String getManifestAttribute(String what) {
    JarFile jarFile = null;
    try {
        // gets JAR file
        jarFile = new JarFile(new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()));

        // gets attributes
        Attributes at = (Attributes) jarFile.getManifest().getAttributes(ConfigKeys.JEM_MANIFEST_SECTION);
        // gets version
        return at.getValue(ConfigKeys.JEM_MANIFEST_VERSION);
    } catch (IOException e) {
        // ignore the stack trace
        LogAppl.getInstance().ignore(e.getMessage(), e);
        LogAppl.getInstance().emit(NodeMessage.JEMC184W);
    } catch (URISyntaxException e) {
        // ignore the stack trace
        LogAppl.getInstance().ignore(e.getMessage(), e);
        LogAppl.getInstance().emit(NodeMessage.JEMC184W);
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {
                // debug
                LogAppl.getInstance().debug(e.getMessage(), e);
            }
        }
    }
    return null;
}

From source file:ml.shifu.shifu.util.ShifuCLI.java

/**
 * print version info for shifu/*from   w  w  w.  ja  va 2 s  . co  m*/
 */
private static void printVersionString() {
    String findContainingJar = JarManager.findContainingJar(ShifuCLI.class);
    JarFile jar = null;
    try {
        jar = new JarFile(findContainingJar);
        final Manifest manifest = jar.getManifest();

        String vendor = manifest.getMainAttributes().getValue("vendor");
        String title = manifest.getMainAttributes().getValue("title");
        String version = manifest.getMainAttributes().getValue("version");
        String timestamp = manifest.getMainAttributes().getValue("timestamp");
        System.out.println(vendor + " " + title + " version " + version + " \ncompiled " + timestamp);
    } catch (Exception e) {
        throw new RuntimeException("unable to read pigs manifest file", e);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
                throw new RuntimeException("jar closed failed", e);
            }
        }
    }
}

From source file:com.magnet.tools.tests.MagnetToolStepDefs.java

@Then("^the jar \"([^\"]*)\" should not contain any matches for:$")
public static void and_the_jar_should_not_contain_any_matches_for(String file, List<String> patterns)
        throws Throwable {
    the_file_should_exist(file);//w ww.  j a v a  2s  . co  m
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(file);
        Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
        StringBuilder matchList = new StringBuilder();
        JarEntry currentEntry;
        while (jarEntryEnumeration.hasMoreElements()) {
            currentEntry = jarEntryEnumeration.nextElement();
            for (String pattern : patterns) {
                if (currentEntry.getName().matches(pattern)) {
                    matchList.append(currentEntry.getName());
                    matchList.append("\n");
                }
            }
        }
        String matchedStrings = matchList.toString();
        Assert.assertTrue("The jar " + file + "contained\n" + matchedStrings, matchedStrings.isEmpty());

    } finally {
        if (null != jarFile) {
            try {
                jarFile.close();
            } catch (Exception e) {
                /* do nothing */ }
        }
    }
}

From source file:org.apache.bcel.BCELBenchmark.java

/**
 * Baseline benchmark. Read the classes but don't parse them.
 *//*from www  .j  a  v a2s . c  o m*/
@Benchmark
public void baseline(Blackhole bh) throws IOException {
    JarFile jar = getJarFile();

    for (JarEntry entry : getClasses(jar)) {
        byte[] bytes = IOUtils.toByteArray(jar.getInputStream(entry));
        bh.consume(bytes);
    }

    jar.close();
}