org.apache.catalina.loader.WebappLoader Java Examples

The following examples show how to use org.apache.catalina.loader.WebappLoader. 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: MBeanFactory.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Create a new Web Application Loader.
 *
 * @param parent MBean Name of the associated parent component
 * @return the object name of the created loader
 *
 * @exception Exception if an MBean cannot be created or registered
 */
public String createWebappLoader(String parent)
    throws Exception {

    // Create a new WebappLoader instance
    WebappLoader loader = new WebappLoader();

    // Add the new instance to its parent component
    ObjectName pname = new ObjectName(parent);
    Container container = getParentContainerFromParent(pname);
    if (container instanceof Context) {
        ((Context) container).setLoader(loader);
    }
    // FIXME add Loader.getObjectName
    //ObjectName oname = loader.getObjectName();
    ObjectName oname =
        MBeanUtils.createObjectName(pname.getDomain(), loader);
    return oname.toString();

}
 
Example #2
Source File: InvokeJaxrsResourceInTomcat.java    From glowroot with Apache License 2.0 6 votes vote down vote up
public void executeApp(String webapp, String contextPath, String url) throws Exception {
    int port = getAvailablePort();
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/tomcat");
    tomcat.setPort(port);
    Context context = tomcat.addWebapp(contextPath,
            new File("src/test/resources/" + webapp).getAbsolutePath());

    WebappLoader webappLoader =
            new WebappLoader(InvokeJaxrsResourceInTomcat.class.getClassLoader());
    context.setLoader(webappLoader);

    tomcat.start();
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    int statusCode = asyncHttpClient.prepareGet("http://localhost:" + port + contextPath + url)
            .execute().get().getStatusCode();
    asyncHttpClient.close();
    if (statusCode != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }

    tomcat.stop();
    tomcat.destroy();
}
 
Example #3
Source File: InvokeJaxwsWebServiceInTomcat.java    From glowroot with Apache License 2.0 6 votes vote down vote up
public void executeApp(String webapp, String contextPath, String url) throws Exception {
    int port = getAvailablePort();
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/tomcat");
    tomcat.setPort(port);
    Context context = tomcat.addWebapp(contextPath,
            new File("src/test/resources/" + webapp).getAbsolutePath());

    WebappLoader webappLoader =
            new WebappLoader(InvokeJaxwsWebServiceInTomcat.class.getClassLoader());
    context.setLoader(webappLoader);

    tomcat.start();

    JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    factory.setServiceClass(ForBothHelloAndRootService.class);
    factory.setAddress("http://localhost:" + port + contextPath + url);
    ForBothHelloAndRootService client = (ForBothHelloAndRootService) factory.create();
    client.echo("abc");

    checkForRequestThreads(webappLoader);
    tomcat.stop();
    tomcat.destroy();
}
 
Example #4
Source File: StrutsOneIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void executeApp() throws Exception {
    int port = getAvailablePort();
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/tomcat");
    tomcat.setPort(port);
    Context context =
            tomcat.addWebapp("", new File("src/test/resources/struts1").getAbsolutePath());

    WebappLoader webappLoader =
            new WebappLoader(ExecuteActionInTomcat.class.getClassLoader());
    context.setLoader(webappLoader);

    tomcat.start();

    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    int statusCode = asyncHttpClient.prepareGet("http://localhost:" + port + "/hello.do")
            .execute().get().getStatusCode();
    asyncHttpClient.close();
    if (statusCode != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }

    tomcat.stop();
    tomcat.destroy();
}
 
Example #5
Source File: InvokeServletInTomcat.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void executeApp() throws Exception {
    int port = getAvailablePort();
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/tomcat");
    tomcat.setPort(port);
    Context context =
            tomcat.addWebapp(contextPath, new File("src/test/resources").getAbsolutePath());

    WebappLoader webappLoader =
            new WebappLoader(InvokeServletInTomcat.class.getClassLoader());
    context.setLoader(webappLoader);

    // this is needed in order for Tomcat to find annotated servlet
    VirtualDirContext resources = new VirtualDirContext();
    resources.setExtraResourcePaths("/WEB-INF/classes=target/test-classes");
    context.setResources(resources);

    tomcat.start();

    doTest(port);

    tomcat.stop();
    tomcat.destroy();
}
 
Example #6
Source File: GrailsIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void executeApp() throws Exception {
    int port = getAvailablePort();
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/tomcat");
    tomcat.setPort(port);
    Context context =
            tomcat.addWebapp("", new File("src/test/resources").getAbsolutePath());

    WebappLoader webappLoader = new WebappLoader(RenderInTomcat.class.getClassLoader());
    context.setLoader(webappLoader);

    // this is needed in order for Tomcat to find annotated classes
    VirtualDirContext resources = new VirtualDirContext();
    resources.setExtraResourcePaths("/WEB-INF/classes=target/test-classes");
    context.setResources(resources);

    tomcat.start();

    doTest(port);

    tomcat.stop();
    tomcat.destroy();
}
 
Example #7
Source File: JsfRenderIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void executeApp() throws Exception {
    int port = getAvailablePort();
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/tomcat");
    tomcat.setPort(port);
    Context context =
            tomcat.addWebapp("", new File("src/test/resources").getAbsolutePath());

    WebappLoader webappLoader = new WebappLoader(RenderJsfInTomcat.class.getClassLoader());
    context.setLoader(webappLoader);

    tomcat.start();

    doTest(port);

    tomcat.stop();
    tomcat.destroy();
}
 
Example #8
Source File: InvokeJaxwsWebServiceInTomcat.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private void checkForRequestThreads(WebappLoader webappLoader) throws Exception {
    Method getThreadsMethod = WebappClassLoaderBase.class.getDeclaredMethod("getThreads");
    getThreadsMethod.setAccessible(true);
    Method isRequestThreadMethod =
            WebappClassLoaderBase.class.getDeclaredMethod("isRequestThread", Thread.class);
    isRequestThreadMethod.setAccessible(true);
    ClassLoader webappClassLoader = webappLoader.getClassLoader();
    Thread[] threads = (Thread[]) getThreadsMethod.invoke(webappClassLoader);
    for (Thread thread : threads) {
        if (thread == null) {
            continue;
        }
        if ((boolean) isRequestThreadMethod.invoke(webappClassLoader, thread)) {
            StringBuilder sb = new StringBuilder();
            for (StackTraceElement element : thread.getStackTrace()) {
                sb.append(element);
                sb.append('\n');
            }
            logger.error("tomcat request thread \"{}\" is still active:\n{}", thread.getName(),
                    sb);
        }
    }
}
 
Example #9
Source File: RedisSessionRequestValveTest.java    From redis-session-manager with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    this.request = mock(Request.class, withSettings().useConstructor()); // useConstructor to instantiate fields
    this.response = mock(Response.class);

    final Context contextContainer = mock(Context.class);
    this.hostContainer = mock(Host.class);

    when(contextContainer.getParent()).thenReturn(hostContainer);
    when(contextContainer.getPath()).thenReturn("/");

    when(request.getRequestURI()).thenReturn("/requestURI"); // override for tests
    when(request.getMethod()).thenReturn("GET");
    when(request.getQueryString()).thenReturn(null);
    when(request.getContext()).thenReturn(contextContainer);

    doCallRealMethod().when(request).setNote(Mockito.anyString(), Mockito.anyObject());
    doCallRealMethod().when(request).removeNote(Mockito.anyString());
    when(request.getNote(Mockito.anyString())).thenCallRealMethod();

    when(contextContainer.getLoader()).thenReturn(new WebappLoader(Thread.currentThread().getContextClassLoader()));
}
 
Example #10
Source File: Server.java    From product-ei with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final File base = createBaseDirectory();
    log.info("Using base folder: " + base.getAbsolutePath());

    final Tomcat tomcat = new Tomcat();
    tomcat.setPort(8080);
    tomcat.setBaseDir( base.getAbsolutePath() );

    Context context = tomcat.addContext( "/", base.getAbsolutePath() );
    Tomcat.addServlet( context, "CXFServlet", new CXFServlet() );

    context.addServletMapping( "/rest/*", "CXFServlet" );
    context.addApplicationListener( ContextLoaderListener.class.getName() );
    context.setLoader( new WebappLoader( Thread.currentThread().getContextClassLoader() ) );

    context.addParameter( "contextClass", AnnotationConfigWebApplicationContext.class.getName() );
    context.addParameter( "contextConfigLocation", MusicConfig.class.getName() );

    tomcat.start();
    tomcat.getServer().await();
}
 
Example #11
Source File: Starter.java    From product-ei with Apache License 2.0 6 votes vote down vote up
public void startPeopleService() throws Exception {
    final File base = createBaseDirectory();
    log.info("Using base folder: " + base.getAbsolutePath());

    final Tomcat tomcat = new Tomcat();
    tomcat.setPort(8080);
    tomcat.setBaseDir(base.getAbsolutePath());

    Context context = tomcat.addContext("/", base.getAbsolutePath());
    Tomcat.addServlet(context, "CXFServlet", new CXFServlet());

    context.addServletMapping("/rest/*", "CXFServlet");
    context.addApplicationListener(ContextLoaderListener.class.getName());
    context.setLoader(new WebappLoader(Thread.currentThread().getContextClassLoader()));

    context.addParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
    context.addParameter("contextConfigLocation", AppConfig.class.getName());

    tomcat.start();
    tomcat.getServer().await();
}
 
Example #12
Source File: MBeanFactory.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new Web Application Loader.
 *
 * @param parent MBean Name of the associated parent component
 *
 * @exception Exception if an MBean cannot be created or registered
 */
public String createWebappLoader(String parent)
    throws Exception {

    // Create a new WebappLoader instance
    WebappLoader loader = new WebappLoader();

    // Add the new instance to its parent component
    ObjectName pname = new ObjectName(parent);
    ContainerBase containerBase = getParentContainerFromParent(pname);
    if (containerBase != null) {
        containerBase.setLoader(loader);
    } 
    // FIXME add Loader.getObjectName
    //ObjectName oname = loader.getObjectName();
    ObjectName oname = 
        MBeanUtils.createObjectName(pname.getDomain(), loader);
    return (oname.toString());
    
}
 
Example #13
Source File: InvokeSpringControllerInTomcat.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private void checkForRequestThreads(WebappLoader webappLoader) throws Exception {
    Method getThreadsMethod = WebappClassLoaderBase.class.getDeclaredMethod("getThreads");
    getThreadsMethod.setAccessible(true);
    Method isRequestThreadMethod =
            WebappClassLoaderBase.class.getDeclaredMethod("isRequestThread", Thread.class);
    isRequestThreadMethod.setAccessible(true);
    ClassLoader webappClassLoader = webappLoader.getClassLoader();
    Thread[] threads = (Thread[]) getThreadsMethod.invoke(webappClassLoader);
    for (Thread thread : threads) {
        if (thread == null) {
            continue;
        }
        if ((Boolean) isRequestThreadMethod.invoke(webappClassLoader, thread)) {
            StringBuilder sb = new StringBuilder();
            for (StackTraceElement element : thread.getStackTrace()) {
                sb.append(element);
                sb.append('\n');
            }
            logger.error("tomcat request thread \"{}\" is still active:\n{}", thread.getName(),
                    sb);
        }
    }
}
 
Example #14
Source File: MBeanFactory.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new Web Application Loader.
 *
 * @param parent MBean Name of the associated parent component
 *
 * @exception Exception if an MBean cannot be created or registered
 */
public String createWebappLoader(String parent)
    throws Exception {

    // Create a new WebappLoader instance
    WebappLoader loader = new WebappLoader();

    // Add the new instance to its parent component
    ObjectName pname = new ObjectName(parent);
    ContainerBase containerBase = getParentContainerFromParent(pname);
    if (containerBase != null) {
        containerBase.setLoader(loader);
    } 
    // FIXME add Loader.getObjectName
    //ObjectName oname = loader.getObjectName();
    ObjectName oname = 
        MBeanUtils.createObjectName(pname.getDomain(), loader);
    return (oname.toString());
    
}
 
Example #15
Source File: WebappLoaderStartInterceptor.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    // target should be an instance of WebappLoader.
    if (target instanceof WebappLoader) {
        WebappLoader webappLoader = (WebappLoader)target;
        try {
            String contextKey = extractContextKey(webappLoader);
            List<String> loadedJarNames = extractLibJars(webappLoader);
            dispatchLibJars(contextKey, loadedJarNames);
        } catch (Exception e) {
            if (logger.isWarnEnabled()) {
                logger.warn(e.getMessage(), e);
            }
        }
    } else {
        logger.warn("Webapp loader is not an instance of org.apache.catalina.loader.WebappLoader. Found [{}]", target.getClass().toString());
    }
}
 
Example #16
Source File: WebappLoaderStartInterceptor.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private String extractContextKey(WebappLoader webappLoader) {
    final String defaultContextName = "";
    try {
        Container container = extractContext(webappLoader);
        // WebappLoader's associated Container should be a Context.
        if (container instanceof Context) {
            Context context = (Context)container;
            String contextName = context.getName();
            Host host = (Host)container.getParent();
            Engine engine = (Engine)host.getParent();
            StringBuilder sb = new StringBuilder();
            sb.append(engine.getName()).append("/").append(host.getName());
            if (!contextName.startsWith("/")) {
                sb.append('/');
            }
            sb.append(contextName);
            return sb.toString();
        }
    } catch (Exception e) {
        // Same action for any and all exceptions.
        logger.warn("Error extracting context name.", e);
    }
    return defaultContextName;
}
 
Example #17
Source File: WebappLoaderStartInterceptor.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private Container extractContext(WebappLoader webappLoader) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Method m;
    try {
        // Tomcat 6, 7 - org.apache.catalina.loader.getContainer() 
        m = webappLoader.getClass().getDeclaredMethod("getContainer");
    } catch (NoSuchMethodException e1) {
        try {
            // Tomcat 8 - org.apache.catalina.loader.getContainer()
            m = webappLoader.getClass().getDeclaredMethod("getContext");
        } catch (NoSuchMethodException e2) {
            logger.warn("Webapp loader does not have access to its container.");
            return null;
        }
    }
    Object container = m.invoke(webappLoader);
    if (container instanceof Container) {
        return (Container)container;
    }
    return null;
}
 
Example #18
Source File: Server.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final File base = createBaseDirectory();
    log.info("Using base folder: " + base.getAbsolutePath());

    final Tomcat tomcat = new Tomcat();
    tomcat.setPort(8080);
    tomcat.setBaseDir(base.getAbsolutePath());

    Context context = tomcat.addContext("/", base.getAbsolutePath());
    Tomcat.addServlet(context, "CXFServlet", new CXFServlet());

    context.addServletMapping("/rest/*", "CXFServlet");
    context.addApplicationListener(ContextLoaderListener.class.getName());
    context.setLoader(new WebappLoader(Thread.currentThread().getContextClassLoader()));

    context.addParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
    context.addParameter("contextConfigLocation", MusicConfig.class.getName());

    tomcat.start();
    tomcat.getServer().await();
}
 
Example #19
Source File: Starter.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public void startPeopleService() throws Exception {
    final File base = createBaseDirectory();
    log.info("Using base folder: " + base.getAbsolutePath());

    final Tomcat tomcat = new Tomcat();
    tomcat.setPort(8080);
    tomcat.setBaseDir(base.getAbsolutePath());

    Context context = tomcat.addContext("/", base.getAbsolutePath());
    Tomcat.addServlet(context, "CXFServlet", new CXFServlet());

    context.addServletMapping("/rest/*", "CXFServlet");
    context.addApplicationListener(ContextLoaderListener.class.getName());
    context.setLoader(new WebappLoader(Thread.currentThread().getContextClassLoader()));

    context.addParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
    context.addParameter("contextConfigLocation", AppConfig.class.getName());

    tomcat.start();
    tomcat.getServer().await();
}
 
Example #20
Source File: InvokeSpringControllerInTomcat.java    From glowroot with Apache License 2.0 5 votes vote down vote up
public void executeApp(String webapp, String contextPath, RunnableWithPort runnable)
        throws Exception {
    int port = getAvailablePort();
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/tomcat");
    tomcat.setPort(port);
    Context context = tomcat.addWebapp(contextPath,
            new File("src/test/resources/" + webapp).getAbsolutePath());

    WebappLoader webappLoader =
            new WebappLoader(InvokeSpringControllerInTomcat.class.getClassLoader());
    context.setLoader(webappLoader);

    tomcat.start();

    runnable.run(port);

    // spring still does a bit of work after the response is concluded,
    // see org.springframework.web.servlet.FrameworkServlet.publishRequestHandledEvent(),
    // so give a bit of time here, otherwise end up with sporadic test failures due to
    // ERROR logged by org.apache.catalina.loader.WebappClassLoaderBase, e.g.
    // "The web application [] is still processing a request that has yet to finish"
    MILLISECONDS.sleep(200);
    checkForRequestThreads(webappLoader);
    tomcat.stop();
    tomcat.destroy();
}
 
Example #21
Source File: WebappLoaderStartInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private List<String> extractLibJars(WebappLoader webappLoader) {
    ClassLoader classLoader = webappLoader.getClassLoader();
    if (classLoader instanceof URLClassLoader) {
        URLClassLoader webappClassLoader = (URLClassLoader)classLoader;
        URL[] urls = webappClassLoader.getURLs();
        return extractLibJarNamesFromURLs(urls);
    } else {
        logger.warn("Webapp class loader is not an instance of URLClassLoader. Found [{}]", classLoader.getClass().toString());
        return Collections.emptyList();
    } 
}
 
Example #22
Source File: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void initContextLoader(final StandardContext standardContext) {
    final Loader standardContextLoader = standardContext.getLoader();
    if (standardContextLoader != null
            && (
            (!TomEEWebappLoader.class.equals(standardContextLoader.getClass())
                && !WebappLoader.class.equals(standardContextLoader.getClass()))
                    || (WebappLoader.class.equals(standardContextLoader.getClass())
                            && !WebappLoader.class.cast(standardContextLoader).getLoaderClass().startsWith("org.apache.tom")))
            ) {
        // custom loader, we don't know it
        // and since we don't have a full delegate pattern for our lazy stop loader
        // simply skip lazy stop loader - normally sides effect will be an early shutdown for ears and some particular features
        // only affecting the app if the classes were not laoded at all
        return;
    }

    if (standardContextLoader != null && TomEEWebappLoader.class.isInstance(standardContextLoader)) {
        standardContextLoader.setContext(standardContext);
        return; // no need to replace the loader
    }

    // we just want to wrap it to lazy stop it (afterstop)
    // to avoid classnotfound in @PreDestoy or destroyApplication()
    final TomEEWebappLoader loader = new TomEEWebappLoader();
    loader.setDelegate(standardContext.getDelegate());
    loader.setLoaderClass(TomEEWebappClassLoader.class.getName());

    final Loader lazyStopLoader = new LazyStopLoader(loader);
    standardContext.setLoader(lazyStopLoader);
}
 
Example #23
Source File: LoaderSF.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Is this an instance of the default <code>Loader</code> configuration,
 * with all-default properties?
 *
 * @param loader
 *            Loader to be tested
 * @return <code>true</code> if this is an instance of the default loader
 */
protected boolean isDefaultLoader(Loader loader) {

    if (!(loader instanceof WebappLoader)) {
        return false;
    }
    WebappLoader wloader = (WebappLoader) loader;
    if ((wloader.getDelegate() != false)
            || !wloader.getLoaderClass().equals(
                    "org.apache.catalina.loader.WebappClassLoader")) {
        return false;
    }
    return true;
}
 
Example #24
Source File: StrutsTwoIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void executeApp() throws Exception {
    int port = getAvailablePort();
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/tomcat");
    tomcat.setPort(port);
    String subdir;
    try {
        Class.forName("org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter");
        subdir = "struts2.5";
    } catch (ClassNotFoundException e) {
        subdir = "struts2";
    }
    Context context = tomcat.addWebapp("",
            new File("src/test/resources/" + subdir).getAbsolutePath());

    WebappLoader webappLoader =
            new WebappLoader(ExecuteActionInTomcat.class.getClassLoader());
    context.setLoader(webappLoader);

    tomcat.start();

    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    int statusCode =
            asyncHttpClient.prepareGet("http://localhost:" + port + "/hello.action")
                    .execute().get().getStatusCode();
    asyncHttpClient.close();
    if (statusCode != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }

    tomcat.stop();
    tomcat.destroy();
}
 
Example #25
Source File: Embedded.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Create and return a class loader manager that can be customized, and
 * then attached to a Context, before it is started.
 *
 * @param parent ClassLoader that will be the parent of the one
 *  created by this Loader
 */
public Loader createLoader(ClassLoader parent) {

    if( log.isDebugEnabled() )
        log.debug("Creating Loader with parent class loader '" +
                   parent + "'");

    WebappLoader loader = new WebappLoader(parent);
    return (loader);

}
 
Example #26
Source File: SpringBootTomcatPlusIT.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public void onDeployUAVApp(Object... args) {
    
    if(UAVServer.ServerVendor.SPRINGBOOT!=UAVServer.instance().getServerInfo(CaptureConstants.INFO_APPSERVER_VENDOR)) {
        return;
    }
    
    Tomcat tomcat=(Tomcat) args[0];
    String mofRoot=(String) args[1];
    
    //add uavApp
    StandardContext context=new StandardContext();
    context.setName("com.creditease.uav");
    context.setPath("/com.creditease.uav");
    context.setDocBase(mofRoot + "/com.creditease.uav");
    context.addLifecycleListener(new Tomcat.FixContextListener());
    tomcat.getHost().addChild(context);
    
    //add default servlet
    Wrapper servlet = context.createWrapper();
    servlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
    servlet.setName("default");
    context.addChild(servlet);    
    servlet.setOverridable(true);
    context.addServletMapping("/", "default");
    
    //init webapp classloader
    context.setLoader(new WebappLoader(Thread.currentThread().getContextClassLoader()));
    context.setDelegate(true);
    
    //after tomcat8, skip jarscan
    Object obj=ReflectionHelper.newInstance("org.apache.tomcat.util.scan.StandardJarScanner", Thread.currentThread().getContextClassLoader());
    if(obj!=null) {
        ReflectionHelper.invoke("org.apache.tomcat.util.scan.StandardJarScanner", obj, "setScanAllFiles", new Class<?>[]{Boolean.class}, new Object[] { false}, Thread.currentThread().getContextClassLoader());
        ReflectionHelper.invoke("org.apache.tomcat.util.scan.StandardJarScanner", obj, "setScanClassPath", new Class<?>[]{Boolean.class}, new Object[] { false}, Thread.currentThread().getContextClassLoader());
        ReflectionHelper.invoke("org.apache.tomcat.util.scan.StandardJarScanner", obj, "setScanAllDirectories", new Class<?>[]{Boolean.class}, new Object[] { false}, Thread.currentThread().getContextClassLoader());            
        
        context.setJarScanner((JarScanner) obj);      
    }        
}
 
Example #27
Source File: Embedded.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Create and return a class loader manager that can be customized, and
 * then attached to a Context, before it is started.
 *
 * @param parent ClassLoader that will be the parent of the one
 *  created by this Loader
 */
public Loader createLoader(ClassLoader parent) {

    if( log.isDebugEnabled() )
        log.debug("Creating Loader with parent class loader '" +
                   parent + "'");

    WebappLoader loader = new WebappLoader(parent);
    return (loader);

}
 
Example #28
Source File: ArkTomcatServletWebServerFactory.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
@Override
protected void prepareContext(Host host, ServletContextInitializer[] initializers) {
    if (host.getState() == LifecycleState.NEW) {
        super.prepareContext(host, initializers);
    } else {
        File documentRoot = getValidDocumentRoot();
        StandardContext context = new StandardContext();
        if (documentRoot != null) {
            context.setResources(new StandardRoot(context));
        }
        context.setName(getContextPath());
        context.setDisplayName(getDisplayName());
        context.setPath(getContextPath());
        File docBase = (documentRoot != null) ? documentRoot : createTempDir("tomcat-docbase");
        context.setDocBase(docBase.getAbsolutePath());
        context.addLifecycleListener(new Tomcat.FixContextListener());
        context.setParentClassLoader(Thread.currentThread().getContextClassLoader());
        resetDefaultLocaleMapping(context);
        addLocaleMappings(context);
        context.setUseRelativeRedirects(false);
        configureTldSkipPatterns(context);
        WebappLoader loader = new WebappLoader(context.getParentClassLoader());
        loader
            .setLoaderClass("com.alipay.sofa.ark.web.embed.tomcat.ArkTomcatEmbeddedWebappClassLoader");
        loader.setDelegate(true);
        context.setLoader(loader);
        if (isRegisterDefaultServlet()) {
            addDefaultServlet(context);
        }
        if (shouldRegisterJspServlet()) {
            addJspServlet(context);
            addJasperInitializer(context);
        }
        context.addLifecycleListener(new StaticResourceConfigurer(context));
        ServletContextInitializer[] initializersToUse = mergeInitializers(initializers);
        context.setParent(host);
        configureContext(context, initializersToUse);
        host.addChild(context);
    }
}
 
Example #29
Source File: TomcatServer.java    From athena-rest with Apache License 2.0 4 votes vote down vote up
private void initTomcat() {
	serverStatus = ServerStatus.STARTING;

	tomcat = new Tomcat();
	tomcat.setPort(port);

	// Changed it to use NIO due to poor performance in burdon test
	Connector connector = new Connector(Utils.getStringProperty(properties, "web.connectorProtocol"));

	
	connector.setURIEncoding("UTF-8");
	connector.setPort(port);
	connector.setUseBodyEncodingForURI(true);
	connector.setAsyncTimeout(Utils.getIntegerValue(properties,
			WEB_ASYNC_TIMEOUT, DEFAULT_ASYNC_TIMEOUT));
	connector.setAttribute("minProcessors", Utils.getIntegerValue(
			properties, WEB_MIN_PROCESSORS, DEFAULT_MIN_PROCESSORS));
	connector.setAttribute("maxProcessors", Utils.getIntegerValue(
			properties, WEB_MAX_PROCESSORS, DEFAULT_MAX_PROCESSORS));
	connector.setAttribute("acceptCount", Utils.getIntegerValue(properties,
			WEB_ACCEPT_COUNT, DEFAULT_ACCEPT_COUNT));
	connector.setAttribute("minSpareThreads", Utils.getIntegerValue(
			properties, WEB_MIN_SPARE_THREADS, DEFAULT_MIN_SPARE_THREADS));
	connector.setAttribute("maxThreads", Utils.getIntegerValue(properties,
			WEB_MAX_THREADS, DEFAULT_MAX_THREADS));
	connector.setRedirectPort(Utils.getIntegerValue(properties,
			WEB_REDIRECT_PORT, DEFAULT_WEB_REDIRECT_PORT));
	
	if (this.minThreads != -1 && this.maxThreads != -1) {
		connector.setAttribute("minThreads", minThreads);
		connector.setAttribute("maxThreads", maxThreads);
	}

	Service tomcatService = tomcat.getService();
	tomcatService.addConnector(connector);
	tomcat.setConnector(connector);

	Context context = null;
	try {
		context = tomcat.addWebapp(contextPath,
				new File(webappPath).getAbsolutePath());
	} catch (ServletException e) {
		log.error("Failed to add webapp + " + webappPath, e);

		exit();
	}
	context.setLoader(new WebappLoader(Thread.currentThread()
			.getContextClassLoader()));

	String extraResourcePaths = properties
			.getProperty(WEB_EXTRA_RESOURCE_PATHS);
	if (!StringUtils.isBlank(extraResourcePaths)) {
		VirtualDirContext virtualDirContext = new VirtualDirContext();
		virtualDirContext.setExtraResourcePaths(extraResourcePaths);
		context.setResources(virtualDirContext);
	}

	StandardServer server = (StandardServer) tomcat.getServer();
	AprLifecycleListener listener = new AprLifecycleListener();
	server.addLifecycleListener(listener);
}
 
Example #30
Source File: EmbeddedTomcatCustomizer.java    From pulsar-manager with Apache License 2.0 4 votes vote down vote up
@Bean
public ServletWebServerFactory servletContainer() {
    log.info("Starting servletContainer");
    return new TomcatServletWebServerFactory() {
        @Override
        protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
            try {
                log.info("Catalina base is " + tomcat.getServer().getCatalinaBase().getAbsolutePath());
                File lib = new File("lib").getAbsoluteFile();
                if (lib.isDirectory()) {
                    File bkvmWar = searchWar(lib, "bkvm", ".war");
                    if (bkvmWar != null) {
                        File configFile = new File("bkvm.conf");
                        log.info("looking for BKVM configuration file at " + configFile.getAbsolutePath());
                        if (configFile.isFile()) {
                            Properties props = new Properties();
                            try (FileReader reader = new FileReader(configFile)) {
                                props.load(reader);
                            }
                            boolean bkvmEnabled = Boolean.parseBoolean(props.getProperty("bkvm.enabled", "false"));
                            log.info("Read bkvm.enabled = {}", bkvmEnabled);
                            if (bkvmEnabled) {
                                System.setProperty("bookkeeper.visual.manager.config.path", configFile.getAbsolutePath());
                                File file = new File(tomcat.getServer().getCatalinaBase(), "/webapps");
                                log.info("Tomcat Webapps directory is " + file.getAbsolutePath());
                                file.mkdirs();
                                File bkvmDirectory = new File(file, "bkvm");
                                log.info("Deploying BKVM to " + bkvmDirectory.getAbsolutePath());
                                unZip(bkvmWar, bkvmDirectory);
                                Context context = tomcat.addWebapp("/bkvm", bkvmDirectory.getAbsolutePath());
                                WebappLoader loader = new WebappLoader(Thread.currentThread().getContextClassLoader());
                                context.setLoader(loader);
                            }
                        }
                    }
                }
                return super.getTomcatWebServer(tomcat);
            } catch (IOException | ServletException ex) {
                throw new RuntimeException(ex);
            }
        }

    };
}