use of org.apache.catalina.core.StandardContext in project meecrowave by apache.
the class Meecrowave method deployWebapp.
public Meecrowave deployWebapp(final DeploymentMeta meta) {
if (contexts.containsKey(meta.context)) {
throw new IllegalArgumentException("Already deployed: '" + meta.context + "'");
}
// always nice to see the deployment with something else than internals
final String base = tomcat.getService().findConnectors().length > 0 ? (configuration.getActiveProtocol() + "://" + tomcat.getHost().getName() + ':' + configuration.getActivePort()) : "";
new LogFacade(Meecrowave.class.getName()).info("--------------- " + base + meta.context);
final OWBJarScanner scanner = new OWBJarScanner();
final StandardContext ctx = new StandardContext() {
@Override
public void setApplicationEventListeners(final Object[] listeners) {
if (listeners == null) {
super.setApplicationEventListeners(null);
return;
}
// if we don't -> no @RequestScoped in request listeners :(
for (int i = 1; i < listeners.length; i++) {
if (OWBAutoSetup.EagerBootListener.class.isInstance(listeners[i])) {
final Object first = listeners[0];
listeners[0] = listeners[i];
listeners[i] = first;
break;
}
}
// and finally let it go after our re-ordering
super.setApplicationEventListeners(listeners);
}
};
ctx.setPath(meta.context);
ctx.setName(meta.context);
ctx.setJarScanner(scanner);
ctx.setInstanceManager(new CDIInstanceManager());
ofNullable(meta.docBase).ifPresent(d -> {
try {
ctx.setDocBase(meta.docBase.getCanonicalPath());
} catch (final IOException e) {
ctx.setDocBase(meta.docBase.getAbsolutePath());
}
});
ofNullable(configuration.getTomcatFilter()).ifPresent(filter -> {
try {
scanner.setJarScanFilter(JarScanFilter.class.cast(Thread.currentThread().getContextClassLoader().loadClass(filter).newInstance()));
} catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
});
final AtomicReference<Runnable> releaseSCI = new AtomicReference<>();
final ServletContainerInitializer meecrowaveInitializer = (c, ctx1) -> {
ctx1.setAttribute("meecrowave.configuration", getConfiguration());
ctx1.setAttribute("meecrowave.instance", Meecrowave.this);
new OWBAutoSetup().onStartup(c, ctx1);
if (Cxfs.IS_PRESENT) {
new CxfCdiAutoSetup().onStartup(c, ctx1);
}
new TomcatAutoInitializer().onStartup(c, ctx1);
if (configuration.isInjectServletContainerInitializer()) {
final Field f;
try {
// now cdi is on, we can inject cdi beans in ServletContainerInitializer
f = StandardContext.class.getDeclaredField("initializers");
if (!f.isAccessible()) {
f.setAccessible(true);
}
} catch (final Exception e) {
throw new IllegalStateException("Bad tomcat version", e);
}
final List<AutoCloseable> cc;
try {
cc = ((Map<ServletContainerInitializer, Set<Class<?>>>) f.get(ctx)).keySet().stream().filter(i -> !i.getClass().getName().startsWith(Meecrowave.class.getName())).map(i -> {
try {
return this.inject(i);
} catch (final IllegalArgumentException iae) {
return null;
}
}).filter(Objects::nonNull).collect(toList());
} catch (final IllegalAccessException e) {
throw new IllegalStateException("Can't read initializers", e);
}
releaseSCI.set(() -> cc.forEach(closeable -> {
try {
closeable.close();
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}));
}
};
ctx.addLifecycleListener(new MeecrowaveContextConfig(configuration, meta.docBase != null, meecrowaveInitializer, meta.redeployCallback));
ctx.addLifecycleListener(event -> {
switch(event.getType()) {
case Lifecycle.BEFORE_START_EVENT:
if (configuration.getWebSessionCookieConfig() != null) {
final Properties p = new Properties();
try {
p.load(new StringReader(configuration.getWebSessionCookieConfig()));
} catch (final IOException e) {
throw new IllegalArgumentException(e);
}
if (p.containsKey("domain")) {
ctx.setSessionCookieDomain(p.getProperty("domain"));
}
if (p.containsKey("path")) {
ctx.setSessionCookiePath(p.getProperty("path"));
}
if (p.containsKey("name")) {
ctx.setSessionCookieName(p.getProperty("name"));
}
if (p.containsKey("use-trailing-slash")) {
ctx.setSessionCookiePathUsesTrailingSlash(Boolean.parseBoolean(p.getProperty("use-trailing-slash")));
}
if (p.containsKey("http-only")) {
ctx.setUseHttpOnly(Boolean.parseBoolean(p.getProperty("http-only")));
}
if (p.containsKey("secured")) {
final SessionCookieConfig sessionCookieConfig = ctx.getServletContext().getSessionCookieConfig();
sessionCookieConfig.setSecure(Boolean.parseBoolean(p.getProperty("secured")));
}
}
break;
case Lifecycle.AFTER_START_EVENT:
ctx.getResources().setCachingAllowed(configuration.isWebResourceCached());
break;
case Lifecycle.BEFORE_INIT_EVENT:
if (configuration.getLoginConfig() != null) {
ctx.setLoginConfig(configuration.getLoginConfig().build());
}
for (final SecurityConstaintBuilder sc : configuration.getSecurityConstraints()) {
ctx.addConstraint(sc.build());
}
if (configuration.getWebXml() != null) {
ctx.getServletContext().setAttribute(Globals.ALT_DD_ATTR, configuration.getWebXml());
}
break;
default:
}
});
// after having configured the security!!!
ctx.addLifecycleListener(new Tomcat.FixContextListener());
ctx.addServletContainerInitializer(meecrowaveInitializer, emptySet());
if (configuration.isUseTomcatDefaults()) {
ctx.setSessionTimeout(configuration.getWebSessionTimeout() != null ? configuration.getWebSessionTimeout() : 30);
ctx.addWelcomeFile("index.html");
ctx.addWelcomeFile("index.htm");
Tomcat.addDefaultMimeTypeMappings(ctx);
} else if (configuration.getWebSessionTimeout() != null) {
ctx.setSessionTimeout(configuration.getWebSessionTimeout());
}
ofNullable(meta.consumer).ifPresent(c -> c.accept(ctx));
if (configuration.isQuickSession() && ctx.getManager() == null) {
final StandardManager manager = new StandardManager();
manager.setSessionIdGenerator(new StandardSessionIdGenerator() {
@Override
protected void getRandomBytes(final byte[] bytes) {
ThreadLocalRandom.current().nextBytes(bytes);
}
@Override
public String toString() {
return "MeecrowaveSessionIdGenerator@" + System.identityHashCode(this);
}
});
ctx.setManager(manager);
}
if (configuration.isAntiResourceLocking() && StandardContext.class.isInstance(ctx)) {
StandardContext.class.cast(ctx).setAntiResourceLocking(true);
}
configuration.getInitializers().forEach(i -> ctx.addServletContainerInitializer(i, emptySet()));
configuration.getGlobalContextConfigurers().forEach(it -> it.accept(ctx));
final Host host = tomcat.getHost();
host.addChild(ctx);
final ClassLoader classLoader = ctx.getLoader().getClassLoader();
if (host.getState().isAvailable()) {
fire(new StartListening(findFirstConnector(), host, ctx), classLoader);
}
contexts.put(meta.context, () -> {
if (host.getState().isAvailable()) {
fire(new StopListening(findFirstConnector(), host, ctx), classLoader);
}
ofNullable(releaseSCI.get()).ifPresent(Runnable::run);
tomcat.getHost().removeChild(ctx);
});
return this;
}
use of org.apache.catalina.core.StandardContext in project sonarqube by SonarSource.
the class TomcatContextsTest method configure_root_webapp.
@Test
public void configure_root_webapp() {
props.setProperty("foo", "bar");
StandardContext context = mock(StandardContext.class);
when(tomcat.addWebapp(anyString(), anyString())).thenReturn(context);
underTest.configure(tomcat, new Props(props));
// configure webapp with properties
verify(context).addParameter("foo", "bar");
}
use of org.apache.catalina.core.StandardContext in project leopard by tanhaichao.
the class TomcatServer method start.
public static void start() throws Exception {
Tomcat tomcat = new Tomcat();
tomcat.setHostname("localhost");
tomcat.setPort(80);
// tomcat.setBaseDir("D:\\work\\zhongcao\\zhongcao\\zhongcao-web");
// tomcat.addWebapp("WebRoot", "D:\\work\\zhongcao\\zhongcao\\zhongcao-web\\target\\zhongcao-web");
StandardContext ctx = (StandardContext) tomcat.addWebapp("/", "D:\\work\\zhongcao\\zhongcao\\zhongcao-web\\target\\zhongcao-web");
StandardRoot resources = new StandardRoot(ctx);
resources.setCachingAllowed(false);
ctx.setResources(resources);
tomcat.start();
}
use of org.apache.catalina.core.StandardContext in project sofa-ark by alipay.
the class ArkTomcatServletWebServerFactory method prepareContext.
@Override
protected void prepareContext(Host host, ServletContextInitializer[] initializers) {
if (host.getState() == LifecycleState.NEW) {
super.prepareContext(host, initializers);
} else {
File documentRoot = getValidDocumentRoot();
StandardContext context = new StandardContext();
if (documentRoot != null) {
context.setResources(new StandardRoot(context));
}
context.setName(getContextPath());
context.setDisplayName(getDisplayName());
context.setPath(getContextPath());
File docBase = (documentRoot != null) ? documentRoot : createTempDir("tomcat-docbase");
context.setDocBase(docBase.getAbsolutePath());
context.addLifecycleListener(new Tomcat.FixContextListener());
context.setParentClassLoader(Thread.currentThread().getContextClassLoader());
resetDefaultLocaleMapping(context);
addLocaleMappings(context);
context.setUseRelativeRedirects(false);
configureTldSkipPatterns(context);
WebappLoader loader = new WebappLoader(context.getParentClassLoader());
loader.setLoaderClass("com.alipay.sofa.ark.web.embed.tomcat.ArkTomcatEmbeddedWebappClassLoader");
loader.setDelegate(true);
context.setLoader(loader);
if (isRegisterDefaultServlet()) {
addDefaultServlet(context);
}
if (shouldRegisterJspServlet()) {
addJspServlet(context);
addJasperInitializer(context);
}
context.addLifecycleListener(new StaticResourceConfigurer(context));
ServletContextInitializer[] initializersToUse = mergeInitializers(initializers);
context.setParent(host);
configureContext(context, initializersToUse);
host.addChild(context);
}
}
use of org.apache.catalina.core.StandardContext in project ranger by apache.
the class EmbeddedServer method start.
public void start() {
SSLContext sslContext = getSSLContext();
if (sslContext != null) {
SSLContext.setDefault(sslContext);
}
final Tomcat server = new Tomcat();
String logDir = null;
logDir = EmbeddedServerUtil.getConfig("logdir");
if (logDir == null) {
logDir = EmbeddedServerUtil.getConfig("kms.log.dir");
}
String servername = EmbeddedServerUtil.getConfig("servername");
String hostName = EmbeddedServerUtil.getConfig("ranger.service.host");
int serverPort = EmbeddedServerUtil.getIntConfig("ranger.service.http.port", 6181);
int sslPort = EmbeddedServerUtil.getIntConfig("ranger.service.https.port", -1);
int shutdownPort = EmbeddedServerUtil.getIntConfig("ranger.service.shutdown.port", DEFAULT_SHUTDOWN_PORT);
String shutdownCommand = EmbeddedServerUtil.getConfig("ranger.service.shutdown.command", DEFAULT_SHUTDOWN_COMMAND);
server.setHostname(hostName);
server.setPort(serverPort);
server.getServer().setPort(shutdownPort);
server.getServer().setShutdown(shutdownCommand);
boolean isHttpsEnabled = Boolean.valueOf(EmbeddedServerUtil.getConfig("ranger.service.https.attrib.ssl.enabled", "false"));
boolean ajpEnabled = Boolean.valueOf(EmbeddedServerUtil.getConfig("ajp.enabled", "false"));
if (ajpEnabled) {
Connector ajpConnector = new Connector("org.apache.coyote.ajp.AjpNioProtocol");
ajpConnector.setPort(serverPort);
ajpConnector.setProperty("protocol", "AJP/1.3");
server.getService().addConnector(ajpConnector);
// Making this as a default connector
server.setConnector(ajpConnector);
LOG.info("Created AJP Connector");
} else if ((sslPort > 0) && isHttpsEnabled) {
Connector ssl = new Connector();
ssl.setPort(sslPort);
ssl.setSecure(true);
ssl.setScheme("https");
ssl.setAttribute("SSLEnabled", "true");
ssl.setAttribute("sslProtocol", EmbeddedServerUtil.getConfig("ranger.service.https.attrib.ssl.protocol", "TLSv1.2"));
ssl.setAttribute("keystoreType", EmbeddedServerUtil.getConfig("ranger.keystore.file.type", RANGER_KEYSTORE_FILE_TYPE_DEFAULT));
ssl.setAttribute("truststoreType", EmbeddedServerUtil.getConfig("ranger.truststore.file.type", RANGER_TRUSTSTORE_FILE_TYPE_DEFAULT));
String clientAuth = EmbeddedServerUtil.getConfig("ranger.service.https.attrib.clientAuth", "false");
if ("false".equalsIgnoreCase(clientAuth)) {
clientAuth = EmbeddedServerUtil.getConfig("ranger.service.https.attrib.client.auth", "want");
}
ssl.setAttribute("clientAuth", clientAuth);
String providerPath = EmbeddedServerUtil.getConfig("ranger.credential.provider.path");
String keyAlias = EmbeddedServerUtil.getConfig("ranger.service.https.attrib.keystore.credential.alias", "keyStoreCredentialAlias");
String keystorePass = null;
if (providerPath != null && keyAlias != null) {
keystorePass = CredentialReader.getDecryptedString(providerPath.trim(), keyAlias.trim(), EmbeddedServerUtil.getConfig("ranger.keystore.file.type", RANGER_KEYSTORE_FILE_TYPE_DEFAULT));
if (StringUtils.isBlank(keystorePass) || "none".equalsIgnoreCase(keystorePass.trim())) {
keystorePass = EmbeddedServerUtil.getConfig("ranger.service.https.attrib.keystore.pass");
}
}
ssl.setAttribute("keyAlias", EmbeddedServerUtil.getConfig("ranger.service.https.attrib.keystore.keyalias", "rangeradmin"));
ssl.setAttribute("keystorePass", keystorePass);
ssl.setAttribute("keystoreFile", getKeystoreFile());
String defaultEnabledProtocols = "TLSv1.2";
String enabledProtocols = EmbeddedServerUtil.getConfig("ranger.service.https.attrib.ssl.enabled.protocols", defaultEnabledProtocols);
ssl.setAttribute("sslEnabledProtocols", enabledProtocols);
String ciphers = EmbeddedServerUtil.getConfig("ranger.tomcat.ciphers");
if (StringUtils.isNotBlank(ciphers)) {
ssl.setAttribute("ciphers", ciphers);
}
server.getService().addConnector(ssl);
//
// Making this as a default connector
//
server.setConnector(ssl);
}
updateHttpConnectorAttribConfig(server);
File logDirectory = new File(logDir);
if (!logDirectory.exists()) {
logDirectory.mkdirs();
}
AccessLogValve valve = new AccessLogValve();
valve.setRotatable(true);
valve.setAsyncSupported(true);
valve.setBuffered(false);
valve.setEnabled(true);
valve.setPrefix(EmbeddedServerUtil.getConfig(ACCESS_LOG_PREFIX, "access-" + hostName));
valve.setFileDateFormat(EmbeddedServerUtil.getConfig(ACCESS_LOG_DATE_FORMAT, "-yyyy-MM-dd.HH"));
valve.setDirectory(logDirectory.getAbsolutePath());
valve.setSuffix(".log");
valve.setRotatable(EmbeddedServerUtil.getBooleanConfig(ACCESS_LOG_ROTATE_ENABLED, true));
valve.setMaxDays(EmbeddedServerUtil.getIntConfig(ACCESS_LOG_ROTATE_MAX_DAYS, 15));
valve.setRenameOnRotate(EmbeddedServerUtil.getBooleanConfig(ACCESS_LOG_ROTATE_RENAME_ON_ROTATE, false));
String defaultAccessLogPattern = servername.equalsIgnoreCase(KMS_SERVER_NAME) ? "%h %l %u %t \"%m %U\" %s %b %D" : "%h %l %u %t \"%r\" %s %b %D";
String logPattern = EmbeddedServerUtil.getConfig(ACCESS_LOG_PATTERN, defaultAccessLogPattern);
valve.setPattern(logPattern);
server.getHost().getPipeline().addValve(valve);
ErrorReportValve errorReportValve = new ErrorReportValve();
boolean showServerinfo = Boolean.valueOf(EmbeddedServerUtil.getConfig("ranger.valve.errorreportvalve.showserverinfo", "true"));
boolean showReport = Boolean.valueOf(EmbeddedServerUtil.getConfig("ranger.valve.errorreportvalve.showreport", "true"));
errorReportValve.setShowServerInfo(showServerinfo);
errorReportValve.setShowReport(showReport);
server.getHost().getPipeline().addValve(errorReportValve);
try {
String webapp_dir = EmbeddedServerUtil.getConfig("xa.webapp.dir");
if (StringUtils.isBlank(webapp_dir)) {
// If webapp location property is not set, then let's derive
// from catalina_base
String catalina_base = EmbeddedServerUtil.getConfig("catalina.base");
if (StringUtils.isBlank(catalina_base)) {
LOG.severe("Tomcat Server failed to start: catalina.base and/or xa.webapp.dir is not set");
System.exit(1);
}
webapp_dir = catalina_base + File.separator + "webapp";
LOG.info("Deriving webapp folder from catalina.base property. folder=" + webapp_dir);
}
// String webContextName = getConfig("xa.webapp.contextName", "/");
String webContextName = EmbeddedServerUtil.getConfig("ranger.contextName", "/");
if (webContextName == null) {
webContextName = "/";
} else if (!webContextName.startsWith("/")) {
LOG.info("Context Name [" + webContextName + "] is being loaded as [ /" + webContextName + "]");
webContextName = "/" + webContextName;
}
File wad = new File(webapp_dir);
if (wad.isDirectory()) {
LOG.info("Webapp file =" + webapp_dir + ", webAppName = " + webContextName);
} else if (wad.isFile()) {
File webAppDir = new File(DEFAULT_WEBAPPS_ROOT_FOLDER);
if (!webAppDir.exists()) {
webAppDir.mkdirs();
}
LOG.info("Webapp file =" + webapp_dir + ", webAppName = " + webContextName);
}
LOG.info("Adding webapp [" + webContextName + "] = path [" + webapp_dir + "] .....");
StandardContext webappCtx = (StandardContext) server.addWebapp(webContextName, new File(webapp_dir).getAbsolutePath());
String workDirPath = EmbeddedServerUtil.getConfig("ranger.tomcat.work.dir", "");
if (!workDirPath.isEmpty() && new File(workDirPath).exists()) {
webappCtx.setWorkDir(workDirPath);
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Skipping to set tomcat server work directory, '" + workDirPath + "', as it is blank or directory does not exist.");
}
}
webappCtx.init();
LOG.info("Finished init of webapp [" + webContextName + "] = path [" + webapp_dir + "].");
} catch (LifecycleException lce) {
LOG.severe("Tomcat Server failed to start webapp:" + lce.toString());
lce.printStackTrace();
}
if (servername.equalsIgnoreCase(ADMIN_SERVER_NAME)) {
String keytab = EmbeddedServerUtil.getConfig(ADMIN_USER_KEYTAB);
String principal = null;
try {
principal = SecureClientLogin.getPrincipal(EmbeddedServerUtil.getConfig(ADMIN_USER_PRINCIPAL), hostName);
} catch (IOException ignored) {
LOG.warning("Failed to get ranger.admin.kerberos.principal. Reason: " + ignored.toString());
}
String nameRules = EmbeddedServerUtil.getConfig(ADMIN_NAME_RULES);
if (StringUtils.isBlank(nameRules)) {
LOG.info("Name is empty. Setting Name Rule as 'DEFAULT'");
nameRules = DEFAULT_NAME_RULE;
}
if (EmbeddedServerUtil.getConfig(AUTHENTICATION_TYPE) != null && EmbeddedServerUtil.getConfig(AUTHENTICATION_TYPE).trim().equalsIgnoreCase(AUTH_TYPE_KERBEROS) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)) {
try {
LOG.info("Provided Kerberos Credential : Principal = " + principal + " and Keytab = " + keytab);
Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules);
Subject.doAs(sub, new PrivilegedAction<Void>() {
@Override
public Void run() {
LOG.info("Starting Server using kerberos credential");
startServer(server);
return null;
}
});
} catch (Exception e) {
LOG.severe("Tomcat Server failed to start:" + e.toString());
e.printStackTrace();
}
} else {
startServer(server);
}
} else {
startServer(server);
}
}
Aggregations