下面列出了怎么用org.eclipse.jetty.server.handler.ContextHandlerCollection的API类实例代码及写法,或者点击链接到github查看源代码。
public static Server getJettyServer(List<ServletContextHandler> handlers, int port) {
Server server = new Server(port);
ErrorHandler errorHandler = new ErrorHandler();
errorHandler.setShowStacks(true);
errorHandler.setServer(server);
server.addBean(errorHandler);
ContextHandlerCollection collection = new ContextHandlerCollection();
ServletContextHandler[] sch = new ServletContextHandler[handlers.size()];
for (int i = 0; i < handlers.size(); i++) {
sch[i] = handlers.get(i);
}
collection.setHandlers(sch);
server.setHandler(collection);
return server;
}
public WebServer(int port, String resRoot){
super(port);
LOG.info("Port:{}, Resources Root:{}", port, resRoot);
ResourceHandler rh0 = new ResourceHandler();
ContextHandler context0 = new ContextHandler();
context0.setContextPath("/res/*");
context0.setResourceBase(resRoot);
context0.setHandler(rh0);
//ServletHandler context1 = new ServletHandler();
//this.setHandler(context1);
ServletContextHandler context1 = new ServletContextHandler();
context1.addServlet(TestSlaveServlet.class, "/slavesite/*");
// Create a ContextHandlerCollection and set the context handlers to it.
// This will let jetty process urls against the declared contexts in
// order to match up content.
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[] { context1, context0});
this.setHandler(contexts);
}
public void start() throws Exception {
RequestLogHandler requestLogHandler = new RequestLogHandler();
Slf4jRequestLog requestLog = new Slf4jRequestLog();
requestLog.setExtended(true);
requestLog.setLogTimeZone(TimeZone.getDefault().getID());
requestLog.setLogLatency(true);
requestLogHandler.setRequestLog(requestLog);
handlers.add(0, new ContextHandlerCollection());
handlers.add(requestLogHandler);
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));
HandlerCollection handlerCollection = new HandlerCollection();
handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
server.setHandler(handlerCollection);
server.start();
log.info("Server started at end point {}", getServiceUri());
}
public void start() throws PulsarServerException {
log.info("Starting web socket proxy at port {}", conf.getWebServicePort().get());
RequestLogHandler requestLogHandler = new RequestLogHandler();
Slf4jRequestLog requestLog = new Slf4jRequestLog();
requestLog.setExtended(true);
requestLog.setLogTimeZone(TimeZone.getDefault().getID());
requestLog.setLogLatency(true);
requestLogHandler.setRequestLog(requestLog);
handlers.add(0, new ContextHandlerCollection());
handlers.add(requestLogHandler);
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));
HandlerCollection handlerCollection = new HandlerCollection();
handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
server.setHandler(handlerCollection);
try {
server.start();
} catch (Exception e) {
throw new PulsarServerException(e);
}
}
public JavaNetReverseProxy(File cacheFolder) throws Exception {
this.cacheFolder = cacheFolder;
cacheFolder.mkdirs();
QueuedThreadPool qtp = new QueuedThreadPool();
qtp.setName("Jetty (JavaNetReverseProxy)");
server = new Server(qtp);
ContextHandlerCollection contexts = new ContextHandlerCollection();
server.setHandler(contexts);
ServletContextHandler root = new ServletContextHandler(contexts, "/", ServletContextHandler.SESSIONS);
root.addServlet(new ServletHolder(this), "/");
ServerConnector connector = new ServerConnector(server);
server.addConnector(connector);
server.start();
localPort = connector.getLocalPort();
}
/**
* Starts the document storage. Afterwards it will be ready to serve
* documents.
*
* @throws Exception
* error starting the web server
*
* @since 0.7.8
*/
public void start() throws Exception {
if (storagePort < 0) {
return;
}
server = new Server(storagePort);
ContextHandler rootContext = new ContextHandler();
rootContext.setHandler(internalGrammarHandler);
ContextHandler internalGrammarContext = new ContextHandler(
InternalGrammarDocumentHandler.CONTEXT_PATH);
internalGrammarContext.setHandler(internalGrammarHandler);
ContextHandler builtinGrammarContext = new ContextHandler(
BuiltinGrammarHandler.CONTEXT_PATH);
ContextHandlerCollection contexts = new ContextHandlerCollection();
builtinGrammarContext.setHandler(builtinGrammarHandler);
ContextHandler[] handlers = new ContextHandler[] { rootContext,
internalGrammarContext, builtinGrammarContext };
contexts.setHandlers(handlers);
server.setHandler(contexts);
server.start();
LOGGER.info("document storage started on port " + storagePort);
}
private static HandlerCollection createHandlers(
final GatewayConfig config,
final GatewayServices services,
final ContextHandlerCollection contexts) {
HandlerCollection handlers = new HandlerCollection();
RequestLogHandler logHandler = new RequestLogHandler();
logHandler.setRequestLog(new AccessHandler());
TraceHandler traceHandler = new TraceHandler();
traceHandler.setHandler(contexts);
traceHandler.setTracedBodyFilter(System.getProperty("org.apache.knox.gateway.trace.body.status.filter"));
CorrelationHandler correlationHandler = new CorrelationHandler();
correlationHandler.setHandler(traceHandler);
DefaultTopologyHandler defaultTopoHandler = new DefaultTopologyHandler(config, services, contexts);
handlers.setHandlers(new Handler[]{correlationHandler, defaultTopoHandler, logHandler});
return handlers;
}
private void applyHandle(final String contextPath, final String warPath) {
final ContextHandlerCollection handler = new ContextHandlerCollection();
final WebAppContext webapp = new WebAppContext();
webapp.setContextPath(contextPath);
webapp.setDefaultsDescriptor(WEB_DEFAULT);
if (StringUtils.isEmpty(warPath)) {
webapp.setResourceBase(DEFAULT_RESOURCE_BASE);
webapp.setDescriptor(DEFAULT_WEB_XML_PATH);
} else {
webapp.setWar(warPath);
}
applySessionHandler(webapp);
handler.addHandler(webapp);
super.setHandler(handler);
}
public static void main( String[] args )
throws Exception
{
Server server = new Server( 8080 );
WebAppContext webappcontext = new WebAppContext( "src/main/webapp", "/jaxrs" );
ContextHandlerCollection servlet_contexts = new ContextHandlerCollection();
webappcontext.setClassLoader( Thread.currentThread().getContextClassLoader() );
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers( new Handler[] { servlet_contexts, webappcontext, new DefaultHandler() } );
server.setHandler( handlers );
server.start();
server.join();
}
public static void main( String[] args )
throws Exception
{
Server server = new Server( 8080 );
WebAppContext webappcontext = new WebAppContext( "src/main/webapp", "/jaxrs" );
ContextHandlerCollection servlet_contexts = new ContextHandlerCollection();
webappcontext.setClassLoader( Thread.currentThread().getContextClassLoader() );
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers( new Handler[] { servlet_contexts, webappcontext, new DefaultHandler() } );
server.setHandler( handlers );
server.start();
server.join();
}
public static void main( String[] args )
throws Exception
{
Server server = new Server( 8080 );
WebAppContext webappcontext = new WebAppContext( "src/main/webapp", "/jaxrs" );
ContextHandlerCollection servlet_contexts = new ContextHandlerCollection();
webappcontext.setClassLoader( Thread.currentThread().getContextClassLoader() );
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers( new Handler[] { servlet_contexts, webappcontext, new DefaultHandler() } );
server.setHandler( handlers );
server.start();
server.join();
}
private void finalizeHandlerCollection(HandlerCollection handlers, HandlerCollection wsHandlers) {
/* DefaultHandler must come last eo ensure all contexts
* have a chance to handle a request first */
handlers.addHandler(new DefaultHandler());
/* Needed for graceful shutdown as per `setStopTimeout` documentation */
StatisticsHandler statsHandler = new StatisticsHandler();
statsHandler.setHandler(handlers);
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[]{
statsHandler,
wsHandlers
});
super.setHandler(wrapWithGzipHandler(contexts));
}
public void registerServlet(String context, Servlet servlet, Dictionary dictionary, HttpContext httpContext) throws ServletException, NamespaceException {
ContextHandlerCollection contexts = new ContextHandlerCollection();
server.setHandler(contexts);
ServletContextHandler root = new ServletContextHandler(contexts, "/",
ServletContextHandler.SESSIONS);
ServletHolder servletHolder = new ServletHolder(servlet);
root.addServlet(servletHolder, context);
if (!server.getServer().getState().equals(server.STARTED)) {
try {
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void configure() throws Exception {
server.addEventListener(mbeans());
server.addConnector(plainConnector());
ContextHandlerCollection handlers = new ContextHandlerCollection();
deploymentManager.setContexts(handlers);
createWebAppContext();
JettyCustomErrorPageHandler errorHandler = new JettyCustomErrorPageHandler();
webAppContext.setErrorHandler(errorHandler);
webAppContext.setGzipHandler(gzipHandler());
server.addBean(errorHandler);
server.addBean(deploymentManager);
HandlerCollection serverLevelHandlers = new HandlerCollection();
serverLevelHandlers.setHandlers(new Handler[]{handlers});
server.setHandler(serverLevelHandlers);
performCustomConfiguration();
server.setStopAtShutdown(true);
}
/**
* Post deploy
* @exception Throwable Thrown if an error occurs
*/
public void postDeploy() throws Throwable
{
if (server != null &&
!server.isRunning() &&
handlers != null && handlers.getHandlers() != null && handlers.getHandlers().length > 0)
{
try
{
ContextHandlerCollection chc = new ContextHandlerCollection();
chc.setHandlers(handlers.getHandlers());
server.setHandler(chc);
server.start();
}
catch (Exception e)
{
log.error("Could not start Jetty webserver", e);
}
}
}
/**
* Start/run the server.
*/
public void start() throws Exception {
long startTime = System.currentTimeMillis();
System.out.println("**** Starting Server (" + getClass().getSimpleName() + ")");
preStart();
ContextHandlerCollection handlers = new ContextHandlerCollection();
addModulesToJetty(handlers);
// Create the server.
int serverPort = serverPort();
server = new Server(serverPort);
server.setHandler(handlers);
server.start();
long endTime = System.currentTimeMillis();
System.out.println("******* Started in " + (endTime - startTime) + "ms");
}
/**
* Start/run the server.
* @throws Exception when any exception occurs
*/
public void start() throws Exception {
long startTime = System.currentTimeMillis();
ContextHandlerCollection handlers = new ContextHandlerCollection();
addModulesToJetty(handlers);
// Create the server.
int serverPort = serverPort();
System.out.println("**** Starting Gateway (" + getClass().getSimpleName() + ") on port: " + serverPort);
server = new Server(serverPort);
server.setHandler(handlers);
server.start();
long endTime = System.currentTimeMillis();
System.out.println("******* Started in " + (endTime - startTime) + "ms");
}
/**
* Start/run the server.
*/
public EchoServer start() throws Exception {
long startTime = System.currentTimeMillis();
System.out.println("**** Starting Server (" + getClass().getSimpleName() + ") on port " + port); //$NON-NLS-1$ //$NON-NLS-2$
preStart();
ContextHandlerCollection handlers = new ContextHandlerCollection();
addModulesToJetty(handlers);
// Create the server.
server = new Server(port);
server.setHandler(handlers);
server.start();
long endTime = System.currentTimeMillis();
System.out.println("******* Started in " + (endTime - startTime) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
return this;
}
private Server createServer(InetSocketAddress address) throws Exception {
Server server = new Server(address);
Configuration.ClassList classList = Configuration.ClassList.setServerDefault(server);
classList.addBefore(JettyWebXmlConfiguration.class.getName(), AnnotationConfiguration.class.getName());
ContextHandlerCollection handlerCollection = new ContextHandlerCollection();
Handler applicationHandler = createApplicationHandler();
handlerCollection.addHandler(applicationHandler);
Handler adminConsoleHandler = createAdminConsoleHandler();
if(adminConsoleHandler != null){
handlerCollection.addHandler(adminConsoleHandler);
}
server.setHandler(handlerCollection);
return server;
}
public static Server startControlledBounceproxy(String bpId) throws Exception {
final int port = ServletUtil.findFreePort();
final String bpUrl = "http://localhost:" + port + "/bounceproxy/";
System.setProperty("joynr.bounceproxy.id", bpId);
System.setProperty("joynr.bounceproxy.controller.baseurl",
System.getProperty(MessagingPropertyKeys.BOUNCE_PROXY_URL));
System.setProperty("joynr.bounceproxy.url4cc", bpUrl);
System.setProperty("joynr.bounceproxy.url4bpc", bpUrl);
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[]{ createControlledBounceproxyWebApp("", null) });
Server server = startServer(contexts, port);
System.clearProperty("joynr.bounceproxy.id");
System.clearProperty("joynr.bounceproxy.controller.baseurl");
System.clearProperty("joynr.bounceproxy.url4cc");
System.clearProperty("joynr.bounceproxy.url4bpc");
return server;
}
private static Server startServer(ContextHandlerCollection contexts, int port) throws Exception {
System.setProperty(MessagingPropertyKeys.PROPERTY_SERVLET_HOST_PATH, "http://localhost:" + port);
setBounceProxyUrl();
setDirectoriesUrl();
logger.info("HOST PATH: {}", System.getProperty(MessagingPropertyKeys.PROPERTY_SERVLET_HOST_PATH));
final Server jettyServer = new Server();
ServerConnector connector = new ServerConnector(jettyServer,
new HttpConnectionFactory(new HttpConfiguration()));
connector.setPort(port);
connector.setAcceptQueueSize(1);
jettyServer.setConnectors(new Connector[]{ connector });
jettyServer.setHandler(contexts);
jettyServer.start();
logger.trace("Started jetty server: {}", jettyServer.dump());
return jettyServer;
}
/**
* bind handler for right url
*/
private void bindHandler() {
logger.debug("bindHandler");
CreateZNodesHandler.register();
RemoveNodeHandler.register();
ExistNodeHandler.register();
ResetCounterHandler.register();
SetInstanceOffline.register();
SetInstanceOnline.register();
SetBinlogPosHandler.register();
SetLeaderHandler.register();
SetCandidateHandler.register();
SetTerminalHandler.register();
GetSlaveBinlogHandler.register();
SetAdminHandler.register();
ContextHandlerCollection contexts = new ContextHandlerCollection();
Handler[] handlers = new Handler[ApiCenter.CONTEXTS.size()];
int index = 0;
for (ContextHandler handler : ApiCenter.CONTEXTS) {
handlers[index++] = handler;
}
contexts.setHandlers(handlers);
server.setHandler(contexts);
}
private void startHttpServer() throws Exception {
KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv();
createAndConfigHttpServer(kylinConfig);
ContextHandlerCollection contexts = new ContextHandlerCollection();
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/kylin");
XmlWebApplicationContext ctx = new XmlWebApplicationContext();
ctx.setConfigLocation("classpath:applicationContext.xml");
ctx.refresh();
DispatcherServlet dispatcher = new DispatcherServlet(ctx);
context.addServlet(new ServletHolder(dispatcher), "/api/*");
ContextHandler logContext = new ContextHandler("/kylin/logs");
String logDir = getLogDir(kylinConfig);
ResourceHandler logHandler = new ResourceHandler();
logHandler.setResourceBase(logDir);
logHandler.setDirectoriesListed(true);
logContext.setHandler(logHandler);
contexts.setHandlers(new Handler[] { context, logContext });
httpServer.setHandler(contexts);
httpServer.start();
httpServer.join();
}
private static ContextHandlerCollection getContexts() {
ContextHandlerCollection ctxs = contexts;
if (ctxs == null) {
throw new RuntimeException("http server not started");
}
return ctxs;
}
/**
* init and start a jetty server, remember to call server.stop when the task is finished
*
* @param handlers
* @throws Exception
*/
protected Server startServerWithHandlers(ContextHandler... handlers) throws Exception {
server = new Server(PORT);
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(handlers);
contexts.addHandler(mockMetaServerHandler());
server.setHandler(contexts);
server.start();
return server;
}
/**
* init and start a jetty server, remember to call server.stop when the task is finished
*/
protected Server startServerWithHandlers(ContextHandler... handlers) throws Exception {
server = new Server(PORT);
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(handlers);
server.setHandler(contexts);
server.start();
return server;
}
/**
* init and start a jetty server, remember to call server.stop when the task is finished
*/
protected Server startServerWithHandlers(ContextHandler... handlers) throws Exception {
server = new Server(PORT);
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(handlers);
server.setHandler(contexts);
server.start();
return server;
}
/**
* Initialization of the context path for the web application "/console" occurs in this method
* and the handler for the web application is set. This only occurs once.
* @return HttpServer: the singleton instance of this class
* @throws IOException
*/
public static HttpServer getInstance() throws Exception {
if (!HttpServerHolder.INITIALIZED) {
HttpServerHolder.WEBAPP.setContextPath("/console");
ServletContextHandler contextJobs = new ServletContextHandler(ServletContextHandler.SESSIONS);
contextJobs.setContextPath("/jobs");
ServletContextHandler contextMetrics = new ServletContextHandler(ServletContextHandler.SESSIONS);
contextMetrics.setContextPath("/metrics");
ServerUtil sUtil = new ServerUtil();
String commandWarFilePath = sUtil.getAbsoluteWarFilePath("console.war");
if (commandWarFilePath.equals("")){
// check if we are on Eclipse, if Eclipse can't find it, it probably does not exist
// running on Eclipse, look for the eclipse war file path
ProtectionDomain protectionDomain = HttpServer.class.getProtectionDomain();
String eclipseWarFilePath = sUtil.getEclipseWarFilePath(protectionDomain, "console.war");
if (!eclipseWarFilePath.equals("")) {
HttpServerHolder.WEBAPP.setWar(eclipseWarFilePath);
} else {
throw new Exception(HttpServerHolder.consoleWarNotFoundMessage);
}
} else {
HttpServerHolder.WEBAPP.setWar(commandWarFilePath);
}
HttpServerHolder.WEBAPP.addAliasCheck(new AllowSymLinkAliasChecker());
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[] { contextJobs, contextMetrics, HttpServerHolder.WEBAPP });
HttpServerHolder.JETTYSERVER.setHandler(contexts);
HttpServerHolder.INITIALIZED = true;
}
return HttpServerHolder.INSTANCE;
}
@Override
public void init(ContextHandlerCollection handlers) {
instance = this;
ServletContextHandler servletHandler = new ServletContextHandler();
servletHandler.setContextPath("/");
servletHandler.addServlet(WSServlet.class, "/ws");
handlers.addHandler(servletHandler);
}
@Override
protected void doStart() throws Exception {
AbstractHandler noContentHandler = new NoContentOutputErrorHandler();
// This part is needed to avoid WARN while starting container.
noContentHandler.setServer(server);
server.addBean(noContentHandler);
// Spring configuration
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "basic");
List<ServletContextHandler> contexts = new ArrayList<>();
if (startPortalAPI) {
// REST configuration for Portal API
ServletContextHandler portalContextHandler = configureAPI(portalEntrypoint, GraviteePortalApplication.class.getName(), SecurityPortalConfiguration.class);
contexts.add(portalContextHandler);
}
if (startManagementAPI) {
// REST configuration for Management API
ServletContextHandler managementContextHandler = configureAPI(managementEntrypoint, GraviteeManagementApplication.class.getName(), SecurityManagementConfiguration.class);
contexts.add(managementContextHandler);
}
if (contexts.isEmpty()) {
throw new IllegalStateException("At least one API should be enabled");
}
server.setHandler(new ContextHandlerCollection(contexts.toArray(new ServletContextHandler[contexts.size()])));
// start the server
server.start();
}