List of usage examples for javax.servlet ServletContext getInitParameter
public String getInitParameter(String name);
String
containing the value of the named context-wide initialization parameter, or null
if the parameter does not exist. From source file:cc.redpen.server.api.RedPenService.java
/** * Create redpens for the given context//from ww w. ja v a2s.com * * @param context the servlet context */ public RedPenService(ServletContext context) { synchronized (redPens) { if (redPens.isEmpty()) { LOG.info("Creating RedPen instances"); try { List<Document> emptyDocuments = new ArrayList<>(); emptyDocuments.add(Document.builder().build()); for (String key : Configuration.getDefaultConfigKeys()) { RedPen redpen = new RedPen( Configuration.builder(key).secure().addAvailableValidatorConfigs().build()); redpen.validate(emptyDocuments); redPens.put(key, redpen); } String configPath = context != null ? context.getInitParameter("redpen.conf.path") : null; if (configPath != null) { LOG.info("Config Path is set to \"{}\"", configPath); Configuration configuration; try { configuration = new ConfigurationLoader().secure().loadFromResource(configPath); } catch (RedPenException rpe) { configuration = new ConfigurationLoader().secure().load(new File(configPath)); } RedPen defaultRedPen = new RedPen(configuration); redPens.put(DEFAULT_LANGUAGE, defaultRedPen); } else { // if config path is not set, fallback to default config path LOG.info("No Config Path set, using default configurations"); redPens.put(DEFAULT_LANGUAGE, redPens.get("en")); } LOG.info("Document Validator Server is running."); } catch (RedPenException e) { LOG.error("Unable to initialize RedPen", e); throw new ExceptionInInitializerError(e); } } } }
From source file:org.apache.ofbiz.order.order.OrderEvents.java
public static String downloadDigitalProduct(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); ServletContext application = session.getServletContext(); Delegator delegator = (Delegator) request.getAttribute("delegator"); GenericValue userLogin = (GenericValue) session.getAttribute("userLogin"); String dataResourceId = request.getParameter("dataResourceId"); try {//from w w w. j av a 2 s .co m // has the userLogin.partyId ordered a product with DIGITAL_DOWNLOAD content associated for the given dataResourceId? GenericValue orderRoleAndProductContentInfo = EntityQuery.use(delegator) .from("OrderRoleAndProductContentInfo") .where("partyId", userLogin.get("partyId"), "dataResourceId", dataResourceId, "productContentTypeId", "DIGITAL_DOWNLOAD", "statusId", "ITEM_COMPLETED") .queryFirst(); if (orderRoleAndProductContentInfo == null) { request.setAttribute("_ERROR_MESSAGE_", "No record of purchase for digital download found (dataResourceId=[" + dataResourceId + "])."); return "error"; } // TODO: check validity based on ProductContent fields: useCountLimit, useTime/useTimeUomId if (orderRoleAndProductContentInfo.getString("mimeTypeId") != null) { response.setContentType(orderRoleAndProductContentInfo.getString("mimeTypeId")); } OutputStream os = response.getOutputStream(); GenericValue dataResource = EntityQuery.use(delegator).from("DataResource") .where("dataResourceId", dataResourceId).cache().queryOne(); Map<String, Object> resourceData = DataResourceWorker.getDataResourceStream(dataResource, "", application.getInitParameter("webSiteId"), UtilHttp.getLocale(request), application.getRealPath("/"), false); os.write(IOUtils.toByteArray((ByteArrayInputStream) resourceData.get("stream"))); os.flush(); } catch (GenericEntityException e) { String errMsg = "Error downloading digital product content: " + e.toString(); Debug.logError(e, errMsg, module); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } catch (GeneralException e) { String errMsg = "Error downloading digital product content: " + e.toString(); Debug.logError(e, errMsg, module); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } catch (IOException e) { String errMsg = "Error downloading digital product content: " + e.toString(); Debug.logError(e, errMsg, module); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } return "success"; }
From source file:org.iterx.miru.support.servlet.dispatcher.context.BootstrapServletContextListener.java
public void contextInitialized(ServletContextEvent servletContextEvent) { try {/*from w w w . j av a 2 s . c o m*/ DispatcherApplicationContext applicationContext; ApplicationContext parentApplicationContext; ServletContext servletContext; String parameter; String path; int next; parentApplicationContext = null; servletContext = servletContextEvent.getServletContext(); path = resolveContextPath(servletContext); next = path.length(); while ((next = path.lastIndexOf('/', next - 1)) > -1) { if ((parentApplicationContext = (ApplicationContext) contexts.get(path.substring(0, next))) != null) break; } applicationContext = ((parentApplicationContext != null) ? new ServletDispatcherApplicationContext(parentApplicationContext, servletContext) : new ServletDispatcherApplicationContext(servletContext)); if ((parameter = servletContext.getInitParameter(ServletDispatcherApplicationContext.BEANS)) != null && applicationContext instanceof Loadable) { URL url; if ((url = (servletContext.getResource(parameter))) != null) ((Loadable) applicationContext).load(new UriStreamResource(url.toURI())); else throw new IOException("Invalid stream [" + parameter + "]"); } if (inheritable) { synchronized (contexts) { contexts.put(path, applicationContext); } } servletContext.setAttribute((DispatcherApplicationContext.class).getName(), applicationContext); } catch (Exception e) { e.printStackTrace(); LOGGER.error("Initialisation failed.", e); throw new RuntimeException("Initialisation failed.", e); } }
From source file:br.bireme.web.AuthenticationServlet.java
/** * Processes requests for both HTTP/*from w ww .j ava 2 s.co m*/ * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding(CODEC); final String username = request.getParameter("email"); final String password = request.getParameter("password"); final String lang = request.getParameter("lang"); final ServletContext context = getServletContext(); final HttpSession session = request.getSession(); final ResourceBundle messages = Tools.getMessages(lang); boolean isAccountsWorking = true; RequestDispatcher dispatcher; session.removeAttribute("collCenter"); session.removeAttribute("user"); if (isAccountsWorking) { if ((username == null) || (username.isEmpty()) || (password == null) || (password.isEmpty())) { response.sendRedirect( "index.jsp?lang=" + lang + "&errMsg=" + messages.getString("login_is_required")); return; } try { final Authentication auth = new Authentication(context.getInitParameter("accounts_host")); final JSONObject user = auth.getUser(username, password); Set<String> centerIds = auth.getCenterIds(user); //if (auth.isAuthenticated(user) && (centerIds != null)) { if (auth.isAuthenticated(user)) { if (centerIds == null) { centerIds = new HashSet<String>(); } centerIds.add(auth.getColCenter(user)); // cc may not belong to a net (it not appear in centerIds) session.setAttribute("user", username); // Login user. session.setAttribute("centerIds", centerIds); dispatcher = context.getRequestDispatcher("/CenterFilterServlet?lang=" + lang); } else { session.removeAttribute("user"); session.removeAttribute("centerIds"); dispatcher = context.getRequestDispatcher( "/index.jsp?lang=" + lang + "&errMsg=" + messages.getString("authentication_failed")); } dispatcher.forward(request, response); } catch (Exception ex) { dispatcher = context.getRequestDispatcher("/index.jsp?lang=" + lang + "&errMsg=" + messages.getString("exception_found") + "<br/><br/>" + ex.getMessage()); dispatcher.forward(request, response); } } else { final Set<String> ccs = new HashSet<String>(); ccs.add("PE1.1"); ccs.add("BR1.1"); dispatcher = context.getRequestDispatcher("/CenterFilterServlet?lang=" + lang); session.setAttribute("user", username); // Login user. session.setAttribute("centerIds", ccs); dispatcher.forward(request, response); } }
From source file:org.traccar.web.server.model.DataServiceImpl.java
@Override public void init() throws ServletException { super.init(); ServletContext servletContext = getServletContext(); modisFilesLocation = servletContext.getInitParameter("modis_files_location"); modisSearchResultLocation = servletContext.getInitParameter("modis_search_result_location"); String persistenceUnit;/*from w ww .ja v a2s .c om*/ try { Context context = new InitialContext(); context.lookup(PERSISTENCE_DATASTORE); persistenceUnit = PERSISTENCE_UNIT_RELEASE; } catch (NamingException e) { persistenceUnit = PERSISTENCE_UNIT_DEBUG; } entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnit); // Create Administrator account EntityManager entityManager = getServletEntityManager(); TypedQuery<User> query = entityManager.createQuery("SELECT x FROM User x WHERE x.login = 'roger'", User.class); List<User> results = query.getResultList(); if (results.isEmpty()) { User user = new User(); user.setLogin("roger"); user.setPassword("roger"); user.setAdmin(true); createUser(entityManager, user); } refreshQuakesTimer.schedule(new TimerTask() { @Override public void run() { loadEarthquakeData(); } }, REFRESH_QUAKES_INTERVAL); // Load earthquake data loadEarthquakeData(); }
From source file:org.apache.cocoon.servlet.RequestProcessor.java
public RequestProcessor(ServletContext servletContext) { this.servletContext = servletContext; this.cocoonBeanFactory = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); this.settings = (Settings) this.cocoonBeanFactory.getBean(Settings.ROLE); this.servletSettings = new ServletSettings(this.settings); final String encoding = this.settings.getContainerEncoding(); if (encoding == null) { this.containerEncoding = "ISO-8859-1"; } else {// w ww .j a v a 2s. c o m this.containerEncoding = encoding; } // Obtain access logger String category = servletContext.getInitParameter("org.apache.cocoon.servlet.logger.access"); if (category == null || category.length() == 0) { category = "access"; } setLogger(LoggerUtils.getChildLogger(this.cocoonBeanFactory, category)); this.processor = getProcessor(); this.environmentContext = new HttpContext(this.servletContext); // get the optional request listener if (this.cocoonBeanFactory.containsBean(RequestListener.ROLE)) { this.requestListener = (RequestListener) this.cocoonBeanFactory.getBean(RequestListener.ROLE); } }
From source file:com.dhcc.framework.web.context.DhccContextLoader.java
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) { Log logger = LogFactory.getLog(DhccContextLoader.class); if (ObjectUtils.identityToString(wac).equals(wac.getId())) { // The application context id is still set to its original default value // -> assign a more useful id based on available information String idParam = sc.getInitParameter(CONTEXT_ID_PARAM); if (idParam != null) { wac.setId(idParam);//w w w .j a v a2 s . c o m } else { // Generate default id... if (sc.getMajorVersion() == 2 && sc.getMinorVersion() < 5) { // Servlet <= 2.4: resort to name specified in web.xml, if any. wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + ObjectUtils.getDisplayString(sc.getServletContextName())); } else { wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + ObjectUtils.getDisplayString(sc.getContextPath())); } } } wac.setServletContext(sc); String initParameter = sc.getInitParameter(CONFIG_LOCATION_PARAM); if (isMicrokernelStart(sc)) { initParameter = "classpath:codeTemplate/applicationSetupContext.xml"; logger.error("because cant't connect to db or setup flg is 0 so init application as Microkernel "); } else { logger.info("initParameter==" + initParameter); } if (initParameter != null) { wac.setConfigLocation(initParameter); } customizeContext(sc, wac); wac.refresh(); }
From source file:it.geosolutions.httpproxy.HTTPProxy.java
/** * Initialize the <code>ProxyServlet</code> * /*from w ww . ja v a 2 s . c om*/ * @param servletConfig The Servlet configuration passed in by the servlet conatiner */ public void init(ServletConfig servletConfig) throws ServletException { super.init(servletConfig); ServletContext context = getServletContext(); String proxyPropPath = context.getInitParameter("proxyPropPath"); proxyConfig = new ProxyConfig(getServletContext(), proxyPropPath); connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setSoTimeout(proxyConfig.getSoTimeout()); params.setConnectionTimeout(proxyConfig.getConnectionTimeout()); params.setMaxTotalConnections(proxyConfig.getMaxTotalConnections()); params.setDefaultMaxConnectionsPerHost(proxyConfig.getDefaultMaxConnectionsPerHost()); //setSystemProxy(params); connectionManager.setParams(params); httpClient = new HttpClient(connectionManager); // // Check for system proxy usage // try { String proxyHost = System.getProperty("http.proxyHost"); int proxyPort = 80; if (proxyHost != null && !proxyHost.isEmpty()) { try { proxyPort = (System.getProperty("http.proxyPort") != null ? Integer.parseInt(System.getProperty("http.proxyPort")) : proxyPort); httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort); } catch (Exception ex) { LOGGER.warning("No proxy port found"); } } } catch (Exception ex) { LOGGER.warning("Exception while setting the system proxy: " + ex.getLocalizedMessage()); } // ////////////////////////////////////////// // Setup the callbacks (in the future this // will be a pluggable lookup). // ////////////////////////////////////////// callbacks = new ArrayList<ProxyCallback>(); callbacks.add(new MimeTypeChecker(proxyConfig)); callbacks.add(new HostNameChecker(proxyConfig)); callbacks.add(new RequestTypeChecker(proxyConfig)); callbacks.add(new MethodsChecker(proxyConfig)); callbacks.add(new HostChecker(proxyConfig)); }
From source file:org.apache.myfaces.custom.roundeddiv.HtmlRoundedDivRenderer.java
private void initCache(ServletContext context) { if (cacheSize != null) { return;/*ww w.j av a2 s . co m*/ } synchronized (imageCache) { if (cacheSize != null) { return; } String param = context.getInitParameter(CACHE_SIZE_KEY); if (cacheSize == null) { cacheSize = new Integer(DEFAULT_CACHE_SIZE); } else { try { cacheSize = new Integer(Integer.parseInt(param)); } catch (NumberFormatException ex) { log.error("Unabled to parse cache size, using default", ex); cacheSize = new Integer(DEFAULT_CACHE_SIZE); } } log.debug("Using a cache of size: " + cacheSize); } }
From source file:org.geowebcache.storage.DefaultStorageFinder.java
/** * Looks for <br>//ww w.j a va2 s . c o m * 1) GEOWEBCACHE_CACHE_DIR<br> * 2) GEOSERVER_DATA_DIR<br> * 3) %TEMP%, $TEMP<br> * <br> * Using<br> * A) Java environment variable<br> * B) Servlet context parameter<br> * C) System environment variable<br> * */ private void determineDefaultPrefix() { ServletContext serlvCtx = context.getServletContext(); final String[] typeStrs = { "Java environment variable ", "Servlet context parameter ", "System environment variable " }; final String[] varStrs = { GWC_CACHE_DIR, GS_DATA_DIR, "TEMP", "TMP" }; String msgPrefix = null; int iVar = 0; for (int i = 0; i < varStrs.length && defaultPrefix == null; i++) { for (int j = 0; j < typeStrs.length && defaultPrefix == null; j++) { String value = null; String varStr = varStrs[i]; String typeStr = typeStrs[j]; switch (j) { case 0: value = System.getProperty(varStr); break; case 1: value = serlvCtx.getInitParameter(varStr); break; case 2: value = System.getenv(varStr); break; } if (value == null || value.equalsIgnoreCase("")) { if (log.isDebugEnabled()) { log.debug(typeStr + varStr + " is unset"); } continue; } File fh = new File(value); // Being a bit pessimistic here msgPrefix = "Found " + typeStr + varStr + " set to " + value; if (!fh.exists()) { log.error(msgPrefix + " , but this path does not exist"); continue; } if (!fh.isDirectory()) { log.error(msgPrefix + " , which is not a directory"); continue; } if (!fh.canWrite()) { log.error(msgPrefix + " , which is not writeable"); continue; } // Sweet, we can work with this this.defaultPrefix = value; iVar = i; } } String logMsg; if (this.defaultPrefix == null) { String tmpDir = System.getProperty("java.io.tmpdir"); if (tmpDir != null) { File temp = new File(tmpDir, "geowebcache"); logMsg = "Reverting to java.io.tmpdir " + this.defaultPrefix + " for storage. " + "Please set " + GWC_CACHE_DIR + "."; if (!temp.exists() && !temp.mkdirs()) { throw new RuntimeException("Can't create " + temp.getAbsolutePath()); } this.defaultPrefix = temp.getAbsolutePath(); } else { logMsg = "Unable to determine temp directory. Proceeding with undefined results."; } } else { switch (iVar) { case 0: // GEOWEBCACHE_CACHE_DIR, do nothing break; case 1: // GEOSERVER_DATA_DIR, prefix this.defaultPrefix = this.defaultPrefix + File.separator + "gwc"; break; case 2: // TEMP directories case 3: this.defaultPrefix = this.defaultPrefix + File.separator + "geowebcache"; } logMsg = msgPrefix + ", using it as the default prefix."; } String warnStr = "*** " + logMsg + " ***"; StringBuilder stars = new StringBuilder(); for (int i = 0; i < warnStr.length(); i++) { stars.append("*"); } log.info(stars.toString()); log.info(warnStr); log.info(stars.toString()); }