List of usage examples for javax.servlet ServletContext removeAttribute
public void removeAttribute(String name);
From source file:org.red5.server.war.RootContextLoaderServlet.java
/** * Clearing the in-memory configuration parameters, we will receive * notification that the servlet context is about to be shut down *///from w w w . j a va 2s . co m @Override public void contextDestroyed(ServletContextEvent sce) { synchronized (instance) { logger.info("Webapp shutdown"); // XXX Paul: grabbed this from // http://opensource.atlassian.com/confluence/spring/display/DISC/Memory+leak+-+classloader+won%27t+let+go // in hopes that we can clear all the issues with J2EE containers // during shutdown try { ServletContext ctx = sce.getServletContext(); // if the ctx being destroyed is root then kill the timer if (ctx.getContextPath().equals("/ROOT")) { timer.cancel(); } else { // remove from registered list registeredContexts.remove(ctx); } // prepare spring for shutdown Introspector.flushCaches(); // dereg any drivers for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements();) { Driver driver = (Driver) e.nextElement(); if (driver.getClass().getClassLoader() == getClass().getClassLoader()) { DriverManager.deregisterDriver(driver); } } // shutdown jmx JMXAgent.shutdown(); // shutdown spring Object attr = ctx.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (attr != null) { // get web application context from the servlet context ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) attr; ConfigurableBeanFactory factory = applicationContext.getBeanFactory(); // for (String scope : factory.getRegisteredScopeNames()) { // logger.debug("Registered scope: " + scope); // } try { for (String singleton : factory.getSingletonNames()) { logger.debug("Registered singleton: " + singleton); factory.destroyScopedBean(singleton); } } catch (RuntimeException e) { } factory.destroySingletons(); ctx.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); applicationContext.close(); } instance.getContextLoader().closeWebApplicationContext(ctx); } catch (Throwable e) { e.printStackTrace(); } finally { // http://jakarta.apache.org/commons/logging/guide.html#Classloader_and_Memory_Management // http://wiki.apache.org/jakarta-commons/Logging/UndeployMemoryLeak?action=print LogFactory.release(Thread.currentThread().getContextClassLoader()); } } }
From source file:org.artifactory.webapp.servlet.ArtifactoryContextConfigListener.java
@Override public void contextInitialized(ServletContextEvent event) { final ServletContext servletContext = event.getServletContext(); setSessionTrackingMode(servletContext); final Thread initThread = new Thread("art-init") { boolean success = true; @SuppressWarnings({ "unchecked" }) @Override// w w w. jav a 2 s .c o m public void run() { try { //Use custom logger String contextId = HttpUtils.getContextId(servletContext); //Build a partial config, since we expect the logger-context to exit in the selector cache by only contextId LoggerConfigInfo configInfo = new LoggerConfigInfo(contextId); LogbackContextSelector.bindConfig(configInfo); //No log field since needs to lazy initialize only after logback customization listener has run Logger log = getLogger(); configure(servletContext, log); LogbackContextSelector.unbindConfig(); } catch (Exception e) { getLogger().error( "Application could not be initialized: " + ExceptionUtils.getRootCause(e).getMessage(), e); success = false; } finally { if (success) { //Run the waiting filters BlockingQueue<DelayedInit> waitingFiltersQueue = (BlockingQueue<DelayedInit>) servletContext .getAttribute(DelayedInit.APPLICATION_CONTEXT_LOCK_KEY); List<DelayedInit> waitingInits = new ArrayList<>(); waitingFiltersQueue.drainTo(waitingInits); for (DelayedInit filter : waitingInits) { try { filter.delayedInit(); } catch (ServletException e) { getLogger().error("Could not init {}.", filter.getClass().getName(), e); success = false; break; } } } //Remove the lock and open the app to requests servletContext.removeAttribute(DelayedInit.APPLICATION_CONTEXT_LOCK_KEY); } } }; initThread.setDaemon(true); servletContext.setAttribute(DelayedInit.APPLICATION_CONTEXT_LOCK_KEY, new LinkedBlockingQueue<DelayedInit>()); initThread.start(); if (Boolean.getBoolean("artifactory.init.useServletContext")) { try { getLogger().info("Waiting for servlet context initialization ..."); initThread.join(); } catch (InterruptedException e) { getLogger().error("Artifactory initialization thread got interrupted", e); } } }
From source file:com.sonicle.webtop.core.app.ContextLoader.java
public void initApp(ServletContext servletContext) throws IllegalStateException { String webappName = ContextUtils.getWebappFullName(servletContext, false); servletContext.setAttribute(WEBAPPNAME_ATTRIBUTE_KEY, webappName); if (servletContext.getAttribute(WEBTOPAPP_ATTRIBUTE_KEY) != null) { throw new IllegalStateException( "There is already a WebTop application associated with the current ServletContext."); }/*from w w w .j av a 2 s . c o m*/ try { WebTopApp wta = new WebTopApp(servletContext); wta.boot(); servletContext.setAttribute(WEBTOPAPP_ATTRIBUTE_KEY, wta); servletContext.setAttribute(JWTSignatureVerifier.SECRET_CONTEXT_ATTRIBUTE, wta.getDocumentServerSecretIn()); Dynamic atmosphereServlet = servletContext.addServlet("AtmosphereServlet", com.sonicle.webtop.core.app.atmosphere.AtmosphereServlet.class); atmosphereServlet.setInitParameter("org.atmosphere.cpr.AtmosphereFramework.analytics", "false"); atmosphereServlet.setInitParameter("org.atmosphere.cpr.broadcasterCacheClass", "com.sonicle.webtop.core.app.atmosphere.UUIDBroadcasterCache"); atmosphereServlet.setInitParameter("org.atmosphere.cpr.broadcasterLifeCyclePolicy", "BroadcasterLifeCyclePolicy.EMPTY"); atmosphereServlet.setInitParameter("org.atmosphere.cpr.asyncSupport", "org.atmosphere.container.JSR356AsyncSupport"); //atmosphereServlet.setInitParameter("org.atmosphere.cpr.asyncSupport", "org.atmosphere.container.Tomcat7CometSupport"); atmosphereServlet.setInitParameter("org.atmosphere.cpr.sessionSupport", "true"); atmosphereServlet.setInitParameter("org.atmosphere.cpr.sessionCreate", "false"); atmosphereServlet.setInitParameter("org.atmosphere.cpr.broadcaster.shareableThreadPool", "true"); atmosphereServlet.setInitParameter("org.atmosphere.cpr.AtmosphereInterceptor", "org.atmosphere.interceptor.ShiroInterceptor"); atmosphereServlet.setLoadOnStartup(1); atmosphereServlet.setAsyncSupported(true); atmosphereServlet.addMapping(com.sonicle.webtop.core.app.atmosphere.AtmosphereServlet.URL + "/*"); Dynamic resourcesServlet = servletContext.addServlet("ResourcesServlet", com.sonicle.webtop.core.app.servlet.ResourceRequest.class); resourcesServlet.setLoadOnStartup(1); resourcesServlet.addMapping(com.sonicle.webtop.core.app.servlet.ResourceRequest.URL + "/*"); Dynamic loginServlet = servletContext.addServlet("LoginServlet", com.sonicle.webtop.core.app.servlet.Login.class); loginServlet.setLoadOnStartup(1); loginServlet.addMapping(com.sonicle.webtop.core.app.servlet.Login.URL + "/*"); Dynamic logoutServlet = servletContext.addServlet("LogoutServlet", com.sonicle.webtop.core.app.servlet.Logout.class); logoutServlet.setLoadOnStartup(1); logoutServlet.addMapping(com.sonicle.webtop.core.app.servlet.Logout.URL + "/*"); Dynamic otpServlet = servletContext.addServlet("OtpServlet", com.sonicle.webtop.core.app.servlet.Otp.class); otpServlet.setLoadOnStartup(1); otpServlet.addMapping(com.sonicle.webtop.core.app.servlet.Otp.URL + "/*"); Dynamic uiPrivateServlet = servletContext.addServlet("UIPrivateServlet", com.sonicle.webtop.core.app.servlet.UIPrivate.class); uiPrivateServlet.setLoadOnStartup(1); uiPrivateServlet.addMapping(com.sonicle.webtop.core.app.servlet.UIPrivate.URL + "/*"); Dynamic privateRequestServlet = servletContext.addServlet("PrivateRequestServlet", com.sonicle.webtop.core.app.servlet.PrivateRequest.class); privateRequestServlet.setLoadOnStartup(1); privateRequestServlet.addMapping(com.sonicle.webtop.core.app.servlet.PrivateRequest.URL + "/*"); privateRequestServlet.addMapping(com.sonicle.webtop.core.app.servlet.PrivateRequest.URL_LEGACY + "/*"); Dynamic publicRequestServlet = servletContext.addServlet("PublicRequestServlet", com.sonicle.webtop.core.app.servlet.PublicRequest.class); publicRequestServlet.setLoadOnStartup(1); publicRequestServlet.addMapping(com.sonicle.webtop.core.app.servlet.PublicRequest.URL + "/*"); Dynamic docEditorServlet = servletContext.addServlet("DocEditorServlet", com.sonicle.webtop.core.app.servlet.DocEditor.class); docEditorServlet.setLoadOnStartup(1); docEditorServlet.addMapping(com.sonicle.webtop.core.app.servlet.DocEditor.URL + "/*"); // Adds RestApiServlets dynamically ServiceManager svcMgr = wta.getServiceManager(); for (String serviceId : svcMgr.listRegisteredServices()) { ServiceDescriptor desc = svcMgr.getDescriptor(serviceId); if (desc.hasOpenApiDefinitions() || desc.hasRestApiEndpoints()) { addRestApiServlet(servletContext, desc); } } } catch (Throwable t) { servletContext.removeAttribute(WEBTOPAPP_ATTRIBUTE_KEY); logger.error("Error initializing WTA [{}]", webappName, t); } }
From source file:com.aurel.track.prop.LoginBL.java
/** * * @param username//from w w w . j av a 2 s .c o m * @param userPwd * @param nonce * @param request * @param anonymousLogin * @return Map with two entries: 1. "errors": ArrayList<LabelValueBean>; 2. * "mappingEnum": Integer with 2: bad credentials, 6: license * problems, 7: forward to URL, 8: first time admin user, 18: * request license, 9: standard login * */ public static Map<String, Object> setEnvironment(String username, String userPwd, String nonce, HttpServletRequest request, Map<String, Object> sessionMap, boolean anonymousLogin, boolean usingContainerBasedAuthentication, boolean springAuthenticated) { HttpSession httpSession = request.getSession(); ArrayList<LabelValueBean> errors = new ArrayList<LabelValueBean>(); HashMap<String, Object> result = new HashMap<String, Object>(); Integer mappingEnum = 0; // Make things robust if (username == null) { username = "x"; } if (userPwd == null) { userPwd = "x"; } // Move locale to one that we actually have, in case there // was a request for a locale that we do not have Locale locale = LocaleHandler.getExistingLocale(request.getLocales()); LocaleHandler.exportLocaleToSession(sessionMap, locale); Support support = new Support(); support.setURIs(request); if (username != null) { ACCESSLOGGER.info("LOGON: User '" + username.trim() + "' trying to log on" + " at " + new Date().toString() + " from " + request.getRemoteAddr()); } ServletContext servletContext = org.apache.struts2.ServletActionContext.getServletContext(); try { if (!Torque.isInit()) { Torque.init(HandleHome.getTorqueProperties(servletContext, true)); LOGGER.debug("Database is " + Torque.getDefaultDB()); LOGGER.info("Torque was re-initialized."); } } catch (Exception e) { LOGGER.error(e.getMessage()); LOGGER.error("Could not initialize Torque (1)"); LOGGER.error(ExceptionUtils.getStackTrace(e)); errors.add(new LabelValueBean("errGeneralError", getText("logon.err.noDataBase", locale) + ":" + e.getMessage())); mappingEnum = 1; result.put("errors", errors); result.put("mappingEnum", mappingEnum); return result; } TPersonBean personBean = null; if (anonymousLogin) { personBean = PersonBL.getAnonymousIfActive(); } else { try { String pwd = ""; if (nonce == null || nonce.length() == 0) { pwd = userPwd; // clear text } else { pwd = decrypt(nonce.charAt(0), userPwd); // key is first // character of // nonce } personBean = PersonBL.loadByLoginNameWithRights(username); if (personBean != null) { personBean.setPlainPwd(pwd); if (personBean.isDisabled()) { errors.add( new LabelValueBean("errCredentials", getText("logon.err.user.disabled", locale))); ACCESSLOGGER .warn("LOGON: User " + personBean.getLoginName() + " is disabled, login refused!"); } else if (usingContainerBasedAuthentication == false && springAuthenticated == false && !personBean.authenticate(pwd)) { ACCESSLOGGER.warn("LOGON: Wrong password given for user " + personBean.getFullName() + " at " + new Date().toString() + " from " + request.getRemoteAddr()); errors.add(new LabelValueBean("errCredentials", getText("logon.err.password.mismatch", locale))); } } else { ACCESSLOGGER.warn("LOGON: No such user: " + username + " at " + new Date().toString() + " from " + request.getRemoteAddr()); errors.add( new LabelValueBean("errCredentials", getText("logon.err.password.mismatch", locale))); LOGGER.debug("User '" + username + "' is not in database..."); } } catch (Exception e) { LOGGER.error(e.getMessage()); LOGGER.error("Could not initialize Torque (2)"); LOGGER.error(ExceptionUtils.getStackTrace(e)); errors.add(new LabelValueBean("errGeneralError", getText("logon.err.noDataBase", locale))); } } if (errors.size() > 0 || personBean == null) { mappingEnum = 2; result.put("errors", errors); result.put("mappingEnum", mappingEnum); return result; } // At this point, we have successfully identified the user. // Try to set the users preferred locale if (personBean.getPrefLocale() != null && !"".equals(personBean.getPrefLocale())) { // get as stored in user profile locale = LocaleHandler.getExistingLocale(LocaleHandler.getLocaleFromString(personBean.getPrefLocale())); } if (locale == null) { // rely on browser settings locale = LocaleHandler.getExistingLocale(request.getLocales()); } personBean.setLocale(locale); // set the bean with the last saved login date and save the actual date // as // last login date in the database personBean.setLastButOneLogin(personBean.getLastLogin()); personBean.setLastLogin(new Date()); PersonBL.saveSimple(personBean); LocaleHandler.exportLocaleToSession(sessionMap, locale); // ----------------------------------------------------- // check if opState // (reject users, but not admin, in maintenance state) ApplicationBean appBean = ApplicationBean.getInstance(); if (appBean == null) { LOGGER.error("appBean == null: this should never happen"); mappingEnum = 3; result.put("errors", errors); result.put("mappingEnum", mappingEnum); return result; } httpSession.setAttribute(Constants.APPLICATION_BEAN, appBean); TSiteBean siteBean = DAOFactory.getFactory().getSiteDAO().load1(); if (ApplicationBean.OPSTATE_MAINTENNANCE.equals(siteBean.getOpState()) && !personBean.getIsSysAdmin()) { // print error, refuse login errors.add(new LabelValueBean("errGeneralError", getText("logon.err.maintenance", locale))); mappingEnum = 4; result.put("errors", errors); result.put("mappingEnum", mappingEnum); return result; } Runtime rt = Runtime.getRuntime(); long mbyte = 1024 * 1024; long freeMemoryMB = rt.freeMemory() / mbyte; if (freeMemoryMB < 50 && !personBean.getIsSysAdmin()) { rt.gc(); freeMemoryMB = rt.freeMemory() / mbyte; if (freeMemoryMB < 50) { errors.add(new LabelValueBean("errGeneralError", getText("logon.err.freeMemory", locale))); mappingEnum = 19; result.put("errors", errors); result.put("mappingEnum", mappingEnum); return result; } } // Save our logged-in user in the session // and set a cookie so she can conveniently point // directly to issues without having to log on for // the next CookieTimeout seconds httpSession.setAttribute(Constants.USER_KEY, personBean); int maxItemsProUser = GeneralSettings.getMaxItems(); FilterUpperTO filterUpperTO = new FilterUpperTO(); TreeFilterExecuterFacade.prepareFilterUpperTO(filterUpperTO, personBean, locale, null, null); int noOfProjectRoleItemsProUser = LoadTreeFilterItemCounts.countTreeFilterProjectRoleItems(filterUpperTO, personBean, locale, maxItemsProUser); int noOfRACIRoleItemsProUser = LoadTreeFilterItemCounts.countTreeFilterRACIRoleItems(filterUpperTO, personBean, locale, maxItemsProUser); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Maximum number of items per user " + maxItemsProUser); LOGGER.debug( "Number of project role items accessible by " + username + ": " + noOfProjectRoleItemsProUser); LOGGER.debug("Number of RACI role items accessible by " + username + ": " + noOfRACIRoleItemsProUser); } boolean projectRoleItemsAboveLimit = noOfProjectRoleItemsProUser >= maxItemsProUser; boolean raciRoleItemsAboveLimit = noOfRACIRoleItemsProUser >= maxItemsProUser; personBean.setProjectRoleItemsAboveLimit(Boolean.valueOf(projectRoleItemsAboveLimit)); personBean.setRaciRoleItemsAboveLimit(Boolean.valueOf(raciRoleItemsAboveLimit)); PersonBL.setLicensedFeatures(personBean); List<TListTypeBean> issueTypes = IssueTypeBL.loadAllByPerson(personBean.getObjectID(), locale); httpSession.setAttribute("issueTypesJSON", JSONUtility.encodeIssueTypes(issueTypes)); Integer sessionTimeoutMinutes = personBean.getSessionTimeoutMinutes(); if (sessionTimeoutMinutes != null && sessionTimeoutMinutes.intValue() != 0) { httpSession.setMaxInactiveInterval(sessionTimeoutMinutes * 60); } // load the my filters in the menu List<FilterInMenuTO> myFilters = FilterBL.loadMyMenuFiltersWithTooltip(personBean, locale); httpSession.setAttribute(FilterBL.MY_MENU_FILTERS_JSON, FilterInMenuJSON.encodeFiltersInMenu(myFilters)); List<FilterInMenuTO> lastQueries = FilterInMenuBL.getLastExecutedQueries(personBean, locale); httpSession.setAttribute(FilterBL.LAST_EXECUTED_FILTERS_JSON, FilterInMenuJSON.encodeFiltersInMenu(lastQueries)); httpSession.setAttribute(ShortcutBL.SHORTCUTS_JSON, ShortcutBL.encodeShortcutsJSON()); // modules List modules = getModuleDescriptors(personBean); httpSession.setAttribute("usedModules", modules); httpSession.setAttribute("usedModulesJSON", MasterHomeJSON.encodeModules(modules, personBean)); httpSession.setAttribute("loggedInPersonUserLevel", personBean.getUserLevel()); httpSession.setAttribute("clientUserLevelID", TPersonBean.USERLEVEL.CLIENT); // maxFileSize int maxFileSize = AttachBL.getMaxFileSize(siteBean); httpSession.setAttribute("MAXFILESIZE", maxFileSize); // ------------------------------------------------------ // Create a new SessionBean for this session and bind it to the session SessionBean sBean = new SessionBean(); httpSession.setAttribute(Constants.SESSION_BEAN, sBean); ItemLockBL.removeLockedIssuesByUser(personBean.getObjectID()); ACCESSLOGGER.info("LOGON: User '" + personBean.getLoginName().trim() + "' (" + personBean.getFullName() + ")" + " logged in at " + new Date().toString() + " from " + request.getRemoteAddr()); LicenseManager lm = appBean.getLicenseManager(); if (lm != null) { int rf = lm.getErrorCode(); boolean haveLicenseErrors = false; switch (rf) { case 1: haveLicenseErrors = true; errors.add( new LabelValueBean("errLicenseError", getText("logon.err.license.needCommercial", locale))); break; case 2: haveLicenseErrors = true; errors.add(new LabelValueBean("errLicenseError", getText("logon.err.license.expired", locale))); break; case 3: haveLicenseErrors = true; errors.add( new LabelValueBean("errLicenseError", getText("logon.err.license.full.exceeded", locale))); break; case 4: haveLicenseErrors = true; errors.add(new LabelValueBean("errLicenseError", getText("logon.err.license.invalid", new String[] { ApplicationBean.getIpNumbersString() }, locale))); break; case 7: haveLicenseErrors = true; errors.add(new LabelValueBean("errLicenseError", getText("logon.err.license.limited.exceeded", locale))); break; case 8: haveLicenseErrors = true; errors.add( new LabelValueBean("errLicenseError", getText("logon.err.license.gantt.exceeded", locale))); break; default: break; } if (haveLicenseErrors == true) { mappingEnum = 6; result.put("errors", errors); result.put("mappingEnum", mappingEnum); return result; } } result.put("errors", errors); httpSession.setAttribute("DESIGNPATH", personBean.getDesignPath()); Boolean isMobileDevice = LogoffBL.isThisAMobileDevice(request); httpSession.setAttribute("mobile", isMobileDevice); LOGGER.debug("Mobile is " + httpSession.getAttribute("mobile")); // check for post-login forward String forwardUrl = (String) httpSession.getAttribute(Constants.POSTLOGINFORWARD); if (forwardUrl != null) { LOGGER.debug("Forward URL found :" + forwardUrl); mappingEnum = 7; result.put("mappingEnum", mappingEnum); return result; } Map ret = new GroovyScriptExecuter().handleEvent(IEventSubscriber.EVENT_POST_USER_LOGGED_IN, new HashMap()); if (ret.get(BINDING_PARAMS.CONTINUE).equals(Boolean.FALSE)) { mappingEnum = 10; result.put("mappingEnum", mappingEnum); return result; } String extendedKey = ApplicationBean.getInstance().getExtendedKey(); if (extendedKey == null || extendedKey.length() < 10) { // no empty keys // allowed mappingEnum = 18; result.put("mappingEnum", mappingEnum); return result; } String firstTime = (String) servletContext.getAttribute("FirstTime"); result.put("user", personBean); if (personBean.getIsSysAdmin() && firstTime != null && firstTime.equals("FT")) { servletContext.removeAttribute("FirstTime"); mappingEnum = 8; result.put("mappingEnum", mappingEnum); return result; } else { // Forward control to the specified success URI mappingEnum = 9; result.put("mappingEnum", mappingEnum); return result; } }