List of usage examples for javax.servlet ServletContext getAttribute
public Object getAttribute(String name);
null
if there is no attribute by that name. From source file:info.magnolia.cms.beans.config.PropertiesInitializer.java
/** * Returns the property files configuration string passed, replacing all the needed values: ${servername} will be * reaplced with the name of the server, ${webapp} will be replaced with webapp name, ${systemProperty/*} will be * replaced with the corresponding system property, ${env/*} will be replaced with the corresponding environment property, * and ${contextAttribute/*} and ${contextParam/*} will be replaced with the corresponding attributes or parameters * taken from servlet context./*from w w w .ja va 2s. c om*/ * This can be very useful for all those application servers that has multiple instances on the same server, like * WebSphere. Typical usage in this case: * <code>WEB-INF/config/${servername}/${contextAttribute/com.ibm.websphere.servlet.application.host}/magnolia.properties</code> * * @param context Servlet context * @param servername Server name * @param webapp Webapp name * @param propertiesFilesString a comma separated list of paths. * @return Property file configuration string with everything replaced. * * @deprecated since 4.5, this is done by {@link info.magnolia.init.DefaultMagnoliaPropertiesResolver#DefaultMagnoliaPropertiesResolver}. * Note: when remove this class and method, this code will need to be cleaned up and moved to info.magnolia.init.DefaultMagnoliaPropertiesResolver */ public static String processPropertyFilesString(ServletContext context, String servername, String webapp, String propertiesFilesString, String contextPath) { // Replacing basic properties. propertiesFilesString = StringUtils.replace(propertiesFilesString, "${servername}", servername); //$NON-NLS-1$ propertiesFilesString = StringUtils.replace(propertiesFilesString, "${webapp}", webapp); //$NON-NLS-1$ propertiesFilesString = StringUtils.replace(propertiesFilesString, "${contextPath}", contextPath); // Replacing servlet context attributes (${contextAttribute/something}) String[] contextAttributeNames = getNamesBetweenPlaceholders(propertiesFilesString, CONTEXT_ATTRIBUTE_PLACEHOLDER_PREFIX); if (contextAttributeNames != null) { for (String ctxAttrName : contextAttributeNames) { if (ctxAttrName != null) { // Some implementation may not accept a null as attribute key, but all should accept an empty // string. final String originalPlaceHolder = PLACEHOLDER_PREFIX + CONTEXT_ATTRIBUTE_PLACEHOLDER_PREFIX + ctxAttrName + PLACEHOLDER_SUFFIX; final Object attrValue = context.getAttribute(ctxAttrName); if (attrValue != null) { propertiesFilesString = propertiesFilesString.replace(originalPlaceHolder, attrValue.toString()); } } } } // Replacing servlet context parameters (${contextParam/something}) String[] contextParamNames = getNamesBetweenPlaceholders(propertiesFilesString, CONTEXT_PARAM_PLACEHOLDER_PREFIX); if (contextParamNames != null) { for (String ctxParamName : contextParamNames) { if (ctxParamName != null) { // Some implementation may not accept a null as param key, but an empty string? TODO Check. final String originalPlaceHolder = PLACEHOLDER_PREFIX + CONTEXT_PARAM_PLACEHOLDER_PREFIX + ctxParamName + PLACEHOLDER_SUFFIX; final String paramValue = context.getInitParameter(ctxParamName); if (paramValue != null) { propertiesFilesString = propertiesFilesString.replace(originalPlaceHolder, paramValue); } } } } // Replacing system property (${systemProperty/something}) String[] systemPropertiesNames = getNamesBetweenPlaceholders(propertiesFilesString, SYSTEM_PROPERTY_PLACEHOLDER_PREFIX); if (systemPropertiesNames != null) { for (String sysPropName : systemPropertiesNames) { if (StringUtils.isNotBlank(sysPropName)) { final String originalPlaceHolder = PLACEHOLDER_PREFIX + SYSTEM_PROPERTY_PLACEHOLDER_PREFIX + sysPropName + PLACEHOLDER_SUFFIX; final String paramValue = System.getProperty(sysPropName); if (paramValue != null) { propertiesFilesString = propertiesFilesString.replace(originalPlaceHolder, paramValue); } } } } // Replacing environment property (${env/something}) String[] envPropertiesNames = getNamesBetweenPlaceholders(propertiesFilesString, ENV_PROPERTY_PLACEHOLDER_PREFIX); if (envPropertiesNames != null) { for (String envPropName : envPropertiesNames) { if (StringUtils.isNotBlank(envPropName)) { final String originalPlaceHolder = PLACEHOLDER_PREFIX + ENV_PROPERTY_PLACEHOLDER_PREFIX + envPropName + PLACEHOLDER_SUFFIX; final String paramValue = System.getenv(envPropName); if (paramValue != null) { propertiesFilesString = propertiesFilesString.replace(originalPlaceHolder, paramValue); } } } } return propertiesFilesString; }
From source file:ServerSnoop.java
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); ServletContext context = getServletContext(); out.println("req.getServerName(): " + req.getServerName()); out.println("req.getServerPort(): " + req.getServerPort()); out.println("context.getServerInfo(): " + context.getServerInfo()); out.println("getServerInfo() name: " + getServerInfoName(context.getServerInfo())); out.println("getServerInfo() version: " + getServerInfoVersion(context.getServerInfo())); out.println("context.getAttributeNames():"); Enumeration e = context.getAttributeNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); out.println(" context.getAttribute(\"" + name + "\"): " + context.getAttribute(name)); }//from ww w.j av a 2 s . c o m }
From source file:com.concursive.connect.indexer.jobs.DirectoryIndexerJob.java
public void execute(JobExecutionContext context) throws JobExecutionException { // The RAM index is lazy loaded so that application startup is not blocked. // The index can also be interrupted if the application needs to shutdown // before the index is loaded. SchedulerContext schedulerContext = null; try {/* w w w . j a v a 2 s.com*/ schedulerContext = context.getScheduler().getContext(); ApplicationPrefs prefs = (ApplicationPrefs) schedulerContext.get("ApplicationPrefs"); ServletContext servletContext = (ServletContext) schedulerContext.get("ServletContext"); //@todo remove the servlet context and use the indexer if (servletContext != null) { IIndexerService indexer = IndexerFactory.getInstance().getIndexerService(); if (indexer == null) { throw (new JobExecutionException("Indexer Configuration error: No indexer defined.")); } // Determine the database connection to use Connection db = null; ConnectionPool commonCP = (ConnectionPool) servletContext.getAttribute(Constants.CONNECTION_POOL); ConnectionElement ce = new ConnectionElement(); ce.setDriver(prefs.get(ApplicationPrefs.CONNECTION_DRIVER)); ce.setUrl(prefs.get(ApplicationPrefs.CONNECTION_URL)); ce.setUsername(prefs.get(ApplicationPrefs.CONNECTION_USER)); ce.setPassword(prefs.get(ApplicationPrefs.CONNECTION_PASSWORD)); // Setup the directory index indexerContext = new IndexerContext(prefs); indexerContext.setIndexType(Constants.INDEXER_DIRECTORY); try { db = commonCP.getConnection(ce, true); indexer.initializeData(indexerContext, db); } catch (Exception e) { LOG.error("Could not load RAM index", e); } finally { commonCP.free(db); } // Tell the indexer it's ok to create other writers now servletContext.setAttribute(Constants.DIRECTORY_INDEX_INITIALIZED, "true"); } } catch (Exception e) { e.printStackTrace(System.out); throw new JobExecutionException(e.getMessage()); } }
From source file:com.thejustdo.servlet.CargaMasivaServlet.java
/** * Processes requests for both HTTP// ww w .j a v a 2 s . c om * <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(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info(String.format("Welcome to the MULTI-PART!!!")); ResourceBundle messages = ResourceBundle.getBundle("com.thejustdo.resources.messages"); // 0. If no user logged, nothing can be done. if (!SecureValidator.checkUserLogged(request, response)) { return; } // 1. Check that we have a file upload request. boolean isMultipart = ServletFileUpload.isMultipartContent(request); log.info(String.format("Is multipart?: %s", isMultipart)); // 2. Getting all the parameters. String social_reason = request.getParameter("razon_social"); String nit = request.getParameter("nit"); String name = request.getParameter("name"); String phone = request.getParameter("phone"); String email = request.getParameter("email"); String office = (String) request.getSession().getAttribute("actualOffice"); String open_amount = (String) request.getParameter("valor_tarjeta"); String open_user = (String) request.getSession().getAttribute("actualUser"); List<String> errors = new ArrayList<String>(); // 6. Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // 7. Configure a repository (to ensure a secure temp location is used) ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); log.info(String.format("Temporal repository: %s", repository.getAbsolutePath())); factory.setRepository(repository); // 8. Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { utx.begin(); EntityManager em = emf.createEntityManager(); // Parse the request List<FileItem> items = upload.parseRequest(request); // 8.0 A set of generated box codes must be maintained. Map<String, String> matrix = new HashMap<String, String>(); // ADDED: Validation 'o file extension. String filename = null; // Runing through the parameters. for (FileItem fi : items) { if (fi.isFormField()) { if ("razon_social".equalsIgnoreCase(fi.getFieldName())) { social_reason = fi.getString(); continue; } if ("nit".equalsIgnoreCase(fi.getFieldName())) { nit = fi.getString(); continue; } if ("name".equalsIgnoreCase(fi.getFieldName())) { name = fi.getString(); continue; } if ("phone".equalsIgnoreCase(fi.getFieldName())) { phone = fi.getString(); continue; } if ("email".equalsIgnoreCase(fi.getFieldName())) { email = fi.getString(); continue; } if ("valor_tarjeta".equalsIgnoreCase(fi.getFieldName())) { open_amount = fi.getString(); continue; } } else { filename = fi.getName(); } } // 3. If we got no file, then a error is generated and re-directed to the exact same page. if (!isMultipart) { errors.add(messages.getString("error.massive.no_file")); log.log(Level.SEVERE, errors.toString()); } // 4. If any of the others paramaeters are missing, then a error must be issued. if ((social_reason == null) || ("".equalsIgnoreCase(social_reason.trim()))) { errors.add(messages.getString("error.massive.no_social_reason")); log.log(Level.SEVERE, errors.toString()); } if ((nit == null) || ("".equalsIgnoreCase(nit.trim()))) { errors.add(messages.getString("error.massive.no_nit")); log.log(Level.SEVERE, errors.toString()); } if ((name == null) || ("".equalsIgnoreCase(name.trim()))) { errors.add(messages.getString("error.massive.no_name")); log.log(Level.SEVERE, errors.toString()); } if ((phone == null) || ("".equalsIgnoreCase(phone.trim()))) { errors.add(messages.getString("error.massive.no_phone")); log.log(Level.SEVERE, errors.toString()); } if ((email == null) || ("".equalsIgnoreCase(email.trim()))) { errors.add(messages.getString("error.massive.no_email")); log.log(Level.SEVERE, errors.toString()); } // If no filename or incorrect extension. if ((filename == null) || (!(filename.endsWith(Constants.MASSIVE_EXT.toLowerCase(Locale.FRENCH))) && !(filename.endsWith(Constants.MASSIVE_EXT.toUpperCase())))) { errors.add(messages.getString("error.massive.invalid_ext")); log.log(Level.SEVERE, errors.toString()); } // 5. If any errors found, we must break the flow. if (errors.size() > 0) { request.setAttribute(Constants.ERROR, errors); //Redirect the response request.getRequestDispatcher("/WEB-INF/jsp/carga_masiva.jsp").forward(request, response); } for (FileItem fi : items) { if (!fi.isFormField()) { // 8.1 Processing the file and building the Beneficiaries. List<Beneficiary> beneficiaries = processFile(fi); log.info(String.format("Beneficiaries built: %d", beneficiaries.size())); // 8.2 If any beneficiaries, then an error is generated. if ((beneficiaries == null) || (beneficiaries.size() < 0)) { errors.add(messages.getString("error.massive.empty_file")); log.log(Level.SEVERE, errors.toString()); request.setAttribute(Constants.ERROR, errors); //Redirect the response request.getRequestDispatcher("/WEB-INF/jsp/carga_masiva.jsp").forward(request, response); } // 8.3 Building main parts. Buyer b = buildGeneralBuyer(em, social_reason, nit, name, phone, email); // 8.3.1 The DreamBox has to be re-newed per beneficiary. DreamBox db; for (Beneficiary _b : beneficiaries) { // 8.3.2 Completing each beneficiary. log.info(String.format("Completying the beneficiary: %d", _b.getIdNumber())); db = buildDreamBox(em, b, office, open_amount, open_user); matrix.put(db.getNumber() + "", _b.getGivenNames() + " " + _b.getLastName()); _b.setOwner(b); _b.setBox(db); em.merge(_b); } } } // 8.4 Commiting to persistence layer. utx.commit(); // 8.5 Re-directing to the right jsp. request.getSession().setAttribute("boxes", matrix); request.getSession().setAttribute("boxamount", open_amount + ""); //Redirect the response generateZIP(request, response); } catch (Exception ex) { errors.add(messages.getString("error.massive.couldnot_process")); log.log(Level.SEVERE, errors.toString()); request.setAttribute(Constants.ERROR, errors); request.getRequestDispatcher("/WEB-INF/jsp/carga_masiva.jsp").forward(request, response); } }
From source file:org.openspaces.pu.container.jee.jetty.JettyWebApplicationContextListener.java
public void contextInitialized(ServletContextEvent servletContextEvent) { final ServletContext servletContext = servletContextEvent.getServletContext(); // a hack to get the jetty context final ServletContextHandler jettyContext = (ServletContextHandler) ((ContextHandler.Context) servletContext) .getContextHandler();// ww w . jav a 2s . co m final SessionHandler sessionHandler = jettyContext.getSessionHandler(); BeanLevelProperties beanLevelProperties = (BeanLevelProperties) servletContext .getAttribute(JeeProcessingUnitContainerProvider.BEAN_LEVEL_PROPERTIES_CONTEXT); ClusterInfo clusterInfo = (ClusterInfo) servletContext .getAttribute(JeeProcessingUnitContainerProvider.CLUSTER_INFO_CONTEXT); if (beanLevelProperties != null) { // automatically enable GigaSpaces Session Manager when passing the relevant property String sessionsSpaceUrl = beanLevelProperties.getContextProperties().getProperty(JETTY_SESSIONS_URL); if (sessionsSpaceUrl != null) { logger.info("Jetty GigaSpaces Session support using space url [" + sessionsSpaceUrl + "]"); GigaSessionManager gigaSessionManager = new GigaSessionManager(); if (sessionsSpaceUrl.startsWith("bean://")) { ApplicationContext applicationContext = (ApplicationContext) servletContext .getAttribute(JeeProcessingUnitContainerProvider.APPLICATION_CONTEXT_CONTEXT); if (applicationContext == null) { throw new IllegalStateException("Failed to find servlet context bound application context"); } GigaSpace space; Object bean = applicationContext.getBean(sessionsSpaceUrl.substring("bean://".length())); if (bean instanceof GigaSpace) { space = (GigaSpace) bean; } else if (bean instanceof IJSpace) { space = new GigaSpaceConfigurer((IJSpace) bean).create(); } else { throw new IllegalArgumentException( "Bean [" + bean + "] is not of either GigaSpace type or IJSpace type"); } gigaSessionManager.setSpace(space); } else { gigaSessionManager.setUrlSpaceConfigurer( new UrlSpaceConfigurer(sessionsSpaceUrl).clusterInfo(clusterInfo)); } String scavangePeriod = beanLevelProperties.getContextProperties() .getProperty(JETTY_SESSIONS_SCAVENGE_PERIOD); if (scavangePeriod != null) { gigaSessionManager.setScavengePeriod(Integer.parseInt(scavangePeriod)); if (logger.isDebugEnabled()) { logger.debug("Setting scavenge period to [" + scavangePeriod + "] seconds"); } } String savePeriod = beanLevelProperties.getContextProperties() .getProperty(JETTY_SESSIONS_SAVE_PERIOD); if (savePeriod != null) { gigaSessionManager.setSavePeriod(Integer.parseInt(savePeriod)); if (logger.isDebugEnabled()) { logger.debug("Setting save period to [" + savePeriod + "] seconds"); } } String lease = beanLevelProperties.getContextProperties().getProperty(JETTY_SESSIONS_LEASE); if (lease != null) { gigaSessionManager.setLease(Long.parseLong(lease)); if (logger.isDebugEnabled()) { logger.debug("Setting lease to [" + lease + "] milliseconds"); } } // copy over session settings SessionManager sessionManager = sessionHandler.getSessionManager(); gigaSessionManager.getSessionCookieConfig() .setName(sessionManager.getSessionCookieConfig().getName()); gigaSessionManager.getSessionCookieConfig() .setDomain(sessionManager.getSessionCookieConfig().getDomain()); gigaSessionManager.getSessionCookieConfig() .setPath(sessionManager.getSessionCookieConfig().getPath()); gigaSessionManager.setUsingCookies(sessionManager.isUsingCookies()); gigaSessionManager.getSessionCookieConfig() .setMaxAge(sessionManager.getSessionCookieConfig().getMaxAge()); gigaSessionManager.getSessionCookieConfig() .setSecure(sessionManager.getSessionCookieConfig().isSecure()); gigaSessionManager.setMaxInactiveInterval(sessionManager.getMaxInactiveInterval()); gigaSessionManager.setHttpOnly(sessionManager.getHttpOnly()); gigaSessionManager.getSessionCookieConfig() .setComment(sessionManager.getSessionCookieConfig().getComment()); String sessionTimeout = beanLevelProperties.getContextProperties() .getProperty(JETTY_SESSIONS_TIMEOUT); if (sessionTimeout != null) { gigaSessionManager.setMaxInactiveInterval(Integer.parseInt(sessionTimeout) * 60); if (logger.isDebugEnabled()) { logger.debug("Setting session timeout to [" + sessionTimeout + "] seconds"); } } GigaSessionIdManager sessionIdManager = new GigaSessionIdManager(jettyContext.getServer()); sessionIdManager.setWorkerName(clusterInfo.getUniqueName().replace('.', '_')); gigaSessionManager.setIdManager(sessionIdManager); // replace the actual session manager inside the LazySessionManager with GS session manager, this is // because in Jetty 9 it no more possible to replace the session manager after the server started // without deleting all webapps. if ("GSLazySessionManager".equals(sessionManager.getClass().getSimpleName())) { try { Method method = ReflectionUtils.findMethod(sessionManager.getClass(), "replaceDefault", SessionManager.class); if (method != null) { ReflectionUtils.invokeMethod(method, sessionManager, gigaSessionManager); } else { throw new NoSuchMethodException("replaceDefault"); } } catch (Exception e) { throw new RuntimeException( "Failed to replace default session manager with GSSessionManager", e); } } } // if we have a simple hash session id manager, set its worker name automatically... if (sessionHandler.getSessionManager().getSessionIdManager() instanceof HashSessionIdManager) { HashSessionIdManager sessionIdManager = (HashSessionIdManager) sessionHandler.getSessionManager() .getSessionIdManager(); if (sessionIdManager.getWorkerName() == null) { final String workerName = clusterInfo.getUniqueName().replace('.', '_'); if (logger.isDebugEnabled()) { logger.debug("Automatically setting worker name to [" + workerName + "]"); } stop(sessionIdManager, "to set worker name"); sessionIdManager.setWorkerName(workerName); start(sessionIdManager, "to set worker name"); } } } }
From source file:de.eonas.opencms.parserimpl.RelativePortalURLImpl.java
public PageConfig getPageConfig(@NotNull ServletContext servletContext) { String requestedPageId = getRenderPath(); if (LOG.isDebugEnabled()) { LOG.debug("Requested Page: " + requestedPageId); }/*from w w w . j av a2 s. c o m*/ return ((DriverConfiguration) servletContext.getAttribute(AttributeKeys.DRIVER_CONFIG)) .getPageConfig(requestedPageId); }
From source file:com.hortonworks.amstore.view.AmbariStoreServlet.java
@Override public void init(ServletConfig config) throws ServletException { super.init(config); ServletContext context = config.getServletContext(); viewContext = (ViewContext) context.getAttribute(ViewContext.CONTEXT_ATTRIBUTE); // main Store Instance (this) mainStoreApplication = new MainStoreApplication(viewContext); }
From source file:org.eiichiro.bootleg.AbstractRequest.java
/** * Returns the Web endpoint method parameter from Web application * ({@code ServletContext})./*from w ww . j av a2s . c om*/ * * @param type The parameter type. * @param name The parameter name. * @return The Web endpoint method parameter from Web application * ({@code ServletContext}). */ protected Object application(Type type, String name) { return parameter(type, name, new Function<String, Object>() { public Object apply(String name) { return context.application().getAttribute(name); } }, new Function<String, Collection<Object>>() { @SuppressWarnings("unchecked") public Collection<Object> apply(String name) { ServletContext servletContext = context.application(); Object attribute = servletContext.getAttribute(name); if (attribute instanceof Collection<?>) { return (Collection<Object>) attribute; } Map<String, Object> map = new TreeMap<String, Object>(); for (Object object : Collections.list(servletContext.getAttributeNames())) { String key = (String) object; if (key.startsWith(name + "[")) { map.put(key, servletContext.getAttribute(key)); } } return (map.isEmpty()) ? null : map.values(); } }); }
From source file:edu.isi.wings.portal.controllers.RunController.java
public boolean stopRun(String runid, ServletContext context) { ExecutionMonitorAPI monitor = config.getDomainExecutionMonitor(); if (monitor.getRunDetails(runid).getRuntimeInfo().getStatus() == RuntimeInfo.Status.RUNNING) { PlanExecutionEngine engine = (PlanExecutionEngine) context.getAttribute("engine_" + runid); RuntimePlan rplan = (RuntimePlan) context.getAttribute("plan_" + runid); if (engine != null && rplan != null) { engine.abort(rplan);/*from w w w .ja va 2 s. com*/ return true; } } return false; }