org.apache.tomcat.util.scan.JarFactory Java Examples

The following examples show how to use org.apache.tomcat.util.scan.JarFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FatJarContextConfig.java    From oxygen with Apache License 2.0 6 votes vote down vote up
private void processJar(URL url) throws IOException {
  try (Jar jar = JarFactory.newInstance(url)) {
    jar.nextEntry();
    String entryName = jar.getEntryName();
    while (entryName != null) {
      if (entryName.startsWith(TomcatConf.META_INF_RESOURCES)) {
        context.getResources()
            .createWebResourceSet(WebResourceRoot.ResourceSetType.RESOURCE_JAR, Strings.SLASH,
                url, TomcatConf.META_INF_RESOURCES_PATH);
        break;
      }
      jar.nextEntry();
      entryName = jar.getEntryName();
    }
  }
}
 
Example #2
Source File: FatJarScanner.java    From oxygen with Apache License 2.0 6 votes vote down vote up
/**
 * Scan a URL for JARs with the optional extensions to look at all files and all directories.
 */
private void process(JarScanType scanType, JarScannerCallback callback, URL url,
    String webappPath, boolean isWebapp, Deque<URL> classPathUrlsToProcess) throws IOException {

  if (log.isTraceEnabled()) {
    log.trace(SM.getString("jarScan.jarUrlStart", url));
  }

  if (Urls.URL_PROTOCOL_JAR.equals(url.getProtocol()) || url.getPath()
      .endsWith(TomcatConf.JAR_EXT)) {
    try (Jar jar = JarFactory.newInstance(url)) {
      processManifest(jar, isWebapp, classPathUrlsToProcess);
      callback.scan(jar, webappPath, isWebapp);
    }
  } else if (Urls.URL_PROTOCOL_FILE.equals(url.getProtocol())) {
    processFile(scanType, callback, url, webappPath, isWebapp, classPathUrlsToProcess);
  }
}
 
Example #3
Source File: FatJarScanner.java    From oxygen with Apache License 2.0 6 votes vote down vote up
private void processFile(JarScanType scanType, JarScannerCallback callback, URL url,
    String webappPath, boolean isWebapp, Deque<URL> classPathUrlsToProcess) throws IOException {
  try {
    File f = new File(url.toURI());
    if (f.isFile()) {
      // Treat this file as a JAR
      try (Jar jar = JarFactory.newInstance(UriUtil.buildJarUrl(f))) {
        processManifest(jar, isWebapp, classPathUrlsToProcess);
        callback.scan(jar, webappPath, isWebapp);
      }
    } else if (f.isDirectory()) {
      if (scanType == JarScanType.PLUGGABILITY) {
        callback.scan(f, webappPath, isWebapp);
      } else {
        if (new File(f.getAbsoluteFile(), TomcatConf.META_INF).isDirectory()) {
          callback.scan(f, webappPath, isWebapp);
        }
      }
    }
  } catch (URISyntaxException e) {
    throw new IOException(e);
  }
}
 
Example #4
Source File: ContextConfig.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Scan JARs that contain web-fragment.xml files that will be used to
 * configure this application to see if they also contain static resources.
 * If static resources are found, add them to the context. Resources are
 * added in web-fragment.xml priority order.
 * @param fragments The set of fragments that will be scanned for
 *  static resources
 */
protected void processResourceJARs(Set<WebXml> fragments) {
    for (WebXml fragment : fragments) {
        URL url = fragment.getURL();
        try {
            if ("jar".equals(url.getProtocol()) || url.toString().endsWith(".jar")) {
                try (Jar jar = JarFactory.newInstance(url)) {
                    jar.nextEntry();
                    String entryName = jar.getEntryName();
                    while (entryName != null) {
                        if (entryName.startsWith("META-INF/resources/")) {
                            context.getResources().createWebResourceSet(
                                    WebResourceRoot.ResourceSetType.RESOURCE_JAR,
                                    "/", url, "/META-INF/resources");
                            break;
                        }
                        jar.nextEntry();
                        entryName = jar.getEntryName();
                    }
                }
            } else if ("file".equals(url.getProtocol())) {
                File file = new File(url.toURI());
                File resources = new File(file, "META-INF/resources/");
                if (resources.isDirectory()) {
                    context.getResources().createWebResourceSet(
                            WebResourceRoot.ResourceSetType.RESOURCE_JAR,
                            "/", resources.getAbsolutePath(), null, "/");
                }
            }
        } catch (IOException ioe) {
            log.error(sm.getString("contextConfig.resourceJarFail", url,
                    context.getName()));
        } catch (URISyntaxException e) {
            log.error(sm.getString("contextConfig.resourceJarFail", url,
                context.getName()));
        }
    }
}
 
Example #5
Source File: TldResourcePath.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Opens a stream to access the TLD.
 *
 * @return a stream containing the TLD content
 * @throws IOException if there was a problem opening the stream
 */
public InputStream openStream() throws IOException {
    if (entryName == null) {
        return url.openStream();
    } else {
        URL entryUrl = JarFactory.getJarEntryURL(url, entryName);
        return entryUrl.openStream();
    }
}
 
Example #6
Source File: JspCServletContext.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Return a URL object of a resource that is mapped to the
 * specified context-relative path.
 *
 * @param path Context-relative path of the desired resource
 *
 * @exception MalformedURLException if the resource path is
 *  not properly formed
 */
@Override
public URL getResource(String path) throws MalformedURLException {

    if (!path.startsWith("/")) {
        throw new MalformedURLException("Path '" + path + "' does not start with '/'");
    }

    // Strip leading '/'
    path = path.substring(1);

    URL url = new URL(myResourceBaseURL, path);
    try (InputStream is = url.openStream()) {
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        url = null;
    }

    // During initialisation, getResource() is called before resourceJARs is
    // initialised
    if (url == null && resourceJARs != null) {
        String jarPath = "META-INF/resources/" + path;
        for (URL jarUrl : resourceJARs) {
            try (Jar jar = JarFactory.newInstance(jarUrl)) {
                if (jar.exists(jarPath)) {
                    return new URL(jar.getURL(jarPath));
                }
            } catch (IOException ioe) {
                // Ignore
            }
        }
    }
    return url;
}
 
Example #7
Source File: TesterPerformance.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testClassParserPerformance() throws IOException {
    File libDir = new File(JAR_LOCATION);
    String[] libs = libDir.list();

    Assert.assertNotNull(libs);

    Set<URL> jarURLs = new HashSet<>();

    for (String lib : libs) {
        if (!lib.toLowerCase(Locale.ENGLISH).endsWith(".jar")) {
            continue;
        }
        jarURLs.add(new URL("jar:" + new File (libDir, lib).toURI().toURL().toExternalForm() + "!/"));
    }

    long duration = 0;

    for (URL jarURL : jarURLs) {
        try (Jar jar = JarFactory.newInstance(jarURL)) {
            jar.nextEntry();
            String jarEntryName = jar.getEntryName();
            while (jarEntryName != null) {
                if (jarEntryName.endsWith(".class")) {
                    InputStream is = jar.getEntryInputStream();
                    long start = System.nanoTime();
                    ClassParser cp = new ClassParser(is);
                    cp.parse();
                    duration += System.nanoTime() - start;
                }
                jar.nextEntry();
                jarEntryName = jar.getEntryName();
            }
        }
    }

    System.out.println("ClassParser performance test took: " + duration + " ns");
}
 
Example #8
Source File: TestTldScanner.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private static void scan(TldScanner.TldScannerCallback callback, File webapp, String path)
        throws Exception {
    String fullPath = new File(webapp, path).toURI().toString();
    URL jarUrl = new URL("jar:" + fullPath + "!/");
    try (Jar jar = JarFactory.newInstance(jarUrl)) {
        callback.scan(jar, path, true);
    }
}
 
Example #9
Source File: ContextConfig.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void scan(JarURLConnection jarConn) throws IOException {

    URL url = jarConn.getURL();
    URL resourceURL = jarConn.getJarFileURL();
    Jar jar = null;
    InputStream is = null;
    WebXml fragment = new WebXml();

    try {
        jar = JarFactory.newInstance(url);
        if (parseRequired || context.getXmlValidation()) {
            is = jar.getInputStream(FRAGMENT_LOCATION);
        }

        if (is == null) {
            // If there is no web-fragment.xml to process there is no
            // impact on distributable
            fragment.setDistributable(true);
        } else {
            InputSource source = new InputSource(
                    "jar:" + resourceURL.toString() + "!/" +
                    FRAGMENT_LOCATION);
            source.setByteStream(is);
            parseWebXml(source, fragment, true);
        }
    } finally {
        if (jar != null) {
            jar.close();
        }
        fragment.setURL(url);
        if (fragment.getName() == null) {
            fragment.setName(fragment.getURL().toString());
        }
        fragment.setJarName(extractJarFileName(url));
        fragments.put(fragment.getName(), fragment);
    }
}
 
Example #10
Source File: ContextConfig.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void scan(JarURLConnection jarConn) throws IOException {

    URL url = jarConn.getURL();
    URL resourceURL = jarConn.getJarFileURL();
    Jar jar = null;
    InputStream is = null;
    WebXml fragment = new WebXml();

    try {
        jar = JarFactory.newInstance(url);
        if (parseRequired || context.getXmlValidation()) {
            is = jar.getInputStream(FRAGMENT_LOCATION);
        }

        if (is == null) {
            // If there is no web-fragment.xml to process there is no
            // impact on distributable
            fragment.setDistributable(true);
        } else {
            InputSource source = new InputSource(
                    "jar:" + resourceURL.toString() + "!/" +
                    FRAGMENT_LOCATION);
            source.setByteStream(is);
            parseWebXml(source, fragment, true);
        }
    } finally {
        if (jar != null) {
            jar.close();
        }
        fragment.setURL(url);
        if (fragment.getName() == null) {
            fragment.setName(fragment.getURL().toString());
        }
        fragment.setJarName(extractJarFileName(url));
        fragments.put(fragment.getName(), fragment);
    }
}
 
Example #11
Source File: OWBJarScanner.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@Override
public void scan(final JarScanType jarScanType, final ServletContext servletContext, final JarScannerCallback callback) {
    switch (jarScanType) {
        case PLUGGABILITY:
            CdiArchive.class.cast(WebScannerService.class.cast(WebBeansContext.getInstance().getScannerService()).getFinder().getArchive())
                    .classesByUrl().keySet().stream()
                    .filter(u -> !"jar:file://!/".equals(u)) // not a fake in memory url
                    .forEach(u -> {
                        try {
                            final URL url = new URL(u);
                            final File asFile = Files.toFile(url);
                            if (!asFile.exists()) {
                                return;
                            }
                            if (filter != null && !filter.check(jarScanType, asFile.getName())) {
                                return;
                            }

                            if (asFile.getName().endsWith(Constants.JAR_EXT)) {
                                try (final Jar jar = JarFactory.newInstance(asFile.toURI().toURL())) {
                                    callback.scan(jar, u, true);
                                }
                            } else if (asFile.isDirectory()) {
                                callback.scan(asFile, asFile.getAbsolutePath(), true);
                            }
                        } catch (final MalformedURLException e) {
                            // skip
                        } catch (final IOException ioe) {
                            throw new IllegalArgumentException(ioe);
                        }
                    });
            return;

        case TLD:
        default:
    }
}
 
Example #12
Source File: JspCServletContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Return the set of resource paths for the "directory" at the
 * specified context path.
 *
 * @param path Context-relative base path
 */
@Override
public Set<String> getResourcePaths(String path) {

    Set<String> thePaths = new HashSet<>();
    if (!path.endsWith("/")) {
        path += "/";
    }
    String basePath = getRealPath(path);
    if (basePath != null) {
        File theBaseDir = new File(basePath);
        if (theBaseDir.isDirectory()) {
            String theFiles[] = theBaseDir.list();
            if (theFiles != null) {
                for (int i = 0; i < theFiles.length; i++) {
                    File testFile = new File(basePath + File.separator + theFiles[i]);
                    if (testFile.isFile()) {
                        thePaths.add(path + theFiles[i]);
                    } else if (testFile.isDirectory()) {
                        thePaths.add(path + theFiles[i] + "/");
                    }
                }
            }
        }
    }

    // During initialisation, getResourcePaths() is called before
    // resourceJARs is initialised
    if (resourceJARs != null) {
        String jarPath = "META-INF/resources" + path;
        for (URL jarUrl : resourceJARs) {
            try (Jar jar = JarFactory.newInstance(jarUrl)) {
                jar.nextEntry();
                for (String entryName = jar.getEntryName();
                        entryName != null;
                        jar.nextEntry(), entryName = jar.getEntryName()) {
                    if (entryName.startsWith(jarPath) &&
                            entryName.length() > jarPath.length()) {
                        // Let the Set implementation handle duplicates
                        int sep = entryName.indexOf("/", jarPath.length());
                        if (sep < 0) {
                            // This is a file - strip leading "META-INF/resources"
                            thePaths.add(entryName.substring(18));
                        } else {
                            // This is a directory - strip leading "META-INF/resources"
                            thePaths.add(entryName.substring(18, sep + 1));
                        }
                    }
                }
            } catch (IOException e) {
                log(e.getMessage(), e);
            }
        }
    }

    return thePaths;
}
 
Example #13
Source File: TldLocationsCache.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
private void tldScanJar(JarURLConnection jarConn) throws IOException {

        Jar jar = null;
        InputStream is;
        boolean foundTld = false;
        
        URL resourceURL = jarConn.getJarFileURL();
        String resourcePath = resourceURL.toString();
        
        try {
            jar = JarFactory.newInstance(jarConn.getURL());
            
            jar.nextEntry();
            String entryName = jar.getEntryName();
            while (entryName != null) {
                if (entryName.startsWith("META-INF/") &&
                        entryName.endsWith(".tld")) {
                    is = null;
                    try {
                        is = jar.getEntryInputStream();
                        foundTld = true;
                        tldScanStream(resourcePath, entryName, is);
                    } finally {
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException ioe) {
                                // Ignore
                            }
                        }
                    }
                }
                jar.nextEntry();
                entryName = jar.getEntryName();
            }
        } finally {
            if (jar != null) {
                jar.close();
            }
        }

        if (!foundTld) {
            if (log.isDebugEnabled()) {
                log.debug(Localizer.getMessage("jsp.tldCache.noTldInJar",
                        resourcePath));
            } else if (showTldScanWarning) {
                // Not entirely thread-safe but a few duplicate log messages are
                // not a huge issue
                showTldScanWarning = false;
                log.info(Localizer.getMessage("jsp.tldCache.noTldSummary"));
            }
        }
    }
 
Example #14
Source File: TesterPerformance.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testClassParserPerformance() throws IOException {
    File libDir = new File(JAR_LOCATION);
    String[] libs = libDir.list();

    Assert.assertNotNull(libs);

    Set<URL> jarURLs = new HashSet<URL>();

    for (String lib : libs) {
        if (!lib.toLowerCase(Locale.ENGLISH).endsWith(".jar")) {
            continue;
        }
        jarURLs.add(new URL("jar:" + new File (libDir, lib).toURI().toURL().toExternalForm() + "!/"));
    }

    long duration = 0;

    for (URL jarURL : jarURLs) {
        Jar jar = JarFactory.newInstance(jarURL);
        try {
            jar.nextEntry();
            String jarEntryName = jar.getEntryName();
            while (jarEntryName != null) {
                if (jarEntryName.endsWith(".class")) {
                    InputStream is = jar.getEntryInputStream();
                    long start = System.nanoTime();
                    ClassParser cp = new ClassParser(is);
                    cp.parse();
                    duration += System.nanoTime() - start;
                }
                jar.nextEntry();
                jarEntryName = jar.getEntryName();
            }
        } finally {
            jar.close();
        }
    }

    System.out.println("ClassParser performance test took: " + duration + " ns");
}
 
Example #15
Source File: TldLocationsCache.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
private void tldScanJar(JarURLConnection jarConn) throws IOException {

        Jar jar = null;
        InputStream is;
        boolean foundTld = false;
        
        URL resourceURL = jarConn.getJarFileURL();
        String resourcePath = resourceURL.toString();
        
        try {
            jar = JarFactory.newInstance(jarConn.getURL());
            
            jar.nextEntry();
            String entryName = jar.getEntryName();
            while (entryName != null) {
                if (entryName.startsWith("META-INF/") &&
                        entryName.endsWith(".tld")) {
                    is = null;
                    try {
                        is = jar.getEntryInputStream();
                        foundTld = true;
                        tldScanStream(resourcePath, entryName, is);
                    } finally {
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException ioe) {
                                // Ignore
                            }
                        }
                    }
                }
                jar.nextEntry();
                entryName = jar.getEntryName();
            }
        } finally {
            if (jar != null) {
                jar.close();
            }
        }

        if (!foundTld) {
            if (log.isDebugEnabled()) {
                log.debug(Localizer.getMessage("jsp.tldCache.noTldInJar",
                        resourcePath));
            } else if (showTldScanWarning) {
                // Not entirely thread-safe but a few duplicate log messages are
                // not a huge issue
                showTldScanWarning = false;
                log.info(Localizer.getMessage("jsp.tldCache.noTldSummary"));
            }
        }
    }
 
Example #16
Source File: TesterPerformance.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testClassParserPerformance() throws IOException {
    File libDir = new File(JAR_LOCATION);
    String[] libs = libDir.list();

    Assert.assertNotNull(libs);

    Set<URL> jarURLs = new HashSet<URL>();

    for (String lib : libs) {
        if (!lib.toLowerCase(Locale.ENGLISH).endsWith(".jar")) {
            continue;
        }
        jarURLs.add(new URL("jar:" + new File (libDir, lib).toURI().toURL().toExternalForm() + "!/"));
    }

    long duration = 0;

    for (URL jarURL : jarURLs) {
        Jar jar = JarFactory.newInstance(jarURL);
        try {
            jar.nextEntry();
            String jarEntryName = jar.getEntryName();
            while (jarEntryName != null) {
                if (jarEntryName.endsWith(".class")) {
                    InputStream is = jar.getEntryInputStream();
                    long start = System.nanoTime();
                    ClassParser cp = new ClassParser(is);
                    cp.parse();
                    duration += System.nanoTime() - start;
                }
                jar.nextEntry();
                jarEntryName = jar.getEntryName();
            }
        } finally {
            jar.close();
        }
    }

    System.out.println("ClassParser performance test took: " + duration + " ns");
}