List of usage examples for javax.servlet ServletContext getContextPath
public String getContextPath();
From source file:org.red5.server.tomcat.TomcatVHostLoader.java
/** * Starts a web application and its red5 (spring) component. This is basically a stripped down * version of init()./*from w w w . j a va2 s . co m*/ * * @return true on success */ @SuppressWarnings("cast") public boolean startWebApplication(String applicationName) { boolean result = false; log.info("Starting Tomcat virtual host - Web application"); log.info("Virtual host root: {}", webappRoot); log.info("Virtual host context id: {}", defaultApplicationContextId); // application directory String contextName = '/' + applicationName; Container cont = null; //check if the context already exists for the host if ((cont = host.findChild(contextName)) == null) { log.debug("Context did not exist in host"); String webappContextDir = FileUtil.formatPath(webappRoot, applicationName); //prepend slash Context ctx = addContext(contextName, webappContextDir); //set the newly created context as the current container cont = ctx; } else { log.debug("Context already exists in host"); } try { ServletContext servletContext = ((Context) cont).getServletContext(); log.debug("Context initialized: {}", servletContext.getContextPath()); String prefix = servletContext.getRealPath("/"); log.debug("Path: {}", prefix); Loader cldr = cont.getLoader(); log.debug("Loader type: {}", cldr.getClass().getName()); ClassLoader webClassLoader = cldr.getClassLoader(); log.debug("Webapp classloader: {}", webClassLoader); //create a spring web application context XmlWebApplicationContext appctx = new XmlWebApplicationContext(); appctx.setClassLoader(webClassLoader); appctx.setConfigLocations(new String[] { "/WEB-INF/red5-*.xml" }); //check for red5 context bean if (applicationContext.containsBean(defaultApplicationContextId)) { appctx.setParent((ApplicationContext) applicationContext.getBean(defaultApplicationContextId)); } else { log.warn("{} bean was not found in context: {}", defaultApplicationContextId, applicationContext.getDisplayName()); //lookup context loader and attempt to get what we need from it if (applicationContext.containsBean("context.loader")) { ContextLoader contextLoader = (ContextLoader) applicationContext.getBean("context.loader"); appctx.setParent(contextLoader.getContext(defaultApplicationContextId)); } else { log.debug("Context loader was not found, trying JMX"); MBeanServer mbs = JMXFactory.getMBeanServer(); //get the ContextLoader from jmx ObjectName oName = JMXFactory.createObjectName("type", "ContextLoader"); ContextLoaderMBean proxy = null; if (mbs.isRegistered(oName)) { proxy = (ContextLoaderMBean) MBeanServerInvocationHandler.newProxyInstance(mbs, oName, ContextLoaderMBean.class, true); log.debug("Context loader was found"); appctx.setParent(proxy.getContext(defaultApplicationContextId)); } else { log.warn("Context loader was not found"); } } } if (log.isDebugEnabled()) { if (appctx.getParent() != null) { log.debug("Parent application context: {}", appctx.getParent().getDisplayName()); } } // appctx.setServletContext(servletContext); //set the root webapp ctx attr on the each servlet context so spring can find it later servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx); appctx.refresh(); result = true; } catch (Throwable t) { log.error("Error setting up context: {}", applicationName, t); if (log.isDebugEnabled()) { t.printStackTrace(); } } return result; }
From source file:com.alibaba.dubbo.rpc.protocol.rest.RestProtocol.java
protected <T> Runnable doExport(T impl, Class<T> type, URL url) throws RpcException { String addr = url.getIp() + ":" + url.getPort(); Class implClass = ServiceClassHolder.getInstance().popServiceClass(); RestServer server = servers.get(addr); if (server == null) { server = serverFactory.createServer(url.getParameter(Constants.SERVER_KEY, "jetty")); server.start(url);/*w w w . j av a 2 s. c om*/ servers.put(addr, server); } String contextPath = getContextPath(url); if ("servlet".equalsIgnoreCase(url.getParameter(Constants.SERVER_KEY, "jetty"))) { ServletContext servletContext = ServletManager.getInstance() .getServletContext(ServletManager.EXTERNAL_SERVER_PORT); if (servletContext == null) { throw new RpcException("No servlet context found. Since you are using server='servlet', " + "make sure that you've configured " + BootstrapListener.class.getName() + " in web.xml"); } String webappPath = servletContext.getContextPath(); if (StringUtils.isNotEmpty(webappPath)) { webappPath = webappPath.substring(1); if (!contextPath.startsWith(webappPath)) { throw new RpcException("Since you are using server='servlet', " + "make sure that the 'contextpath' property starts with the path of external webapp"); } contextPath = contextPath.substring(webappPath.length()); if (contextPath.startsWith("/")) { contextPath = contextPath.substring(1); } } } final Class resourceDef = GetRestful.getRootResourceClass(implClass) != null ? implClass : type; server.deploy(resourceDef, impl, contextPath); final RestServer s = server; return new Runnable() { public void run() { // TODO due to dubbo's current architecture, // it will be called from registry protocol in the shutdown process and won't appear in logs s.undeploy(resourceDef); } }; }
From source file:com.ctg.itrdc.janus.rpc.protocol.rest.RestProtocol.java
protected <T> Runnable doExport(T impl, Class<T> type, URL url) throws RpcException { String addr = url.getIp() + ":" + url.getPort(); Class implClass = ServiceClassHolder.getInstance().popServiceClass(); RestServer server = servers.get(addr); if (server == null) { server = serverFactory.createServer(url.getParameter(Constants.SERVER_KEY, "jetty")); server.start(url);//from ww w . j av a2s . co m servers.put(addr, server); } String contextPath = getContextPath(url); if ("servlet".equalsIgnoreCase(url.getParameter(Constants.SERVER_KEY, "jetty"))) { ServletContext servletContext = ServletManager.getInstance() .getServletContext(ServletManager.EXTERNAL_SERVER_PORT); if (servletContext == null) { throw new RpcException("No servlet context found. Since you are using server='servlet', " + "make sure that you've configured " + BootstrapListener.class.getName() + " in web.xml"); } String webappPath = servletContext.getContextPath(); if (StringUtils.isNotEmpty(webappPath)) { webappPath = webappPath.substring(1); if (!contextPath.startsWith(webappPath)) { throw new RpcException("Since you are using server='servlet', " + "make sure that the 'contextpath' property starts with the path of external webapp"); } contextPath = contextPath.substring(webappPath.length()); if (contextPath.startsWith("/")) { contextPath = contextPath.substring(1); } } } final Class resourceDef = GetRestful.getRootResourceClass(implClass) != null ? implClass : type; server.deploy(resourceDef, impl, contextPath); final RestServer s = server; return new Runnable() { public void run() { // TODO due to janus's current architecture, // it will be called from registry protocol in the shutdown process and won't appear in logs s.undeploy(resourceDef); } }; }
From source file:org.apache.dubbo.rpc.protocol.rest.RestProtocol.java
@Override protected <T> Runnable doExport(T impl, Class<T> type, URL url) throws RpcException { String addr = getAddr(url);/*w ww . j a v a 2 s . c o m*/ Class implClass = ServiceClassHolder.getInstance().popServiceClass(); RestServer server = servers.get(addr); if (server == null) { server = serverFactory.createServer(url.getParameter(Constants.SERVER_KEY, "jetty")); server.start(url); servers.put(addr, server); } String contextPath = getContextPath(url); if ("servlet".equalsIgnoreCase(url.getParameter(Constants.SERVER_KEY, "jetty"))) { ServletContext servletContext = ServletManager.getInstance() .getServletContext(ServletManager.EXTERNAL_SERVER_PORT); if (servletContext == null) { throw new RpcException("No servlet context found. Since you are using server='servlet', " + "make sure that you've configured " + BootstrapListener.class.getName() + " in web.xml"); } String webappPath = servletContext.getContextPath(); if (StringUtils.isNotEmpty(webappPath)) { webappPath = webappPath.substring(1); if (!contextPath.startsWith(webappPath)) { throw new RpcException("Since you are using server='servlet', " + "make sure that the 'contextpath' property starts with the path of external webapp"); } contextPath = contextPath.substring(webappPath.length()); if (contextPath.startsWith("/")) { contextPath = contextPath.substring(1); } } } final Class resourceDef = GetRestful.getRootResourceClass(implClass) != null ? implClass : type; server.deploy(resourceDef, impl, contextPath); final RestServer s = server; return new Runnable() { @Override public void run() { // TODO due to dubbo's current architecture, // it will be called from registry protocol in the shutdown process and won't appear in logs s.undeploy(resourceDef); } }; }
From source file:com.alibaba.dubbo.rpc.protocol.resteasy.RestProtocol.java
protected <T> Runnable doExport(T impl, Class<T> type, URL url) throws RpcException { String addr = url.getIp() + ":" + url.getPort(); Class implClass = ServiceClassHolder.getInstance().popServiceClass(); RestServer server = servers.get(addr); if (server == null) { server = serverFactory.createServer(url.getParameter(Constants.SERVER_KEY, "jetty")); server.start(url);/*from ww w. j ava 2 s . c o m*/ servers.put(addr, server); } String contextPath = getContextPath(url); if ("servlet".equalsIgnoreCase(url.getParameter(Constants.SERVER_KEY, "jetty"))) { ServletContext servletContext = ServletManager.getInstance() .getServletContext(ServletManager.EXTERNAL_SERVER_PORT); if (servletContext == null) { throw new RpcException("No servlet context found. Since you are using server='servlet', " + "make sure that you've configured " + BootstrapListener.class.getName() + " in web.xml"); } String webappPath = servletContext.getContextPath(); if (StringUtils.isNotEmpty(webappPath)) { webappPath = webappPath.substring(1); if (!contextPath.startsWith(webappPath)) { throw new RpcException("Since you are using server='servlet', " + "make sure that the 'contextpath' property starts with the path of external webapp"); } contextPath = contextPath.substring(webappPath.length()); if (contextPath.startsWith("/")) { contextPath = contextPath.substring(1); } } } final Class resourceDef = GetRestful.getRootResourceClass(implClass) != null ? implClass : type; // dubbo ? String version = url.getParameter(Constants.VERSION_KEY); if (StringUtils.isNotEmpty(version)) { contextPath = version + "/" + contextPath; } server.deploy(resourceDef, impl, contextPath); final RestServer s = server; return new Runnable() { public void run() { // TODO due to dubbo's current architecture, // it will be called from registry protocol in the shutdown process and won't appear in logs s.undeploy(resourceDef); } }; }
From source file:org.red5.server.tomcat.TomcatVHostLoader.java
/** * Initialization./*from w ww . j a v a 2 s . c o m*/ */ @SuppressWarnings("cast") public void init() { log.info("Loading tomcat virtual host"); if (webappFolder != null) { //check for match with base webapp root if (webappFolder.equals(webappRoot)) { log.error("Web application root cannot be the same as base"); return; } } ClassLoader classloader = Thread.currentThread().getContextClassLoader(); //ensure we have a host if (host == null) { host = createHost(); } host.setParentClassLoader(classloader); String propertyPrefix = name; if (domain != null) { propertyPrefix += '_' + domain.replace('.', '_'); } log.debug("Generating name (for props) {}", propertyPrefix); System.setProperty(propertyPrefix + ".webapp.root", webappRoot); log.info("Virtual host root: {}", webappRoot); log.info("Virtual host context id: {}", defaultApplicationContextId); // Root applications directory File appDirBase = new File(webappRoot); // Subdirs of root apps dir File[] dirs = appDirBase.listFiles(new TomcatLoader.DirectoryFilter()); // Search for additional context files for (File dir : dirs) { String dirName = '/' + dir.getName(); // check to see if the directory is already mapped if (null == host.findChild(dirName)) { String webappContextDir = FileUtil.formatPath(appDirBase.getAbsolutePath(), dirName); Context ctx = null; if ("/root".equals(dirName) || "/root".equalsIgnoreCase(dirName)) { log.debug("Adding ROOT context"); ctx = addContext("/", webappContextDir); } else { log.debug("Adding context from directory scan: {}", dirName); ctx = addContext(dirName, webappContextDir); } log.debug("Context: {}", ctx); webappContextDir = null; } } appDirBase = null; dirs = null; // Dump context list if (log.isDebugEnabled()) { for (Container cont : host.findChildren()) { log.debug("Context child name: {}", cont.getName()); } } engine.addChild(host); // Start server try { log.info("Starting Tomcat virtual host"); //may not have to do this step for every host LoaderBase.setApplicationLoader(new TomcatApplicationLoader(embedded, host, applicationContext)); for (Container cont : host.findChildren()) { if (cont instanceof StandardContext) { StandardContext ctx = (StandardContext) cont; ServletContext servletContext = ctx.getServletContext(); log.debug("Context initialized: {}", servletContext.getContextPath()); //set the hosts id servletContext.setAttribute("red5.host.id", getHostId()); String prefix = servletContext.getRealPath("/"); log.debug("Path: {}", prefix); try { Loader cldr = ctx.getLoader(); log.debug("Loader type: {}", cldr.getClass().getName()); ClassLoader webClassLoader = cldr.getClassLoader(); log.debug("Webapp classloader: {}", webClassLoader); //create a spring web application context XmlWebApplicationContext appctx = new XmlWebApplicationContext(); appctx.setClassLoader(webClassLoader); appctx.setConfigLocations(new String[] { "/WEB-INF/red5-*.xml" }); //check for red5 context bean if (applicationContext.containsBean(defaultApplicationContextId)) { appctx.setParent( (ApplicationContext) applicationContext.getBean(defaultApplicationContextId)); } else { log.warn("{} bean was not found in context: {}", defaultApplicationContextId, applicationContext.getDisplayName()); //lookup context loader and attempt to get what we need from it if (applicationContext.containsBean("context.loader")) { ContextLoader contextLoader = (ContextLoader) applicationContext .getBean("context.loader"); appctx.setParent(contextLoader.getContext(defaultApplicationContextId)); } else { log.debug("Context loader was not found, trying JMX"); MBeanServer mbs = JMXFactory.getMBeanServer(); //get the ContextLoader from jmx ObjectName oName = JMXFactory.createObjectName("type", "ContextLoader"); ContextLoaderMBean proxy = null; if (mbs.isRegistered(oName)) { proxy = (ContextLoaderMBean) MBeanServerInvocationHandler.newProxyInstance(mbs, oName, ContextLoaderMBean.class, true); log.debug("Context loader was found"); appctx.setParent(proxy.getContext(defaultApplicationContextId)); } else { log.warn("Context loader was not found"); } } } if (log.isDebugEnabled()) { if (appctx.getParent() != null) { log.debug("Parent application context: {}", appctx.getParent().getDisplayName()); } } // appctx.setServletContext(servletContext); //set the root webapp ctx attr on the each servlet context so spring can find it later servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx); appctx.refresh(); } catch (Throwable t) { log.error("Error setting up context: {}", servletContext.getContextPath(), t); if (log.isDebugEnabled()) { t.printStackTrace(); } } } } } catch (Exception e) { log.error("Error loading Tomcat virtual host", e); } }
From source file:net.community.chest.gitcloud.facade.AbstractEnvironmentInitializer.java
protected void contextInitialized(ServletContext context) { PlaceholderResolver contextResolver = ServletUtils.toPlaceholderResolver(context); Pair<File, Boolean> result = ConfigUtils.resolveGitcloudBase(new AggregatedExtendedPlaceholderResolver( contextResolver, ExtendedPlaceholderResolverUtils.SYSPROPS_RESOLVER, ExtendedPlaceholderResolverUtils.ENVIRON_RESOLVER)); File rootDir = result.getLeft(); Boolean baseExists = result.getRight(); if (!baseExists.booleanValue()) { System.setProperty(ConfigUtils.GITCLOUD_BASE_PROP, rootDir.getAbsolutePath()); logger.info("contextInitialized(" + context.getContextPath() + ") - added " + ConfigUtils.GITCLOUD_BASE_PROP + ": " + ExtendedFileUtils.toString(rootDir)); } else {//from ww w . ja v a 2 s . c om logger.info("contextInitialized(" + context.getContextPath() + ") using " + ConfigUtils.GITCLOUD_BASE_PROP + ": " + ExtendedFileUtils.toString(rootDir)); } extractConfigFiles(new File(rootDir, ConfigUtils.CONF_DIR_NAME)); }
From source file:org.red5.server.winstone.WinstoneLoader.java
/** * Initialization./*from w w w . j a v a 2 s . co m*/ */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void init() { log.info("Loading Winstone context"); //get a reference to the current threads classloader final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); // root location for servlet container String serverRoot = System.getProperty("red5.root"); log.info("Server root: {}", serverRoot); String confRoot = System.getProperty("red5.config_root"); log.info("Config root: {}", confRoot); // configure the webapps folder, make sure we have one if (webappFolder == null) { // Use default webapps directory webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps"); } System.setProperty("red5.webapp.root", webappFolder); log.info("Application root: {}", webappFolder); // create one embedded (server) and use it everywhere Map args = new HashMap(); //args.put("webroot", webappFolder + "/root"); args.put("webappsDir", webappFolder); // Start server try { log.info("Starting Winstone servlet engine"); Launcher.initLogger(args); // spawns threads, so your application doesn't block embedded = new StoneLauncher(args); log.trace("Classloader for embedded: {} TCL: {}", Launcher.class.getClassLoader(), originalClassLoader); // get the default host HostConfiguration host = embedded.getHostGroup().getHostByName(null); // set the primary application loader LoaderBase.setApplicationLoader(new WinstoneApplicationLoader(host, applicationContext)); // get root first, we may want to start a spring config internally but for now skip it WebAppConfiguration root = host.getWebAppByURI("/"); log.trace("Root: {}", root); // scan the sub directories to determine our context names buildContextNameList(webappFolder); // loop the other contexts for (String contextName : contextNames) { WebAppConfiguration ctx = host.getWebAppByURI(contextName); // get access to the servlet context final ServletContext servletContext = ctx.getContext(contextName); log.debug("Context initialized: {}", servletContext.getContextPath()); //set the hosts id servletContext.setAttribute("red5.host.id", host.getHostname()); // get the path String prefix = servletContext.getRealPath("/"); log.debug("Path: {}", prefix); try { final ClassLoader cldr = ctx.getLoader(); log.debug("Loader type: {}", cldr.getClass().getName()); // get the (spring) config file path final String contextConfigLocation = servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null ? defaultSpringConfigLocation : servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM); log.debug("Spring context config location: {}", contextConfigLocation); // get the (spring) parent context key final String parentContextKey = servletContext.getInitParameter( org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null ? defaultParentContextKey : servletContext.getInitParameter( org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM); log.debug("Spring parent context key: {}", parentContextKey); //set current threads classloader to the webapp classloader Thread.currentThread().setContextClassLoader(cldr); //create a thread to speed-up application loading Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) { public void run() { //set thread context classloader to web classloader Thread.currentThread().setContextClassLoader(cldr); //get the web app's parent context ApplicationContext parentContext = null; if (applicationContext.containsBean(parentContextKey)) { parentContext = (ApplicationContext) applicationContext.getBean(parentContextKey); } else { log.warn("Parent context was not found: {}", parentContextKey); } // create a spring web application context final String contextClass = servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null ? XmlWebApplicationContext.class.getName() : servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM); //web app context (spring) ConfigurableWebApplicationContext appctx = null; try { Class<?> clazz = Class.forName(contextClass, true, cldr); appctx = (ConfigurableWebApplicationContext) clazz.newInstance(); } catch (Throwable e) { throw new RuntimeException("Failed to load webapplication context class.", e); } appctx.setConfigLocations(new String[] { contextConfigLocation }); appctx.setServletContext(servletContext); //set parent context or use current app context if (parentContext != null) { appctx.setParent(parentContext); } else { appctx.setParent(applicationContext); } // set the root webapp ctx attr on the each servlet context so spring can find it later servletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx); //refresh the factory log.trace("Classloader prior to refresh: {}", appctx.getClassLoader()); appctx.refresh(); if (log.isDebugEnabled()) { log.debug("Red5 app is active: {} running: {}", appctx.isActive(), appctx.isRunning()); } } }; thread.setDaemon(true); thread.start(); } catch (Throwable t) { log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(), t.getMessage()); t.printStackTrace(); } finally { //reset the classloader Thread.currentThread().setContextClassLoader(originalClassLoader); } } } catch (Exception e) { if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) { log.error( "Error loading Winstone, unable to bind connector. You may not have permission to use the selected port", e); } else { log.error("Error loading Winstone", e); } } finally { registerJMX(); } }
From source file:org.openmrs.web.Listener.java
/** * Hacky way to get the current contextPath. This will usually be "openmrs". This method will be * obsolete when servlet api ~2.6 comes out...at which point a call like * servletContext.getContextRoot() would be sufficient * * @return current contextPath of this webapp without initial slash *//*from ww w . j av a 2 s . c om*/ private String getContextPath(ServletContext servletContext) { // Get the context path without the request. String contextPath = ""; try { contextPath = servletContext.getContextPath(); } catch (NoSuchMethodError ex) { // ServletContext.getContextPath() was added in version 2.5 of the Servlet API. Tomcat 5.5 // has version 2.4 of the servlet API, so we fall back to the hacky code we were previously // using try { String path = servletContext.getResource("/").getPath(); contextPath = path.substring(0, path.lastIndexOf("/")); contextPath = contextPath.substring(contextPath.lastIndexOf("/")); } catch (Exception e) { log.error(e); } } catch (Exception e) { log.error(e); } // trim off initial slash if it exists if (contextPath.indexOf("/") != -1) { contextPath = contextPath.substring(1); } return contextPath; }
From source file:no.kantega.publishing.spring.OpenAksessContextLoaderListener.java
@Override protected void customizeContext(ServletContext servletContext, ConfigurableWebApplicationContext wac) { Configuration.setApplicationDirectory(dataDirectory); // Make dataDir available as Servlet Context attribute servletContext.setAttribute(APPLICATION_DIRECTORY, dataDirectory); // Set up @Autowired support ApplicationContextUtils.addAutowiredSupport(wac); final Configuration configuration = new Configuration(properties); if (configuration.getBoolean("caching.enabled", true)) { wac.getEnvironment().setActiveProfiles("useCaching"); }//ww w. java 2 s.c o m Aksess.setContextPath(servletContext.getContextPath()); // Set and load configuration on these classes since they are not DI-based (hackish..) Aksess.setConfiguration(configuration); Aksess.loadConfiguration(); // Add ${appDir} property for the Spring Context ApplicationContextUtils.addAppDirPropertySupport(wac); dbConnectionFactory.setServletContext(servletContext); dbConnectionFactory.setConfiguration(configuration); dbConnectionFactory.loadConfiguration(); // Add the Configuration and the ConfigurationLoader as Spring beans addConfigurationAndLoaderAsSingletonsInContext(wac, configuration, configurationLoader); // Replace ${} properties in Spring with config properties addConfigurationPropertyReplacer(wac, properties); RootContext.setInstance(wac); }