List of usage examples for javax.servlet ServletContext getContextPath
public String getContextPath();
From source file:com.dominion.salud.nomenclator.configuration.NOMENCLATORInitializer.java
@Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.scan("com.dominion.salud.nomenclator.configuration"); ctx.setServletContext(servletContext); ctx.refresh();// w w w.j av a 2 s . c om logger.info(" Registrando servlets de configuracion"); ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)); dispatcher.setInitParameter("contextClass", ctx.getClass().getName()); dispatcher.setLoadOnStartup(1); logger.info(" Agregando mapping: /"); dispatcher.addMapping("/"); logger.info(" Agregando mapping: /controller/*"); dispatcher.addMapping("/controller/*"); logger.info(" Agregando mapping: /services/*"); dispatcher.addMapping("/services/*"); servletContext.addListener(new ContextLoaderListener(ctx)); logger.info(" Servlets de configuracion registrados correctamente"); // Configuracion general logger.info(" Iniciando la configuracion del modulo"); NOMENCLATORConstantes._HOME = StringUtils.endsWith(servletContext.getRealPath("/"), File.separator) ? servletContext.getRealPath("/") : servletContext.getRealPath("/") + File.separator; NOMENCLATORConstantes._TEMP = NOMENCLATORConstantes._HOME + "WEB-INF" + File.separator + "temp" + File.separator; NOMENCLATORConstantes._VERSION = ResourceBundle.getBundle("version").getString("version"); NOMENCLATORConstantes._LOGS = NOMENCLATORConstantes._HOME + "WEB-INF" + File.separator + "classes" + File.separator + "logs"; NOMENCLATORConstantes._CONTEXT_NAME = servletContext.getServletContextName(); NOMENCLATORConstantes._CONTEXT_PATH = servletContext.getContextPath(); NOMENCLATORConstantes._CONTEXT_SERVER = servletContext.getServerInfo(); NOMENCLATORConstantes._ENABLE_TECHNICAL_INFORMATION = StringUtils.isNotBlank( ResourceBundle.getBundle("application").getString("nomenclator.enable.technical.information")) ? Boolean.parseBoolean(ResourceBundle.getBundle("application") .getString("nomenclator.enable.technical.information")) : false; PropertyConfigurator.configureAndWatch("log4j"); logger.info(" Configuracion general del sistema"); logger.info(" nomenclator.home: " + NOMENCLATORConstantes._HOME); logger.info(" nomenclator.temp: " + NOMENCLATORConstantes._TEMP); logger.info(" nomenclator.version: " + NOMENCLATORConstantes._VERSION); logger.info(" nomenclator.logs: " + NOMENCLATORConstantes._LOGS); logger.info(" nomenclator.context.name: " + NOMENCLATORConstantes._CONTEXT_NAME); logger.info(" nomenclator.context.path: " + NOMENCLATORConstantes._CONTEXT_PATH); logger.info(" nomenclator.context.server: " + NOMENCLATORConstantes._CONTEXT_SERVER); logger.info(" Parametrizacion del sistema"); logger.info(" nomenclator.enable.technical.information: " + NOMENCLATORConstantes._ENABLE_TECHNICAL_INFORMATION); logger.info(" Modulo configurado correctamente"); logger.info("MODULO INICIADO CORRECTAMENTE"); }
From source file:org.kuali.mobility.tags.PageTag.java
public void doTag() throws JspException { PageContext pageContext = (PageContext) getJspContext(); HttpServletRequest hsr = (HttpServletRequest) pageContext.getRequest(); Cookie cks[] = hsr.getCookies();/* w ww .j ava2 s . c o m*/ if (cks != null) { for (Cookie c : cks) { if (c.getName().equals("jqmHeader")) { jqmHeader = 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"); Locale locale = RequestContextUtils.getLocale((HttpServletRequest) pageContext.getRequest()); MessageSource ms = (MessageSource) ac.getBean("messageSource"); String msgCatString = null; 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().isEmpty()) { setAppcacheEnabled(kmeProperties.getProperty("appcache.enabled", "true")); } LOG.info("param.appcacheEnabled: " + getAppcacheEnabled()); if (!appcacheEnabled.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 + "/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\" />"); addTheme(); // 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/ServerDetails.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>"); if (this.isNative()) { out.println( "<script type=\"text/javascript\" src=\"" + contextPath + "/js/PushConfig.js\"></script>"); } // out.println("<script src=\"http://jsconsole.com/remote.js?2EA94DB3-FD2F-4FF8-B41E-AB2B9A064544\"></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/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>"); } } /* Google Analytics */ String profileId = coreService.findGoogleAnalyticsProfileId().trim(); if (!disableGoogleAnalytics && profileId.length() > 0) { String profileDomain = coreService.getGoogleAnalyticsProfileDomain().trim(); if (coreService.isGoogleUniversalAnalytics() && !profileDomain.isEmpty()) { out.println("<script type=\"text/javascript\">"); out.println("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){"); out.println("(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),"); out.println("m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)"); out.println("})(window,document,'script','//www.google-analytics.com/analytics.js','ga');"); out.println("ga('create', '" + profileId + "', '" + profileDomain + "'); "); out.println("ga('send', 'pageview');"); out.println("</script>"); } else { 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=\"https://maps.google.com/maps/api/js?sensor=true&language=" + getMapLocale() + "\"></script>"); } else { out.println( "<script type=\"text/javascript\" src=\"https://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=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\">"); // 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 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>"); } out.println("<div data-role=\"page\" id=\"" + getId() + "\">"); LOG.info("----" + jqmHeader); if (getJqmHeader() != null && getJqmHeader().equals("hide")) { LOG.info("---- Hide Header"); out.println("<div data-role=\"header\" style=\"display:none\">"); } else if (getJqmHeader() != null && getJqmHeader().equals("fixed")) { LOG.info("---- Fixed Header"); out.println("<div data-role=\"header\" data-position=\"fixed\">"); } else { LOG.info("---- Show Header"); out.println("<div data-role=\"header\">"); } if (isLoginButton() || getAuthMapper().getLoginURL() != null) { if (user == null || user.isPublicUser()) { msgCatString = ms.getMessage("shared.login", null, "Login", locale); out.println("<a href=\"" + (getLoginButtonURL() != null ? getLoginButtonURL() : (getAuthMapper().getLoginURL() != null ? getAuthMapper().getLoginURL() : contextPath + "/login")) + "\" data-role=\"button\" data-icon=\"lock\">" + msgCatString + "</a>"); } else { msgCatString = ms.getMessage("shared.logout", null, "Logout", locale); out.println("<a href=\"" + (getLogoutButtonURL() != null ? getLogoutButtonURL() : (getAuthMapper().getLogoutURL() != null ? getAuthMapper().getLogoutURL() : contextPath + "/logout")) + "\" data-role=\"button\" data-icon=\"unlock\">" + msgCatString + "</a>"); } } if (isBackButton()) { msgCatString = ms.getMessage("shared.back", null, "Back", locale); // out.println("<a href=\"" + (getBackButtonURL() != null ? getBackButtonURL() : "javascript: history.go(-1)") + "\" class=\"ui-btn-left\" data-icon=\"back\" data-iconpos=\"notext\">" + msgCatString + "</a>"); boolean showButton = true; if (null == this.getPhonegap() || "".equalsIgnoreCase(getPhonegap())) { // showButton = true; } else { if (null != kmeProperties) { StringBuilder builder = new StringBuilder("shim.backbutton."); builder.append(this.getPlatform().toLowerCase()); if (kmeProperties.containsKey(builder.toString()) && "false".equalsIgnoreCase(kmeProperties.getProperty(builder.toString()))) { showButton = false; } } } if (showButton) { out.println("<a href=\"" + ((getBackButtonURL() != null && StringUtils.isNotBlank(getBackButtonURL())) ? getBackButtonURL() : "javascript: history.go(-1)") + "\" class=\"ui-btn-left\" data-icon=\"back\" data-iconpos=\"notext\">" + msgCatString + "</a>"); } } out.println("<h1>" + getTitle() + "</h1>"); if (isPreferencesButton()) { if (null != kmeProperties && "true".equalsIgnoreCase(kmeProperties.getProperty("home.preferences.enabled", "true"))) { msgCatString = ms.getMessage("shared.preferences", null, "Preferences", locale); out.println("<a href=\"" + (getPreferencesButtonURL() != null ? getPreferencesButtonURL() : contextPath + "/preferences") + "\" class=\"ui-btn-right\" data-icon=\"gear\" data-iconpos=\"notext\">" + msgCatString + "</a>"); } } if (isHomeButton()) { msgCatString = ms.getMessage("shared.home", null, "Home", locale); // out.println("<a href=\"" + contextPath + "/home\" class=\"ui-btn-right\" data-icon=\"home\" data-iconpos=\"notext\">" + msgCatString + "</a>"); boolean homeButton = true; if (null == this.getPhonegap() || "".equalsIgnoreCase(getPhonegap())) { // showButton = true; } else { if (null != kmeProperties) { StringBuilder builder = new StringBuilder("shim.homebutton."); builder.append(this.getPlatform().toLowerCase()); if (kmeProperties.containsKey(builder.toString()) && "false".equalsIgnoreCase(kmeProperties.getProperty(builder.toString()))) { homeButton = false; } } } if (homeButton) { out.println("<a href=\"" + contextPath + "/home\" class=\"ui-btn-right\" data-icon=\"home\" data-iconpos=\"notext\">" + msgCatString + "</a>"); } } out.println("</div>"); getJspBody().invoke(out); out.println("</div>"); out.println("</body>"); out.println("</html>"); } catch (Exception e) { LOG.error(e.getMessage(), e); } }
From source file:com.dlshouwen.jspc.zjpc.controller.ExpreviewController.java
private String getItemForHtml(List<EvalItem> items, ServletContext sc) { String result = "", preHtml, sufHtml; sufHtml = "</tr>" + "</table>" + "</div>" + "</li>"; if (!items.equals(null) && items.size() > 0) { for (int i = 0; i < items.size(); i++) { preHtml = "<li class='item-table-list-li'>" + "<div class='item-table-list-box'>" // + "<i class='fa fa-edit' style='display:none;' onclick=\"editItem('"+items.get(i).getEvalItem_id()+"','"+items.get(i).getType()+"')\"></i>" // + "<i class='fa fa-times' style='display:none;' id='"+items.get(i).getEvalItem_id()+"' onclick=\"deleteItem('"+items.get(i).getEvalItem_id()+"')\"></i>" + "<table class='table table-responsive item-table-list' width='100%' border='0' cellspacing='0' cellpadding='0'>" + "<tr>"; String bDate = DateUtils.getYearMonth(items.get(i).getBeginDate()); String eDate = DateUtils.getYearMonth(items.get(i).getEndDate()); String level = CodeTableUtils.getValue(sc, "ryjb", items.get(i).getLevel()); String grade = CodeTableUtils.getValue(sc, "hjdj", items.get(i).getGrade()); level = StringUtils.isEmpty(level) ? "" : level; grade = StringUtils.isEmpty(grade) ? "" : grade; result += preHtml;//from w ww . ja v a2s. c o m result += "<td class='first_td'>" + bDate + "-" + eDate + "</td>"; result += "<td>" + items.get(i).getName() + "</td>"; result += "<td>" + level + grade + "</td>"; result += "<td><a href='" + sc.getContextPath() + "/jspc/zwpc/zwpc/downloadFile?itemId=" + items.get(i).getEvalItem_id() + "' class='table-tc-fj-open' ></a></td>"; result += sufHtml; } } else { result = "<div class='div_zanwu'></div>"; } return result; }
From source file:org.epics.archiverappliance.config.DefaultConfigService.java
@Override public void initialize(ServletContext sce) throws ConfigException { this.servletContext = sce; String contextPath = sce.getContextPath(); logger.info("DefaultConfigService was created with a servlet context " + contextPath); try {/* w w w . j ava 2 s . co m*/ String pathToVersionTxt = sce.getRealPath("ui/comm/version.txt"); logger.debug("The full path to the version.txt is " + pathToVersionTxt); List<String> lines = Files.readAllLines(Paths.get(pathToVersionTxt), Charset.forName("UTF-8")); for (String line : lines) { configlogger.info(line); } } catch (Throwable t) { logger.fatal("Unable to determine appliance version", t); } try { // We first try Java system properties for this appliance's identity // If a property is not defined, then we check the environment. // This gives us the ability to cater to unit tests as well as running using buildAndDeploy scripts without touching the server.xml file. // Probably not the most standard way but suited to this need. // Finally, we use the local machine's hostname as the myidentity. myIdentity = System.getProperty(ARCHAPPL_MYIDENTITY); if (myIdentity == null) { myIdentity = System.getenv(ARCHAPPL_MYIDENTITY); if (myIdentity != null) { logger.info("Obtained my identity from environment variable " + myIdentity); } else { logger.info("Using the local machine's hostname " + myIdentity + " as my identity"); myIdentity = InetAddress.getLocalHost().getCanonicalHostName(); } if (myIdentity == null) { throw new ConfigException("Unable to determine identity of this appliance"); } } else { logger.info("Obtained my identity from Java system properties " + myIdentity); } logger.info("My identity is " + myIdentity); } catch (Exception ex) { String msg = "Cannot determine this appliance's identity using either the environment variable " + ARCHAPPL_MYIDENTITY + " or the java system property " + ARCHAPPL_MYIDENTITY; configlogger.fatal(msg); throw new ConfigException(msg, ex); } // Appliances should be local and come straight from persistence. try { appliances = AppliancesList.loadAppliancesXML(servletContext); } catch (Exception ex) { throw new ConfigException("Exception loading appliances.xml", ex); } myApplianceInfo = appliances.get(myIdentity); if (myApplianceInfo == null) throw new ConfigException("Unable to determine applianceinfo using identity " + myIdentity); configlogger.info("My identity is " + myApplianceInfo.getIdentity() + " and my mgmt URL is " + myApplianceInfo.getMgmtURL()); // To make sure we are not starting multiple appliance with the same identity, we make sure that the hostnames match try { String machineHostName = InetAddress.getLocalHost().getCanonicalHostName(); String[] myAddrParts = myApplianceInfo.getClusterInetPort().split(":"); String myHostNameFromInfo = myAddrParts[0]; if (myHostNameFromInfo.equals("localhost")) { logger.debug( "Using localhost for the cluster inet port. If you are indeed running a cluster, the cluster members will not join the cluster."); } else if (myHostNameFromInfo.equals(machineHostName)) { logger.debug( "Hostname from config and hostname from InetAddress match exactly; we are correctly configured " + machineHostName); } else if (InetAddressValidator.getInstance().isValid(myHostNameFromInfo)) { logger.debug("Using ipAddress for cluster config " + myHostNameFromInfo); } else { String msg = "The hostname from appliances.xml is " + myHostNameFromInfo + " and from a call to InetAddress.getLocalHost().getCanonicalHostName() (typially FQDN) is " + machineHostName + ". These are not identical. They are probably equivalent but to prevent multiple appliances binding to the same identity we enforce this equality."; configlogger.fatal(msg); throw new ConfigException(msg); } } catch (UnknownHostException ex) { configlogger.error( "Got an UnknownHostException when trying to determine the hostname. This happens when DNS is not set correctly on this machine (for example, when using VM's. See the documentation for InetAddress.getLocalHost().getCanonicalHostName()"); } try { String archApplPropertiesFileName = System.getProperty(ARCHAPPL_PROPERTIES_FILENAME); if (archApplPropertiesFileName == null) { archApplPropertiesFileName = System.getenv(ARCHAPPL_PROPERTIES_FILENAME); } if (archApplPropertiesFileName == null) { archApplPropertiesFileName = new URL(this.getClass().getClassLoader() .getResource(DEFAULT_ARCHAPPL_PROPERTIES_FILENAME).toString()).getPath(); configlogger.info( "Loading archappl.properties from the webapp classpath " + archApplPropertiesFileName); } else { configlogger.info("Loading archappl.properties using the environment/JVM property from " + archApplPropertiesFileName); } try (InputStream is = new FileInputStream(new File(archApplPropertiesFileName))) { archapplproperties.load(is); configlogger.info( "Done loading installation specific properties file from " + archApplPropertiesFileName); } catch (Exception ex) { throw new ConfigException( "Exception loading installation specific properties file " + archApplPropertiesFileName, ex); } } catch (ConfigException cex) { throw cex; } catch (Exception ex) { configlogger.fatal("Exception loading the appliance properties file", ex); } switch (contextPath) { case "/mgmt": warFile = WAR_FILE.MGMT; this.mgmtRuntime = new MgmtRuntimeState(this); break; case "/engine": warFile = WAR_FILE.ENGINE; this.engineContext = new EngineContext(this); break; case "/retrieval": warFile = WAR_FILE.RETRIEVAL; this.retrievalState = new RetrievalState(this); break; case "/etl": this.etlPVLookup = new PBThreeTierETLPVLookup(this); warFile = WAR_FILE.ETL; break; default: logger.error("We seem to have introduced a new component into the system " + contextPath); } String pvName2KeyMappingClass = this.getInstallationProperties() .getProperty(ARCHAPPL_PVNAME_TO_KEY_MAPPING_CLASSNAME); if (pvName2KeyMappingClass == null || pvName2KeyMappingClass.equals("") || pvName2KeyMappingClass.length() < 1) { logger.info("Using the default key mapping class"); pvName2KeyConverter = new ConvertPVNameToKey(); pvName2KeyConverter.initialize(this); } else { try { logger.info("Using " + pvName2KeyMappingClass + " as the name to key mapping class"); pvName2KeyConverter = (PVNameToKeyMapping) Class.forName(pvName2KeyMappingClass).newInstance(); pvName2KeyConverter.initialize(this); } catch (Exception ex) { logger.fatal("Cannot initialize pv name to key mapping class " + pvName2KeyMappingClass, ex); throw new ConfigException( "Cannot initialize pv name to key mapping class " + pvName2KeyMappingClass, ex); } } String runtimeFieldsListStr = this.getInstallationProperties() .getProperty("org.epics.archiverappliance.config.RuntimeKeys"); if (runtimeFieldsListStr != null && !runtimeFieldsListStr.isEmpty()) { logger.debug("Got runtime fields from the properties file " + runtimeFieldsListStr); String[] runTimeFieldsArr = runtimeFieldsListStr.split(","); for (String rf : runTimeFieldsArr) { this.runTimeFields.add(rf.trim()); } } startupExecutor = Executors.newScheduledThreadPool(1, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("Startup executor"); return t; } }); this.addShutdownHook(new Runnable() { @Override public void run() { logger.info("Shutting down startup scheduled executor..."); startupExecutor.shutdown(); } }); this.startupState = STARTUP_SEQUENCE.READY_TO_JOIN_APPLIANCE; if (this.warFile == WAR_FILE.MGMT) { logger.info("Scheduling webappReady's for the mgmt webapp "); MgmtPostStartup mgmtPostStartup = new MgmtPostStartup(this); ScheduledFuture<?> postStartupFuture = startupExecutor.scheduleAtFixedRate(mgmtPostStartup, 10, 20, TimeUnit.SECONDS); mgmtPostStartup.setCancellingFuture(postStartupFuture); } else { logger.info("Scheduling webappReady's for the non-mgmt webapp " + this.warFile.toString()); NonMgmtPostStartup nonMgmtPostStartup = new NonMgmtPostStartup(this, this.warFile.toString()); ScheduledFuture<?> postStartupFuture = startupExecutor.scheduleAtFixedRate(nonMgmtPostStartup, 10, 20, TimeUnit.SECONDS); nonMgmtPostStartup.setCancellingFuture(postStartupFuture); } // Measure some JMX metrics once a minute startupExecutor.scheduleAtFixedRate(new Runnable() { @Override public void run() { processMetrics.takeMeasurement(); } }, 60, 60, TimeUnit.SECONDS); }
From source file:net.bull.javamelody.TestMonitoringFilter.java
/** * Initialisation.//from w w w. j a va2 s . c o m * @throws ServletException e */ @Before public void setUp() throws ServletException { try { final Field field = MonitoringFilter.class.getDeclaredField("instanceCreated"); field.setAccessible(true); field.set(null, false); } catch (final IllegalAccessException e) { throw new IllegalStateException(e); } catch (final NoSuchFieldException e) { throw new IllegalStateException(e); } final FilterConfig config = createNiceMock(FilterConfig.class); final ServletContext context = createNiceMock(ServletContext.class); expect(config.getServletContext()).andReturn(context).anyTimes(); expect(config.getFilterName()).andReturn(FILTER_NAME).anyTimes(); // anyTimes sur getInitParameter car TestJdbcDriver a pu fixer la proprit systme false expect(context.getInitParameter(Parameters.PARAMETER_SYSTEM_PREFIX + Parameter.DISABLED.getCode())) .andReturn(null).anyTimes(); expect(config.getInitParameter(Parameter.DISABLED.getCode())).andReturn(null).anyTimes(); expect(context.getMajorVersion()).andReturn(2).anyTimes(); expect(context.getMinorVersion()).andReturn(5).anyTimes(); expect(context.getServletContextName()).andReturn("test webapp").anyTimes(); // mockJetty pour avoir un applicationServerIconName dans JavaInformations expect(context.getServerInfo()).andReturn("mockJetty").anyTimes(); // dependencies pour avoir des dpendances dans JavaInformations final Set<String> dependencies = new LinkedHashSet<String>( Arrays.asList("/WEB-INF/lib/jrobin.jar", "/WEB-INF/lib/javamelody.jar")); // et flags pour considrer que les ressources pom.xml et web.xml existent JavaInformations.setWebXmlExistsAndPomXmlExists(true, true); expect(context.getResourcePaths("/WEB-INF/lib/")).andReturn(dependencies).anyTimes(); expect(context.getContextPath()).andReturn(CONTEXT_PATH).anyTimes(); monitoringFilter = new MonitoringFilter(); monitoringFilter.setApplicationType("Test"); replay(config); replay(context); monitoringFilter.init(config); verify(config); verify(context); }
From source file:org.plutext.htmleditor.Load.java
@SuppressWarnings("deprecation") @POST/*from w w w . j a v a 2s .c o m*/ // @Consumes("multipart/form-data") @Produces({ "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "text/html" }) public Response processForm(@Context HttpServletRequest request, @Context HttpServletResponse response, @Context ServletContext servletContext, @FormDataParam("docxfile") InputStream docxInputStream, @FormDataParam("docxfile") FormDataContentDisposition docxFileDetail, @FormDataParam("adv") String editorHtml) throws Docx4JException, IOException { try { LoginCredentials currentUser = (LoginCredentials) request.getSession() .getAttribute("currentSessionCredentials"); String openFilePath = currentUser.getProjFolderPath(); HttpSession session = request.getSession(true); final WordprocessingMLPackage wordMLPackage; WordprocessingMLPackage tmpPkg; LoadFromZipNG loader = new LoadFromZipNG(); //JSONParser parser = new JSONParser(); // pathWar webapps\CitelumApp\ // String pathWorkspace = "C:\\Users\\Project 08\\workspace\\Git\\CITELUM\\CitelumApp\\WebContent\\"; // reads the selected file String loadPath = openFilePath; //============================================================================== CHANGE PATH HERE ================================== //============================================================================== CHANGE PATH HERE ================================== //============================================================================== CHANGE PATH HERE ================================== //Object obj = parser.parse(new FileReader(pathWar + "views\\selectedLoad.txt")); //============================================================================== CHANGE PATH HERE ================================== //============================================================================== CHANGE PATH HERE ================================== //============================================================================== CHANGE PATH HERE ================================== //Object obj = parser.parse(new FileReader(pathWorkspace + "views\\selectedLoad.txt")); //JSONObject jsonObject = (JSONObject) obj; //String name = (String) jsonObject.get("load"); //System.out.println(name); // Path the Template folder - only missing the selected file name tmpPkg = (WordprocessingMLPackage) loader.get(loadPath); wordMLPackage = tmpPkg; // Store the docx, so we can later inject XHTML into it... session.setAttribute("docx", wordMLPackage); Editor editor = new Editor(); Editor.setContextPath(servletContext.getContextPath()); ResponseBuilder builder; if (editorHtml != null && editorHtml.equals("bare") && chapValString != null) { builder = editor.streamDocxAsHtml(wordMLPackage, session, EditorHTML.BARE, response); } else { builder = editor.streamDocxAsHtml(wordMLPackage, session, EditorHTML.CKEditor3, response); } return builder.build(); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); response.sendRedirect("../web/saveTemplateFirst"); throw new WebApplicationException(new Docx4JException(e.getMessage(), e), Status.INTERNAL_SERVER_ERROR); } }
From source file:com.boylesoftware.web.impl.RouteImpl.java
/** * Create new mapping.//from w w w.j a va 2s . c om * * @param sc Servlet context. * @param id Route id, or {@code null} to auto-generate based on the URI * pattern. * @param uriPattern Request URI pattern, which is a server root relative * URI that can optionally contain URI parameter placeholders. Each * placeholder is an expression surrounded by curly braces. Inside curly * braces there is the parameter name and optionally, separated by a colon, * the value regular expression. The regular expression must not contain any * capturing groups and if the expression contains curly braces, they must * be balanced. If the parameter name is empty, the value is not converted * to a request parameter. If the regular expression is unspecified, regular * expression that matches anything except "/" is used. Each URI parameter * is converted to a regular request parameter with the specified name. * @param securityMode Security mode. * @param commonScript Additional logic associated with the mapping, or * {@code null} if none. If specified, the script is executed each time for * the matched request before the controller is called and the view is sent * back to the client. * @param controller Controller, or {@code null} if no controller is * associated with the mapped resource. * @param argHandlerProvider Controller method argument handler provider to * use. * @param viewIdPattern Mapped resource view id. The id may contain * placeholders for request attributes and parameters in curly braces with * the attribute or parameter name inside. Attributes take precedence over * parameters. * @param viewSender View sender to use to send the view to the client. * @param viewScript Additional logic associated with the view, or * {@code null} if none. If specified, the script is executed each time * before the view is sent to the client. The script's purpose it to prepare * data used by the view. * * @throws UnavailableException If an error happens. */ RouteImpl(final ServletContext sc, final String id, final String uriPattern, final SecurityMode securityMode, final Script commonScript, final Object controller, final ControllerMethodArgHandlerProvider argHandlerProvider, final String viewIdPattern, final ViewSender viewSender, final Script viewScript) throws UnavailableException { // parse URI pattern and template final StringBuilder uriTemplateSB = new StringBuilder(); final StringBuilder uriPatternSB = new StringBuilder(); final List<String> uriParamNamesList = new ArrayList<>(); final StringBuilder paramNameSB = new StringBuilder(); final StringBuilder paramPatternSB = new StringBuilder(); final int patternLen = uriPattern.length(); uriPatternSB.append("\\Q"); for (int cInd = 0; cInd < patternLen; cInd++) { final char c = uriPattern.charAt(cInd); if (c == '{') { try { paramNameSB.setLength(0); paramPatternSB.setLength(0); StringBuilder curSB = paramNameSB; int balance = 1; while (balance > 0) { final char c1 = uriPattern.charAt(++cInd); switch (c1) { case '{': balance++; curSB.append(c1); break; case '}': if (--balance > 0) curSB.append(c1); break; case ':': if (curSB != paramPatternSB) curSB = paramPatternSB; else curSB.append(c1); break; default: curSB.append(c1); } } } catch (final IndexOutOfBoundsException e) { LogFactory.getLog(this.getClass()).error("error parsing mapping URI pattern", e); throw new UnavailableException("Unbalanced curly braces in URI pattern \"" + uriPattern + "\" at position " + cInd + "."); } uriParamNamesList.add(paramNameSB.length() > 0 ? paramNameSB.toString() : null); uriPatternSB.append("\\E(").append(paramPatternSB.length() > 0 ? paramPatternSB : "[^/]+") .append(")\\Q"); uriTemplateSB.append("%"); } else { // character outside parameter placeholder uriPatternSB.append(c); uriTemplateSB.append(c); } } uriPatternSB.append("\\E"); this.uriPattern = Pattern.compile(uriPatternSB.toString()); this.uriParamNames = uriParamNamesList.toArray(new String[uriParamNamesList.size()]); this.uriTemplate = uriTemplateSB.toString(); // route id this.id = (id != null ? id : this.uriTemplate.substring(StringUtils.emptyIfNull(sc.getContextPath()).length())); // save security mode this.securityMode = securityMode; // save the script this.script = commonScript; // create controller handler this.controllerHandler = (controller != null ? new ControllerHandlerImpl(sc, controller, argHandlerProvider) : null); // create view handler this.viewHandler = new ViewHandlerImpl(viewIdPattern, viewScript, viewSender); // initially the mapping has not been matched this.numMatched = new AtomicLong(); }
From source file:org.wso2.carbon.apimgt.webapp.publisher.lifecycle.listener.APIPublisherLifecycleListener.java
@Override public void lifecycleEvent(LifecycleEvent lifecycleEvent) { if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType()) && WebappPublisherConfig.getInstance().isPublished()) { StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); ServletContext servletContext = context.getServletContext(); String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); String profile = System.getProperty(PROPERTY_PROFILE); if (WebappPublisherConfig.getInstance().getProfiles().getProfile().contains(profile.toLowerCase()) && isManagedApi) { try { AnnotationProcessor annotationProcessor = new AnnotationProcessor(context); Set<String> annotatedSwaggerAPIClasses = annotationProcessor .scanStandardContext(io.swagger.annotations.SwaggerDefinition.class.getName()); List<APIResourceConfiguration> apiDefinitions = annotationProcessor .extractAPIInfo(servletContext, annotatedSwaggerAPIClasses); for (APIResourceConfiguration apiDefinition : apiDefinitions) { APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition); APIPublisherUtil.setResourceAuthTypes(servletContext, apiConfig); try { int tenantId = APIPublisherDataHolder.getInstance().getTenantManager() .getTenantId(apiConfig.getTenantDomain()); boolean isTenantActive = APIPublisherDataHolder.getInstance().getTenantManager() .isTenantActive(tenantId); if (isTenantActive) { boolean isServerStarted = APIPublisherDataHolder.getInstance().isServerStarted(); if (isServerStarted) { APIPublisherService apiPublisherService = APIPublisherDataHolder.getInstance() .getApiPublisherService(); if (apiPublisherService == null) { throw new IllegalStateException( "API Publisher service is not initialized properly"); }//from ww w. j a v a2 s. c o m apiPublisherService.publishAPI(apiConfig); } else { if (log.isDebugEnabled()) { log.debug("Server has not started yet. Hence adding API '" + apiConfig.getName() + "' to the queue"); } APIPublisherDataHolder.getInstance().getUnpublishedApis().push(apiConfig); } } else { log.error("No tenant [" + apiConfig.getTenantDomain() + "] " + "found when publishing the Web app"); } } catch (Throwable e) { log.error("Error occurred while publishing API '" + apiConfig.getName() + "' with the context '" + apiConfig.getContext() + "' and version '" + apiConfig.getVersion() + "'", e); } } } catch (IOException e) { log.error("Error encountered while discovering annotated classes", e); } catch (ClassNotFoundException e) { log.error("Error while scanning class for annotations", e); } catch (UserStoreException e) { log.error("Error while retrieving tenant admin user for the tenant domain" + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(), e); } catch (Throwable e) { // This is done to stop tomcat failure if a webapp failed to publish apis. log.error("Failed to Publish api from " + servletContext.getContextPath(), e); } } } }
From source file:io.joynr.runtime.MessagingServletConfig.java
@Override public void contextInitialized(ServletContextEvent servletContextEvent) { ServletContext servletContext = servletContextEvent.getServletContext(); // properties from appProperties will extend and override the default // properties Properties properties = new LowerCaseProperties( PropertyLoader.loadProperties(DEFAULT_SERVLET_MESSAGING_PROPERTIES)); String appPropertiesFileName = servletContext.getInitParameter("properties"); if (appPropertiesFileName != null) { Properties appProperties = ServletPropertyLoader.loadProperties(appPropertiesFileName, servletContext); properties.putAll(appProperties); } else {/*w w w .jav a 2s.co m*/ logger.warn("to load properties, set the initParameter 'properties' "); } // add OS environment properties properties.putAll(System.getenv()); servletModuleName = properties.getProperty(INIT_PARAM_SERVLET_MODULE_CLASSNAME); servletModuleName = servletModuleName == null ? DEFAULT_SERVLET_MODULE_NAME : servletModuleName; // create a reflection set used to find // * all plugin application classes implementing the JoynApplication interface // * all servlets annotated as WebServlet // * the class implementing JoynrInjectorFactory (should be only one) Object[] appPackages = mergeAppPackages(properties); // Add Java system properties (set with -D) properties.putAll(System.getProperties()); // TODO if reflections is ever a performance problem, can statically scan and save the reflections data using // Maven, // then work on the previously scanned data // see: https://code.google.com/p/reflections/wiki/UseCases Reflections reflections = new Reflections("io.joynr.runtime", appPackages); final Set<Class<?>> classesAnnotatedWithWebServlet = reflections .getTypesAnnotatedWith(JoynrWebServlet.class); final Set<Class<?>> classesAnnotatedWithProvider = reflections .getTypesAnnotatedWith(javax.ws.rs.ext.Provider.class); // The jerseyServletModule injects the servicing classes using guice, // instead of letting jersey do it natively jerseyServletModule = new AbstractJoynrServletModule() { @SuppressWarnings("unchecked") @Override protected void configureJoynrServlets() { bind(GuiceContainer.class); bind(JacksonJsonProvider.class).asEagerSingleton(); bind(MessagingService.class); //get all classes annotated with @Provider and bind them for (Class<?> providerClass : classesAnnotatedWithProvider) { bind(providerClass).in(Scopes.SINGLETON); } for (Class<?> webServletClass : classesAnnotatedWithWebServlet) { if (!HttpServlet.class.isAssignableFrom(webServletClass)) { continue; } bind(webServletClass); JoynrWebServlet webServletAnnotation = webServletClass.getAnnotation(JoynrWebServlet.class); if (webServletAnnotation == null) { logger.error("webServletAnnotation was NULL."); continue; } serve(webServletAnnotation.value()).with((Class<? extends HttpServlet>) webServletClass); } } // this @SuppressWarnings is needed for the build on jenkins @SuppressWarnings("unused") @Provides public IServletMessageReceivers providesMessageReceivers() { return messageReceivers; } }; Class<?> servletModuleClass = null; Module servletModule = null; try { servletModuleClass = this.getClass().getClassLoader().loadClass(servletModuleName); servletModule = (Module) servletModuleClass.newInstance(); } catch (ClassNotFoundException e) { logger.debug("Servlet module class not found will use default configuration"); } catch (Exception e) { logger.error("", e); } if (servletModule == null) { servletModule = new EmptyModule(); } properties.put(MessagingPropertyKeys.PROPERTY_SERVLET_CONTEXT_ROOT, servletContext.getContextPath()); String hostPath = properties.getProperty(MessagingPropertyKeys.PROPERTY_SERVLET_HOST_PATH); if (hostPath == null) { hostPath = properties.getProperty("hostpath"); } if (hostPath != null) { properties.setProperty(MessagingPropertyKeys.PROPERTY_SERVLET_HOST_PATH, hostPath); } // find all plugin application classes implementing the JoynApplication interface Set<Class<? extends JoynrApplication>> joynrApplicationsClasses = reflections .getSubTypesOf(JoynrApplication.class); Set<Class<? extends AbstractJoynrInjectorFactory>> joynrInjectorFactoryClasses = reflections .getSubTypesOf(AbstractJoynrInjectorFactory.class); assert (joynrInjectorFactoryClasses.size() == 1); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { } }); AbstractJoynrInjectorFactory injectorFactory = injector .getInstance(joynrInjectorFactoryClasses.iterator().next()); appLauncher = injector.getInstance(JoynrApplicationLauncher.class); logger.info("starting joynr with properties: {}", properties); appLauncher.init(properties, joynrApplicationsClasses, injectorFactory, Modules.override(jerseyServletModule, new CCInProcessRuntimeModule()).with(servletModule, new ServletMessagingModule())); super.contextInitialized(servletContextEvent); }
From source file:org.apache.marmotta.platform.core.startup.MarmottaStartupService.java
/** * Startup the Apache Marmotta Configuration. This method ensures that the Apache Marmotta home directory is created and the * ConfigurationService is properly initialised. It must be called first in the startup sequence. * The parameters home and configurationOverride can be used to override the default settings * of the Apache Marmotta.// w ww.java2 s .c o m * * @param home home directory of the Apache Marmotta instance (may be null, in which case the default will be used) * @param configurationOverride configuration options that should override the default values from default-config.properties (may be null) * @param context the servlet context the Apache Marmotta is running in (may be null) */ public void startupConfiguration(String home, Configuration configurationOverride, ServletContext context) { lock.lock(); //to set config version number String versionNumber = DEFAULT_KIWI_VERSION; try { if (configurationStarted) { log.warn("Apache Marmotta Startup: configuration already started; ignoring second request"); return; } ModuleConfiguration coreConfiguration = moduleService.getModuleConfiguration(this.getClass()); if (coreConfiguration.hasBuildInfo()) { log.info("Apache Marmotta Core Version {} starting up ... ", coreConfiguration.getModuleVersion()); log.info("Build Information:"); log.info(" - Build User: {}", coreConfiguration.getBuildUser()); log.info(" - Build Host: {}", coreConfiguration.getBuildHost()); log.info(" - Build Time: {}", coreConfiguration.getBuildTimestamp()); log.info(" - Build OS: {}", coreConfiguration.getBuildOS()); log.info(" - Revision: {}", coreConfiguration.getBuildRevisionHash()); versionNumber = coreConfiguration.getModuleVersion(); } else { log.info("Apache Marmotta Core (Development Version) starting up ... "); } //TODO: refactor this code if (StringUtils.isBlank(home)) { home = System.getProperty("marmotta.home"); if (StringUtils.isNotBlank(home)) { log.info("Configured working directory {} from system property marmotta.home", home); } else { home = System.getProperty("lmf.home"); if (StringUtils.isNotBlank(home)) { log.info("Configured working directory {} from system property lmf.home", home); } else { home = System.getProperty("kiwi.home"); if (StringUtils.isNotBlank(home)) { log.info("Configured working directory {} from system property kiwi.home", home); } else { home = System.getenv("MARMOTTA_HOME"); if (StringUtils.isNotBlank(home)) { log.info("Configured working directory {} from environment variable MARMOTTA_HOME", home); } else { home = System.getenv("LMF_HOME"); if (StringUtils.isNotBlank(home)) { log.info("Configured working directory {} from environment variable LMF_HOME", home); } else { home = System.getenv("KIWI_HOME"); if (StringUtils.isNotBlank(home)) { log.info( "Configured working directory {} from environment variable KIWI_HOME", home); } else { if (context != null) { home = context.getInitParameter("marmotta.home"); if (StringUtils.isNotBlank(home)) { log.info( "Configured working directory {} from servlet context parameter marmotta.home", home); } } else { log.error( "could not determine Apache Marmotta home directory, please set the environment variable MARMOTTA_HOME"); } } } } } } } } if (StringUtils.isNotBlank(home)) { if (home.startsWith("~" + File.separator)) { home = System.getProperty("user.home") + home.substring(1); } configurationService.setHome(home); } else { log.error("home directory not properly initialized!!!"); } if (context != null) { configurationService.setServletContext(context); } configurationService.initialize(home, configurationOverride); configurationService.setConfiguration("kiwi.version", versionNumber); if (context != null) { configurationService.setConfiguration("kiwi.path", context.getContextPath()); // register the systray links provided by the different components Map<String, String> demoLinks = new HashMap<>(); Map<String, String> adminLinks = new HashMap<>(); for (MarmottaSystrayLink link : CDIContext.getInstances(MarmottaSystrayLink.class)) { if (link.getSection() == MarmottaSystrayLink.Section.DEMO) { demoLinks.put(link.getLabel(), link.getLink()); } else if (link.getSection() == MarmottaSystrayLink.Section.ADMIN) { adminLinks.put(link.getLabel(), link.getLink()); } } context.setAttribute("systray.admin", adminLinks); context.setAttribute("systray.demo", demoLinks); } configurationStarted = true; } finally { lock.unlock(); } }