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

The following examples show how to use org.eclipse.jetty.webapp.WebAppContext#setBaseResource() . 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: ApiWebSite.java    From dapeng-soa with Apache License 2.0 6 votes vote down vote up
public static Server createServer(int port) throws MalformedURLException, URISyntaxException {
    Server server = new Server();
    server.setStopAtShutdown(true);

    ServerConnector connector = new ServerConnector(server);
    connector.setPort(port);
    connector.setReuseAddress(true);

    server.setConnectors(new Connector[]{connector});

    WebAppContext webContext = new WebAppContext("webapp", CONTEXT);
    webContext.setBaseResource(Resource.newResource(new URL(ApiWebSite.class.getResource("/webapp/WEB-INF"), ".")));
    webContext.setClassLoader(ApiWebSite.class.getClassLoader());

    server.setHandler(webContext);

    return server;
}
 
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: AegisServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void run() {
    //System.out.println("Starting Server");

    server = new org.eclipse.jetty.server.Server(Integer.parseInt(PORT));

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath("/");
    webappcontext.setBaseResource(Resource.newClassPathResource("/webapp"));

    server.setHandler(new HandlerCollection(webappcontext, new DefaultHandler()));
    try {
        server.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example 5
Source File: AbstractSpringServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void run() {
    server = new org.eclipse.jetty.server.Server(port);

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath(contextPath);
    webappcontext.setBaseResource(Resource.newClassPathResource(resourcePath));

    server.setHandler(new HandlerCollection(webappcontext, new DefaultHandler()));

    try {
        configureServer(server);
        server.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 6
Source File: ResolverTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void startServer() throws Throwable {
    Server server = new org.eclipse.jetty.server.Server(Integer.parseInt(PORT));

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath("/resolver");
    webappcontext.setBaseResource(Resource.newClassPathResource("/resolver"));

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});
    server.setHandler(handlers);
    server.start();
    Throwable e = webappcontext.getUnavailableException();
    if (e != null) {
        throw e;
    }
    server.stop();
}
 
Example 7
Source File: DigestServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void run() {
    server = new org.eclipse.jetty.server.Server(Integer.parseInt(PORT));

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath("/digestauth");
    webappcontext.setBaseResource(Resource.newClassPathResource("/digestauth"));

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});

    server.setHandler(handlers);

    try {
        configureServer();
        server.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: AbstractSpringServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void run() {
    server = new org.eclipse.jetty.server.Server(port);

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath(contextPath);
    webappcontext.setBaseResource(Resource.newClassPathResource(resourcePath));

    server.setHandler(new HandlerCollection(webappcontext, new DefaultHandler()));

    try {
        configureServer(server);
        server.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 9
Source File: JettyServer.java    From shiro-jersey with Apache License 2.0 5 votes vote down vote up
public static Server start(int port) throws Exception {
    Server server = new Server(port);

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    String resourcePath = JettyServer.class.getPackage().getName().replace('.', '/');
    webapp.setBaseResource(Resource.newClassPathResource(resourcePath));
    webapp.setParentLoaderPriority(true);

    server.setHandler(webapp);
    server.setStopTimeout(5000);
    server.start();
    return server;
}
 
Example 10
Source File: JettyServer.java    From shiro-jersey with Apache License 2.0 5 votes vote down vote up
public static Server start(int port) throws Exception {
    Server server = new Server(port);

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    String resourcePath = JettyServer.class.getPackage().getName().replace('.', '/');
    webapp.setBaseResource(Resource.newClassPathResource(resourcePath));
    webapp.setParentLoaderPriority(true);

    server.setHandler(webapp);
    server.setStopTimeout(5000);
    server.start();
    return server;
}
 
Example 11
Source File: IdentityServer.java    From vipps-developers with MIT License 4 votes vote down vote up
private WebAppContext createWebAppContext() throws IOException {
    WebAppContext webAppContext = new WebAppContext();
    webAppContext.setContextPath("/");
    webAppContext.setBaseResource(Resource.newClassPathResource("/webapp-identity"));
    webAppContext.getInitParams().put("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");

    addOpenIdConnectServlet(webAppContext, "/id/vipps/*", "vipps", "https://apitest.vipps.no/access-management-1.0/access");

    webAppContext.addServlet(new ServletHolder(new UserServlet()), "/user");

    webAppContext.addServlet(new ServletHolder(new OpenIdConnectServlet()), "/callback/*");

    webAppContext.addServlet(new ServletHolder(new LogEventsServlet()), "/logs/*");


    return webAppContext;
}
 
Example 12
Source File: WebServerTools.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Server start(WebServer webServer) throws Exception {

		/**
		 * 更新x_desktop的center指向
		 */
		updateCenterConfigJson();
		/**
		 * 更新 favicon.ico
		 */
		updateFavicon();
		/**
		 * 创建index.html
		 */
		createIndexPage();

		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setMinThreads(WEBSERVER_THREAD_POOL_SIZE_MIN);
		threadPool.setMaxThreads(WEBSERVER_THREAD_POOL_SIZE_MAX);
		Server server = new Server(threadPool);
		if (webServer.getSslEnable()) {
			addHttpsConnector(server, webServer.getPort());
		} else {
			addHttpConnector(server, webServer.getPort());
		}
		WebAppContext context = new WebAppContext();
		context.setContextPath("/");
		context.setBaseResource(Resource.newResource(new File(Config.base(), "servers/webServer")));
		// context.setResourceBase(".");
		context.setParentLoaderPriority(true);
		context.setExtractWAR(false);
		// context.setDefaultsDescriptor(new File(Config.base(),
		// "commons/webdefault_w.xml").getAbsolutePath());
		context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "" + webServer.getDirAllowed());
		context.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
		if (webServer.getCacheControlMaxAge() > 0) {
			context.setInitParameter("org.eclipse.jetty.servlet.Default.cacheControl",
					"max-age=" + webServer.getCacheControlMaxAge());
		}
		context.setInitParameter("org.eclipse.jetty.servlet.Default.maxCacheSize", "256000000");
		context.setInitParameter("org.eclipse.jetty.servlet.Default.maxCachedFileSize", "200000000");
		context.setWelcomeFiles(new String[] { "default.html", "index.html" });
		context.setGzipHandler(new GzipHandler());
		context.setParentLoaderPriority(true);
		context.getMimeTypes().addMimeMapping("wcss", "application/json");
		/* stat */
		if (webServer.getStatEnable()) {
			FilterHolder statFilterHolder = new FilterHolder(new WebStatFilter());
			statFilterHolder.setInitParameter("exclusions", webServer.getStatExclusions());
			context.addFilter(statFilterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
			ServletHolder statServletHolder = new ServletHolder(StatViewServlet.class);
			statServletHolder.setInitParameter("sessionStatEnable", "false");
			context.addServlet(statServletHolder, "/druid/*");
		}
		/* stat end */
		server.setHandler(context);
		server.setDumpAfterStart(false);
		server.setDumpBeforeStop(false);
		server.setStopAtShutdown(true);
		server.start();

		context.setMimeTypes(Config.mimeTypes());
		System.out.println("****************************************");
		System.out.println("* web server start completed.");
		System.out.println("* port: " + webServer.getPort() + ".");
		System.out.println("****************************************");
		return server;
	}
 
Example 13
Source File: EmbeddedJetty.java    From junit-servers with MIT License 4 votes vote down vote up
/**
 * Build web app context used to launch server.
 * May be override by subclasses.
 *
 * @throws Exception May be thrown by web app context initialization (will be wrapped later).
 */
private WebAppContext createdWebAppContext() throws Exception {
	final String path = configuration.getPath();
	final String webapp = configuration.getWebapp();
	final String classpath = configuration.getClasspath();
	final ClassLoader parentClassLoader = configuration.getParentClassLoader();
	final String overrideDescriptor = configuration.getOverrideDescriptor();
	final Resource baseResource = configuration.getBaseResource();
	final String containerJarPattern = configuration.getContainerJarPattern();
	final String webInfJarPattern = configuration.getWebInfJarPattern();

	final WebAppContext ctx = new WebAppContext();

	if (containerJarPattern != null) {
		log.debug("Setting jetty 'containerJarPattern' attribute: {}", containerJarPattern);
		ctx.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, containerJarPattern);
	}
	else if (Java.isPostJdk9()) {
		// Fix to make TLD scanning works with Java >= 9
		log.debug("Setting default jetty 'containerJarPattern' for JRE >= 9: {}");
		ctx.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, ".*\\.jar");
	}

	if (webInfJarPattern != null) {
		log.debug("Setting jetty 'WebInfJarPattern' attribute: {}", webInfJarPattern);
		ctx.setAttribute(WebInfConfiguration.WEBINF_JAR_PATTERN, webInfJarPattern);
	}

	final ClassLoader systemClassLoader = Thread.currentThread().getContextClassLoader();
	final ClassLoader classLoader;

	if (parentClassLoader != null) {
		log.debug("Overriding jetty parent classloader");
		classLoader = new CompositeClassLoader(parentClassLoader, systemClassLoader);
	}
	else {
		log.debug("Using current thread classloader as jetty parent classloader");
		classLoader = systemClassLoader;
	}

	log.debug("Set jetty classloader");
	ctx.setClassLoader(classLoader);

	log.debug("Set jetty context path to: {}", path);
	ctx.setContextPath(path);

	if (baseResource == null) {
		// use default base resource
		log.debug("Initializing default jetty base resource from: {}", webapp);
		ctx.setBaseResource(newResource(webapp));
	}
	else {
		log.debug("Initializing jetty base resource from: {}", baseResource);
		ctx.setBaseResource(baseResource);
	}

	if (overrideDescriptor != null) {
		log.debug("Set jetty descriptor: {}", overrideDescriptor);
		ctx.setOverrideDescriptor(overrideDescriptor);
	}

	log.debug("Initializing jetty configuration classes");
	ctx.setConfigurations(new Configuration[] {
		new WebInfConfiguration(),
		new WebXmlConfiguration(),
		new AnnotationConfiguration(),
		new JettyWebXmlConfiguration(),
		new MetaInfConfiguration(),
		new FragmentConfiguration()
	});

	if (isNotBlank(classpath)) {
		log.debug("Adding jetty container resource: {}", classpath);

		// Fix to scan Spring WebApplicationInitializer
		// This will add compiled classes to jetty classpath
		// See: http://stackoverflow.com/questions/13222071/spring-3-1-webapplicationinitializer-embedded-jetty-8-annotationconfiguration
		// And more precisely: http://stackoverflow.com/a/18449506/1215828
		final File classes = new File(classpath);
		final PathResource containerResources = new PathResource(classes.toURI());
		ctx.getMetaData().addContainerResource(containerResources);
	}

	ctx.setParentLoaderPriority(true);
	ctx.setWar(webapp);
	ctx.setServer(server);

	// Add server context
	server.setHandler(ctx);

	return ctx;
}
 
Example 14
Source File: ServerRpcProvider.java    From incubator-retired-wave with Apache License 2.0 4 votes vote down vote up
public void startWebSocketServer(final Injector injector) {
  httpServer = new Server();

  List<Connector> connectors = getSelectChannelConnectors(httpAddresses);
  if (connectors.isEmpty()) {
    LOG.severe("No valid http end point address provided!");
  }
  for (Connector connector : connectors) {
    httpServer.addConnector(connector);
  }
  final WebAppContext context = new WebAppContext();

  context.setParentLoaderPriority(true);

  if (jettySessionManager != null) {
    // This disables JSessionIDs in URLs redirects
    // see: http://stackoverflow.com/questions/7727534/how-do-you-disable-jsessionid-for-jetty-running-with-the-eclipse-jetty-maven-plu
    // and: http://jira.codehaus.org/browse/JETTY-467?focusedCommentId=114884&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-114884
    jettySessionManager.setSessionIdPathParameterName(null);

    context.getSessionHandler().setSessionManager(jettySessionManager);
  }
  final ResourceCollection resources = new ResourceCollection(resourceBases);
  context.setBaseResource(resources);

  addWebSocketServlets();

  try {

    final ServletModule servletModule = getServletModule();

    ServletContextListener contextListener = new GuiceServletContextListener() {

      private final Injector childInjector = injector.createChildInjector(servletModule);

      @Override
      protected Injector getInjector() {
        return childInjector;
      }
    };

    context.addEventListener(contextListener);
    context.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    context.addFilter(GzipFilter.class, "/webclient/*", EnumSet.allOf(DispatcherType.class));
    httpServer.setHandler(context);

    httpServer.start();
    restoreSessions();

  } catch (Exception e) { // yes, .start() throws "Exception"
    LOG.severe("Fatal error starting http server.", e);
    return;
  }
  LOG.fine("WebSocket server running.");
}