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

The following examples show how to use org.eclipse.jetty.webapp.WebAppContext#addBean() . 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: App.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
private WebAppContext createDeployedApplicationInstance(File workDirectory,
		String deployedApplicationPath) {
	WebAppContext deployedApplication = new WebAppContext();
	deployedApplication.setContextPath(this.getContextPath());
	deployedApplication.setWar(deployedApplicationPath);
	deployedApplication.setAttribute("javax.servlet.context.tempdir",
			workDirectory.getAbsolutePath());
	deployedApplication
			.setAttribute(
					"org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
					".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/.*taglibs.*\\.jar$");
	deployedApplication.setAttribute(
			"org.eclipse.jetty.containerInitializers", jspInitializers());
	deployedApplication.setAttribute(InstanceManager.class.getName(),
			new SimpleInstanceManager());
	deployedApplication.addBean(new ServletContainerInitializersStarter(
			deployedApplication), true);
	// webapp.setClassLoader(new URLClassLoader(new
	// URL[0],App.class.getClassLoader()));
	deployedApplication.addServlet(jspServletHolder(), "*.jsp");
	return deployedApplication;
}
 
Example 2
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 3
Source File: JettyServiceStartupTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
static WebAppContext newWebAppContext() throws MalformedURLException {
    final File webAppRoot = WebAppContainerTest.webAppRoot();
    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 4
Source File: JenkinsRuleNonLocalhost.java    From kubernetes-pipeline-plugin with Apache License 2.0 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 {
    server = new Server(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),new ThreadFactory() {
        public Thread newThread(Runnable 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(HOST);
    if (System.getProperty("port")!=null)
        connector.setPort(Integer.parseInt(System.getProperty("port")));

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

    localPort = connector.getLocalPort();
    LOGGER.log(Level.INFO, "Running on {0}", getURL());

    return context.getServletContext();
}
 
Example 5
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 6
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 7
Source File: EmbeddedJettyServer.java    From Alpine with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final CliArgs cliArgs = new CliArgs(args);
    final String contextPath = cliArgs.switchValue("-context", "/");
    final String host = cliArgs.switchValue("-host", "0.0.0.0");
    final int port = cliArgs.switchIntegerValue("-port", 8080);

    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();

    final Server server = new Server();
    final HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.addCustomizer( new org.eclipse.jetty.server.ForwardedRequestCustomizer() ); // Add support for X-Forwarded headers

    final HttpConnectionFactory connectionFactory = new HttpConnectionFactory( httpConfig );
    final ServerConnector connector = new ServerConnector(server, connectionFactory);
    connector.setHost(host);
    connector.setPort(port);
    disableServerVersionHeader(connector);
    server.setConnectors(new Connector[]{connector});

    final WebAppContext context = new WebAppContext();
    context.setServer(server);
    context.setContextPath(contextPath);
    context.setErrorHandler(new ErrorHandler());
    context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/[^/]*taglibs.*\\.jar$");
    context.setAttribute("org.eclipse.jetty.containerInitializers", jspInitializers());
    context.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
    context.addBean(new ServletContainerInitializersStarter(context), true);

    // Prevent loading of logging classes
    context.getSystemClasspathPattern().add("org.apache.log4j.");
    context.getSystemClasspathPattern().add("org.slf4j.");
    context.getSystemClasspathPattern().add("org.apache.commons.logging.");

    final ProtectionDomain protectionDomain = EmbeddedJettyServer.class.getProtectionDomain();
    final URL location = protectionDomain.getCodeSource().getLocation();
    context.setWar(location.toExternalForm());

    server.setHandler(context);
    server.addBean(new ErrorHandler());
    try {
        server.start();
        addJettyShutdownHook(server);
        server.join();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
}
 
Example 8
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 9
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 10
Source File: JenkinsRuleNonLocalhost.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Prepares a webapp hosting environment to get {@link javax.servlet.ServletContext} implementation
 * that we need for testing.
 */
protected ServletContext createWebServer() throws Exception {
    server = new Server(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),new ThreadFactory() {
        public Thread newThread(Runnable 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);
    System.err.println("Listening on host address: " + HOST);
    connector.setHost(HOST);

    if (System.getProperty("port")!=null) {
        LOGGER.info("Overriding port using system property: " + System.getProperty("port"));
        connector.setPort(Integer.parseInt(System.getProperty("port")));
    } else {
        if (port != null) {
            connector.setPort(port);
        }
    }

    server.addConnector(connector);
    try {
        server.start();
    } catch (BindException e) {
        throw new BindException(String.format("Error binding to %s:%d %s", connector.getHost(), connector.getPort(),
                e.getMessage()));
    }

    localPort = connector.getLocalPort();
    LOGGER.log(Level.INFO, "Running on {0}", getURL());

    return context.getServletContext();
}