public void visitContainerInitializer( WebAppContext context, ContainerInitializer containerInitializer) { if (containerInitializer == null) return; // add the ContainerInitializer to the list of container initializers List<ContainerInitializer> containerInitializers = (List<ContainerInitializer>) context.getAttribute(AnnotationConfiguration.CONTAINER_INITIALIZERS); if (containerInitializers == null) { containerInitializers = new ArrayList<ContainerInitializer>(); context.setAttribute(AnnotationConfiguration.CONTAINER_INITIALIZERS, containerInitializers); } containerInitializers.add(containerInitializer); // Ensure a bean is set up on the context that will invoke the ContainerInitializers as the // context starts ServletContainerInitializersStarter starter = (ServletContainerInitializersStarter) context.getAttribute(AnnotationConfiguration.CONTAINER_INITIALIZER_STARTER); if (starter == null) { starter = new ServletContainerInitializersStarter(context); context.setAttribute(AnnotationConfiguration.CONTAINER_INITIALIZER_STARTER, starter); context.addBean(starter, true); } }
/** * @param context * @param scis * @throws Exception */ public void createServletContainerInitializerAnnotationHandlers( WebAppContext context, List<ServletContainerInitializer> scis) throws Exception { if (scis == null || scis.isEmpty()) return; // nothing to do List<ContainerInitializer> initializers = new ArrayList<ContainerInitializer>(); context.setAttribute(CONTAINER_INITIALIZERS, initializers); for (ServletContainerInitializer service : scis) { HandlesTypes annotation = service.getClass().getAnnotation(HandlesTypes.class); ContainerInitializer initializer = null; if (annotation != null) { // There is a HandlesTypes annotation on the on the ServletContainerInitializer Class<?>[] classes = annotation.value(); if (classes != null) { initializer = new ContainerInitializer(service, classes); // If we haven't already done so, we need to register a handler that will // process the whole class hierarchy to satisfy the ServletContainerInitializer if (context.getAttribute(CLASS_INHERITANCE_MAP) == null) { // MultiMap<String> map = new MultiMap<>(); ConcurrentHashMap<String, ConcurrentHashSet<String>> map = new ClassInheritanceMap(); context.setAttribute(CLASS_INHERITANCE_MAP, map); _classInheritanceHandler = new ClassInheritanceHandler(map); } for (Class<?> c : classes) { // The value of one of the HandlesTypes classes is actually an Annotation itself so // register a handler for it if (c.isAnnotation()) { if (LOG.isDebugEnabled()) LOG.debug("Registering annotation handler for " + c.getName()); _containerInitializerAnnotationHandlers.add( new ContainerInitializerAnnotationHandler(initializer, c)); } } } else { initializer = new ContainerInitializer(service, null); if (LOG.isDebugEnabled()) LOG.debug("No classes in HandlesTypes on initializer " + service.getClass()); } } else { initializer = new ContainerInitializer(service, null); if (LOG.isDebugEnabled()) LOG.debug("No annotation on initializer " + service.getClass()); } initializers.add(initializer); } // add a bean to the context which will call the servletcontainerinitializers when appropriate ServletContainerInitializersStarter starter = (ServletContainerInitializersStarter) context.getAttribute(CONTAINER_INITIALIZER_STARTER); if (starter != null) throw new IllegalStateException("ServletContainerInitializersStarter already exists"); starter = new ServletContainerInitializersStarter(context); context.setAttribute(CONTAINER_INITIALIZER_STARTER, starter); context.addBean(starter, true); }
/** 设置除jstl-*.jar外其他含tld文件的jar包的名称. jar名称不需要版本号,如sitemesh, shiro-web */ public static void setTldJarNames(Server server, String... jarNames) { WebAppContext context = (WebAppContext) server.getHandler(); List<String> jarNameExprssions = Lists.newArrayList(".*/jstl-[^/]*\\.jar$", ".*/.*taglibs[^/]*\\.jar$"); for (String jarName : jarNames) { jarNameExprssions.add(".*/" + jarName + "-[^/]*\\.jar$"); } context.setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", StringUtils.join(jarNameExprssions, '|')); }
public void start(int port) throws Exception { LOG.warn("Port used: " + port + " location " + WEBAPP_LOCATION + " " + databaseInfo.toString()); server = new Server(port); WebAppContext root = new WebAppContext(); root.setContextPath("/"); root.setDescriptor(WEBAPP_LOCATION + "/WEB-INF/web.xml"); root.setResourceBase(WEBAPP_LOCATION); root.setParentLoaderPriority(true); root.setAttribute(ConsoleFilter.DATABASE_ATTRIBUTE, databaseInfo); setupRequestLimits(root, REQUEST_TIME_LIMIT, MAX_OPS_LIMIT); server.setHandler(root); server.start(); }
public void visitMetaInfResource(WebAppContext context, Resource dir) { Collection<Resource> metaInfResources = (Collection<Resource>) context.getAttribute(MetaInfConfiguration.METAINF_RESOURCES); if (metaInfResources == null) { metaInfResources = new HashSet<Resource>(); context.setAttribute(MetaInfConfiguration.METAINF_RESOURCES, metaInfResources); } metaInfResources.add(dir); // also add to base resource of webapp Resource[] collection = new Resource[metaInfResources.size() + 1]; int i = 0; collection[i++] = context.getBaseResource(); for (Resource resource : metaInfResources) collection[i++] = resource; context.setBaseResource(new ResourceCollection(collection)); }
public static final void main(String args[]) throws Exception { // Create the server Server server = new Server(8080); // Enable parsing of jndi-related parts of web.xml and jetty-env.xml org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList.setServerDefault(server); classlist.addAfter( "org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration"); classlist.addBefore( "org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration"); // Create a WebApp WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/"); webapp.setWar( "../../tests/test-webapps/test-servlet-spec/test-spec-webapp/target/test-spec-webapp-9.1.0-SNAPSHOT.war"); webapp.setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/javax.servlet-[^/]*\\.jar$|.*/servlet-api-[^/]*\\.jar$"); server.setHandler(webapp); // Register new transaction manager in JNDI // At runtime, the webapp accesses this as java:comp/UserTransaction org.eclipse.jetty.plus.jndi.Transaction transactionMgr = new org.eclipse.jetty.plus.jndi.Transaction(new com.acme.MockUserTransaction()); // Define an env entry with webapp scope. org.eclipse.jetty.plus.jndi.EnvEntry maxAmount = new org.eclipse.jetty.plus.jndi.EnvEntry(webapp, "maxAmount", new Double(100), true); // Register a mock DataSource scoped to the webapp org.eclipse.jetty.plus.jndi.Resource mydatasource = new org.eclipse.jetty.plus.jndi.Resource( webapp, "jdbc/mydatasource", new com.acme.MockDataSource()); // Configure a LoginService HashLoginService loginService = new HashLoginService(); loginService.setName("Test Realm"); loginService.setConfig("src/test/resources/realm.properties"); server.addBean(loginService); server.start(); server.join(); }
public void start(int port) throws Exception { LOG.warn("Port used: " + port + " location " + WEBAPP_LOCATION + " " + databaseInfo.toString()); server = new Server(port); WebAppContext root = new WebAppContext(); root.setContextPath("/"); root.setDescriptor(WEBAPP_LOCATION + "/WEB-INF/web.xml"); root.setResourceBase(WEBAPP_LOCATION); root.setParentLoaderPriority(true); root.setAttribute(BackendFilter.DATABASE_ATTRIBUTE, databaseInfo); // setupRequestLimits(root, REQUEST_TIME_LIMIT, MAX_OPS_LIMIT); final HandlerList handlers = new HandlerList(); final Handler resourceHandler = createResourceHandler("/console_assets", WEBAPP_LOCATION); handlers.setHandlers(new Handler[] {resourceHandler, root}); server.setHandler(handlers); server.start(); }
@BeforeClass(groups = "Integration") public void setUp() throws Exception { WebAppContext context; // running in source mode; need to use special classpath context = new WebAppContext("src/test/webapp", "/"); context.setExtraClasspath("./target/test-rest-server/"); context.setAttribute( BrooklynServiceAttributes.BROOKLYN_MANAGEMENT_CONTEXT, getManagementContext()); Server server = BrooklynRestApiLauncher.launcher() .managementContext(manager) .customContext(context) .start(); api = new BrooklynApi("http://localhost:" + server.getConnectors()[0].getPort() + "/"); }
static WebAppContext newWebAppContext() throws MalformedURLException { final WebAppContext handler = new WebAppContext(); handler.setContextPath("/"); handler.setBaseResource(Resource.newClassPathResource("/tomcat_service")); handler.setClassLoader( new URLClassLoader( new URL[] { Resource.newClassPathResource("/tomcat_service/WEB-INF/lib/hello.jar") .getURI() .toURL() }, JettyService.class.getClassLoader())); handler.addBean(new ServletContainerInitializersStarter(handler), true); handler.setAttribute( "org.eclipse.jetty.containerInitializers", Collections.singletonList(new ContainerInitializer(new JettyJasperInitializer(), null))); return handler; }
public static void configureJetty(Server server, HandlerCollection collection) { Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server); classlist.addBefore( "org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration"); // Set the ContainerIncludeJarPattern so that jetty examines these // container-path jars for tlds, web-fragments etc. // If you omit the jar that contains the jstl .tlds, the jsp engine will // scan for them instead. for (Handler handler : collection.getHandlers()) { if (handler instanceof WebAppContext) { ((WebAppContext) handler) .setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$"); } } }
public void doHandle(Class clazz) { // Check that the PreDestroy is on a class that we're interested in if (Util.supportsPostConstructPreDestroy(clazz)) { Method[] methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Method m = (Method) methods[i]; if (m.isAnnotationPresent(PreDestroy.class)) { if (m.getParameterTypes().length != 0) throw new IllegalStateException(m + " has parameters"); if (m.getReturnType() != Void.TYPE) throw new IllegalStateException(m + " is not void"); if (m.getExceptionTypes().length != 0) throw new IllegalStateException(m + " throws checked exceptions"); if (Modifier.isStatic(m.getModifiers())) throw new IllegalStateException(m + " is static"); // ServletSpec 3.0 p80 If web.xml declares even one predestroy then all predestroys // in fragments must be ignored. Otherwise, they are additive. MetaData metaData = _context.getMetaData(); Origin origin = metaData.getOrigin("pre-destroy"); if (origin != null && (origin == Origin.WebXml || origin == Origin.WebDefaults || origin == Origin.WebOverride)) return; PreDestroyCallback callback = new PreDestroyCallback(); callback.setTarget(clazz.getName(), m.getName()); LifeCycleCallbackCollection lifecycles = (LifeCycleCallbackCollection) _context.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION); if (lifecycles == null) { lifecycles = new LifeCycleCallbackCollection(); _context.setAttribute( LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION, lifecycles); } lifecycles.add(callback); } } } }
/** Returns webapp handler which is able to handle war file */ private Handler getWebAppHandler(String warLocation, Server server) { WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/"); File warFile = new File(warLocation); if (!warFile.exists()) { throw new RuntimeException("Unable to find WAR File: " + warFile.getAbsolutePath()); } webapp.setWar(warFile.getAbsolutePath()); webapp.setExtractWAR(true); Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server); classlist.addBefore( "org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration"); webapp.setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$"); return webapp; }
protected WebAppContext newWebApp() { WebAppContext webApp = new WebAppContext(); webApp.setAttribute(OSGiWebappConstants.WATERMARK, OSGiWebappConstants.WATERMARK); // make sure we protect also the osgi dirs specified by OSGi Enterprise spec String[] targets = webApp.getProtectedTargets(); String[] updatedTargets = null; if (targets != null) { updatedTargets = new String[targets.length + OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length]; System.arraycopy(targets, 0, updatedTargets, 0, targets.length); } else updatedTargets = new String[OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length]; System.arraycopy( OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS, 0, updatedTargets, targets.length, OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length); webApp.setProtectedTargets(updatedTargets); return webApp; }
/** * Configure a jetty instance and deploy the webapps presented as args * * @param args the command line arguments * @throws Exception if unable to configure */ public void configure(String[] args) throws Exception { // handle classpath bits first so we can initialize the log mechanism. for (int i = 0; i < args.length; i++) { if ("--lib".equals(args[i])) { try (Resource lib = Resource.newResource(args[++i])) { if (!lib.exists() || !lib.isDirectory()) usage("No such lib directory " + lib); _classpath.addJars(lib); } } else if ("--jar".equals(args[i])) { try (Resource jar = Resource.newResource(args[++i])) { if (!jar.exists() || jar.isDirectory()) usage("No such jar " + jar); _classpath.addPath(jar); } } else if ("--classes".equals(args[i])) { try (Resource classes = Resource.newResource(args[++i])) { if (!classes.exists() || !classes.isDirectory()) usage("No such classes directory " + classes); _classpath.addPath(classes); } } else if (args[i].startsWith("--")) i++; } initClassLoader(); LOG.info("Runner"); LOG.debug("Runner classpath {}", _classpath); String contextPath = __defaultContextPath; boolean contextPathSet = false; int port = __defaultPort; String host = null; int stopPort = 0; String stopKey = null; boolean runnerServerInitialized = false; for (int i = 0; i < args.length; i++) { switch (args[i]) { case "--port": port = Integer.parseInt(args[++i]); break; case "--host": host = args[++i]; break; case "--stop-port": stopPort = Integer.parseInt(args[++i]); break; case "--stop-key": stopKey = args[++i]; break; case "--log": _logFile = args[++i]; break; case "--out": String outFile = args[++i]; PrintStream out = new PrintStream(new RolloverFileOutputStream(outFile, true, -1)); LOG.info("Redirecting stderr/stdout to " + outFile); System.setErr(out); System.setOut(out); break; case "--path": contextPath = args[++i]; contextPathSet = true; break; case "--config": if (_configFiles == null) _configFiles = new ArrayList<>(); _configFiles.add(args[++i]); break; case "--lib": ++i; // skip break; case "--jar": ++i; // skip break; case "--classes": ++i; // skip break; case "--stats": _enableStats = true; _statsPropFile = args[++i]; _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile); break; default: // process contexts if (!runnerServerInitialized) // log handlers not registered, server maybe not created, // etc { if (_server == null) // server not initialized yet { // build the server _server = new Server(); } // apply jetty config files if there are any if (_configFiles != null) { for (String cfg : _configFiles) { try (Resource resource = Resource.newResource(cfg)) { XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.getURL()); xmlConfiguration.configure(_server); } } } // check that everything got configured, and if not, make the handlers HandlerCollection handlers = (HandlerCollection) _server.getChildHandlerByClass(HandlerCollection.class); if (handlers == null) { handlers = new HandlerCollection(); _server.setHandler(handlers); } // check if contexts already configured _contexts = (ContextHandlerCollection) handlers.getChildHandlerByClass(ContextHandlerCollection.class); if (_contexts == null) { _contexts = new ContextHandlerCollection(); prependHandler(_contexts, handlers); } if (_enableStats) { // if no stats handler already configured if (handlers.getChildHandlerByClass(StatisticsHandler.class) == null) { StatisticsHandler statsHandler = new StatisticsHandler(); Handler oldHandler = _server.getHandler(); statsHandler.setHandler(oldHandler); _server.setHandler(statsHandler); ServletContextHandler statsContext = new ServletContextHandler(_contexts, "/stats"); statsContext.addServlet(new ServletHolder(new StatisticsServlet()), "/"); statsContext.setSessionHandler(new SessionHandler()); if (_statsPropFile != null) { HashLoginService loginService = new HashLoginService("StatsRealm", _statsPropFile); Constraint constraint = new Constraint(); constraint.setName("Admin Only"); constraint.setRoles(new String[] {"admin"}); constraint.setAuthenticate(true); ConstraintMapping cm = new ConstraintMapping(); cm.setConstraint(constraint); cm.setPathSpec("/*"); ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); securityHandler.setLoginService(loginService); securityHandler.setConstraintMappings(Collections.singletonList(cm)); securityHandler.setAuthenticator(new BasicAuthenticator()); statsContext.setSecurityHandler(securityHandler); } } } // ensure a DefaultHandler is present if (handlers.getChildHandlerByClass(DefaultHandler.class) == null) { handlers.addHandler(new DefaultHandler()); } // ensure a log handler is present _logHandler = (RequestLogHandler) handlers.getChildHandlerByClass(RequestLogHandler.class); if (_logHandler == null) { _logHandler = new RequestLogHandler(); handlers.addHandler(_logHandler); } // check a connector is configured to listen on Connector[] connectors = _server.getConnectors(); if (connectors == null || connectors.length == 0) { ServerConnector connector = new ServerConnector(_server); connector.setPort(port); if (host != null) connector.setHost(host); _server.addConnector(connector); if (_enableStats) connector.addBean(new ConnectorStatistics()); } else { if (_enableStats) { for (Connector connector : connectors) { ((AbstractConnector) connector).addBean(new ConnectorStatistics()); } } } runnerServerInitialized = true; } // Create a context try (Resource ctx = Resource.newResource(args[i])) { if (!ctx.exists()) usage("Context '" + ctx + "' does not exist"); if (contextPathSet && !(contextPath.startsWith("/"))) contextPath = "/" + contextPath; // Configure the context if (!ctx.isDirectory() && ctx.toString().toLowerCase().endsWith(".xml")) { // It is a context config file XmlConfiguration xmlConfiguration = new XmlConfiguration(ctx.getURL()); xmlConfiguration.getIdMap().put("Server", _server); ContextHandler handler = (ContextHandler) xmlConfiguration.configure(); if (contextPathSet) handler.setContextPath(contextPath); _contexts.addHandler(handler); handler.setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", __containerIncludeJarPattern); } else { // assume it is a WAR file WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath); webapp.setConfigurationClasses(__plusConfigurationClasses); webapp.setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", __containerIncludeJarPattern); } } // reset contextPathSet = false; contextPath = __defaultContextPath; break; } } if (_server == null) usage("No Contexts defined"); _server.setStopAtShutdown(true); switch ((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) { case 1: usage("Must specify --stop-key when --stop-port is specified"); break; case 2: usage("Must specify --stop-port when --stop-key is specified"); break; case 3: ShutdownMonitor monitor = ShutdownMonitor.getInstance(); monitor.setPort(stopPort); monitor.setKey(stopKey); monitor.setExitVm(true); break; } if (_logFile != null) { NCSARequestLog requestLog = new NCSARequestLog(_logFile); requestLog.setExtended(false); _logHandler.setRequestLog(requestLog); } }
public void configureWebApp() throws Exception { // TODO turn this around and let any context.xml file get applied first, and have the // properties override _webApp.setContextPath(_contextPath); // osgi Enterprise Spec r4 p.427 _webApp.setAttribute(OSGiWebappConstants.OSGI_BUNDLECONTEXT, _bundle.getBundleContext()); String overrideBundleInstallLocation = (String) _properties.get(OSGiWebappConstants.JETTY_BUNDLE_INSTALL_LOCATION_OVERRIDE); File bundleInstallLocation = (overrideBundleInstallLocation == null ? BundleFileLocatorHelperFactory.getFactory() .getHelper() .getBundleInstallLocation(_bundle) : new File(overrideBundleInstallLocation)); URL url = null; Resource rootResource = Resource.newResource( BundleFileLocatorHelperFactory.getFactory() .getHelper() .getLocalURL(bundleInstallLocation.toURI().toURL())); // try and make sure the rootResource is useable - if its a jar then make it a jar file url if (rootResource.exists() && !rootResource.isDirectory() && !rootResource.toString().startsWith("jar:")) { Resource jarResource = JarResource.newJarResource(rootResource); if (jarResource.exists() && jarResource.isDirectory()) rootResource = jarResource; } // if the path wasn't set or it was ., then it is the root of the bundle's installed location if (_webAppPath == null || _webAppPath.length() == 0 || ".".equals(_webAppPath)) { url = bundleInstallLocation.toURI().toURL(); } else { // Get the location of the root of the webapp inside the installed bundle if (_webAppPath.startsWith("/") || _webAppPath.startsWith("file:")) { url = new File(_webAppPath).toURI().toURL(); } else if (bundleInstallLocation != null && bundleInstallLocation.isDirectory()) { url = new File(bundleInstallLocation, _webAppPath).toURI().toURL(); } else if (bundleInstallLocation != null) { Enumeration<URL> urls = BundleFileLocatorHelperFactory.getFactory() .getHelper() .findEntries(_bundle, _webAppPath); if (urls != null && urls.hasMoreElements()) url = urls.nextElement(); } } if (url == null) { throw new IllegalArgumentException( "Unable to locate " + _webAppPath + " in " + (bundleInstallLocation != null ? bundleInstallLocation.getAbsolutePath() : "unlocated bundle '" + _bundle.getSymbolicName() + "'")); } // Sets the location of the war file // converts bundleentry: protocol if necessary _webApp.setWar( BundleFileLocatorHelperFactory.getFactory().getHelper().getLocalURL(url).toString()); // Set up what has been configured on the provider _webApp.setParentLoaderPriority(isParentLoaderPriority()); _webApp.setExtractWAR(isExtract()); if (getConfigurationClasses() != null) _webApp.setConfigurationClasses(getConfigurationClasses()); else _webApp.setConfigurationClasses(__defaultConfigurations); if (getDefaultsDescriptor() != null) _webApp.setDefaultsDescriptor(getDefaultsDescriptor()); // Set up configuration from manifest headers // extra classpath String tmp = (String) _properties.get(OSGiWebappConstants.JETTY_EXTRA_CLASSPATH); if (tmp != null) _webApp.setExtraClasspath(tmp); // web.xml tmp = (String) _properties.get(OSGiWebappConstants.JETTY_WEB_XML_PATH); if (tmp != null && tmp.trim().length() != 0) { File webXml = getFile(tmp, bundleInstallLocation); if (webXml != null && webXml.exists()) _webApp.setDescriptor(webXml.getAbsolutePath()); } // webdefault.xml tmp = (String) _properties.get(OSGiWebappConstants.JETTY_DEFAULT_WEB_XML_PATH); if (tmp != null) { File defaultWebXml = getFile(tmp, bundleInstallLocation); if (defaultWebXml != null) { if (defaultWebXml.exists()) _webApp.setDefaultsDescriptor(defaultWebXml.getAbsolutePath()); else LOG.warn(defaultWebXml.getAbsolutePath() + " does not exist"); } } // Handle Require-TldBundle // This is a comma separated list of names of bundles that contain tlds that this webapp uses. // We add them to the webapp classloader. String requireTldBundles = (String) _properties.get(OSGiWebappConstants.REQUIRE_TLD_BUNDLE); String pathsToTldBundles = getPathsToRequiredBundles(requireTldBundles); // make sure we provide access to all the jetty bundles by going // through this bundle. OSGiWebappClassLoader webAppLoader = new OSGiWebappClassLoader( _serverWrapper.getParentClassLoaderForWebapps(), _webApp, _bundle); if (pathsToTldBundles != null) webAppLoader.addClassPath(pathsToTldBundles); _webApp.setClassLoader(webAppLoader); // apply any META-INF/context.xml file that is found to configure // the webapp first applyMetaInfContextXml(rootResource); // pass the value of the require tld bundle so that the TagLibOSGiConfiguration // can pick it up. _webApp.setAttribute(OSGiWebappConstants.REQUIRE_TLD_BUNDLE, requireTldBundles); // Set up some attributes // rfc66 _webApp.setAttribute( OSGiWebappConstants.RFC66_OSGI_BUNDLE_CONTEXT, _bundle.getBundleContext()); // spring-dm-1.2.1 looks for the BundleContext as a different attribute. // not a spec... but if we want to support // org.springframework.osgi.web.context.support.OsgiBundleXmlWebApplicationContext // then we need to do this to: _webApp.setAttribute( "org.springframework.osgi.web." + BundleContext.class.getName(), _bundle.getBundleContext()); // also pass the bundle directly. sometimes a bundle does not have a // bundlecontext. // it is still useful to have access to the Bundle from the servlet // context. _webApp.setAttribute(OSGiWebappConstants.JETTY_OSGI_BUNDLE, _bundle); }
/** * @param context * @param descriptor * @param node */ public void visitContextParam(WebAppContext context, Descriptor descriptor, XmlParser.Node node) throws Exception { String name = node.getString("param-name", false, true); String value = node.getString("param-value", false, true); List<String> values = new ArrayList<>(); // extract values switch (name) { case ServletContext.ORDERED_LIBS: case AnnotationConfiguration.CONTAINER_INITIALIZERS: case MetaInfConfiguration.METAINF_TLDS: case MetaInfConfiguration.METAINF_RESOURCES: context.removeAttribute(name); QuotedStringTokenizer tok = new QuotedStringTokenizer(value, ","); while (tok.hasMoreElements()) values.add(tok.nextToken().trim()); break; default: values.add(value); } // handle values switch (name) { case ServletContext.ORDERED_LIBS: { List<Object> libs = new ArrayList<>(); Object o = context.getAttribute(ServletContext.ORDERED_LIBS); if (o instanceof Collection<?>) libs.addAll((Collection<?>) o); libs.addAll(values); if (libs.size() > 0) context.setAttribute(ServletContext.ORDERED_LIBS, libs); break; } case AnnotationConfiguration.CONTAINER_INITIALIZERS: { for (String i : values) visitContainerInitializer( context, new ContainerInitializer(Thread.currentThread().getContextClassLoader(), i)); break; } case MetaInfConfiguration.METAINF_TLDS: { List<Object> tlds = new ArrayList<>(); String war = context.getBaseResource().getURI().toString(); Object o = context.getAttribute(MetaInfConfiguration.METAINF_TLDS); if (o instanceof Collection<?>) tlds.addAll((Collection<?>) o); for (String i : values) { Resource r = Resource.newResource(i.replace("${WAR}/", war)); if (r.exists()) tlds.add(r.getURL()); else throw new IllegalArgumentException("TLD not found: " + r); } if (tlds.size() > 0) context.setAttribute(MetaInfConfiguration.METAINF_TLDS, tlds); break; } case MetaInfConfiguration.METAINF_RESOURCES: { String war = context.getBaseResource().getURI().toString(); for (String i : values) { Resource r = Resource.newResource(i.replace("${WAR}/", war)); if (r.exists()) visitMetaInfResource(context, r); else throw new IllegalArgumentException("Resource not found: " + r); } break; } default: } }
/* ------------------------------------------------------------ */ @Override public ContextHandler createContextHandler(final App app) throws Exception { Resource resource = Resource.newResource(app.getOriginId()); File file = resource.getFile(); if (!resource.exists()) throw new IllegalStateException("App resouce does not exist " + resource); String context = file.getName(); if (resource.exists() && FileID.isXmlFile(file)) { XmlConfiguration xmlc = new XmlConfiguration(resource.getURL()); xmlc.getIdMap().put("Server", getDeploymentManager().getServer()); if (getConfigurationManager() != null) xmlc.getProperties().putAll(getConfigurationManager().getProperties()); return (ContextHandler) xmlc.configure(); } else if (file.isDirectory()) { // must be a directory } else if (FileID.isWebArchiveFile(file)) { // Context Path is the same as the archive. context = context.substring(0, context.length() - 4); } else { throw new IllegalStateException("unable to create ContextHandler for " + app); } // Ensure "/" is Not Trailing in context paths. if (context.endsWith("/") && context.length() > 0) { context = context.substring(0, context.length() - 1); } // Start building the webapplication WebAppContext wah = new WebAppContext(); wah.setDisplayName(context); // special case of archive (or dir) named "root" is / context if (context.equalsIgnoreCase("root")) { context = URIUtil.SLASH; } else if (context.toLowerCase().startsWith("root-")) { int dash = context.toLowerCase().indexOf('-'); String virtual = context.substring(dash + 1); wah.setVirtualHosts(new String[] {virtual}); context = URIUtil.SLASH; } // Ensure "/" is Prepended to all context paths. if (context.charAt(0) != '/') { context = "/" + context; } wah.setContextPath(context); wah.setWar(file.getAbsolutePath()); if (_defaultsDescriptor != null) { wah.setDefaultsDescriptor(_defaultsDescriptor); } wah.setExtractWAR(_extractWars); wah.setParentLoaderPriority(_parentLoaderPriority); if (_configurationClasses != null) { wah.setConfigurationClasses(_configurationClasses); } if (_tempDirectory != null) { /* Since the Temp Dir is really a context base temp directory, * Lets set the Temp Directory in a way similar to how WebInfConfiguration does it, * instead of setting the * WebAppContext.setTempDirectory(File). * If we used .setTempDirectory(File) all webapps will wind up in the * same temp / work directory, overwriting each others work. */ wah.setAttribute(WebAppContext.BASETEMPDIR, _tempDirectory); } return wah; }
public void initializePlugin(PluginManager manager, File pluginDirectory) { Log.info("[" + NAME + "] initialize " + NAME + " plugin resources"); try { openfire = new Openfire(); openfire.start(); JmxHelper.register(openfire, OBJECTNAME_OPENFIRE); Log.info("[" + NAME + "] .. started openfire server detector."); } catch (Exception e) { Log.debug("cannot start openfire server detector: " + e.getMessage(), e); } try { packetCounter = new PacketCounter(); packetCounter.start(); JmxHelper.register(packetCounter, OBJECTNAME_PACKET_COUNTER); Log.info("[" + NAME + "] .. started stanza counter."); } catch (Exception e) { Log.debug("cannot start stanza counter: " + e.getMessage(), e); } try { client = new CoreThreadPool( ((ConnectionManagerImpl) XMPPServer.getInstance().getConnectionManager()) .getSocketAcceptor()); client.start(); JmxHelper.register(client, OBJECTNAME_CORE_CLIENT_THREADPOOL); Log.info("[" + NAME + "] .. started client thread pool monitor."); } catch (Exception e) { Log.debug("cannot start client thread pool monitor: " + e.getMessage(), e); } try { database = new DatabasePool(); database.start(); JmxHelper.register(database, OBJECTNAME_DATABASEPOOL); Log.info("[" + NAME + "] .. started database pool monitor."); } catch (Exception e) { Log.debug("cannot start database pool monitor: " + e.getMessage(), e); } try { ContextHandlerCollection contexts = HttpBindManager.getInstance().getContexts(); try { Log.info("[" + NAME + "] starting jolokia"); WebAppContext context = new WebAppContext(contexts, pluginDirectory.getPath(), "/jolokia"); final List<ContainerInitializer> initializers = new ArrayList<>(); initializers.add(new ContainerInitializer(new JasperInitializer(), null)); context.setAttribute("org.eclipse.jetty.containerInitializers", initializers); context.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager()); context.setWelcomeFiles(new String[] {"index.html"}); Log.info("[" + NAME + "] starting hawtio"); WebAppContext context2 = new WebAppContext(contexts, pluginDirectory.getPath() + "/hawtio", "/hawtio"); final List<ContainerInitializer> initializers2 = new ArrayList<>(); initializers2.add(new ContainerInitializer(new JasperInitializer(), null)); context2.setAttribute("org.eclipse.jetty.containerInitializers", initializers2); context2.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager()); context2.setWelcomeFiles(new String[] {"index.html"}); if (JiveGlobals.getBooleanProperty("xmpp.jmx.secure", true)) { SecurityHandler securityHandler = basicAuth("jmxweb"); if (securityHandler != null) context.setSecurityHandler(securityHandler); SecurityHandler securityHandler2 = basicAuth("jmxweb"); if (securityHandler2 != null) context2.setSecurityHandler(securityHandler2); } } catch (Exception e) { Log.error("An error has occurred", e); } } catch (Exception e) { Log.error("Error initializing JmxWeb Plugin", e); } if (JiveGlobals.getBooleanProperty("jmxweb.email.monitoring", true)) { Log.info("[" + NAME + "] starting email monitoring"); emailScheduler = new EmailScheduler(); emailScheduler.startMonitoring(); Log.info("[" + NAME + "] started monitoring"); } }