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:com.app.server.util.ClassLoaderUtil.java

public static CopyOnWriteArrayList closeClassLoader(ClassLoader cl) {
    CopyOnWriteArrayList jars = new CopyOnWriteArrayList();
    boolean res = false;
    Class classURLClassLoader = null;
    if (cl instanceof URLClassLoader) {
        classURLClassLoader = URLClassLoader.class;
        if (cl instanceof WebClassLoader) {
            String url = "";
            CopyOnWriteArrayList webCLUrl = ((WebClassLoader) cl).geturlS();
            for (int index = 0; index < webCLUrl.size(); index++) {

                try {
                    url = ((URL) webCLUrl.get(index)).toURI().toString();
                } catch (URISyntaxException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }//  w  w  w.  j a v  a  2 s. c  o  m
                jars.add(url.replace("file:", "").replace("/", "\\").toUpperCase());
            }
        }
    } else if (cl instanceof VFSClassLoader) {
        classURLClassLoader = VFSClassLoader.class;
    }
    Field f = null;
    try {
        f = classURLClassLoader.getDeclaredField("ucp");
        //log.info(f);
    } catch (NoSuchFieldException e1) {
        // e1.printStackTrace();
        // log.info(e1.getMessage(), e1);

    }
    if (f != null) {
        f.setAccessible(true);
        Object obj = null;
        try {
            obj = f.get(cl);
        } catch (IllegalAccessException e1) {
            // e1.printStackTrace();
            // log.info(e1.getMessage(), e1);
        }
        if (obj != null) {
            final Object ucp = obj;
            f = null;
            try {
                f = ucp.getClass().getDeclaredField("loaders");
                //log.info(f);
            } catch (NoSuchFieldException e1) {
                // e1.printStackTrace();
                // log.info(e1.getMessage(), e1);
            }
            if (f != null) {
                f.setAccessible(true);
                ArrayList loaders = null;
                try {
                    loaders = (ArrayList) f.get(ucp);
                    res = true;
                } catch (IllegalAccessException e1) {
                    // e1.printStackTrace();
                }
                for (int i = 0; loaders != null && i < loaders.size(); i++) {
                    obj = loaders.get(i);
                    f = null;
                    try {
                        f = obj.getClass().getDeclaredField("jar");
                        // log.info(f);
                    } catch (NoSuchFieldException e) {
                        // e.printStackTrace();
                        // log.info(e.getMessage(), e);
                    }
                    if (f != null) {
                        f.setAccessible(true);
                        try {
                            obj = f.get(obj);
                        } catch (IllegalAccessException e1) {
                            // e1.printStackTrace();
                            // log.info(e1.getMessage(), e1);
                        }
                        if (obj instanceof JarFile) {
                            final JarFile jarFile = (JarFile) obj;
                            //log.info(jarFile.getName());
                            jars.add(jarFile.getName().replace("/", "\\").trim().toUpperCase());
                            // try {
                            // jarFile.getManifest().clear();
                            // } catch (IOException e) {
                            // // ignore
                            // }
                            try {
                                jarFile.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                                // ignore
                                // log.info(e.getMessage(), e);
                            }
                        }
                    }
                }
            }
        }
    }
    return jars;
}

From source file:org.hyperic.hq.plugin.jboss.JBossDetector.java

public static String getVersion(File installPath, String jar) {
    File file = new File(installPath, "lib" + File.separator + jar);

    if (!file.exists()) {
        log.debug("[getVersion] file '" + file + "' not found");
        return null;
    }//from w  w  w  . ja v  a2 s .c  om

    Attributes attributes;
    try {
        JarFile jarFile = new JarFile(file);
        log.debug("[getVersion] jarFile='" + jarFile.getName() + "'");
        attributes = jarFile.getManifest().getMainAttributes();
        jarFile.close();
    } catch (IOException e) {
        log.debug(e, e);
        return null;
    }

    //e.g. Implementation-Version:
    //3.0.6 Date:200301260037
    //3.2.1 (build: CVSTag=JBoss_3_2_1 date=200306201521)
    //3.2.2 (build: CVSTag=JBoss_3_2_2 date=200310182216)
    //3.2.3 (build: CVSTag=JBoss_3_2_3 date=200311301445)
    //4.0.0DR2 (build: CVSTag=JBoss_4_0_0_DR2 date=200307030107)
    //5.0.1.GA (build: SVNTag=JBoss_5_0_1_GA date=200902231221)
    String version = attributes.getValue("Implementation-Version");
    log.debug("[getVersion] version='" + version + "'");

    if (version == null) {
        return null;
    }
    if (version.length() < 3) {
        return null;
    }

    if (!(Character.isDigit(version.charAt(0)) && (version.charAt(1) == '.')
            && Character.isDigit(version.charAt(2)))) {
        return null;
    }

    return version;
}

From source file:org.apache.hadoop.util.TestClasspath.java

/**
 * Asserts that the specified file is a jar file with a manifest containing a
 * non-empty classpath attribute./*from  w  w  w .j av a  2s.  c  o  m*/
 *
 * @param file File to check
 * @throws IOException if there is an I/O error
 */
private static void assertJar(File file) throws IOException {
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(file);
        Manifest manifest = jarFile.getManifest();
        assertNotNull(manifest);
        Attributes mainAttributes = manifest.getMainAttributes();
        assertNotNull(mainAttributes);
        assertTrue(mainAttributes.containsKey(Attributes.Name.CLASS_PATH));
        String classPathAttr = mainAttributes.getValue(Attributes.Name.CLASS_PATH);
        assertNotNull(classPathAttr);
        assertFalse(classPathAttr.isEmpty());
    } finally {
        // It's too bad JarFile doesn't implement Closeable.
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {
                LOG.warn("exception closing jarFile: " + jarFile, e);
            }
        }
    }
}

From source file:JarUtil.java

/**
 * Adds the given file to the specified JAR file.
 * // w w w. j ava 2  s .c om
 * @param file
 *            the file that should be added
 * @param jarFile
 *            The JAR to which the file should be added
 * @param parentDir
 *            the parent directory of the file, this is used to calculate
 *            the path witin the JAR file. When null is given, the file will
 *            be added into the root of the JAR.
 * @param compress
 *            True when the jar file should be compressed
 * @throws FileNotFoundException
 *             when the jarFile does not exist
 * @throws IOException
 *             when a file could not be written or the jar-file could not
 *             read.
 */
public static void addToJar(File file, File jarFile, File parentDir, boolean compress)
        throws FileNotFoundException, IOException {
    File tmpJarFile = File.createTempFile("tmp", ".jar", jarFile.getParentFile());
    JarOutputStream out = new JarOutputStream(new FileOutputStream(tmpJarFile));
    if (compress) {
        out.setLevel(ZipOutputStream.DEFLATED);
    } else {
        out.setLevel(ZipOutputStream.STORED);
    }
    // copy contents of old jar to new jar:
    JarFile inputFile = new JarFile(jarFile);
    JarInputStream in = new JarInputStream(new FileInputStream(jarFile));
    CRC32 crc = new CRC32();
    byte[] buffer = new byte[512 * 1024];
    JarEntry entry = (JarEntry) in.getNextEntry();
    while (entry != null) {
        InputStream entryIn = inputFile.getInputStream(entry);
        add(entry, entryIn, out, crc, buffer);
        entryIn.close();
        entry = (JarEntry) in.getNextEntry();
    }
    in.close();
    inputFile.close();

    int sourceDirLength;
    if (parentDir == null) {
        sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1;
    } else {
        sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1
                - parentDir.getAbsolutePath().length();
    }
    addFile(file, out, crc, sourceDirLength, buffer);
    out.close();

    // remove old jar file and rename temp file to old one:
    if (jarFile.delete()) {
        if (!tmpJarFile.renameTo(jarFile)) {
            throw new IOException(
                    "Unable to rename temporary JAR file to [" + jarFile.getAbsolutePath() + "].");
        }
    } else {
        throw new IOException("Unable to delete old JAR file [" + jarFile.getAbsolutePath() + "].");
    }

}

From source file:net.minecraftforge.fml.relauncher.libraries.LibraryManager.java

private static Pair<Artifact, byte[]> extractPacked(File file, ModList modlist, File... modDirs) {
    if (processed.contains(file)) {
        FMLLog.log.debug("File already proccessed {}, Skipping", file.getAbsolutePath());
        return null;
    }//from  w w  w.  j a  va 2 s.  c  o  m
    JarFile jar = null;
    try {
        jar = new JarFile(file);
        FMLLog.log.debug("Examining file: {}", file.getName());
        processed.add(file);
        return extractPacked(jar, modlist, modDirs);
    } catch (IOException ioe) {
        FMLLog.log.error("Unable to read the jar file {} - ignoring", file.getName(), ioe);
    } finally {
        try {
            if (jar != null)
                jar.close();
        } catch (IOException e) {
        }
    }
    return null;
}

From source file:org.apache.openejb.config.Deploy.java

private static boolean shouldUnpack(final File file) {
    final String name = file.getName();
    if (name.endsWith(".ear") || name.endsWith(".rar") || name.endsWith(".rar")) {
        return true;
    }/*w w  w  .ja v a2  s .c  o m*/

    JarFile jarFile = null;
    try {
        jarFile = new JarFile(file);

        if (jarFile.getEntry("META-INF/application.xml") != null) {
            return true;
        }
        if (jarFile.getEntry("META-INF/ra.xml") != null) {
            return true;
        }
        if (jarFile.getEntry("WEB-INF/web.xml") != null) {
            return true;
        }
    } catch (final IOException e) {
        // no-op
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (final IOException ignored) {
                // no-op
            }
        }
    }

    return false;
}

From source file:azkaban.jobtype.connectors.teradata.TeraDataWalletInitializer.java

/**
 * As of TDCH 1.4.1, integration with Teradata wallet only works with hadoop jar command line command.
 * This is mainly because TDCH depends on the behavior of hadoop jar command line which extracts jar file
 * into hadoop tmp folder./*w  w w.  j  av a 2  s  . c o m*/
 *
 * This method will extract tdchJarfile and place it into temporary folder, and also add jvm shutdown hook
 * to delete the directory when JVM shuts down.
 * @param tdchJarFile TDCH jar file.
 */
public static void initialize(File tmpDir, File tdchJarFile) {
    synchronized (TeraDataWalletInitializer.class) {
        if (tdchJarExtractedDir != null) {
            return;
        }

        if (tdchJarFile == null) {
            throw new IllegalArgumentException("TDCH jar file cannot be null.");
        }
        if (!tdchJarFile.exists()) {
            throw new IllegalArgumentException(
                    "TDCH jar file does not exist. " + tdchJarFile.getAbsolutePath());
        }
        try {
            //Extract TDCH jar.
            File unJarDir = createUnjarDir(
                    new File(tmpDir.getAbsolutePath() + File.separator + UNJAR_DIR_NAME));
            JarFile jar = new JarFile(tdchJarFile);
            Enumeration<JarEntry> enumEntries = jar.entries();

            while (enumEntries.hasMoreElements()) {
                JarEntry srcFile = enumEntries.nextElement();
                File destFile = new File(unJarDir + File.separator + srcFile.getName());
                if (srcFile.isDirectory()) { // if its a directory, create it
                    destFile.mkdir();
                    continue;
                }

                InputStream is = jar.getInputStream(srcFile);
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(destFile));
                IOUtils.copy(is, os);
                close(os);
                close(is);
            }
            jar.close();
            tdchJarExtractedDir = unJarDir;
        } catch (IOException e) {
            throw new RuntimeException("Failed while extracting TDCH jar file.", e);
        }
    }
    logger.info("TDCH jar has been extracted into directory: " + tdchJarExtractedDir.getAbsolutePath());
}

From source file:com.app.server.JarDeployer.java

/**
 * This method obtains the class name inside the jar
 * @param jarPath/*w ww .j a  va2 s .co  m*/
 * @param content
 * @throws IOException
 */
public static void getJarContent(String jarPath, CopyOnWriteArrayList content) throws IOException {
    try {
        log.info("enumer=" + jarPath);

        JarFile jarFile = new JarFile(jarPath);
        Enumeration enumer = (Enumeration) jarFile.entries();
        while (enumer.hasMoreElements()) {
            JarEntry entry = (JarEntry) enumer.nextElement();
            String name = entry.getName();
            if (name.endsWith(".class"))
                content.add(name.replace("/", "."));
        }
        log.info(content);
        jarFile.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:ar.edu.taco.TacoMain.java

/**
 * /* ww w  . j  a va  2 s  . co  m*/
 */
private static String getManifestAttribute(Name name) {
    String manifestAttributeValue = "Undefined";
    try {

        String jarFileName = System.getProperty("java.class.path")
                .split(System.getProperty("path.separator"))[0];
        JarFile jar = new JarFile(jarFileName);
        Manifest manifest = jar.getManifest();

        Attributes mainAttributes = manifest.getMainAttributes();
        manifestAttributeValue = mainAttributes.getValue(name);
        jar.close();
    } catch (IOException e) {
    }

    return manifestAttributeValue;
}

From source file:com.web.server.JarDeployer.java

/**
 * This method obtains the class name inside the jar
 * @param jarPath//  w  w w  .j a va  2s.com
 * @param content
 * @throws IOException
 */
public static void getJarContent(String jarPath, CopyOnWriteArrayList content) throws IOException {
    try {
        System.out.println("enumer=" + jarPath);

        JarFile jarFile = new JarFile(jarPath);
        Enumeration enumer = (Enumeration) jarFile.entries();
        while (enumer.hasMoreElements()) {
            JarEntry entry = (JarEntry) enumer.nextElement();
            String name = entry.getName();
            if (name.endsWith(".class"))
                content.add(name.replace("/", "."));
        }
        System.out.println(content);
        jarFile.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}