List of usage examples for javax.servlet ServletContext setAttribute
public void setAttribute(String name, Object object);
From source file:ro.cs.cm.start.InitApplication.java
/** * Initializarea contextului. Aici se preiau nomenclatoarele ce se vor * pastra pe sesiune// w w w . j a v a 2 s . c o m */ public void init(ServletConfig conf) throws ServletException { logger.info("Initializare aplicatie..."); try { ServletContext sc = conf.getServletContext(); logger.info("*******************************************************"); logger.info("* *"); logger.info("* INITIATING APPLICATION CLIENT MANAGEMENT-> *"); logger.info("* *"); logger.info("*******************************************************"); logger.info(IConstant.APP_VERSION.concat("/").concat(IConstant.APP_RELEASE_DATE)); sc.setAttribute("VERSION", IConstant.APP_VERSION); sc.setAttribute("RELEASE_DATE", IConstant.APP_RELEASE_DATE); sc.setAttribute("RELEASE_YEAR", IConstant.APP_RELEASE_YEAR); //Nomenclators ListLoader.getInstance().load_nom_resultsPerPage(); // PROJECT ListLoader.getInstance().load_nom_projectStatus(); // PROJECT TEAM ListLoader.getInstance().load_nom_projectTeamStatus(); // TEAM MEMBER ListLoader.getInstance().load_nom_teamMemberStatus(); // CLIENT ListLoader.getInstance().load_nom_clientType(); ListLoader.getInstance().load_nom_clientStatus(); RoleVoter rv = (RoleVoter) CMContext.getApplicationContext().getBean("roleVoter"); // put exceptionContant bean on servletContect sc.setAttribute(IConstant.EXCEPTION_CONSTANT, ExceptionConstant.getInstance()); sc.setAttribute(IConstant.PERMISSION_CONSTANT, PermissionConstant.getInstance()); sc.setAttribute(IConstant.BACK_CONSTANT, BackConstant.getInstance()); // initialize scheduler initScheduler(true); // job for deleting project details deleteProjectDetailJob(); // job for finishing project details finishProjectDetailJob(); // job for aborting project details abortProjectDetailJob(); // open for opening project details openProjectDetailJob(); // job for deleting team member details deleteTeamMemberDetailJob(); logger.info("Role Prefix: \"" + rv.getRolePrefix() + "\""); logger.info("*******************************************************"); logger.info("* *"); logger.info("* INITIATING APPLICATION END CLIENT MANAGEMENT<- *"); logger.info("* *"); logger.info("*******************************************************"); } catch (Exception ex) { logger.info("*******************************************************"); logger.info("* *"); logger.info("* ERROR INITIATING APPLICATION!!! *"); logger.info("* *"); logger.info("*******************************************************"); logger.error("", ex); } logger.info("The application was initiated!"); }
From source file:org.mobicents.servlet.sip.restcomm.callmanager.mgcp.MgcpCallManager.java
@Override public final void init(final ServletConfig config) throws ServletException { try {/*w w w.java 2s. c om*/ final ServletContext context = config.getServletContext(); LOGGER.info( "initializing the servlet with context:" + context + " ServerInfo:" + context.getServerInfo() + " ServletContextName:" + context.getServletContextName() + " config:" + config); context.setAttribute("org.mobicents.servlet.sip.restcomm.callmanager.CallManager", this); try { Bootstrapper.bootstrap(config); } catch (final BootstrapException exception) { throw new ServletException(exception); } sipFactory = (SipFactory) config.getServletContext().getAttribute(SIP_FACTORY); final ServiceLocator services = ServiceLocator.getInstance(); servers = services.get(MgcpServerManager.class); configuration = services.get(Configuration.class); proxyUser = configuration.getString("outbound-proxy-user"); proxyPassword = configuration.getString("outbound-proxy-password"); final String uri = configuration.getString("outbound-proxy-uri"); if (uri != null && !uri.isEmpty()) { proxyUri = sipFactory.createSipURI(null, uri); } /////////// LOGGER.info("initializing jvoicexml inteface........"); embJVXML = new EmbeddedJVXML(); embJVXML.init(); // //init jvoicexml context // contextJXML = new InitialContext(); // LOGGER.info("init jvoicexml context:contextJXML:"+contextJXML); // // // // LOGGER.info("creating VoiceXML documents and binding to the applications....."); // vxmlDocument = createVXMLDoc(); // printDocument(vxmlDocument); // // // // LOGGER.info("adding VXML document to repository..."); // vxmlURI=addDocument(vxmlDocument); // } catch (Exception e) { ExLog.exception(LOGGER, e); } }
From source file:com.rapid.forms.RapidFormAdapter.java
protected Map<String, FormPageControlValues> getUserFormPageControlValues(RapidRequest rapidRequest) throws Exception { // get the servlet context ServletContext servletContext = rapidRequest.getRapidServlet().getServletContext(); // get all app page control values from the context Map<String, Map<String, FormPageControlValues>> userAppPageControlValues = (Map<String, Map<String, FormPageControlValues>>) servletContext .getAttribute(USER_FORM_PAGE_CONTROL_VALUES); // if null/*from w w w.j a v a 2 s . c om*/ if (userAppPageControlValues == null) { // instantiate userAppPageControlValues = new HashMap<String, Map<String, FormPageControlValues>>(); // add to session servletContext.setAttribute(USER_FORM_PAGE_CONTROL_VALUES, userAppPageControlValues); } // get the form id String formId = getFormId(rapidRequest); // the page controls for specified app Map<String, FormPageControlValues> userPageControlValues = userAppPageControlValues.get(formId); // if null, instantiate if (userPageControlValues == null) { // instantiate userPageControlValues = new HashMap<String, FormPageControlValues>(); // add to user app pages userAppPageControlValues.put(formId, userPageControlValues); } // example page control pre-population // userPageControlValues.put("P2", new FormPageControlValues(new FormControlValue("P2_C1_", "Hello world !!!"))); // return! return userPageControlValues; }
From source file:org.apache.myfaces.shared_impl.util.StateUtils.java
/** * Does nothing if the user has disabled the SecretKey cache. This is * useful when dealing with a JCA provider whose SecretKey * implementation is not thread safe.//from w w w .j a v a 2 s . c om * * Instantiates a SecretKey instance based upon what the user has * specified in the deployment descriptor. The SecretKey is then * stored in application scope where it can be used for all requests. */ public static void initSecret(ServletContext ctx) { if (ctx == null) throw new NullPointerException("ServletContext ctx"); String cache = ctx.getInitParameter(INIT_SECRET_KEY_CACHE); if (cache == null) { cache = ctx.getInitParameter(INIT_SECRET_KEY_CACHE.toLowerCase()); } if ("false".equals(cache)) return; String _secret = ctx.getInitParameter(INIT_SECRET); if (_secret == null) { _secret = ctx.getInitParameter(INIT_SECRET.toLowerCase()); } String _algorithm = ctx.getInitParameter(INIT_ALGORITHM); if (_algorithm == null) { _algorithm = ctx.getInitParameter(INIT_ALGORITHM.toLowerCase()); } if (_algorithm == null) { if (log.isDebugEnabled()) { log.debug("Using default algorithm " + DEFAULT_ALGORITHM); } _algorithm = DEFAULT_ALGORITHM; } if (_secret == null) throw new NullPointerException("_secret String - '" + INIT_SECRET_KEY_CACHE + "' has been enabled, " + "but there is no '" + INIT_SECRET + "'"); byte[] secret = new Base64().decode(_secret.getBytes()); // you want to do this as few times as possible SecretKey secretKey = new SecretKeySpec(secret, _algorithm); if (log.isDebugEnabled()) log.debug("Storing SecretKey @ " + INIT_SECRET_KEY_CACHE); ctx.setAttribute(INIT_SECRET_KEY_CACHE, secretKey); }
From source file:org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil.java
/** * Build the API Configuration to be passed to APIM, from a given list of URL templates * * @param servletContext//from w w w . j a v a 2 s. c om * @param apiDef * @return */ public static APIConfig buildApiConfig(ServletContext servletContext, APIResourceConfiguration apiDef) throws UserStoreException { APIConfig apiConfig = new APIConfig(); String name = apiDef.getName(); if (name == null || name.isEmpty()) { if (log.isDebugEnabled()) { log.debug("API Name not set in @SwaggerDefinition Annotation"); } name = servletContext.getServletContextName(); } apiConfig.setName(name); String version = apiDef.getVersion(); if (version == null || version.isEmpty()) { if (log.isDebugEnabled()) { log.debug("'API Version not set in @SwaggerDefinition Annotation'"); } version = API_CONFIG_DEFAULT_VERSION; } apiConfig.setVersion(version); String context = apiDef.getContext(); if (context == null || context.isEmpty()) { if (log.isDebugEnabled()) { log.debug("'API Context not set in @SwaggerDefinition Annotation'"); } context = servletContext.getContextPath(); } apiConfig.setContext(context); String[] tags = apiDef.getTags(); if (tags == null || tags.length == 0) { if (log.isDebugEnabled()) { log.debug("'API tag not set in @SwaggerDefinition Annotation'"); } } else { apiConfig.setTags(tags); } String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); servletContext.setAttribute(PARAM_PROVIDER_TENANT_DOMAIN, tenantDomain); tenantDomain = (tenantDomain != null && !tenantDomain.isEmpty()) ? tenantDomain : MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; apiConfig.setTenantDomain(tenantDomain); String endpoint = servletContext.getInitParameter(PARAM_MANAGED_API_ENDPOINT); if (endpoint == null || endpoint.isEmpty()) { if (log.isDebugEnabled()) { log.debug("'managed-api-endpoint' attribute is not configured"); } String endpointContext = apiDef.getContext(); endpoint = APIPublisherUtil.getApiEndpointUrl(endpointContext); } apiConfig.setEndpoint(endpoint); String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration() .getAdminUserName(); if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { owner = owner + "@" + tenantDomain; } if (owner == null || owner.isEmpty()) { if (log.isDebugEnabled()) { log.debug("'managed-api-owner' attribute is not configured"); } } apiConfig.setOwner(owner); apiConfig.setSecured(false); boolean isDefault = true; String isDefaultParam = servletContext.getInitParameter(PARAM_IS_DEFAULT); if (isDefaultParam != null && !isDefaultParam.isEmpty()) { isDefault = Boolean.parseBoolean(isDefaultParam); } apiConfig.setDefault(isDefault); String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS); if (transports == null || transports.isEmpty()) { if (log.isDebugEnabled()) { log.debug("'managed-api-transports' attribute is not configured. Therefore using the default, " + "which is 'https'"); } transports = "https,http"; } apiConfig.setTransports(transports); String sharingValueParam = servletContext.getInitParameter(PARAM_SHARED_WITH_ALL_TENANTS); boolean isSharedWithAllTenants = Boolean.parseBoolean(sharingValueParam); if (isSharedWithAllTenants && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { isSharedWithAllTenants = false; } apiConfig.setSharedWithAllTenants(isSharedWithAllTenants); Set<ApiUriTemplate> uriTemplates = new LinkedHashSet<>(); for (APIResource apiResource : apiDef.getResources()) { ApiUriTemplate template = new ApiUriTemplate(); template.setAuthType(apiResource.getAuthType()); template.setHttpVerb(apiResource.getHttpVerb()); template.setResourceURI(apiResource.getUri()); template.setUriTemplate(apiResource.getUriTemplate()); template.setScope(apiResource.getScope()); uriTemplates.add(template); } apiConfig.setUriTemplates(uriTemplates); // adding scopes to the api Map<String, ApiScope> apiScopes = new HashMap<>(); if (uriTemplates != null) { // this creates distinct scopes list for (ApiUriTemplate template : uriTemplates) { ApiScope scope = template.getScope(); if (scope != null) { if (apiScopes.get(scope.getKey()) == null) { apiScopes.put(scope.getKey(), scope); } } } Set<ApiScope> scopes = new HashSet<>(apiScopes.values()); // set current scopes to API apiConfig.setScopes(scopes); } String policy = servletContext.getInitParameter(PARAM_MANAGED_API_POLICY); if (policy == null || policy.isEmpty()) { if (log.isDebugEnabled()) { log.debug("'managed-api-policy' attribute is not configured. Therefore using the default, " + "which is 'null'"); } policy = null; } apiConfig.setPolicy(policy); return apiConfig; }
From source file:com.openkm.servlet.admin.DatabaseQueryServlet.java
/** * Execute JDBC query//from w w w . j ava2s. co m */ private void executeJdbc(Session session, String qs, ServletContext sc, HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException { WorkerJdbc worker = new WorkerJdbc(); worker.setQueryString(qs); session.doWork(worker); sc.setAttribute("showSql", null); sc.setAttribute("exception", null); sc.setAttribute("globalResults", worker.getGlobalResults()); sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response); }
From source file:be.fedict.eid.idp.webapp.IdentityProviderServletContextListener.java
/** * Initialize the WS endpoints/* w w w . ja v a2 s . c om*/ * * @param context * servlet context * @param wsEndpointsMap * endpoints map */ private void initWsEndpoints(ServletContext context, Map<String, String> wsEndpointsMap) { try { classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader == null) { classLoader = getClass().getClassLoader(); } loader = new ServletResourceLoader(context); container = createContainer(context); adapterFactory = new ServletAdapterList(context); adapters = getAdapters(wsEndpointsMap); delegate = createDelegate(context); context.setAttribute(WSServlet.JAXWS_RI_RUNTIME_INFO, delegate); // Emit deployment probe event for each endpoint for (ServletAdapter adapter : adapters) { probe.deploy(adapter); } } catch (Exception e) { LOG.error(e, e); } }
From source file:org.red5.server.war.RootContextLoaderServlet.java
public void registerSubContext(String webAppKey) { // get the sub contexts - servlet context ServletContext ctx = servletContext.getContext(webAppKey); logger.info("Registering subcontext for servlet context: " + ctx.getContextPath()); if (registeredContexts.contains(ctx)) { logger.debug("Context is already registered: " + webAppKey); return;//from w w w .j av a 2s. co m } ContextLoader loader = new ContextLoader(); ConfigurableWebApplicationContext appCtx = (ConfigurableWebApplicationContext) loader .initWebApplicationContext(ctx); appCtx.setParent(applicationContext); appCtx.refresh(); ctx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appCtx); ConfigurableBeanFactory appFactory = appCtx.getBeanFactory(); logger.debug("About to grab Webcontext bean for " + webAppKey); Context webContext = (Context) appCtx.getBean("web.context"); webContext.setCoreBeanFactory(parentFactory); webContext.setClientRegistry(clientRegistry); webContext.setServiceInvoker(globalInvoker); webContext.setScopeResolver(globalResolver); webContext.setMappingStrategy(globalStrategy); WebScope scope = (WebScope) appFactory.getBean("web.scope"); scope.setServer(server); scope.setParent(global); scope.register(); scope.start(); // register the context so we dont try to reinitialize it registeredContexts.add(ctx); }
From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2ArtifactProtocolServiceTest.java
@Test public void testHandleReturnResponse() throws Exception { // setup// w w w. j a v a 2s . c om 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).times(3); EasyMock.expect(mockServletContext.getAttribute(AbstractSAML2ProtocolService.IDP_CONFIG_CONTEXT_ATTRIBUTE)) .andReturn(mockConfiguration).times(3); 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(mockConfiguration.getResponseTokenValidity()).andStubReturn(5); EasyMock.expect(mockConfiguration.findIdentity()).andStubReturn(idpIdentity); EasyMock.expect(mockConfiguration.getIdentityCertificateChain()) .andStubReturn(Collections.singletonList(certificate)); EasyMock.expect(mockConfiguration.getDefaultIssuer()).andStubReturn("TestIssuer"); EasyMock.expect(mockHttpServletRequest.getSession()).andReturn(mockHttpSession).times(3); EasyMock.expect( mockServletContext.getAttribute(AbstractSAML2ArtifactProtocolService.ARTIFACT_MAP_ATTRIBUTE)) .andReturn(null); mockServletContext.setAttribute( EasyMock.matches(AbstractSAML2ArtifactProtocolService.ARTIFACT_MAP_ATTRIBUTE), EasyMock.anyObject()); EasyMock.expect(mockHttpServletRequest.getServerName()).andReturn("127.0.0.1").times(2); EasyMock.expect(mockHttpServletRequest.getServerPort()).andReturn(8443).times(3); EasyMock.expect(mockHttpServletRequest.getContextPath()).andReturn("/eid-idp").times(2); EasyMock.expect(mockHttpSession.getAttribute(AbstractSAML2ArtifactProtocolService.ISSUER_SESSION_ATTRIBUTE)) .andReturn("SPIssuer"); // 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 samlArtAttribute = null; for (NameValuePair attribute : attributes) { if ("RelayState".equals(attribute.getName())) { relayStateAttribute = attribute; continue; } if ("SAMLart".equals(attribute.getName())) { samlArtAttribute = attribute; continue; } } assertNotNull(relayStateAttribute); assertEquals("relay-state", relayStateAttribute.getValue()); assertNotNull("no SAMLArt attribute", samlArtAttribute); String encodedSamlArt = samlArtAttribute.getValue(); assertNotNull(encodedSamlArt); String samlArtifact = new String(Base64.decodeBase64(encodedSamlArt)); LOG.debug("SAML Artifact: " + samlArtifact); }
From source file:org.apache.struts.faces.application.ActionListenerImpl.java
/** * <p>Look up and return the <code>RequestProcessor</code> responsible for * the specified module, creating a new one if necessary. This method is * based on the corresponding code in <code>ActionServlet</code>, which * cannot be used directly because it is a protected method.</p> * * @param config The module configuration for which to * acquire and return a RequestProcessor * @param context The <code>ServletContext</code> instance * for this web application/*w ww . j a va2 s. c o m*/ * * @exception IllegalStateException if we cannot instantiate a * RequestProcessor instance */ protected RequestProcessor getRequestProcessor(ModuleConfig config, ServletContext context) { String key = Globals.REQUEST_PROCESSOR_KEY + config.getPrefix(); RequestProcessor processor = (RequestProcessor) context.getAttribute(key); if (processor == null) { try { if (log.isDebugEnabled()) { log.debug("Instantiating RequestProcessor of class " + config.getControllerConfig().getProcessorClass()); } ActionServlet servlet = (ActionServlet) context.getAttribute(Globals.ACTION_SERVLET_KEY); processor = (RequestProcessor) RequestUtils .applicationInstance(config.getControllerConfig().getProcessorClass()); processor.init(servlet, config); context.setAttribute(key, processor); } catch (Exception e) { log.error("Cannot instantiate RequestProcessor of class " + config.getControllerConfig().getProcessorClass(), e); throw new IllegalStateException("Cannot initialize RequestProcessor of class " + config.getControllerConfig().getProcessorClass() + ": " + e); } } return (processor); }