use of org.eclipse.jetty.deploy.DeploymentManager in project jetty.project by eclipse.
the class OverlayServer method main.
public static void main(String[] args) throws Exception {
// NamingUtil.__log.setDebugEnabled(true);
String jetty_home = System.getProperty("jetty.home", "target/test-classes/home");
System.setProperty("jetty.home", jetty_home);
Server server = new Server();
server.setAttribute("org.eclipse.jetty.webapp.configuration", new String[] { org.eclipse.jetty.webapp.WebInfConfiguration.class.getCanonicalName(), org.eclipse.jetty.webapp.WebXmlConfiguration.class.getCanonicalName(), org.eclipse.jetty.webapp.MetaInfConfiguration.class.getCanonicalName(), org.eclipse.jetty.webapp.FragmentConfiguration.class.getCanonicalName(), org.eclipse.jetty.plus.webapp.EnvConfiguration.class.getCanonicalName(), org.eclipse.jetty.plus.webapp.PlusConfiguration.class.getCanonicalName(), org.eclipse.jetty.webapp.JettyWebXmlConfiguration.class.getCanonicalName() });
// Setup Connectors
ServerConnector connector = new ServerConnector(server);
connector.setPort(8080);
server.addConnector(connector);
HandlerCollection handlers = new HandlerCollection();
ContextHandlerCollection contexts = new ContextHandlerCollection();
RequestLogHandler requestLogHandler = new RequestLogHandler();
handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
StatisticsHandler stats = new StatisticsHandler();
stats.setHandler(handlers);
server.setHandler(stats);
// Setup deployers
DeploymentManager deployer = new DeploymentManager();
deployer.setContexts(contexts);
server.addBean(deployer);
OverlayedAppProvider provider = new OverlayedAppProvider();
provider.setNodeName("nodeA");
provider.setScanDir(new File(jetty_home + "/overlays"));
provider.setScanInterval(2);
deployer.addAppProvider(provider);
server.setStopAtShutdown(true);
//server.setSendServerVersion(true);
// Uncomment to work with JNDI examples
// new org.eclipse.jetty.plus.jndi.Transaction(new com.atomikos.icatch.jta.UserTransactionImp());
server.start();
server.join();
}
use of org.eclipse.jetty.deploy.DeploymentManager in project gocd by gocd.
the class Jetty9ServerTest method setUp.
@BeforeEach
public void setUp() throws Exception {
when(server.getThreadPool()).thenReturn(new QueuedThreadPool(1));
Answer<Void> setHandlerMock = invocation -> {
serverLevelHandler = (Handler) invocation.getArguments()[0];
serverLevelHandler.setServer((Server) invocation.getMock());
return null;
};
Mockito.lenient().doAnswer(setHandlerMock).when(server).setHandler(any(Handler.class));
appCaptor = ArgumentCaptor.forClass(App.class);
Mockito.doNothing().when(deploymentManager).addApp(appCaptor.capture());
when(systemEnvironment.getServerPort()).thenReturn(1234);
when(systemEnvironment.getWebappContextPath()).thenReturn("context");
when(systemEnvironment.getCruiseWar()).thenReturn("cruise.war");
when(systemEnvironment.getParentLoaderPriority()).thenReturn(true);
when(systemEnvironment.useCompressedJs()).thenReturn(true);
when(systemEnvironment.get(SystemEnvironment.RESPONSE_BUFFER_SIZE)).thenReturn(1000);
when(systemEnvironment.get(SystemEnvironment.IDLE_TIMEOUT)).thenReturn(2000);
when(systemEnvironment.configDir()).thenReturn(configDir);
when(systemEnvironment.getJettyConfigFile()).thenReturn(new File("foo"));
when(systemEnvironment.isSessionCookieSecure()).thenReturn(false);
when(systemEnvironment.sessionTimeoutInSeconds()).thenReturn(1234);
when(systemEnvironment.sessionCookieMaxAgeInSeconds()).thenReturn(5678);
when(sslSocketFactory.getSupportedCipherSuites()).thenReturn(new String[] {});
jetty9Server = new Jetty9Server(systemEnvironment, "pwd", server, deploymentManager);
ReflectionUtil.setStaticField(Jetty9Server.class, "JETTY_XML_LOCATION_IN_JAR", "config");
}
use of org.eclipse.jetty.deploy.DeploymentManager in project athenz by yahoo.
the class AthenzJettyContainer method addServletHandlers.
public void addServletHandlers(String serverHostName) {
// Handler Structure
RewriteHandler rewriteHandler = new RewriteHandler();
// Check whether or not to disable Keep-Alive support in Jetty.
// This will be the first handler in our array so we always set
// the appropriate header in response. However, since we're now
// behind ATS, we want to keep the connections alive so ATS
// can re-use them as necessary
boolean keepAlive = Boolean.parseBoolean(System.getProperty(AthenzConsts.ATHENZ_PROP_KEEP_ALIVE, "true"));
if (!keepAlive) {
HeaderPatternRule disableKeepAliveRule = new HeaderPatternRule();
disableKeepAliveRule.setPattern("/*");
disableKeepAliveRule.setName(HttpHeader.CONNECTION.asString());
disableKeepAliveRule.setValue(HttpHeaderValue.CLOSE.asString());
rewriteHandler.addRule(disableKeepAliveRule);
}
// Add response-headers, according to configuration
final String responseHeadersJson = System.getProperty(AthenzConsts.ATHENZ_PROP_RESPONSE_HEADERS_JSON);
if (!StringUtil.isEmpty(responseHeadersJson)) {
HashMap<String, String> responseHeaders;
try {
responseHeaders = new ObjectMapper().readValue(responseHeadersJson, new TypeReference<HashMap<String, String>>() {
});
} catch (Exception exception) {
throw new RuntimeException("System-property \"" + AthenzConsts.ATHENZ_PROP_RESPONSE_HEADERS_JSON + "\" must be a JSON object with string values. System property's value: " + responseHeadersJson);
}
for (Map.Entry<String, String> responseHeader : responseHeaders.entrySet()) {
HeaderPatternRule rule = new HeaderPatternRule();
rule.setPattern("/*");
rule.setName(responseHeader.getKey());
rule.setValue(responseHeader.getValue());
rewriteHandler.addRule(rule);
}
}
// Return a Host field in the response so during debugging
// we know what server was handling request
HeaderPatternRule hostNameRule = new HeaderPatternRule();
hostNameRule.setPattern("/*");
hostNameRule.setName(HttpHeader.HOST.asString());
hostNameRule.setValue(serverHostName);
rewriteHandler.addRule(hostNameRule);
handlers.addHandler(rewriteHandler);
ContextHandlerCollection contexts = new ContextHandlerCollection();
// check to see if gzip support is enabled
boolean gzipSupport = Boolean.parseBoolean(System.getProperty(AthenzConsts.ATHENZ_PROP_GZIP_SUPPORT, "false"));
if (gzipSupport) {
int gzipMinSize = Integer.parseInt(System.getProperty(AthenzConsts.ATHENZ_PROP_GZIP_MIN_SIZE, "1024"));
GzipHandler gzipHandler = new GzipHandler();
gzipHandler.setMinGzipSize(gzipMinSize);
gzipHandler.setIncludedMimeTypes("application/json");
gzipHandler.setHandler(contexts);
handlers.addHandler(gzipHandler);
}
// check to see if graceful shutdown support is enabled
boolean gracefulShutdown = Boolean.parseBoolean(System.getProperty(AthenzConsts.ATHENZ_PROP_GRACEFUL_SHUTDOWN, "false"));
if (gracefulShutdown) {
server.setStopAtShutdown(true);
long stopTimeout = Long.parseLong(System.getProperty(AthenzConsts.ATHENZ_PROP_GRACEFUL_SHUTDOWN_TIMEOUT, "30000"));
server.setStopTimeout(stopTimeout);
StatisticsHandler statisticsHandler = new StatisticsHandler();
statisticsHandler.setHandler(contexts);
handlers.addHandler(statisticsHandler);
}
handlers.addHandler(contexts);
// now setup our default servlet handler for filters
ServletContextHandler servletCtxHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
servletCtxHandler.setContextPath("/");
FilterHolder filterHolder = new FilterHolder(HealthCheckFilter.class);
final String healthCheckPath = System.getProperty(AthenzConsts.ATHENZ_PROP_HEALTH_CHECK_PATH, getRootDir());
filterHolder.setInitParameter(AthenzConsts.ATHENZ_PROP_HEALTH_CHECK_PATH, healthCheckPath);
final String checkList = System.getProperty(AthenzConsts.ATHENZ_PROP_HEALTH_CHECK_URI_LIST);
if (!StringUtil.isEmpty(checkList)) {
String[] checkUriArray = checkList.split(",");
for (String checkUri : checkUriArray) {
servletCtxHandler.addFilter(filterHolder, checkUri.trim(), EnumSet.of(DispatcherType.REQUEST));
}
}
contexts.addHandler(servletCtxHandler);
DeploymentManager deployer = new DeploymentManager();
boolean debug = Boolean.parseBoolean(System.getProperty(AthenzConsts.ATHENZ_PROP_DEBUG, "false"));
if (debug) {
DebugListener debugListener = new DebugListener(System.err, true, true, true);
server.addBean(debugListener);
deployer.addLifeCycleBinding(new DebugListenerBinding(debugListener));
}
deployer.setContexts(contexts);
deployer.setContextAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/servlet-api-[^/]*\\.jar$");
final String jettyHome = System.getProperty(AthenzConsts.ATHENZ_PROP_JETTY_HOME, getRootDir());
WebAppProvider webappProvider = new WebAppProvider();
webappProvider.setMonitoredDirName(jettyHome + "/webapps");
webappProvider.setScanInterval(60);
webappProvider.setExtractWars(true);
webappProvider.setConfigurationManager(new PropertiesConfigurationManager());
webappProvider.setParentLoaderPriority(true);
// set up a Default web.xml file. file is applied to a Web application before it's own WEB_INF/web.xml
setDefaultsDescriptor(webappProvider, jettyHome);
final String jettyTemp = System.getProperty(AthenzConsts.ATHENZ_PROP_JETTY_TEMP, jettyHome + "/temp");
webappProvider.setTempDir(new File(jettyTemp));
deployer.addAppProvider(webappProvider);
server.addBean(deployer);
}
use of org.eclipse.jetty.deploy.DeploymentManager in project jetty.project by eclipse.
the class LikeJettyXml method main.
public static void main(String[] args) throws Exception {
// Path to as-built jetty-distribution directory
String jettyHomeBuild = "../../jetty-distribution/target/distribution";
// Find jetty home and base directories
String homePath = System.getProperty("jetty.home", jettyHomeBuild);
File start_jar = new File(homePath, "start.jar");
if (!start_jar.exists()) {
homePath = jettyHomeBuild = "jetty-distribution/target/distribution";
start_jar = new File(homePath, "start.jar");
if (!start_jar.exists())
throw new FileNotFoundException(start_jar.toString());
}
File homeDir = new File(homePath);
String basePath = System.getProperty("jetty.base", homeDir + "/demo-base");
File baseDir = new File(basePath);
if (!baseDir.exists()) {
throw new FileNotFoundException(baseDir.getAbsolutePath());
}
// Configure jetty.home and jetty.base system properties
String jetty_home = homeDir.getAbsolutePath();
String jetty_base = baseDir.getAbsolutePath();
System.setProperty("jetty.home", jetty_home);
System.setProperty("jetty.base", jetty_base);
// === jetty.xml ===
// Setup Threadpool
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setMaxThreads(500);
// Server
Server server = new Server(threadPool);
// Scheduler
server.addBean(new ScheduledExecutorScheduler());
// HTTP Configuration
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(8443);
http_config.setOutputBufferSize(32768);
http_config.setRequestHeaderSize(8192);
http_config.setResponseHeaderSize(8192);
http_config.setSendServerVersion(true);
http_config.setSendDateHeader(false);
// httpConfig.addCustomizer(new ForwardedRequestCustomizer());
// Handler Structure
HandlerCollection handlers = new HandlerCollection();
ContextHandlerCollection contexts = new ContextHandlerCollection();
handlers.setHandlers(new Handler[] { contexts, new DefaultHandler() });
server.setHandler(handlers);
// Extra options
server.setDumpAfterStart(false);
server.setDumpBeforeStop(false);
server.setStopAtShutdown(true);
// === jetty-jmx.xml ===
MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
server.addBean(mbContainer);
// === jetty-http.xml ===
ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config));
http.setPort(8080);
http.setIdleTimeout(30000);
server.addConnector(http);
// === jetty-https.xml ===
// SSL Context Factory
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(jetty_home + "/../../../jetty-server/src/test/config/etc/keystore");
sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
sslContextFactory.setTrustStorePath(jetty_home + "/../../../jetty-server/src/test/config/etc/keystore");
sslContextFactory.setTrustStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
sslContextFactory.setExcludeCipherSuites("SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA", "SSL_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
// SSL HTTP Configuration
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
// SSL Connector
ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(https_config));
sslConnector.setPort(8443);
server.addConnector(sslConnector);
// === jetty-deploy.xml ===
DeploymentManager deployer = new DeploymentManager();
DebugListener debug = new DebugListener(System.err, true, true, true);
server.addBean(debug);
deployer.addLifeCycleBinding(new DebugListenerBinding(debug));
deployer.setContexts(contexts);
deployer.setContextAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/servlet-api-[^/]*\\.jar$");
WebAppProvider webapp_provider = new WebAppProvider();
webapp_provider.setMonitoredDirName(jetty_base + "/webapps");
webapp_provider.setDefaultsDescriptor(jetty_home + "/etc/webdefault.xml");
webapp_provider.setScanInterval(1);
webapp_provider.setExtractWars(true);
webapp_provider.setConfigurationManager(new PropertiesConfigurationManager());
deployer.addAppProvider(webapp_provider);
server.addBean(deployer);
// === setup jetty plus ==
Configuration.ClassList.setServerDefault(server).addAfter("org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration");
// === jetty-stats.xml ===
StatisticsHandler stats = new StatisticsHandler();
stats.setHandler(server.getHandler());
server.setHandler(stats);
ServerConnectionStatistics.addToAllConnectors(server);
// === Rewrite Handler
RewriteHandler rewrite = new RewriteHandler();
rewrite.setHandler(server.getHandler());
server.setHandler(rewrite);
// === jetty-requestlog.xml ===
NCSARequestLog requestLog = new NCSARequestLog();
requestLog.setFilename(jetty_home + "/logs/yyyy_mm_dd.request.log");
requestLog.setFilenameDateFormat("yyyy_MM_dd");
requestLog.setRetainDays(90);
requestLog.setAppend(true);
requestLog.setExtended(true);
requestLog.setLogCookies(false);
requestLog.setLogTimeZone("GMT");
RequestLogHandler requestLogHandler = new RequestLogHandler();
requestLogHandler.setRequestLog(requestLog);
handlers.addHandler(requestLogHandler);
// === jetty-lowresources.xml ===
LowResourceMonitor lowResourcesMonitor = new LowResourceMonitor(server);
lowResourcesMonitor.setPeriod(1000);
lowResourcesMonitor.setLowResourcesIdleTimeout(200);
lowResourcesMonitor.setMonitorThreads(true);
lowResourcesMonitor.setMaxConnections(0);
lowResourcesMonitor.setMaxMemory(0);
lowResourcesMonitor.setMaxLowResourcesTime(5000);
server.addBean(lowResourcesMonitor);
// === test-realm.xml ===
HashLoginService login = new HashLoginService();
login.setName("Test Realm");
login.setConfig(jetty_base + "/etc/realm.properties");
login.setHotReload(false);
server.addBean(login);
// Start the server
server.start();
server.join();
}
use of org.eclipse.jetty.deploy.DeploymentManager in project jetty.project by eclipse.
the class ServerInstanceWrapper method init.
/* ------------------------------------------------------------ */
/**
* Must be called after the server is configured.
*
* It is assumed the server has already been configured with the ContextHandlerCollection structure.
*
*/
private void init() {
// Get the context handler
_ctxtCollection = (ContextHandlerCollection) _server.getChildHandlerByClass(ContextHandlerCollection.class);
if (_ctxtCollection == null)
throw new IllegalStateException("ERROR: No ContextHandlerCollection configured in Server");
List<String> providerClassNames = new ArrayList<String>();
// get a deployerManager and some providers
Collection<DeploymentManager> deployers = _server.getBeans(DeploymentManager.class);
if (deployers != null && !deployers.isEmpty()) {
_deploymentManager = deployers.iterator().next();
for (AppProvider provider : _deploymentManager.getAppProviders()) {
providerClassNames.add(provider.getClass().getName());
}
} else {
//add some kind of default
_deploymentManager = new DeploymentManager();
_deploymentManager.setContexts(_ctxtCollection);
_server.addBean(_deploymentManager);
}
_deploymentManager.setUseStandardBindings(false);
List<AppLifeCycle.Binding> deploymentLifeCycleBindings = new ArrayList<AppLifeCycle.Binding>();
deploymentLifeCycleBindings.add(new OSGiDeployer(this));
deploymentLifeCycleBindings.add(new StandardStarter());
deploymentLifeCycleBindings.add(new StandardStopper());
deploymentLifeCycleBindings.add(new OSGiUndeployer(this));
_deploymentManager.setLifeCycleBindings(deploymentLifeCycleBindings);
if (!providerClassNames.contains(BundleWebAppProvider.class.getName())) {
// create it on the fly with reasonable default values.
try {
BundleWebAppProvider webAppProvider = new BundleWebAppProvider(this);
_deploymentManager.addAppProvider(webAppProvider);
} catch (Exception e) {
LOG.warn(e);
}
}
if (!providerClassNames.contains(ServiceWebAppProvider.class.getName())) {
// create it on the fly with reasonable default values.
try {
ServiceWebAppProvider webAppProvider = new ServiceWebAppProvider(this);
_deploymentManager.addAppProvider(webAppProvider);
} catch (Exception e) {
LOG.warn(e);
}
}
if (!providerClassNames.contains(BundleContextProvider.class.getName())) {
try {
BundleContextProvider contextProvider = new BundleContextProvider(this);
_deploymentManager.addAppProvider(contextProvider);
} catch (Exception e) {
LOG.warn(e);
}
}
if (!providerClassNames.contains(ServiceContextProvider.class.getName())) {
try {
ServiceContextProvider contextProvider = new ServiceContextProvider(this);
_deploymentManager.addAppProvider(contextProvider);
} catch (Exception e) {
LOG.warn(e);
}
}
}
Aggregations