private void initServer() throws Exception { // point catalina at the provided home directory server = new Embedded(); server.setCatalinaHome(catalinaHome.getAbsolutePath()); Engine engine = server.createEngine(); engine.setName("embedded"); server.addEngine(engine); host = server.createHost("localhost", new File(catalinaHome, "webapps").getAbsolutePath()); engine.addChild(host); engine.setDefaultHost(host.getName()); // bind to an available port httpConnector = new EmbeddedConnector(); server.addConnector(httpConnector); // disable session persistence on restart sessions = new MemoryStore(); sessionManager = new PersistentManager(); sessionManager.setDistributable(false); sessionManager.setSaveOnRestart(false); sessionManager.setStore(sessions); Context root = server.createContext("", new File(catalinaHome, "conf").getAbsolutePath()); root.setManager(sessionManager); host.addChild(root); }
public File getAppBase() { File base = new File(host.getAppBase()); if (!base.isAbsolute()) { base = new File(System.getProperty("catalina.base"), host.getAppBase()); } return base; }
/** * Create an <code>ObjectName</code> for this <code>Manager</code> object. * * @param domain Domain in which this name is to be created * @param manager The Manager to be named * @exception MalformedObjectNameException if a name cannot be created */ static ObjectName createObjectName(String domain, Manager manager) throws MalformedObjectNameException { ObjectName name = null; Container container = manager.getContainer(); if (container instanceof Engine) { name = new ObjectName(domain + ":type=Manager"); } else if (container instanceof Host) { name = new ObjectName(domain + ":type=Manager,host=" + container.getName()); } else if (container instanceof Context) { String path = ((Context) container).getPath(); if (path.length() < 1) { path = "/"; } Host host = (Host) container.getParent(); name = new ObjectName(domain + ":type=Manager,path=" + path + ",host=" + host.getName()); } else if (container == null) { DefaultContext defaultContext = manager.getDefaultContext(); if (defaultContext != null) { Container parent = defaultContext.getParent(); if (parent instanceof Engine) { name = new ObjectName(domain + ":type=DefaultManager"); } else if (parent instanceof Host) { name = new ObjectName(domain + ":type=DefaultManager,host=" + parent.getName()); } } } return (name); }
@BeforeClass(alwaysRun = true) public void setUpGlobal() throws Exception { port1 = findFreePort(); embedded = new Embedded(); String path = new File(".").getAbsolutePath(); embedded.setCatalinaHome(path); Engine engine = embedded.createEngine(); engine.setDefaultHost("127.0.0.1"); Host host = embedded.createHost("127.0.0.1", path); engine.addChild(host); Context c = embedded.createContext("/", path); c.setReloadable(false); Wrapper w = c.createWrapper(); w.addMapping("/*"); w.setServletClass(org.apache.catalina.servlets.WebdavServlet.class.getName()); w.addInitParameter("readonly", "false"); w.addInitParameter("listings", "true"); w.setLoadOnStartup(0); c.addChild(w); host.addChild(c); Connector connector = embedded.createConnector("127.0.0.1", port1, Http11NioProtocol.class.getName()); connector.setContainer(host); embedded.addEngine(engine); embedded.addConnector(connector); embedded.start(); }
public void registerListenersForEngine(Engine engine) throws RemoteException, RemoteException { for (Container hostContainer : engine.findChildren()) { Host host = (Host) hostContainer; host.addContainerListener(this); registerListenersForHost(host); } }
/** * Creates a single webapp configuration to be run in Tomcat. * * @param contextName the context name without leading slash, for example, "openmrs" * @param port the port at which to run tomcat. */ public TomcatManager(String contextName, int port) { // create server container = new Embedded(); container.setCatalinaHome("tomcat"); // create context Context rootContext = container.createContext("/" + contextName, contextName); rootContext.setReloadable(true); // create host Host localHost = container.createHost("localhost", "webapps"); localHost.addChild(rootContext); // create engine Engine engine = container.createEngine(); engine.setName("Catalina"); engine.addChild(localHost); engine.setDefaultHost(localHost.getName()); container.addEngine(engine); // create http connector Connector httpConnector = container.createConnector((InetAddress) null, port, false); container.addConnector(httpConnector); }
/** * Doing the start, stop, reload and lazy unload of webapps inside all hosts respectively when * getting request. * * @param nameOfOperation the operation to be performed in oder to hot update the host * @throws CarbonException if errors occurs when hot update the host */ private void handleHotUpdateToHost(String nameOfOperation) throws CarbonException { if (DataHolder.getHotUpdateService() != null) { List<String> mappings = URLMappingHolder.getInstance().getUrlMappingsPerApplication(this.context.getName()); Engine engine = DataHolder.getCarbonTomcatService().getTomcat().getEngine(); Context hostContext; Host host; for (String hostName : mappings) { host = (Host) engine.findChild(hostName); if (host != null) { hostContext = (Context) host.findChild("/"); if (hostContext != null) { if (nameOfOperation.equalsIgnoreCase("start")) { start(hostContext); } else if (nameOfOperation.equalsIgnoreCase("stop")) { stop(hostContext); } else if (nameOfOperation.equalsIgnoreCase("reload")) { reload(hostContext); } else if (nameOfOperation.equalsIgnoreCase("lazyunload")) { lazyUnload(hostContext); DataHolder.getHotUpdateService().removeHost(hostName); } else if (nameOfOperation.equalsIgnoreCase("delete")) { DataHolder.getHotUpdateService().deleteHost(hostName); } } } } } }
/** * Create an <code>ObjectName</code> for this <code>ContextResource</code> object. * * @param domain Domain in which this name is to be created * @param resource The ContextResource to be named * @exception MalformedObjectNameException if a name cannot be created */ public static ObjectName createObjectName(String domain, ContextResource resource) throws MalformedObjectNameException { ObjectName name = null; String encodedResourceName = encodeStr(resource.getName()); Object container = resource.getNamingResources().getContainer(); if (container instanceof Server) { name = new ObjectName( domain + ":type=Resource" + ",resourcetype=Global,class=" + resource.getType() + ",name=" + encodedResourceName); } else if (container instanceof Context) { String path = ((Context) container).getPath(); if (path.length() < 1) path = "/"; Host host = (Host) ((Context) container).getParent(); name = new ObjectName( domain + ":type=Resource" + ",resourcetype=Context,path=" + path + ",host=" + host.getName() + ",class=" + resource.getType() + ",name=" + encodedResourceName); } else if (container instanceof DefaultContext) { container = ((DefaultContext) container).getParent(); if (container instanceof Host) { Host host = (Host) container; name = new ObjectName( domain + ":type=Resource" + ",resourcetype=HostDefaultContext,host=" + host.getName() + ",class=" + resource.getType() + ",name=" + encodedResourceName); } else if (container instanceof Engine) { name = new ObjectName( domain + ":type=Resource" + ",resourcetype=ServiceDefaultContext,class=" + resource.getType() + ",name=" + encodedResourceName); } } return (name); }
@Override public void start(StartContext startContext) throws StartException { ServerEnvironment env = injectedServerEnvironment.getValue(); Host virtualHost = injectedVirtualHost.getValue().getHost(); BundleContext syscontext = injectedSystemContext.getValue(); WebServer webServer = injectedWebServer.getValue(); File storageDir = new File( env.getServerTempDir() + File.separator + CONTEXT_NAME + File.separator + "httpservice-root"); context.setDocBase(storageDir.getPath()); storageDir.mkdirs(); context.setPath(CONTEXT_NAME); context.addLifecycleListener(new ContextConfig()); Loader loader = new WebCtxLoader(getClass().getClassLoader()); loader.setContainer(virtualHost); context.setLoader(loader); context.setInstanceManager(new LocalInstanceManager()); context.addMimeMapping("html", "text/html"); context.addMimeMapping("jpg", "image/jpeg"); context.addMimeMapping("png", "image/png"); context.addMimeMapping("gif", "image/gif"); context.addMimeMapping("css", "text/css"); context.addMimeMapping("js", "text/javascript"); virtualHost.addChild(context); WEB_LOGGER.registerWebapp(context.getName()); try { context.create(); } catch (Exception ex) { throw new StartException(WebMessages.MESSAGES.createContextFailed(), ex); } try { context.start(); } catch (LifecycleException ex) { throw new StartException(WebMessages.MESSAGES.startContextFailed(), ex); } Hashtable<String, Object> props = new Hashtable<String, Object>(); props.put(Constants.SERVICE_RANKING, Integer.MIN_VALUE); props.put("provider", getClass().getPackage().getName()); ServiceFactory serviceFactory = new HttpServiceFactory(webServer, virtualHost, context); registration = syscontext.registerService(HttpService.class.getName(), serviceFactory, props); }
/** * Create an <code>ObjectName</code> for this <code>Valve</code> object. * * @param domain Domain in which this name is to be created * @param valve The Valve to be named * @exception MalformedObjectNameException if a name cannot be created */ static ObjectName createObjectName(String domain, GlassFishValve valve) throws MalformedObjectNameException { if (valve instanceof ValveBase) { ObjectName name = ((ValveBase) valve).getObjectName(); if (name != null) return name; } ObjectName name = null; Container container = null; String className = valve.getClass().getName(); int period = className.lastIndexOf('.'); if (period >= 0) className = className.substring(period + 1); if (valve instanceof Contained) { container = ((Contained) valve).getContainer(); } if (container == null) { throw new MalformedObjectNameException( "Cannot create mbean for non-contained valve " + valve); } if (container instanceof Engine) { String local = ""; int seq = getSeq(local); String ext = ""; if (seq > 0) { ext = ",seq=" + seq; } name = new ObjectName(domain + ":type=Valve,name=" + className + ext + local); } else if (container instanceof Host) { String local = ",host=" + container.getName(); int seq = getSeq(local); String ext = ""; if (seq > 0) { ext = ",seq=" + seq; } name = new ObjectName(domain + ":type=Valve,name=" + className + ext + local); } else if (container instanceof Context) { String path = ((Context) container).getPath(); if (path.length() < 1) { path = "/"; } Host host = (Host) container.getParent(); String local = ",path=" + path + ",host=" + host.getName(); int seq = getSeq(local); String ext = ""; if (seq > 0) { ext = ",seq=" + seq; } name = new ObjectName(domain + ":type=Valve,name=" + className + ext + local); } return (name); }
public static void setupContainer(String warName, String jvmRoute, Manager mgr) { Engine engine = new MockEngine(); engine.setName(JVM_ROUTE_CACHE_NAME); engine.setJvmRoute(jvmRoute); Host host = new MockHost(); host.setName("localhost"); engine.addChild(host); StandardContext context = new StandardContext(); context.setName(warName); context.setDomain(jvmRoute); host.addChild(context); context.setManager(mgr); }
/** * Add a new child Host to our associated Engine. * * @param host Child host to add */ private void addHost(Host host) { if (debug >= 3) engine.log("Adding host '" + host.getName() + "'"); host.addContainerListener(this); // Register the host name addAlias(host.getName(), host); // Register all associated aliases String aliases[] = host.findAliases(); for (int i = 0; i < aliases.length; i++) addAlias(aliases[i], host); }
/** * Create an <code>ObjectName</code> for this <code>DefaultContext</code> object. * * @param domain Domain in which this name is to be created * @param context The DefaultContext to be named * @exception MalformedObjectNameException if a name cannot be created */ static ObjectName createObjectName(String domain, DefaultContext context) throws MalformedObjectNameException { ObjectName name = null; Container container = context.getParent(); if (container instanceof Host) { Host host = (Host) container; name = new ObjectName(domain + ":type=DefaultContext,host=" + host.getName()); } else if (container instanceof Engine) { name = new ObjectName(domain + ":type=DefaultContext"); } return (name); }
/** Process a "start" event for this Host. */ public void start() { if (log.isDebugEnabled()) log.debug(sm.getString("hostConfig.start")); try { ObjectName hostON = new ObjectName(host.getObjectName()); oname = new ObjectName(hostON.getDomain() + ":type=Deployer,host=" + host.getName()); Registry.getRegistry(null, null).registerComponent(this, oname, this.getClass().getName()); } catch (Exception e) { log.error(sm.getString("hostConfig.jmx.register", oname), e); } if (host.getDeployOnStartup()) deployApps(); }
/** Return a File object representing the "application root" directory for our associated Host. */ protected File appBase() { if (appBase != null) { return appBase; } File file = new File(host.getAppBase()); if (!file.isAbsolute()) file = new File(System.getProperty("catalina.base"), host.getAppBase()); try { appBase = file.getCanonicalFile(); } catch (IOException e) { appBase = file; } return (appBase); }
public void setWrapper(Wrapper wrapper) { if (wrapper != null) { host = (Host) wrapper.getParent().getParent(); try { deployerOName = new ObjectName(host.getParent().getName() + ":type=Deployer,host=" + host.getName()); } catch (MalformedObjectNameException e) { // do nothing here } host.getPipeline().addValve(valve); mBeanServer = Registry.getRegistry(null, null).getMBeanServer(); } else if (host != null) { host.getPipeline().removeValve(valve); } }
private static StandardContext startWebApp(Host host, WSEndpointDeploymentUnit unit) throws Exception { StandardContext context = new StandardContext(); try { JBossWebMetaData jbwebMD = unit.getAttachment(WSAttachmentKeys.JBOSSWEB_METADATA_KEY); context.setPath(jbwebMD.getContextRoot()); context.addLifecycleListener(new ContextConfig()); ServerConfigService config = (ServerConfigService) unit.getServiceRegistry().getService(WSServices.CONFIG_SERVICE).getService(); File docBase = new File(config.getValue().getServerTempDir(), jbwebMD.getContextRoot()); if (!docBase.exists()) { docBase.mkdirs(); } context.setDocBase(docBase.getPath()); final Loader loader = new WebCtxLoader(unit.getAttachment(WSAttachmentKeys.CLASSLOADER_KEY)); loader.setContainer(host); context.setLoader(loader); context.setInstanceManager(new LocalInstanceManager()); addServlets(jbwebMD, context); host.addChild(context); context.create(); } catch (Exception e) { throw MESSAGES.createContextPhaseFailed(e); } try { context.start(); } catch (LifecycleException e) { throw MESSAGES.startContextPhaseFailed(e); } return context; }
protected void prepareContext(Host host, ServletContextInitializer[] initializers) { File docBase = getValidDocumentRoot(); docBase = (docBase != null ? docBase : createTempDir("tomcat-docbase")); TomcatEmbeddedContext context = new TomcatEmbeddedContext(); context.setName(getContextPath()); context.setPath(getContextPath()); context.setDocBase(docBase.getAbsolutePath()); context.addLifecycleListener(new FixContextListener()); context.setParentClassLoader( this.resourceLoader != null ? this.resourceLoader.getClassLoader() : ClassUtils.getDefaultClassLoader()); SkipPatternJarScanner.apply(context, this.tldSkip); WebappLoader loader = new WebappLoader(context.getParentClassLoader()); loader.setLoaderClass(TomcatEmbeddedWebappClassLoader.class.getName()); loader.setDelegate(true); context.setLoader(loader); if (isRegisterDefaultServlet()) { addDefaultServlet(context); } if (isRegisterJspServlet() && ClassUtils.isPresent(getJspServletClassName(), getClass().getClassLoader())) { addJspServlet(context); addJasperInitializer(context); context.addLifecycleListener(new StoreMergedWebXmlListener()); } ServletContextInitializer[] initializersToUse = mergeInitializers(initializers); configureContext(context, initializersToUse); host.addChild(context); postProcessContext(context); }
public EmbeddedTomcat(String contextPath, int port, String jvmRoute) throws MalformedURLException { this.contextPath = contextPath; this.port = port; // create server container = new Embedded(); container.setCatalinaHome(catalinaHome); // Not really necessasry, but let's still do it... container.setRealm(new MemoryRealm()); // create webapp loader WebappLoader loader = new WebappLoader(this.getClass().getClassLoader()); if (classesDir != null) { loader.addRepository(new File(classesDir).toURI().toURL().toString()); } rootContext = container.createContext("", webappDir); rootContext.setLoader(loader); rootContext.setReloadable(true); // Otherwise we get NPE when instantiating servlets rootContext.setIgnoreAnnotations(true); // create host Host localHost = container.createHost("127.0.0.1", new File("").getAbsolutePath()); localHost.addChild(rootContext); localHost.setDeployOnStartup(true); // create engine engine = container.createEngine(); engine.setName("localEngine"); engine.addChild(localHost); engine.setDefaultHost(localHost.getName()); engine.setJvmRoute(jvmRoute); engine.setService(new StandardService()); container.addEngine(engine); // create http connector Connector httpConnector = container.createConnector((InetAddress) null, port, false); container.addConnector(httpConnector); container.setAwait(true); // Create the JVMRoute valve for session failover ValveBase valve = new JvmRouteBinderValve(); ((StandardEngine) engine).addValve(valve); }
public void deploy(String url, File dir) { if (host.findChild(url) != null) return; if (dir == null || !dir.exists() || !dir.isDirectory()) return; log.debug("deploy new context:" + url + ", dir:" + dir.getAbsolutePath()); this.host.addChild(this.embedded.createContext(url, dir.getAbsolutePath())); }
/** Undeploy all deployed applications. */ protected void undeployApps() { if (log.isDebugEnabled()) log.debug(sm.getString("hostConfig.undeploying")); // Soft undeploy all contexts we have deployed DeployedApplication[] apps = (DeployedApplication[]) deployed.values().toArray(new DeployedApplication[0]); for (int i = 0; i < apps.length; i++) { try { host.removeChild(host.findChild(apps[i].name)); } catch (Throwable t) { log.warn(sm.getString("hostConfig.context.remove", apps[i].name), t); } } deployed.clear(); }
/** * Create an <code>ObjectName</code> for this <code>Context</code> object. * * @param domain Domain in which this name is to be created * @param context The Context to be named * @exception MalformedObjectNameException if a name cannot be created */ static ObjectName createObjectName(String domain, Context context) throws MalformedObjectNameException { ObjectName name = null; Host host = (Host) context.getParent(); String path = context.getPath(); if (path.length() < 1) path = "/"; // FIXME name = new ObjectName( domain + ":j2eeType=WebModule,name=//" + host.getName() + path + ",J2EEApplication=none,J2EEServer=none"); return (name); }
public Host getHost() { if (host == null) { host = new StandardHost(); host.setName(hostname); getEngine().addChild(host); } return host; }
/** * Create an <code>ObjectName</code> for this <code>ContextResource</code> object. * * @param resource The resource * @return ObjectName The object name * @exception MalformedObjectNameException if a name cannot be created */ protected ObjectName createObjectName(ContextResource resource) throws MalformedObjectNameException { String domain = null; if (container instanceof StandardServer) { domain = ((StandardServer) container).getDomain(); } else if (container instanceof ContainerBase) { domain = ((ContainerBase) container).getDomain(); } if (domain == null) { domain = "Catalina"; } ObjectName name = null; String quotedResourceName = ObjectName.quote(resource.getName()); if (container instanceof Server) { name = new ObjectName( domain + ":type=DataSource" + ",class=" + resource.getType() + ",name=" + quotedResourceName); } else if (container instanceof Context) { String contextName = ((Context) container).getName(); if (!contextName.startsWith("/")) contextName = "/" + contextName; Host host = (Host) ((Context) container).getParent(); name = new ObjectName( domain + ":type=DataSource" + ",host=" + host.getName() + ",context=" + contextName + ",class=" + resource.getType() + ",name=" + quotedResourceName); } return (name); }
/** * Return a File object representing the "configuration root" directory for our associated Host. */ protected File configBase() { if (configBase != null) { return configBase; } File file = new File(System.getProperty("catalina.base"), "conf"); Container parent = host.getParent(); if ((parent != null) && (parent instanceof Engine)) { file = new File(file, parent.getName()); } file = new File(file, host.getName()); try { configBase = file.getCanonicalFile(); } catch (IOException e) { configBase = file; } return (configBase); }
/** * Remove an existing child Host from our associated Engine. * * @param host Host to be removed */ private void removeHost(Host host) { if (debug >= 3) engine.log("Removing host '" + host.getName() + "'"); host.removeContainerListener(this); // Identify all names mapped to this host ArrayList removes = new ArrayList(); Iterator keys = cache.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); if (host.equals((Host) cache.get(key))) removes.add(key); } // Remove the associated names keys = removes.iterator(); while (keys.hasNext()) { removeAlias((String) keys.next()); } }
private void silence(Host host, String ctx) { String base = "org.apache.catalina.core.ContainerBase.[default].["; if (host == null) { base += getHost().getName(); } else { base += host.getName(); } base += "].["; base += ctx; base += "]"; LOG.warn(base); }
/** * Create an <code>ObjectName</code> for this <code>Realm</code> object. * * @param domain Domain in which this name is to be created * @param realm The Realm to be named * @exception MalformedObjectNameException if a name cannot be created */ static ObjectName createObjectName(String domain, Realm realm) throws MalformedObjectNameException { ObjectName name = null; Container container = realm.getContainer(); if (container instanceof Engine) { name = new ObjectName(domain + ":type=Realm"); } else if (container instanceof Host) { name = new ObjectName(domain + ":type=Realm,host=" + container.getName()); } else if (container instanceof Context) { String path = ((Context) container).getPath(); if (path.length() < 1) { path = "/"; } Host host = (Host) container.getParent(); name = new ObjectName(domain + ":type=Realm,path=" + path + ",host=" + host.getName()); } return (name); }
private void silence(Host host, String ctx) { String base = "org.apache.catalina.core.ContainerBase.[default].["; if (host == null) { base += getHost().getName(); } else { base += host.getName(); } base += "].["; base += ctx; base += "]"; Logger.getLogger(base).setLevel(Level.WARNING); }
@Override public synchronized void start() throws Exception { Host host = ServerUtil.getDefaultHost().getHost(); _serverContext = (StandardContext) host.findChild("/" + _contextName); if (_serverContext == null) { _serverContext = new StandardContext(); _serverContext.setPath("/" + _contextName); File docBase = new File(SERVER_TEMP_DIR, _contextName); if (!docBase.exists()) { if (!docBase.mkdirs()) { throw new RuntimeException("Unable to create temp directory " + docBase.getPath()); } } _serverContext.setDocBase(docBase.getPath()); _serverContext.addLifecycleListener(new ContextConfig()); final Loader loader = new WebCtxLoader(Thread.currentThread().getContextClassLoader()); loader.setContainer(host); _serverContext.setLoader(loader); _serverContext.setInstanceManager(new LocalInstanceManager()); Wrapper wrapper = _serverContext.createWrapper(); wrapper.setName(SERVLET_NAME); wrapper.setServletClass(SwitchYardRemotingServlet.class.getName()); wrapper.setLoadOnStartup(1); _serverContext.addChild(wrapper); _serverContext.addServletMapping("/*", SERVLET_NAME); host.addChild(_serverContext); _serverContext.create(); _serverContext.start(); SwitchYardRemotingServlet remotingServlet = (SwitchYardRemotingServlet) wrapper.getServlet(); remotingServlet.setEndpointPublisher(this); _log.info("Published Remote Service Endpoint " + _serverContext.getPath()); } else { throw new RuntimeException("Context " + _contextName + " already exists!"); } }