Example usage for java.net JarURLConnection setUseCaches

List of usage examples for java.net JarURLConnection setUseCaches

Introduction

In this page you can find the example usage for java.net JarURLConnection setUseCaches.

Prototype

public void setUseCaches(boolean usecaches) 

Source Link

Document

Sets the value of the useCaches field of this URLConnection to the specified value.

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
 *//*from w ww .  j a  v  a 2  s  .  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 (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:catalina.startup.ContextConfig.java

/**
 * Scan the JAR file at the specified resource path for TLDs in the
 * <code>META-INF</code> subdirectory, and scan them for application
 * event listeners that need to be registered.
 *
 * @param resourcePath Resource path of the JAR file to scan
 *
 * @exception Exception if an exception occurs while scanning this JAR
 *//*from   w ww.  ja va 2s .c  o  m*/
private void tldScanJar(String resourcePath) throws Exception {

    if (debug >= 1) {
        log(" Scanning JAR at resource path '" + resourcePath + "'");
    }

    JarFile jarFile = null;
    String name = null;
    InputStream inputStream = null;
    try {
        URL url = context.getServletContext().getResource(resourcePath);
        if (url == null) {
            throw new IllegalArgumentException(sm.getString("contextConfig.tldResourcePath", resourcePath));
        }
        url = new URL("jar:" + url.toString() + "!/");
        JarURLConnection conn = (JarURLConnection) url.openConnection();
        conn.setUseCaches(false);
        jarFile = conn.getJarFile();
        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 (debug >= 2) {
                log("  Processing TLD at '" + name + "'");
            }
            inputStream = jarFile.getInputStream(entry);
            tldScanStream(inputStream);
            inputStream.close();
            inputStream = null;
            name = null;
        }
        // FIXME - Closing the JAR file messes up the class loader???
        //            jarFile.close();
    } catch (Exception e) {
        if (name == null) {
            throw new ServletException(sm.getString("contextConfig.tldJarException", resourcePath), e);
        } else {
            throw new ServletException(sm.getString("contextConfig.tldEntryException", name, resourcePath), e);
        }
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Throwable t) {
                ;
            }
            inputStream = null;
        }
        if (jarFile != null) {
            // FIXME - Closing the JAR file messes up the class loader???
            //                try {
            //                    jarFile.close();
            //                } catch (Throwable t) {
            //                    ;
            //                }
            jarFile = null;
        }
    }

}

From source file:org.apache.jasper.compiler.TagLibraryInfoImpl.java

/**
 * Constructor./*w w w  . j  a  v  a 2 s .com*/
 */
public TagLibraryInfoImpl(JspCompilationContext ctxt, ParserController pc, String prefix, String uriIn,
        String[] location, ErrorDispatcher err) throws JasperException {
    super(prefix, uriIn);

    this.ctxt = ctxt;
    this.parserController = pc;
    this.err = err;
    InputStream in = null;
    JarFile jarFile = null;

    if (location == null) {
        // The URI points to the TLD itself or to a JAR file in which the
        // TLD is stored
        location = generateTLDLocation(uri, ctxt);
    }

    try {
        if (!location[0].endsWith("jar")) {
            // Location points to TLD file
            try {
                in = getResourceAsStream(location[0]);
                if (in == null) {
                    throw new FileNotFoundException(location[0]);
                }
            } catch (FileNotFoundException ex) {
                err.jspError("jsp.error.file.not.found", location[0]);
            }

            parseTLD(ctxt, location[0], in, null);
            // Add TLD to dependency list
            PageInfo pageInfo = ctxt.createCompiler().getPageInfo();
            if (pageInfo != null) {
                pageInfo.addDependant(location[0]);
            }
        } else {
            // Tag library is packaged in JAR file
            try {
                URL jarFileUrl = new URL("jar:" + location[0] + "!/");
                JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection();
                conn.setUseCaches(false);
                conn.connect();
                jarFile = conn.getJarFile();
                ZipEntry jarEntry = jarFile.getEntry(location[1]);
                in = jarFile.getInputStream(jarEntry);
                parseTLD(ctxt, location[0], in, jarFileUrl);
            } catch (Exception ex) {
                err.jspError("jsp.error.tld.unable_to_read", location[0], location[1], ex.toString());
            }
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Throwable t) {
            }
        }
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (Throwable t) {
            }
        }
    }

}

From source file:org.apache.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 ww .  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.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  ww w .j  av  a 2  s.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.b3log.latke.ioc.ClassPathResolver.java

/**
 * scan the jar to get the URLS of the Classes.
 *
 * @param rootDirResource which is "Jar"
 * @param subPattern      subPattern/*from   www  . ja  v a 2 s . c  o m*/
 * @return the URLs of all the matched classes
 */
private static Collection<? extends URL> doFindPathMatchingJarResources(final URL rootDirResource,
        final String subPattern) {

    final Set<URL> result = new LinkedHashSet<URL>();

    JarFile jarFile = null;
    String jarFileUrl;
    String rootEntryPath = null;
    URLConnection con;
    boolean newJarFile = false;

    try {
        con = rootDirResource.openConnection();

        if (con instanceof JarURLConnection) {
            final JarURLConnection jarCon = (JarURLConnection) con;

            jarCon.setUseCaches(false);
            jarFile = jarCon.getJarFile();
            jarFileUrl = jarCon.getJarFileURL().toExternalForm();
            final JarEntry jarEntry = jarCon.getJarEntry();

            rootEntryPath = jarEntry != null ? jarEntry.getName() : "";
        } else {
            // No JarURLConnection -> need to resort to URL file parsing.
            // We'll assume URLs of the format "jar:path!/entry", with the
            // protocol
            // being arbitrary as long as following the entry format.
            // We'll also handle paths with and without leading "file:"
            // prefix.
            final String urlFile = rootDirResource.getFile();
            final int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);

            if (separatorIndex != -1) {
                jarFileUrl = urlFile.substring(0, separatorIndex);
                rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length());
                jarFile = getJarFile(jarFileUrl);
            } else {
                jarFile = new JarFile(urlFile);
                jarFileUrl = urlFile;
                rootEntryPath = "";
            }
            newJarFile = true;

        }

    } catch (final IOException e) {
        LOGGER.log(Level.ERROR, "reslove jar File error", e);
        return result;
    }
    try {
        if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
            // Root entry path must end with slash to allow for proper
            // matching.
            // The Sun JRE does not return a slash here, but BEA JRockit
            // does.
            rootEntryPath = rootEntryPath + "/";
        }
        for (final Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            final JarEntry entry = (JarEntry) entries.nextElement();
            final String entryPath = entry.getName();

            String relativePath = null;

            if (entryPath.startsWith(rootEntryPath)) {
                relativePath = entryPath.substring(rootEntryPath.length());

                if (AntPathMatcher.match(subPattern, relativePath)) {
                    if (relativePath.startsWith("/")) {
                        relativePath = relativePath.substring(1);
                    }
                    result.add(new URL(rootDirResource, relativePath));
                }
            }
        }
        return result;
    } catch (final IOException e) {
        LOGGER.log(Level.ERROR, "parse the JarFile error", e);
    } finally {
        // Close jar file, but only if freshly obtained -
        // not from JarURLConnection, which might cache the file reference.
        if (newJarFile) {
            try {
                jarFile.close();
            } catch (final IOException e) {
                LOGGER.log(Level.WARN, " occur error when closing jarFile", e);
            }
        }
    }
    return result;
}

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

/**
 * Constructor which builds a TagLibraryInfoImpl by parsing a TLD.
 *///  ww  w .ja  v a 2  s  . c  om
public TagLibraryInfoImpl(JspCompilationContext ctxt, ParserController pc, String prefix, String uriIn,
        String[] location, ErrorDispatcher err) throws JasperException {
    super(prefix, uriIn);

    this.ctxt = ctxt;
    this.parserController = pc;
    this.pageInfo = pc.getCompiler().getPageInfo();
    this.err = err;
    InputStream in = null;
    JarFile jarFile = null;

    if (location == null) {
        // The URI points to the TLD itself or to a JAR file in which the
        // TLD is stored
        location = generateTLDLocation(uri, ctxt);
    }

    try {
        if (!location[0].endsWith("jar")) {
            // Location points to TLD file
            try {
                in = getResourceAsStream(location[0]);
                if (in == null) {
                    throw new FileNotFoundException(location[0]);
                }
            } catch (FileNotFoundException ex) {
                err.jspError("jsp.error.file.not.found", location[0]);
            }
            parseTLD(ctxt, location[0], in, null);
            // Add TLD to dependency list
            PageInfo pageInfo = ctxt.createCompiler(false).getPageInfo();
            if (pageInfo != null) {
                pageInfo.addDependant(location[0]);
            }
        } else {
            // Tag library is packaged in JAR file
            try {
                URL jarFileUrl = new URL("jar:" + location[0] + "!/");
                JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection();
                conn.setUseCaches(false);
                conn.connect();
                jarFile = conn.getJarFile();
                ZipEntry jarEntry = jarFile.getEntry(location[1]);
                in = jarFile.getInputStream(jarEntry);
                parseTLD(ctxt, location[0], in, jarFileUrl);
            } catch (Exception ex) {
                err.jspError("jsp.error.tld.unable_to_read", location[0], location[1], ex.toString());
            }
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Throwable t) {
            }
        }
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (Throwable t) {
            }
        }
    }

}

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.
 * /*  w w w  .j a v  a2 s  .  co  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
                }
            }
        }
    }
}

From source file:org.zkoss.spring.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * Find all resources in jar files that match the given location pattern
 * via the Ant-style PathMatcher.//from   ww  w  .  ja va  2s.  c o  m
 * @param rootDirResource the root directory as Resource
 * @param subPattern the sub pattern to match (below the root directory)
 * @return the Set of matching Resource instances
 * @throws IOException in case of I/O errors
 * @see java.net.JarURLConnection
 * @see org.springframework.util.PathMatcher
 */
protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern)
        throws IOException {

    URLConnection con = rootDirResource.getURL().openConnection();
    JarFile jarFile;
    String jarFileUrl;
    String rootEntryPath;
    boolean newJarFile = false;

    if (con instanceof JarURLConnection) {
        // Should usually be the case for traditional JAR files.
        JarURLConnection jarCon = (JarURLConnection) con;
        jarCon.setUseCaches(false);
        jarFile = jarCon.getJarFile();
        jarFileUrl = jarCon.getJarFileURL().toExternalForm();
        JarEntry jarEntry = jarCon.getJarEntry();
        rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
    } else {
        // No JarURLConnection -> need to resort to URL file parsing.
        // We'll assume URLs of the format "jar:path!/entry", with the protocol
        // being arbitrary as long as following the entry format.
        // We'll also handle paths with and without leading "file:" prefix.
        String urlFile = rootDirResource.getURL().getFile();
        int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
        if (separatorIndex != -1) {
            jarFileUrl = urlFile.substring(0, separatorIndex);
            rootEntryPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
            jarFile = getJarFile(jarFileUrl);
        } else {
            jarFile = new JarFile(urlFile);
            jarFileUrl = urlFile;
            rootEntryPath = "";
        }
        newJarFile = true;
    }

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Looking for matching resources in jar file [" + jarFileUrl + "]");
        }
        if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
            // Root entry path must end with slash to allow for proper matching.
            // The Sun JRE does not return a slash here, but BEA JRockit does.
            rootEntryPath = rootEntryPath + "/";
        }
        Set<Resource> result = new LinkedHashSet<Resource>(8);
        for (Enumeration entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = (JarEntry) entries.nextElement();
            String entryPath = entry.getName();
            if (entryPath.startsWith(rootEntryPath)) {
                String relativePath = entryPath.substring(rootEntryPath.length());
                if (getPathMatcher().match(subPattern, relativePath)) {
                    result.add(rootDirResource.createRelative(relativePath));
                }
            }
        }
        return result;
    } finally {
        // Close jar file, but only if freshly obtained -
        // not from JarURLConnection, which might cache the file reference.
        if (newJarFile) {
            jarFile.close();
        }
    }
}