Example usage for org.springframework.context ApplicationContext getBeanNamesForType

List of usage examples for org.springframework.context ApplicationContext getBeanNamesForType

Introduction

In this page you can find the example usage for org.springframework.context ApplicationContext getBeanNamesForType.

Prototype

String[] getBeanNamesForType(ResolvableType type);

Source Link

Document

Return the names of beans matching the given type (including subclasses), judging from either bean definitions or the value of getObjectType in the case of FactoryBeans.

Usage

From source file:org.liquibase.test.junit.LiquibaseTestExecutionListener.java

/**
 * Wrapper to get a method/*w  w  w  .j av  a  2  s .co m*/
 * <code>ApplicationContext.getBean(Class _class)</code> like in spring 3.0.
 * It will returns always the first instance of the founded class.
 * 
 * @param context
 *            from which the bean should be retrieved
 * @param classType
 *            class type that should be retrieved from the configuration
 *            file.
 * 
 * @return a object of the type or <code>null</code>
 */
@SuppressWarnings("unchecked")
private <T> T getBean(final ApplicationContext context, final Class<T> classType) {
    T result = null;

    String[] names = context.getBeanNamesForType(classType);

    if (names != null && names.length > 0) {
        // we always return the bean with the first name

        result = (T) context.getBean(names[0]);
    }

    return result;
}

From source file:org.flywaydb.test.junit.FlywayTestExecutionListener.java

/**
 * Wrapper to get a method/*from  w  w  w.  java2  s .  c o m*/
 * <code>ApplicationContext.getBean(Class _class)</code> like in spring 3.0.
 * It will returns always the first instance of the founded class.
 *
 * @param context
 *            from which the bean should be retrieved
 * @param classType
 *            class type that should be retrieved from the configuration
 *            file.
 *
 * @return a object of the type or <code>null</code>
 */
private Flyway getBean(final ApplicationContext context, final Class<?> classType) {
    Flyway result = null;

    String[] names = context.getBeanNamesForType(classType);

    if (names != null && names.length > 0) {
        // we always return the bean with the first name

        result = (Flyway) context.getBean(names[0]);
    }

    return result;
}

From source file:edu.internet2.middleware.shibboleth.common.relyingparty.provider.SAMLMDRelyingPartyConfigurationManager.java

/** {@inheritDoc} */
protected void onNewContextCreated(ApplicationContext newServiceContext) throws ServiceException {
    MetadataProvider oldProvider = metadataProvider;
    HashMap<String, RelyingPartyConfiguration> oldRpConfigs = rpConfigs;
    try {/*from  w  w  w.  ja  v a 2  s . c  om*/
        String[] relyingPartyGroupNames = newServiceContext.getBeanNamesForType(RelyingPartyGroup.class);
        RelyingPartyGroup newRpGroup = (RelyingPartyGroup) newServiceContext.getBean(relyingPartyGroupNames[0]);

        metadataProvider = newRpGroup.getMetadataProvider();

        HashMap<String, RelyingPartyConfiguration> newRpConfigs = new HashMap<String, RelyingPartyConfiguration>();
        List<RelyingPartyConfiguration> loadRpConfigs = newRpGroup.getRelyingParties();
        if (loadRpConfigs != null) {
            for (RelyingPartyConfiguration newRpConfig : loadRpConfigs) {
                newRpConfigs.put(newRpConfig.getRelyingPartyId(), newRpConfig);
                log.debug("Registering configuration for relying party: {}", newRpConfig.getRelyingPartyId());
            }
        }
        newRpConfigs.put(ANONYMOUS_RP_NAME, newRpGroup.getAnonymousRP());
        newRpConfigs.put(DEFAULT_RP_NAME, newRpGroup.getDefaultRP());
        rpConfigs = newRpConfigs;

        if (oldProvider instanceof BaseMetadataProvider) {
            ((BaseMetadataProvider) oldProvider).destroy();
        }
    } catch (Exception e) {
        metadataProvider = oldProvider;
        rpConfigs = oldRpConfigs;
        throw new ServiceException(getId() + " configuration is not valid, retaining old configuration", e);
    }
}

From source file:edu.internet2.middleware.shibboleth.common.attribute.filtering.provider.ShibbolethAttributeFilteringEngine.java

/** {@inheritDoc} */
protected void onNewContextCreated(ApplicationContext newServiceContext) throws ServiceException {
    List<AttributeFilterPolicy> oldFilterPolicies = filterPolicies;

    try {/*from   ww  w .ja  v a 2s  .c  o  m*/
        List<AttributeFilterPolicy> newFilterPolicies = new ArrayList<AttributeFilterPolicy>();
        String[] beanNames = newServiceContext.getBeanNamesForType(AttributeFilterPolicy.class);
        for (String beanName : beanNames) {
            newFilterPolicies.add((AttributeFilterPolicy) newServiceContext.getBean(beanName));
        }
        filterPolicies = newFilterPolicies;
    } catch (Exception e) {
        filterPolicies = oldFilterPolicies;
        throw new ServiceException(getId() + " configuration is not valid, retaining old configuration", e);
    }
}

From source file:org.flywaydb.test.dbunit.DBUnitTestExecutionListener.java

/**
 * Wrapper to get a methode//  w  w  w. j a  v  a  2s . c o  m
 * <code>ApplicationContext.getBean(Class _class)</code> like in spring 3.0.
 *
 * @param context
 *            from which the bean should be retrieved
 * @param classType
 *            class type
 *
 * @return a object of the type or <code>null</code>
 */
private DataSource getBean(final ApplicationContext context, final Class<?> classType) {
    DataSource result = null;

    String[] names = context.getBeanNamesForType(classType);

    if (names != null && names.length > 0) {
        // we always return the bean with the first name

        result = (DataSource) context.getBean(names[0]);
    }

    return result;
}

From source file:edu.internet2.middleware.shibboleth.common.attribute.resolver.provider.ShibbolethAttributeResolver.java

/** {@inheritDoc} */
protected void onNewContextCreated(ApplicationContext newServiceContext) throws ServiceException {
    String[] beanNames;//from w  ww.  j  a v  a 2  s  . c  o  m

    Map<String, DataConnector> oldDataConnectors = dataConnectors;
    Map<String, DataConnector> newDataConnectors = new HashMap<String, DataConnector>();
    DataConnector dConnector;
    beanNames = newServiceContext.getBeanNamesForType(DataConnector.class);
    log.debug("Loading {} data connectors", beanNames.length);
    for (String beanName : beanNames) {
        dConnector = (DataConnector) newServiceContext.getBean(beanName);
        newDataConnectors.put(dConnector.getId(), dConnector);
    }

    Map<String, AttributeDefinition> oldAttributeDefinitions = definitions;
    Map<String, AttributeDefinition> newAttributeDefinitions = new HashMap<String, AttributeDefinition>();
    AttributeDefinition aDefinition;
    beanNames = newServiceContext.getBeanNamesForType(AttributeDefinition.class);
    log.debug("Loading {} attribute definitions", beanNames.length);
    for (String beanName : beanNames) {
        aDefinition = (AttributeDefinition) newServiceContext.getBean(beanName);
        newAttributeDefinitions.put(aDefinition.getId(), aDefinition);
    }

    Map<String, PrincipalConnector> oldPrincipalConnectors = principalConnectors;
    Map<String, PrincipalConnector> newPrincipalConnectors = new HashMap<String, PrincipalConnector>();
    PrincipalConnector pConnector;
    beanNames = newServiceContext.getBeanNamesForType(PrincipalConnector.class);
    log.debug("Loading {} principal connectors", beanNames.length);
    for (String beanName : beanNames) {
        pConnector = (PrincipalConnector) newServiceContext.getBean(beanName);
        newPrincipalConnectors.put(pConnector.getId(), pConnector);
    }

    try {
        dataConnectors = newDataConnectors;
        definitions = newAttributeDefinitions;
        principalConnectors = newPrincipalConnectors;
        validate();
    } catch (AttributeResolutionException e) {
        dataConnectors = oldDataConnectors;
        definitions = oldAttributeDefinitions;
        principalConnectors = oldPrincipalConnectors;
        throw new ServiceException(getId() + " configuration is not valid, retaining old configuration", e);
    }
}

From source file:com.dushyant.portlet.gwt.PathBasedGwtRpcServiceResolver.java

/**
 * Scans the application context and its parents for service beans that implement the {@link
 * com.google.gwt.user.client.rpc.RemoteService}
 *
 * @param appContext Application context
 *
 * @return Map<String, Object> A map of RemoteServiceRelativePath annotation values vs the RPC service instances
 *//*from w  ww.  j  ava  2s. c om*/
private Map<String, Object> initGwtRpcServiceMap(final ApplicationContext appContext) {
    // Create a map of rpc services keyed against the RemoteServiceRelativePath annotation value
    Map<String, Object> rpcServiceMap = new HashMap<String, Object>();

    // If Gwt RPC service beans exist already (may be explicitly configured through spring config xml file)
    // then add them first.
    Map<String, Object> existingGwtRpcServiceMap = getGwtRpcServiceMap();
    if (existingGwtRpcServiceMap != null) {
        rpcServiceMap.putAll(existingGwtRpcServiceMap);
    }

    if (appContext != null) {
        //Find the beans of type RemoteService
        String[] remoteServiceBeans = appContext.getBeanNamesForType(RemoteService.class);
        if (!ArrayUtils.isEmpty(remoteServiceBeans)) {
            // If remoteServiceBeans are found then scan for Gwt Rpc beans
            scanForGwtRpcBeans(appContext, rpcServiceMap, remoteServiceBeans);
        }
    }
    return rpcServiceMap;
}

From source file:org.geowebcache.storage.blobstore.memory.MemoryBlobStore.java

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    if (!cacheAlreadySet.get()) {
        // Get all the CacheProvider beans
        String[] beans = applicationContext.getBeanNamesForType(CacheProvider.class);
        int beanSize = beans.length;
        boolean configured = false;
        // If at least one bean is present, use it
        if (beanSize > 0) {
            // If a bean name is defined, get the related bean
            if (cacheBeanName != null && !cacheBeanName.isEmpty()) {
                for (String beanDef : beans) {
                    if (cacheBeanName.equalsIgnoreCase(beanDef)) {
                        CacheProvider bean = applicationContext.getBean(beanDef, CacheProvider.class);
                        if (bean.isAvailable()) {
                            setCacheProvider(bean);
                            configured = true;
                            break;
                        }/*from  w  ww  .  j  ava  2s  . c o  m*/
                    }
                }
            }
            // If only one is present it is used
            if (!configured && beanSize == 1) {
                CacheProvider bean = applicationContext.getBean(beans[0], CacheProvider.class);
                if (bean.isAvailable()) {
                    setCacheProvider(bean);
                    configured = true;
                }
            }
            // If two are present and at least one of them is not guava, then it is used
            if (!configured && beanSize == 2) {
                for (String beanDef : beans) {
                    CacheProvider bean = applicationContext.getBean(beanDef, CacheProvider.class);
                    if (!(bean instanceof GuavaCacheProvider) && bean.isAvailable()) {
                        setCacheProvider(bean);
                        configured = true;
                        break;
                    }
                }
                // Try again and search if at least a GuavaCacheProvider is present
                if (!configured) {
                    for (String beanDef : beans) {
                        CacheProvider bean = applicationContext.getBean(beanDef, CacheProvider.class);
                        if (bean.isAvailable()) {
                            setCacheProvider(bean);
                            configured = true;
                            break;
                        }
                    }
                }
            }
            if (!configured) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("CacheProvider not configured, use default configuration");
                }
            }
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("CacheProvider already configured");
        }
    }
}

From source file:it.cilea.osd.jdyna.web.controller.ImportConfigurazione.java

/** Performa l'import da file xml di configurazioni di oggetti;
 *  Sull'upload del file la configurazione dell'oggetto viene caricato come contesto di spring
 *  e salvate su db./*w  ww.  ja v a  2s.  c o  m*/
 */
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object,
        BindException errors) throws RuntimeException, IOException {

    FileUploadConfiguration bean = (FileUploadConfiguration) object;
    MultipartFile file = (CommonsMultipartFile) bean.getFile();
    File a = null;

    //creo il file temporaneo che sara' caricato come contesto di spring per caricare la configurazione degli oggetti
    a = File.createTempFile("jdyna", ".xml", new File(path));
    file.transferTo(a);

    ApplicationContext context = null;
    try {
        context = new FileSystemXmlApplicationContext(new String[] { "file:" + a.getAbsolutePath() },
                getApplicationContext());

    } catch (XmlBeanDefinitionStoreException exc) {
        //cancello il file dalla directory temporanea
        logger.warn("Errore nell'importazione della configurazione dal file: " + file.getOriginalFilename(),
                exc);
        a.delete();
        saveMessage(request, getText("action.file.nosuccess.upload", new Object[] { exc.getMessage() },
                request.getLocale()));
        return new ModelAndView(getErrorView());
    }
    //cancello il file dalla directory temporanea
    a.delete();
    String[] tpDefinitions = context.getBeanNamesForType(tpClass);
    //la variabile i conta le tipologie caricate con successo
    int i = 0;
    //la variabile j conta le tipologie non caricate
    int j = 0;
    for (String tpNameDefinition : tpDefinitions) {
        try {
            TP tipologiaDaImportare = (TP) context.getBean(tpNameDefinition);
            applicationService.saveOrUpdate(tpClass, tipologiaDaImportare);
        } catch (Exception ecc) {
            saveMessage(request, getText("action.file.nosuccess.metadato.upload",
                    new Object[] { ecc.getMessage() }, request.getLocale()));
            j++;
            i--;
        }
        i++;
    }

    String[] areeDefinitions = context.getBeanNamesForType(areaClass);
    int w = 0;
    int v = 0;
    for (String areaNameDefinition : areeDefinitions) {
        try {
            A areaDaImportare = (A) context.getBean(areaNameDefinition);
            applicationService.saveOrUpdate(areaClass, areaDaImportare);
        } catch (Exception ecc) {
            saveMessage(request, getText("action.file.nosuccess.metadato.upload",
                    new Object[] { ecc.getMessage() }, request.getLocale()));
            v++;
            w--;
        }
        w++;
    }
    // check sulla tipologia poiche' ci sono oggetti che non hanno la tipologia tipo Opera e Parte
    if (typeClass != null) {
        String[] typeDefinitions = context.getBeanNamesForType(typeClass);
        int r = 0;
        int t = 0;
        for (String typeDefinition : typeDefinitions) {
            try {
                TY tipologiaDaImportare = (TY) context.getBean(typeDefinition);
                applicationService.saveOrUpdate(typeClass, tipologiaDaImportare);
            } catch (Exception ecc) {
                saveMessage(request, getText("action.file.nosuccess.metadato.upload",
                        new Object[] { ecc.getMessage() }, request.getLocale()));
                t++;
                r--;
            }
            r++;
        }

        saveMessage(request,
                getText("action.file.success.upload.tipologie",
                        new Object[] { new String("Totale Tipologie:" + (t + r) + " [" + r
                                + "caricate con successo/" + t + " fallito caricamento]") },
                        request.getLocale()));

    }

    saveMessage(request,
            getText("action.file.success.upload",
                    new Object[] {
                            new String("Totale TP:" + (i + j) + "" + "[" + i + " caricate con successo/" + j
                                    + " fallito caricamento]"),
                            new String("Totale Aree:" + (w + v) + " [" + w + "caricate con successo/" + v
                                    + " fallito caricamento]") },
                    request.getLocale()));

    return new ModelAndView(getDetailsView());
}