List of usage examples for javax.servlet ServletContext setAttribute
public void setAttribute(String name, Object object);
From source file:com.sinosoft.one.mvc.web.impl.module.ModulesBuilderImpl.java
public List<Module> build(List<ModuleResource> moduleResources, WebApplicationContext rootContext) throws Exception { // ????????/*from w w w. j a v a 2 s . c o m*/ moduleResources = new ArrayList<ModuleResource>(moduleResources); Collections.sort(moduleResources); // ?? List<Module> modules = new ArrayList<Module>(moduleResources.size()); Map<ModuleResource, Module> modulesAsMap = new HashMap<ModuleResource, Module>(); /* * ModuleResource ?web??? * modelResourcesmodel * */ for (ModuleResource moduleResource : moduleResources) { final Module parentModule = (moduleResource.getParent() == null) ? null// : modulesAsMap.get(moduleResource.getParent()); final WebApplicationContext parentContext = (parentModule == null) ? rootContext// : parentModule.getApplicationContext(); final String namespace = "context@controllers" + moduleResource.getRelativePath().replace('/', '.'); // modulespring context final ServletContext servletContext = parentContext == null ? null // : parentContext.getServletContext(); final ModuleAppContext moduleContext = ModuleAppContext.createModuleContext(// parentContext, // moduleResource.getContextResources(), // moduleResource.getMessageBasenames(), // /*id*/moduleResource.getModuleUrl().toString(), // namespace// ); // ??...applicationContext registerBeanDefinitions(moduleContext, moduleResource.getModuleClasses()); // module final ModuleImpl module = new ModuleImpl(// parentModule, // moduleResource.getModuleUrl(), // moduleResource.getMappingPath(), // moduleResource.getRelativePath(), // moduleContext); // modulesAsMap.put(moduleResource, module); // servletContext if (servletContext != null) { String contextAttrKey = WebApplicationContext.class.getName() + "@" + moduleResource.getModuleUrl(); servletContext.setAttribute(contextAttrKey, moduleContext); } // Springweb??ParamValidatorParamResolver, ControllerInterceptor, ControllerErrorHandler List<ParamResolver> customerResolvers = findContextResolvers(moduleContext); // resolvers module.setCustomerResolvers(customerResolvers); if (logger.isDebugEnabled()) { logger.debug("module '" + module.getMappingPath() + "': apply resolvers " + customerResolvers); } // module List<InterceptorDelegate> interceptors = findInterceptors(moduleContext); for (Iterator<InterceptorDelegate> iter = interceptors.iterator(); iter.hasNext();) { InterceptorDelegate interceptor = iter.next(); ControllerInterceptor most = InterceptorDelegate.getMostInnerInterceptor(interceptor); if (!most.getClass().getName().startsWith("com.sinosoft.one.mvc.web")) { // deny? if (moduleResource.getInterceptedDeny() != null) { if (MvcStringUtil.matches(moduleResource.getInterceptedDeny(), interceptor.getName())) { iter.remove(); if (logger.isDebugEnabled()) { logger.debug("module '" + module.getMappingPath() + "': remove interceptor by mvc.properties: " + most.getClass().getName()); } continue; } } // allow? if (moduleResource.getInterceptedAllow() != null) { if (!MvcStringUtil.matches(moduleResource.getInterceptedAllow(), interceptor.getName())) { iter.remove(); if (logger.isDebugEnabled()) { logger.debug("module '" + module.getMappingPath() + "': remove interceptor by mvc.properties: " + most.getClass().getName()); } continue; } } } } module.setControllerInterceptors(interceptors); if (logger.isDebugEnabled()) { logger.debug("module '" + module.getMappingPath() + "': apply intercetpors " + interceptors); } // validatormodule List<ParamValidator> validators = findContextValidators(moduleContext); module.setValidators(validators); if (logger.isDebugEnabled()) { logger.debug("module '" + module.getMappingPath() + "': apply global validators " + validators); } // errorhandler ControllerErrorHandler errorHandler = getContextErrorHandler(moduleContext); if (errorHandler != null) { if (Proxy.isProxyClass(errorHandler.getClass())) { module.setErrorHandler(errorHandler); } else { ErrorHandlerDispatcher dispatcher = new ErrorHandlerDispatcher(errorHandler); module.setErrorHandler(dispatcher); } if (logger.isInfoEnabled()) { logger.info("set errorHandler: " + module.getMappingPath() + " " + errorHandler); } } // controllers final ListableBeanFactory beanFactory = moduleContext.getBeanFactory(); for (String beanName : beanFactory.getBeanDefinitionNames()) { checkController(moduleContext, beanName, module); } // modules.add(module); } return modules; }
From source file:org.red5.logging.ContextLoggingListener.java
public void contextInitialized(ServletContextEvent event) { ServletContext servletContext = event.getServletContext(); String contextName = servletContext.getContextPath().replaceAll("/", ""); if ("".equals(contextName)) { contextName = "root"; }//from w w w .j a v a 2 s.c o m System.out.printf("Context init: %s%n", contextName); ConfigurableWebApplicationContext appctx = (ConfigurableWebApplicationContext) servletContext .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (appctx != null) { System.out.printf( "ConfigurableWebApplicationContext is not null in ContextLoggingListener for: %s, this indicates a misconfiguration or load order problem%n", contextName); } try { // get the selector ContextSelector selector = Red5LoggerFactory.getContextSelector(); // get the logger context for this servlet / app context by name URL url = servletContext.getResource(String.format("/WEB-INF/classes/logback-%s.xml", contextName)); if (url != null && Files.exists(Paths.get(url.toURI()))) { System.out.printf("Context logger config found: %s%n", url.toURI()); } else { url = servletContext.getResource("/WEB-INF/classes/logback.xml"); if (url != null && Files.exists(Paths.get(url.toURI()))) { System.out.printf("Context logger config found: %s%n", url.toURI()); } } // get the logger context for the servlet context LoggerContext loggerContext = url != null ? ((LoggingContextSelector) selector).getLoggerContext(contextName, url) : selector.getLoggerContext(contextName); // set the logger context for use elsewhere in the servlet context servletContext.setAttribute(Red5LoggerFactory.LOGGER_CONTEXT_ATTRIBUTE, loggerContext); // get the root logger for this context Logger logger = Red5LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME, contextName); logger.info("Starting up context: {}", contextName); } catch (Exception e) { System.err.printf("LoggingContextSelector is not the correct type: %s%n", e.getMessage()); e.printStackTrace(); } }
From source file:com.sun.faces.config.ConfigureListener.java
public void contextInitialized(ServletContextEvent sce) { // Prepare local variables we will need Digester digester = null;//from w w w.ja va 2s . c o m FacesConfigBean fcb = new FacesConfigBean(); ServletContext context = sce.getServletContext(); // store the servletContext instance in Thread local Storage. // This enables our Application's ApplicationAssociate to locate // it so it can store the ApplicationAssociate in the // ServletContext. tlsExternalContext.set(new ServletContextAdapter(context)); // see if we're operating in the unit test environment try { if (RIConstants.IS_UNIT_TEST_MODE) { // if so, put the fcb in the servletContext context.setAttribute(FACES_CONFIG_BEAN_KEY, fcb); } } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Can't query for test environment"); } } // see if we need to disable our TLValidator RIConstants.HTML_TLV_ACTIVE = isFeatureEnabled(context, ENABLE_HTML_TLV); URL url = null; if (log.isDebugEnabled()) { log.debug("contextInitialized(" + context.getServletContextName() + ")"); } // Ensure that we initialize a particular application ony once if (initialized()) { return; } // Step 1, configure a Digester instance we can use digester = digester(isFeatureEnabled(context, VALIDATE_XML)); // Step 2, parse the RI configuration resource url = Util.getCurrentLoader(this).getResource(JSF_RI_CONFIG); parse(digester, url, fcb); // Step 3, parse any "/META-INF/faces-config.xml" resources Iterator resources; try { List list = new LinkedList(); Enumeration items = Util.getCurrentLoader(this).getResources(META_INF_RESOURCES); while (items.hasMoreElements()) { list.add(0, items.nextElement()); } resources = list.iterator(); } catch (IOException e) { String message = null; try { message = Util.getExceptionMessageString(Util.CANT_PARSE_FILE_ERROR_MESSAGE_ID, new Object[] { META_INF_RESOURCES }); } catch (Exception ee) { message = "Can't parse configuration file:" + META_INF_RESOURCES; } log.warn(message, e); throw new FacesException(message, e); } while (resources.hasNext()) { url = (URL) resources.next(); parse(digester, url, fcb); } // Step 4, parse any context-relative resources specified in // the web application deployment descriptor String paths = context.getInitParameter(FacesServlet.CONFIG_FILES_ATTR); if (paths != null) { for (StringTokenizer t = new StringTokenizer(paths.trim(), ","); t.hasMoreTokens();) { url = getContextURLForPath(context, t.nextToken().trim()); if (url != null) { parse(digester, url, fcb); } } } // Step 5, parse "/WEB-INF/faces-config.xml" if it exists url = getContextURLForPath(context, WEB_INF_RESOURCE); if (url != null) { parse(digester, url, fcb); } // Step 6, use the accumulated configuration beans to configure the RI try { configure(context, fcb); } catch (FacesException e) { e.printStackTrace(); throw e; } catch (Exception e) { e.printStackTrace(); throw new FacesException(e); } // Step 7, verify that all the configured factories are available // and optionall that configured objects can be created verifyFactories(); if (isFeatureEnabled(context, VERIFY_OBJECTS)) { verifyObjects(context, fcb); } tlsExternalContext.set(null); }
From source file:jp.or.openid.eiwg.scim.operation.Operation.java
/** * /*from w ww . j av a2 s. c o m*/ * * @param context * @param request * @param attributes * @param requestJson */ public boolean deleteUserInfo(ServletContext context, HttpServletRequest request, String targetId) { // ? setError(0, null, null); // id? LinkedHashMap<String, Object> targetInfo = null; @SuppressWarnings("unchecked") ArrayList<LinkedHashMap<String, Object>> users = (ArrayList<LinkedHashMap<String, Object>>) context .getAttribute("Users"); Iterator<LinkedHashMap<String, Object>> usersIt = null; if (users != null && !users.isEmpty()) { usersIt = users.iterator(); while (usersIt.hasNext()) { LinkedHashMap<String, Object> userInfo = usersIt.next(); Object id = SCIMUtil.getAttribute(userInfo, "id"); if (id != null && id instanceof String) { if (targetId.equals(id.toString())) { targetInfo = userInfo; break; } } } } if (targetInfo == null) { // ??? setError(HttpServletResponse.SC_NOT_FOUND, null, MessageConstants.ERROR_NOT_FOUND); return false; } // (??) usersIt.remove(); context.setAttribute("Users", users); return true; }
From source file:com.openkm.servlet.admin.ConfigServlet.java
/** * List config//from w ww. j a va2s . co m */ private void list(String userId, String filter, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, DatabaseException { log.debug("list({}, {}, {}, {})", new Object[] { userId, filter, request, response }); ServletContext sc = getServletContext(); List<Config> list = ConfigDAO.findAll(); for (Iterator<Config> it = list.iterator(); it.hasNext();) { Config cfg = it.next(); if (Config.STRING.equals(cfg.getType())) { cfg.setType("String"); } else if (Config.TEXT.equals(cfg.getType())) { cfg.setType("Text"); } else if (Config.BOOLEAN.equals(cfg.getType())) { cfg.setType("Boolean"); } else if (Config.INTEGER.equals(cfg.getType())) { cfg.setType("Integer"); } else if (Config.LONG.equals(cfg.getType())) { cfg.setType("Long"); } else if (Config.FILE.equals(cfg.getType())) { cfg.setType("File"); } else if (Config.LIST.equals(cfg.getType())) { cfg.setType("List"); } else if (Config.SELECT.equals(cfg.getType())) { cfg.setType("Select"); ConfigStoredSelect stSelect = new Gson().fromJson(cfg.getValue(), ConfigStoredSelect.class); for (ConfigStoredOption stOption : stSelect.getOptions()) { if (stOption.isSelected()) { cfg.setValue(stOption.getValue()); } } } else if (Config.HIDDEN.equals(cfg.getType())) { it.remove(); } if (!Config.HIDDEN.equals(cfg.getType()) && !cfg.getKey().contains(filter)) { it.remove(); } } sc.setAttribute("configs", list); sc.setAttribute("filter", filter); sc.getRequestDispatcher("/admin/config_list.jsp").forward(request, response); log.debug("list: void"); }
From source file:be.fedict.eid.idp.sp.protocol.openid.AuthenticationRequestServlet.java
/** * {@inheritDoc}/*from w ww. j a v a2s . c om*/ */ @Override public void init(ServletConfig config) throws ServletException { this.userIdentifier = config.getInitParameter(USER_IDENTIFIER_PARAM); this.spDestination = config.getInitParameter(SP_DESTINATION_PARAM); this.spDestinationPage = config.getInitParameter(SP_DESTINATION_PAGE_PARAM); this.languages = config.getInitParameter(LANGUAGES_PARAM); this.authenticationRequestServiceLocator = new ServiceLocator<AuthenticationRequestService>( AUTHN_REQUEST_SERVICE_PARAM, config); // validate necessary configuration params if (null == this.userIdentifier && !this.authenticationRequestServiceLocator.isConfigured()) { throw new ServletException("need to provide either " + USER_IDENTIFIER_PARAM + " or " + AUTHN_REQUEST_SERVICE_PARAM + "(Class) init-params"); } if (null == this.spDestination && null == this.spDestinationPage && !this.authenticationRequestServiceLocator.isConfigured()) { throw new ServletException("need to provide either " + SP_DESTINATION_PARAM + " or " + SP_DESTINATION_PAGE_PARAM + " or " + AUTHN_REQUEST_SERVICE_PARAM + "(Class) init-param"); } // SSL configuration String trustServer = config.getInitParameter(TRUST_SERVER_PARAM); if (null != trustServer) { this.trustServer = Boolean.parseBoolean(trustServer); } X509Certificate serverCertificate = null; if (this.authenticationRequestServiceLocator.isConfigured()) { AuthenticationRequestService service = this.authenticationRequestServiceLocator.locateService(); serverCertificate = service.getServerCertificate(); } if (this.trustServer) { LOG.warn("Trusting all SSL server certificates!"); try { OpenIDSSLSocketFactory.installAllTrusted(); } catch (Exception e) { throw new ServletException("could not install OpenID SSL Socket Factory: " + e.getMessage(), e); } } else if (null != serverCertificate) { LOG.info("Trusting specified SSL certificate: " + serverCertificate); try { OpenIDSSLSocketFactory.install(serverCertificate); } catch (Exception e) { throw new ServletException("could not install OpenID SSL Socket Factory: " + e.getMessage(), e); } } ServletContext servletContext = config.getServletContext(); this.consumerManager = (ConsumerManager) servletContext.getAttribute(CONSUMER_MANAGER_ATTRIBUTE); if (null == this.consumerManager) { try { if (this.trustServer || null != serverCertificate) { TrustManager trustManager; if (this.trustServer) { trustManager = new OpenIDTrustManager(); } else { trustManager = new OpenIDTrustManager(serverCertificate); } SSLContext sslContext = SSLContext.getInstance("SSL"); TrustManager[] trustManagers = { trustManager }; sslContext.init(null, trustManagers, null); HttpFetcherFactory httpFetcherFactory = new HttpFetcherFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); YadisResolver yadisResolver = new YadisResolver(httpFetcherFactory); RealmVerifierFactory realmFactory = new RealmVerifierFactory(yadisResolver); HtmlResolver htmlResolver = new HtmlResolver(httpFetcherFactory); XriResolver xriResolver = Discovery.getXriResolver(); Discovery discovery = new Discovery(htmlResolver, yadisResolver, xriResolver); this.consumerManager = new ConsumerManager(realmFactory, discovery, httpFetcherFactory); } else { this.consumerManager = new ConsumerManager(); } } catch (Exception e) { throw new ServletException("could not init OpenID ConsumerManager"); } servletContext.setAttribute(CONSUMER_MANAGER_ATTRIBUTE, this.consumerManager); } }
From source file:com.gtwm.pb.servlets.AppController.java
/** * init() is called once automatically by the servlet container (e.g. * Tomcat) at servlet startup. We use it to initialise various things, * namely:/*from w ww .j a v a 2 s. c o m*/ * * a) create the DatabaseDefn object which is the top level application * object. The DatabaseDefn object will load the list of tables & reports * into memory when it is constructed. It will also configure and load the * object database * * b) create a DataSource object here to pass to the DatabaseDefn. This data * source then acts as a pool of connections from which a connection to the * relational database can be called up whenever needed. */ public void init() throws ServletException { logger.info("Initialising " + AppProperties.applicationName); ServletContext servletContext = getServletContext(); this.webAppRoot = servletContext.getRealPath("/"); // Create and cache a DatabaseDefn object which is an entry point to all // application logic // and schema information. The relational database is also gotten DataSource relationalDataSource = null; InitialContext initialContext = null; try { // Get a data source for the relational database to pass to the // DatabaseDefn object initialContext = new InitialContext(); relationalDataSource = (DataSource) initialContext.lookup("java:comp/env/jdbc/agileBaseData"); if (relationalDataSource == null) { throw new ServletException("Can't get data source"); } this.relationalDataSource = relationalDataSource; // Store 'global objects' data sources and webAppRoot in // databaseDefn this.databaseDefn = new DatabaseDefn(relationalDataSource, this.webAppRoot); // Store top level stuff in the context so that other servlets can // access it servletContext.setAttribute("com.gtwm.pb.servlets.databaseDefn", this.databaseDefn); servletContext.setAttribute("com.gtwm.pb.servlets.relationalDataSource", this.relationalDataSource); } catch (NullPointerException npex) { ServletUtilMethods.logException(npex, "Error initialising controller servlet"); throw new ServletException("Error initialising controller servlet", npex); } catch (SQLException sqlex) { ServletUtilMethods.logException(sqlex, "Database error loading schema"); throw new ServletException("Database error loading schema", sqlex); } catch (NamingException neex) { ServletUtilMethods.logException(neex, "Can't get initial context"); throw new ServletException("Can't get initial context"); } catch (RuntimeException rtex) { ServletUtilMethods.logException(rtex, "Runtime initialisation error"); throw new ServletException("Runtime initialisation error", rtex); } catch (Exception ex) { ServletUtilMethods.logException(ex, "General initialisation error"); throw new ServletException("General initialisation error", ex); } logger.info("Application fully loaded"); }
From source file:net.naijatek.myalumni.modules.admin.presentation.action.MaintainSystemModuleAction.java
public ActionForward maintainScroll(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ServletContext sCtx = request.getSession().getServletContext(); List<ScrollVO> allScrolls = new ArrayList<ScrollVO>(); // check to see if the user logged on is a member if (!adminSecurityCheck(request)) { return mapping.findForward(BaseConstants.FWD_ADMIN_LOGIN); }/*from w ww .j a va2 s. c om*/ ScrollForm scrollForm = (ScrollForm) form; if (scrollForm.getType().equalsIgnoreCase("list")) { allScrolls = systemConfigService.getAllScrolls(); setSessionObject(request, BaseConstants.LIST_OF_SCROLLS, allScrolls); } else if (scrollForm.getType().equalsIgnoreCase("update")) { systemConfigService.updateScroll(scrollForm.getScrollId(), getLastModifiedBy(request)); sCtx.setAttribute(BaseConstants.SCROLL_VO, systemConfigService.getLatestScroll()); } else if (scrollForm.getType().equalsIgnoreCase("new")) { ScrollVO scrollVO = new ScrollVO(); BeanUtils.copyProperties(scrollVO, scrollForm); scrollVO.setLastModifiedBy(getLastModifiedBy(request)); scrollVO.setScrollId(null); systemConfigService.addScroll(scrollVO); sCtx.setAttribute(BaseConstants.SCROLL_VO, scrollVO); allScrolls = systemConfigService.getAllScrolls(); setSessionObject(request, BaseConstants.LIST_OF_SCROLLS, allScrolls); } return mapping.findForward(BaseConstants.FWD_SUCCESS); }
From source file:jp.or.openid.eiwg.listener.InitListener.java
/** * Web???/*from www. j a v a 2 s .com*/ * * @param contextEvent */ @Override public void contextInitialized(ServletContextEvent contextEvent) { // ? ServletContext context = contextEvent.getServletContext(); // ??DBLDAP???? // ???????? ObjectMapper mapper = new ObjectMapper(); Map<String, Object> serviceProviderConfigs = null; ArrayList<LinkedHashMap<String, Object>> resourceTypes = null; ArrayList<LinkedHashMap<String, Object>> schemas = null; ArrayList<LinkedHashMap<String, Object>> users = null; // ?(ServiceProviderConfigs.json)?? try { serviceProviderConfigs = mapper.readValue( new File(context.getRealPath("/WEB-INF/ServiceProviderConfigs.json")), new TypeReference<LinkedHashMap<String, Object>>() { }); } catch (IOException e) { e.printStackTrace(); } // (ResourceTypes.json)?? try { resourceTypes = mapper.readValue(new File(context.getRealPath("/WEB-INF/ResourceTypes.json")), new TypeReference<ArrayList<LinkedHashMap<String, Object>>>() { }); } catch (IOException e) { e.printStackTrace(); } // (Schemas.json)?? try { schemas = mapper.readValue(new File(context.getRealPath("/WEB-INF/Schemas.json")), new TypeReference<ArrayList<LinkedHashMap<String, Object>>>() { }); } catch (IOException e) { e.printStackTrace(); } // ?? try { users = mapper.readValue(new File(context.getRealPath("/WEB-INF/Users.json")), new TypeReference<ArrayList<LinkedHashMap<String, Object>>>() { }); } catch (IOException e) { e.printStackTrace(); } // ? context.setAttribute("ServiceProviderConfigs", serviceProviderConfigs); context.setAttribute("ResourceTypes", resourceTypes); context.setAttribute("Schemas", schemas); context.setAttribute("Users", users); }
From source file:com.concursive.connect.config.ApplicationPrefs.java
/** * Configures freemarker for template loading * * @param context the servlet context to store the configuration *//* w ww.j av a2s . c om*/ private void configureFreemarker(ServletContext context) { LOG.info("configureFreemarker"); try { Configuration freemarkerConfiguration = new Configuration(); // Customized templates are stored here File customEmailFolder = new File(get(FILE_LIBRARY_PATH) + "1" + fs + "email"); FileTemplateLoader ftl = null; if (customEmailFolder.exists()) { ftl = new FileTemplateLoader(customEmailFolder); } // Default templates are stored here WebappTemplateLoader wtl = new WebappTemplateLoader(context, "/WEB-INF/email"); // Order the loaders TemplateLoader[] loaders = null; if (ftl != null) { loaders = new TemplateLoader[] { ftl, wtl }; } else { loaders = new TemplateLoader[] { wtl }; } MultiTemplateLoader mtl = new MultiTemplateLoader(loaders); freemarkerConfiguration.setTemplateLoader(mtl); freemarkerConfiguration.setObjectWrapper(new DefaultObjectWrapper()); context.setAttribute(Constants.FREEMARKER_CONFIGURATION, freemarkerConfiguration); } catch (Exception e) { LOG.error("freemarker error", e); } }