Example usage for org.springframework.context ApplicationContext isTypeMatch

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

Introduction

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

Prototype

boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;

Source Link

Document

Check whether the bean with the given name matches the specified type.

Usage

From source file:org.carewebframework.api.spring.SpringUtil.java

/**
 * Returns the bean with an id matching the specified id, or null if none found.
 * //w  ww .  j av a 2s. co  m
 * @param id Bean id
 * @param clazz Expected return type.
 * @return Returns the bean instance whose id matches the specified id, or null if none found or
 *         if the application context cannot be determined.
 */
public static <T> T getBean(String id, Class<T> clazz) {
    ApplicationContext appContext = getAppContext();
    return appContext == null ? null
            : appContext.containsBean(id) && appContext.isTypeMatch(id, clazz) ? appContext.getBean(id, clazz)
                    : null;
}

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

/**
 * Initialise Web Scripts/*  www.jav a2 s.c  o  m*/
 *
 * 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);
        }
    }
}