Java Code Examples for org.eclipse.jetty.webapp.WebAppContext#setClassLoader()

The following examples show how to use org.eclipse.jetty.webapp.WebAppContext#setClassLoader() . 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: JettyServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
static WebAppContext newWebAppContext() throws MalformedURLException {
    final WebAppContext handler = new WebAppContext();
    handler.setContextPath("/");
    handler.setBaseResource(Resource.newResource(webAppRoot()));
    handler.setClassLoader(new URLClassLoader(
            new URL[] {
                    Resource.newResource(new File(webAppRoot(),
                                                  "WEB-INF" + File.separatorChar +
                                                  "lib" + File.separatorChar +
                                                  "hello.jar")).getURI().toURL()
            },
            JettyService.class.getClassLoader()));

    handler.addBean(new ServletContainerInitializersStarter(handler), true);
    handler.setAttribute(
            "org.eclipse.jetty.containerInitializers",
            Collections.singletonList(new ContainerInitializer(new JettyJasperInitializer(), null)));
    return handler;
}
 
Example 2
Source File: EmbeddedServer.java    From xdocreport.samples with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void main( String[] args )
    throws Exception
{
    Server server = new Server( 8080 );

    WebAppContext webappcontext = new WebAppContext( "src/main/webapp", "/jaxrs" );

    ContextHandlerCollection servlet_contexts = new ContextHandlerCollection();
    webappcontext.setClassLoader( Thread.currentThread().getContextClassLoader() );
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers( new Handler[] { servlet_contexts, webappcontext, new DefaultHandler() } );

    server.setHandler( handlers );


    server.start();
    server.join();
}
 
Example 3
Source File: EmbeddedServer.java    From xdocreport.samples with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void main( String[] args )
    throws Exception
{
    Server server = new Server( 8080 );

    WebAppContext webappcontext = new WebAppContext( "src/main/webapp", "/jaxrs" );

    ContextHandlerCollection servlet_contexts = new ContextHandlerCollection();
    webappcontext.setClassLoader( Thread.currentThread().getContextClassLoader() );
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers( new Handler[] { servlet_contexts, webappcontext, new DefaultHandler() } );

    server.setHandler( handlers );


    server.start();
    server.join();
}
 
Example 4
Source File: DockerSimpleBuildWrapperTest.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
@Override
protected ServletContext createWebServer() throws Exception {
    server = new Server(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), r -> {
        Thread t = new Thread(r);
        t.setName("Jetty Thread Pool");
        return t;
    })));

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(configureUserRealm());
    context.setResourceBase(WarExploder.getExplodedDir().getPath());

    ServerConnector connector = new ServerConnector(server);
    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost(ADDRESS);
    if (System.getProperty("port") != null)
        connector.setPort(Integer.parseInt(System.getProperty("port")));

    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();
    LOG.info("Running on {}", getURL());

    return context.getServletContext();
}
 
Example 5
Source File: HessianServer.java    From MyTv with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws Exception {
	// 启动web应用
	org.eclipse.jetty.server.Server server = new Server();
	server.setStopAtShutdown(true);
	SelectChannelConnector connector = new SelectChannelConnector();
	connector.setPort(Config.NET_CONFIG.getHessianPort());
	connector.setHost(Config.NET_CONFIG.getIp());
	// 解决Windows下重复启动Jetty居然不报告端口冲突的问题.
	connector.setReuseAddress(false);
	server.setConnectors(new Connector[] { connector });
	// web配置
	WebAppContext context = new WebAppContext();
	String resourcePath = MyTvUtils.getRunningPath(HessianServer.class);
	logger.info("web app context path: " + resourcePath);
	context.setContextPath("/");
	String descriptor = resourcePath + "/WEB-INF/web.xml";
	logger.info("web app descriptor: " + descriptor);
	context.setDescriptor(descriptor);
	context.setResourceBase(resourcePath);
	context.setParentLoaderPriority(true);
	ClassLoader appClassLoader = Thread.currentThread()
			.getContextClassLoader();
	context.setClassLoader(appClassLoader);

	server.setHandler(context);
	server.start();
}
 
Example 6
Source File: SSLTest.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Override
protected WebAppContext getWebAppContext(String path) {
    WebAppContext application = new WebAppContext(path, "/");
    application.setDescriptor(System.getProperty("projectBaseDir") + "/webapp/src/test/webapp/WEB-INF/web.xml");
    application.setClassLoader(Thread.currentThread().getContextClassLoader());
    return application;
}
 
Example 7
Source File: BaseSSLAndKerberosTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Override
protected WebAppContext getWebAppContext(String path) {
    WebAppContext application = new WebAppContext(path, "/");
    application.setDescriptor(System.getProperty("projectBaseDir") + "/webapp/src/test/webapp/WEB-INF/web.xml");
    application.setClassLoader(Thread.currentThread().getContextClassLoader());
    return application;
}
 
Example 8
Source File: AtlasAuthenticationKerberosFilterTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Override
protected WebAppContext getWebAppContext(String path) {
    WebAppContext application = new WebAppContext(path, "/");
    application.setDescriptor(System.getProperty("projectBaseDir") + "/webapp/src/test/webapp/WEB-INF/web.xml");
    application.setClassLoader(Thread.currentThread().getContextClassLoader());
    return application;
}
 
Example 9
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Prepares a webapp hosting environment to get {@link ServletContext} implementation
 * that we need for testing.
 */
protected ServletContext createWebServer() throws Exception {
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (HudsonTestCase)");
    server = new Server(qtp);

    explodedWarDir = WarExploder.getExplodedDir();
    WebAppContext context = new WebAppContext(explodedWarDir.getPath(), contextPath);
    context.setResourceBase(explodedWarDir.getPath());
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(configureUserRealm());

    ServerConnector connector = new ServerConnector(server);

    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost("localhost");

    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();

    return context.getServletContext();
}
 
Example 10
Source File: DevServer.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
private static void reloadWebAppContext(Server server) throws Exception {
    WebAppContext webAppContext = (WebAppContext) server.getHandler();
    System.out.println("[INFO] Application reloading");
    webAppContext.stop();
    WebAppClassLoader classLoader = new WebAppClassLoader(webAppContext);
    classLoader.addClassPath(getAbsolutePath() + "target/classes");
    classLoader.addClassPath(getAbsolutePath() + "target/test-classes");
    webAppContext.setClassLoader(classLoader);
    webAppContext.start();
    System.out.println("[INFO] Application reloaded");
}
 
Example 11
Source File: JettyFactory.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void reloadWebAppContext(Server server) throws Exception {
	WebAppContext webAppContext = (WebAppContext) server.getHandler();
	System.out.println("[INFO] Application reloading");
	webAppContext.stop();
	WebAppClassLoader classLoader = new WebAppClassLoader(webAppContext);
	classLoader.addClassPath(getAbsolutePath() + "target/classes");
	classLoader.addClassPath(getAbsolutePath() + "target/test-classes");
	webAppContext.setClassLoader(classLoader);
	webAppContext.start();
	System.out.println("[INFO] Application reloaded");
}
 
Example 12
Source File: JettyFactory.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void reloadWebAppContext(Server server) throws Exception {
	WebAppContext webAppContext = (WebAppContext) server.getHandler();
	System.out.println("[INFO] Application reloading");
	webAppContext.stop();
	WebAppClassLoader classLoader = new WebAppClassLoader(webAppContext);
	classLoader.addClassPath(getAbsolutePath() + "target/classes");
	classLoader.addClassPath(getAbsolutePath() + "target/test-classes");
	webAppContext.setClassLoader(classLoader);
	webAppContext.start();
	System.out.println("[INFO] Application reloaded");
}
 
Example 13
Source File: BaseSSLAndKerberosTest.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Override
protected WebAppContext getWebAppContext(String path) {
    WebAppContext application = new WebAppContext(path, "/");
    application.setDescriptor(System.getProperty("projectBaseDir") + "/webapp/src/test/webapp/WEB-INF/web.xml");
    application.setClassLoader(Thread.currentThread().getContextClassLoader());
    return application;
}
 
Example 14
Source File: JettyFactory.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void reloadWebAppContext(Server server) throws Exception {
	WebAppContext webAppContext = (WebAppContext) server.getHandler();
	System.out.println("[INFO] Application reloading");
	webAppContext.stop();
	WebAppClassLoader classLoader = new WebAppClassLoader(webAppContext);
	classLoader.addClassPath(getAbsolutePath() + "target/classes");
	classLoader.addClassPath(getAbsolutePath() + "target/test-classes");
	webAppContext.setClassLoader(classLoader);
	webAppContext.start();
	System.out.println("[INFO] Application reloaded");
}
 
Example 15
Source File: EmbeddedServer.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
protected WebAppContext getWebAppContext(String path) {
    WebAppContext application = new WebAppContext(path, "/");
    application.setClassLoader(Thread.currentThread().getContextClassLoader());
    // Disable directory listing
    application.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    return application;
}
 
Example 16
Source File: JettyServer.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
private WebAppContext loadWar(final File warFile, final String contextPath, final URL[] additionalResources)
        throws IOException {
    final WebAppContext webappContext = new WebAppContext(warFile.getPath(), contextPath);
    webappContext.setContextPath(contextPath);
    webappContext.setDisplayName(contextPath);

    // remove slf4j server class to allow WAR files to have slf4j dependencies in WEB-INF/lib
    List<String> serverClasses = new ArrayList<>(Arrays.asList(webappContext.getServerClasses()));
    serverClasses.remove("org.slf4j.");
    webappContext.setServerClasses(serverClasses.toArray(new String[0]));
    webappContext.setDefaultsDescriptor(WEB_DEFAULTS_XML);

    // get the temp directory for this webapp
    final File webWorkingDirectory = properties.getWebWorkingDirectory();
    final File tempDir = new File(webWorkingDirectory, warFile.getName());
    if (tempDir.exists() && !tempDir.isDirectory()) {
        throw new RuntimeException(tempDir.getAbsolutePath() + " is not a directory");
    } else if (!tempDir.exists()) {
        final boolean made = tempDir.mkdirs();
        if (!made) {
            throw new RuntimeException(tempDir.getAbsolutePath() + " could not be created");
        }
    }
    if (!(tempDir.canRead() && tempDir.canWrite())) {
        throw new RuntimeException(tempDir.getAbsolutePath() + " directory does not have read/write privilege");
    }

    // configure the temp dir
    webappContext.setTempDirectory(tempDir);

    // configure the max form size (3x the default)
    webappContext.setMaxFormContentSize(600000);

    // add HTTP security headers to all responses
    final String ALL_PATHS = "/*";
    ArrayList<Class<? extends Filter>> filters = new ArrayList<>(Arrays.asList(XFrameOptionsFilter.class, ContentSecurityPolicyFilter.class, XSSProtectionFilter.class));
    if(properties.isHTTPSConfigured()) {
        filters.add(StrictTransportSecurityFilter.class);
    }

    filters.forEach( (filter) -> addFilters(filter, ALL_PATHS, webappContext));

    // start out assuming the system ClassLoader will be the parent, but if additional resources were specified then
    // inject a new ClassLoader in between the system and webapp ClassLoaders that contains the additional resources
    ClassLoader parentClassLoader = ClassLoader.getSystemClassLoader();
    if (additionalResources != null && additionalResources.length > 0) {
        URLClassLoader additionalClassLoader = new URLClassLoader(additionalResources, ClassLoader.getSystemClassLoader());
        parentClassLoader = additionalClassLoader;
    }

    webappContext.setClassLoader(new WebAppClassLoader(parentClassLoader, webappContext));

    logger.info("Loading WAR: " + warFile.getAbsolutePath() + " with context path set to " + contextPath);
    return webappContext;
}
 
Example 17
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
/**
 * Creates a web server on which Jenkins can run
 *
 * @param contextPath              the context path at which to put Jenkins
 * @param portSetter               the port on which the server runs will be set using this function
 * @param classLoader              the class loader for the {@link WebAppContext}
 * @param localPort                port on which the server runs
 * @param loginServiceSupplier     configures the {@link LoginService} for the instance
 * @param contextAndServerConsumer configures the {@link WebAppContext} and the {@link Server} for the instance, before they are started
 * @return ImmutablePair consisting of the {@link Server} and the {@link ServletContext}
 * @since 2.50
 */
public static ImmutablePair<Server, ServletContext> _createWebServer(String contextPath, Consumer<Integer> portSetter,
                                                                     ClassLoader classLoader, int localPort,
                                                                     Supplier<LoginService> loginServiceSupplier,
                                                                     @CheckForNull BiConsumer<WebAppContext, Server> contextAndServerConsumer)
        throws Exception {
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (JenkinsRule)");
    Server server = new Server(qtp);

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(classLoader);
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(loginServiceSupplier.get());
    context.setResourceBase(WarExploder.getExplodedDir().getPath());

    ServerConnector connector = new ServerConnector(server);
    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost("localhost");
    if (System.getProperty("port") != null) {
        connector.setPort(Integer.parseInt(System.getProperty("port")));
    } else if (localPort != 0) {
        connector.setPort(localPort);
    }

    server.addConnector(connector);
    if (contextAndServerConsumer != null) {
        contextAndServerConsumer.accept(context, server);
    }
    server.start();

    portSetter.accept(connector.getLocalPort());

    ServletContext servletContext =  context.getServletContext();
    return new ImmutablePair<>(server, servletContext);
}
 
Example 18
Source File: JettyAppServer.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private void setEmbeddedClassloaderForDeployment(WebAppContext webAppContext) {
    ClassLoader parentCl = Thread.currentThread().getContextClassLoader();
    webAppContext.setClassLoader(parentCl);
}
 
Example 19
Source File: JettyLauncher.java    From JobX with Apache License 2.0 4 votes vote down vote up
@Override
public void start(boolean devMode, int port) throws Exception {

    Server server = new Server(new QueuedThreadPool(Constants.WEB_THREADPOOL_SIZE));

    WebAppContext appContext = new WebAppContext();
    String resourceBasePath = "";
    //开发者模式
    if (devMode) {
        String artifact = MavenUtils.get(Thread.currentThread().getContextClassLoader()).getArtifactId();
        resourceBasePath = artifact + "/src/main/webapp";
    }
    appContext.setDescriptor(resourceBasePath + "WEB-INF/web.xml");
    appContext.setResourceBase(resourceBasePath);
    appContext.setExtractWAR(true);

    //init param
    appContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    if (CommonUtils.isWindows()) {
        appContext.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
    }

    //for jsp support
    appContext.addBean(new JettyJspParser(appContext));
    appContext.addServlet(JettyJspServlet.class, "*.jsp");

    appContext.setContextPath("/");
    appContext.getServletContext().setExtendedListenerTypes(true);
    appContext.setParentLoaderPriority(true);
    appContext.setThrowUnavailableOnStartupException(true);
    appContext.setConfigurationDiscovered(true);
    appContext.setClassLoader(Thread.currentThread().getContextClassLoader());


    ServerConnector connector = new ServerConnector(server);
    connector.setHost("localhost");
    connector.setPort(port);

    server.setConnectors(new Connector[]{connector});
    server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", 1024 * 1024 * 1024);
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);
    server.setStopAtShutdown(true);
    server.setHandler(appContext);
    logger.info("[JobX] JettyLauncher starting...");
    server.start();
}
 
Example 20
Source File: JettyServer.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
private WebAppContext loadWar(final File warFile, final String contextPath, final ClassLoader parentClassLoader) {
    final WebAppContext webappContext = new WebAppContext(warFile.getPath(), contextPath);
    webappContext.setContextPath(contextPath);
    webappContext.setDisplayName(contextPath);

    // instruction jetty to examine these jars for tlds, web-fragments, etc
    webappContext.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\\\.jar$|.*/[^/]*taglibs.*\\.jar$" );

    // remove slf4j server class to allow WAR files to have slf4j dependencies in WEB-INF/lib
    List<String> serverClasses = new ArrayList<>(Arrays.asList(webappContext.getServerClasses()));
    serverClasses.remove("org.slf4j.");
    webappContext.setServerClasses(serverClasses.toArray(new String[0]));
    webappContext.setDefaultsDescriptor(WEB_DEFAULTS_XML);

    // get the temp directory for this webapp
    File tempDir = new File(props.getWebWorkingDirectory(), warFile.getName());
    if (tempDir.exists() && !tempDir.isDirectory()) {
        throw new RuntimeException(tempDir.getAbsolutePath() + " is not a directory");
    } else if (!tempDir.exists()) {
        final boolean made = tempDir.mkdirs();
        if (!made) {
            throw new RuntimeException(tempDir.getAbsolutePath() + " could not be created");
        }
    }
    if (!(tempDir.canRead() && tempDir.canWrite())) {
        throw new RuntimeException(tempDir.getAbsolutePath() + " directory does not have read/write privilege");
    }

    // configure the temp dir
    webappContext.setTempDirectory(tempDir);

    // configure the max form size (3x the default)
    webappContext.setMaxFormContentSize(600000);

    try {
        // configure the class loader - webappClassLoader -> jetty nar -> web app's nar -> ...
        webappContext.setClassLoader(new WebAppClassLoader(parentClassLoader, webappContext));
    } catch (final IOException ioe) {
        startUpFailure(ioe);
    }

    logger.info("Loading WAR: " + warFile.getAbsolutePath() + " with context path set to " + contextPath);
    return webappContext;
}