Example usage for org.springframework.context ApplicationContext containsBean

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

Introduction

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

Prototype

boolean containsBean(String name);

Source Link

Document

Does this bean factory contain a bean definition or externally registered singleton instance with the given name?

Usage

From source file:org.springframework.data.gemfire.config.CreateDefinedIndexesApplicationListenerTest.java

@Test
public void createDefinedIndexesThrowingAnExceptionIsLogged() throws Exception {
    ApplicationContext mockApplicationContext = mock(ApplicationContext.class,
            "testCreateDefinedIndexesThrowingAnExceptionIsLogged.MockApplicationContext");

    ContextRefreshedEvent mockEvent = mock(ContextRefreshedEvent.class,
            "testCreateDefinedIndexesThrowingAnExceptionIsLogged.MockContextRefreshedEvent");

    QueryService mockQueryService = mock(QueryService.class,
            "testCreateDefinedIndexesThrowingAnExceptionIsLogged.MockQueryService");

    when(mockEvent.getApplicationContext()).thenReturn(mockApplicationContext);
    when(mockApplicationContext
            .containsBean(eq(GemfireConstants.DEFAULT_GEMFIRE_INDEX_DEFINITION_QUERY_SERVICE)))
                    .thenReturn(true);/*from w w w .ja  va2 s.c  om*/
    when(mockApplicationContext.getBean(eq(GemfireConstants.DEFAULT_GEMFIRE_INDEX_DEFINITION_QUERY_SERVICE),
            eq(QueryService.class))).thenReturn(mockQueryService);
    when(mockQueryService.createDefinedIndexes()).thenThrow(new MultiIndexCreationException(
            new HashMap<String, Exception>(Collections.singletonMap("TestKey", new RuntimeException("TEST")))));

    final Log mockLog = mock(Log.class, "testCreateDefinedIndexesThrowingAnExceptionIsLogged.MockLog");

    CreateDefinedIndexesApplicationListener listener = new CreateDefinedIndexesApplicationListener() {
        @Override
        Log initLogger() {
            return mockLog;
        }
    };

    listener.onApplicationEvent(mockEvent);

    verify(mockEvent, times(1)).getApplicationContext();
    verify(mockApplicationContext, times(1))
            .containsBean(eq(GemfireConstants.DEFAULT_GEMFIRE_INDEX_DEFINITION_QUERY_SERVICE));
    verify(mockApplicationContext, times(1)).getBean(
            eq(GemfireConstants.DEFAULT_GEMFIRE_INDEX_DEFINITION_QUERY_SERVICE), eq(QueryService.class));
    verify(mockLog, times(1)).warn(startsWith("unable to create defined Indexes (if any):"));
}

From source file:org.springframework.data.gemfire.config.support.DefinedIndexesApplicationListener.java

private QueryService getQueryService(ContextRefreshedEvent event) {

    ApplicationContext applicationContext = event.getApplicationContext();

    String queryServiceBeanName = getQueryServiceBeanName();

    return (applicationContext.containsBean(queryServiceBeanName)
            ? applicationContext.getBean(queryServiceBeanName, QueryService.class)
            : null);// w  ww. java 2  s  .com
}

From source file:org.springframework.extensions.webscripts.DeclarativeRegistry.java

/**
 * Initialise Web Scripts/* ww w.  j  a  v  a  2 s  .c om*/
 *
 * Note: Each invocation of this method resets the list of the services
 */
private void initWebScripts() {
    if (logger.isDebugEnabled())
        logger.debug("Initialising Web Scripts (Container: " + container.getName() + ", URI index: "
                + uriIndex.getClass().getName() + ")");

    this.indexResetLock.writeLock().lock();
    try {
        // clear currently registered services
        uriIndex.clear();
        uriIndexCache.clear();
        webscriptsById.clear();
        failedWebScriptsByPath.clear();
        packageByPath.clear();
        packageByPath.put("/", new PathImpl("/"));
        uriByPath.clear();
        uriByPath.put("/", new PathImpl("/"));
        familyByPath.clear();
        familyByPath.put("/", new PathImpl("/"));
        lifecycleByPath.clear();
        lifecycleByPath.put("/", new PathImpl("/"));
        failedPackageDescriptionsByPath.clear();
        failedSchemaDescriptionsByPath.clear();
        packageDocumentByPath.clear();
        schemaDocumentById.clear();

        for (Store apiStore : searchPath.getStores()) {
            // Process package description documents.
            if (logger.isDebugEnabled())
                logger.debug("Locating package descriptions within " + apiStore.getBasePath());

            String[] packageDescPaths;
            try {
                packageDescPaths = apiStore.getDocumentPaths("/", true,
                        PackageDescriptionDocument.DESC_NAME_PATTERN);
            } catch (IOException e) {
                throw new WebScriptException("Failed to search for package descriptions in store " + apiStore,
                        e);
            }
            for (String packageDescPath : packageDescPaths) {
                try {
                    // build package description
                    PackageDescriptionDocument packageDesc = null;
                    InputStream packageDescIS = null;
                    try {
                        packageDescIS = apiStore.getDocument(packageDescPath);
                        packageDesc = createPackageDescription(apiStore, packageDescPath, packageDescIS);

                        String packageDescId = packageDesc.getId();
                        // register the package description document
                        if (!packageDocumentByPath.containsKey(packageDescId)) {
                            packageDocumentByPath.put(packageDescId, packageDesc);
                        }
                    } catch (IOException e) {
                        throw new WebScriptException("Failed to read package description document "
                                + apiStore.getBasePath() + packageDescPath, e);
                    } finally {
                        try {
                            if (packageDescIS != null)
                                packageDescIS.close();
                        } catch (IOException e) {
                            // NOTE: ignore close exception
                        }
                    }
                } catch (WebScriptException e) {
                    // record package description document failure
                    String path = apiStore.getBasePath() + "/" + packageDescPath;
                    Throwable c = e;
                    String cause = c.getMessage();
                    while (c.getCause() != null && !c.getCause().equals(c)) {
                        c = c.getCause();
                        cause += " ; " + c.getMessage();
                    }
                    failedPackageDescriptionsByPath.put(path, cause);
                }

            }

            // Process schema description documents.

            if (logger.isDebugEnabled())
                logger.debug("Locating schema descriptions within " + apiStore.getBasePath());

            String[] schemaDescPaths;
            try {
                schemaDescPaths = apiStore.getDocumentPaths("/", true,
                        SchemaDescriptionDocument.DESC_NAME_PATTERN);
            } catch (IOException e) {
                throw new WebScriptException("Failed to search for schema descriptions in store " + apiStore,
                        e);
            }
            for (String schemaDescPath : schemaDescPaths) {
                try {
                    // build schema description
                    SchemaDescriptionDocument schemaDesc = null;
                    InputStream schemaDescIS = null;
                    try {
                        schemaDescIS = apiStore.getDocument(schemaDescPath);
                        schemaDesc = createSchemaDescription(apiStore, schemaDescPath, schemaDescIS);

                        String schemaDescId = schemaDesc.getId();
                        // register the schema description document
                        if (!schemaDocumentById.containsKey(schemaDescId)) {
                            schemaDocumentById.put(schemaDescId, schemaDesc);
                        }
                    } catch (IOException e) {
                        throw new WebScriptException("Failed to read Web Script description document "
                                + apiStore.getBasePath() + schemaDescPath, e);
                    } finally {
                        try {
                            if (schemaDescIS != null)
                                schemaDescIS.close();
                        } catch (IOException e) {
                            // NOTE: ignore close exception
                        }
                    }
                } catch (WebScriptException e) {
                    // record web script definition failure
                    String path = apiStore.getBasePath() + "/" + schemaDescPath;
                    Throwable c = e;
                    String cause = c.getMessage();
                    while (c.getCause() != null && !c.getCause().equals(c)) {
                        c = c.getCause();
                        cause += " ; " + c.getMessage();
                    }
                    failedSchemaDescriptionsByPath.put(path, cause);
                }

            }

            // register services
            if (logger.isDebugEnabled())
                logger.debug("Locating Web Scripts within " + apiStore.getBasePath());

            String[] serviceDescPaths;
            try {
                serviceDescPaths = apiStore.getDescriptionDocumentPaths();
            } catch (IOException e) {
                throw new WebScriptException("Failed to search for web scripts in store " + apiStore, e);
            }
            for (String serviceDescPath : serviceDescPaths) {
                try {
                    // build service description
                    DescriptionImpl serviceDesc = null;
                    InputStream serviceDescIS = null;
                    try {
                        serviceDescIS = apiStore.getDocument(serviceDescPath);
                        serviceDesc = createDescription(apiStore, serviceDescPath, serviceDescIS);
                    } catch (IOException e) {
                        throw new WebScriptException("Failed to read Web Script description document "
                                + apiStore.getBasePath() + serviceDescPath, e);
                    } finally {
                        try {
                            if (serviceDescIS != null)
                                serviceDescIS.close();
                        } catch (IOException e) {
                            // NOTE: ignore close exception
                        }
                    }

                    // determine if service description has been registered
                    String id = serviceDesc.getId();
                    if (webscriptsById.containsKey(id)) {
                        // move to next service
                        if (logger.isDebugEnabled()) {
                            WebScript existingService = webscriptsById.get(id);
                            Description existingDesc = existingService.getDescription();
                            String msg = "Web Script description document " + serviceDesc.getStorePath() + "/"
                                    + serviceDesc.getDescPath();
                            msg += " overridden by " + existingDesc.getStorePath() + "/"
                                    + existingDesc.getDescPath();
                            logger.debug(msg);
                        }
                        continue;
                    }

                    //
                    // construct service implementation
                    //

                    // establish kind of service implementation
                    ApplicationContext applicationContext = getApplicationContext();
                    String kind = serviceDesc.getKind();
                    String serviceImplName = null;
                    String descImplName = null;
                    if (kind == null) {
                        // rely on default mapping of webscript id to service implementation
                        // NOTE: always fallback to vanilla Declarative Web Script
                        String beanName = "webscript." + id.replace('/', '.');
                        serviceImplName = (applicationContext.containsBean(beanName) ? beanName
                                : defaultWebScript);
                        descImplName = "webscriptdesc." + id.replace('/', '.');
                    } else {
                        // rely on explicitly defined web script kind
                        if (!applicationContext.containsBean("webscript." + kind)) {
                            throw new WebScriptException("Web Script kind '" + kind + "' is unknown");
                        }
                        serviceImplName = "webscript." + kind;
                        descImplName = "webscriptdesc." + kind;
                    }

                    // extract service specific description extensions
                    if (applicationContext.containsBean(descImplName)
                            && applicationContext.isTypeMatch(descImplName, DescriptionExtension.class)) {
                        DescriptionExtension descriptionExtensions = (DescriptionExtension) applicationContext
                                .getBean(descImplName);
                        serviceDescIS = null;
                        try {
                            serviceDescIS = apiStore.getDocument(serviceDescPath);
                            Map<String, Serializable> extensions = descriptionExtensions
                                    .parseExtensions(serviceDescPath, serviceDescIS);
                            serviceDesc.setExtensions(extensions);

                            if (logger.isDebugEnabled())
                                logger.debug("Extracted " + (extensions == null ? "0" : extensions.size())
                                        + " description extension(s) for Web Script " + id + " (" + extensions
                                        + ")");
                        } catch (IOException e) {
                            throw new WebScriptException(
                                    "Failed to parse extensions from Web Script description document "
                                            + apiStore.getBasePath() + serviceDescPath,
                                    e);
                        } finally {
                            try {
                                if (serviceDescIS != null)
                                    serviceDescIS.close();
                            } catch (IOException e) {
                                // NOTE: ignore close exception
                            }
                        }
                    }

                    // retrieve service implementation
                    WebScript serviceImpl = (WebScript) applicationContext.getBean(serviceImplName);
                    serviceImpl.init(container, serviceDesc);

                    if (logger.isDebugEnabled())
                        logger.debug("Found Web Script " + id + " (desc: " + serviceDescPath + ", impl: "
                                + serviceImplName + ", auth: " + serviceDesc.getRequiredAuthentication()
                                + ", trx: " + serviceDesc.getRequiredTransaction() + ", format style: "
                                + serviceDesc.getFormatStyle() + ", default format: "
                                + serviceDesc.getDefaultFormat() + ")");

                    // register service and its urls
                    webscriptsById.put(id, serviceImpl);
                    for (String uriTemplate : serviceDesc.getURIs()) {
                        uriIndex.registerUri(serviceImpl, uriTemplate);
                        if (logger.isDebugEnabled())
                            logger.debug("Registered Web Script URL '"
                                    + serviceImpl.getDescription().getMethod() + ":" + uriTemplate + "'");
                    }

                    // build path indexes to web script
                    Path scriptPath = registerPackage(serviceImpl);
                    serviceDesc.setPackage(scriptPath);
                    registerURIs(serviceImpl);
                    registerFamily(serviceImpl);
                    registerLifecycle(serviceImpl);
                } catch (WebScriptException e) {
                    // record web script definition failure
                    String path = apiStore.getBasePath() + "/" + serviceDescPath;
                    Throwable c = e;
                    String cause = c.getMessage();
                    while (c.getCause() != null && !c.getCause().equals(c)) {
                        c = c.getCause();
                        cause += " ; " + c.getMessage();
                    }
                    failedWebScriptsByPath.put(path, cause);
                }
            }
        }
    } finally {
        this.indexResetLock.writeLock().unlock();
    }
    if (logger.isWarnEnabled()) {
        for (Map.Entry<String, String> failedWebScript : failedWebScriptsByPath.entrySet()) {
            String msg = "Unable to register script " + failedWebScript.getKey() + " due to error: "
                    + failedWebScript.getValue();
            logger.warn(msg);
        }
        for (Map.Entry<String, String> failedPackageDesription : failedPackageDescriptionsByPath.entrySet()) {
            String msg = "Unable to register package description document " + failedPackageDesription.getKey()
                    + " due to error: " + failedPackageDesription.getValue();
            logger.warn(msg);
        }
        for (Map.Entry<String, String> failedSchemaDescription : failedSchemaDescriptionsByPath.entrySet()) {
            String msg = "Unable to register schema description document " + failedSchemaDescription.getKey()
                    + " due to error: " + failedSchemaDescription.getValue();
            logger.warn(msg);
        }
    }
}

From source file:org.springframework.richclient.application.support.AbstractApplicationWindow.java

protected PageDescriptor getPageDescriptor(String pageDescriptorId) {
    ApplicationContext ctx = Application.instance().getApplicationContext();
    Assert.state(ctx.containsBean(pageDescriptorId), "Do not know about page or view descriptor with name '"
            + pageDescriptorId + "' - check your context config");
    Object desc = ctx.getBean(pageDescriptorId);
    if (desc instanceof PageDescriptor) {
        return (PageDescriptor) desc;
    } else if (desc instanceof ViewDescriptor) {
        return new SingleViewPageDescriptor((ViewDescriptor) desc);
    } else {//w w w.ja  va2  s  .  c  om
        throw new IllegalArgumentException(
                "Page id '" + pageDescriptorId + "' is not backed by an ApplicationPageDescriptor");
    }
}

From source file:org.springframework.richclient.application.support.DefaultApplicationServices.java

/**
 * Get the implementation of a service by using the decapitalized shortname of the serviceType class name.
 *
 * @param serviceType/*from   ww w . j a v  a 2s.  c  o  m*/
 *            the service class to lookup the bean definition
 * @return the found service implementation if a bean definition can be found and it implements the required service
 *         type, otherwise null
 * @see ClassUtils#getShortNameAsProperty(Class)
 */
protected Object getServiceForClassType(Class serviceType) {
    String lookupName = ClassUtils.getShortNameAsProperty(serviceType);
    ApplicationContext ctx = getApplicationContext();
    if (ctx.containsBean(lookupName)) {
        Object bean = ctx.getBean(lookupName);
        if (serviceType.isAssignableFrom(bean.getClass())) {
            if (logger.isDebugEnabled()) {
                logger.debug("Using bean '" + lookupName + "' (" + bean.getClass().getName() + ") for service "
                        + serviceType.getName());
            }
            return bean;
        } else if (logger.isDebugEnabled()) {
            logger.debug("Bean with id '" + lookupName + "' (" + bean.getClass().getName()
                    + ") does not implement " + serviceType.getName());
        }
    } else if (logger.isDebugEnabled()) {
        logger.debug("No Bean with id '" + lookupName + "' found for service " + serviceType.getName());
    }
    return null;
}

From source file:org.springframework.web.reactive.result.view.AbstractView.java

/**
 * Return the {@link RequestDataValueProcessor} to use.
 * <p>The default implementation looks in the {@link #getApplicationContext()
 * Spring configuration} for a {@code RequestDataValueProcessor} bean with
 * the name {@link #REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME}.
 * @return the RequestDataValueProcessor, or null if there is none at the
 * application context.//from w w  w  .  j a  va 2  s  .c om
 */
@Nullable
protected RequestDataValueProcessor getRequestDataValueProcessor() {
    ApplicationContext context = getApplicationContext();
    if (context != null && context.containsBean(REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME)) {
        return context.getBean(REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME, RequestDataValueProcessor.class);
    }
    return null;
}

From source file:ro.nextreports.server.web.NextServerApplication.java

public Object getSpringBean(String beanName) {
    ApplicationContext applicationContext = WebApplicationContextUtils
            .getWebApplicationContext(getServletContext());
    if (!applicationContext.containsBean(beanName)) {
        return null;
    }/*from w  w  w. jav a  2s  .  co m*/

    return applicationContext.getBean(beanName);
}

From source file:ubic.gemma.apps.ExpressionExperimentLoadSpacesMasterCLI.java

/**
 * Initialization of spring beans./*from  w  w  w .ja  v  a 2s  .  c o m*/
 * 
 * @throws Exception
 */
protected void init() throws Exception {

    // spacesUtil = this.getBean( SpacesUtil.class );
    ApplicationContext updatedContext = null; // spacesUtil.addGemmaSpacesToApplicationContext();

    if (!updatedContext.containsBean("gigaspacesTemplate"))
        throw new RuntimeException("GemmaSpaces beans could not be loaded. Cannot start master.");

    template = (GigaSpacesTemplate) updatedContext.getBean("gigaspacesTemplate");

    proxy = (ExpressionExperimentLoadTask) updatedContext.getBean("javaspaceProxyInterfaceFactory");
}