Search in sources :

Example 16 with NamespaceHandler

use of org.apache.aries.blueprint.NamespaceHandler in project aries by apache.

the class BlueprintNamespaceHandler method getOrCreateParserContext.

private org.springframework.beans.factory.xml.ParserContext getOrCreateParserContext(ParserContext parserContext) {
    ComponentDefinitionRegistry registry = parserContext.getComponentDefinitionRegistry();
    ExtendedBlueprintContainer container = getBlueprintContainer(parserContext);
    // Create spring application context
    SpringApplicationContext applicationContext = getPassThrough(parserContext, SPRING_APPLICATION_CONTEXT_ID, SpringApplicationContext.class);
    if (applicationContext == null) {
        applicationContext = new SpringApplicationContext(container);
        registry.registerComponentDefinition(createPassThrough(parserContext, SPRING_APPLICATION_CONTEXT_ID, applicationContext, "destroy"));
    }
    // Create registry
    DefaultListableBeanFactory beanFactory = getPassThrough(parserContext, SPRING_BEAN_FACTORY_ID, DefaultListableBeanFactory.class);
    if (beanFactory == null) {
        beanFactory = applicationContext.getBeanFactory();
        registry.registerComponentDefinition(createPassThrough(parserContext, SPRING_BEAN_FACTORY_ID, beanFactory));
    }
    // Create spring parser context
    org.springframework.beans.factory.xml.ParserContext springParserContext = getPassThrough(parserContext, SPRING_CONTEXT_ID, org.springframework.beans.factory.xml.ParserContext.class);
    if (springParserContext == null) {
        // Create spring context
        springParserContext = createSpringParserContext(parserContext, beanFactory);
        registry.registerComponentDefinition(createPassThrough(parserContext, SPRING_CONTEXT_ID, springParserContext));
    }
    // Create processor
    if (!parserContext.getComponentDefinitionRegistry().containsComponentDefinition(SPRING_BEAN_PROCESSOR_ID)) {
        MutableBeanMetadata bm = parserContext.createMetadata(MutableBeanMetadata.class);
        bm.setId(SPRING_BEAN_PROCESSOR_ID);
        bm.setProcessor(true);
        bm.setScope(BeanMetadata.SCOPE_SINGLETON);
        bm.setRuntimeClass(SpringBeanProcessor.class);
        bm.setActivation(BeanMetadata.ACTIVATION_EAGER);
        bm.addArgument(createRef(parserContext, "blueprintBundleContext"), null, 0);
        bm.addArgument(createRef(parserContext, "blueprintContainer"), null, 0);
        bm.addArgument(createRef(parserContext, SPRING_APPLICATION_CONTEXT_ID), null, 0);
        registry.registerComponentDefinition(bm);
    }
    // Add the namespace handlers' bundle to the application context classloader
    for (URI uri : parserContext.getNamespaces()) {
        NamespaceHandler ns = parserContext.getNamespaceHandler(uri);
        if (ns instanceof BlueprintNamespaceHandler) {
            applicationContext.addSourceBundle(((BlueprintNamespaceHandler) ns).bundle);
        }
    }
    return springParserContext;
}
Also used : MutableBeanMetadata(org.apache.aries.blueprint.mutable.MutableBeanMetadata) ComponentDefinitionRegistry(org.apache.aries.blueprint.ComponentDefinitionRegistry) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) NamespaceHandler(org.apache.aries.blueprint.NamespaceHandler) ExtendedBlueprintContainer(org.apache.aries.blueprint.services.ExtendedBlueprintContainer) URI(java.net.URI)

Example 17 with NamespaceHandler

use of org.apache.aries.blueprint.NamespaceHandler in project aries by apache.

the class Parser method parseCustomElement.

private Metadata parseCustomElement(Element element, ComponentMetadata enclosingComponent) {
    NamespaceHandler handler = getNamespaceHandler(element);
    ParserContextImpl context = new ParserContextImpl(this, registry, enclosingComponent, element);
    return handler.parse(element, context);
}
Also used : NamespaceHandler(org.apache.aries.blueprint.NamespaceHandler)

Example 18 with NamespaceHandler

use of org.apache.aries.blueprint.NamespaceHandler in project aries by apache.

the class Parser method handleCustomScope.

/**
 * Tests if a scope attribute value is a custom scope, and if so invokes
 * the appropriate namespace handler, passing the blueprint scope node.
 * <p>
 * Currently this tests for custom scope by looking for the presence of
 * a ':' char within the scope attribute value. This is valid as long as
 * the blueprint schema continues to restrict that custom scopes should
 * require that characters presence.
 * <p>
 *
 * @param scope Value of scope attribute
 * @param bean DOM element for bean associated to this scope
 * @return Metadata as processed by NS Handler.
 * @throws ComponentDefinitionException if an undeclared prefix is used,
 *           if a namespace handler is unavailable for a resolved prefix,
 *           or if the resolved prefix results as the blueprint namespace.
 */
private ComponentMetadata handleCustomScope(Node scope, Element bean, ComponentMetadata metadata) {
    URI scopeNS = getNamespaceForAttributeValue(scope);
    if (scopeNS != null && !BLUEPRINT_NAMESPACE.equals(scopeNS.toString())) {
        NamespaceHandler nsHandler = getNamespaceHandler(scopeNS);
        ParserContextImpl context = new ParserContextImpl(this, registry, metadata, scope);
        metadata = nsHandler.decorate(scope, metadata, context);
    } else if (scopeNS != null) {
        throw new ComponentDefinitionException("Custom scopes cannot use the blueprint namespace " + scope);
    }
    return metadata;
}
Also used : ComponentDefinitionException(org.osgi.service.blueprint.container.ComponentDefinitionException) NamespaceHandler(org.apache.aries.blueprint.NamespaceHandler) URI(java.net.URI)

Example 19 with NamespaceHandler

use of org.apache.aries.blueprint.NamespaceHandler in project aries by apache.

the class SpringOsgiCompendiumNamespaceHandler method parse.

@Override
public Metadata parse(Element element, ParserContext context) {
    fixDom(element, CM_NAMESPACE);
    NamespaceHandler handler = context.getNamespaceHandler(URI.create(CM_NAMESPACE));
    return handler.parse(element, context);
}
Also used : NamespaceHandler(org.apache.aries.blueprint.NamespaceHandler)

Example 20 with NamespaceHandler

use of org.apache.aries.blueprint.NamespaceHandler in project aries by apache.

the class BlueprintContainerImpl method doRun.

/**
 * This method must be called inside a synchronized block to ensure this method is not run concurrently
 */
private void doRun() {
    try {
        for (; ; ) {
            if (destroyed.get()) {
                return;
            }
            if (bundle.getState() != Bundle.ACTIVE && bundle.getState() != Bundle.STARTING) {
                return;
            }
            if (bundle.getBundleContext() != bundleContext) {
                return;
            }
            LOGGER.debug("Running container for blueprint bundle {}/{} in state {}", getBundle().getSymbolicName(), getBundle().getVersion(), state);
            switch(state) {
                case Unknown:
                    readDirectives();
                    eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.CREATING, getBundle(), getExtenderBundle()));
                    parser = new Parser();
                    parser.parse(pathList);
                    namespaces = parser.getNamespaces();
                    if (additionalNamespaces != null) {
                        namespaces.addAll(additionalNamespaces);
                    }
                    handlerSet = handlers.getNamespaceHandlers(namespaces, getBundle());
                    handlerSet.addListener(this);
                    state = State.WaitForNamespaceHandlers;
                    break;
                case WaitForNamespaceHandlers:
                    {
                        List<String> missing = new ArrayList<String>();
                        List<URI> missingURIs = new ArrayList<URI>();
                        for (URI ns : handlerSet.getNamespaces()) {
                            if (handlerSet.getNamespaceHandler(ns) == null) {
                                missing.add("(&(" + Constants.OBJECTCLASS + "=" + NamespaceHandler.class.getName() + ")(" + NamespaceHandlerRegistryImpl.NAMESPACE + "=" + ns + "))");
                                missingURIs.add(ns);
                            }
                        }
                        if (missing.size() > 0) {
                            LOGGER.info("Blueprint bundle {}/{} is waiting for namespace handlers {}", getBundle().getSymbolicName(), getBundle().getVersion(), missingURIs);
                            eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.GRACE_PERIOD, getBundle(), getExtenderBundle(), missing.toArray(new String[missing.size()])));
                            return;
                        }
                        resetComponentDefinitionRegistry();
                        if (xmlValidation == null || "true".equals(xmlValidation)) {
                            for (URI ns : handlerSet.getNamespaces()) {
                                NamespaceHandler handler = handlerSet.getNamespaceHandler(ns);
                                if (handler instanceof NamespaceHandler2) {
                                    if (((NamespaceHandler2) handler).usePsvi()) {
                                        xmlValidation = "psvi";
                                        break;
                                    }
                                }
                            }
                        }
                        try {
                            if (xmlValidation == null || "true".equals(xmlValidation)) {
                                parser.validate(handlerSet.getSchema(parser.getSchemaLocations()));
                            } else if ("structure".equals(xmlValidation)) {
                                parser.validate(handlerSet.getSchema(parser.getSchemaLocations()), new ValidationHandler());
                            } else if ("psvi".equals(xmlValidation)) {
                                parser.validatePsvi(handlerSet.getSchema(parser.getSchemaLocations()));
                            }
                            parser.populate(handlerSet, componentDefinitionRegistry);
                            state = State.Populated;
                        } catch (MissingNamespaceException e) {
                            // If we found a missing namespace when parsing the schema,
                            // we remain in the current state
                            handlerSet.getNamespaces().add(e.getNamespace());
                        }
                        break;
                    }
                case Populated:
                    getRepository();
                    trackServiceReferences();
                    Runnable r = new Runnable() {

                        public void run() {
                            synchronized (scheduled) {
                                if (destroyed.get()) {
                                    return;
                                }
                                String[] missingDependecies = getMissingDependencies();
                                if (missingDependecies.length == 0) {
                                    return;
                                }
                                Throwable t = new TimeoutException();
                                state = State.Failed;
                                tidyupComponents();
                                LOGGER.error("Unable to start container for blueprint bundle {}/{} due to unresolved dependencies {}", getBundle().getSymbolicName(), getBundle().getVersion(), Arrays.asList(missingDependecies), t);
                                eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.FAILURE, getBundle(), getExtenderBundle(), missingDependecies, t));
                            }
                        }
                    };
                    timeoutFuture = timer.schedule(r, timeout, TimeUnit.MILLISECONDS);
                    state = State.WaitForInitialReferences;
                    break;
                case WaitForInitialReferences:
                    if (waitForDependencies) {
                        String[] missingDependencies = getMissingDependencies();
                        if (missingDependencies.length > 0) {
                            LOGGER.info("Blueprint bundle {}/{} is waiting for dependencies {}", getBundle().getSymbolicName(), getBundle().getVersion(), Arrays.asList(missingDependencies));
                            eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.GRACE_PERIOD, getBundle(), getExtenderBundle(), missingDependencies));
                            return;
                        }
                    }
                    state = State.InitialReferencesSatisfied;
                    break;
                case InitialReferencesSatisfied:
                    processTypeConverters();
                    processProcessors();
                    state = State.WaitForInitialReferences2;
                    break;
                case WaitForInitialReferences2:
                    if (waitForDependencies) {
                        String[] missingDependencies = getMissingDependencies();
                        if (missingDependencies.length > 0) {
                            LOGGER.info("Blueprint bundle {}/{} is waiting for dependencies {}", getBundle().getSymbolicName(), getBundle().getVersion(), Arrays.asList(missingDependencies));
                            eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.GRACE_PERIOD, getBundle(), getExtenderBundle(), missingDependencies));
                            return;
                        }
                    }
                    state = State.Create;
                    break;
                case Create:
                    cancelFutureIfPresent();
                    instantiateEagerComponents();
                    // Register the services after the eager components are ready, as per 121.6
                    registerServices();
                    // Register the BlueprintContainer in the OSGi registry
                    int bs = bundle.getState();
                    if (registration == null && (bs == Bundle.ACTIVE || bs == Bundle.STARTING)) {
                        Properties props = new Properties();
                        props.put(BlueprintConstants.CONTAINER_SYMBOLIC_NAME_PROPERTY, bundle.getSymbolicName());
                        props.put(BlueprintConstants.CONTAINER_VERSION_PROPERTY, JavaUtils.getBundleVersion(bundle));
                        registration = registerService(new String[] { BlueprintContainer.class.getName() }, this, props);
                    }
                    LOGGER.info("Blueprint bundle {}/{} has been started", getBundle().getSymbolicName(), getBundle().getVersion());
                    eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.CREATED, getBundle(), getExtenderBundle()));
                    state = State.Created;
                    break;
                case Created:
                case Failed:
                    return;
            }
        }
    } catch (Throwable t) {
        try {
            state = State.Failed;
            cancelFutureIfPresent();
            tidyupComponents();
            LOGGER.error("Unable to start container for blueprint bundle {}/{}", getBundle().getSymbolicName(), getBundle().getVersion(), t);
            eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.FAILURE, getBundle(), getExtenderBundle(), t));
        } catch (RuntimeException re) {
            LOGGER.debug("Tidying up components failed. ", re);
            throw re;
        }
    }
}
Also used : Properties(java.util.Properties) URI(java.net.URI) HeaderParser(org.apache.aries.blueprint.utils.HeaderParser) Parser(org.apache.aries.blueprint.parser.Parser) NamespaceHandler2(org.apache.aries.blueprint.NamespaceHandler2) NamespaceHandler(org.apache.aries.blueprint.NamespaceHandler) List(java.util.List) ArrayList(java.util.ArrayList) MissingNamespaceException(org.apache.aries.blueprint.namespace.MissingNamespaceException) BlueprintEvent(org.osgi.service.blueprint.container.BlueprintEvent) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

NamespaceHandler (org.apache.aries.blueprint.NamespaceHandler)20 URI (java.net.URI)6 IOException (java.io.IOException)4 Bundle (org.osgi.framework.Bundle)4 URL (java.net.URL)3 ArrayList (java.util.ArrayList)3 Properties (java.util.Properties)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 ComponentMetadata (org.osgi.service.blueprint.reflect.ComponentMetadata)3 SAXException (org.xml.sax.SAXException)3 InputStream (java.io.InputStream)2 MalformedURLException (java.net.MalformedURLException)2 URISyntaxException (java.net.URISyntaxException)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 ConcurrentMap (java.util.concurrent.ConcurrentMap)2 W3C_XML_SCHEMA_NS_URI (javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI)2 XML_NS_URI (javax.xml.XMLConstants.XML_NS_URI)2 ParserContext (org.apache.aries.blueprint.ParserContext)2 SimpleNamespaceHandlerSet (org.apache.aries.blueprint.container.SimpleNamespaceHandlerSet)2