org.apache.tomcat.util.compat.JreCompat Java Examples

The following examples show how to use org.apache.tomcat.util.compat.JreCompat. 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: AbstractSingleArchiveResourceSet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected boolean isMultiRelease() {
    if (multiRelease == null) {
        synchronized (archiveLock) {
            if (multiRelease == null) {
                JarFile jarFile = null;
                try {
                    jarFile = openJarFile();
                    multiRelease = Boolean.valueOf(
                            JreCompat.getInstance().jarFileIsMultiRelease(jarFile));
                } catch (IOException ioe) {
                    // Should never happen
                    throw new IllegalStateException(ioe);
                } finally {
                    if (jarFile != null) {
                        closeJarFile();
                    }
                }
            }
        }
    }

    return multiRelease.booleanValue();
}
 
Example #2
Source File: TestParallelWebappClassLoader.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testParallelIncapableOnJre6() {
    if (JreCompat.isJre7Available()) {
        // ignore on Jre7 or above
        return;
    }
    try {
        Tomcat tomcat = getTomcatInstance();
        // Must have a real docBase - just use temp
        Context ctx = tomcat.addContext("",
                System.getProperty("java.io.tmpdir"));

        WebappLoader webappLoader = new WebappLoader();
        webappLoader.setLoaderClass(PARALLEL_CLASSLOADER);
        ctx.setLoader(webappLoader);

        tomcat.start();

        ClassLoader classloader = ctx.getLoader().getClassLoader();

        Assert.assertTrue(classloader instanceof ParallelWebappClassLoader);

        // parallel class loading capable
        Method getClassLoadingLock =
                getDeclaredMethod(classloader.getClass(), "getClassLoadingLock", String.class);
        // make sure we don't have getClassLoadingLock on JRE6.
        Assert.assertNull(getClassLoadingLock);
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("testParallelIncapableOnJre6 fails.");
    }
}
 
Example #3
Source File: TestParallelWebappClassLoader.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testParallelCapableOnJre7() {
    if (!JreCompat.isJre7Available()) {
        // ignore on Jre6 or lower
        return;
    }
    try {
        Tomcat tomcat = getTomcatInstance();
        Context ctx = tomcat.addContext("", null);

        WebappLoader webappLoader = new WebappLoader();
        webappLoader.setLoaderClass(PARALLEL_CLASSLOADER);
        ctx.setLoader(webappLoader);

        tomcat.start();

        ClassLoader classloader = ctx.getLoader().getClassLoader();

        Assert.assertTrue(classloader instanceof ParallelWebappClassLoader);

        // parallel class loading capable
        Method getClassLoadingLock =
                getDeclaredMethod(classloader.getClass(), "getClassLoadingLock", String.class);
        // make sure we have getClassLoadingLock on JRE7.
        Assert.assertNotNull(getClassLoadingLock);
        // give us permission to access protected method
        getClassLoadingLock.setAccessible(true);

        Object lock = getClassLoadingLock.invoke(classloader, DUMMY_SERVLET);
        // make sure it is not a ParallelWebappClassLoader object lock
        Assert.assertNotEquals(lock, classloader);
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("testParallelCapableOnJre7 fails.");
    }
}
 
Example #4
Source File: AbstractEndpoint.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Configures SSLEngine to honor cipher suites ordering based upon
 * endpoint configuration.
 *
 * @throws InvalidAlgorithmParameterException If the runtime JVM doesn't
 *         support this setting.
 */
protected void configureUseServerCipherSuitesOrder(SSLEngine engine) {
    String useServerCipherSuitesOrderStr = this
            .getUseServerCipherSuitesOrder().trim();

    // Only use this feature if the user explicitly requested its use.
    if(!"".equals(useServerCipherSuitesOrderStr)) {
        boolean useServerCipherSuitesOrder =
                ("true".equalsIgnoreCase(useServerCipherSuitesOrderStr)
                        || "yes".equalsIgnoreCase(useServerCipherSuitesOrderStr));
        JreCompat jreCompat = JreCompat.getInstance();
        jreCompat.setUseServerCipherSuitesOrder(engine, useServerCipherSuitesOrder);
    }
}
 
Example #5
Source File: AbstractEndpoint.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private void testServerCipherSuitesOrderSupport() {
    // Only test this feature if the user explicitly requested its use.
    if(!"".equals(getUseServerCipherSuitesOrder().trim())) {
        if (!JreCompat.isJre8Available()) {
            throw new UnsupportedOperationException(
                    sm.getString("endpoint.jsse.cannotHonorServerCipherOrder"));
        }
    }
}
 
Example #6
Source File: JSSESocketFactory.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Configures SSLEngine to honor cipher suites ordering based upon
 * endpoint configuration.
 *
 * @throws InvalidAlgorithmParameterException If the runtime JVM doesn't
 *         support this setting.
 */
protected void configureUseServerCipherSuitesOrder(SSLServerSocket socket) {
    String useServerCipherSuitesOrderStr = endpoint
            .getUseServerCipherSuitesOrder().trim();

    // Only use this feature if the user explicitly requested its use.
    if(!"".equals(useServerCipherSuitesOrderStr)) {
        boolean useServerCipherSuitesOrder =
                ("true".equalsIgnoreCase(useServerCipherSuitesOrderStr)
                        || "yes".equalsIgnoreCase(useServerCipherSuitesOrderStr));
        JreCompat jreCompat = JreCompat.getInstance();
        jreCompat.setUseServerCipherSuitesOrder(socket, useServerCipherSuitesOrder);
    }
}
 
Example #7
Source File: WebappClassLoaderBase.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private Object getClassLoadingLockInternal(String className) {
    if (JreCompat.isJre7Available() && GET_CLASSLOADING_LOCK_METHOD != null) {
        try {
            return GET_CLASSLOADING_LOCK_METHOD.invoke(this, className);
        } catch (Exception e) {
            // ignore
        }
    }
    return this;
}
 
Example #8
Source File: TestParallelWebappClassLoader.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testParallelIncapableOnJre6() {
    if (JreCompat.isJre7Available()) {
        // ignore on Jre7 or above
        return;
    }
    try {
        Tomcat tomcat = getTomcatInstance();
        // Must have a real docBase - just use temp
        Context ctx = tomcat.addContext("",
                System.getProperty("java.io.tmpdir"));

        WebappLoader webappLoader = new WebappLoader();
        webappLoader.setLoaderClass(PARALLEL_CLASSLOADER);
        ctx.setLoader(webappLoader);

        tomcat.start();

        ClassLoader classloader = ctx.getLoader().getClassLoader();

        Assert.assertTrue(classloader instanceof ParallelWebappClassLoader);

        // parallel class loading capable
        Method getClassLoadingLock =
                getDeclaredMethod(classloader.getClass(), "getClassLoadingLock", String.class);
        // make sure we don't have getClassLoadingLock on JRE6.
        Assert.assertNull(getClassLoadingLock);
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("testParallelIncapableOnJre6 fails.");
    }
}
 
Example #9
Source File: TestParallelWebappClassLoader.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testParallelCapableOnJre7() {
    if (!JreCompat.isJre7Available()) {
        // ignore on Jre6 or lower
        return;
    }
    try {
        Tomcat tomcat = getTomcatInstance();
        Context ctx = tomcat.addContext("", null);

        WebappLoader webappLoader = new WebappLoader();
        webappLoader.setLoaderClass(PARALLEL_CLASSLOADER);
        ctx.setLoader(webappLoader);

        tomcat.start();

        ClassLoader classloader = ctx.getLoader().getClassLoader();

        Assert.assertTrue(classloader instanceof ParallelWebappClassLoader);

        // parallel class loading capable
        Method getClassLoadingLock =
                getDeclaredMethod(classloader.getClass(), "getClassLoadingLock", String.class);
        // make sure we have getClassLoadingLock on JRE7.
        Assert.assertNotNull(getClassLoadingLock);
        // give us permission to access protected method
        getClassLoadingLock.setAccessible(true);

        Object lock = getClassLoadingLock.invoke(classloader, DUMMY_SERVLET);
        // make sure it is not a ParallelWebappClassLoader object lock
        Assert.assertNotEquals(lock, classloader);
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("testParallelCapableOnJre7 fails.");
    }
}
 
Example #10
Source File: AbstractEndpoint.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Configures SSLEngine to honor cipher suites ordering based upon
 * endpoint configuration.
 *
 * @throws InvalidAlgorithmParameterException If the runtime JVM doesn't
 *         support this setting.
 */
protected void configureUseServerCipherSuitesOrder(SSLEngine engine) {
    String useServerCipherSuitesOrderStr = this
            .getUseServerCipherSuitesOrder().trim();

    // Only use this feature if the user explicitly requested its use.
    if(!"".equals(useServerCipherSuitesOrderStr)) {
        boolean useServerCipherSuitesOrder =
                ("true".equalsIgnoreCase(useServerCipherSuitesOrderStr)
                        || "yes".equalsIgnoreCase(useServerCipherSuitesOrderStr));
        JreCompat jreCompat = JreCompat.getInstance();
        jreCompat.setUseServerCipherSuitesOrder(engine, useServerCipherSuitesOrder);
    }
}
 
Example #11
Source File: AbstractEndpoint.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private void testServerCipherSuitesOrderSupport() {
    // Only test this feature if the user explicitly requested its use.
    if(!"".equals(getUseServerCipherSuitesOrder().trim())) {
        if (!JreCompat.isJre8Available()) {
            throw new UnsupportedOperationException(
                    sm.getString("endpoint.jsse.cannotHonorServerCipherOrder"));
        }
    }
}
 
Example #12
Source File: JSSESocketFactory.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Configures SSLEngine to honor cipher suites ordering based upon
 * endpoint configuration.
 *
 * @throws InvalidAlgorithmParameterException If the runtime JVM doesn't
 *         support this setting.
 */
protected void configureUseServerCipherSuitesOrder(SSLServerSocket socket) {
    String useServerCipherSuitesOrderStr = endpoint
            .getUseServerCipherSuitesOrder().trim();

    // Only use this feature if the user explicitly requested its use.
    if(!"".equals(useServerCipherSuitesOrderStr)) {
        boolean useServerCipherSuitesOrder =
                ("true".equalsIgnoreCase(useServerCipherSuitesOrderStr)
                        || "yes".equalsIgnoreCase(useServerCipherSuitesOrderStr));
        JreCompat jreCompat = JreCompat.getInstance();
        jreCompat.setUseServerCipherSuitesOrder(socket, useServerCipherSuitesOrder);
    }
}
 
Example #13
Source File: WebappClassLoaderBase.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private Object getClassLoadingLockInternal(String className) {
    if (JreCompat.isJre7Available() && GET_CLASSLOADING_LOCK_METHOD != null) {
        try {
            return GET_CLASSLOADING_LOCK_METHOD.invoke(this, className);
        } catch (Exception e) {
            // ignore
        }
    }
    return this;
}
 
Example #14
Source File: TomcatEmbeddedWebappClassLoader.java    From spring-graalvm-native with Apache License 2.0 5 votes vote down vote up
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
	synchronized (JreCompat.isGraalAvailable() ? this : getClassLoadingLock(name)) {
		Class<?> result = findExistingLoadedClass(name);
		result = (result != null) ? result : doLoadClass(name);
		if (result == null) {
			throw new ClassNotFoundException(name);
		}
		return resolveIfNecessary(result, resolve);
	}
}
 
Example #15
Source File: TestSSLHostConfigCompat.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();

    AprLifecycleListener listener = new AprLifecycleListener();
    Assume.assumeTrue(AprLifecycleListener.isAprAvailable());
    Assume.assumeTrue(JreCompat.isJre8Available());

    Tomcat tomcat = getTomcatInstance();
    Connector connector = tomcat.getConnector();

    connector.setPort(0);
    connector.setScheme("https");
    connector.setSecure(true);
    connector.setProperty("SSLEnabled", "true");
    connector.setProperty("sslImplementationName", sslImplementationName);
    sslHostConfig.setProtocols("TLSv1.2");
    connector.addSslHostConfig(sslHostConfig);

    StandardServer server = (StandardServer) tomcat.getServer();
    server.addLifecycleListener(listener);

    // Simple webapp
    Context ctxt = tomcat.addContext("", null);
    Tomcat.addServlet(ctxt, "TesterServlet", new TesterServlet());
    ctxt.addServletMappingDecoded("/*", "TesterServlet");
}
 
Example #16
Source File: AbstractSingleArchiveResourceSet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void initInternal() throws LifecycleException {

    try (JarFile jarFile = JreCompat.getInstance().jarFileNewInstance(getBase())) {
        setManifest(jarFile.getManifest());
    } catch (IOException ioe) {
        throw new IllegalArgumentException(ioe);
    }

    try {
        setBaseUrl(UriUtil.buildJarSafeUrl(new File(getBase())));
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #17
Source File: AbstractArchiveResourceSet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
protected JarFile openJarFile() throws IOException {
    synchronized (archiveLock) {
        if (archive == null) {
            archive = JreCompat.getInstance().jarFileNewInstance(getBase());
        }
        archiveUseCount++;
        return archive;
    }
}
 
Example #18
Source File: TestJarInputStreamWrapper.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private InputStream getUnwrappedClosedInputStream() throws IOException {
    File file = new File("test/webresources/non-static-resources.jar");
    JarFile jarFile = JreCompat.getInstance().jarFileNewInstance(file);
    ZipEntry jarEntry = jarFile.getEntry("META-INF/MANIFEST.MF");
    InputStream unwrapped = jarFile.getInputStream(jarEntry);
    unwrapped.close();
    jarFile.close();
    return unwrapped;
}
 
Example #19
Source File: SSLHostConfig.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * @return An OpenSSL cipher string for the current configuration.
 */
public String getCiphers() {
    if (ciphers == null) {
        if (!JreCompat.isJre8Available() && Type.JSSE.equals(configType)) {
            ciphers = DEFAULT_CIPHERS + ":!DHE";
        } else {
            ciphers = DEFAULT_CIPHERS;
        }

    }
    return ciphers;
}
 
Example #20
Source File: AbstractJsseEndpoint.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void testServerCipherSuitesOrderSupport() {
    // Only need to test for this if running on Java < 8 and not using the
    // OpenSSL SSLImplementation
    if(!JreCompat.isJre8Available() &&
            !OpenSSLImplementation.class.getName().equals(getSslImplementationName())) {
        for (SSLHostConfig sslHostConfig : sslHostConfigs.values()) {
            if (sslHostConfig.getHonorCipherOrder() != null) {
                throw new UnsupportedOperationException(
                        sm.getString("endpoint.jsse.cannotHonorServerCipherOrder"));
            }
        }
    }
}
 
Example #21
Source File: TesterBug50640SslImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public SSLUtil getSSLUtil(SSLHostConfigCertificate certificate) {
    SSLHostConfig sslHostConfig = certificate.getSSLHostConfig();
    if (sslHostConfig.getProtocols().size() == 1 &&
            sslHostConfig.getProtocols().contains(PROPERTY_VALUE)) {
        if (JreCompat.isJre8Available()) {
            sslHostConfig.setProtocols(Constants.SSL_PROTO_TLSv1_2);
        } else {
            sslHostConfig.setProtocols(Constants.SSL_PROTO_TLSv1);
        }
        return super.getSSLUtil(certificate);
    } else {
        return null;
    }
}
 
Example #22
Source File: AbstractInputStreamJar.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void reset() throws IOException {
    closeStream();
    entry = null;
    jarInputStream = createJarInputStream();
    // Only perform multi-release processing on first access
    if (multiRelease == null) {
        if (JreCompat.isJre9Available()) {
            Manifest manifest = jarInputStream.getManifest();
            if (manifest == null) {
                multiRelease = Boolean.FALSE;
            } else {
                String mrValue = manifest.getMainAttributes().getValue("Multi-Release");
                if (mrValue == null) {
                    multiRelease = Boolean.FALSE;
                } else {
                    multiRelease = Boolean.valueOf(mrValue);
                }
            }
        } else {
            multiRelease = Boolean.FALSE;
        }
        if (multiRelease.booleanValue()) {
            if (mrMap == null) {
                populateMrMap();
            }
        }
    }
}
 
Example #23
Source File: AbstractJsseEndpoint.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
protected SSLEngine createSSLEngine(String sniHostName, List<Cipher> clientRequestedCiphers,
        List<String> clientRequestedApplicationProtocols) {
    SSLHostConfig sslHostConfig = getSSLHostConfig(sniHostName);

    SSLHostConfigCertificate certificate = selectCertificate(sslHostConfig, clientRequestedCiphers);

    SSLContext sslContext = certificate.getSslContext();
    if (sslContext == null) {
        throw new IllegalStateException(
                sm.getString("endpoint.jsse.noSslContext", sniHostName));
    }

    SSLEngine engine = sslContext.createSSLEngine();
    engine.setUseClientMode(false);
    engine.setEnabledCipherSuites(sslHostConfig.getEnabledCiphers());
    engine.setEnabledProtocols(sslHostConfig.getEnabledProtocols());

    SSLParameters sslParameters = engine.getSSLParameters();
    String honorCipherOrderStr = sslHostConfig.getHonorCipherOrder();
    if (honorCipherOrderStr != null) {
        boolean honorCipherOrder = Boolean.parseBoolean(honorCipherOrderStr);
        JreCompat.getInstance().setUseServerCipherSuitesOrder(sslParameters, honorCipherOrder);
    }

    if (JreCompat.isJre9Available() && clientRequestedApplicationProtocols != null
            && clientRequestedApplicationProtocols.size() > 0
            && negotiableProtocols.size() > 0) {
        // Only try to negotiate if both client and server have at least
        // one protocol in common
        // Note: Tomcat does not explicitly negotiate http/1.1
        // TODO: Is this correct? Should it change?
        List<String> commonProtocols = new ArrayList<>();
        commonProtocols.addAll(negotiableProtocols);
        commonProtocols.retainAll(clientRequestedApplicationProtocols);
        if (commonProtocols.size() > 0) {
            String[] commonProtocolsArray = commonProtocols.toArray(new String[commonProtocols.size()]);
            JreCompat.getInstance().setApplicationProtocols(sslParameters, commonProtocolsArray);
        }
    }
    switch (sslHostConfig.getCertificateVerification()) {
    case NONE:
        sslParameters.setNeedClientAuth(false);
        sslParameters.setWantClientAuth(false);
        break;
    case OPTIONAL:
    case OPTIONAL_NO_CA:
        sslParameters.setWantClientAuth(true);
        break;
    case REQUIRED:
        sslParameters.setNeedClientAuth(true);
        break;
    }
    // The getter (at least in OpenJDK and derivatives) returns a defensive copy
    engine.setSSLParameters(sslParameters);

    return engine;
}
 
Example #24
Source File: WebappClassLoaderBase.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void checkThreadLocalsForLeaks() {
    Thread[] threads = getThreads();

    try {
        // Make the fields in the Thread class that store ThreadLocals
        // accessible
        Field threadLocalsField =
            Thread.class.getDeclaredField("threadLocals");
        threadLocalsField.setAccessible(true);
        Field inheritableThreadLocalsField =
            Thread.class.getDeclaredField("inheritableThreadLocals");
        inheritableThreadLocalsField.setAccessible(true);
        // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects
        // accessible
        Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
        Field tableField = tlmClass.getDeclaredField("table");
        tableField.setAccessible(true);
        Method expungeStaleEntriesMethod = tlmClass.getDeclaredMethod("expungeStaleEntries");
        expungeStaleEntriesMethod.setAccessible(true);

        for (int i = 0; i < threads.length; i++) {
            Object threadLocalMap;
            if (threads[i] != null) {

                // Clear the first map
                threadLocalMap = threadLocalsField.get(threads[i]);
                if (null != threadLocalMap){
                    expungeStaleEntriesMethod.invoke(threadLocalMap);
                    checkThreadLocalMapForLeaks(threadLocalMap, tableField);
                }

                // Clear the second map
                threadLocalMap =inheritableThreadLocalsField.get(threads[i]);
                if (null != threadLocalMap){
                    expungeStaleEntriesMethod.invoke(threadLocalMap);
                    checkThreadLocalMapForLeaks(threadLocalMap, tableField);
                }
            }
        }
    } catch (Throwable t) {
        JreCompat jreCompat = JreCompat.getInstance();
        if (jreCompat.isInstanceOfInaccessibleObjectException(t)) {
            // Must be running on Java 9 without the necessary command line
            // options.
            log.warn(sm.getString("webappClassLoader.addExportsThreadLocal"));
        } else {
            ExceptionUtils.handleThrowable(t);
            log.warn(sm.getString(
                    "webappClassLoader.checkThreadLocalsForLeaksFail",
                    getContextName()), t);
        }
    }
}
 
Example #25
Source File: JarWarResourceSet.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * JarWar can't optimise for a single resource so the Map is always
 * returned.
 */
@Override
protected HashMap<String,JarEntry> getArchiveEntries(boolean single) {
    synchronized (archiveLock) {
        if (archiveEntries == null) {
            JarFile warFile = null;
            InputStream jarFileIs = null;
            archiveEntries = new HashMap<>();
            boolean multiRelease = false;
            try {
                warFile = openJarFile();
                JarEntry jarFileInWar = warFile.getJarEntry(archivePath);
                jarFileIs = warFile.getInputStream(jarFileInWar);

                try (TomcatJarInputStream jarIs = new TomcatJarInputStream(jarFileIs)) {
                    JarEntry entry = jarIs.getNextJarEntry();
                    while (entry != null) {
                        archiveEntries.put(entry.getName(), entry);
                        entry = jarIs.getNextJarEntry();
                    }
                    Manifest m = jarIs.getManifest();
                    setManifest(m);
                    if (m != null && JreCompat.isJre9Available()) {
                        String value = m.getMainAttributes().getValue("Multi-Release");
                        if (value != null) {
                            multiRelease = Boolean.parseBoolean(value);
                        }
                    }
                    // Hack to work-around JarInputStream swallowing these
                    // entries. TomcatJarInputStream is used above which
                    // extends JarInputStream and the method that creates
                    // the entries over-ridden so we can a) tell if the
                    // entries are present and b) cache them so we can
                    // access them here.
                    entry = jarIs.getMetaInfEntry();
                    if (entry != null) {
                        archiveEntries.put(entry.getName(), entry);
                    }
                    entry = jarIs.getManifestEntry();
                    if (entry != null) {
                        archiveEntries.put(entry.getName(), entry);
                    }
                }
                if (multiRelease) {
                    processArchivesEntriesForMultiRelease();
                }
            } catch (IOException ioe) {
                // Should never happen
                archiveEntries = null;
                throw new IllegalStateException(ioe);
            } finally {
                if (warFile != null) {
                    closeJarFile();
                }
                if (jarFileIs != null) {
                    try {
                        jarFileIs.close();
                    } catch (IOException e) {
                        // Ignore
                    }
                }
            }
        }
        return archiveEntries;
    }
}
 
Example #26
Source File: StandardJarScanner.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
protected void doScanClassPath(JarScanType scanType, ServletContext context,
        JarScannerCallback callback, Set<URL> processedURLs) {
    if (log.isTraceEnabled()) {
        log.trace(sm.getString("jarScan.classloaderStart"));
    }

    ClassLoader stopLoader = null;
    if (!isScanBootstrapClassPath()) {
        // Stop when we reach the bootstrap class loader
        stopLoader = ClassLoader.getSystemClassLoader().getParent();
    }

    ClassLoader classLoader = context.getClassLoader();

    // JARs are treated as application provided until the common class
    // loader is reached.
    boolean isWebapp = true;

    // Use a Deque so URLs can be removed as they are processed
    // and new URLs can be added as they are discovered during
    // processing.
    Deque<URL> classPathUrlsToProcess = new LinkedList<>();

    while (classLoader != null && classLoader != stopLoader) {
        if (classLoader instanceof URLClassLoader) {
            if (isWebapp) {
                isWebapp = isWebappClassLoader(classLoader);
            }

            classPathUrlsToProcess.addAll(
                    Arrays.asList(((URLClassLoader) classLoader).getURLs()));

            processURLs(scanType, callback, processedURLs, isWebapp, classPathUrlsToProcess);
        }
        classLoader = classLoader.getParent();
    }

    if (JreCompat.isJre9Available()) {
        // The application and platform class loaders are not
        // instances of URLClassLoader. Use the class path in this
        // case.
        addClassPath(classPathUrlsToProcess);
        // Also add any modules
        JreCompat.getInstance().addBootModulePath(classPathUrlsToProcess);
        processURLs(scanType, callback, processedURLs, false, classPathUrlsToProcess);
    }
}
 
Example #27
Source File: AbstractInputStreamJar.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void populateMrMap() throws IOException {
    int targetVersion = JreCompat.getInstance().jarFileRuntimeMajorVersion();

    Map<String,Integer> mrVersions = new HashMap<>();

    JarEntry jarEntry = jarInputStream.getNextJarEntry();

    // Tracking the base name and the latest valid version found is
    // sufficient to be able to create the renaming map required
    while (jarEntry != null) {
        String name = jarEntry.getName();
        if (name.startsWith("META-INF/versions/") && name.endsWith(".class")) {

            // Get the base name and version for this versioned entry
            int i = name.indexOf('/', 18);
            if (i > 0) {
                String baseName = name.substring(i + 1);
                int version = Integer.parseInt(name.substring(18, i));

                // Ignore any entries targeting for a later version than
                // the target for this runtime
                if (version <= targetVersion) {
                    Integer mappedVersion = mrVersions.get(baseName);
                    if (mappedVersion == null) {
                        // No version found for this name. Create one.
                        mrVersions.put(baseName, Integer.valueOf(version));
                    } else {
                        // Ignore any entry for which we have already found
                        // a later version
                        if (version > mappedVersion.intValue()) {
                            // Replace the earlier version
                            mrVersions.put(baseName, Integer.valueOf(version));
                        }
                    }
                }
            }
        }
        jarEntry = jarInputStream.getNextJarEntry();
    }

    mrMap = new HashMap<>();

    for (Entry<String,Integer> mrVersion : mrVersions.entrySet()) {
        mrMap.put(mrVersion.getKey() , "META-INF/versions/" + mrVersion.getValue().toString() +
                "/" +  mrVersion.getKey());
    }

    // Reset stream back to the beginning of the JAR
    closeStream();
    jarInputStream = createJarInputStream();
}
 
Example #28
Source File: JSSEImplementation.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public boolean isAlpnSupported() {
    return JreCompat.isJre9Available();
}
 
Example #29
Source File: FatJarScanner.java    From oxygen with Apache License 2.0 4 votes vote down vote up
private void doScanClassPath(JarScanType scanType, ServletContext context,
    JarScannerCallback callback, Set<URL> processedURLs) {
  if (log.isTraceEnabled()) {
    log.trace(SM.getString("jarScan.classloaderStart"));
  }
  ClassLoader classLoader = context.getClassLoader();

  ClassLoader stopLoader = null;
  if (classLoader.getParent() != null) {
    // Stop when we reach the bootstrap class loader
    stopLoader = classLoader.getParent().getParent();
  }

  // JARs are treated as application provided until the common class
  // loader is reached.
  boolean isWebapp = true;

  // Use a Deque so URLs can be removed as they are processed
  // and new URLs can be added as they are discovered during
  // processing.
  Deque<URL> classPathUrlsToProcess = new LinkedList<>();

  while (classLoader != null && classLoader != stopLoader) {
    if (classLoader instanceof URLClassLoader) {
      if (isWebapp) {
        isWebapp = isWebappClassLoader(classLoader);
      }

      classPathUrlsToProcess.addAll(Arrays.asList(((URLClassLoader) classLoader).getURLs()));

      processURLs(scanType, callback, processedURLs, isWebapp, classPathUrlsToProcess);
    }
    classLoader = classLoader.getParent();
  }

  if (JreCompat.isJre9Available()) {
    // The application and platform class loaders are not
    // instances of URLClassLoader. Use the class path in this
    // case.
    addClassPath(classPathUrlsToProcess);
    // Also add any modules
    JreCompat.getInstance().addBootModulePath(classPathUrlsToProcess);
    processURLs(scanType, callback, processedURLs, false, classPathUrlsToProcess);
  }
}
 
Example #30
Source File: TomcatEmbeddedWebappClassLoader.java    From spring-graalvm-native with Apache License 2.0 4 votes vote down vote up
private Class<?> findExistingLoadedClass(String name) {
	Class<?> resultClass = findLoadedClass0(name);
	resultClass = (resultClass != null || JreCompat.isGraalAvailable()) ? resultClass : findLoadedClass(name);
	return resultClass;
}