List of usage examples for org.springframework.web.context WebApplicationContext getBean
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
From source file:jp.terasoluna.fw.web.thin.AbstractControlFilter.java
/** * DIReiRg??[CX^X?B/*from w w w . ja v a 2 s. co m*/ * * @return E Rg??[CX^X */ @SuppressWarnings("unchecked") protected E getController() { if (log.isDebugEnabled()) { log.debug("setController() called."); } // WebApplicationContext WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext()); // tB^?p??[^Bean`t@C // id?n String controllerId = config.getInitParameter("controller"); if (controllerId == null || "".equals(controllerId)) { if (log.isDebugEnabled()) { log.debug("init parameter 'controller' isn't defined or " + "empty"); } controllerId = getDefaultControllerBeanId(); } // Rg??[`bean id\ if (log.isDebugEnabled()) { log.debug("controller bean id = \"" + controllerId + "\""); } // DIReiRg??[CX^X E controller = null; try { controller = (E) wac.getBean(controllerId, getControllerClass()); } catch (NoSuchBeanDefinitionException e) { // Bean`t@CwBean`?? log.error("not found " + controllerId + ". " + "controller bean not defined in Beans definition file.", e); throw new SystemException(e, getErrorCode()); } catch (BeanNotOfRequiredTypeException e) { // Bean`t@CwBean?AwNX // qNX?? log.error("controller not implemented " + getControllerClass().toString() + ".", e); throw new SystemException(e, getErrorCode()); } catch (BeansException e) { // CX^X??s?? log.error("bean generation failed.", e); throw new SystemException(e, getErrorCode()); } return controller; }
From source file:org.zkoss.zk.grails.web.ZULUrlMappingsFilter.java
@Override protected void initFilterBean() throws ServletException { super.initFilterBean(); urlHelper.setUrlDecode(false);//from ww w .j a v a2 s .c o m final ServletContext servletContext = getServletContext(); final WebApplicationContext applicationContext = WebApplicationContextUtils .getRequiredWebApplicationContext(servletContext); handlerInterceptors = WebUtils.lookupHandlerInterceptors(servletContext); application = WebUtils.lookupApplication(servletContext); viewResolver = WebUtils.lookupViewResolver(servletContext); ApplicationContext mainContext = application.getMainContext(); urlConverter = mainContext.getBean(UrlConverter.BEAN_NAME, UrlConverter.class); if (application != null) { grailsConfig = new GrailsConfig(application); } if (applicationContext.containsBean(MimeType.BEAN_NAME)) { this.mimeTypes = applicationContext.getBean(MimeType.BEAN_NAME, MimeType[].class); } composerMapping = applicationContext.getBean(ComposerMapping.BEAN_NAME, ComposerMapping.class); createStackTraceFilterer(); }
From source file:com.mtgi.analytics.servlet.BehaviorTrackingFilter.java
public void init(FilterConfig config) throws ServletException { servletContext = config.getServletContext(); WebApplicationContext context = getRequiredWebApplicationContext(servletContext); String managerName = config.getInitParameter(PARAM_MANAGER_NAME); BehaviorTrackingManager manager;/* w ww . ja v a 2 s . co m*/ if (managerName == null) { //if there is no bean name configured, we assume there //must be exactly one such bean in the application context. Map<?, ?> managers = context.getBeansOfType(BehaviorTrackingManager.class); if (managers.isEmpty()) throw new ServletException( "Unable to find a bean of class " + BehaviorTrackingManager.class.getName() + " in the Spring application context; perhaps it has not been configured?"); if (managers.size() > 1) throw new ServletException("More than one instance of " + BehaviorTrackingManager.class.getName() + " in Spring application context; you must specify which to use with the filter parameter " + PARAM_MANAGER_NAME); manager = (BehaviorTrackingManager) managers.values().iterator().next(); } else { //lookup the specified bean name. manager = (BehaviorTrackingManager) context.getBean(managerName, BehaviorTrackingManager.class); } //see if there is an event type name configured. String eventType = config.getInitParameter(PARAM_EVENT_TYPE); //parameters included in event data String params = config.getInitParameter(PARAM_PARAMETERS_INCLUDE); String[] parameters = params == null ? null : LIST_SEPARATOR.split(params); //parameters included in event name String nameParams = config.getInitParameter(PARAM_PARAMETERS_NAME); String[] nameParameters = nameParams == null ? null : LIST_SEPARATOR.split(nameParams); delegate = new ServletRequestBehaviorTrackingAdapter(eventType, manager, parameters, nameParameters, null); //increment count of tracking filters registered in the servlet context. the filter //and alternative request listener check this attribute to make sure both are not registered at once. Integer count = (Integer) servletContext.getAttribute(ATT_FILTER_REGISTERED); servletContext.setAttribute(ATT_FILTER_REGISTERED, count == null ? 1 : count + 1); }
From source file:de.itsvs.cwtrpc.controller.RemoteServiceControllerServlet.java
@Override public void init(ServletConfig config) throws ServletException { final WebApplicationContext applicationContext; final RemoteServiceControllerConfig controllerConfig; String configBeanName;//from www . j a v a2 s. co m String initParam; super.init(config); initParam = config.getInitParameter(SPRING_REQUEST_CONTEXT_ENABLED_INIT_PARAM); if (initParam != null) { setSpringRequestContextEnabled(Boolean.valueOf(initParam)); } else { setSpringRequestContextEnabled(DEFAULT_SPRING_REQUEST_CONTEXT_ENABLED); } if (log.isInfoEnabled()) { log.info("Spring request context initialization on every request: " + isSpringRequestContextEnabled()); } configBeanName = config.getInitParameter(CONFIG_BEAN_NAME_INIT_PARAM); if (configBeanName == null) { configBeanName = RemoteServiceControllerConfig.DEFAULT_BEAN_ID; } applicationContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext()); if (log.isDebugEnabled()) { log.debug( "Resolving controller config with bean name '" + configBeanName + "' from application context"); } controllerConfig = applicationContext.getBean(configBeanName, RemoteServiceControllerConfig.class); setApplicationContext(applicationContext); setSerializationPolicyProvider(controllerConfig.getSerializationPolicyProvider()); setServiceConfigsByUri( Collections.unmodifiableMap(createPreparedRemoteServiceConfigBuilder().build(controllerConfig))); setUncaughtExceptions(getUncaughtExceptions(controllerConfig)); }
From source file:org.orderofthebee.addons.support.tools.repo.caches.CacheLookupUtils.java
/** * Resolves the {@link CacheStatistics cache statistics} of the {@link TransactionalCache transactional cache} instance that facades a * specific {@link SimpleCache shared/*from ww w. j a v a2 s . c om*/ * cache} and provides it in a more script-friendly representation. * * @param sharedCacheName * the name of the shared cache * @return a facade to a snapshot of the cache statistics */ public static AlfrescoCacheStatsFacade resolveStatisticsViaTransactional(final String sharedCacheName) { ParameterCheck.mandatoryString("sharedCacheName", sharedCacheName); LOGGER.debug("Trying to resolve transactional cache for shared cache {}", sharedCacheName); String txnCacheName = null; final WebApplicationContext applicationContext = ContextLoader.getCurrentWebApplicationContext(); if (applicationContext instanceof ConfigurableApplicationContext) { final ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext) .getBeanFactory(); final String[] txnCacheBeanNames = applicationContext.getBeanNamesForType(TransactionalCache.class, false, false); // this is a rather ugly reference lookup, but so far I see no other way for (final String txnCacheBeanName : txnCacheBeanNames) { final BeanDefinition txnCacheDefinition = beanFactory.getBeanDefinition(txnCacheBeanName); final PropertyValue sharedCacheValue = txnCacheDefinition.getPropertyValues() .getPropertyValue("sharedCache"); final PropertyValue nameValue = txnCacheDefinition.getPropertyValues().getPropertyValue("name"); if (nameValue != null && sharedCacheValue != null) { final Object sharedCacheRef = sharedCacheValue.getValue(); if (sharedCacheRef instanceof RuntimeBeanReference) { final String sharedCacheBeanName = ((RuntimeBeanReference) sharedCacheRef).getBeanName(); Object nameValueObj = nameValue.getValue(); if (nameValueObj instanceof TypedStringValue) { nameValueObj = ((TypedStringValue) nameValueObj).getValue(); } if (EqualsHelper.nullSafeEquals(sharedCacheBeanName, sharedCacheName)) { if (txnCacheName != null) { LOGGER.info("Shared cache {} is referenced by multiple transactional caches", sharedCacheName); txnCacheName = null; break; } txnCacheName = String.valueOf(nameValueObj); LOGGER.debug("Resolved transactional cache {} for shared cache {}", txnCacheName, sharedCacheName); } else { try { final DefaultSimpleCache<?, ?> defaultSimpleCache = applicationContext .getBean(sharedCacheBeanName, DefaultSimpleCache.class); if (EqualsHelper.nullSafeEquals(defaultSimpleCache.getCacheName(), sharedCacheName)) { if (txnCacheName != null) { LOGGER.info( "Shared cache {} is referenced by multiple transactional caches", sharedCacheName); txnCacheName = null; break; } txnCacheName = String.valueOf(nameValueObj); LOGGER.debug("Resolved transactional cache {} for shared cache {}", txnCacheName, sharedCacheName); } continue; } catch (final BeansException be) { // ignore - can be expected e.g. in EE or with alternative cache implementations } } } } } if (txnCacheName == null) { LOGGER.debug("Unable to resolve unique transactional cache for shared cache {}", sharedCacheName); } } else { LOGGER.debug( "Application context is not a configurable application context - unable to resolve transactional cache"); } AlfrescoCacheStatsFacade facade = null; if (txnCacheName != null) { final CacheStatistics cacheStatistics = applicationContext.getBean("cacheStatistics", CacheStatistics.class); try { final Map<OpType, OperationStats> allStats = cacheStatistics.allStats(txnCacheName); facade = new AlfrescoCacheStatsFacade(allStats); } catch (final NoStatsForCache e) { facade = new AlfrescoCacheStatsFacade(Collections.emptyMap()); } } return facade; }
From source file:org.akaza.openclinica.control.MainMenuServlet.java
public boolean processSpecificStudyEnvUuid(HttpServletRequest request, UserAccountBean ub) throws Exception { logger.info(//from ww w . j a va2 s . co m "MainMenuServlet processSpecificStudyEnvUuid:%%%%%%%%" + session.getAttribute("firstLoginCheck")); boolean isRenewAuth = false; String studyEnvUuid = (String) request.getParameter("studyEnvUuid"); if (StringUtils.isEmpty(studyEnvUuid)) { return isRenewAuth; } if (processForceRenewAuth()) return true; ServletContext context = getServletContext(); WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context); String currentSchema = CoreResources.getRequestSchema(request); CoreResources.setRequestSchema(request, "public"); StudyBuildService studyService = ctx.getBean("studyBuildService", StudyBuildServiceImpl.class); studyService.updateStudyUserRoles(request, studyService.getUserAccountObject(ub), ub.getActiveStudyId()); UserAccountDAO userAccountDAO = new UserAccountDAO(sm.getDataSource()); ArrayList userRoleBeans = (ArrayList) userAccountDAO.findAllRolesByUserName(ub.getName()); ub.setRoles(userRoleBeans); StudyDAO sd = getStudyDAO(); StudyBean tmpPublicStudy = sd.findByStudyEnvUuid(studyEnvUuid); if (tmpPublicStudy == null) { CoreResources.setRequestSchema(request, currentSchema); return isRenewAuth; } currentPublicStudy = tmpPublicStudy; CoreResources.setRequestSchema(request, currentPublicStudy.getSchemaName()); currentStudy = sd.findByStudyEnvUuid(studyEnvUuid); if (currentStudy.getParentStudyId() > 0) { currentStudy.setParentStudyName(sd.findByPK(currentStudy.getParentStudyId()).getName()); currentPublicStudy.setParentStudyName(currentStudy.getParentStudyName()); } StudyConfigService scs = new StudyConfigService(sm.getDataSource()); scs.setParametersForStudy(currentStudy); session.setAttribute("publicStudy", currentPublicStudy); session.setAttribute("study", currentStudy); StudyUserRoleBean role = ub.getRoleByStudy(currentPublicStudy.getId()); if (role.getStudyId() == 0) { logger.error("You have no roles for this study." + studyEnvUuid + " currentStudy is:" + currentStudy.getName() + " schema:" + currentPublicStudy.getSchemaName()); logger.error("Creating an invalid role, ChangeStudy page will be shown"); //throw new Exception("You have no roles for this study."); currentStudy = new StudyBean(); currentPublicStudy = new StudyBean(); currentRole = new StudyUserRoleBean(); session.setAttribute("publicStudy", currentPublicStudy); session.setAttribute("study", currentStudy); session.setAttribute("userRole", currentRole); } else { currentRole = role; session.setAttribute("userRole", role); logger.info("Found role for this study:" + role.getRoleName()); if (ub.getActiveStudyId() == currentPublicStudy.getId()) return isRenewAuth; ub.setActiveStudyId(currentPublicStudy.getId()); } return isRenewAuth; }
From source file:org.alfresco.web.bean.wcm.AVMUtil.java
public static String getPreviewURI(String storeId, String assetPath) { if (!deprecatedPreviewURIGeneratorChecked) { if (deprecatedPreviewURIGenerator == null) { // backwards compatibility - will hide new implementation, until custom providers/context are migrated WebApplicationContext wac = FacesContextUtils .getRequiredWebApplicationContext(FacesContext.getCurrentInstance()); if (wac.containsBean(SPRING_BEAN_NAME_PREVIEW_URI_SERVICE)) { // if the bean is present retrieve it deprecatedPreviewURIGenerator = (PreviewURIService) wac .getBean(SPRING_BEAN_NAME_PREVIEW_URI_SERVICE, PreviewURIService.class); logger.warn("Found deprecated '" + SPRING_BEAN_NAME_PREVIEW_URI_SERVICE + "' config - which will be used instead of new 'WCMPreviewURIService' until migrated (changing web project preview provider will have no effect)"); }//from w ww.ja v a 2 s . c o m } deprecatedPreviewURIGeneratorChecked = true; } if (deprecatedPreviewURIGenerator != null) { return deprecatedPreviewURIGenerator.getPreviewURI(storeId, assetPath); } return getPreviewURIService().getPreviewURI(storeId, assetPath); }
From source file:org.apache.nifi.web.server.JettyServer.java
@Override public void start() { try {//from w w w.j ava 2 s .c om // 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.codehaus.groovy.grails.web.context.GrailsContextLoader.java
@Override public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { // disable annoying ehcache up-to-date check System.setProperty("net.sf.ehcache.skipUpdateCheck", "true"); ExpandoMetaClass.enableGlobally();/*from w ww .j a v a 2 s .co m*/ Metadata metadata = Metadata.getCurrent(); if (metadata != null && metadata.isWarDeployed()) { Grape.setEnableAutoDownload(false); Grape.setEnableGrapes(false); Environment.cacheCurrentEnvironment(); } if (LOG.isDebugEnabled()) { LOG.debug("[GrailsContextLoader] Loading context. Creating parent application context"); } WebApplicationContext ctx; try { ctx = super.initWebApplicationContext(servletContext); if (LOG.isDebugEnabled()) { LOG.debug("[GrailsContextLoader] Created parent application context"); } application = ctx.getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class); final WebApplicationContext finalCtx = ctx; ShutdownOperations.addOperation(new Runnable() { public void run() { if (application != null) { ClassLoader classLoader = application.getClassLoader(); if (classLoader instanceof GroovyClassLoader) { MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry(); Class<?>[] loadedClasses = ((GroovyClassLoader) classLoader).getLoadedClasses(); for (Class<?> loadedClass : loadedClasses) { metaClassRegistry.removeMetaClass(loadedClass); } } } GrailsPluginManager pluginManager = null; if (finalCtx.containsBean(GrailsPluginManager.BEAN_NAME)) { pluginManager = finalCtx.getBean(GrailsPluginManager.BEAN_NAME, GrailsPluginManager.class); } if (pluginManager != null) { try { pluginManager.shutdown(); } catch (Exception e) { new DefaultStackTraceFilterer().filter(e); LOG.error("Error occurred shutting down plug-in manager: " + e.getMessage(), e); } } } }); ctx = GrailsConfigUtils.configureWebApplicationContext(servletContext, ctx); GrailsConfigUtils.executeGrailsBootstraps(application, ctx, servletContext); } catch (Throwable e) { GrailsUtil.deepSanitize(e); LOG.error("Error initializing the application: " + e.getMessage(), e); if (Environment.isDevelopmentMode() && !Environment.isWarDeployed()) { // bail out early in order to show appropriate error if (System.getProperty("grails.disable.exit") == null) { System.exit(1); } } LOG.error("Error initializing Grails: " + e.getMessage(), e); if (e instanceof BeansException) throw (BeansException) e; throw new BootstrapException("Error executing bootstraps", e); } return ctx; }
From source file:org.codehaus.groovy.grails.web.pages.GroovyPagesServlet.java
@Override protected void initFrameworkServlet() throws ServletException, BeansException { context = getServletContext();// ww w . j av a 2 s. c o m context.log("GSP servlet initialized"); context.setAttribute(SERVLET_INSTANCE, this); final WebApplicationContext webApplicationContext = getWebApplicationContext(); grailsAttributes = new DefaultGrailsApplicationAttributes(context); webApplicationContext.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); groovyPagesTemplateEngine = webApplicationContext.getBean(GroovyPagesTemplateEngine.BEAN_ID, GroovyPagesTemplateEngine.class); }