List of usage examples for org.springframework.context ApplicationContext containsBean
boolean containsBean(String name);
From source file:org.codeconsole.web.analytics.AnalyticsFilter.java
/** * @see Filter#init(FilterConfig)/*from w ww.j a v a2 s .c om*/ */ public void init(FilterConfig fConfig) throws ServletException { String springConfigurationParam = fConfig.getInitParameter("spring-context-location"); if (springConfigurationParam != null) { this.springConfiguration = springConfigurationParam; } ApplicationContext context = null; try { context = new ClassPathXmlApplicationContext(springConfiguration); } catch (BeanDefinitionStoreException notfound) { System.out.println("AnalyticsFilter: Could not locate context configuration: " + springConfiguration + ". Attempting to load root Web Application Context."); context = WebApplicationContextUtils.getWebApplicationContext(fConfig.getServletContext()); } System.out.println("AnalyticsFilter: Loading bean definitions."); if (context != null) { if (context.containsBean("analyticsGateway")) { analyticsGateway = context.getBean("analyticsGateway", AnalyticsGateway.class); System.out.println("AnalyticsFilter: Gateway loaded."); } else { System.out.println( "AnalyticsFilter: Could not a bean named 'analyticsGateway'. Analytics will not be sent!"); } if (context.containsBean("userDetailsResolver")) { userDetailsResolver = context.getBean("userDetailsResolver", UserDetailsResolver.class); System.out.println("AnalyticsFilter: UserDetailsResolver loaded."); } if (context.containsBean("sourceRevisionResolver")) { sourceRevisionResolver = context.getBean("sourceRevisionResolver", SourceRevisionResolver.class); System.out.println("AnalyticsFilter: SourceRevisionResolver loaded."); } } else { System.out.println("AnalyticsFilter: Could not load root Web Application Context."); } String historySize = fConfig.getInitParameter("history-size"); if (historySize != null) { this.maxHistorySize = Integer.parseInt(historySize); } String sessionAttribute = fConfig.getInitParameter("session-attribute"); if (sessionAttribute != null) { this.sessionAttributeName = sessionAttribute; } String excluded = fConfig.getInitParameter("exclude-urls"); if (excluded != null) { String[] excludes = excluded.split("[\r\n]+"); for (String exclude : excludes) { exclude = exclude.trim(); if (!exclude.isEmpty()) excludedUrlPatterns.add(Pattern.compile(exclude)); } } String excludedParms = fConfig.getInitParameter("exclude-params"); if (excludedParms != null) { String[] paramExcludes = excludedParms.split("[\r\n]+"); for (String exclude : paramExcludes) { exclude = exclude.trim(); if (!exclude.isEmpty()) excludedParamPatterns.add(Pattern.compile(exclude)); } } }
From source file:org.apache.click.extras.spring.SpringClickServlet.java
/** * This method associates the <tt>ApplicationContext</tt> with any * <tt>ApplicationContextAware</tt> pages and supports the deserialization * of stateful pages.//w ww. j a va2 s .c o m * * @see ClickServlet#activatePageInstance(Page) * * @param page the page instance to activate */ @Override protected void activatePageInstance(Page page) { ApplicationContext applicationContext = getApplicationContext(); if (page instanceof ApplicationContextAware) { ApplicationContextAware aware = (ApplicationContextAware) page; aware.setApplicationContext(applicationContext); } Class<? extends Page> pageClass = page.getClass(); String beanName = toBeanName(pageClass); if (applicationContext.containsBean(beanName) || applicationContext.containsBean(pageClass.getName())) { // Beans are injected through Spring } else { // Inject any Spring beans into the page instance if (!pageSetterBeansMap.isEmpty()) { // In development mode, lazily loaded page classes won't have // their bean setters methods mapped, thus beans won't be injected List<BeanNameAndMethod> beanList = pageSetterBeansMap.get(page.getClass()); if (beanList != null) { for (BeanNameAndMethod bnam : beanList) { Object bean = applicationContext.getBean(bnam.beanName); try { Object[] args = { bean }; bnam.method.invoke(page, args); } catch (Exception error) { throw new RuntimeException(error); } } } } } }
From source file:org.red5.server.tomcat.TomcatLoader.java
/** * Initialization./*from www . j a v a 2 s .c o m*/ */ public void init() { log.info("Loading tomcat context"); //get a reference to the current threads classloader final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); // root location for servlet container String serverRoot = System.getProperty("red5.root"); log.info("Server root: {}", serverRoot); String confRoot = System.getProperty("red5.config_root"); log.info("Config root: {}", confRoot); // create one embedded (server) and use it everywhere embedded = new Embedded(); embedded.createLoader(originalClassLoader); embedded.setCatalinaBase(serverRoot); embedded.setCatalinaHome(serverRoot); embedded.setName(serviceEngineName); log.trace("Classloader for embedded: {} TCL: {}", Embedded.class.getClassLoader(), originalClassLoader); engine = embedded.createEngine(); engine.setDefaultHost(host.getName()); engine.setName(serviceEngineName); if (webappFolder == null) { // Use default webapps directory webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps"); } System.setProperty("red5.webapp.root", webappFolder); log.info("Application root: {}", webappFolder); // scan for additional webapp contexts // Root applications directory File appDirBase = new File(webappFolder); // Subdirs of root apps dir File[] dirs = appDirBase.listFiles(new DirectoryFilter()); // Search for additional context files for (File dir : dirs) { String dirName = '/' + dir.getName(); // check to see if the directory is already mapped if (null == host.findChild(dirName)) { String webappContextDir = FileUtil.formatPath(appDirBase.getAbsolutePath(), dirName); log.debug("Webapp context directory (full path): {}", webappContextDir); Context ctx = null; if ("/root".equals(dirName) || "/root".equalsIgnoreCase(dirName)) { log.trace("Adding ROOT context"); ctx = addContext("/", webappContextDir); } else { log.trace("Adding context from directory scan: {}", dirName); ctx = addContext(dirName, webappContextDir); } log.trace("Context: {}", ctx); //see if the application requests php support String enablePhp = ctx.findParameter("enable-php"); //if its null try to read directly if (enablePhp == null) { File webxml = new File(webappContextDir + "/WEB-INF/", "web.xml"); if (webxml.exists() && webxml.canRead()) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(webxml); // normalize text representation doc.getDocumentElement().normalize(); log.trace("Root element of the doc is {}", doc.getDocumentElement().getNodeName()); NodeList listOfElements = doc.getElementsByTagName("context-param"); int totalElements = listOfElements.getLength(); log.trace("Total no of elements: {}", totalElements); for (int s = 0; s < totalElements; s++) { Node fstNode = listOfElements.item(s); if (fstNode.getNodeType() == Node.ELEMENT_NODE) { Element fstElmnt = (Element) fstNode; NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("param-name"); Element fstNmElmnt = (Element) fstNmElmntLst.item(0); NodeList fstNm = fstNmElmnt.getChildNodes(); String pName = (fstNm.item(0)).getNodeValue(); log.trace("Param name: {}", pName); if ("enable-php".equals(pName)) { NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("param-value"); Element lstNmElmnt = (Element) lstNmElmntLst.item(0); NodeList lstNm = lstNmElmnt.getChildNodes(); String pValue = (lstNm.item(0)).getNodeValue(); log.trace("Param value: {}", pValue); enablePhp = pValue; // break; } } } } catch (Exception e) { log.warn("Error reading web.xml", e); } } webxml = null; } log.debug("Enable php: {}", enablePhp); if ("true".equals(enablePhp)) { log.info("Adding PHP (Quercus) servlet for context: {}", ctx.getName()); // add servlet wrapper StandardWrapper wrapper = (StandardWrapper) ctx.createWrapper(); wrapper.setServletName("QuercusServlet"); wrapper.setServletClass("com.caucho.quercus.servlet.QuercusServlet"); log.debug("Wrapper: {}", wrapper); ctx.addChild(wrapper); // add servlet mappings ctx.addServletMapping("*.php", "QuercusServlet"); } webappContextDir = null; } } appDirBase = null; dirs = null; // Dump context list if (log.isDebugEnabled()) { for (Container cont : host.findChildren()) { log.debug("Context child name: {}", cont.getName()); } } // Set a realm if (realm == null) { realm = new MemoryRealm(); } embedded.setRealm(realm); // use Tomcat jndi or not if (System.getProperty("catalina.useNaming") != null) { embedded.setUseNaming(Boolean.valueOf(System.getProperty("catalina.useNaming"))); } // add the valves to the host for (Valve valve : valves) { log.debug("Adding host valve: {}", valve); ((StandardHost) host).addValve(valve); } // baseHost = embedded.createHost(hostName, appRoot); engine.addChild(host); // add any additional hosts if (hosts != null && !hosts.isEmpty()) { // grab current contexts from base host Container[] currentContexts = host.findChildren(); log.info("Adding {} additional hosts", hosts.size()); for (Host h : hosts) { log.debug("Host - name: {} appBase: {} info: {}", new Object[] { h.getName(), h.getAppBase(), h.getInfo() }); //add the contexts to each host for (Container cont : currentContexts) { Context c = (Context) cont; addContext(c.getPath(), c.getDocBase(), h); } //add the host to the engine engine.addChild(h); } } // Add new Engine to set of Engine for embedded server embedded.addEngine(engine); // set connection properties for (String key : connectionProperties.keySet()) { log.debug("Setting connection property: {} = {}", key, connectionProperties.get(key)); if (connectors == null || connectors.isEmpty()) { connector.setProperty(key, connectionProperties.get(key)); } else { for (Connector ctr : connectors) { ctr.setProperty(key, connectionProperties.get(key)); } } } // set the bind address if (address == null) { //bind locally address = InetSocketAddress.createUnresolved("127.0.0.1", connector.getPort()).getAddress(); } // apply the bind address ProtocolHandler handler = connector.getProtocolHandler(); if (handler instanceof Http11Protocol) { ((Http11Protocol) handler).setAddress(address); } else if (handler instanceof Http11NioProtocol) { ((Http11NioProtocol) handler).setAddress(address); } else { log.warn("Unknown handler type: {}", handler.getClass().getName()); } // Start server try { // Add new Connector to set of Connectors for embedded server, // associated with Engine if (connectors == null || connectors.isEmpty()) { embedded.addConnector(connector); log.trace("Connector oName: {}", connector.getObjectName()); } else { for (Connector ctr : connectors) { embedded.addConnector(ctr); log.trace("Connector oName: {}", ctr.getObjectName()); } } log.info("Starting Tomcat servlet engine"); embedded.start(); LoaderBase.setApplicationLoader(new TomcatApplicationLoader(embedded, host, applicationContext)); for (Container cont : host.findChildren()) { if (cont instanceof StandardContext) { StandardContext ctx = (StandardContext) cont; final ServletContext servletContext = ctx.getServletContext(); log.debug("Context initialized: {}", servletContext.getContextPath()); //set the hosts id servletContext.setAttribute("red5.host.id", getHostId()); String prefix = servletContext.getRealPath("/"); log.debug("Path: {}", prefix); try { if (ctx.resourcesStart()) { log.debug("Resources started"); } log.debug("Context - available: {} privileged: {}, start time: {}, reloadable: {}", new Object[] { ctx.getAvailable(), ctx.getPrivileged(), ctx.getStartTime(), ctx.getReloadable() }); Loader cldr = ctx.getLoader(); log.debug("Loader delegate: {} type: {}", cldr.getDelegate(), cldr.getClass().getName()); if (cldr instanceof WebappLoader) { log.debug("WebappLoader class path: {}", ((WebappLoader) cldr).getClasspath()); } final ClassLoader webClassLoader = cldr.getClassLoader(); log.debug("Webapp classloader: {}", webClassLoader); // get the (spring) config file path final String contextConfigLocation = servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null ? defaultSpringConfigLocation : servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM); log.debug("Spring context config location: {}", contextConfigLocation); // get the (spring) parent context key final String parentContextKey = servletContext.getInitParameter( org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null ? defaultParentContextKey : servletContext.getInitParameter( org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM); log.debug("Spring parent context key: {}", parentContextKey); //set current threads classloader to the webapp classloader Thread.currentThread().setContextClassLoader(webClassLoader); //create a thread to speed-up application loading Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) { public void run() { //set thread context classloader to web classloader Thread.currentThread().setContextClassLoader(webClassLoader); //get the web app's parent context ApplicationContext parentContext = null; if (applicationContext.containsBean(parentContextKey)) { parentContext = (ApplicationContext) applicationContext .getBean(parentContextKey); } else { log.warn("Parent context was not found: {}", parentContextKey); } // create a spring web application context final String contextClass = servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null ? XmlWebApplicationContext.class.getName() : servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM); //web app context (spring) ConfigurableWebApplicationContext appctx = null; try { Class<?> clazz = Class.forName(contextClass, true, webClassLoader); appctx = (ConfigurableWebApplicationContext) clazz.newInstance(); } catch (Throwable e) { throw new RuntimeException("Failed to load webapplication context class.", e); } appctx.setConfigLocations(new String[] { contextConfigLocation }); appctx.setServletContext(servletContext); //set parent context or use current app context if (parentContext != null) { appctx.setParent(parentContext); } else { appctx.setParent(applicationContext); } // set the root webapp ctx attr on the each servlet context so spring can find it later servletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx); //refresh the factory log.trace("Classloader prior to refresh: {}", appctx.getClassLoader()); appctx.refresh(); if (log.isDebugEnabled()) { log.debug("Red5 app is active: {} running: {}", appctx.isActive(), appctx.isRunning()); } } }; thread.setDaemon(true); thread.start(); } catch (Throwable t) { log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(), t.getMessage()); t.printStackTrace(); } finally { //reset the classloader Thread.currentThread().setContextClassLoader(originalClassLoader); } } } // if everything is ok at this point then call the rtmpt and rtmps // beans so they will init if (applicationContext.containsBean("red5.core")) { ApplicationContext core = (ApplicationContext) applicationContext.getBean("red5.core"); if (core.containsBean("rtmpt.server")) { log.debug("Initializing RTMPT"); core.getBean("rtmpt.server"); log.debug("Finished initializing RTMPT"); } else { log.info("Dedicated RTMPT server configuration was not specified"); } if (core.containsBean("rtmps.server")) { log.debug("Initializing RTMPS"); core.getBean("rtmps.server"); log.debug("Finished initializing RTMPS"); } else { log.info("Dedicated RTMPS server configuration was not specified"); } } else { log.info("Core context was not found"); } } catch (Exception e) { if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) { log.error( "Error loading tomcat, unable to bind connector. You may not have permission to use the selected port", e); } else { log.error("Error loading tomcat", e); } } finally { registerJMX(); } }
From source file:io.servicecomb.springboot.starter.configuration.CseDelegatingProxyUtils.java
public static <T> T getNamedInstance(Class<T> type, String name) { ApplicationContext context = (ApplicationContext) ConfigurationManager.getConfigInstance() .getProperty(APPLICATION_CONTEXT); return context != null && context.containsBean(name) ? context.getBean(name, type) : null; }
From source file:jp.terasoluna.fw.web.taglib.WriteCodeValueTag.java
/** * ^O]Jn?\bh?B//www . ja v a2 s . c o m * * <p> * T?[ubgReLXg?AApplicationContext?A * "codeList" ?w id * CodeListLoader ?AR?[hXg * l?A?o?B * "key" ?w?AL?[l?A * w?A"name" ?wbean * L?[p?B * * R?[hXg???A * L?[????A?o?B * </p> * * @return ???w?B? EVAL_BODY_INCLUDE * @throws JspException JSP O */ @Override public int doStartTag() throws JspException { if (log.isDebugEnabled()) { log.debug("doStartTag() called."); } if ("".equals(codeList) || codeList == null) { // codeListw?? log.error("codeList is required."); throw new JspTagException("codeList is required."); } if (key == null && name == null) { // keynamew?? log.error("key and name is required."); throw new JspTagException("key and name is required."); } String codeKey = null; if ((key == null) && (name != null)) { if (TagUtil.lookup(pageContext, name, scope) == null) { log.error("bean id:" + name + " is not defined."); throw new JspTagException("bean id:" + name + " is not defined."); } Object bean = null; try { bean = TagUtil.lookup(pageContext, name, property, scope); } catch (JspException e) { // } if (bean == null) { log.error("Cannot get property[" + name + "." + property + "]."); throw new JspTagException("Cannot get property[" + name + "." + property + "]."); } codeKey = bean.toString(); } else { codeKey = key; } // T?[ubgReLXg?AApplicationContext?B ServletContext sc = pageContext.getServletContext(); ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); CodeListLoader loader = null; if (context.containsBean(codeList)) { try { loader = (CodeListLoader) context.getBean(codeList); } catch (ClassCastException e) { // BeanCodeListLoaderOX??[ String errorMessage = "bean id:" + codeList + " is not instance of CodeListLoader."; log.error(errorMessage); throw new JspTagException(errorMessage, e); } } JspWriter out = pageContext.getOut(); if (loader == null) { log.error("CodeListLoader:" + codeList + " is not defined."); throw new JspTagException("CodeListLoader:" + codeList + " is not defined."); } // ?P?[ Locale locale = RequestUtils.getUserLocale((HttpServletRequest) pageContext.getRequest(), Globals.LOCALE_KEY); CodeBean[] codeBeanArray = loader.getCodeBeans(locale); if (codeBeanArray == null) { // codeBeanListnull?? if (log.isWarnEnabled()) { log.warn("Codebean is null. CodeListLoader(bean id:" + codeList + ")"); } // } else { try { // ????R?[hXgl?o?B for (int i = 0; i < codeBeanArray.length; i++) { if (codeKey.equals(codeBeanArray[i].getId())) { out.print(codeBeanArray[i].getName()); break; } } // } catch (IOException ioe) { log.error("", ioe); throw new JspTagException(ioe); } } return EVAL_BODY_INCLUDE; }
From source file:org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass.java
ConstraintsEvaluator getConstraintsEvaluator() { if (grailsApplication != null && grailsApplication.getMainContext() != null) { final ApplicationContext context = grailsApplication.getMainContext(); if (context.containsBean(ConstraintsEvaluator.BEAN_NAME)) { return context.getBean(ConstraintsEvaluator.BEAN_NAME, ConstraintsEvaluator.class); }//w ww.j a v a2 s . c o m } return new DefaultConstraintEvaluator(defaultConstraints); }
From source file:org.codehaus.groovy.grails.commons.spring.DefaultRuntimeSpringConfiguration.java
private void trySettingClassLoaderOnContextIfFoundInParent(ApplicationContext parentCtx) { if (parentCtx.containsBean("classLoader")) { Object cl = parentCtx.getBean("classLoader"); if (cl instanceof ClassLoader) { setClassLoaderOnContext((ClassLoader) cl); }/*from w ww . ja v a2 s . c o m*/ } }
From source file:org.codehaus.groovy.grails.orm.hibernate.AbstractEventTriggeringInterceptor.java
protected boolean isDefinedByCurrentDataStore(Object entity, AbstractGrailsDomainBinder binder) { SessionFactory currentDataStoreSessionFactory = ((AbstractHibernateDatastore) datastore) .getSessionFactory();/* ww w .j a v a 2s . c o m*/ ApplicationContext applicationContext = datastore.getApplicationContext(); Mapping mapping = binder.getMapping(entity.getClass()); List<String> dataSourceNames = null; if (mapping == null) { GrailsApplication grailsApplication = applicationContext.getBean("grailsApplication", GrailsApplication.class); GrailsDomainClass dc = (GrailsDomainClass) grailsApplication .getArtefact(DomainClassArtefactHandler.TYPE, entity.getClass().getName()); if (dc != null) { dataSourceNames = getDatasourceNames(dc); } } else { dataSourceNames = mapping.getDatasources(); } if (dataSourceNames == null) { return false; } for (String dataSource : dataSourceNames) { if (GrailsDomainClassProperty.ALL_DATA_SOURCES.equals(dataSource)) { return true; } boolean isDefault = dataSource.equals(GrailsDomainClassProperty.DEFAULT_DATA_SOURCE); String suffix = isDefault ? "" : "_" + dataSource; String sessionFactoryBeanName = "sessionFactory" + suffix; if (applicationContext.containsBean(sessionFactoryBeanName)) { SessionFactory sessionFactory = applicationContext.getBean(sessionFactoryBeanName, SessionFactory.class); if (currentDataStoreSessionFactory == sessionFactory) { return true; } } else { log.warn("Cannot resolve SessionFactory for dataSource [" + dataSource + "] and entity [" + entity.getClass().getName() + "]"); } } return false; }
From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.AbstractGrailsDomainBinder.java
/** * Evaluates the table name for the given property * * @param domainClass The domain class to evaluate * @return The table name/*from w w w .j av a 2 s . c om*/ */ protected String getTableName(GrailsDomainClass domainClass, String sessionFactoryBeanName) { Mapping m = getMapping(domainClass.getClazz()); String tableName = null; if (m != null && m.getTableName() != null) { tableName = m.getTableName(); } if (tableName == null) { String shortName = domainClass.getShortName(); final GrailsApplication grailsApplication = domainClass.getApplication(); if (grailsApplication != null) { final ApplicationContext mainContext = grailsApplication.getMainContext(); if (mainContext != null && mainContext.containsBean("pluginManager")) { final GrailsPluginManager pluginManager = (GrailsPluginManager) mainContext .getBean("pluginManager"); final GrailsPlugin pluginForClass = pluginManager.getPluginForClass(domainClass.getClazz()); if (pluginForClass != null) { final String pluginName = pluginForClass.getName(); boolean shouldApplyPluginPrefix = false; if (!shortName.toLowerCase().startsWith(pluginName.toLowerCase())) { final String pluginSpecificConfigProperty = "grails.gorm." + GrailsNameUtils.getPropertyName(pluginName) + ".table.prefix.enabled"; final Config config = grailsApplication.getConfig(); if (config.containsKey(pluginSpecificConfigProperty)) { shouldApplyPluginPrefix = config.getProperty(pluginSpecificConfigProperty, Boolean.class, false); } else { shouldApplyPluginPrefix = config.getProperty("grails.gorm.table.prefix.enabled", Boolean.class, false); } } if (shouldApplyPluginPrefix) { shortName = pluginName + shortName; } } } } tableName = getNamingStrategy(sessionFactoryBeanName).classToTableName(shortName); } return tableName; }