下面列出了org.eclipse.jetty.server.Server#setDumpAfterStart ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void main(String args[]) throws Exception {
if(args.length != 1) {
throw new Exception("Need exactly two argument containing th path to the configuration " +
"followed by the port number the server should use");
}
final String configPath = args[0];
// Setup a minimal servlet context for hosting our message broker servlet.
final Server server = new Server(0);
final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/qa-regress");
final MessageBrokerServlet messageBrokerServlet = new MessageBrokerServlet();
final ServletHolder servlet = new ServletHolder(messageBrokerServlet);
servlet.setInitParameter("services.configuration.file", configPath);
context.addServlet(servlet, "/messagebroker/amf/*");
server.setHandler(context);
server.setDumpAfterStart(true);
try {
server.start();
} catch(Exception e) {
e.printStackTrace();
}
int port = ((ServerConnector) server.getConnectors()[0]).getLocalPort();
System.out.println("Port:" + port);
}
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;
}
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;
}
@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();
}
/**
* Returns a newly-created {@link JettyService} based on the properties of this builder.
*/
public JettyService build() {
final JettyServiceConfig config = new JettyServiceConfig(
hostname, dumpAfterStart, dumpBeforeStop, stopTimeoutMillis, handler, requestLog,
sessionIdManagerFactory, attrs, beans, handlerWrappers, eventListeners, lifeCycleListeners,
configurators);
final Function<ScheduledExecutorService, Server> serverFactory = blockingTaskExecutor -> {
final Server server = new Server(new ArmeriaThreadPool(blockingTaskExecutor));
if (config.dumpAfterStart() != null) {
server.setDumpAfterStart(config.dumpAfterStart());
}
if (config.dumpBeforeStop() != null) {
server.setDumpBeforeStop(config.dumpBeforeStop());
}
if (config.stopTimeoutMillis() != null) {
server.setStopTimeout(config.stopTimeoutMillis());
}
if (config.handler() != null) {
server.setHandler(config.handler());
}
if (config.requestLog() != null) {
server.setRequestLog(requestLog);
}
if (config.sessionIdManagerFactory() != null) {
server.setSessionIdManager(config.sessionIdManagerFactory().apply(server));
}
config.handlerWrappers().forEach(server::insertHandler);
config.attrs().forEach(server::setAttribute);
config.beans().forEach(bean -> {
final Boolean managed = bean.isManaged();
if (managed == null) {
server.addBean(bean.bean());
} else {
server.addBean(bean.bean(), managed);
}
});
config.eventListeners().forEach(server::addEventListener);
config.lifeCycleListeners().forEach(server::addLifeCycleListener);
config.configurators().forEach(c -> c.accept(server));
return server;
};
final Consumer<Server> postStopTask = server -> {
try {
JettyService.logger.info("Destroying an embedded Jetty: {}", server);
server.destroy();
} catch (Exception e) {
JettyService.logger.warn("Failed to destroy an embedded Jetty: {}", server, e);
}
};
return new JettyService(config.hostname(), serverFactory, postStopTask);
}
@SuppressWarnings({"resource", "boxing"})
public static Server newServer(int jettyPort, String jettyWebAppDir, JettyServiceSetting jettyServiceSetting) throws Exception {
if (jettyPort == 0 || jettyWebAppDir == null) {
throw new IllegalArgumentException("Jetty port and resource dir may not be empty");
}
// server setup
Server server = new Server();
server.addBean(new ScheduledExecutorScheduler());
server.setDumpAfterStart(false);
server.setDumpBeforeStop(false);
server.setStopAtShutdown(true);
// http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html#d0e19050
// Setup JMX
MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
server.addBean(mbContainer);
//setup handlers according to the jetty settings
HandlerCollection handlerCollection = new HandlerCollection();
if (jettyServiceSetting == JettyServiceSetting.ARTIFACTORY || jettyServiceSetting == JettyServiceSetting.BOTH) {
// The WebAppContext is the entity that controls the environment in
// which a web application lives and breathes. In this example the
// context path is being set to "/" so it is suitable for serving root
// context requests and then we see it setting the location of the war.
// A whole host of other configurations are available, ranging from
// configuring to support annotation scanning in the webapp (through
// PlusConfiguration) to choosing where the webapp will unpack itself.
WebAppContext webapp = new WebAppContext();
File warFile = new File(jettyWebAppDir + File.separator + "artifactory.war");
webapp.setContextPath("/artifactory");
webapp.setWar(warFile.getAbsolutePath());
// A WebAppContext is a ContextHandler as well so it needs to be set to
// the server so it is aware of where to send the appropriate requests.
handlerCollection.addHandler(webapp);
}
if (jettyServiceSetting == JettyServiceSetting.VIP || jettyServiceSetting == JettyServiceSetting.BOTH) {
// Serve resource files which reside in the jettyWebAppDir
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(false);
resourceHandler.setResourceBase(jettyWebAppDir);
handlerCollection.addHandler(resourceHandler);
}
server.setHandler(handlerCollection);
// http configuration
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSendServerVersion(true);
// HTTP connector
ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config));
http.setPort(jettyPort);
server.addConnector(http);
// start server
server.start();
LOG.info("Started jetty server on port: {}, resource dir: {} ", jettyPort, jettyWebAppDir);
return server;
}
/**
* Creates a Server that exposes the TestClient1 services via http and https
*
* @return the Server instance
*/
@Override
protected Server createServer() {
// Need this CredentialsSourceFactory in our config to enable our test of basic auth
// with our httpInvoker-echoServiceSecure
registerTestCredentialsSourceFactory();
ConfigConstants configConstants = new ConfigConstants();
Server server = new Server();
SelectChannelConnector connector0 = new SelectChannelConnector();
connector0.setPort(configConstants.SERVER_HTTP_PORT);
connector0.setMaxIdleTime(30000);
connector0.setRequestHeaderSize(8192);
SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector();
ssl_connector.setPort(configConstants.SERVER_HTTPS_PORT);
SslContextFactory cf = ssl_connector.getSslContextFactory();
cf.setKeyStore(configConstants.KEYSTORE_PATH);
cf.setKeyStorePassword(configConstants.KEYSTORE_PASS);
cf.setKeyManagerPassword(configConstants.KEYSTORE_PASS);
server.setConnectors(new Connector[]{connector0, ssl_connector});
URL webRoot = getClass().getClassLoader().getResource(configConstants.WEB_ROOT);
String location = webRoot.getPath();
LOG.debug("#####################################");
LOG.debug("#");
LOG.debug("# Starting Client1 using following web root " + location);
LOG.debug("#");
LOG.debug("#####################################");
WebAppContext context = new WebAppContext();
context.setResourceBase(location);
context.setContextPath(configConstants.CONTEXT);
HandlerCollection handlers = new HandlerCollection();
handlers.addHandler(context);
server.setHandler(handlers);
server.setDumpAfterStart(true);
//server.setDumpBeforeStop(true);
return server;
}