List of usage examples for javax.servlet ServletContext setAttribute
public void setAttribute(String name, Object object);
From source file:com.liferay.portal.servlet.MainServlet.java
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { if (!PortalInstances.matches()) { String html = ContentUtil.get("messages/en_US/init.html"); res.getOutputStream().print(html); return;/* ww w . j a va 2 s . c om*/ } if (ShutdownUtil.isShutdown()) { String html = ContentUtil.get("messages/en_US/shutdown.html"); res.getOutputStream().print(html); return; } req.setAttribute("dotcache", "no"); // Shared session HttpSession ses = req.getSession(); if (!GetterUtil.getBoolean(PropsUtil.get(PropsUtil.TCK_URL))) { String sharedSessionId = CookieUtil.get(req.getCookies(), CookieKeys.SHARED_SESSION_ID); _log.debug("Shared session id is " + sharedSessionId); if (sharedSessionId == null) { sharedSessionId = PwdGenerator.getPassword(PwdGenerator.KEY1 + PwdGenerator.KEY2, 12); Cookie sharedSessionIdCookie = new Cookie(CookieKeys.SHARED_SESSION_ID, sharedSessionId); sharedSessionIdCookie.setPath("/"); sharedSessionIdCookie.setMaxAge(86400); res.addCookie(sharedSessionIdCookie); _log.debug("Shared session id is " + sharedSessionId); } // if (ses.getAttribute(WebKeys.SHARED_SESSION_ID) == null) { ses.setAttribute(WebKeys.SHARED_SESSION_ID, sharedSessionId); // } HttpSession portalSes = (HttpSession) SharedSessionPool.get(sharedSessionId); if ((portalSes == null) || (ses != portalSes)) { if (portalSes == null) { _log.debug("No session exists in pool"); } else { _log.debug("Session " + portalSes.getId() + " in pool is old"); } _log.debug("Inserting current session " + ses.getId() + " in pool"); SharedSessionPool.put(sharedSessionId, ses); } } // Test CAS auto login /* * ses.setAttribute( * com.liferay.portal.auth.CASAutoLogin.CAS_FILTER_USER, * "liferay.com.1"); */ // CTX ServletContext ctx = getServletContext(); ServletContext portalCtx = ctx.getContext(PropsUtil.get(PropsUtil.PORTAL_CTX)); if (portalCtx == null) { portalCtx = ctx; } req.setAttribute(WebKeys.CTX, portalCtx); // CTX_PATH variable String ctxPath = (String) ctx.getAttribute(WebKeys.CTX_PATH); if (portalCtx.getAttribute(WebKeys.CTX_PATH) == null) { portalCtx.setAttribute(WebKeys.CTX_PATH, ctxPath); } if (ses.getAttribute(WebKeys.CTX_PATH) == null) { ses.setAttribute(WebKeys.CTX_PATH, ctxPath); } req.setAttribute(WebKeys.CTX_PATH, ctxPath); // CAPTCHA_PATH variable String captchaPath = (String) ctx.getAttribute(WebKeys.CAPTCHA_PATH); if (portalCtx.getAttribute(WebKeys.CAPTCHA_PATH) == null) { portalCtx.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath); } if (ses.getAttribute(WebKeys.CAPTCHA_PATH) == null) { ses.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath); } req.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath); // IMAGE_PATH variable String imagePath = (String) ctx.getAttribute(WebKeys.IMAGE_PATH); if (portalCtx.getAttribute(WebKeys.IMAGE_PATH) == null) { portalCtx.setAttribute(WebKeys.IMAGE_PATH, imagePath); } if (ses.getAttribute(WebKeys.IMAGE_PATH) == null) { ses.setAttribute(WebKeys.IMAGE_PATH, imagePath); } req.setAttribute(WebKeys.IMAGE_PATH, imagePath); // WebKeys.COMPANY_ID variable String companyId = (String) ctx.getAttribute(WebKeys.COMPANY_ID); if (portalCtx.getAttribute(WebKeys.COMPANY_ID) == null) { portalCtx.setAttribute(WebKeys.COMPANY_ID, companyId); } if (ses.getAttribute(WebKeys.COMPANY_ID) == null) { ses.setAttribute(WebKeys.COMPANY_ID, companyId); } req.setAttribute(WebKeys.COMPANY_ID, companyId); // Portlet Request Processor PortletRequestProcessor portletReqProcessor = (PortletRequestProcessor) portalCtx .getAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR); if (portletReqProcessor == null) { portletReqProcessor = new PortletRequestProcessor(this, getModuleConfig(req)); portalCtx.setAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR, portletReqProcessor); } // Tiles definitions factory if (portalCtx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY) == null) { portalCtx.setAttribute(TilesUtilImpl.DEFINITIONS_FACTORY, ctx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY)); } // Set character encoding String strutsCharEncoding = PropsUtil.get(PropsUtil.STRUTS_CHAR_ENCODING); req.setCharacterEncoding(strutsCharEncoding); /* * if (!BrowserSniffer.is_wml(req)) { res.setContentType( * Constants.TEXT_HTML + "; charset=" + strutsCharEncoding); } */ // Determine content type String contentType = req.getHeader("Content-Type"); if ((contentType != null) && (contentType.startsWith("multipart/form-data"))) { req = new UploadServletRequest(req); } else if (ParamUtil.get(req, WebKeys.ENCRYPT, false)) { try { Company company = CompanyLocalManagerUtil.getCompany(companyId); req = new EncryptedServletRequest(req, company.getKeyObj()); } catch (Exception e) { } } // Current URL String completeURL = Http.getCompleteURL(req); if (completeURL.indexOf("j_security_check") != -1) { completeURL = ctxPath; } else { completeURL = completeURL.substring(completeURL.indexOf("://") + 3, completeURL.length()); completeURL = completeURL.substring(completeURL.indexOf("/"), completeURL.length()); } req.setAttribute(WebKeys.CURRENT_URL, completeURL); // Chat server // Login String userId = PortalUtil.getUserId(req); if ((userId != null)) { PrincipalThreadLocal.setName(userId); } if (userId == null) { try { User user = UserManagerUtil.getDefaultUser(companyId); if (ses.getAttribute(Globals.LOCALE_KEY) == null) ses.setAttribute(Globals.LOCALE_KEY, user.getLocale()); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } } // Process pre service events try { EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_PRE), req, res); } catch (Exception e) { Logger.error(this, e.getMessage(), e); req.setAttribute(PageContext.EXCEPTION, e); StrutsUtil.forward(PropsUtil.get(PropsUtil.SERVLET_SERVICE_EVENTS_PRE_ERROR_PAGE), portalCtx, req, res); } // Struts service callParentService(req, res); // Process post service events try { EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_POST), req, res); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } // Clear the principal associated with this thread PrincipalThreadLocal.setName(null); }
From source file:org.sindice.core.analytics.commons.webapps.SparqledContextListener.java
@Override public void contextInitialized(ServletContextEvent sce) { final ServletContext context = sce.getServletContext(); addEnvToContext(context);/*from w w w.jav a2 s. c o m*/ final String home = (String) context.getInitParameter(SPARQLED_HOME); final File sparqledHome = home == null ? null : new File(home); if (sparqledHome == null || !sparqledHome.exists()) { throw new RuntimeException("Missing sparqled home"); } logger.info("Looking for configuration in [{}]", sparqledHome); configureLogging(context, sparqledHome); final XMLConfiguration config = createXMLConfiguration(context); final File applicationConfigFile = new File(sparqledHome, CONFIG_XML); try { config.load(applicationConfigFile); } catch (ConfigurationException e) { throw new RuntimeException("Invalid configuration file: " + applicationConfigFile, e); } // important to set this as it is used later in logback.xml context.setAttribute("sparqled.home", home); context.setAttribute("config", config); logger.info("config now availabe via the following line of code\n" + " XMLConfiguration appConfig = (XMLConfiguration) servletContext.getAttribute(\"config\");"); }
From source file:org.apache.nifi.web.server.JettyServer.java
@Override public void start() { try {//w ww .j a va2s. com // start the server server.start(); // ensure everything started successfully for (Handler handler : server.getChildHandlers()) { // see if the handler is a web app if (handler instanceof WebAppContext) { WebAppContext context = (WebAppContext) handler; // see if this webapp had any exceptions that would // cause it to be unavailable if (context.getUnavailableException() != null) { startUpFailure(context.getUnavailableException()); } } } // ensure the appropriate wars deployed successfully before injecting the NiFi context and security filters // this must be done after starting the server (and ensuring there were no start up failures) if (webApiContext != null) { // give the web api the component ui extensions final ServletContext webApiServletContext = webApiContext.getServletHandler().getServletContext(); webApiServletContext.setAttribute("nifi-ui-extensions", componentUiExtensions); // get the application context final WebApplicationContext webApplicationContext = WebApplicationContextUtils .getRequiredWebApplicationContext(webApiServletContext); // component ui extensions if (CollectionUtils.isNotEmpty(componentUiExtensionWebContexts)) { final NiFiWebConfigurationContext configurationContext = webApplicationContext .getBean("nifiWebConfigurationContext", NiFiWebConfigurationContext.class); for (final WebAppContext customUiContext : componentUiExtensionWebContexts) { // set the NiFi context in each custom ui servlet context final ServletContext customUiServletContext = customUiContext.getServletHandler() .getServletContext(); customUiServletContext.setAttribute("nifi-web-configuration-context", configurationContext); // add the security filter to any ui extensions wars final FilterHolder securityFilter = webApiContext.getServletHandler() .getFilter("springSecurityFilterChain"); if (securityFilter != null) { customUiContext.addFilter(securityFilter, "/*", EnumSet.allOf(DispatcherType.class)); } } } // content viewer extensions if (CollectionUtils.isNotEmpty(contentViewerWebContexts)) { for (final WebAppContext contentViewerContext : contentViewerWebContexts) { // add the security filter to any content viewer wars final FilterHolder securityFilter = webApiContext.getServletHandler() .getFilter("springSecurityFilterChain"); if (securityFilter != null) { contentViewerContext.addFilter(securityFilter, "/*", EnumSet.allOf(DispatcherType.class)); } } } // content viewer controller if (webContentViewerContext != null) { final ContentAccess contentAccess = webApplicationContext.getBean("contentAccess", ContentAccess.class); // add the content access final ServletContext webContentViewerServletContext = webContentViewerContext .getServletHandler().getServletContext(); webContentViewerServletContext.setAttribute("nifi-content-access", contentAccess); final FilterHolder securityFilter = webApiContext.getServletHandler() .getFilter("springSecurityFilterChain"); if (securityFilter != null) { webContentViewerContext.addFilter(securityFilter, "/*", EnumSet.allOf(DispatcherType.class)); } } } // ensure the web document war was loaded and provide the extension mapping if (webDocsContext != null) { final ServletContext webDocsServletContext = webDocsContext.getServletHandler().getServletContext(); webDocsServletContext.setAttribute("nifi-extension-mapping", extensionMapping); } // if this nifi is a node in a cluster, start the flow service and load the flow - the // flow service is loaded here for clustered nodes because the loading of the flow will // initialize the connection between the node and the NCM. if the node connects (starts // heartbeating, etc), the NCM may issue web requests before the application (wars) have // finished loading. this results in the node being disconnected since its unable to // successfully respond to the requests. to resolve this, flow loading was moved to here // (after the wars have been successfully deployed) when this nifi instance is a node // in a cluster if (props.isNode()) { FlowService flowService = null; try { logger.info("Loading Flow..."); ApplicationContext ctx = WebApplicationContextUtils .getWebApplicationContext(webApiContext.getServletContext()); flowService = ctx.getBean("flowService", FlowService.class); // start and load the flow flowService.start(); flowService.load(null); logger.info("Flow loaded successfully."); } catch (BeansException | LifeCycleStartException | IOException | FlowSerializationException | FlowSynchronizationException | UninheritableFlowException e) { // ensure the flow service is terminated if (flowService != null && flowService.isRunning()) { flowService.stop(false); } throw new Exception("Unable to load flow due to: " + e, e); } } // dump the application url after confirming everything started successfully dumpUrls(); } catch (Exception ex) { startUpFailure(ex); } }
From source file:org.glom.web.server.OnlineGlomServlet.java
protected UserStore getUserStore() { //See if there is already a shared userstore final ServletConfig config = this.getServletConfig(); if (config == null) { Log.error("getServletConfig() return null"); return null; }/* w ww .j ava 2 s . co m*/ final ServletContext context = config.getServletContext(); if (context == null) { Log.error("getServletContext() return null"); return null; } //Use the existing shared document set, if any: final Object object = context.getAttribute(USER_STORE); if ((object != null) && !(object instanceof UserStore)) { Log.error("The configuredDocumentSet attribute is not of the expected type."); return null; } UserStore userStore = (UserStore) object; if (userStore != null) { return userStore; } //Create the shared userstore //TODO: Possible race condition between checking and creating+setting: userStore = new UserStore(); //Store it in the Servlet Context, //so it is available to all servlets: context.setAttribute(USER_STORE, userStore); return userStore; }
From source file:org.springbyexample.web.service.EmbeddedJetty.java
@PostConstruct public void init() throws Exception { ctx = new ClassPathXmlApplicationContext(); ((AbstractApplicationContext) ctx).getEnvironment().setActiveProfiles(activeProfiles); ((AbstractXmlApplicationContext) ctx).setConfigLocations(configLocations); if (logger.isInfoEnabled()) { logger.info("Creating embedded jetty context. activeProfiles='{}' configLocations='{}'", new Object[] { ArrayUtils.toString(activeProfiles), ArrayUtils.toString(configLocations) }); }/*from w ww . j a va 2 s . com*/ ((AbstractXmlApplicationContext) ctx).refresh(); ((AbstractApplicationContext) ctx).registerShutdownHook(); Server server = (Server) ctx.getBean("jettyServer"); if (port > 0) { Connector connector = server.getConnectors()[0]; connector.setPort(port); } ServletContext servletContext = null; for (Handler handler : server.getHandlers()) { if (handler instanceof Context) { Context context = (Context) handler; if (StringUtils.hasText(contextPath)) { context.setContextPath("/" + contextPath); } servletContext = context.getServletContext(); // setup Spring Security Filter FilterHolder filterHolder = new FilterHolder(); filterHolder.setName(SECURITY_FILTER_NAME); filterHolder.setClassName(DelegatingFilterProxy.class.getName()); context.getServletHandler().addFilterWithMapping(filterHolder, "/*", 0); break; } } XmlWebApplicationContext wctx = new XmlWebApplicationContext(); wctx.setParent(ctx); wctx.setConfigLocation(""); wctx.setServletContext(servletContext); wctx.refresh(); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wctx); server.start(); logger.info("Server started."); }
From source file:org.apache.shindig.common.servlet.GuiceServletContextListener.java
public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); //HNN setting all system.properties specified in the web.xml setSystemProperties(context);/*from ww w . ja v a 2 s . c o m*/ String moduleNames = context.getInitParameter(MODULES_ATTRIBUTE); List<Module> modules = Lists.newLinkedList(); if (moduleNames != null) { for (String moduleName : StringUtils.split(moduleNames, ':')) { try { moduleName = moduleName.trim(); if (moduleName.length() > 0) { modules.add((Module) Class.forName(moduleName).newInstance()); } } catch (InstantiationException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } Injector injector = Guice.createInjector(Stage.PRODUCTION, modules); context.setAttribute(INJECTOR_ATTRIBUTE, injector); try { if (!jmxInitialized) { Manager.manage("ShindigGuiceContext", injector); jmxInitialized = true; } } catch (Exception e) { // Ignore errors } }
From source file:com.openkm.servlet.admin.JcrRepositoryViewServlet.java
/** * Edit property//from w w w.j a v a 2 s. co m */ private void edit(Session session, String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, javax.jcr.PathNotFoundException, RepositoryException { log.debug("edit({}, {}, {}, {})", new Object[] { session, path, request, response }); String property = WebUtils.getString(request, "property"); ServletContext sc = getServletContext(); Node node = session.getRootNode().getNode(path.substring(1)); Property prop = node.getProperty(property); boolean multiple = false; String value; if (prop.getDefinition().isMultiple()) { value = toString(prop.getValues(), "\n"); multiple = true; } else { value = prop.getValue().getString(); } // Activity log UserActivity.log(session.getUserID(), "ADMIN_REPOSITORY_EDIT", node.getUUID(), path, property + ", " + value); sc.setAttribute("node", node); sc.setAttribute("property", prop); sc.setAttribute("multiple", multiple || prop.getName().equals(Scripting.SCRIPT_CODE)); sc.setAttribute("value", value); sc.getRequestDispatcher("/admin/jcr_repository_edit.jsp").forward(request, response); log.debug("edit: void"); }
From source file:com.ikon.servlet.admin.RepositoryViewServlet.java
/** * Edit property/*from w ww . j a v a 2 s .c o m*/ */ private void edit(Session session, String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, javax.jcr.PathNotFoundException, RepositoryException { log.debug("edit({}, {}, {}, {})", new Object[] { session, path, request, response }); String property = WebUtils.getString(request, "property"); ServletContext sc = getServletContext(); Node node = session.getRootNode().getNode(path.substring(1)); Property prop = node.getProperty(property); boolean multiple = false; String value; if (prop.getDefinition().isMultiple()) { value = toString(prop.getValues(), "\n"); multiple = true; } else { value = prop.getValue().getString(); } // Activity log UserActivity.log(session.getUserID(), "ADMIN_REPOSITORY_EDIT", node.getUUID(), path, property + ", " + value); sc.setAttribute("node", node); sc.setAttribute("property", prop); sc.setAttribute("multiple", multiple || prop.getName().equals(Scripting.SCRIPT_CODE)); sc.setAttribute("value", value); sc.getRequestDispatcher("/admin/repository_edit.jsp").forward(request, response); log.debug("edit: void"); }
From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java
private ApplicationContext loadContext(String[] configLocations, URLClassLoader cl, String contextDisplayName, Properties properties) throws Exception { ServletContext servletContext = ((ConfigurableWebApplicationContext) this._applicationContext) .getServletContext();// w w w . jav a 2 s .c om //if plugin's classes have been loaded we can go on List<ClassPathXmlApplicationContext> ctxList = (List<ClassPathXmlApplicationContext>) servletContext .getAttribute("pluginsContextsList"); if (ctxList == null) { ctxList = new ArrayList<ClassPathXmlApplicationContext>(); servletContext.setAttribute("pluginsContextsList", ctxList); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); ClassPathXmlApplicationContext newContext = null; try { //create a new spring context with the classloader and the paths defined as parameter in pluginsInstallerContext.xml. //The new context is given the default webapplication context as its parent Thread.currentThread().setContextClassLoader(cl); newContext = new ClassPathXmlApplicationContext(); //ClassPathXmlApplicationContext newContext = new ClassPathXmlApplicationContext(configLocations, applicationContext); PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer(); configurer.setProperties(properties); newContext.addBeanFactoryPostProcessor(configurer); newContext.setClassLoader(cl); newContext.setParent(this._applicationContext); String[] configLocs = new String[] { "classpath:spring/restServerConfig.xml", "classpath:spring/baseSystemConfig.xml" }; newContext.setConfigLocations(configLocs); newContext.refresh(); BaseConfigManager baseConfigManager = (BaseConfigManager) ((ConfigurableWebApplicationContext) this._applicationContext) .getBean("BaseConfigManager"); baseConfigManager.init(); newContext.setConfigLocations(configLocations); newContext.refresh(); newContext.setDisplayName(contextDisplayName); ClassPathXmlApplicationContext currentCtx = (ClassPathXmlApplicationContext) this .getStoredContext(contextDisplayName); if (currentCtx != null) { currentCtx.close(); ctxList.remove(currentCtx); } ctxList.add(newContext); } catch (Exception e) { _logger.error("Unexpected error loading application context: " + e.getMessage()); e.printStackTrace(); throw e; } finally { Thread.currentThread().setContextClassLoader(currentClassLoader); } return newContext; }
From source file:com.concursive.connect.config.ApplicationPrefs.java
/** * Adds a feature to the Parameter attribute of the ApplicationPrefs object * * @param context The feature to be added to the Parameter attribute * @param param The feature to be added to the Parameter attribute * @param value The feature to be added to the Parameter attribute * @param defaultValue The feature to be added to the Parameter attribute *//*from w ww. ja v a 2 s . c om*/ private void addParameter(ServletContext context, String param, String value, String defaultValue) { if (value != null) { context.setAttribute(param, value); } else { if (defaultValue != null) { context.setAttribute(param, defaultValue); } else { context.removeAttribute(param); } } }