Example usage for org.springframework.beans.factory.xml NamespaceHandler parse

List of usage examples for org.springframework.beans.factory.xml NamespaceHandler parse

Introduction

In this page you can find the example usage for org.springframework.beans.factory.xml NamespaceHandler parse.

Prototype

@Nullable
BeanDefinition parse(Element element, ParserContext parserContext);

Source Link

Document

Parse the specified Element and register any resulting BeanDefinition BeanDefinitions with the org.springframework.beans.factory.support.BeanDefinitionRegistry that is embedded in the supplied ParserContext .

Usage

From source file:org.jboss.windup.config.spring.namespace.java.SpringNamespaceHandlerUtil.java

public static BeanDefinition resolveBeanDefinition(BeanDefinition beanDef, Element element,
        ParserContext context) {/* w  w  w . ja  v  a  2 s .  com*/
    BeanDefinitionParserDelegate delegate = context.getDelegate();
    String namespace = element.getNamespaceURI();

    // check to see whether it is the default Spring bean decorator...
    if (StringUtils.equals(namespace, BeanDefinitionParserDelegate.BEANS_NAMESPACE_URI)) {
        BeanDefinitionHolder holder = delegate.parseBeanDefinitionElement(element, beanDef);
        return holder.getBeanDefinition();
    }

    // otherwise, see if it is supported based on our namespace resolver...
    NamespaceHandler namespaceHandler = delegate.getReaderContext().getNamespaceHandlerResolver()
            .resolve(namespace);
    if (namespaceHandler == null) {
        throw new FatalBeanException("Unable to find parser for bean with namespace: " + namespace);
    }

    return namespaceHandler.parse(element, new ParserContext(delegate.getReaderContext(), delegate, beanDef));
}

From source file:edu.internet2.middleware.shibboleth.common.config.SpringConfigurationUtils.java

/**
 * Creates a {@link BeanDefinition} from a custom element.
 * //from   ww w  .  j  a  v  a  2s  . c  o m
 * @param element configuration element
 * @param parserContext currently parser context
 * 
 * @return the bean definition
 */
private static BeanDefinition createBeanDefinition(Element element, ParserContext parserContext) {
    BeanDefinitionParserDelegate delegate = parserContext.getDelegate();
    String namespaceUri = element.getNamespaceURI();

    if (XMLHelper.hasXSIType(element)) {
        namespaceUri = XMLHelper.getXSIType(element).getNamespaceURI();
    }

    NamespaceHandler handler = delegate.getReaderContext().getNamespaceHandlerResolver().resolve(namespaceUri);
    if (handler == null) {
        log.error("Unable to locate NamespaceHandler for namespace [" + namespaceUri + "]");
        return null;
    }
    return handler.parse(element, new ParserContext(delegate.getReaderContext(), delegate));
}

From source file:com.mtgi.analytics.aop.config.v11.BtPersisterChainBeanDefinitionParser.java

@Override
@SuppressWarnings("unchecked")
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {

    //propagate shared template factory into sub-components if necessary.  this would not be
    //necessary if parserContext gave us access to the entire component stack instead of just the
    //top.  In that case, deeply nested children could search up the stack until they found
    //the template.  perhaps a future version of the Spring API will support this.
    DefaultListableBeanFactory template = findEnclosingTemplateFactory(parserContext);
    if (template != null)
        parserContext.pushContainingComponent(new TemplateComponentDefinition(element.getNodeName(),
                parserContext.extractSource(element), template));

    try {//from w w w. ja  v a  2s  .c  om
        //parse delegate persister definitions
        ManagedList persisters = new ManagedList();
        persisters.setSource(element);

        NodeList nodes = element.getChildNodes();
        for (int i = 0; i < nodes.getLength(); ++i) {
            Node node = nodes.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                String namespaceUri = node.getNamespaceURI();
                NamespaceHandler handler = parserContext.getReaderContext().getNamespaceHandlerResolver()
                        .resolve(namespaceUri);
                Object def = handler == null
                        ? parserContext.getDelegate().parsePropertySubElement((Element) node,
                                builder.getRawBeanDefinition())
                        : handler.parse((Element) node, parserContext);
                persisters.add(def);
            }
        }
        builder.addPropertyValue("delegates", persisters);
    } finally {
        if (template != null)
            parserContext.popContainingComponent();
    }

    //register persister implementation with parent.
    if (parserContext.isNested()) {
        AbstractBeanDefinition def = builder.getBeanDefinition();
        String id = element.hasAttribute("id") ? element.getAttribute("id")
                : parserContext.getReaderContext().generateBeanName(def);
        BeanDefinitionHolder holder = new BeanDefinitionHolder(def, id);
        BtManagerBeanDefinitionParser.registerNestedBean(holder, "persister", parserContext);
    }
}

From source file:com.mtgi.analytics.aop.config.v11.BtManagerBeanDefinitionParser.java

@Override
protected void transform(ConfigurableListableBeanFactory factory, BeanDefinition template, Element element,
        ParserContext parserContext) {//  w  ww  .  j  av  a 2  s .  c o m

    ManagerComponentDefinition def = (ManagerComponentDefinition) parserContext.getContainingComponent();

    String managerId = overrideAttribute(ATT_ID, template, element);
    if (managerId == null)
        template.setAttribute(ATT_ID, managerId = "defaultTrackingManager");

    if ("false".equals(element.getAttribute(ATT_ENABLED))) {
        //manager is disabled.  replace definition with dummy instance.
        template.setBeanClassName(DisabledBehaviorTrackingManager.class.getName());
        //clear properties and attributes.
        for (String att : template.attributeNames())
            if (!ATT_ID.equals(att))
                template.removeAttribute(att);
        template.getPropertyValues().clear();
        //terminate immediately, do not parse any nested definitions (persisters, AOP config, context beans, etc)
        return;
    }

    overrideProperty(ATT_APPLICATION, template, element, false);
    overrideProperty(ATT_FLUSH_THRESHOLD, template, element, false);

    //wake up MBeanExporter if we're going to be doing MBean registration.
    if ("true".equalsIgnoreCase(element.getAttribute(ATT_REGISTER_MBEANS))) {
        AbstractBeanDefinition exporter = (AbstractBeanDefinition) factory
                .getBeanDefinition(CONFIG_MBEAN_EXPORTER);
        exporter.setLazyInit(false);

        //append manager ID to mbean name, in case of multiple managers in a single application.
        BeanDefinition naming = factory.getBeanDefinition(CONFIG_NAMING_STRATEGY);
        naming.getPropertyValues().addPropertyValue("value", managerId);
    }

    //prefer references to beans in the parent factory if they've been specified
    if (element.hasAttribute(ATT_MBEAN_SERVER))
        factory.registerAlias(element.getAttribute(ATT_MBEAN_SERVER), CONFIG_MBEAN_SERVER);

    if (element.hasAttribute(ATT_SCHEDULER))
        factory.registerAlias(element.getAttribute(ATT_SCHEDULER), CONFIG_SCHEDULER);

    if (element.hasAttribute(ATT_TASK_EXECUTOR))
        factory.registerAlias(element.getAttribute(ATT_TASK_EXECUTOR), CONFIG_EXECUTOR);

    //make note of external persister element so that we don't activate log rotation.
    if (element.hasAttribute(ATT_PERSISTER)) {
        def.addNestedProperty(ATT_PERSISTER);
        MutablePropertyValues props = template.getPropertyValues();
        props.removePropertyValue(ATT_PERSISTER);
        props.addPropertyValue(ATT_PERSISTER, new RuntimeBeanReference(element.getAttribute(ATT_PERSISTER)));
    }

    if (element.hasAttribute(ATT_SESSION_CONTEXT)) {
        //override default session context with reference
        def.addNestedProperty("sessionContext");
        factory.registerAlias(element.getAttribute(ATT_SESSION_CONTEXT), CONFIG_SESSION_CONTEXT);
    }

    //handle AOP configuration if needed
    if (element.hasAttribute(ATT_METHOD_EXPRESSION)) {
        //activate global AOP proxying if it hasn't already been done (borrowed logic from AopNamespaceHandler / config element parser)
        activateAopProxies(parserContext, element);

        //register pointcut definition for the provided expression.
        RootBeanDefinition pointcut = new RootBeanDefinition(AspectJExpressionPointcut.class);
        //rely on deprecated method to maintain spring 2.0 support
        pointcut.setSingleton(false);
        pointcut.setSynthetic(true);
        pointcut.getPropertyValues().addPropertyValue("expression",
                element.getAttribute(ATT_METHOD_EXPRESSION));

        //create implicit pointcut advice bean.
        RootBeanDefinition advice = new RootBeanDefinition(BehaviorTrackingAdvice.class);
        advice.getPropertyValues().addPropertyValue("trackingManager", new RuntimeBeanReference(managerId));

        //register advice, pointcut, and advisor entry to bind the two together.
        XmlReaderContext ctx = parserContext.getReaderContext();
        String pointcutId = ctx.registerWithGeneratedName(pointcut);
        String adviceId = ctx.registerWithGeneratedName(advice);

        RootBeanDefinition advisorDefinition = new RootBeanDefinition(DefaultBeanFactoryPointcutAdvisor.class);
        advisorDefinition.getPropertyValues().addPropertyValue("adviceBeanName",
                new RuntimeBeanNameReference(adviceId));
        advisorDefinition.getPropertyValues().addPropertyValue("pointcut",
                new RuntimeBeanReference(pointcutId));
        ctx.registerWithGeneratedName(advisorDefinition);
    }

    //configure flush trigger and job to be globally unique based on manager name.
    BeanDefinition flushTrigger = factory.getBeanDefinition("com.mtgi.analytics.btFlushTrigger");
    SchedulerActivationPostProcessor.configureTriggerDefinition(flushTrigger,
            element.getAttribute(ATT_FLUSH_SCHEDULE), managerId + "_flush");

    //set up a post-processor to register the flush job with the selected scheduler instance.  the job and scheduler
    //come from the template factory, but the post-processor runs when the currently-parsing factory is finished.
    SchedulerActivationPostProcessor.registerPostProcessor(parserContext, factory, CONFIG_SCHEDULER,
            CONFIG_NAMESPACE + ".btFlushTrigger");

    //ManagerComponentDefinition is a flag to nested parsers that they should push their parsed bean definitions into
    //the manager bean definition.  for example, see BtPersisterBeanDefinitionParser.
    //descend on nested child nodes to pick up persister and session context configuration
    NodeList children = element.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            String namespaceUri = node.getNamespaceURI();
            NamespaceHandler handler = parserContext.getReaderContext().getNamespaceHandlerResolver()
                    .resolve(namespaceUri);
            ParserContext nestedCtx = new ParserContext(parserContext.getReaderContext(),
                    parserContext.getDelegate(), template);
            nestedCtx.pushContainingComponent(def);
            handler.parse((Element) node, nestedCtx);
        }
    }

    if (!def.nestedProperties.contains(ATT_PERSISTER)) {
        //no persister registered.  schedule default log rotation trigger.
        BtXmlPersisterBeanDefinitionParser.configureLogRotation(parserContext, factory, null);
    }

    if (!def.nestedProperties.contains("sessionContext")) {
        //custom session context not registered.  select appropriate default class
        //depending on whether we are in a web context or not.
        if (parserContext.getReaderContext().getReader().getResourceLoader() instanceof WebApplicationContext) {
            BeanDefinition scDef = factory.getBeanDefinition(CONFIG_SESSION_CONTEXT);
            scDef.setBeanClassName(SpringSessionContext.class.getName());
        }
    }
}

From source file:org.mule.config.spring.MuleHierarchicalBeanDefinitionParserDelegate.java

public BeanDefinition parseCustomElement(Element element, BeanDefinition parent) {
    if (logger.isDebugEnabled()) {
        logger.debug("parsing: " + SpringXMLUtils.elementToString(element));
    }/* w w  w  . ja v  a  2s  .  c o  m*/
    if (SpringXMLUtils.isBeansNamespace(element)) {
        return handleSpringElements(element, parent);
    } else {
        String namespaceUri = element.getNamespaceURI();
        NamespaceHandler handler = getReaderContext().getNamespaceHandlerResolver().resolve(namespaceUri);
        if (handler == null) {
            getReaderContext().error("Unable to locate NamespaceHandler for namespace [" + namespaceUri + "]",
                    element);
            return null;
        }

        boolean noRecurse = false;
        boolean forceRecurse = false;
        BeanDefinition finalChild;

        do {
            ParserContext parserContext = new ParserContext(getReaderContext(), this, parent);
            finalChild = handler.parse(element, parserContext);
            registerBean(element, finalChild);
            noRecurse = noRecurse || testFlag(finalChild, MULE_NO_RECURSE);
            forceRecurse = forceRecurse || testFlag(finalChild, MULE_FORCE_RECURSE);
        } while (null != finalChild && testFlag(finalChild, MULE_REPEAT_PARSE));

        // Only iterate and parse child mule name-spaced elements. Spring does not do
        // hierarchical parsing by default so we need to maintain this behavior
        // for non-mule elements to ensure that we don't break the parsing of any
        // other custom name-spaces e.g spring-jee.

        // We also avoid parsing inside elements that have constructed a factory bean
        // because that means we're dealing with (something like) ChildMapDefinitionParser,
        // which handles iteration internally (this is a hack needed because Spring doesn't
        // expose the DP for "<spring:entry>" elements directly).

        boolean isRecurse;
        if (noRecurse) {
            // no recursion takes precedence, as recursion is set by default
            isRecurse = false;
        } else {
            if (forceRecurse) {
                isRecurse = true;
            } else {
                // default behaviour if no control specified
                isRecurse = SpringXMLUtils.isMuleNamespace(element);
            }
        }

        if (isRecurse) {
            NodeList list = element.getChildNodes();
            for (int i = 0; i < list.getLength(); i++) {
                if (list.item(i) instanceof Element) {
                    parseCustomElement((Element) list.item(i), finalChild);
                }
            }
        }

        // If a parser requests post-processing we call again after children called

        if (testFlag(finalChild, MULE_POST_CHILDREN)) {
            ParserContext parserContext = new ParserContext(getReaderContext(), this, parent);
            finalChild = handler.parse(element, parserContext);
        }

        return finalChild;
    }
}

From source file:org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.java

@Nullable
public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
    String namespaceUri = getNamespaceURI(ele);
    if (namespaceUri == null) {
        return null;
    }/*w  w w  . j  a va  2 s .c o m*/
    NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
    if (handler == null) {
        error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
        return null;
    }
    return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
}