List of usage examples for javax.servlet ServletContext getContextPath
public String getContextPath();
From source file:org.kuali.mobility.tags.MultiPageTag.java
public void doTag() throws JspException { PageContext pageContext = (PageContext) getJspContext(); HttpServletRequest hsr = (HttpServletRequest) pageContext.getRequest(); Cookie cks[] = hsr.getCookies();/*from w ww . jav a 2 s . c om*/ if (cks != null) { for (Cookie c : cks) { if (c.getName().equals("jqmHeader")) { setJqmHeader(c.getValue()); //LOG.info("---jqmHeader: " + jqmHeader); } } } ServletContext servletContext = pageContext.getServletContext(); WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(servletContext); setAuthMapper((AuthenticationMapper) ac.getBean("authenticationMapper")); CoreService coreService = (CoreService) ac.getBean("coreService"); Properties kmeProperties = (Properties) ac.getBean("kmeProperties"); User user = (User) pageContext.getSession().getAttribute(AuthenticationConstants.KME_USER_KEY); String contextPath = servletContext.getContextPath(); JspWriter out = pageContext.getOut(); try { out.println("<!DOCTYPE html>"); if (!getAppcacheEnabled().equals("false")) { LOG.debug("Appcache Enabled"); out.println("<html manifest=\"" + contextPath + "/" + (StringUtils.isEmpty(getAppcacheFilename()) ? "kme.appcache" : getAppcacheFilename().trim()) + "\">"); } else { LOG.debug("Appcache Disabled"); out.println("<html>"); } out.println("<head>"); out.println("<title>" + getTitle() + "</title>"); out.println( "<link href=\"" + kmeProperties.getProperty("favico.url", "http://www.kuali.org/favicon.ico") + "\" rel=\"icon\" />"); out.println( "<link href=\"" + kmeProperties.getProperty("favico.url", "http://www.kuali.org/favicon.ico") + "\" rel=\"shortcut icon\" />"); // out.println("<link rel=\"apple-touch-icon\" href=\"" + contextPath + "/apple-touch-icon-precomposed.png\"/>"); out.println("<link rel=\"apple-touch-icon\" href=\"" + contextPath + "/touch-icon-iphone.png\"/>"); out.println("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"" + contextPath + "/touch-icon-ipad.png\"/>"); out.println("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"" + contextPath + "/touch-icon-iphone-retina.png\"/>"); out.println("<link rel=\"apple-touch-icon\" sizes=\"144x144\" href=\"" + contextPath + "/touch-icon-ipad-retina.png\"/>"); out.println("<link href=\"" + contextPath + "/css/jquery.mobile.css\" rel=\"stylesheet\" type=\"text/css\" />"); out.println("<link href=\"" + contextPath + "/css/jquery-mobile-fluid960.css\" rel=\"stylesheet\" type=\"text/css\" />"); out.println("<link href=\"" + contextPath + "/css/kme.css\" rel=\"stylesheet\" type=\"text/css\" />"); out.println("<link href=\"" + contextPath + "/css/institution.css\" rel=\"stylesheet\" type=\"text/css\" />"); // Attach all CSS files for (String cssFile : getCssFilenames()) { out.println("<link href=\"" + contextPath + "/css/" + cssFile + ".css\" rel=\"stylesheet\" type=\"text/css\" />"); } out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/jquery.js\"></script>"); out.println( "<script type=\"text/javascript\" src=\"" + contextPath + "/js/jquery.cookie.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/custom.js\"></script>"); out.println( "<script type=\"text/javascript\" src=\"" + contextPath + "/js/jquery.mobile.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/jquery.tmpl.js\"></script>"); out.println( "<script type=\"text/javascript\" src=\"" + contextPath + "/js/jquery.validate.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/jquery.validate.ready.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/jquery.templates.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/jquery.transit.min.js\"></script>"); out.println( "<script type=\"text/javascript\" src=\"" + contextPath + "/js/BrowserDetect.js\"></script>"); out.println( "<script type=\"text/javascript\" src=\"" + contextPath + "/js/ServerDetails.js\"></script>"); if (isNative()) { out.println( "<script type=\"text/javascript\" src=\"" + contextPath + "/js/PushConfig.js\"></script>"); } out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/jquery.autoellipsis-1.0.3.min.js\"></script>"); // if (getPlatform() != null && getPlatform().equals("iOS")) { // out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/phonegap-" + getPhonegap() + ".js\"></script>"); // out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/ChildBrowser.js\"></script>"); // out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/barcodescanner.js\"></script>"); //// out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/Connection.js\"></script>"); // out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/PushHandler.js\"></script>"); // out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/Badge.js\"></script>"); // out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/applicationPreferences.js\"></script>"); // } else if (getPlatform() != null && getPlatform().equals("Android")) { // out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/phonegap-" + getPhonegap() + ".js\"></script>"); // out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/childbrowser.js\"></script>"); // out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/barcodescanner.js\"></script>"); // out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/statusbarnotification.js\"></script>"); // //out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/C2DMPlugin.js\"></script>"); // //out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/PG_C2DM_script.js\"></script>"); // } if (isPlatform(Device.TYPE_IOS)) { if (isPhoneGap("1.4.1")) { out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/phonegap-1.4.1.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/ChildBrowser.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/barcodescanner.js\"></script>"); // out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/Connection.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/PushHandler.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/Badge.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/applicationPreferences.js\"></script>"); } else if (isPhoneGap("1.7.0")) { out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/1.7.0/cordova-1.7.0.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/1.7.0/ChildBrowser.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/1.7.0/barcodescanner.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/1.7.0/ActionSheet.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/1.7.0/Badge.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/1.7.0/LocalNotifications.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/1.7.0/Notifications.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/1.7.0/PrintPlugin.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/1.7.0/applicationPreferences.js\"></script>"); } else if (isPhoneGap("2.2.0")) { out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/2.2.0/cordova-2.2.0.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/2.2.0/ActionSheet.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/2.2.0/applicationPreferences.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/2.2.0/AudioStreamer.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/2.2.0/Badge.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/2.2.0/barcodescanner.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/2.2.0/ChildBrowser.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/PushHandler.js\"></script>"); } else if (isPhoneGap("2.3.0")) { out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/2.3.0/cordova-2.3.0.js\"></script>"); } else if (isPhoneGap("2.4.0")) { out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/2.4.0/cordova-2.4.0.js\"></script>"); } else if (isPhoneGap("2.5.0")) { out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/2.5.0/cordova-2.5.0.js\"></script>"); } else if (isPhoneGap("2.6.0")) { out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/2.6.0/cordova-2.6.0.js\"></script>"); } else if (isPhoneGap("2.7.0")) { out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/2.7.0/cordova-2.7.0.js\"></script>"); } else if (isPhoneGap("2.8.1")) { out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/iOS/2.8.1/cordova.js\"></script>"); } } else if (isPlatform(Device.TYPE_ANDROID)) { if (isPhoneGap("2.2.0")) { out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/2.2.0/cordova-2.2.0.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/2.2.0/childbrowser.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/2.2.0/barcodescanner.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/2.2.0/statusbarnotification.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/2.2.0/datePickerPlugin.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/2.2.0/applicationPreferences.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/2.2.0/AudioStreamer.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/2.2.0/GCMPlugin.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/2.2.0/CORDOVA_GCM_script.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/PushHandler.js\"></script>"); } else { out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/phonegap-" + getPhonegap() + ".js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/childbrowser.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/barcodescanner.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/statusbarnotification.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/C2DMPlugin.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/PG_C2DM_script.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/android/PushHandler.js\"></script>"); } } else if (isPlatform(Device.TYPE_BLACKBERRY)) { if (isPhoneGap("2.2.0")) { out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/PushConfig.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/blackberry/2.2.0/cordova-2.2.0.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/blackberry/2.2.0/kme-application.js\"></script>"); } } else if (isPlatform(Device.TYPE_WINDOWS)) { if (isPhoneGap("2.2.0")) { out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/windowsMobile/2.2.0/cordova-2.2.0.js\"></script>"); } } String profileId = coreService.findGoogleAnalyticsProfileId().trim(); if (!isDisableGoogleAnalytics() && profileId.length() > 0) { out.println("<script type=\"text/javascript\">"); out.println("var _gaq = _gaq || [];"); out.println("_gaq.push(['_setAccount', '" + profileId + "']);"); out.println("_gaq.push(['_trackPageview']);"); out.println("(function() {"); out.println( "var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;"); out.println( "ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';"); out.println( "var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);"); out.println("})();"); out.println("</script>"); } if (isUsesGoogleMaps()) { if (getMapLocale() != null) { out.println( "<script type=\"text/javascript\" src=\"http://maps.google.com/maps/api/js?sensor=true&language=" + getMapLocale() + "\"></script>"); } else { out.println( "<script type=\"text/javascript\" src=\"http://maps.google.com/maps/api/js?sensor=true\"></script>"); } } // Now add all the javascripts for (String javascript : getJsFilenames()) { out.println("<script type=\"text/javascript\" src=\"" + contextPath + "/js/" + javascript + ".js\"></script>"); } // out.println("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />"); // out.println("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\" />"); out.println( "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\">"); out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"); out.println("</head>"); if (getOnBodyLoad() != null) { out.println("<body onload='" + getOnBodyLoad() + "'>"); } else { out.println("<body>"); } getJspBody().invoke(out); out.println("</body>"); out.println("</html>"); } catch (Exception e) { LOG.error(e.getMessage(), e); } }
From source file:org.red5.server.tomcat.TomcatLoader.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 va 2s . c om*/ * @return true on success */ public boolean startWebApplication(String applicationName) { log.info("Starting Tomcat - Web application"); boolean result = false; //get a reference to the current threads classloader final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); log.debug("Webapp root: {}", webappFolder); // application directory String contextName = '/' + applicationName; Container ctx = null; if (webappFolder == null) { // Use default webapps directory webappFolder = System.getProperty("red5.root") + "/webapps"; } System.setProperty("red5.webapp.root", webappFolder); log.info("Application root: {}", webappFolder); // scan for additional webapp contexts // Root applications directory File appDirBase = new File(webappFolder); // check if the context already exists for the host if ((ctx = host.findChild(contextName)) == null) { log.debug("Context did not exist in host"); String webappContextDir = FileUtil.formatPath(appDirBase.getAbsolutePath(), applicationName); log.debug("Webapp context directory (full path): {}", webappContextDir); // set the newly created context as the current container ctx = addContext(contextName, webappContextDir); } else { log.debug("Context already exists in host"); } final ServletContext servletContext = ((Context) ctx).getServletContext(); log.debug("Context initialized: {}", servletContext.getContextPath()); String prefix = servletContext.getRealPath("/"); log.debug("Path: {}", prefix); try { Loader cldr = ctx.getLoader(); log.debug("Loader delegate: {} type: {}", cldr.getDelegate(), cldr.getClass().getName()); if (cldr instanceof WebappLoader) { log.debug("WebappLoader class path: {}", ((WebappLoader) cldr).getClasspath()); } final ClassLoader webClassLoader = cldr.getClassLoader(); log.debug("Webapp classloader: {}", webClassLoader); // get the (spring) config file path final String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation") == null ? defaultSpringConfigLocation : servletContext.getInitParameter("contextConfigLocation"); log.debug("Spring context config location: {}", contextConfigLocation); // get the (spring) parent context key final String parentContextKey = servletContext.getInitParameter("parentContextKey") == null ? defaultParentContextKey : servletContext.getInitParameter("parentContextKey"); log.debug("Spring parent context key: {}", parentContextKey); //set current threads classloader to the webapp classloader Thread.currentThread().setContextClassLoader(webClassLoader); //create a thread to speed-up application loading Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) { @SuppressWarnings("cast") public void run() { //set current threads classloader to the webapp classloader Thread.currentThread().setContextClassLoader(webClassLoader); // create a spring web application context XmlWebApplicationContext appctx = new XmlWebApplicationContext(); appctx.setClassLoader(webClassLoader); appctx.setConfigLocations(new String[] { contextConfigLocation }); // check for red5 context bean ApplicationContext parentAppCtx = null; if (applicationContext.containsBean(defaultParentContextKey)) { parentAppCtx = (ApplicationContext) applicationContext.getBean(defaultParentContextKey); } else { log.warn("{} bean was not found in context: {}", defaultParentContextKey, 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"); parentAppCtx = contextLoader.getContext(defaultParentContextKey); } 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"); parentAppCtx = proxy.getContext(defaultParentContextKey); } else { log.warn("Context loader was not found"); } } } if (log.isDebugEnabled()) { if (appctx.getParent() != null) { log.debug("Parent application context: {}", appctx.getParent().getDisplayName()); } } appctx.setParent(parentAppCtx); 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(); } }; thread.setDaemon(true); thread.start(); result = true; } 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); } return result; }
From source file:org.cloudfoundry.identity.uaa.config.YamlServletProfileInitializer.java
private void applyLog4jConfiguration(ConfigurableEnvironment environment, ServletContext servletContext) { String log4jConfigLocation = "classpath:log4j.properties"; if (environment.containsProperty("logging.file")) { String location = environment.getProperty("logging.file"); servletContext.log("Setting LOG_FILE: " + location); System.setProperty("LOG_FILE", location); }/*ww w . j a v a 2 s.co m*/ else if (environment.containsProperty("logging.path")) { String location = environment.getProperty("logging.path"); servletContext.log("Setting LOG_PATH: " + location); System.setProperty("LOG_PATH", location); } else if (environment.containsProperty("logging.config")) { log4jConfigLocation = environment.getProperty("logging.config"); } try { servletContext.log("Loading log4j config from location: " + log4jConfigLocation); Log4jConfigurer.initLogging(log4jConfigLocation); } catch (FileNotFoundException e) { servletContext.log("Error loading log4j config from location: " + log4jConfigLocation, e); } MDC.put("context", servletContext.getContextPath()); }
From source file:com.tremolosecurity.config.util.UnisonConfigManagerImpl.java
/** * @param configXML//from ww w .j av a 2 s .c o m * @param path * @throws Exception */ public UnisonConfigManagerImpl(String configXML, ServletContext ctx, String name) throws Exception { this.errorPages = new HashMap<Integer, String>(); this.configXML = configXML; this.ctx = ctx; this.name = name; this.notifiers = new ArrayList<ReloadNotification>(); if (ctx != null) { if (ctx.getContextPath().equalsIgnoreCase("/")) { this.authPath = "/auth/"; } else { this.authPath = ctx.getContextPath() + "/auth/"; } } else { this.authPath = "/auth/"; } this.authForms = this.authPath + "forms/"; this.authIdP = this.authPath + "idp/"; if (this.ctx != null) { this.ctxPath = ctx.getContextPath(); } else { this.ctxPath = "/"; } this.secretKeyCache = new HashMap<String, Key>(); }
From source file:org.wso2.carbon.device.mgt.core.config.permission.lifecycle.WebAppDeploymentLifecycleListener.java
@Override public void lifecycleEvent(LifecycleEvent lifecycleEvent) { if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) { StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); ServletContext servletContext = context.getServletContext(); String contextPath = context.getServletContext().getContextPath(); String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); if (isManagedApi) { try { AnnotationProcessor annotationProcessor = new AnnotationProcessor(context); Set<String> annotatedAPIClasses = annotationProcessor .scanStandardContext(io.swagger.annotations.SwaggerDefinition.class.getName()); List<Permission> permissions = annotationProcessor.extractPermissions(annotatedAPIClasses); PermissionManagerService permissionManagerService = PermissionManagerServiceImpl.getInstance(); if (permissions != null) { for (Permission permission : permissions) { permissionManagerService.addPermission(permission); }//from w w w. ja va 2 s . c o m } } catch (PermissionManagementException e) { log.error("Exception occurred while adding the permissions from webapp : " + servletContext.getContextPath(), e); } catch (IOException e) { log.error("Cannot find API annotation Class in the webapp '" + contextPath + "' class path", e); } } } }
From source file:org.red5.server.tomcat.TomcatLoader.java
/** * Initialization./* w w w.j a v a2s . c o m*/ */ public void init() { log.info("Loading tomcat 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); // create one embedded (server) and use it everywhere embedded = new Embedded(); embedded.createLoader(originalClassLoader); embedded.setCatalinaBase(serverRoot); embedded.setCatalinaHome(serverRoot); embedded.setName(serviceEngineName); log.trace("Classloader for embedded: {} TCL: {}", Embedded.class.getClassLoader(), originalClassLoader); engine = embedded.createEngine(); engine.setDefaultHost(host.getName()); engine.setName(serviceEngineName); 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); // scan for additional webapp contexts // Root applications directory File appDirBase = new File(webappFolder); // Subdirs of root apps dir File[] dirs = appDirBase.listFiles(new 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); log.debug("Webapp context directory (full path): {}", webappContextDir); Context ctx = null; if ("/root".equals(dirName) || "/root".equalsIgnoreCase(dirName)) { log.trace("Adding ROOT context"); ctx = addContext("/", webappContextDir); } else { log.trace("Adding context from directory scan: {}", dirName); ctx = addContext(dirName, webappContextDir); } log.trace("Context: {}", ctx); //see if the application requests php support String enablePhp = ctx.findParameter("enable-php"); //if its null try to read directly if (enablePhp == null) { File webxml = new File(webappContextDir + "/WEB-INF/", "web.xml"); if (webxml.exists() && webxml.canRead()) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(webxml); // normalize text representation doc.getDocumentElement().normalize(); log.trace("Root element of the doc is {}", doc.getDocumentElement().getNodeName()); NodeList listOfElements = doc.getElementsByTagName("context-param"); int totalElements = listOfElements.getLength(); log.trace("Total no of elements: {}", totalElements); for (int s = 0; s < totalElements; s++) { Node fstNode = listOfElements.item(s); if (fstNode.getNodeType() == Node.ELEMENT_NODE) { Element fstElmnt = (Element) fstNode; NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("param-name"); Element fstNmElmnt = (Element) fstNmElmntLst.item(0); NodeList fstNm = fstNmElmnt.getChildNodes(); String pName = (fstNm.item(0)).getNodeValue(); log.trace("Param name: {}", pName); if ("enable-php".equals(pName)) { NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("param-value"); Element lstNmElmnt = (Element) lstNmElmntLst.item(0); NodeList lstNm = lstNmElmnt.getChildNodes(); String pValue = (lstNm.item(0)).getNodeValue(); log.trace("Param value: {}", pValue); enablePhp = pValue; // break; } } } } catch (Exception e) { log.warn("Error reading web.xml", e); } } webxml = null; } log.debug("Enable php: {}", enablePhp); if ("true".equals(enablePhp)) { log.info("Adding PHP (Quercus) servlet for context: {}", ctx.getName()); // add servlet wrapper StandardWrapper wrapper = (StandardWrapper) ctx.createWrapper(); wrapper.setServletName("QuercusServlet"); wrapper.setServletClass("com.caucho.quercus.servlet.QuercusServlet"); log.debug("Wrapper: {}", wrapper); ctx.addChild(wrapper); // add servlet mappings ctx.addServletMapping("*.php", "QuercusServlet"); } webappContextDir = null; } } appDirBase = null; dirs = null; // Dump context list if (log.isDebugEnabled()) { for (Container cont : host.findChildren()) { log.debug("Context child name: {}", cont.getName()); } } // Set a realm if (realm == null) { realm = new MemoryRealm(); } embedded.setRealm(realm); // use Tomcat jndi or not if (System.getProperty("catalina.useNaming") != null) { embedded.setUseNaming(Boolean.valueOf(System.getProperty("catalina.useNaming"))); } // add the valves to the host for (Valve valve : valves) { log.debug("Adding host valve: {}", valve); ((StandardHost) host).addValve(valve); } // baseHost = embedded.createHost(hostName, appRoot); engine.addChild(host); // add any additional hosts if (hosts != null && !hosts.isEmpty()) { // grab current contexts from base host Container[] currentContexts = host.findChildren(); log.info("Adding {} additional hosts", hosts.size()); for (Host h : hosts) { log.debug("Host - name: {} appBase: {} info: {}", new Object[] { h.getName(), h.getAppBase(), h.getInfo() }); //add the contexts to each host for (Container cont : currentContexts) { Context c = (Context) cont; addContext(c.getPath(), c.getDocBase(), h); } //add the host to the engine engine.addChild(h); } } // Add new Engine to set of Engine for embedded server embedded.addEngine(engine); // set connection properties for (String key : connectionProperties.keySet()) { log.debug("Setting connection property: {} = {}", key, connectionProperties.get(key)); if (connectors == null || connectors.isEmpty()) { connector.setProperty(key, connectionProperties.get(key)); } else { for (Connector ctr : connectors) { ctr.setProperty(key, connectionProperties.get(key)); } } } // set the bind address if (address == null) { //bind locally address = InetSocketAddress.createUnresolved("127.0.0.1", connector.getPort()).getAddress(); } // apply the bind address ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof Http11Protocol) { ((Http11Protocol) handler).setAddress(address); } else if (handler instanceof Http11NioProtocol) { ((Http11NioProtocol) handler).setAddress(address); } else { log.warn("Unknown handler type: {}", handler.getClass().getName()); } // Start server try { // Add new Connector to set of Connectors for embedded server, // associated with Engine if (connectors == null || connectors.isEmpty()) { embedded.addConnector(connector); log.trace("Connector oName: {}", connector.getObjectName()); } else { for (Connector ctr : connectors) { embedded.addConnector(ctr); log.trace("Connector oName: {}", ctr.getObjectName()); } } log.info("Starting Tomcat servlet engine"); embedded.start(); LoaderBase.setApplicationLoader(new TomcatApplicationLoader(embedded, host, applicationContext)); for (Container cont : host.findChildren()) { if (cont instanceof StandardContext) { StandardContext ctx = (StandardContext) cont; final 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 { if (ctx.resourcesStart()) { log.debug("Resources started"); } log.debug("Context - available: {} privileged: {}, start time: {}, reloadable: {}", new Object[] { ctx.getAvailable(), ctx.getPrivileged(), ctx.getStartTime(), ctx.getReloadable() }); Loader cldr = ctx.getLoader(); log.debug("Loader delegate: {} type: {}", cldr.getDelegate(), cldr.getClass().getName()); if (cldr instanceof WebappLoader) { log.debug("WebappLoader class path: {}", ((WebappLoader) cldr).getClasspath()); } final ClassLoader webClassLoader = cldr.getClassLoader(); log.debug("Webapp classloader: {}", webClassLoader); // 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(webClassLoader); //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(webClassLoader); //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, webClassLoader); 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); } } } // if everything is ok at this point then call the rtmpt and rtmps // beans so they will init if (applicationContext.containsBean("red5.core")) { ApplicationContext core = (ApplicationContext) applicationContext.getBean("red5.core"); if (core.containsBean("rtmpt.server")) { log.debug("Initializing RTMPT"); core.getBean("rtmpt.server"); log.debug("Finished initializing RTMPT"); } else { log.info("Dedicated RTMPT server configuration was not specified"); } if (core.containsBean("rtmps.server")) { log.debug("Initializing RTMPS"); core.getBean("rtmps.server"); log.debug("Finished initializing RTMPS"); } else { log.info("Dedicated RTMPS server configuration was not specified"); } } else { log.info("Core context was not found"); } } catch (Exception e) { if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) { log.error( "Error loading tomcat, unable to bind connector. You may not have permission to use the selected port", e); } else { log.error("Error loading tomcat", e); } } finally { registerJMX(); } }
From source file:org.ohmage.request.RequestBuilder.java
@Override public void setServletContext(final ServletContext servletContext) { singleton = this; apiRoot = servletContext.getContextPath(); // Annotation apiAnnotationPromptResponseCreate = apiRoot + "/annotation/prompt_response/create"; apiAnnotationPromptResponseRead = apiRoot + "/annotation/prompt_response/read"; apiAnnotationSurveyResponseCreate = apiRoot + "/annotation/survey_response/create"; apiAnnotationSurveyResponseRead = apiRoot + "/annotation/survey_response/read"; apiAnnotationUpdate = apiRoot + "/annotation/update"; apiAnnotationDelete = apiRoot + "/annotation/delete"; // Audio/*from www . j a va2s .c o m*/ apiAudioRead = apiRoot + "/audio/read"; // Audit apiAuditRead = apiRoot + "/audit/read"; // Authentication apiUserAuth = apiRoot + "/user/auth"; apiUserAuthToken = apiRoot + "/user/auth_token"; apiUserLogout = apiRoot + "/user/logout"; apiUserWhoAmI = apiRoot + "/user/whoami"; // Campaign apiCampaignAssignment = apiRoot + "/campaign/assign"; apiCampaignCreate = apiRoot + "/campaign/create"; apiCampaignRead = apiRoot + "/campaign/read"; apiCampaignSearch = apiRoot + "/campaign/search"; apiCampaignUpdate = apiRoot + "/campaign/update"; apiCampaignDelete = apiRoot + "/campaign/delete"; // Class apiClassCreate = apiRoot + "/class/create"; apiClassRead = apiRoot + "/class/read"; apiClassRosterRead = apiRoot + "/class/roster/read"; apiClassSearch = apiRoot + "/class/search"; apiClassUpdate = apiRoot + "/class/update"; apiClassRosterUpdate = apiRoot + "/class/roster/update"; apiClassDelete = apiRoot + "/class/delete"; // Config apiConfigRead = apiRoot + "/config/read"; // Document apiDocumentCreate = apiRoot + "/document/create"; apiDocumentRead = apiRoot + "/document/read"; apiDocumentReadContents = apiRoot + "/document/read/contents"; apiDocumentUpdate = apiRoot + "/document/update"; apiDocumentDelete = apiRoot + "/document/delete"; // Image apiImageRead = apiRoot + "/image/read"; apiImageBatchZipRead = apiRoot + "/image/batch/zip/read"; // Mobility apiMobilityUpload = apiRoot + "/mobility/upload"; apiMobilityRead = apiRoot + "/mobility/read"; apiMobilityReadChunked = apiRoot + "/mobility/read/chunked"; apiMobilityAggregateRead = apiRoot + "/mobility/aggregate/read"; apiMobilityDatesRead = apiRoot + "/mobility/dates/read"; apiMobilityReadCsv = apiRoot + "/mobility/read/csv"; apiMobilityUpdate = apiRoot + "/mobility/update"; // Observer apiObserverCreate = apiRoot + "/observer/create"; apiObserverRead = apiRoot + "/observer/read"; apiObserverReadXml = apiRoot + "/observer/read/xml"; apiObserverUpdate = apiRoot + "/observer/update"; apiStreamUpload = apiRoot + "/stream/upload"; apiStreamRead = apiRoot + "/stream/read"; apiStreamInvalidRead = apiRoot + "/stream/invalid/read"; // OMH apiOmhAuth = apiRoot + "/omh/v1.0/authenticate"; apiOmhRegistryCreate = apiRoot + "/omh/v1.0/registry/create"; apiOmhRegistryRead = apiRoot + "/omh/v1.0/registry/read"; apiOmhRegistryUpdate = apiRoot + "/omh/v1.0/registry/update"; apiOmhCatalog = apiRoot + "/omh/v1.0/catalog"; apiOmhRead = apiRoot + "/omh/v1.0/read"; apiOmhWrite = apiRoot + "/omh/v1.0/write"; // Survey apiSurveyUpload = apiRoot + "/survey/upload"; apiSurveyResponseDelete = apiRoot + "/survey_response/delete"; apiSurveyResponseRead = apiRoot + "/survey_response/read"; apiSurveyResponseUpdate = apiRoot + "/survey_response/update"; apiSurveyResponseFunctionRead = apiRoot + "/survey_response/function/read"; // User apiUserCreate = apiRoot + "/user/create"; apiUserRegister = apiRoot + "/user/register"; apiUserActivate = apiRoot + "/user/activate"; apiUserPasswordReset = apiRoot + "/user/reset_password"; apiUserRead = apiRoot + "/user/read"; apiUserInfoRead = apiRoot + "/user_info/read"; apiUserStatsRead = apiRoot + "/user_stats/read"; apiUserSearch = apiRoot + "/user/search"; apiUserUpdate = apiRoot + "/user/update"; apiUserChangePassword = apiRoot + "/user/change_password"; apiUserDelete = apiRoot + "/user/delete"; // Registration apiRegistrationRead = apiRoot + "/registration/read"; // Video apiVideoRead = apiRoot + "/video/read"; // Visualization apiVisualization = apiRoot + "/viz"; apiVisualizationSurveyResponseCount = apiVisualization + "/survey_response_count/read"; apiVisualizationPromptDistribution = apiVisualization + "/prompt_distribution/read"; apiVisualizationPromptTimeseries = apiVisualization + "/prompt_timeseries/read"; apiVisualizationUserTimeseries = apiVisualization + "/user_timeseries/read"; apiVisualizationScatterPlot = apiVisualization + "/scatter_plot/read"; apiVisualization2dDensity = apiVisualization + "/2d_density/read"; apiVisualizationSurveyResponsePrivacy = apiVisualization + "/survey_responses_privacy_state/read"; apiVisualizationSurveyResponsePrivacyTimeseries = apiVisualization + "/survey_responses_privacy_state_time/read"; }
From source file:com.boylesoftware.web.impl.AbstractRouterConfiguration.java
/** * Create new router configuration object. * * @param sc Servlet context./* w w w. j ava 2 s . co m*/ * @param appServices The application services. * @param argHandlerProvider Controller method argument handler provider. * @param viewSender View sender. * * @throws UnavailableException If configuration is incorrect. */ public AbstractRouterConfiguration(final ServletContext sc, final ApplicationServices appServices, final ControllerMethodArgHandlerProvider argHandlerProvider, final ViewSender viewSender) throws UnavailableException { this.webapp = appServices.getApplication(); final RoutesBuilder routesBuilder = new RoutesBuilder(sc, argHandlerProvider, viewSender); this.buildRoutes(sc, routesBuilder); this.mappings = routesBuilder.getRoutes(); this.loginPageURI = routesBuilder.getLoginPageURI(); final Pattern protectedURIPattern = routesBuilder.getProtectedURIPattern(); final Pattern publicURIPattern = routesBuilder.getPublicURIPattern(); this.protectedURIPattern = (protectedURIPattern != null ? protectedURIPattern : (publicURIPattern != null ? ANY_URI : NO_URI)); this.publicURIPattern = (publicURIPattern != null ? publicURIPattern : (protectedURIPattern != null ? NO_URI : ANY_URI)); final String fullLoginPageURI = (this.loginPageURI != null ? StringUtils.emptyIfNull(sc.getContextPath()) + this.loginPageURI : null); if (fullLoginPageURI != null) { if (this.protectedURIPattern.matcher(fullLoginPageURI).matches() && !this.publicURIPattern.matcher(fullLoginPageURI).matches()) throw new UnavailableException("Provided login page URI" + " requires an authenticated user. Check the protected and" + " public URI patterns."); } final int numMappings = this.mappings.length; this.mappingsById = new HashMap<>(numMappings); for (int i = 0; i < numMappings; i++) { RouteImpl mapping = this.mappings[i]; if ((fullLoginPageURI != null) && mapping.getURIPattern().matcher(fullLoginPageURI).matches()) { switch (mapping.getSecurityMode()) { case DEFAULT: this.mappings[i] = mapping = new RouteImpl(mapping, SecurityMode.FORCE_SSL); break; case FORCE_SSL: break; case FORCE_REQUIRE_AUTH: throw new UnavailableException("Provided login page URI" + " requires an authenticated user. Check the mapping's" + " security mode."); } } if (this.mappingsById.put(mapping.getId(), mapping) != null) throw new UnavailableException("More than one mapping share route id " + mapping.getId() + "."); } this.routerRequestPool = new FastPool<>(new PoolableObjectFactory<RouterRequestImpl>() { @Override public RouterRequestImpl makeNew(final FastPool<RouterRequestImpl> pool, final int pooledObjectId) { return new RouterRequestImpl(pool, pooledObjectId, appServices); } }, "RouterRequestsPool"); }
From source file:com.litt.saap.core.web.listener.InitSystemListener.java
/** * ?.//from w ww . j a v a 2 s . com */ public void contextInitialized(ServletContextEvent event) { super.contextInitialized(event); ServletContext application = event.getServletContext(); //HOME? Configuration config = ConfigManager.getInstance().getConfig(); if (config.isEmpty()) { logger.error("???"); throw new java.lang.RuntimeException("???"); } logger.info("?" + config.getString("system.version")); //homePath = props.getProperty("home.path"); String homePath = config.getString("home.path"); CoreConstants.IS_DEBUG = config.getBoolean("debug", false); SaapConstants.HOME_PATH = homePath; //???? logger.info("?" + homePath); File homeFile = new File(homePath); if (!homeFile.exists()) //??? { homeFile.mkdirs(); } //read license. // File licensePath = new File(homePath, "license"); // File licenseFile = new File(licensePath, "license.xml"); // File publicKeyFile = new File(licensePath, "license.key"); // try { // LicenseManager.reload(licenseFile.getPath(), publicKeyFile.getPath()); // } catch (LicenseException e) { // logger.error("Can't read license file.", e); // } String contextPath = application.getContextPath(); //???APPLICATION ISystemInfoService systemInfoService = BeanManager.getBean("systemInfoService", ISystemInfoService.class); SystemInfoVo systemInfoVo = systemInfoService.getSystemInfo(); systemInfoVo.setBaseUrl(config.getString("baseUrl") + contextPath); systemInfoVo.setHomePath(homePath); application.setAttribute(CoreConstants.APP_SYSTEMINFO, systemInfoVo); //servlet? }
From source file:org.jbpm.formbuilder.server.RESTFormServiceTest.java
public void testGetFormPreviewTranslatorProblem() throws Exception { final Renderer renderer = EasyMock.createMock(Renderer.class); final Translator translator = EasyMock.createMock(Translator.class); final ServletContext context = EasyMock.createMock(ServletContext.class); final HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class); RESTFormService restService = emulateRESTFormService(translator, null, renderer, null); restService.setFormService(new MockFormDefinitionService()); FormRepresentation form = createMockForm("myForm", "key1", "key2"); FormPreviewDTO dto = createFormPreviewDTO(form); TranslatorException exception = new TranslatorException("Something going wrong"); EasyMock.expect(translator.translateForm(EasyMock.eq(form))).andThrow(exception).once(); EasyMock.expect(context.getContextPath()).andReturn("/").anyTimes(); EasyMock.replay(renderer, translator, context, request); Response resp = restService.getFormPreview(dto, "lang", context, request); EasyMock.verify(renderer, translator, context, request); assertNotNull("resp shouldn't be null", resp); assertStatus(resp.getStatus(), Status.INTERNAL_SERVER_ERROR); }