下面列出了org.eclipse.jetty.server.handler.HandlerList#addHandler ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected ServletContextHandler addResourceHandler(String contextPath, Path resourceBase) {
ServletContextHandler context = new ServletContextHandler();
ResourceHandler staticResource = new ResourceHandler();
staticResource.setDirectoriesListed(true);
staticResource.setWelcomeFiles(new String[] { "index.html" });
staticResource.setResourceBase(resourceBase.toAbsolutePath().toString());
MimeTypes mimeTypes = new MimeTypes();
mimeTypes.addMimeMapping("appcache", "text/cache-manifest");
staticResource.setMimeTypes(mimeTypes);
context.setContextPath(contextPath);
context.setAliasChecks(Arrays.asList(new ApproveAliases(), new AllowSymLinkAliasChecker()));
HandlerList allHandlers = new HandlerList();
allHandlers.addHandler(staticResource);
allHandlers.addHandler(context.getHandler());
context.setHandler(allHandlers);
handlers.addHandler(context);
return context;
}
public ChaosHttpProxy(URI endpoint, ChaosConfig config)
throws Exception {
setChaosConfig(config);
Supplier<Failure> supplier = new RandomFailureSupplier(
config.getFailures());
requireNonNull(endpoint);
client = new HttpClient();
server = new Server();
HttpConnectionFactory httpConnectionFactory =
new HttpConnectionFactory();
// TODO: SSL
ServerConnector connector = new ServerConnector(server,
httpConnectionFactory);
connector.setHost(endpoint.getHost());
connector.setPort(endpoint.getPort());
server.addConnector(connector);
this.handler = new ChaosHttpProxyHandler(client, supplier);
HandlerList handlers = new HandlerList();
handlers.addHandler(new ChaosApiHandler(this, handler));
handlers.addHandler(handler);
server.setHandler(handlers);
}
public static void main(final String[] args) throws Exception {
final Server server = new Server(8686);
final ServletHolder staticHolder = new ServletHolder(new DefaultServlet());
final ServletContextHandler staticContext = new ServletContextHandler();
staticContext.setContextPath("/static");
staticContext.addServlet(staticHolder, "/*");
staticContext.setResourceBase(StatsServer.class.getResource("/web-ui").toURI().toString());
// Register and map the dispatcher servlet
final CXFCdiServlet cxfServlet = new CXFCdiServlet();
final ServletHolder cxfServletHolder = new ServletHolder(cxfServlet);
final ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.addEventListener(new Listener());
context.addEventListener(new BeanManagerResourceBindingListener());
context.addServlet(cxfServletHolder, "/rest/*");
HandlerList handlers = new HandlerList();
handlers.addHandler(staticContext);
handlers.addHandler(context);
server.setHandler(handlers);
server.start();
server.join();
}
public static void main(String[] argv) throws Exception {
Server server = new Server(Integer.parseInt(argv[0]));
HandlerList handlers = new HandlerList();
handlers.addHandler(new JsltHandler());
server.setHandler(handlers);
server.start();
server.join();
}
public static void main(String[] args) throws Exception {
Flags flags = new Flags();
JCommander.newBuilder().addObject(flags).build().parse(args);
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(flags.port);
server.setConnectors(new Connector[] {connector });
HandlerList handlers = new HandlerList();
ContextHandler context = new ContextHandler();
context.setContextPath("/tests");
ResourceHandler testHandler = new ResourceHandler();
testHandler.setBaseResource(Resource.newClassPathResource("/tests"));
testHandler.setDirectoriesListed(true);
context.setHandler(testHandler);
handlers.addHandler(context);
ContextHandler coreContext = new ContextHandler();
coreContext.setContextPath("/core");
ResourceHandler coreHandler = new ResourceHandler();
coreHandler.setBaseResource(Resource.newClassPathResource("/core"));
coreContext.setHandler(coreHandler);
handlers.addHandler(coreContext);
ServletContextHandler driverContext = new ServletContextHandler();
driverContext.setContextPath("/");
driverContext.addServlet(WebDriverServlet.class, "/wd/hub/*");
handlers.addHandler(driverContext);
server.setHandler(handlers);
server.start();
}
/**
* Start server.
*
* @param packages restful implementation class package
* @param resourcePath resource path
* @param servletPath servlet path
* @throws Exception exception when startup
*/
public void start(final String packages, final Optional<String> resourcePath, final Optional<String> servletPath) throws Exception {
log.info("Elastic Job: Start RESTful server");
HandlerList handlers = new HandlerList();
if (resourcePath.isPresent()) {
servletContextHandler.setBaseResource(Resource.newClassPathResource(resourcePath.get()));
servletContextHandler.addServlet(new ServletHolder(DefaultServlet.class), "/*");
}
String servletPathStr = (servletPath.isPresent() ? servletPath.get() : "") + "/*";
servletContextHandler.addServlet(getServletHolder(packages), servletPathStr);
handlers.addHandler(servletContextHandler);
server.setHandler(handlers);
server.start();
}
@BeforeClass
public static void setUp() throws Exception {
// uncomment this to debug locally in IDE
//setConfigSystemPropertiesForDebugging();
server = new Server();
connector = new ServerConnector(server);
connector.setPort(PORT);
server.addConnector(connector);
HandlerList handlers = new HandlerList();
ServletContextHandler context = new ServletContextHandler();
ServletHolder defaultServ = new ServletHolder("default",
DefaultServlet.class);
defaultServ.setInitParameter("resourceBase",
System.getProperty("builddir") + "/" +
System.getProperty("artifactId") + "-" +
System.getProperty("version") + "/");
defaultServ.setInitParameter("dirAllowed",
"true");
context.addServlet(defaultServ,
"/");
handlers.addHandler(context);
server.setHandler(handlers);
server.start();
}
public static void main(String[] args) throws Exception {
Map<String, String> settings = System.getenv();
// When run from app-runner, you must use the port set in the environment variable APP_PORT
int port = Integer.parseInt(settings.getOrDefault("APP_PORT", "8081"));
// All URLs must be prefixed with the app name, which is got via the APP_NAME env var.
String appName = settings.getOrDefault("APP_NAME", "my-app");
String env = settings.getOrDefault("APP_ENV", "local"); // "prod" or "local"
boolean isLocal = "local".equals(env);
log.info("Starting " + appName + " in " + env + " on port " + port);
Server jettyServer = new Server(new InetSocketAddress("localhost", port));
jettyServer.setStopAtShutdown(true);
HandlerList handlers = new HandlerList();
// TODO: set your own handlers
handlers.addHandler(resourceHandler(isLocal));
// you must serve everything from a directory named after your app
ContextHandler ch = new ContextHandler();
ch.setContextPath("/" + appName);
ch.setHandler(handlers);
jettyServer.setHandler(ch);
try {
jettyServer.start();
} catch (Throwable e) {
log.error("Error on start", e);
System.exit(1);
}
log.info("Started app at http://localhost:" + port + ch.getContextPath());
jettyServer.join();
}
@Override
public void run() {
Server server = new Server(new QueuedThreadPool(maxThreads, 8, idleTimeout, queue));
ServerConnector connector = new ServerConnector(server, acceptors, selectors);
connector.setIdleTimeout(idleTimeout);
connector.setPort(port);
connector.setHost(host);
connector.setName("Continuum Ingress");
server.setConnectors(new Connector[] { connector });
HandlerList handlers = new HandlerList();
Handler cors = new CORSHandler();
handlers.addHandler(cors);
handlers.addHandler(new InfluxDBHandler(url, token));
server.setHandler(handlers);
JettyUtil.setSendServerVersion(server, false);
try {
server.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void installSwagger(HandlerList handlers) {
LOGGER.debug("Adding Swagger documentation");
final ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(true); //
resourceHandler.setResourceBase(getClass().getResource("/swagger").toExternalForm());
ContextHandler swaggerHandler = new ContextHandler("/swagger/*");
swaggerHandler.setHandler(resourceHandler);
handlers.addHandler(swaggerHandler);
}
private void addWarFile(HandlerList handlerList, File file, String[] virtualHost) {
String contextPath = "/" + FilenameUtils.getBaseName(file.getName());
WebAppContext webApp = createWebAppContext(contextPath, virtualHost);
webApp.setWar(file.getAbsolutePath());
handlerList.addHandler(webApp);
logger.debug("Deploying " + contextPath + " using war file " + file);
}
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);
}
private void addStaticFolder(HandlerList handlerList, File file, String[] virtualHost) {
String contextPath = "/" + file.getName();
WebAppContext webApp = createWebAppContext(contextPath, virtualHost);
webApp.setWar(file.getAbsolutePath());
handlerList.addHandler(webApp);
logger.debug("Deploying " + contextPath + " using folder " + file);
}
private void addGetStartedApplication(HandlerList handlerList, File file, String[] virtualHost) {
if (file.exists()) {
String contextPath = "/";
WebAppContext webApp = createWebAppContext(contextPath, virtualHost);
webApp.setWar(file.getAbsolutePath());
handlerList.addHandler(webApp);
}
}
private int startTransformServer() throws Exception {
URL transforms = EngineTest.class.getClassLoader().getResource(
"transforms");
if (transforms == null) {
Assert.fail();
}
int port = findFreePort();
Server fileServer = new Server(port);
ResourceHandler handler = new ResourceHandler();
MimeTypes mimeTypes = handler.getMimeTypes();
mimeTypes.addMimeMapping("json", "application/json; charset=UTF-8");
handler.setDirectoriesListed(true);
handler.setBaseResource(JarResource.newResource(transforms));
HandlerList handlers = new HandlerList();
handlers.addHandler(handler);
handlers.addHandler(new DefaultHandler());
fileServer.setHandler(handlers);
fileServer.start();
return port;
}
public void start() throws Exception {
FuzzerServiceImpl fuzzerService = new FuzzerServiceImpl(
Paths.get(workingDir, processingDir).toString(),
executorService);
FuzzerService.Processor processor =
new FuzzerService.Processor<FuzzerService.Iface>(fuzzerService);
FuzzerServiceManagerImpl fuzzerServiceManager = new FuzzerServiceManagerImpl(fuzzerService,
new PublicServerCommandDispatcher());
FuzzerServiceManager.Processor managerProcessor =
new FuzzerServiceManager.Processor<FuzzerServiceManager.Iface>(fuzzerServiceManager);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
{
ServletHolder sh = new ServletHolder();
sh.setServlet(new TServlet(processor, new TBinaryProtocol.Factory()));
context.addServlet(sh, "/request");
}
{
ServletHolder serveltHolderJson = new ServletHolder();
serveltHolderJson.setServlet(new TServlet(processor, new TJSONProtocol.Factory()));
context.addServlet(serveltHolderJson, "/requestJSON");
}
{
ServletHolder shManager = new ServletHolder();
shManager.setServlet(new TServlet(managerProcessor, new TBinaryProtocol.Factory()));
context.addServlet(shManager, "/manageAPI");
}
final String staticDir = ToolPaths.getStaticDir();
context.addServlet(
new ServletHolder(
new FileDownloadServlet(
(pathInfo, worker) -> Paths.get(staticDir, pathInfo).toFile(), staticDir)),
"/static/*");
HandlerList handlerList = new HandlerList();
handlerList.addHandler(context);
GzipHandler gzipHandler = new GzipHandler();
gzipHandler.setHandler(handlerList);
Server server = new Server(port);
server.setHandler(gzipHandler);
server.start();
server.join();
}
/**
* Creates and starts a server that is bound into the local Namespace using DEFAULT_NAMESPACE_NAME and returned
*
*
*/
public Server startServer() {
// do what StartJetty and then JettyServer did to start
try {
// Resource.setDefaultUseCaches(false);
// needs to be loaded first into the server as it setups up Emissary stuff
ContextHandler emissaryHandler = buildEmissaryHandler();
// TODO: rework this, no need for it be set with a context path but if this
// is left out, it matches / and nothing works correctly
emissaryHandler.setContextPath("/idontreallyservecontentnowdoi");
ContextHandler lbConfigHandler = buildLogbackConfigHandler();
lbConfigHandler.setContextPath("/lbConfig");
ContextHandler apiHandler = buildApiHandler();
apiHandler.setContextPath("/api");
ContextHandler mvcHandler = buildMVCHandler();
mvcHandler.setContextPath("/emissary");
// needs to be loaded last into the server so other contexts can match or fall through
ContextHandler staticHandler = buildStaticHandler();
staticHandler.setContextPath("/");
LoginService loginService = buildLoginService();
ConstraintSecurityHandler security = buildSecurityHandler();
security.setLoginService(loginService);
// secure some of the contexts
final HandlerList securedHandlers = new HandlerList();
securedHandlers.addHandler(lbConfigHandler);
securedHandlers.addHandler(apiHandler);
securedHandlers.addHandler(mvcHandler);
securedHandlers.addHandler(staticHandler);
security.setHandler(securedHandlers);
final HandlerList handlers = new HandlerList();
handlers.addHandler(emissaryHandler); // not secured, no endpoints and must be loaded first
handlers.addHandler(security);
Server server = configureServer();
server.setHandler(handlers);
server.addBean(loginService);
server.setStopAtShutdown(true);
server.setStopTimeout(10000l);
if (this.cmd.shouldDumpJettyBeans()) {
server.dump(System.out);
}
this.server = server;
bindServer(); // emissary specific
server.start();
// server.join(); // don't join so we can shutdown
String serverLocation = cmd.getScheme() + "://" + cmd.getHost() + ":" + cmd.getPort();
// write out env.sh file here
Path envsh = Paths.get(ConfigUtil.getProjectBase() + File.separator + "env.sh");
if (Files.exists(envsh)) {
LOG.debug("Removing old {}", envsh.toAbsolutePath());
Files.delete(envsh);
}
String envURI = serverLocation + "/api/env.sh";
EmissaryResponse er = new EmissaryClient().send(new HttpGet(envURI));
String envString = er.getContentString();
Files.createFile(envsh);
Files.write(envsh, envString.getBytes());
LOG.info("Wrote {}", envsh.toAbsolutePath());
LOG.debug(" with \n{}", envString);
if (cmd.isPause()) {
pause(true);
} else {
unpause(true);
}
LOG.info("Started EmissaryServer at {}", serverLocation);
return server;
} catch (Throwable t) {
t.printStackTrace(System.err);
throw new RuntimeException("Emissary server didn't start", t);
}
}
public static Server start(CenterServer centerServer) throws Exception {
cleanWorkDirectory();
HandlerList handlers = new HandlerList();
File war = new File(Config.dir_store(), x_program_center.class.getSimpleName() + ".war");
File dir = new File(Config.dir_servers_centerServer_work(true), x_program_center.class.getSimpleName());
if (war.exists()) {
modified(war, dir);
QuickStartWebApp webApp = new QuickStartWebApp();
webApp.setAutoPreconfigure(false);
webApp.setDisplayName(x_program_center.class.getSimpleName());
webApp.setContextPath("/" + x_program_center.class.getSimpleName());
webApp.setResourceBase(dir.getAbsolutePath());
webApp.setDescriptor(new File(dir, "WEB-INF/web.xml").getAbsolutePath());
webApp.setExtraClasspath(calculateExtraClassPath(x_program_center.class));
webApp.getInitParams().put("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
webApp.getInitParams().put("org.eclipse.jetty.jsp.precompiled", "true");
webApp.getInitParams().put("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
/* stat */
if (centerServer.getStatEnable()) {
FilterHolder statFilterHolder = new FilterHolder(new WebStatFilter());
statFilterHolder.setInitParameter("exclusions", centerServer.getStatExclusions());
webApp.addFilter(statFilterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
ServletHolder statServletHolder = new ServletHolder(StatViewServlet.class);
statServletHolder.setInitParameter("sessionStatEnable", "false");
webApp.addServlet(statServletHolder, "/druid/*");
}
/* stat end */
handlers.addHandler(webApp);
} else {
throw new Exception("centerServer war not exist.");
}
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setMinThreads(CENTERSERVER_THREAD_POOL_SIZE_MIN);
threadPool.setMaxThreads(CENTERSERVER_THREAD_POOL_SIZE_MAX);
Server server = new Server(threadPool);
server.setAttribute("maxFormContentSize", centerServer.getMaxFormContent() * 1024 * 1024);
if (centerServer.getSslEnable()) {
addHttpsConnector(server, centerServer.getPort());
} else {
addHttpConnector(server, centerServer.getPort());
}
GzipHandler gzipHandler = new GzipHandler();
gzipHandler.setHandler(handlers);
server.setHandler(gzipHandler);
server.setDumpAfterStart(false);
server.setDumpBeforeStop(false);
server.setStopAtShutdown(true);
server.start();
Thread.sleep(1000);
System.out.println("****************************************");
System.out.println("* center server start completed.");
System.out.println("* port: " + centerServer.getPort() + ".");
System.out.println("****************************************");
return server;
}
private void start() {
// Start a Jetty server with some sensible(?) defaults
try {
Server srv = new Server();
srv.setStopAtShutdown(true);
// Allow 5 seconds to complete.
// Adjust this to fit with your own webapp needs.
// Remove this if you wish to shut down immediately (i.e. kill <pid>
// or Ctrl+C).
srv.setGracefulShutdown(5000);
// Increase thread pool
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setMaxThreads(100);
srv.setThreadPool(threadPool);
// Ensure using the non-blocking connector (NIO)
Connector connector = new SelectChannelConnector();
connector.setPort(port);
connector.setMaxIdleTime(30000);
srv.setConnectors(new Connector[] { connector });
// Get the war-file
ProtectionDomain protectionDomain = Main.class
.getProtectionDomain();
String warFile = protectionDomain.getCodeSource().getLocation()
.toExternalForm();
String currentDir = new File(protectionDomain.getCodeSource()
.getLocation().getPath()).getParent();
// Handle signout/signin in BigIP-cluster
// Add the warFile (this jar)
WebAppContext context = new WebAppContext(warFile, contextPath);
context.setServer(srv);
resetTempDirectory(context, currentDir);
// Add the handlers
HandlerList handlers = new HandlerList();
handlers.addHandler(context);
handlers.addHandler(new ShutdownHandler(srv, context, secret));
handlers.addHandler(new BigIPNodeHandler(secret));
srv.setHandler(handlers);
srv.start();
srv.join();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
int port = 7878;
if (args.length > 1) {
if ("-port".equalsIgnoreCase(args[0])) {
try {
port = Integer.parseInt(args[1]);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid port number " + args[1]);
}
}
}
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setMaxThreads(128);
threadPool.setMinThreads(32);
Server server = new Server(threadPool);
ServerConnector connector = new ServerConnector(server);
connector.setPort(port);
server.addConnector(connector);
HandlerList handlers = new HandlerList();
handlers.addHandler(new AbstractHandler() {
@Override
public void handle(String s, Request jettyRequest,
HttpServletRequest servletRequest, HttpServletResponse servletResponse)
throws IOException, ServletException {
servletResponse.setCharacterEncoding("UTF-8");
jettyRequest.setHandled(false);
}
});
ServletHandler servletHandler = new ServletHandler();
servletHandler.addServletWithMapping(BossGameJettyServlet.class, "/PlayBossMassiveGame");
servletHandler.addServletWithMapping(ArenaGameJettyServlet.class, "/PlayAutoMassiveGame");
servletHandler.addServletWithMapping(MapGameJettyServlet.class, "/PlayMapMassiveGame");
servletHandler.addServletWithMapping(LilithGameJettyServlet.class, "/PlayLilithMassiveGame");
servletHandler.addServletWithMapping(PingJettyServlet.class, "/Ping");
handlers.addHandler(servletHandler);
server.setHandler(handlers);
server.start();
server.join();
}