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

The following examples show how to use org.eclipse.jetty.webapp.WebAppContext#setAttribute() . 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: WebServerComponent.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private WebAppContext deployWar(String url, String warFile, Path warDirectory) throws IOException {
   WebAppContext webapp = new WebAppContext();
   if (url.startsWith("/")) {
      webapp.setContextPath(url);
   } else {
      webapp.setContextPath("/" + url);
   }
   //add the filters needed for audit logging
   webapp.addFilter(new FilterHolder(JolokiaFilter.class), "/*", EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
   webapp.addFilter(new FilterHolder(AuthenticationFilter.class), "/auth/login/*", EnumSet.of(DispatcherType.REQUEST));

   webapp.setWar(warDirectory.resolve(warFile).toString());

   webapp.setAttribute("org.eclipse.jetty.webapp.basetempdir", temporaryWarDir.toFile().getAbsolutePath());

   handlers.addHandler(webapp);
   return webapp;
}
 
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: 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 4
Source File: GatewayServer.java    From knox with Apache License 2.0 6 votes vote down vote up
private WebAppContext createWebAppContext( Topology topology, File warFile, String warPath ) {
  String topoName = topology.getName();
  WebAppContext context = new WebAppContext();
  String contextPath;
  contextPath = "/" + Urls.trimLeadingAndTrailingSlashJoin( config.getGatewayPath(), topoName, warPath );
  context.setContextPath( contextPath );
  SessionCookieConfig sessionCookieConfig = context.getServletContext().getSessionCookieConfig();
  sessionCookieConfig.setName(KNOXSESSIONCOOKIENAME);
  context.setWar( warFile.getAbsolutePath() );
  context.setAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE, topoName );
  context.setAttribute( "org.apache.knox.gateway.frontend.uri", getFrontendUri( context, config ) );
  context.setAttribute( GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE, config );
  // Add support for JSPs.
  context.setAttribute(
      "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
      ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );
  context.setTempDirectory( FileUtils.getFile( warFile, "META-INF", "temp" ) );
  context.setErrorHandler( createErrorHandler() );
  context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
  ClassLoader jspClassLoader = new URLClassLoader(new URL[0], this.getClass().getClassLoader());
  context.setClassLoader(jspClassLoader);
  return context;
}
 
Example 5
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 6
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 supportJspAndSetTldJarNames(Server server, String... jarNames) {
	WebAppContext context = (WebAppContext) server.getHandler();
	// This webapp will use jsps and jstl. We need to enable the
	// AnnotationConfiguration in
	// order to correctly set up the jsp container
	org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList
		.setServerDefault(server);
	classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
		"org.eclipse.jetty.annotations.AnnotationConfiguration");
	// Set the ContainerIncludeJarPattern so that jetty examines these container-path
	// jars for
	// tlds, web-fragments etc.
	// If you omit the jar that contains the jstl .tlds, the jsp engine will scan for
	// them
	// instead.
	ArrayList jarNameExprssions = Lists.newArrayList(".*/[^/]*servlet-api-[^/]*\\.jar$",
		".*/javax.servlet.jsp.jstl-.*\\.jar$", ".*/[^/]*taglibs.*\\.jar$");

	for (String jarName : jarNames) {
		jarNameExprssions.add(".*/" + jarName + "-[^/]*\\.jar$");
	}

	context.setAttribute("org.eclipse.jetty.io.github.dunwu.javaee.server.webapp.ContainerIncludeJarPattern",
		StringUtils.join(jarNameExprssions, '|'));
}
 
Example 7
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 supportJspAndSetTldJarNames(Server server, String... jarNames) {
	WebAppContext context = (WebAppContext) server.getHandler();
	// This webapp will use jsps and jstl. We need to enable the
	// AnnotationConfiguration in
	// order to correctly set up the jsp container
	org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList
		.setServerDefault(server);
	classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
		"org.eclipse.jetty.annotations.AnnotationConfiguration");
	// Set the ContainerIncludeJarPattern so that jetty examines these container-path
	// jars for
	// tlds, web-fragments etc.
	// If you omit the jar that contains the jstl .tlds, the jsp engine will scan for
	// them
	// instead.
	ArrayList jarNameExprssions = Lists.newArrayList(".*/[^/]*servlet-api-[^/]*\\.jar$",
		".*/javax.servlet.jsp.jstl-.*\\.jar$", ".*/[^/]*taglibs.*\\.jar$");

	for (String jarName : jarNames) {
		jarNameExprssions.add(".*/" + jarName + "-[^/]*\\.jar$");
	}

	context.setAttribute("org.eclipse.jetty.io.github.dunwu.javaee.server.webapp.ContainerIncludeJarPattern",
		StringUtils.join(jarNameExprssions, '|'));
}
 
Example 8
Source File: JettyFactory.java    From base-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 设置除jstl-*.jar外其他含tld文件的jar包的名称.
 * jar名称不需要版本号,如sitemesh, shiro-web
 */
public static void setTldJarNames(Server server, String... jarNames) {
	WebAppContext context = (WebAppContext) server.getHandler();
	List<String> jarNameExprssions = Lists.newArrayList(".*/jstl-[^/]*\\.jar$", ".*/.*taglibs[^/]*\\.jar$");
	for (String jarName : jarNames) {
		jarNameExprssions.add(".*/" + jarName + "-[^/]*\\.jar$");
	}

	context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
			StringUtils.join(jarNameExprssions, '|'));

}
 
Example 9
Source File: HttpServer2.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
private static WebAppContext createWebAppContext(Builder b,
    AccessControlList adminsAcl, final String appDir) {
  WebAppContext ctx = new WebAppContext();
  ctx.setDefaultsDescriptor(null);
  ServletHolder holder = new ServletHolder(new DefaultServlet());
  Map<String, String> params = ImmutableMap.<String, String>builder()
      .put("acceptRanges", "true")
      .put("dirAllowed", "false")
      .put("gzip", "true")
      .put("useFileMappedBuffer", "true")
      .build();
  holder.setInitParameters(params);
  ctx.setWelcomeFiles(new String[] {"index.html"});
  ctx.addServlet(holder, "/");
  ctx.setDisplayName(b.name);
  ctx.setContextPath("/");
  ctx.setWar(appDir + "/" + b.name);
  String tempDirectory = b.conf.get(HTTP_TEMP_DIR_KEY);
  if (tempDirectory != null && !tempDirectory.isEmpty()) {
    ctx.setTempDirectory(new File(tempDirectory));
    ctx.setAttribute("javax.servlet.context.tempdir", tempDirectory);
  }
  ctx.getServletContext().setAttribute(CONF_CONTEXT_ATTRIBUTE, b.conf);
  ctx.getServletContext().setAttribute(ADMINS_ACL, adminsAcl);
  addNoCacheFilter(ctx);
  return ctx;
}
 
Example 10
Source File: JettyAppServer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void addRestEasyServlet(WebArchive archive, WebAppContext webAppContext) {
    log.debug("Starting Resteasy deployment");
    boolean addServlet = true;
    ServletHolder resteasyServlet = new ServletHolder("javax.ws.rs.core.Application", new HttpServlet30Dispatcher());

    String jaxrsApplication = getJaxRsApplication(archive);
    Set<Class<?>> pathAnnotatedClasses = getPathAnnotatedClasses(archive);

    if (jaxrsApplication != null) {
        log.debug("App has an Application.class: " + jaxrsApplication);
        resteasyServlet.setInitParameter("javax.ws.rs.Application", jaxrsApplication);
    } else if (!pathAnnotatedClasses.isEmpty()) {
        log.debug("App has @Path annotated classes: " + pathAnnotatedClasses);
        ResteasyDeployment deployment = new ResteasyDeployment();
        deployment.setApplication(new RestSamlApplicationConfig(pathAnnotatedClasses));
        webAppContext.setAttribute(ResteasyDeployment.class.getName(), deployment);
    } else {
        log.debug("An application doesn't have Application.class, nor @Path annotated classes. Skipping Resteasy initialization.");
        addServlet = false;
    }

    if (addServlet) {
        // this should be /* in general. However Jetty 9.2 (this is bug specific to this version),
        // can not merge two instances of javax.ws.rs.Application together (one from web.xml
        // and the other one added here). In 9.1 and 9.4 this works fine.
        // Once we stop supporting 9.2, this should replaced with /* and this comment should be removed.
        webAppContext.addServlet(resteasyServlet, "/");
    }
    log.debug("Finished Resteasy deployment");
}
 
Example 11
Source File: BrooklynRestApiLauncher.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private WebAppContext servletContextHandler(ManagementContext managementContext) {
    WebAppContext context = new WebAppContext();

    context.setAttribute(BrooklynServiceAttributes.BROOKLYN_MANAGEMENT_CONTEXT, managementContext);

    installWar(context);
    ImmutableList.Builder<Object> providersListBuilder = ImmutableList.builder();
    providersListBuilder.add(
            new ManagementContextProvider(),
            new ShutdownHandlerProvider(shutdownListener),
            new RequestTaggingRsFilter(),
            new NoCacheFilter(),
            new BrooklynSecurityProviderFilterJersey(),
            new HaHotCheckResourceFilter(),
            new EntitlementContextFilter(),
            new CsrfTokenFilter());
    if (BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_CORS_CXF_PROPERTY)) {
        providersListBuilder.add(new CorsImplSupplierFilter(managementContext));
    }
    RestApiSetup.installRest(context,
            providersListBuilder.build().toArray());
    
    RestApiSetup.installServletFilters(context, this.filters);

    context.setContextPath("/");
    return context;
}
 
Example 12
Source File: HttpServer2.java    From knox with Apache License 2.0 5 votes vote down vote up
private static WebAppContext createWebAppContext(Builder b,
                                                 AccessControlList adminsAcl, final String appDir) {
  WebAppContext ctx = new WebAppContext();
  ctx.setDefaultsDescriptor(null);
  ServletHolder holder = new ServletHolder(new DefaultServlet());
  Map<String, String> params = ImmutableMap. <String, String> builder()
                                   .put("acceptRanges", "true")
                                   .put("dirAllowed", "false")
                                   .put("gzip", "true")
                                   .put("useFileMappedBuffer", "true")
                                   .build();
  holder.setInitParameters(params);
  ctx.setWelcomeFiles(new String[] {"index.html"});
  ctx.addServlet(holder, "/");
  ctx.setDisplayName(b.name);
  ctx.setContextPath("/");
  ctx.setWar(appDir + "/" + b.name);
  String tempDirectory = b.conf.get(HTTP_TEMP_DIR_KEY);
  if (tempDirectory != null && !tempDirectory.isEmpty()) {
    ctx.setTempDirectory(new File(tempDirectory));
    ctx.setAttribute("javax.servlet.context.tempdir", tempDirectory);
  }
  ctx.getServletContext().setAttribute(CONF_CONTEXT_ATTRIBUTE, b.conf);
  ctx.getServletContext().setAttribute(ADMINS_ACL, adminsAcl);
  addNoCacheFilter(ctx);
  return ctx;
}
 
Example 13
Source File: JettyStarter.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addExplodedWebApp(HandlerList handlerList, File file, String[] virtualHost) {
    String contextPath = "/" + file.getName();
    WebAppContext webApp = createWebAppContext(contextPath, virtualHost);

    // Don't scan classes for annotations. Saves 1 second at startup.
    webApp.setAttribute("org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern", "^$");
    webApp.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", "^$");

    webApp.setDescriptor(new File(file, "/WEB-INF/web.xml").getAbsolutePath());
    webApp.setResourceBase(file.getAbsolutePath());
    handlerList.addHandler(webApp);
    logger.debug("Deploying " + contextPath + " using exploded war " + file);
}
 
Example 14
Source File: JettyServer.java    From 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(CONTAINER_INCLUDE_PATTERN_KEY, CONTAINER_INCLUDE_PATTERN_VALUE);

    // 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);
    webappContext.getMimeTypes().addMimeMapping("ttf", "font/ttf");

    // 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);

    // 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,
                    XContentTypeOptionsFilter.class));

    if(props.isHTTPSConfigured()) {
        filters.add(StrictTransportSecurityFilter.class);
    }
    filters.forEach( (filter) -> addFilters(filter, ALL_PATHS, webappContext));
    addFiltersWithProps(ALL_PATHS, webappContext);

    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;
}
 
Example 15
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 16
Source File: ServerLauncher.java    From bromium with MIT License 4 votes vote down vote up
public static void main(final String[] args) {
  InetSocketAddress _inetSocketAddress = new InetSocketAddress("localhost", 8080);
  final Server server = new Server(_inetSocketAddress);
  WebAppContext _webAppContext = new WebAppContext();
  final Procedure1<WebAppContext> _function = (WebAppContext it) -> {
    it.setResourceBase("WebRoot");
    it.setWelcomeFiles(new String[] { "index.html" });
    it.setContextPath("/");
    AnnotationConfiguration _annotationConfiguration = new AnnotationConfiguration();
    WebXmlConfiguration _webXmlConfiguration = new WebXmlConfiguration();
    WebInfConfiguration _webInfConfiguration = new WebInfConfiguration();
    MetaInfConfiguration _metaInfConfiguration = new MetaInfConfiguration();
    it.setConfigurations(new Configuration[] { _annotationConfiguration, _webXmlConfiguration, _webInfConfiguration, _metaInfConfiguration });
    it.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, ".*/com\\.hribol\\.bromium\\.dsl\\.web/.*,.*\\.jar");
    it.setInitParameter("org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false");
  };
  WebAppContext _doubleArrow = ObjectExtensions.<WebAppContext>operator_doubleArrow(_webAppContext, _function);
  server.setHandler(_doubleArrow);
  String _name = ServerLauncher.class.getName();
  final Slf4jLog log = new Slf4jLog(_name);
  try {
    server.start();
    URI _uRI = server.getURI();
    String _plus = ("Server started " + _uRI);
    String _plus_1 = (_plus + "...");
    log.info(_plus_1);
    final Runnable _function_1 = () -> {
      try {
        log.info("Press enter to stop the server...");
        final int key = System.in.read();
        if ((key != (-1))) {
          server.stop();
        } else {
          log.warn("Console input is not available. In order to stop the server, you need to cancel process manually.");
        }
      } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
      }
    };
    new Thread(_function_1).start();
    server.join();
  } catch (final Throwable _t) {
    if (_t instanceof Exception) {
      final Exception exception = (Exception)_t;
      log.warn(exception.getMessage());
      System.exit(1);
    } else {
      throw Exceptions.sneakyThrow(_t);
    }
  }
}
 
Example 17
Source File: ServerLauncher.java    From xtext-web with Eclipse Public License 2.0 4 votes vote down vote up
public static void main(String[] args) {
	Server server = new Server(new InetSocketAddress("localhost", 8080));
	RewriteHandler rewriteHandler = new RewriteHandler();
	server.setHandler(rewriteHandler);
	RewriteRegexRule rule = new RewriteRegexRule();
	rule.setRegex("/xtext/@xtext-version-placeholder@/(.*)");
	rule.setReplacement("/xtext/$1");
	rule.setTerminating(false);
	rewriteHandler.addRule(rule);
	HandlerList handlerList = new HandlerList();
	ResourceHandler resourceHandler1 = new ResourceHandler();
	resourceHandler1.setResourceBase("src/main/webapp");
	resourceHandler1.setWelcomeFiles(new String[] { "index.html" });
	ResourceHandler resourceHandler2 = new ResourceHandler();
	resourceHandler2.setResourceBase("../org.eclipse.xtext.web/src/main/css");
	WebAppContext webAppContext = new WebAppContext();
	webAppContext.setResourceBase("../org.eclipse.xtext.web/src/main/js");
	webAppContext.setContextPath("/");
	webAppContext.setConfigurations(new Configuration[] { new AnnotationConfiguration(), new WebXmlConfiguration(),
			new WebInfConfiguration(), new MetaInfConfiguration() });
	webAppContext.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN,
			".*/org\\.eclipse\\.xtext\\.web.*,.*/org.webjars.*");

	handlerList.setHandlers(new Handler[] { resourceHandler1, resourceHandler2, webAppContext });
	rewriteHandler.setHandler(handlerList);
	Slf4jLog log = new Slf4jLog(ServerLauncher.class.getName());
	try {
		server.start();
		log.info("Server started " + server.getURI() + "...");
		new Thread() {

			public void run() {
				try {
					log.info("Press enter to stop the server...");
					int key = System.in.read();
					if (key != -1) {
						server.stop();
					} else {
						log.warn(
								"Console input is not available. In order to stop the server, you need to cancel process manually.");
					}
				} catch (Exception e) {
					log.warn(e);
				}
			}

		}.start();
		server.join();
	} catch (Exception exception) {
		log.warn(exception.getMessage());
		System.exit(1);
	}
}
 
Example 18
Source File: ComponentDemoServer.java    From flow with Apache License 2.0 4 votes vote down vote up
/**
 * Starts a web server to the port defined by {@link #getPort()}. It serves
 * the test UIs annotated with <code>@Route</code>.
 * 
 * @throws Exception
 *             if any issue on server start occurs
 * 
 * @return the server object
 */
public Server startServer() throws Exception {

    Server server = new Server();

    final ServerConnector connector = new ServerConnector(server);
    connector.setPort(getPort());
    server.setConnectors(new Connector[] { connector });

    WebAppContext context = new WebAppContext();

    File file = new File(WEB_APP_PATH);
    if (!file.exists()) {
        try {
            if (!file.mkdirs()) {
                throw new RuntimeException(
                        "Failed to create the following directory for webapp: "
                                + WEB_APP_PATH);
            }
        } catch (SecurityException exception) {
            throw new RuntimeException(
                    "Failed to create the following directory for webapp: "
                            + WEB_APP_PATH,
                    exception);
        }
    }
    context.setWar(file.getPath());

    context.setContextPath("/");

    ClassList classlist = ClassList.setServerDefault(server);
    classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
            "org.eclipse.jetty.annotations.AnnotationConfiguration");

    // Enable annotation scanning for uitest classes.
    // Enable scanning for resources inside jar-files.
    context.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN,
            TEST_CLASSES_PATH + "|" + JAR_PATTERN);

    configure(context, server);
    server.setHandler(context);
    server.start();
    return server;
}
 
Example 19
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 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;
}