List of usage examples for javax.servlet ServletContext setAttribute
public void setAttribute(String name, Object object);
From source file:org.acmsl.commons.utils.http.HttpServletUtils.java
/** * Stores an object in the repository./*from w w w.ja v a2 s. c om*/ * @param object the object to store. * @param key the key. * @param request the request. * @param session the session. * @param servletContext the context. * @return <code>true</code> if the object has been stored successfully. */ public boolean store(@NotNull final Object object, @NotNull final String key, @Nullable final ServletRequest request, @Nullable final HttpSession session, @Nullable final ServletContext servletContext) { boolean result = false; // Thanks Sun for had missed an interface for // all classes that export setAttribute(). if (request != null) { request.setAttribute(key, object); result = true; } if (session != null) { session.setAttribute(key, object); result = true; } if (servletContext != null) { servletContext.setAttribute(key, object); result = true; } return result; }
From source file:uk.ac.ebi.ep.controller.SearchController.java
/** * Retrieves any previous searches stored in the application context. * * @param servletContext the application context. * @return a map of searches to results. *///from w w w . j a v a2 s . c o m @SuppressWarnings("unchecked") protected Map<String, SearchResults> getPreviousSearches(ServletContext servletContext) { Map<String, SearchResults> prevSearches = (Map<String, SearchResults>) servletContext .getAttribute(Attribute.prevSearches.name()); if (prevSearches == null) { // Map implementation which maintains the order of access: prevSearches = Collections.synchronizedMap( new LinkedHashMap<String, SearchResults>(searchConfig.getSearchCacheSize(), 1, true)); servletContext.setAttribute(Attribute.prevSearches.getName(), prevSearches); } return prevSearches; }
From source file:org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.java
/** * Prepare the {@link WebApplicationContext} with the given fully loaded * {@link ServletContext}. This method is usually called from * {@link ServletContextInitializer#onStartup(ServletContext)} and is similar to the * functionality usually provided by a {@link ContextLoaderListener}. * @param servletContext the operational servlet context *///from ww w .j a v a 2 s .c o m protected void prepareWebApplicationContext(ServletContext servletContext) { Object rootContext = servletContext .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (rootContext != null) { if (rootContext == this) { throw new IllegalStateException( "Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ServletContextInitializers!"); } return; } Log logger = LogFactory.getLog(ContextLoader.class); servletContext.log("Initializing Spring embedded WebApplicationContext"); try { servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this); if (logger.isDebugEnabled()) { logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); } setServletContext(servletContext); if (logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - getStartupDate(); logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); } } catch (RuntimeException | Error ex) { logger.error("Context initialization failed", ex); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } }
From source file:br.bireme.web.AuthenticationServlet.java
@Override public void init() { try {// www . j a v a 2 s. com final ServletContext context = getServletContext(); final String host = context.getInitParameter("host"); final int port = Integer.parseInt(context.getInitParameter("port")); final String user = context.getInitParameter("username"); final String password = context.getInitParameter("password"); final MongoClient mongoClient = new MongoClient(host, port); final DB db = mongoClient.getDB(SOCIAL_CHECK_DB); if (!user.trim().isEmpty()) { final boolean auth = db.authenticate(user, password.toCharArray()); if (!auth) { throw new IllegalArgumentException("invalid user/password"); } } final DBCollection coll = db.getCollection(BROKEN_LINKS_COL); final DBCollection hcoll = db.getCollection(HISTORY_COL); context.setAttribute("collection", coll); context.setAttribute("historycoll", hcoll); context.setAttribute("readOnlyMode", false); } catch (UnknownHostException ex) { Logger.getLogger(AuthenticationServlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.springframework.boot.legacy.context.web.NonEmbeddedWebApplicationContext.java
/** * Prepare the {@link WebApplicationContext} with the given fully loaded * {@link ServletContext}. This method is usually called from * {@link ServletContextInitializer#onStartup(ServletContext)} and is similar to the * functionality usually provided by a {@link ContextLoaderListener}. * @param servletContext the operational servlet context *//* w w w . j a va2 s. com*/ protected void prepareWebApplicationContext(ServletContext servletContext) { Object rootContext = servletContext .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (rootContext != null) { if (rootContext == this) { throw new IllegalStateException( "Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ServletContextInitializers!"); } else { return; } } Log logger = LogFactory.getLog(ContextLoader.class); servletContext.log("Initializing Spring embedded WebApplicationContext"); WebApplicationContextUtils.registerWebApplicationScopes(getBeanFactory(), getServletContext()); WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), getServletContext()); try { servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this); if (logger.isDebugEnabled()) { logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); } if (logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - getStartupDate(); logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); } } catch (RuntimeException ex) { logger.error("Context initialization failed", ex); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } catch (Error ex) { logger.error("Context initialization failed", ex); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } }
From source file:org.apache.pluto.driver.PortalStartupListener.java
/** * Receives the startup notification and subsequently starts up the portal * driver. The following are done in this order: * <ol>//from ww w . j a v a2 s .c o m * <li>Retrieve the ResourceConfig File</li> * <li>Parse the ResourceConfig File into ResourceConfig Objects</li> * <li>Create a Portal Context</li> * <li>Create the ContainerServices implementation</li> * <li>Create the Portlet Container</li> * <li>Initialize the Container</li> * <li>Bind the configuration to the ServletContext</li> * <li>Bind the container to the ServletContext</li> * <ol> * * @param event the servlet context event. */ public void contextInitialized(ServletContextEvent event) { LOG.info("Starting up Pluto Portal Driver. . ."); ServletContext servletContext = event.getServletContext(); WebApplicationContext springContext = null; try { springContext = (WebApplicationContext) servletContext .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); } catch (RuntimeException ex) { String msg = "Problem getting Spring context: " + ex.getMessage(); LOG.error(msg, ex); throw ex; } LOG.debug(" [1a] Loading DriverConfiguration. . . "); DriverConfiguration driverConfiguration = (DriverConfiguration) springContext .getBean("DriverConfiguration"); driverConfiguration.init(servletContext); LOG.debug(" [1b] Registering DriverConfiguration. . ."); servletContext.setAttribute(DRIVER_CONFIG_KEY, driverConfiguration); LOG.debug(" [2a] Loading Optional AdminConfiguration. . ."); AdminConfiguration adminConfiguration = (AdminConfiguration) springContext.getBean("AdminConfiguration"); if (adminConfiguration != null) { LOG.debug(" [2b] Registering Optional AdminConfiguration"); servletContext.setAttribute(ADMIN_CONFIG_KEY, adminConfiguration); } else { LOG.info("Optional AdminConfiguration not found. Ignoring."); } // LOG.debug(" [3a] Loading VWBConfiguration. . ."); // VWBConfiguration vwbconfig = (VWBConfiguration)springContext.getBean("VWBConfiguration"); // vwbconfig.init(servletContext); // LOG.debug(" [3b] Registering VWBConfiguration. . ."); // servletContext.setAttribute(VWB_CONFIG_KEY, vwbconfig); // PortalSessionServiceImpl.init(vwbconfig); initContainer(servletContext); LOG.info("********** Pluto Portal Driver Started **********\n\n"); }
From source file:org.carrot2.webapp.LogInitContextListener.java
/** * Callback hook from the application container. Initialize logging appenders * immediately or defer initialization until possible. *///from w w w. j av a2 s . c om public void contextInitialized(ServletContextEvent event) { final ServletContext servletContext = event.getServletContext(); if (servletContext.getAttribute(CONTEXT_ID) != null) { // Only one instance needed. return; } /* * If the container has Servlet 2.5 API, init loggers immediately. Otherwise, save * itself to the context and wait for {@link QueryProcessorServlet} to perform * deferred initialization. */ try { final Method method = ServletContext.class.getMethod("getContextPath"); final String contextPath = (String) method.invoke(servletContext); addAppenders(contextPath); } catch (RuntimeException e) { // Rethrow runtime exceptions, if any. throw e; } catch (Exception e) { /* * No servlet 2.5 API (getContextPath), save in the context for deferred * initialization. */ servletContext.setAttribute(CONTEXT_ID, this); } }
From source file:edu.lternet.pasta.portal.BrowseServlet.java
/** * Initialization of the servlet. <br> * //w w w . j a v a 2 s . co m * @throws ServletException * if an error occurs */ public void init() throws ServletException { ServletContext servletContext = getServletContext(); PropertiesConfiguration options = ConfigurationListener.getOptions(); xslpath = options.getString("resultsetutility.xslpath"); cwd = options.getString("system.cwd"); String browseDirPath = options.getString("browse.dir"); BrowseSearch.setBrowseCacheDir(browseDirPath); BrowseSearch browseSearch = null; BrowseGroup browseGroup = null; File browseKeywordFile = new File(BrowseSearch.browseKeywordPath); if (browseKeywordFile.exists()) { browseSearch = new BrowseSearch(); browseGroup = browseSearch.readBrowseCache(browseKeywordFile); /* Lock the servlet context object to guarantee that only one thread at a * time can be getting or setting the context attribute. */ synchronized (servletContext) { servletContext.setAttribute("browseKeywordHTML", browseGroup.toHTML()); } } else { logger.warn("Missing browse keyword file at location: " + BrowseSearch.browseKeywordPath); } }
From source file:org.topazproject.ambra.auth.web.AuthServletContextListener.java
public void contextInitialized(final ServletContextEvent event) { final ServletContext context = event.getServletContext(); Configuration conf = ConfigurationStore.getInstance().getConfiguration(); String url = conf.getString(PREF + "url"); final Properties dbProperties = new Properties(); dbProperties.setProperty("url", url); dbProperties.setProperty("user", conf.getString(PREF + "user")); dbProperties.setProperty("password", conf.getString(PREF + "password")); try {/*from w ww. j a v a2s. c o m*/ dbContext = DatabaseContext.createDatabaseContext(conf.getString(PREF + "driver"), dbProperties, conf.getInt(PREF + "initialSize"), conf.getInt(PREF + "maxActive"), conf.getString(PREF + "connectionValidationQuery")); } catch (final DatabaseException ex) { throw new Error("Failed to initialize the database context to '" + url + "'", ex); } final UserService userService = new UserService(dbContext, conf.getString(PREF + "usernameToGuidSql"), conf.getString(PREF + "guidToUsernameSql")); context.setAttribute(AuthConstants.USER_SERVICE, userService); }
From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2ProtocolServiceTest.java
@Test public void testHandleReturnResponse() throws Exception { // setup/*from ww w .ja v a2 s .co m*/ SAML2ProtocolServiceAuthIdent saml2ProtocolService = new SAML2ProtocolServiceAuthIdent(); String userId = UUID.randomUUID().toString(); String givenName = "test-given-name"; String surName = "test-sur-name"; Identity identity = new Identity(); identity.name = surName; identity.firstName = givenName; identity.gender = Gender.MALE; identity.dateOfBirth = new GregorianCalendar(); identity.nationality = "BELG"; identity.placeOfBirth = "Gent"; HttpSession mockHttpSession = EasyMock.createMock(HttpSession.class); HttpServletRequest mockHttpServletRequest = EasyMock.createMock(HttpServletRequest.class); HttpServletResponse mockHttpServletResponse = EasyMock.createMock(HttpServletResponse.class); ServletContext mockServletContext = EasyMock.createMock(ServletContext.class); KeyPair keyPair = generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusMonths(1); X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=Test", notBefore, notAfter); IdPIdentity idpIdentity = new IdPIdentity("test", new KeyStore.PrivateKeyEntry(keyPair.getPrivate(), new Certificate[] { certificate })); IdentityProviderConfiguration mockConfiguration = EasyMock.createMock(IdentityProviderConfiguration.class); // expectations mockServletContext.setAttribute(AbstractSAML2ProtocolService.IDP_CONFIG_CONTEXT_ATTRIBUTE, mockConfiguration); EasyMock.expect(mockHttpSession.getServletContext()).andReturn(mockServletContext); EasyMock.expect(mockServletContext.getAttribute(AbstractSAML2ProtocolService.IDP_CONFIG_CONTEXT_ATTRIBUTE)) .andReturn(mockConfiguration); EasyMock.expect(mockHttpSession.getAttribute(AbstractSAML2ProtocolService.TARGET_URL_SESSION_ATTRIBUTE)) .andStubReturn("http://127.0.0.1"); EasyMock.expect(mockHttpSession.getAttribute(AbstractSAML2ProtocolService.RELAY_STATE_SESSION_ATTRIBUTE)) .andStubReturn("relay-state"); EasyMock.expect(mockHttpSession.getAttribute(AbstractSAML2ProtocolService.IN_RESPONSE_TO_SESSION_ATTRIBUTE)) .andStubReturn("a77a1c87-e590-47d7-a3e0-afea455ebc01"); EasyMock.expect(mockHttpSession.getAttribute(AbstractSAML2ProtocolService.ISSUER_SESSION_ATTRIBUTE)) .andStubReturn("Issuer"); EasyMock.expect(mockHttpServletRequest.getSession()).andReturn(mockHttpSession); EasyMock.expect(mockHttpSession.getServletContext()).andReturn(mockServletContext); EasyMock.expect(mockServletContext.getAttribute(AbstractSAML2ProtocolService.IDP_CONFIG_CONTEXT_ATTRIBUTE)) .andReturn(mockConfiguration); EasyMock.expect(mockConfiguration.getResponseTokenValidity()).andStubReturn(5); EasyMock.expect(mockConfiguration.findIdentity()).andStubReturn(idpIdentity); EasyMock.expect(mockConfiguration.getIdentityCertificateChain()) .andStubReturn(Collections.singletonList(certificate)); EasyMock.expect(mockConfiguration.getDefaultIssuer()).andStubReturn("TestIssuer"); // prepare EasyMock.replay(mockHttpServletRequest, mockHttpSession, mockServletContext, mockConfiguration); // operate saml2ProtocolService.init(mockServletContext, mockConfiguration); ReturnResponse returnResponse = saml2ProtocolService.handleReturnResponse(mockHttpSession, userId, new HashMap<String, Attribute>(), null, null, null, mockHttpServletRequest, mockHttpServletResponse); // verify EasyMock.verify(mockHttpServletRequest, mockHttpSession, mockServletContext, mockConfiguration); assertNotNull(returnResponse); assertEquals("http://127.0.0.1", returnResponse.getActionUrl()); List<NameValuePair> attributes = returnResponse.getAttributes(); assertNotNull(attributes); NameValuePair relayStateAttribute = null; NameValuePair samlResponseAttribute = null; for (NameValuePair attribute : attributes) { if ("RelayState".equals(attribute.getName())) { relayStateAttribute = attribute; continue; } if ("SAMLResponse".equals(attribute.getName())) { samlResponseAttribute = attribute; continue; } } assertNotNull(relayStateAttribute); assertEquals("relay-state", relayStateAttribute.getValue()); assertNotNull("no SAMLResponse attribute", samlResponseAttribute); String encodedSamlResponse = samlResponseAttribute.getValue(); assertNotNull(encodedSamlResponse); String samlResponse = new String(Base64.decodeBase64(encodedSamlResponse)); LOG.debug("SAML response: " + samlResponse); File tmpFile = File.createTempFile("saml-response-", ".xml"); FileUtils.writeStringToFile(tmpFile, samlResponse); LOG.debug("tmp file: " + tmpFile.getAbsolutePath()); }