List of usage examples for org.springframework.context ApplicationContext getBeanNamesForType
String[] getBeanNamesForType(ResolvableType type);
From source file:org.apache.s4.MainApp.java
public static void main(String args[]) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c")); options.addOption(/*from w w w. j a v a 2s . com*/ OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a")); options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d")); options.addOption(OptionBuilder.withArgName("seedtime").hasArg() .withDescription("event clock initialization time").create("s")); options.addOption( OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e")); options.addOption( OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i")); options.addOption( OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t")); CommandLineParser parser = new GnuParser(); CommandLine commandLine = null; String clockType = "wall"; try { commandLine = parser.parse(options, args); } catch (ParseException pe) { System.err.println(pe.getLocalizedMessage()); System.exit(1); } int instanceId = -1; if (commandLine.hasOption("i")) { String instanceIdStr = commandLine.getOptionValue("i"); try { instanceId = Integer.parseInt(instanceIdStr); } catch (NumberFormatException nfe) { System.err.println("Bad instance id: %s" + instanceIdStr); System.exit(1); } } if (commandLine.hasOption("c")) { coreHome = commandLine.getOptionValue("c"); } if (commandLine.hasOption("a")) { appsHome = commandLine.getOptionValue("a"); } if (commandLine.hasOption("d")) { clockType = commandLine.getOptionValue("d"); } if (commandLine.hasOption("e")) { extsHome = commandLine.getOptionValue("e"); } String configType = "typical"; if (commandLine.hasOption("t")) { configType = commandLine.getOptionValue("t"); } long seedTime = 0; if (commandLine.hasOption("s")) { seedTime = Long.parseLong(commandLine.getOptionValue("s")); } File coreHomeFile = new File(coreHome); if (!coreHomeFile.isDirectory()) { System.err.println("Bad core home: " + coreHome); System.exit(1); } File appsHomeFile = new File(appsHome); if (!appsHomeFile.isDirectory()) { System.err.println("Bad applications home: " + appsHome); System.exit(1); } if (instanceId > -1) { System.setProperty("instanceId", "" + instanceId); } else { System.setProperty("instanceId", "" + S4Util.getPID()); } List loArgs = commandLine.getArgList(); if (loArgs.size() < 1) { // System.err.println("No bean configuration file specified"); // System.exit(1); } // String s4ConfigXml = (String) loArgs.get(0); // System.out.println("s4ConfigXml is " + s4ConfigXml); ClassPathResource propResource = new ClassPathResource("s4-core.properties"); Properties prop = new Properties(); if (propResource.exists()) { prop.load(propResource.getInputStream()); } else { System.err.println("Unable to find s4-core.properties. It must be available in classpath"); System.exit(1); } ApplicationContext coreContext = null; String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType; String configPath = ""; List<String> coreConfigUrls = new ArrayList<String>(); File configFile = null; // load clock configuration configPath = configBase + File.separatorChar + clockType + "-clock.xml"; coreConfigUrls.add(configPath); // load core config xml configPath = configBase + File.separatorChar + "s4-core-conf.xml"; configFile = new File(configPath); if (!configFile.exists()) { System.err.printf("S4 core config file %s does not exist\n", configPath); System.exit(1); } coreConfigUrls.add(configPath); String[] coreConfigFiles = new String[coreConfigUrls.size()]; coreConfigUrls.toArray(coreConfigFiles); String[] coreConfigFileUrls = new String[coreConfigFiles.length]; for (int i = 0; i < coreConfigFiles.length; i++) { coreConfigFileUrls[i] = "file:" + coreConfigFiles[i]; } coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext); ApplicationContext context = coreContext; Clock clock = (Clock) context.getBean("clock"); if (clock instanceof EventClock && seedTime > 0) { EventClock s4EventClock = (EventClock) clock; s4EventClock.updateTime(seedTime); System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime()); } PEContainer peContainer = (PEContainer) context.getBean("peContainer"); Watcher w = (Watcher) context.getBean("watcher"); w.setConfigFilename(configPath); // load extension modules String[] configFileNames = getModuleConfigFiles(extsHome, prop); if (configFileNames.length > 0) { String[] configFileUrls = new String[configFileNames.length]; for (int i = 0; i < configFileNames.length; i++) { configFileUrls[i] = "file:" + configFileNames[i]; } context = new FileSystemXmlApplicationContext(configFileUrls, context); } // load application modules configFileNames = getModuleConfigFiles(appsHome, prop); if (configFileNames.length > 0) { String[] configFileUrls = new String[configFileNames.length]; for (int i = 0; i < configFileNames.length; i++) { configFileUrls[i] = "file:" + configFileNames[i]; } context = new FileSystemXmlApplicationContext(configFileUrls, context); // attach any beans that implement ProcessingElement to the PE // Container String[] processingElementBeanNames = context.getBeanNamesForType(AbstractPE.class); for (String processingElementBeanName : processingElementBeanNames) { AbstractPE bean = (AbstractPE) context.getBean(processingElementBeanName); bean.setClock(clock); try { bean.setSafeKeeper((SafeKeeper) context.getBean("safeKeeper")); } catch (NoSuchBeanDefinitionException ignored) { // no safe keeper = no checkpointing / recovery } // if the application did not specify an id, use the Spring bean name if (bean.getId() == null) { bean.setId(processingElementBeanName); } System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id " + ((AbstractPE) bean).getId()); peContainer.addProcessor((AbstractPE) bean); } } }
From source file:org.reusables.test.SpringTestUtils.java
/** * Find a single bean form the context with the given type. * //from w ww.j ava2 s . com * @param <T> Type of the bean. * @param ctx The Spring context. * @param type Type of the bean. * @return The bean with the given type, or null if not exactly one bean of the given type was present. */ public static <T> T findBeanByType(final ApplicationContext ctx, final Class<T> type) { final String[] names = ctx.getBeanNamesForType(type); return names.length == 1 ? (T) ctx.getBean(names[0]) : null; }
From source file:org.reusables.test.SpringTestUtils.java
/** * Get a single bean form the context with the given type. * //from w w w . j ava 2 s . c om * @param <T> Type of the bean. * @param ctx The Spring context. * @param type Type of the bean. * @return The bean with the given type. */ public static <T> T getBeanByType(final ApplicationContext ctx, final Class<T> type) { final String[] names = ctx.getBeanNamesForType(type); Validate.isTrue(names.length == 1, "Number of beans of type '" + type.getName() + "' found: " + names.length); return (T) ctx.getBean(names[0]); }
From source file:com.taobao.itest.spring.context.SpringContextManager.java
private static Object getBean(Class<?> type, ApplicationContext applicationContext) { String[] names = applicationContext.getBeanNamesForType(type); if (names.length > 1) { throw new RuntimeException("Found more than one bean which type is " + type); }//from w w w . ja va 2 s. co m return getBean(applicationContext.getBeanNamesForType(type)[0], applicationContext); }
From source file:com.bstek.dorado.spring.RemovableBeanUtils.java
protected static int doDestroyRemovableBeans(ApplicationContext applicationContext) { int removed = 0; if (applicationContext instanceof GenericApplicationContext) { String[] beanNames = applicationContext.getBeanNamesForType(RemovableBean.class); for (String beanName : beanNames) { ((GenericApplicationContext) applicationContext).removeBeanDefinition(beanName); }/*from w ww . j a v a2 s. c om*/ removed = beanNames.length; } else if (applicationContext instanceof AbstractRefreshableApplicationContext) { ConfigurableListableBeanFactory beanFactory = ((AbstractRefreshableApplicationContext) applicationContext) .getBeanFactory(); if (beanFactory instanceof DefaultListableBeanFactory) { String[] beanNames = applicationContext.getBeanNamesForType(RemovableBean.class); for (String beanName : beanNames) { ((DefaultListableBeanFactory) beanFactory).removeBeanDefinition(beanName); } removed = beanNames.length; } } return removed; }
From source file:org.jspringbot.spring.KeywordUtils.java
/** * Builds mapping of robot keywords to actual bean names in spring context. * * @param context Spring application context. * @return mapping of robot keywords to bean names *///from w w w. ja va 2 s. c o m public static Map<String, String> getKeywordMap(ApplicationContext context) { Map<String, String> keywordToBeanMap = new HashMap<String, String>(); // Retrieve beans implementing the Keyword interface. String[] beanNames = context.getBeanNamesForType(Keyword.class); for (String beanName : beanNames) { Object bean = context.getBean(beanName); // Retrieve keyword information KeywordInfo keywordInfo = AnnotationUtils.findAnnotation(bean.getClass(), KeywordInfo.class); // Set keyword name as specified in the keyword info, or if information is not available, use bean name. String keywordName = keywordInfo != null ? keywordInfo.name() : beanName; if (keywordToBeanMap.put(keywordName, beanName) != null) { // If map already contains the keyword name, throw an exception. Keywords should be unique. throw new RuntimeException("Multiple definitions for keyword '" + keywordName + "' exists."); } } return keywordToBeanMap; }
From source file:org.raistlic.spring.test.flyway.FlywayTestExecutionListener.java
/** * The method gets the {@link Flyway} bean from the {@code applicationContext}, using the given * {@code name} if its not empty and there are multiple instances of beans of type {@link Flyway}. * * @param applicationContext the application context to find the bean from, cannot be {@code null}. * @param name the name to help identify the bean if multiple instances exist, {@code null} or * empty if not specified.// w w w . jav a2 s. c o m * @return the required {@link Flyway} bean. * * @throws PreconditionException when {@code applicationContext} is {@code null}. * @throws FlywayTestExecutionException when any other error occur in the process of finding the * {@link Flyway} bean. */ static Flyway getFlywayBean(ApplicationContext applicationContext, String name) { Precondition.param(applicationContext, "applicationContext").notNull(); try { String[] names = applicationContext.getBeanNamesForType(Flyway.class); if (names.length == 0) { throw new FlywayTestExecutionException("Flyway bean definition not found in applicationContext."); } if (names.length == 1) { return applicationContext.getBean(Flyway.class); } if (name == null || name.isEmpty()) { throw new FlywayTestExecutionException( "Name not specified while multiple Flyway beans found in applicationContext: " + Arrays.asList(names)); } return applicationContext.getBean(name, Flyway.class); } catch (Exception ex) { if (ex instanceof FlywayTestExecutionException) { throw (FlywayTestExecutionException) ex; } else { throw new FlywayTestExecutionException(ex); } } }
From source file:edu.internet2.middleware.shibboleth.common.attribute.AttributeAuthorityCLI.java
/** * Builds the attribute request context from the command line arguments. * /*from w ww . j a va2 s . co m*/ * @param parser command line argument parser * @param appCtx spring application context * * @return attribute request context */ private static BaseSAMLProfileRequestContext buildAttributeRequestContext(CmdLineParser parser, ApplicationContext appCtx) { BaseSAMLProfileRequestContext requestContext = new BaseSAMLProfileRequestContext(); String[] rpConfigManagerNames = appCtx.getBeanNamesForType(SAMLMDRelyingPartyConfigurationManager.class); SAMLMDRelyingPartyConfigurationManager rpConfigManager = (SAMLMDRelyingPartyConfigurationManager) appCtx .getBean(rpConfigManagerNames[0]); requestContext.setMetadataProvider(rpConfigManager.getMetadataProvider()); String requester = (String) parser.getOptionValue(CLIParserBuilder.REQUESTER_ARG); if (requester != null) { requestContext.setRelyingPartyConfiguration(rpConfigManager.getRelyingPartyConfiguration(requester)); } else { requester = rpConfigManager.getAnonymousRelyingConfiguration().getRelyingPartyId(); requestContext.setRelyingPartyConfiguration(rpConfigManager.getAnonymousRelyingConfiguration()); } try { requestContext.setInboundMessageIssuer(requester); requestContext.setPeerEntityId(requester); requestContext .setPeerEntityMetadata(requestContext.getMetadataProvider().getEntityDescriptor(requester)); if (requestContext.getPeerEntityMetadata() != null) { requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); requestContext.setPeerEntityRoleMetadata( requestContext.getPeerEntityMetadata().getSPSSODescriptor(protocol)); } } catch (MetadataProviderException e) { errorAndExit("Unable to query for metadata for requester " + requester, e); } try { String issuer = requestContext.getRelyingPartyConfiguration().getProviderId(); requestContext.setOutboundMessageIssuer(issuer); requestContext.setLocalEntityId(issuer); requestContext.setLocalEntityMetadata(requestContext.getMetadataProvider().getEntityDescriptor(issuer)); } catch (MetadataProviderException e) { errorAndExit("Unable to query for metadata for issuer " + requester, e); } String principal = (String) parser.getOptionValue(CLIParserBuilder.PRINCIPAL_ARG); requestContext.setPrincipalName(principal); String authnMethod = (String) parser.getOptionValue(CLIParserBuilder.AUTHN_METHOD_ARG); requestContext.setPrincipalAuthenticationMethod(authnMethod); return requestContext; }
From source file:net.sourceforge.stripes.integration.spring.SpringHelper.java
/** * Looks up a Spring managed bean from an Application Context. First looks for a bean * with name specified. If no such bean exists, looks for a bean by type. If there is * only one bean of the appropriate type, it is returned. If zero or more than one bean * of the correct type exists, an exception is thrown. * * @param ctx the Spring Application Context * @param name the name of the spring bean to look for * @param type the type of bean to look for * @param allowFindByType true to indicate that finding a bean by type is acceptable * if find by name fails.// w w w . j a v a 2 s . c o m * @exception RuntimeException various subclasses of RuntimeException are thrown if it * is not possible to find a unique matching bean in the spring context given * the constraints supplied. */ public static Object findSpringBean(ApplicationContext ctx, String name, Class<?> type, boolean allowFindByType) { // First try to lookup using the name provided try { Object bean = ctx.getBean(name, type); if (bean != null) { log.debug("Found spring bean with name [", name, "] and type [", bean.getClass().getName(), "]"); } return bean; } catch (NestedRuntimeException nre) { if (!allowFindByType) throw nre; } // If we got here then we didn't find a bean yet, try by type String[] beanNames = ctx.getBeanNamesForType(type); if (beanNames.length == 0) { throw new StripesRuntimeException("Unable to find SpringBean with name [" + name + "] or type [" + type.getName() + "] in the Spring application context."); } else if (beanNames.length > 1) { throw new StripesRuntimeException("Unable to find SpringBean with name [" + name + "] or unique bean with type [" + type.getName() + "] in the Spring application context. Found " + beanNames.length + "beans of matching type."); } else { log.debug("Found unique SpringBean with type [" + type.getName() + "]. Matching on ", "type is a little risky so watch out!"); return ctx.getBean(beanNames[0], type); } }
From source file:com.fusesource.forge.jmstest.frontend.CommandLineClient.java
public void setCommand(String command) { if (command.equals("shutdown")) { commands.add(new ShutdownCommand()); }/*from ww w . ja va2s . c o m*/ if (command.startsWith("submit:")) { String configDirs = command.substring("submit:".length()); ApplicationContext appContext = getApplicationContext(configDirs); String[] beanNames = appContext.getBeanNamesForType(BenchmarkConfig.class); log().info("beanNames size --> " + beanNames.length); for (String name : beanNames) { BenchmarkConfig cfg = (BenchmarkConfig) appContext.getBean(name); cfg.getSpringConfigurations(); log().info("Submitting benchmark: " + cfg.getBenchmarkId()); commands.add(new SubmitBenchmarkCommand(cfg)); } } }