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:org.springframework.web.context.support.ServletContextResourcePatternResolver.java

/**
 * Extract entries from the given jar by pattern.
 * @param jarFilePath the path to the jar file
 * @param entryPattern the pattern for jar entries to match
 * @param result the Set of matching Resources to add to
 *///from  w  w w. j a v a  2s  . c  o  m
private void doRetrieveMatchingJarEntries(String jarFilePath, String entryPattern, Set<Resource> result) {
    if (logger.isDebugEnabled()) {
        logger.debug("Searching jar file [" + jarFilePath + "] for entries matching [" + entryPattern + "]");
    }
    try {
        JarFile jarFile = new JarFile(jarFilePath);
        try {
            for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
                JarEntry entry = entries.nextElement();
                String entryPath = entry.getName();
                if (getPathMatcher().match(entryPattern, entryPath)) {
                    result.add(new UrlResource(ResourceUtils.URL_PROTOCOL_JAR, ResourceUtils.FILE_URL_PREFIX
                            + jarFilePath + ResourceUtils.JAR_URL_SEPARATOR + entryPath));
                }
            }
        } finally {
            jarFile.close();
        }
    } catch (IOException ex) {
        if (logger.isWarnEnabled()) {
            logger.warn("Cannot search for matching resources in jar file [" + jarFilePath
                    + "] because the jar cannot be opened through the file system", ex);
        }
    }
}

From source file:Zip.java

/**
 * Reads a Jar file, displaying the attributes in its manifest and dumping
 * the contents of each file contained to the console.
 *//*  w w  w. j av  a2s. com*/
public static void readJarFile(String fileName) {
    JarFile jarFile = null;
    try {
        // JarFile extends ZipFile and adds manifest information
        jarFile = new JarFile(fileName);
        if (jarFile.getManifest() != null) {
            System.out.println("Manifest Main Attributes:");
            Iterator iter = jarFile.getManifest().getMainAttributes().keySet().iterator();
            while (iter.hasNext()) {
                Attributes.Name attribute = (Attributes.Name) iter.next();
                System.out.println(
                        attribute + " : " + jarFile.getManifest().getMainAttributes().getValue(attribute));
            }
            System.out.println();
        }
        // use the Enumeration to dump the contents of each file to the console
        System.out.println("Jar file entries:");
        for (Enumeration e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = (JarEntry) e.nextElement();
            if (!jarEntry.isDirectory()) {
                System.out.println(jarEntry.getName() + " contains:");
                BufferedReader jarReader = new BufferedReader(
                        new InputStreamReader(jarFile.getInputStream(jarEntry)));
                while (jarReader.ready()) {
                    System.out.println(jarReader.readLine());
                }
                jarReader.close();
            }
        }
    } catch (IOException ioe) {
        System.out.println("An IOException occurred: " + ioe.getMessage());
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:org.apache.maven.shared.osgi.DefaultMaven2OsgiConverter.java

private String getGroupIdFromPackage(File artifactFile) {
    try {//from  w ww .  j a  v  a 2  s .  c  om
        /* get package names from jar */
        Set packageNames = new HashSet();
        JarFile jar = new JarFile(artifactFile, false);
        Enumeration entries = jar.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.getName().endsWith(".class")) {
                File f = new File(entry.getName());
                String packageName = f.getParent();
                if (packageName != null) {
                    packageNames.add(packageName);
                }
            }
        }
        jar.close();

        /* find the top package */
        String[] groupIdSections = null;
        for (Iterator it = packageNames.iterator(); it.hasNext();) {
            String packageName = (String) it.next();

            String[] packageNameSections = packageName.split("\\" + FILE_SEPARATOR);
            if (groupIdSections == null) {
                /* first candidate */
                groupIdSections = packageNameSections;
            } else
            // if ( packageNameSections.length < groupIdSections.length )
            {
                /*
                 * find the common portion of current package and previous selected groupId
                 */
                int i;
                for (i = 0; (i < packageNameSections.length) && (i < groupIdSections.length); i++) {
                    if (!packageNameSections[i].equals(groupIdSections[i])) {
                        break;
                    }
                }
                groupIdSections = new String[i];
                System.arraycopy(packageNameSections, 0, groupIdSections, 0, i);
            }
        }

        if ((groupIdSections == null) || (groupIdSections.length == 0)) {
            return null;
        }

        /* only one section as id doesn't seem enough, so ignore it */
        if (groupIdSections.length == 1) {
            return null;
        }

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < groupIdSections.length; i++) {
            sb.append(groupIdSections[i]);
            if (i < groupIdSections.length - 1) {
                sb.append('.');
            }
        }
        return sb.toString();
    } catch (IOException e) {
        /* we took all the precautions to avoid this */
        throw new RuntimeException(e);
    }
}

From source file:com.eucalyptus.simpleworkflow.common.client.WorkflowClientStandalone.java

private void processJar(File f) throws Exception {
    final JarFile jar = new JarFile(f);
    final Properties props = new Properties();
    final List<JarEntry> jarList = Collections.list(jar.entries());
    LOG.trace("-> Trying to load component info from " + f.getAbsolutePath());
    for (final JarEntry j : jarList) {
        try {/*w ww.  j a  v  a  2 s . c o  m*/
            if (j.getName().matches(".*\\.class.{0,1}")) {
                handleClassFile(f, j);
            }
        } catch (RuntimeException ex) {
            LOG.error(ex, ex);
            jar.close();
            throw ex;
        }
    }
    jar.close();
}

From source file:com.fengduo.bee.commons.core.utilities.ClassPathScanner.java

void findInJar(List<Class<?>> results, File file, String packageName) {
    JarFile jarFile = null;
    String packagePath = dotToPath(packageName) + "/";
    try {//www  . jav  a 2 s  .  com
        jarFile = new JarFile(file);
        Enumeration<JarEntry> en = jarFile.entries();
        while (en.hasMoreElements()) {
            JarEntry je = en.nextElement();
            String name = je.getName();
            if (name.startsWith(packagePath) && name.endsWith(CLASS_FILE)) {
                String className = name.substring(0, name.length() - CLASS_FILE.length());
                add(results, pathToDot(className));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.zb.jcseg.core.JcsegTaskConfig.java

public static void unJar(JarFile jar, File toDir) throws IOException {
    try {//from  w  ww .  jav  a  2  s.  c om
        Enumeration<JarEntry> 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:SerialVersionUID.java

/**
 * Build a TreeMap of the class name to ClassVersionInfo
 * //w w w .j  a  v  a2  s .c  o m
 * @param jar
 * @param classVersionMap
 *          TreeMap<String, ClassVersionInfo> for serializable classes
 * @param cl -
 *          the class loader to use
 * @throws IOException
 *           thrown if the jar cannot be opened
 */
static void generateJarSerialVersionUIDs(URL jar, TreeMap classVersionMap, ClassLoader cl, String pkgPrefix)
        throws IOException {
    String jarName = jar.getFile();
    JarFile jf = new JarFile(jarName);
    Enumeration entries = jf.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = (JarEntry) entries.nextElement();
        String name = entry.getName();
        if (name.endsWith(".class") && name.startsWith(pkgPrefix)) {
            name = name.substring(0, name.length() - 6);
            String classname = name.replace('/', '.');
            try {
                log.fine("Creating ClassVersionInfo for: " + classname);
                ClassVersionInfo cvi = new ClassVersionInfo(classname, cl);
                log.fine(cvi.toString());
                if (cvi.getSerialVersion() != 0) {
                    ClassVersionInfo prevCVI = (ClassVersionInfo) classVersionMap.put(classname, cvi);
                    if (prevCVI != null) {
                        if (prevCVI.getSerialVersion() != cvi.getSerialVersion()) {
                            log.severe("Found inconsistent classes, " + prevCVI + " != " + cvi + ", jar: "
                                    + jarName);
                        }
                    }
                    if (cvi.getHasExplicitSerialVersionUID() == false) {
                        log.warning("No explicit serialVersionUID: " + cvi);
                    }
                }
            } catch (OutOfMemoryError e) {
                log.log(Level.SEVERE, "Check the MaxPermSize", e);
            } catch (Throwable e) {
                log.log(Level.FINE, "While loading: " + name, e);
            }
        }
    }
    jf.close();
}

From source file:org.eclipse.licensing.eclipse_licensing_plugin.InjectLicensingMojo.java

private void extractLicensingBaseFiles() throws IOException {
    JarFile jar = new JarFile(getLicensingBasePlugin());
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String entryName = entry.getName();
        if (entryName.startsWith("org")) {
            File file = new File(classesDirectory, entryName);
            if (entry.isDirectory()) {
                file.mkdir();/*from  w w w.  ja v  a 2s.c  o  m*/
            } else {
                InputStream is = jar.getInputStream(entry);
                FileOutputStream fos = new FileOutputStream(file);
                while (is.available() > 0) {
                    fos.write(is.read());
                }
                fos.close();
                is.close();
            }
        }
    }
    jar.close();
}

From source file:com.netflix.nicobar.core.archive.JarScriptArchive.java

protected JarScriptArchive(ScriptModuleSpec moduleSpec, Path jarPath, String moduleSpecEntry, long createTime)
        throws IOException {
    this.createTime = createTime;
    this.moduleSpec = Objects.requireNonNull(moduleSpec, "moduleSpec");
    Objects.requireNonNull(jarPath, "jarFile");
    if (!jarPath.isAbsolute())
        throw new IllegalArgumentException("jarPath must be absolute.");

    // initialize the index
    JarFile jarFile = new JarFile(jarPath.toFile());
    Set<String> indexBuilder;
    try {//from  w ww.j  a v a2  s  .c o m
        Enumeration<JarEntry> jarEntries = jarFile.entries();
        indexBuilder = new HashSet<String>();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            // Skip adding moduleSpec to archive entries
            if (jarEntry.getName().equals(moduleSpecEntry)) {
                continue;
            }

            if (!jarEntry.isDirectory()) {
                indexBuilder.add(jarEntry.getName());
            }
        }
    } finally {
        jarFile.close();
    }

    entryNames = Collections.unmodifiableSet(indexBuilder);

    rootUrl = jarPath.toUri().toURL();
}

From source file:com.wavemaker.tools.util.CFClassLoader.java

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {

    if (this.resources == null) {
        throw new ClassNotFoundException("invalid search root: " + this.resources);
    } else if (name == null) {
        throw new ClassNotFoundException(MessageResource.NULL_CLASS.getMessage());
    }/*  w w w . j  a va 2 s  .  c om*/

    String classNamePath = name.replace('.', '/') + ".class";

    List<Resource> files = new ArrayList<Resource>();
    for (int i = 0; i < this.resources.length; i++) {
        files.addAll(this.fileSystem.listAllChildren(this.resources[i], null));
    }

    byte[] fileBytes = null;
    try {
        InputStream is = null;
        JarFile jarFile = null;

        for (Resource entry : files) {
            String resourcePath = getPath(entry);
            int len1 = resourcePath.length();
            int len2 = classNamePath.length();
            if (len1 > len2) {
                if (resourcePath.substring(len1 - len2, len1).equals(classNamePath)) {
                    is = entry.getInputStream();
                    break;
                }
            }
        }

        if (is != null) {
            try {
                fileBytes = IOUtils.toByteArray(is);
                is.close();
            } finally {
                if (jarFile != null) {
                    jarFile.close();
                }
            }
        }
    } catch (IOException e) {
        throw new ClassNotFoundException(e.getMessage(), e);
    }

    if (name.contains(".")) {
        String packageName = name.substring(0, name.lastIndexOf('.'));
        if (getPackage(packageName) == null) {
            definePackage(packageName, "", "", "", "", "", "", null);
        }
    }

    Class<?> ret;
    try {
        if (fileBytes == null) {
            ret = ClassLoaderUtils.loadClass(name, this.parentClassLoader);
        } else {
            ret = defineClass(name, fileBytes, 0, fileBytes.length);
        }
    } catch (WMRuntimeException ex) {
        ret = null;
    }

    if (ret == null) {
        throw new ClassNotFoundException(
                "Couldn't find class " + name + " in expected classpath: " + this.resources);
    }

    return ret;
}