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

The following examples show how to use org.eclipse.jetty.webapp.WebAppContext#setParentLoaderPriority() . 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: VarOneServer.java    From varOne with MIT License 6 votes vote down vote up
private static WebAppContext setupWebAppContext(VarOneConfiguration conf) {
	WebAppContext webApp = new WebAppContext();
    webApp.setContextPath(conf.getServerContextPath());
    File warPath = new File(conf.getString(ConfVars.VARONE_WAR));
    if (warPath.isDirectory()) {
      webApp.setResourceBase(warPath.getPath());
      webApp.setParentLoaderPriority(true);
    } else {
      // use packaged WAR
      webApp.setWar(warPath.getAbsolutePath());
      File warTempDirectory = new File(conf.getRelativeDir(ConfVars.VARONE_WAR_TEMPDIR));
      warTempDirectory.mkdir();
      LOG.info("VarOneServer Webapp path: {}" + warTempDirectory.getPath());
      webApp.setTempDirectory(warTempDirectory);
    }
    // Explicit bind to root
    webApp.addServlet(new ServletHolder(new DefaultServlet()), "/*");
    return webApp;
}
 
Example 2
Source File: ServersUtil.java    From joynr with Apache License 2.0 6 votes vote down vote up
public static WebAppContext createControlledBounceproxyWebApp(String parentContext, Properties props) {
    WebAppContext bounceproxyWebapp = new WebAppContext();
    bounceproxyWebapp.setContextPath(createContextPath(parentContext, BOUNCEPROXY_CONTEXT));
    bounceproxyWebapp.setWar("target/controlled-bounceproxy.war");

    if (props != null) {
        bounceproxyWebapp.setConfigurations(new Configuration[]{ new WebInfConfiguration(),
                new WebXmlConfiguration(), new SystemPropertyServletConfiguration(props) });
    }

    // Makes jetty load classes in the same order as JVM. Otherwise there's
    // a conflict loading loggers.
    bounceproxyWebapp.setParentLoaderPriority(true);

    return bounceproxyWebapp;
}
 
Example 3
Source File: JettyFactory.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
public static void initWebAppContext(Server server, int type) throws Exception {
	System.out.println("[INFO] Application loading");
	WebAppContext webAppContext = (WebAppContext) server.getHandler();
	webAppContext.setContextPath(CONTEXT);
	webAppContext.setResourceBase(getAbsolutePath() + RESOURCE_BASE_PATH);
	webAppContext.setDescriptor(getAbsolutePath() + RESOURCE_BASE_PATH + WEB_XML_PATH);

	if (IDE_INTELLIJ == type) {
		webAppContext.setDefaultsDescriptor(WINDOWS_WEBDEFAULT_PATH);
		supportJspAndSetTldJarNames(server, TLD_JAR_NAMES);
	} else {
		webAppContext.setParentLoaderPriority(true);
	}

	System.out.println("[INFO] Application loaded");
}
 
Example 4
Source File: MetricServer.java    From realtime-analytics with GNU General Public License v2.0 6 votes vote down vote up
public void startStandAlone() {
    try {
        WebAppContext context = new WebAppContext();
        String baseUrl = getBaseUrl();
        LOGGER.info("Metric server baseUrl: " + baseUrl);
        context.setDescriptor(baseUrl + "/WEB-INF/web.xml");
        context.setResourceBase(baseUrl);
        context.setContextPath("/");
        context.setParentLoaderPriority(true);
        context.setAttribute("JetStreamRoot", applicationContext);
        Server s_server = new Server(s_port);
        s_server.setHandler(context);

        LOGGER.info( "Metric server started, listening on port " + s_port);
        s_server.start();
        running.set(true);
    } catch (Throwable t) {
        throw CommonUtils.runtimeException(t);
    }
}
 
Example 5
Source File: JettyFactory.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
public static void initWebAppContext(Server server, int type) throws Exception {
	System.out.println("[INFO] Application loading");
	WebAppContext webAppContext = (WebAppContext) server.getHandler();
	webAppContext.setContextPath(CONTEXT);
	webAppContext.setResourceBase(getAbsolutePath() + RESOURCE_BASE_PATH);
	webAppContext.setDescriptor(getAbsolutePath() + RESOURCE_BASE_PATH + WEB_XML_PATH);

	if (IDE_INTELLIJ == type) {
		webAppContext.setDefaultsDescriptor(WINDOWS_WEBDEFAULT_PATH);
		supportJspAndSetTldJarNames(server, TLD_JAR_NAMES);
	} else {
		webAppContext.setParentLoaderPriority(true);
	}

	System.out.println("[INFO] Application loaded");
}
 
Example 6
Source File: ExplorerServer.java    From Explorer with Apache License 2.0 6 votes vote down vote up
/**
 * Handles the WebApplication for Swagger-ui
 *
 * @return WebAppContext with swagger ui context
 */
private static WebAppContext setupWebAppSwagger(ExplorerConfiguration conf) {
    WebAppContext webApp = new WebAppContext();
    File webapp = new File(conf.getString(ExplorerConfiguration.ConfVars.EXPLORER_API_WAR));

    if (webapp.isDirectory()) {
        webApp.setResourceBase(webapp.getPath());
    } else {
        webApp.setWar(webapp.getAbsolutePath());
    }
    webApp.setContextPath("/docs");
    webApp.setParentLoaderPriority(true);
    // Bind swagger-ui to the path HOST/docs
    webApp.addServlet(new ServletHolder(new DefaultServlet()), "/docs/*");
    return webApp;
}
 
Example 7
Source File: ServersUtil.java    From joynr with Apache License 2.0 6 votes vote down vote up
public static WebAppContext createBounceproxyControllerWebApp(String warFileName,
                                                              String parentContext,
                                                              Properties props) {
    WebAppContext bounceproxyWebapp = new WebAppContext();
    bounceproxyWebapp.setContextPath(createContextPath(parentContext, BOUNCEPROXYCONTROLLER_CONTEXT));
    bounceproxyWebapp.setWar("target/" + warFileName + ".war");

    if (props != null) {
        bounceproxyWebapp.setConfigurations(new Configuration[]{ new WebInfConfiguration(),
                new WebXmlConfiguration(), new SystemPropertyServletConfiguration(props) });
    }
    // Makes jetty load classes in the same order as JVM. Otherwise there's
    // a conflict loading loggers.
    bounceproxyWebapp.setParentLoaderPriority(true);

    return bounceproxyWebapp;
}
 
Example 8
Source File: Jetty9Server.java    From gocd with Apache License 2.0 6 votes vote down vote up
private WebAppContext createWebAppContext() {
    webAppContext = new WebAppContext();
    webAppContext.setDefaultsDescriptor(GoWebXmlConfiguration.configuration(getWarFile()));

    webAppContext.setConfigurationClasses(new String[]{
            WebInfConfiguration.class.getCanonicalName(),
            WebXmlConfiguration.class.getCanonicalName(),
            JettyWebXmlConfiguration.class.getCanonicalName()
    });
    webAppContext.setContextPath(systemEnvironment.getWebappContextPath());

    // delegate all logging to parent classloader to avoid initialization of loggers in multiple classloaders
    webAppContext.getSystemClasspathPattern().add("org.apache.log4j.");
    webAppContext.getSystemClasspathPattern().add("org.slf4j.");
    webAppContext.getSystemClasspathPattern().add("org.apache.commons.logging.");

    webAppContext.setWar(getWarFile());
    webAppContext.setParentLoaderPriority(systemEnvironment.getParentLoaderPriority());
    return webAppContext;
}
 
Example 9
Source File: WebApp.java    From json-schema-validator-demo with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void main(final String... args)
    throws Exception
{
    final String webappDirLocation = "src/main/webapp/";

    //The port that we should run on can be set into an environment variable
    //Look for that variable and default to 8080 if it isn't there.
    String webPort = System.getenv("PORT");
    if (Strings.isNullOrEmpty(webPort))
        webPort = "8080";

    final Server server = new Server(Integer.valueOf(webPort));
    final WebAppContext root = new WebAppContext();

    root.setContextPath("/");
    root.setDescriptor(webappDirLocation + "/WEB-INF/web.xml");
    root.setResourceBase(webappDirLocation);

    //Parent loader priority is a class loader setting that Jetty accepts.
    //By default Jetty will behave like most web containers in that it will
    //allow your application to replace non-server libraries that are part of the
    //container. Setting parent loader priority to true changes this behavior.
    //Read more here: http://wiki.eclipse.org/Jetty/Reference/Jetty_Classloading
    root.setParentLoaderPriority(true);

    server.setHandler(root);

    server.start();
    server.join();
}
 
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: ExampleServerR5IT.java    From hapi-fhir-jpaserver-starter with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception {
    String path = Paths.get("").toAbsolutePath().toString();

    ourLog.info("Project base path is: {}", path);

    ourServer = new Server(0);

    WebAppContext webAppContext = new WebAppContext();
    webAppContext.setContextPath("/hapi-fhir-jpaserver");
    webAppContext.setDisplayName("HAPI FHIR");
    webAppContext.setDescriptor(path + "/src/main/webapp/WEB-INF/web.xml");
    webAppContext.setResourceBase(path + "/target/hapi-fhir-jpaserver-starter");
    webAppContext.setParentLoaderPriority(true);

    ourServer.setHandler(webAppContext);
    ourServer.start();

    ourPort = JettyUtil.getPortForStartedServer(ourServer);

    ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);
    ourCtx.getRestfulClientFactory().setSocketTimeout(1200 * 1000);
    String ourServerBase = "http://localhost:" + ourPort + "/hapi-fhir-jpaserver/fhir/";

    ourClient = ourCtx.newRestfulGenericClient(ourServerBase);
    ourClient.registerInterceptor(new LoggingInterceptor(true));
}
 
Example 12
Source File: TapestrySecurityIntegrationTest.java    From tapestry-security with Apache License 2.0 5 votes vote down vote up
@Override
public WebAppContext buildContext()
{
	WebAppContext context = new WebAppContext("src/test/webapp", "/test");
	/*
	 * Sets the classloading model for the context to avoid an strange "ClassNotFoundException: org.slf4j.Logger"
	 */
	context.setParentLoaderPriority(true);
	return context;
}
 
Example 13
Source File: ZeppelinServer.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private static WebAppContext setupWebAppContext(
    ContextHandlerCollection contexts, ZeppelinConfiguration conf, String warPath, String contextPath) {
  WebAppContext webApp = new WebAppContext();
  webApp.setContextPath(contextPath);
  LOG.info("warPath is: {}", warPath);
  File warFile = new File(warPath);
  if (warFile.isDirectory()) {
    // Development mode, read from FS
    // webApp.setDescriptor(warPath+"/WEB-INF/web.xml");
    webApp.setResourceBase(warFile.getPath());
    webApp.setParentLoaderPriority(true);
  } else {
    // use packaged WAR
    webApp.setWar(warFile.getAbsolutePath());
    webApp.setExtractWAR(false);
    File warTempDirectory = new File(conf.getRelativeDir(ConfVars.ZEPPELIN_WAR_TEMPDIR) + contextPath);
    warTempDirectory.mkdir();
    LOG.info("ZeppelinServer Webapp path: {}", warTempDirectory.getPath());
    webApp.setTempDirectory(warTempDirectory);
  }
  // Explicit bind to root
  webApp.addServlet(new ServletHolder(new DefaultServlet()), "/*");
  contexts.addHandler(webApp);

  webApp.addFilter(new FilterHolder(CorsFilter.class), "/*", EnumSet.allOf(DispatcherType.class));

  webApp.setInitParameter(
      "org.eclipse.jetty.servlet.Default.dirAllowed",
      Boolean.toString(conf.getBoolean(ConfVars.ZEPPELIN_SERVER_DEFAULT_DIR_ALLOWED)));
  return webApp;
}
 
Example 14
Source File: RESTInterface.java    From nadia with Apache License 2.0 5 votes vote down vote up
@Override
public void start(){
	try{
		NadiaProcessorConfig config = NadiaProcessorConfig.getInstance();
		
		//Jetty:
		server = new Server();
		
		//main config
        WebAppContext context = new WebAppContext();
        context.setDescriptor(config.getProperty(NadiaProcessorConfig.JETTYWEBXMLPATH));
        context.setResourceBase(config.getProperty(NadiaProcessorConfig.JETTYRESOURCEBASE));
        context.setContextPath(config.getProperty(NadiaProcessorConfig.JETTYCONTEXTPATH));
        context.setParentLoaderPriority(true);
        server.setHandler(context);
        
        //ssl (https)
        SslContextFactory sslContextFactory = new SslContextFactory(config.getProperty(NadiaProcessorConfig.JETTYKEYSTOREPATH));
        sslContextFactory.setKeyStorePassword(config.getProperty(NadiaProcessorConfig.JETTYKEYSTOREPASS));

        ServerConnector serverconn = new ServerConnector(server, sslContextFactory);
        serverconn.setPort(8080); //443 (or 80) not allowed on Linux unless run as root
        server.setConnectors(new Connector[] {serverconn});
        
        //start	        
        server.start();
        logger.info("REST interface started on "+server.getURI());
        server.join();
		
	}
	catch(Exception ex){
		ex.printStackTrace();
		logger.severe("Nadia: failed to start Jetty: "+ex.getMessage());
		server.destroy();
	}
}
 
Example 15
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 16
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.");
}
 
Example 17
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 18
Source File: JDBCDriverTest.java    From Kylin with Apache License 2.0 4 votes vote down vote up
protected static void startJetty() throws Exception {
    String jetty_home = System.getProperty("jetty.home", "..");

    server = new Server(7070);

    WebAppContext context = new WebAppContext();
    context.setDescriptor("./src/main/webapp/WEB-INF/web.xml");
    context.setResourceBase("./src/main/webapp");
    context.setContextPath("/kylin");
    context.setParentLoaderPriority(true);

    server.setHandler(context);

    server.start();

}
 
Example 19
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 20
Source File: ITRestClientTest.java    From kylin with Apache License 2.0 3 votes vote down vote up
protected static void startJetty() throws Exception {

        server = new Server(PORT);

        WebAppContext context = new WebAppContext();
        context.setDescriptor("../server/src/main/webapp/WEB-INF/web.xml");
        context.setResourceBase("../server/src/main/webapp");
        context.setContextPath("/kylin");
        context.setParentLoaderPriority(true);

        server.setHandler(context);

        server.start();

    }