Example usage for java.util.jar JarFile entries

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

Introduction

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

Prototype

public Enumeration<JarEntry> entries() 

Source Link

Document

Returns an enumeration of the jar file entries.

Usage

From source file:com.icesoft.jasper.compiler.TldLocationsCache.java

/**
 * Scans the given JarURLConnection for TLD files located in META-INF (or a
 * subdirectory of it), adding an implicit map entry to the taglib map for
 * any TLD that has a <uri> element.
 *
 * @param conn   The JarURLConnection to the JAR file to scan
 * @param ignore true if any exceptions raised when processing the given JAR
 *               should be ignored, false otherwise
 */// w  w  w .j ava2  s. co  m
private void scanJar(JarURLConnection conn, boolean ignore) throws JasperException {

    JarFile jarFile = null;
    String resourcePath = conn.getJarFileURL().toString();
    try {
        if (redeployMode) {
            conn.setUseCaches(false);
        }
        jarFile = conn.getJarFile();
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            String name = entry.getName();
            if (!name.startsWith("META-INF/"))
                continue;
            if (!name.endsWith(".tld"))
                continue;
            InputStream stream = jarFile.getInputStream(entry);
            try {
                String uri = getUriFromTld(resourcePath, stream);
                // Add implicit map entry only if its uri is not already
                // present in the map
                if (uri != null && mappings.get(uri) == null) {
                    mappings.put(uri, new String[] { resourcePath, name });
                }
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                        if (log.isDebugEnabled()) {
                            log.debug(e.getLocalizedMessage(), e);
                        }
                    }
                }
            }
        }
    } catch (IOException ex) {
        if (log.isDebugEnabled()) {
            log.debug(ex.getMessage(), ex);
        }
        if (!redeployMode) {
            // if not in redeploy mode, close the jar in case of an error
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getLocalizedMessage(), e);
                    }
                }
            }
        }
        if (!ignore) {
            throw new JasperException(ex);
        }
    } finally {
        if (redeployMode) {
            // if in redeploy mode, always close the jar
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getLocalizedMessage(), e);
                    }
                }
            }
        }
    }
}

From source file:com.slamd.admin.JobPack.java

/**
 * Extracts the contents of the job pack and registers the included jobs with
 * the SLAMD server.//from   w  w w .  j  ava2  s . c  o  m
 *
 * @throws  SLAMDServerException  If a problem occurs while processing the job
 *                                pack JAR file.
 */
public void processJobPack() throws SLAMDServerException {
    byte[] fileData = null;
    File tempFile = null;
    String fileName = null;
    String separator = System.getProperty("file.separator");

    if (filePath == null) {
        // First, get the request and ensure it is multipart content.
        HttpServletRequest request = requestInfo.request;
        if (!FileUpload.isMultipartContent(request)) {
            throw new SLAMDServerException("Request does not contain multipart " + "content");
        }

        // Iterate through the request fields to get to the file data.
        Iterator iterator = fieldList.iterator();
        while (iterator.hasNext()) {
            FileItem fileItem = (FileItem) iterator.next();
            String fieldName = fileItem.getFieldName();

            if (fieldName.equals(Constants.SERVLET_PARAM_JOB_PACK_FILE)) {
                fileData = fileItem.get();
                fileName = fileItem.getName();
            }
        }

        // Make sure that a file was actually uploaded.
        if (fileData == null) {
            throw new SLAMDServerException("No file data was found in the " + "request.");
        }

        // Write the JAR file data to a temp file, since that's the only way we
        // can parse it.
        if (separator == null) {
            separator = "/";
        }

        tempFile = new File(jobClassDirectory + separator + fileName);
        try {
            FileOutputStream outputStream = new FileOutputStream(tempFile);
            outputStream.write(fileData);
            outputStream.flush();
            outputStream.close();
        } catch (IOException ioe) {
            try {
                tempFile.delete();
            } catch (Exception e) {
            }

            ioe.printStackTrace();
            slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
            throw new SLAMDServerException("I/O error writing temporary JAR " + "file:  " + ioe, ioe);
        }
    } else {
        tempFile = new File(filePath);
        if ((!tempFile.exists()) || (!tempFile.isFile())) {
            throw new SLAMDServerException("Specified job pack file \"" + filePath + "\" does not exist");
        }

        try {
            fileName = tempFile.getName();
            int fileLength = (int) tempFile.length();
            fileData = new byte[fileLength];

            FileInputStream inputStream = new FileInputStream(tempFile);
            int bytesRead = 0;
            while (bytesRead < fileLength) {
                bytesRead += inputStream.read(fileData, bytesRead, fileLength - bytesRead);
            }
            inputStream.close();
        } catch (Exception e) {
            slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e));
            throw new SLAMDServerException("Error reading job pack file \"" + filePath + "\" -- " + e, e);
        }
    }

    StringBuilder htmlBody = requestInfo.htmlBody;

    // Parse the jar file
    JarFile jarFile = null;
    Manifest manifest = null;
    Enumeration jarEntries = null;
    try {
        jarFile = new JarFile(tempFile, true);
        manifest = jarFile.getManifest();
        jarEntries = jarFile.entries();
    } catch (IOException ioe) {
        try {
            if (filePath == null) {
                tempFile.delete();
            }
        } catch (Exception e) {
        }

        ioe.printStackTrace();
        slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
        throw new SLAMDServerException("Unable to parse the JAR file:  " + ioe, ioe);
    }

    ArrayList<String> dirList = new ArrayList<String>();
    ArrayList<String> fileNameList = new ArrayList<String>();
    ArrayList<byte[]> fileDataList = new ArrayList<byte[]>();
    while (jarEntries.hasMoreElements()) {
        JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
        String entryName = jarEntry.getName();
        if (jarEntry.isDirectory()) {
            dirList.add(entryName);
        } else {
            try {
                int entrySize = (int) jarEntry.getSize();
                byte[] entryData = new byte[entrySize];
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                extractFileData(inputStream, entryData);
                fileNameList.add(entryName);
                fileDataList.add(entryData);
            } catch (IOException ioe) {
                try {
                    jarFile.close();
                    if (filePath == null) {
                        tempFile.delete();
                    }
                } catch (Exception e) {
                }

                ioe.printStackTrace();
                slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
                throw new SLAMDServerException("I/O error parsing JAR entry " + entryName + " -- " + ioe, ioe);
            } catch (SLAMDServerException sse) {
                try {
                    jarFile.close();
                    if (filePath == null) {
                        tempFile.delete();
                    }
                } catch (Exception e) {
                }

                sse.printStackTrace();
                throw sse;
            }
        }
    }

    // If we have gotten here, then we have read all the data from the JAR file.
    // Delete the temporary file to prevent possible (although unlikely)
    // conflicts with data contained in the JAR.
    try {
        jarFile.close();
        if (filePath == null) {
            tempFile.delete();
        }
    } catch (Exception e) {
    }

    // Create the directory structure specified in the JAR file.
    if (!dirList.isEmpty()) {
        htmlBody.append("<B>Created the following directories</B>" + Constants.EOL);
        htmlBody.append("<BR>" + Constants.EOL);
        htmlBody.append("<UL>" + Constants.EOL);

        for (int i = 0; i < dirList.size(); i++) {
            File dirFile = new File(jobClassDirectory + separator + dirList.get(i));
            try {
                dirFile.mkdirs();
                htmlBody.append("  <LI>" + dirFile.getAbsolutePath() + "</LI>" + Constants.EOL);
            } catch (Exception e) {
                htmlBody.append("</UL>" + Constants.EOL);
                e.printStackTrace();
                slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e));
                throw new SLAMDServerException(
                        "Unable to create directory \"" + dirFile.getAbsolutePath() + " -- " + e, e);
            }
        }

        htmlBody.append("</UL>" + Constants.EOL);
        htmlBody.append("<BR><BR>" + Constants.EOL);
    }

    // Write all the files to disk.  If we have gotten this far, then there
    // should not be any failures, but if there are, then we will have to
    // leave things in a "dirty" state.
    if (!fileNameList.isEmpty()) {
        htmlBody.append("<B>Created the following files</B>" + Constants.EOL);
        htmlBody.append("<BR>" + Constants.EOL);
        htmlBody.append("<UL>" + Constants.EOL);

        for (int i = 0; i < fileNameList.size(); i++) {
            File dataFile = new File(jobClassDirectory + separator + fileNameList.get(i));

            try {
                // Make sure the parent directory exists.
                dataFile.getParentFile().mkdirs();
            } catch (Exception e) {
            }

            try {
                FileOutputStream outputStream = new FileOutputStream(dataFile);
                outputStream.write(fileDataList.get(i));
                outputStream.flush();
                outputStream.close();
                htmlBody.append("  <LI>" + dataFile.getAbsolutePath() + "</LI>" + Constants.EOL);
            } catch (IOException ioe) {
                htmlBody.append("</UL>" + Constants.EOL);
                ioe.printStackTrace();
                slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
                throw new SLAMDServerException("Unable to write file " + dataFile.getAbsolutePath() + ioe, ioe);
            }
        }

        htmlBody.append("</UL>" + Constants.EOL);
        htmlBody.append("<BR><BR>" + Constants.EOL);
    }

    // Finally, parse the manifest to get the names of the classes that should
    // be registered with the SLAMD server.
    Attributes manifestAttributes = manifest.getMainAttributes();
    Attributes.Name key = new Attributes.Name(Constants.JOB_PACK_MANIFEST_REGISTER_JOBS_ATTR);
    String registerClassesStr = (String) manifestAttributes.get(key);
    if ((registerClassesStr == null) || (registerClassesStr.length() == 0)) {
        htmlBody.append("<B>No job classes registered</B>" + Constants.EOL);
    } else {
        ArrayList<String> successList = new ArrayList<String>();
        ArrayList<String> failureList = new ArrayList<String>();

        StringTokenizer tokenizer = new StringTokenizer(registerClassesStr, ", \t\r\n");
        while (tokenizer.hasMoreTokens()) {
            String className = tokenizer.nextToken();

            try {
                JobClass jobClass = slamdServer.loadJobClass(className);
                slamdServer.addJobClass(jobClass);
                successList.add(className);
            } catch (Exception e) {
                failureList.add(className + ":  " + e);
            }
        }

        if (!successList.isEmpty()) {
            htmlBody.append("<B>Registered Job Classes</B>" + Constants.EOL);
            htmlBody.append("<UL>" + Constants.EOL);
            for (int i = 0; i < successList.size(); i++) {
                htmlBody.append("  <LI>" + successList.get(i) + "</LI>" + Constants.EOL);
            }
            htmlBody.append("</UL>" + Constants.EOL);
            htmlBody.append("<BR><BR>" + Constants.EOL);
        }

        if (!failureList.isEmpty()) {
            htmlBody.append("<B>Unable to Register Job Classes</B>" + Constants.EOL);
            htmlBody.append("<UL>" + Constants.EOL);
            for (int i = 0; i < failureList.size(); i++) {
                htmlBody.append("  <LI>" + failureList.get(i) + "</LI>" + Constants.EOL);
            }
            htmlBody.append("</UL>" + Constants.EOL);
            htmlBody.append("<BR><BR>" + Constants.EOL);
        }
    }
}

From source file:org.apache.struts2.jasper.compiler.TldLocationsCache.java

/**
 * Scans the given JarURLConnection for TLD files located in META-INF
 * (or a subdirectory of it), adding an implicit map entry to the taglib
 * map for any TLD that has a <uri> element.
 *
 * @param conn The JarURLConnection to the JAR file to scan
 * @param ignore true if any exceptions raised when processing the given
 * JAR should be ignored, false otherwise
 *///from w w  w . j a  v  a  2s .c  o  m
private void scanJar(JarURLConnection conn, boolean ignore) throws JasperException {

    JarFile jarFile = null;
    String resourcePath = conn.getJarFileURL().toString();
    try {
        if (redeployMode) {
            conn.setUseCaches(false);
        }
        jarFile = conn.getJarFile();
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            String name = entry.getName();
            if (!name.startsWith("META-INF/"))
                continue;
            if (!name.endsWith(".tld"))
                continue;
            InputStream stream = jarFile.getInputStream(entry);
            try {
                String uri = getUriFromTld(resourcePath, stream);
                // Add implicit map entry only if its uri is not already
                // present in the map
                if (uri != null && mappings.get(uri) == null) {
                    mappings.put(uri, new String[] { resourcePath, name });
                }
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (Throwable t) {
                        // do nothing
                    }
                }
            }
        }
    } catch (Exception ex) {
        if (!redeployMode) {
            // if not in redeploy mode, close the jar in case of an error
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        }
        if (!ignore) {
            throw new JasperException(ex);
        }
    } finally {
        if (redeployMode) {
            // if in redeploy mode, always close the jar
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        }
    }
}

From source file:org.hyperic.hq.plugin.websphere.WebsphereProductPlugin.java

private File runtimeJarHack(File file) throws Exception {
    String tmp = System.getProperty("java.io.tmpdir"); //agent/tmp
    File newJar = new File(tmp, file.getName());
    if (newJar.exists()) {
        return newJar;
    }//from  w  w  w  .ja v  a 2s . c  om
    log.debug("Creating " + newJar);
    JarFile jar = new JarFile(file);
    JarOutputStream os = new JarOutputStream(new FileOutputStream(newJar));
    byte[] buffer = new byte[1024];
    try {
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            int n;
            JarEntry entry = e.nextElement();

            if (entry.getName().startsWith("org/apache/commons/logging/")) {
                continue;
            }
            InputStream entryStream = jar.getInputStream(entry);

            os.putNextEntry(entry);
            while ((n = entryStream.read(buffer)) != -1) {
                os.write(buffer, 0, n);
            }
            entryStream.close();
        }
    } finally {
        jar.close();
        os.close();
    }
    return newJar;
}

From source file:com.taobao.android.builder.tools.multidex.FastMultiDexer.java

@Override
public Collection<File> repackageJarList(Collection<File> files) throws IOException {

    List<String> mainDexList = getMainDexList(files);

    List<File> jarList = new ArrayList<>();
    List<File> folderList = new ArrayList<>();
    for (File file : files) {
        if (file.isDirectory()) {
            folderList.add(file);// ww w  .ja v a2s  . c o  m
        } else {
            jarList.add(file);
        }
    }

    File dir = new File(appVariantContext.getScope().getGlobalScope().getIntermediatesDir(),
            "fastmultidex/" + appVariantContext.getVariantName());
    FileUtils.deleteDirectory(dir);
    dir.mkdirs();

    if (!folderList.isEmpty()) {
        File mergedJar = new File(dir, "jarmerging/combined.jar");
        mergedJar.getParentFile().mkdirs();
        mergedJar.delete();
        mergedJar.createNewFile();
        JarMerger jarMerger = new JarMerger(mergedJar);
        for (File folder : folderList) {
            jarMerger.addFolder(folder);
        }
        jarMerger.close();
        if (mergedJar.length() > 0) {
            jarList.add(mergedJar);
        }
    }

    List<File> result = new ArrayList<>();
    File maindexJar = new File(dir, "fastmaindex.jar");

    JarOutputStream mainJarOuputStream = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(maindexJar)));
    for (File jar : jarList) {
        File outJar = new File(dir, FileNameUtils.getUniqueJarName(jar) + ".jar");
        result.add(outJar);
        JarFile jarFile = new JarFile(jar);
        JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar)));
        Enumeration<JarEntry> jarFileEntries = jarFile.entries();
        while (jarFileEntries.hasMoreElements()) {
            JarEntry ze = jarFileEntries.nextElement();
            String pathName = ze.getName();
            if (mainDexList.contains(pathName)) {
                copyStream(jarFile.getInputStream(ze), mainJarOuputStream, ze, pathName);
            } else {
                copyStream(jarFile.getInputStream(ze), jos, ze, pathName);
            }
        }
        jarFile.close();
        IOUtils.closeQuietly(jos);
    }
    IOUtils.closeQuietly(mainJarOuputStream);

    Collections.sort(result, new NameComparator());

    result.add(0, maindexJar);

    return result;
}

From source file:org.jenkins.tools.test.PluginCompatTester.java

/**
 * Scans through a WAR file, accumulating plugin information
 * @param war WAR to scan// w  w  w.ja  v  a2  s.  c o m
 * @param pluginGroupIds Map pluginName to groupId if set in the manifest, MUTATED IN THE EXECUTION
 * @return Update center data
 * @throws IOException
 */
private UpdateSite.Data scanWAR(File war, Map<String, String> pluginGroupIds) throws IOException {
    JSONObject top = new JSONObject();
    top.put("id", DEFAULT_SOURCE_ID);
    JSONObject plugins = new JSONObject();
    JarFile jf = new JarFile(war);
    if (pluginGroupIds == null) {
        pluginGroupIds = new HashMap<String, String>();
    }
    try {
        Enumeration<JarEntry> entries = jf.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String name = entry.getName();
            Matcher m = Pattern.compile("WEB-INF/lib/jenkins-core-([0-9.]+(?:-[0-9.]+)?(?:-SNAPSHOT)?)[.]jar")
                    .matcher(name);
            if (m.matches()) {
                if (top.has("core")) {
                    throw new IOException(">1 jenkins-core.jar in " + war);
                }
                top.put("core", new JSONObject().accumulate("name", "core").accumulate("version", m.group(1))
                        .accumulate("url", ""));
            }
            m = Pattern.compile("WEB-INF/(?:optional-)?plugins/([^/.]+)[.][hj]pi").matcher(name);
            if (m.matches()) {
                JSONObject plugin = new JSONObject().accumulate("url", "");
                InputStream is = jf.getInputStream(entry);
                try {
                    JarInputStream jis = new JarInputStream(is);
                    try {
                        Manifest manifest = jis.getManifest();
                        String shortName = manifest.getMainAttributes().getValue("Short-Name");
                        if (shortName == null) {
                            shortName = manifest.getMainAttributes().getValue("Extension-Name");
                            if (shortName == null) {
                                shortName = m.group(1);
                            }
                        }
                        plugin.put("name", shortName);
                        pluginGroupIds.put(shortName, manifest.getMainAttributes().getValue("Group-Id"));
                        plugin.put("version", manifest.getMainAttributes().getValue("Plugin-Version"));
                        plugin.put("url", "jar:" + war.toURI() + "!/" + name);
                        JSONArray dependenciesA = new JSONArray();
                        String dependencies = manifest.getMainAttributes().getValue("Plugin-Dependencies");
                        if (dependencies != null) {
                            // e.g. matrix-auth:1.0.2;resolution:=optional,credentials:1.8.3;resolution:=optional
                            for (String pair : dependencies.replace(";resolution:=optional", "").split(",")) {
                                String[] nameVer = pair.split(":");
                                assert nameVer.length == 2;
                                dependenciesA.add(new JSONObject().accumulate("name", nameVer[0])
                                        .accumulate("version", nameVer[1])
                                        ./* we do care about even optional deps here */accumulate("optional",
                                                "false"));
                            }
                        }
                        plugin.accumulate("dependencies", dependenciesA);
                        plugins.put(shortName, plugin);
                    } finally {
                        jis.close();
                    }
                } finally {
                    is.close();
                }
            }
        }
    } finally {
        jf.close();
    }
    top.put("plugins", plugins);
    if (!top.has("core")) {
        throw new IOException("no jenkins-core.jar in " + war);
    }
    System.out.println("Scanned contents of " + war + ": " + top);
    return newUpdateSiteData(new UpdateSite(DEFAULT_SOURCE_ID, null), top);
}

From source file:org.apache.catalina.startup.TldConfig.java

/**
 * Scans all TLD entries in the given JAR for application listeners.
 *
 * @param file JAR file whose TLD entries are scanned for application
 * listeners/*from   w  w w. j  a  v  a2 s .co  m*/
 */
private void tldScanJar(File file) throws Exception {

    JarFile jarFile = null;
    String name = null;

    String jarPath = file.getAbsolutePath();

    try {
        jarFile = new JarFile(file);
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            name = entry.getName();
            if (!name.startsWith("META-INF/")) {
                continue;
            }
            if (!name.endsWith(".tld")) {
                continue;
            }
            if (log.isTraceEnabled()) {
                log.trace("  Processing TLD at '" + name + "'");
            }
            try {
                tldScanStream(new InputSource(jarFile.getInputStream(entry)));
            } catch (Exception e) {
                log.error(sm.getString("contextConfig.tldEntryException", name, jarPath, context.getPath()), e);
            }
        }
    } catch (Exception e) {
        log.error(sm.getString("contextConfig.tldJarException", jarPath, context.getPath()), e);
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (Throwable t) {
                // Ignore
            }
        }
    }
}

From source file:org.hyperic.snmp.MIBTree.java

public boolean parse(JarFile jar, String[] accept) throws IOException {
    AcceptFilter filter = new AcceptFilter(accept);

    for (Enumeration e = jar.entries(); e.hasMoreElements();) {
        JarEntry entry = (JarEntry) e.nextElement();

        if (entry.isDirectory()) {
            continue;
        }//from  w  w  w.ja va2  s .c o  m

        if (!entry.getName().startsWith("mibs/")) {
            continue;
        }

        String name = entry.getName().substring(5);

        if (!filter.accept(name)) {
            continue;
        }

        if (hasParsedFile(new File(name))) {
            continue;
        }

        String where = jar.getName() + "!" + entry.getName();

        parse(where, jar.getInputStream(entry));
    }

    return true;
}

From source file:net.lightbody.bmp.proxy.jetty.util.JarFileResource.java

/**
 * Returns true if the respresenetd resource exists.
 *//*from   ww w  .j a  va2s.  c  om*/
public boolean exists() {
    if (_exists)
        return true;

    if (_urlString.endsWith("!/")) {
        String file_url = _urlString.substring(4, _urlString.length() - 2);
        try {
            return newResource(file_url).exists();
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            return false;
        }
    }

    boolean check = checkConnection();

    // Is this a root URL?
    if (_jarUrl != null && _path == null) {
        // Then if it exists it is a directory
        _directory = check;
        return true;
    } else {
        // Can we find a file for it?
        JarFile jarFile = null;
        if (check)
            // Yes
            jarFile = _jarFile;
        else {
            // No - so lets look if the root entry exists.
            try {
                jarFile = ((JarURLConnection) ((new URL(_jarUrl)).openConnection())).getJarFile();
            } catch (Exception e) {
                LogSupport.ignore(log, e);
            }
        }

        // Do we need to look more closely?
        if (jarFile != null && _entry == null && !_directory) {
            // OK - we have a JarFile, lets look at the entries for our path
            Enumeration e = jarFile.entries();
            while (e.hasMoreElements()) {
                JarEntry entry = (JarEntry) e.nextElement();
                String name = entry.getName().replace('\\', '/');

                // Do we have a match
                if (name.equals(_path)) {
                    _entry = entry;
                    // Is the match a directory
                    _directory = _path.endsWith("/");
                    break;
                } else if (_path.endsWith("/")) {
                    if (name.startsWith(_path)) {
                        _directory = true;
                        break;
                    }
                } else if (name.startsWith(_path) && name.length() > _path.length()
                        && name.charAt(_path.length()) == '/') {
                    _directory = true;
                    break;
                }
            }
        }
    }

    _exists = (_directory || _entry != null);
    return _exists;
}

From source file:org.tinygroup.jspengine.compiler.TldLocationsCache.java

/**
 * Scans the given JarURLConnection for TLD files located in META-INF (or a
 * subdirectory of it), adding an implicit map entry to the taglib map for
 * any TLD that has a <uri> element.
 * //from  w ww  . jav a2  s.c o m
 * @param conn
 *            The JarURLConnection to the JAR file to scan
 * @param ignore
 *            true if any exceptions raised when processing the given JAR
 *            should be ignored, false otherwise
 */
private void scanJar(JarURLConnection conn, boolean ignore) throws JasperException {

    JarFile jarFile = null;
    String resourcePath = conn.getJarFileURL().toString();
    try {
        if (redeployMode) {
            conn.setUseCaches(false);
        }
        jarFile = conn.getJarFile();
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            String name = entry.getName();
            if (!name.startsWith("META-INF/"))
                continue;
            if (!name.endsWith(".tld"))
                continue;
            InputStream stream = jarFile.getInputStream(entry);
            try {
                String uri = getUriFromTld(resourcePath, stream);
                // Add map entry.
                // Override existing entries as we move higher
                // up in the classloader delegation chain.
                if (uri != null && (mappings.get(uri) == null || systemUris.contains(uri)
                        || (systemUrisJsf.contains(uri) && !useMyFaces))) {
                    mappings.put(uri, new String[] { resourcePath, name });
                }
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (Throwable t) {
                        // do nothing
                    }
                }
            }
        }
    } catch (Exception ex) {
        if (!redeployMode) {
            // if not in redeploy mode, close the jar in case of an error
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        }
        if (!ignore) {
            throw new JasperException(ex);
        }
    } finally {
        if (redeployMode) {
            // if in redeploy mode, always close the jar
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        }
    }
}