Search in sources :

Example 66 with ManagedMap

use of org.springframework.beans.factory.support.ManagedMap in project spring-security-oauth by spring-projects.

the class AuthorizationServerBeanDefinitionParser method parseEndpointAndReturnFilter.

@Override
protected AbstractBeanDefinition parseEndpointAndReturnFilter(Element element, ParserContext parserContext, String tokenServicesRef, String serializerRef) {
    String clientDetailsRef = element.getAttribute("client-details-service-ref");
    String oAuth2RequestFactoryRef = element.getAttribute("authorization-request-manager-ref");
    String tokenEndpointUrl = element.getAttribute("token-endpoint-url");
    String checkTokenUrl = element.getAttribute("check-token-endpoint-url");
    String enableCheckToken = element.getAttribute("check-token-enabled");
    String authorizationEndpointUrl = element.getAttribute("authorization-endpoint-url");
    String tokenGranterRef = element.getAttribute("token-granter-ref");
    String redirectStrategyRef = element.getAttribute("redirect-strategy-ref");
    String userApprovalHandlerRef = element.getAttribute("user-approval-handler-ref");
    String approvalPage = element.getAttribute("user-approval-page");
    String errorPage = element.getAttribute("error-page");
    String approvalParameter = element.getAttribute("approval-parameter-name");
    String redirectResolverRef = element.getAttribute("redirect-resolver-ref");
    String oAuth2RequestValidatorRef = element.getAttribute("request-validator-ref");
    // Create a bean definition speculatively for the auth endpoint
    BeanDefinitionBuilder authorizationEndpointBean = BeanDefinitionBuilder.rootBeanDefinition(AuthorizationEndpoint.class);
    if (!StringUtils.hasText(clientDetailsRef)) {
        parserContext.getReaderContext().error("ClientDetailsService must be provided", element);
        return null;
    }
    if (!StringUtils.hasText(oAuth2RequestValidatorRef)) {
        oAuth2RequestValidatorRef = "defaultOAuth2RequestValidator";
        BeanDefinitionBuilder oAuth2RequestValidator = BeanDefinitionBuilder.rootBeanDefinition(DefaultOAuth2RequestValidator.class);
        parserContext.getRegistry().registerBeanDefinition(oAuth2RequestValidatorRef, oAuth2RequestValidator.getBeanDefinition());
    }
    authorizationEndpointBean.addPropertyReference("oAuth2RequestValidator", oAuth2RequestValidatorRef);
    if (!StringUtils.hasText(oAuth2RequestFactoryRef)) {
        oAuth2RequestFactoryRef = "oAuth2AuthorizationRequestManager";
        BeanDefinitionBuilder oAuth2RequestManager = BeanDefinitionBuilder.rootBeanDefinition(DefaultOAuth2RequestFactory.class);
        oAuth2RequestManager.addConstructorArgReference(clientDetailsRef);
        parserContext.getRegistry().registerBeanDefinition(oAuth2RequestFactoryRef, oAuth2RequestManager.getBeanDefinition());
    }
    ManagedList<BeanMetadataElement> tokenGranters = null;
    if (!StringUtils.hasText(tokenGranterRef)) {
        tokenGranterRef = "oauth2TokenGranter";
        BeanDefinitionBuilder tokenGranterBean = BeanDefinitionBuilder.rootBeanDefinition(CompositeTokenGranter.class);
        parserContext.getRegistry().registerBeanDefinition(tokenGranterRef, tokenGranterBean.getBeanDefinition());
        tokenGranters = new ManagedList<BeanMetadataElement>();
        tokenGranterBean.addConstructorArgValue(tokenGranters);
    }
    authorizationEndpointBean.addPropertyReference("tokenGranter", tokenGranterRef);
    boolean registerAuthorizationEndpoint = false;
    Element authorizationCodeElement = DomUtils.getChildElementByTagName(element, "authorization-code");
    if (authorizationCodeElement != null && !"true".equalsIgnoreCase(authorizationCodeElement.getAttribute("disabled"))) {
        // authorization code grant configuration.
        String authorizationCodeServices = authorizationCodeElement.getAttribute("authorization-code-services-ref");
        String clientTokenCacheRef = authorizationCodeElement.getAttribute("client-token-cache-ref");
        BeanDefinitionBuilder authorizationCodeTokenGranterBean = BeanDefinitionBuilder.rootBeanDefinition(AuthorizationCodeTokenGranter.class);
        if (StringUtils.hasText(tokenServicesRef)) {
            authorizationCodeTokenGranterBean.addConstructorArgReference(tokenServicesRef);
        }
        if (!StringUtils.hasText(authorizationCodeServices)) {
            authorizationCodeServices = "oauth2AuthorizationCodeServices";
            BeanDefinitionBuilder authorizationCodeServicesBean = BeanDefinitionBuilder.rootBeanDefinition(InMemoryAuthorizationCodeServices.class);
            parserContext.getRegistry().registerBeanDefinition(authorizationCodeServices, authorizationCodeServicesBean.getBeanDefinition());
        }
        authorizationEndpointBean.addPropertyReference("authorizationCodeServices", authorizationCodeServices);
        authorizationCodeTokenGranterBean.addConstructorArgReference(authorizationCodeServices);
        authorizationCodeTokenGranterBean.addConstructorArgReference(clientDetailsRef);
        authorizationCodeTokenGranterBean.addConstructorArgReference(oAuth2RequestFactoryRef);
        if (StringUtils.hasText(clientTokenCacheRef)) {
            authorizationEndpointBean.addPropertyReference("clientTokenCache", clientTokenCacheRef);
        }
        if (StringUtils.hasText(oAuth2RequestFactoryRef)) {
            authorizationEndpointBean.addPropertyReference("oAuth2RequestFactory", oAuth2RequestFactoryRef);
        }
        if (tokenGranters != null) {
            tokenGranters.add(authorizationCodeTokenGranterBean.getBeanDefinition());
        }
        // end authorization code provider configuration.
        registerAuthorizationEndpoint = true;
    }
    if (tokenGranters != null) {
        Element refreshTokenElement = DomUtils.getChildElementByTagName(element, "refresh-token");
        if (refreshTokenElement != null && !"true".equalsIgnoreCase(refreshTokenElement.getAttribute("disabled"))) {
            BeanDefinitionBuilder refreshTokenGranterBean = BeanDefinitionBuilder.rootBeanDefinition(RefreshTokenGranter.class);
            refreshTokenGranterBean.addConstructorArgReference(tokenServicesRef);
            refreshTokenGranterBean.addConstructorArgReference(clientDetailsRef);
            refreshTokenGranterBean.addConstructorArgReference(oAuth2RequestFactoryRef);
            tokenGranters.add(refreshTokenGranterBean.getBeanDefinition());
        }
        Element implicitElement = DomUtils.getChildElementByTagName(element, "implicit");
        if (implicitElement != null && !"true".equalsIgnoreCase(implicitElement.getAttribute("disabled"))) {
            BeanDefinitionBuilder implicitGranterBean = BeanDefinitionBuilder.rootBeanDefinition(ImplicitTokenGranter.class);
            implicitGranterBean.addConstructorArgReference(tokenServicesRef);
            implicitGranterBean.addConstructorArgReference(clientDetailsRef);
            implicitGranterBean.addConstructorArgReference(oAuth2RequestFactoryRef);
            tokenGranters.add(implicitGranterBean.getBeanDefinition());
            registerAuthorizationEndpoint = true;
        }
        Element clientCredentialsElement = DomUtils.getChildElementByTagName(element, "client-credentials");
        if (clientCredentialsElement != null && !"true".equalsIgnoreCase(clientCredentialsElement.getAttribute("disabled"))) {
            BeanDefinitionBuilder clientCredentialsGranterBean = BeanDefinitionBuilder.rootBeanDefinition(ClientCredentialsTokenGranter.class);
            clientCredentialsGranterBean.addConstructorArgReference(tokenServicesRef);
            clientCredentialsGranterBean.addConstructorArgReference(clientDetailsRef);
            clientCredentialsGranterBean.addConstructorArgReference(oAuth2RequestFactoryRef);
            tokenGranters.add(clientCredentialsGranterBean.getBeanDefinition());
        }
        Element clientPasswordElement = DomUtils.getChildElementByTagName(element, "password");
        if (clientPasswordElement != null && !"true".equalsIgnoreCase(clientPasswordElement.getAttribute("disabled"))) {
            BeanDefinitionBuilder clientPasswordTokenGranter = BeanDefinitionBuilder.rootBeanDefinition(ResourceOwnerPasswordTokenGranter.class);
            String authenticationManagerRef = clientPasswordElement.getAttribute("authentication-manager-ref");
            if (!StringUtils.hasText(authenticationManagerRef)) {
                authenticationManagerRef = BeanIds.AUTHENTICATION_MANAGER;
            }
            clientPasswordTokenGranter.addConstructorArgReference(authenticationManagerRef);
            clientPasswordTokenGranter.addConstructorArgReference(tokenServicesRef);
            clientPasswordTokenGranter.addConstructorArgReference(clientDetailsRef);
            clientPasswordTokenGranter.addConstructorArgReference(oAuth2RequestFactoryRef);
            tokenGranters.add(clientPasswordTokenGranter.getBeanDefinition());
        }
        List<Element> customGrantElements = DomUtils.getChildElementsByTagName(element, "custom-grant");
        for (Element customGrantElement : customGrantElements) {
            if (!"true".equalsIgnoreCase(customGrantElement.getAttribute("disabled"))) {
                String customGranterRef = customGrantElement.getAttribute("token-granter-ref");
                tokenGranters.add(new RuntimeBeanReference(customGranterRef));
            }
        }
    }
    if (registerAuthorizationEndpoint) {
        BeanDefinitionBuilder approvalEndpointBean = BeanDefinitionBuilder.rootBeanDefinition(WhitelabelApprovalEndpoint.class);
        parserContext.getRegistry().registerBeanDefinition("oauth2ApprovalEndpoint", approvalEndpointBean.getBeanDefinition());
        if (!StringUtils.hasText(clientDetailsRef)) {
            parserContext.getReaderContext().error("A client details service is mandatory", element);
        }
        if (StringUtils.hasText(redirectStrategyRef)) {
            authorizationEndpointBean.addPropertyReference("redirectStrategy", redirectStrategyRef);
        }
        if (StringUtils.hasText(userApprovalHandlerRef)) {
            authorizationEndpointBean.addPropertyReference("userApprovalHandler", userApprovalHandlerRef);
        }
        authorizationEndpointBean.addPropertyReference("clientDetailsService", clientDetailsRef);
        if (StringUtils.hasText(redirectResolverRef)) {
            authorizationEndpointBean.addPropertyReference("redirectResolver", redirectResolverRef);
        }
        if (StringUtils.hasText(approvalPage)) {
            authorizationEndpointBean.addPropertyValue("userApprovalPage", approvalPage);
        }
        if (StringUtils.hasText(errorPage)) {
            authorizationEndpointBean.addPropertyValue("errorPage", errorPage);
        }
        parserContext.getRegistry().registerBeanDefinition("oauth2AuthorizationEndpoint", authorizationEndpointBean.getBeanDefinition());
    }
    // configure the token endpoint
    BeanDefinitionBuilder tokenEndpointBean = BeanDefinitionBuilder.rootBeanDefinition(TokenEndpoint.class);
    tokenEndpointBean.addPropertyReference("clientDetailsService", clientDetailsRef);
    tokenEndpointBean.addPropertyReference("tokenGranter", tokenGranterRef);
    authorizationEndpointBean.addPropertyReference("oAuth2RequestValidator", oAuth2RequestValidatorRef);
    parserContext.getRegistry().registerBeanDefinition("oauth2TokenEndpoint", tokenEndpointBean.getBeanDefinition());
    if (StringUtils.hasText(oAuth2RequestFactoryRef)) {
        tokenEndpointBean.addPropertyReference("oAuth2RequestFactory", oAuth2RequestFactoryRef);
    }
    if (StringUtils.hasText(oAuth2RequestValidatorRef)) {
        tokenEndpointBean.addPropertyReference("oAuth2RequestValidator", oAuth2RequestValidatorRef);
    }
    // Register a handler mapping that can detect the auth server endpoints
    BeanDefinitionBuilder handlerMappingBean = BeanDefinitionBuilder.rootBeanDefinition(FrameworkEndpointHandlerMapping.class);
    ManagedMap<String, TypedStringValue> mappings = new ManagedMap<String, TypedStringValue>();
    if (StringUtils.hasText(tokenEndpointUrl) || StringUtils.hasText(authorizationEndpointUrl)) {
        if (StringUtils.hasText(tokenEndpointUrl)) {
            mappings.put("/oauth/token", new TypedStringValue(tokenEndpointUrl, String.class));
        }
        if (StringUtils.hasText(authorizationEndpointUrl)) {
            mappings.put("/oauth/authorize", new TypedStringValue(authorizationEndpointUrl, String.class));
        }
        if (StringUtils.hasText(approvalPage)) {
            mappings.put("/oauth/confirm_access", new TypedStringValue(approvalPage, String.class));
        }
    }
    if (StringUtils.hasText(enableCheckToken) && enableCheckToken.equals("true")) {
        // configure the check token endpoint
        BeanDefinitionBuilder checkTokenEndpointBean = BeanDefinitionBuilder.rootBeanDefinition(CheckTokenEndpoint.class);
        checkTokenEndpointBean.addConstructorArgReference(tokenServicesRef);
        parserContext.getRegistry().registerBeanDefinition("oauth2CheckTokenEndpoint", checkTokenEndpointBean.getBeanDefinition());
        if (StringUtils.hasText(checkTokenUrl)) {
            mappings.put("/oauth/check_token", new TypedStringValue(checkTokenUrl, String.class));
        }
    }
    if (!mappings.isEmpty()) {
        handlerMappingBean.addPropertyValue("mappings", mappings);
    }
    if (StringUtils.hasText(approvalParameter) && registerAuthorizationEndpoint) {
        if (!StringUtils.hasText(userApprovalHandlerRef)) {
            BeanDefinitionBuilder userApprovalHandler = BeanDefinitionBuilder.rootBeanDefinition(DefaultUserApprovalHandler.class);
            userApprovalHandler.addPropertyValue("approvalParameter", new TypedStringValue(approvalParameter, String.class));
            authorizationEndpointBean.addPropertyValue("userApprovalHandler", userApprovalHandler.getBeanDefinition());
        }
        handlerMappingBean.addPropertyValue("approvalParameter", approvalParameter);
    }
    parserContext.getRegistry().registerBeanDefinition("oauth2HandlerMapping", handlerMappingBean.getBeanDefinition());
    // We aren't defining a filter...
    return null;
}
Also used : BeanMetadataElement(org.springframework.beans.BeanMetadataElement) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) BeanMetadataElement(org.springframework.beans.BeanMetadataElement) Element(org.w3c.dom.Element) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) ManagedMap(org.springframework.beans.factory.support.ManagedMap)

Example 67 with ManagedMap

use of org.springframework.beans.factory.support.ManagedMap in project dubbo by alibaba.

the class DubboBeanDefinitionParser method parse.

@SuppressWarnings("unchecked")
private static RootBeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) {
    RootBeanDefinition beanDefinition = new RootBeanDefinition();
    beanDefinition.setBeanClass(beanClass);
    beanDefinition.setLazyInit(false);
    String id = resolveAttribute(element, "id", parserContext);
    if (StringUtils.isEmpty(id) && required) {
        String generatedBeanName = resolveAttribute(element, "name", parserContext);
        if (StringUtils.isEmpty(generatedBeanName)) {
            if (ProtocolConfig.class.equals(beanClass)) {
                generatedBeanName = "dubbo";
            } else {
                generatedBeanName = resolveAttribute(element, "interface", parserContext);
            }
        }
        if (StringUtils.isEmpty(generatedBeanName)) {
            generatedBeanName = beanClass.getName();
        }
        id = generatedBeanName;
        int counter = 2;
        while (parserContext.getRegistry().containsBeanDefinition(id)) {
            id = generatedBeanName + (counter++);
        }
    }
    if (StringUtils.isNotEmpty(id)) {
        if (parserContext.getRegistry().containsBeanDefinition(id)) {
            throw new IllegalStateException("Duplicate spring bean id " + id);
        }
        parserContext.getRegistry().registerBeanDefinition(id, beanDefinition);
        beanDefinition.getPropertyValues().addPropertyValue("id", id);
    }
    if (ProtocolConfig.class.equals(beanClass)) {
        for (String name : parserContext.getRegistry().getBeanDefinitionNames()) {
            BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(name);
            PropertyValue property = definition.getPropertyValues().getPropertyValue("protocol");
            if (property != null) {
                Object value = property.getValue();
                if (value instanceof ProtocolConfig && id.equals(((ProtocolConfig) value).getName())) {
                    definition.getPropertyValues().addPropertyValue("protocol", new RuntimeBeanReference(id));
                }
            }
        }
    } else if (ServiceBean.class.equals(beanClass)) {
        String className = resolveAttribute(element, "class", parserContext);
        if (StringUtils.isNotEmpty(className)) {
            RootBeanDefinition classDefinition = new RootBeanDefinition();
            classDefinition.setBeanClass(ReflectUtils.forName(className));
            classDefinition.setLazyInit(false);
            parseProperties(element.getChildNodes(), classDefinition, parserContext);
            beanDefinition.getPropertyValues().addPropertyValue("ref", new BeanDefinitionHolder(classDefinition, id + "Impl"));
        }
    } else if (ProviderConfig.class.equals(beanClass)) {
        parseNested(element, parserContext, ServiceBean.class, true, "service", "provider", id, beanDefinition);
    } else if (ConsumerConfig.class.equals(beanClass)) {
        parseNested(element, parserContext, ReferenceBean.class, false, "reference", "consumer", id, beanDefinition);
    }
    Set<String> props = new HashSet<>();
    ManagedMap parameters = null;
    for (Method setter : beanClass.getMethods()) {
        String name = setter.getName();
        if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(setter.getModifiers()) && setter.getParameterTypes().length == 1) {
            Class<?> type = setter.getParameterTypes()[0];
            String beanProperty = name.substring(3, 4).toLowerCase() + name.substring(4);
            String property = StringUtils.camelToSplitName(beanProperty, "-");
            props.add(property);
            // check the setter/getter whether match
            Method getter = null;
            try {
                getter = beanClass.getMethod("get" + name.substring(3), new Class<?>[0]);
            } catch (NoSuchMethodException e) {
                try {
                    getter = beanClass.getMethod("is" + name.substring(3), new Class<?>[0]);
                } catch (NoSuchMethodException e2) {
                // ignore, there is no need any log here since some class implement the interface: EnvironmentAware,
                // ApplicationAware, etc. They only have setter method, otherwise will cause the error log during application start up.
                }
            }
            if (getter == null || !Modifier.isPublic(getter.getModifiers()) || !type.equals(getter.getReturnType())) {
                continue;
            }
            if ("parameters".equals(property)) {
                parameters = parseParameters(element.getChildNodes(), beanDefinition, parserContext);
            } else if ("methods".equals(property)) {
                parseMethods(id, element.getChildNodes(), beanDefinition, parserContext);
            } else if ("arguments".equals(property)) {
                parseArguments(id, element.getChildNodes(), beanDefinition, parserContext);
            } else {
                String value = resolveAttribute(element, property, parserContext);
                if (value != null) {
                    value = value.trim();
                    if (value.length() > 0) {
                        if ("registry".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) {
                            RegistryConfig registryConfig = new RegistryConfig();
                            registryConfig.setAddress(RegistryConfig.NO_AVAILABLE);
                            beanDefinition.getPropertyValues().addPropertyValue(beanProperty, registryConfig);
                        } else if ("provider".equals(property) || "registry".equals(property) || ("protocol".equals(property) && AbstractServiceConfig.class.isAssignableFrom(beanClass))) {
                            /**
                             * For 'provider' 'protocol' 'registry', keep literal value (should be id/name) and set the value to 'registryIds' 'providerIds' protocolIds'
                             * The following process should make sure each id refers to the corresponding instance, here's how to find the instance for different use cases:
                             * 1. Spring, check existing bean by id, see{@link ServiceBean#afterPropertiesSet()}; then try to use id to find configs defined in remote Config Center
                             * 2. API, directly use id to find configs defined in remote Config Center; if all config instances are defined locally, please use {@link ServiceConfig#setRegistries(List)}
                             */
                            beanDefinition.getPropertyValues().addPropertyValue(beanProperty + "Ids", value);
                        } else {
                            Object reference;
                            if (isPrimitive(type)) {
                                if ("async".equals(property) && "false".equals(value) || "timeout".equals(property) && "0".equals(value) || "delay".equals(property) && "0".equals(value) || "version".equals(property) && "0.0.0".equals(value) || "stat".equals(property) && "-1".equals(value) || "reliable".equals(property) && "false".equals(value)) {
                                    // backward compatibility for the default value in old version's xsd
                                    value = null;
                                }
                                reference = value;
                            } else if (ONRETURN.equals(property) || ONTHROW.equals(property) || ONINVOKE.equals(property)) {
                                int index = value.lastIndexOf(".");
                                String ref = value.substring(0, index);
                                String method = value.substring(index + 1);
                                reference = new RuntimeBeanReference(ref);
                                beanDefinition.getPropertyValues().addPropertyValue(property + METHOD, method);
                            } else {
                                if ("ref".equals(property) && parserContext.getRegistry().containsBeanDefinition(value)) {
                                    BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value);
                                    if (!refBean.isSingleton()) {
                                        throw new IllegalStateException("The exported service ref " + value + " must be singleton! Please set the " + value + " bean scope to singleton, eg: <bean id=\"" + value + "\" scope=\"singleton\" ...>");
                                    }
                                }
                                reference = new RuntimeBeanReference(value);
                            }
                            beanDefinition.getPropertyValues().addPropertyValue(beanProperty, reference);
                        }
                    }
                }
            }
        }
    }
    NamedNodeMap attributes = element.getAttributes();
    int len = attributes.getLength();
    for (int i = 0; i < len; i++) {
        Node node = attributes.item(i);
        String name = node.getLocalName();
        if (!props.contains(name)) {
            if (parameters == null) {
                parameters = new ManagedMap();
            }
            String value = node.getNodeValue();
            parameters.put(name, new TypedStringValue(value, String.class));
        }
    }
    if (parameters != null) {
        beanDefinition.getPropertyValues().addPropertyValue("parameters", parameters);
    }
    return beanDefinition;
}
Also used : RegistryConfig(org.apache.dubbo.config.RegistryConfig) NamedNodeMap(org.w3c.dom.NamedNodeMap) Node(org.w3c.dom.Node) PropertyValue(org.springframework.beans.PropertyValue) Method(java.lang.reflect.Method) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) AbstractBeanDefinition(org.springframework.beans.factory.support.AbstractBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) ServiceBean(org.apache.dubbo.config.spring.ServiceBean) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) ReferenceBean(org.apache.dubbo.config.spring.ReferenceBean) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) ConsumerConfig(org.apache.dubbo.config.ConsumerConfig) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue) ProtocolConfig(org.apache.dubbo.config.ProtocolConfig) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) ManagedMap(org.springframework.beans.factory.support.ManagedMap) HashSet(java.util.HashSet)

Example 68 with ManagedMap

use of org.springframework.beans.factory.support.ManagedMap in project droolsjbpm-integration by kiegroup.

the class KSessionDefinitionParser method parseBatch.

private void parseBatch(ParserContext parserContext, BeanDefinitionBuilder factory, Element batch) {
    if (batch != null) {
        // we know there can only ever be one
        ManagedList children = new ManagedList();
        for (int i = 0, length = batch.getChildNodes().getLength(); i < length; i++) {
            Node n = batch.getChildNodes().item(i);
            if (n instanceof Element) {
                Element e = (Element) n;
                BeanDefinitionBuilder beanBuilder = null;
                if ("insert-object".equals(e.getLocalName())) {
                    String ref = e.getAttribute("ref");
                    Element nestedElm = getFirstElement(e.getChildNodes());
                    beanBuilder = BeanDefinitionBuilder.genericBeanDefinition(InsertObjectCommand.class);
                    if (org.springframework.util.StringUtils.hasText(ref)) {
                        beanBuilder.addConstructorArgReference(ref);
                    } else if (nestedElm != null) {
                        beanBuilder.addConstructorArgValue(parserContext.getDelegate().parsePropertySubElement(nestedElm, null, null));
                    } else {
                        throw new IllegalArgumentException("insert-object must either specify a 'ref' attribute or have a nested bean");
                    }
                } else if ("set-global".equals(e.getLocalName())) {
                    String ref = e.getAttribute("ref");
                    Element nestedElm = getFirstElement(e.getChildNodes());
                    beanBuilder = BeanDefinitionBuilder.genericBeanDefinition(SetGlobalCommand.class);
                    beanBuilder.addConstructorArgValue(e.getAttribute("identifier"));
                    if (org.springframework.util.StringUtils.hasText(ref)) {
                        beanBuilder.addConstructorArgReference(ref);
                    } else if (nestedElm != null) {
                        beanBuilder.addConstructorArgValue(parserContext.getDelegate().parsePropertySubElement(nestedElm, null, null));
                    } else {
                        throw new IllegalArgumentException("set-global must either specify a 'ref' attribute or have a nested bean");
                    }
                } else if ("fire-until-halt".equals(e.getLocalName())) {
                    beanBuilder = BeanDefinitionBuilder.genericBeanDefinition(FireUntilHaltCommand.class);
                } else if ("fire-all-rules".equals(e.getLocalName())) {
                    beanBuilder = BeanDefinitionBuilder.genericBeanDefinition(FireAllRulesCommand.class);
                    String max = e.getAttribute("max");
                    if (org.springframework.util.StringUtils.hasText(max)) {
                        beanBuilder.addPropertyValue("max", max);
                    }
                } else if ("start-process".equals(e.getLocalName())) {
                    beanBuilder = BeanDefinitionBuilder.genericBeanDefinition(StartProcessCommand.class);
                    String processId = e.getAttribute("process-id");
                    if (!org.springframework.util.StringUtils.hasText(processId)) {
                        throw new IllegalArgumentException("start-process must specify a process-id");
                    }
                    beanBuilder.addConstructorArgValue(processId);
                    List<Element> params = DomUtils.getChildElementsByTagName(e, "parameter");
                    if (!params.isEmpty()) {
                        ManagedMap map = new ManagedMap();
                        for (Element param : params) {
                            String identifier = param.getAttribute("identifier");
                            if (!org.springframework.util.StringUtils.hasText(identifier)) {
                                throw new IllegalArgumentException("start-process paramaters must specify an identifier");
                            }
                            String ref = param.getAttribute("ref");
                            Element nestedElm = getFirstElement(param.getChildNodes());
                            if (org.springframework.util.StringUtils.hasText(ref)) {
                                map.put(identifier, new RuntimeBeanReference(ref));
                            } else if (nestedElm != null) {
                                map.put(identifier, parserContext.getDelegate().parsePropertySubElement(nestedElm, null, null));
                            } else {
                                throw new IllegalArgumentException("start-process parameters must either specify a 'ref' attribute or have a nested bean");
                            }
                        }
                        beanBuilder.addPropertyValue("parameters", map);
                    }
                } else if ("signal-event".equals(e.getLocalName())) {
                    beanBuilder = BeanDefinitionBuilder.genericBeanDefinition(SignalEventCommand.class);
                    String processInstanceId = e.getAttribute("process-instance-id");
                    if (org.springframework.util.StringUtils.hasText(processInstanceId)) {
                        beanBuilder.addConstructorArgValue(processInstanceId);
                    }
                    beanBuilder.addConstructorArgValue(e.getAttribute("event-type"));
                    String ref = e.getAttribute("ref");
                    Element nestedElm = getFirstElement(e.getChildNodes());
                    if (org.springframework.util.StringUtils.hasText(ref)) {
                        beanBuilder.addConstructorArgReference(ref);
                    } else if (nestedElm != null) {
                        beanBuilder.addConstructorArgValue(parserContext.getDelegate().parsePropertySubElement(nestedElm, null, null));
                    } else {
                        throw new IllegalArgumentException("signal-event must either specify a 'ref' attribute or have a nested bean");
                    }
                }
                if (beanBuilder == null) {
                    throw new IllegalStateException("Unknow element: " + e.getLocalName());
                }
                children.add(beanBuilder.getBeanDefinition());
            }
        }
        factory.addPropertyValue("batch", children);
    }
}
Also used : Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) ManagedList(org.springframework.beans.factory.support.ManagedList) FireUntilHaltCommand(org.drools.core.command.runtime.rule.FireUntilHaltCommand) StartProcessCommand(org.drools.core.command.runtime.process.StartProcessCommand) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) InsertObjectCommand(org.drools.core.command.runtime.rule.InsertObjectCommand) ManagedMap(org.springframework.beans.factory.support.ManagedMap)

Example 69 with ManagedMap

use of org.springframework.beans.factory.support.ManagedMap in project droolsjbpm-integration by kiegroup.

the class KSessionDefinitionParser method parseSessionConf.

private void parseSessionConf(BeanDefinitionBuilder factory, Element ksessionConf) {
    if (ksessionConf != null) {
        Element persistenceElm = DomUtils.getChildElementByTagName(ksessionConf, "jpa-persistence");
        if (persistenceElm != null) {
            BeanDefinitionBuilder beanBuilder = BeanDefinitionBuilder.genericBeanDefinition(StatefulKSessionFactoryBeanHelper.JpaConfiguration.class);
            String loadId = persistenceElm.getAttribute("load");
            if (org.springframework.util.StringUtils.hasText(loadId)) {
                beanBuilder.addPropertyValue(ID_ATTRIBUTE, Long.parseLong(loadId));
            }
            Element tnxMng = DomUtils.getChildElementByTagName(persistenceElm, TX_MANAGER_ATTRIBUTE);
            String ref = tnxMng.getAttribute("ref");
            beanBuilder.addPropertyReference("platformTransactionManager", ref);
            Element emf = DomUtils.getChildElementByTagName(persistenceElm, EMF_ATTRIBUTE);
            ref = emf.getAttribute("ref");
            beanBuilder.addPropertyReference("entityManagerFactory", ref);
            Element variablePersisters = DomUtils.getChildElementByTagName(persistenceElm, "variable-persisters");
            if (variablePersisters != null && variablePersisters.hasChildNodes()) {
                List<Element> childPersisterElems = DomUtils.getChildElementsByTagName(variablePersisters, "persister");
                ManagedMap persistors = new ManagedMap(childPersisterElems.size());
                for (Element persisterElem : childPersisterElems) {
                    String forClass = persisterElem.getAttribute(FORCLASS_ATTRIBUTE);
                    String implementation = persisterElem.getAttribute(IMPLEMENTATION_ATTRIBUTE);
                    if (!org.springframework.util.StringUtils.hasText(forClass)) {
                        throw new RuntimeException("persister element must have valid for-class attribute");
                    }
                    if (!org.springframework.util.StringUtils.hasText(implementation)) {
                        throw new RuntimeException("persister element must have valid implementation attribute");
                    }
                    persistors.put(forClass, implementation);
                }
                beanBuilder.addPropertyValue("variablePersisters", persistors);
            }
            factory.addPropertyValue("jpaConfiguration", beanBuilder.getBeanDefinition());
        }
        BeanDefinitionBuilder rbaseConfBuilder = BeanDefinitionBuilder.rootBeanDefinition(SessionConfiguration.class, "newInstance");
        Element e = DomUtils.getChildElementByTagName(ksessionConf, KEEP_REFERENCE);
        if (e != null && org.springframework.util.StringUtils.hasText(e.getAttribute("enabled"))) {
            rbaseConfBuilder.addPropertyValue("keepReference", Boolean.parseBoolean(e.getAttribute("enabled")));
        }
        e = DomUtils.getChildElementByTagName(ksessionConf, CLOCK_TYPE);
        if (e != null && org.springframework.util.StringUtils.hasText(e.getAttribute("type"))) {
            rbaseConfBuilder.addPropertyValue("clockType", ClockType.resolveClockType(e.getAttribute("type")));
        }
        factory.addPropertyValue("conf", rbaseConfBuilder.getBeanDefinition());
        e = DomUtils.getChildElementByTagName(ksessionConf, WORK_ITEMS);
        if (e != null) {
            List<Element> children = DomUtils.getChildElementsByTagName(e, WORK_ITEM);
            if (children != null && !children.isEmpty()) {
                ManagedMap workDefs = new ManagedMap();
                for (Element child : children) {
                    workDefs.put(child.getAttribute("name"), new RuntimeBeanReference(child.getAttribute("ref")));
                }
                factory.addPropertyValue("workItems", workDefs);
            }
        }
    }
}
Also used : BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) Element(org.w3c.dom.Element) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) StatefulKSessionFactoryBeanHelper(org.kie.spring.factorybeans.helper.StatefulKSessionFactoryBeanHelper) ManagedMap(org.springframework.beans.factory.support.ManagedMap)

Example 70 with ManagedMap

use of org.springframework.beans.factory.support.ManagedMap in project spring-amqp by spring-projects.

the class ListenerContainerParser method parseListener.

private // NOSONAR complexity
void parseListener(// NOSONAR complexity
Element listenerEle, // NOSONAR complexity
Element containerEle, // NOSONAR complexity
ParserContext parserContext, ManagedList<RuntimeBeanReference> containerList) {
    RootBeanDefinition listenerDef = new RootBeanDefinition();
    listenerDef.setSource(parserContext.extractSource(listenerEle));
    String ref = listenerEle.getAttribute(REF_ATTRIBUTE);
    if (!StringUtils.hasText(ref)) {
        parserContext.getReaderContext().error("Listener 'ref' attribute contains empty value.", listenerEle);
    } else {
        listenerDef.getPropertyValues().add("delegate", new RuntimeBeanReference(ref));
    }
    String method = null;
    if (listenerEle.hasAttribute(METHOD_ATTRIBUTE)) {
        method = listenerEle.getAttribute(METHOD_ATTRIBUTE);
        if (!StringUtils.hasText(method)) {
            parserContext.getReaderContext().error("Listener 'method' attribute contains empty value.", listenerEle);
        }
    }
    listenerDef.getPropertyValues().add("defaultListenerMethod", method);
    if (containerEle.hasAttribute(MESSAGE_CONVERTER_ATTRIBUTE)) {
        String messageConverter = containerEle.getAttribute(MESSAGE_CONVERTER_ATTRIBUTE);
        if (!StringUtils.hasText(messageConverter)) {
            parserContext.getReaderContext().error("Listener container 'message-converter' attribute contains empty value.", containerEle);
        } else {
            listenerDef.getPropertyValues().add("messageConverter", new RuntimeBeanReference(messageConverter));
        }
    }
    BeanDefinition containerDef = RabbitNamespaceUtils.parseContainer(containerEle, parserContext);
    if (listenerEle.hasAttribute(RESPONSE_EXCHANGE_ATTRIBUTE)) {
        String responseExchange = listenerEle.getAttribute(RESPONSE_EXCHANGE_ATTRIBUTE);
        listenerDef.getPropertyValues().add("responseExchange", responseExchange);
    }
    if (listenerEle.hasAttribute(RESPONSE_ROUTING_KEY_ATTRIBUTE)) {
        String responseRoutingKey = listenerEle.getAttribute(RESPONSE_ROUTING_KEY_ATTRIBUTE);
        listenerDef.getPropertyValues().add("responseRoutingKey", responseRoutingKey);
    }
    listenerDef.setBeanClass(MessageListenerAdapter.class);
    containerDef.getPropertyValues().add("messageListener", listenerDef);
    String exclusive = listenerEle.getAttribute(EXCLUSIVE);
    if (StringUtils.hasText(exclusive)) {
        containerDef.getPropertyValues().add("exclusive", exclusive);
    }
    String childElementId = listenerEle.getAttribute(ID_ATTRIBUTE);
    String containerBeanName = StringUtils.hasText(childElementId) ? childElementId : BeanDefinitionReaderUtils.generateBeanName(containerDef, parserContext.getRegistry());
    if (!NamespaceUtils.isAttributeDefined(listenerEle, QUEUE_NAMES_ATTRIBUTE) && !NamespaceUtils.isAttributeDefined(listenerEle, QUEUES_ATTRIBUTE)) {
        parserContext.getReaderContext().error("Listener 'queue-names' or 'queues' attribute must be provided.", listenerEle);
    }
    if (NamespaceUtils.isAttributeDefined(listenerEle, QUEUE_NAMES_ATTRIBUTE) && NamespaceUtils.isAttributeDefined(listenerEle, QUEUES_ATTRIBUTE)) {
        parserContext.getReaderContext().error("Listener 'queue-names' or 'queues' attribute must be provided but not both.", listenerEle);
    }
    String queueNames = listenerEle.getAttribute(QUEUE_NAMES_ATTRIBUTE);
    if (StringUtils.hasText(queueNames)) {
        containerDef.getPropertyValues().add("queueNames", queueNames);
    }
    String queues = listenerEle.getAttribute(QUEUES_ATTRIBUTE);
    if (StringUtils.hasText(queues)) {
        if (queues.startsWith("#{")) {
            containerDef.getPropertyValues().add("queues", queues);
        } else {
            String[] names = StringUtils.commaDelimitedListToStringArray(queues);
            List<RuntimeBeanReference> values = new ManagedList<RuntimeBeanReference>();
            for (int i = 0; i < names.length; i++) {
                values.add(new RuntimeBeanReference(names[i].trim()));
            }
            containerDef.getPropertyValues().add("queues", values);
        }
    }
    ManagedMap<String, TypedStringValue> args = new ManagedMap<String, TypedStringValue>();
    String priority = listenerEle.getAttribute("priority");
    if (StringUtils.hasText(priority)) {
        args.put("x-priority", new TypedStringValue(priority, Integer.class));
    }
    if (args.size() > 0) {
        containerDef.getPropertyValues().add("consumerArguments", args);
    }
    String admin = listenerEle.getAttribute("admin");
    if (StringUtils.hasText(admin)) {
        containerDef.getPropertyValues().add("rabbitAdmin", new RuntimeBeanReference(admin));
    }
    // Register the listener and fire event
    parserContext.registerBeanComponent(new BeanComponentDefinition(containerDef, containerBeanName));
    if (containerList != null) {
        containerList.add(new RuntimeBeanReference(containerBeanName));
    }
}
Also used : ManagedList(org.springframework.beans.factory.support.ManagedList) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue) BeanComponentDefinition(org.springframework.beans.factory.parsing.BeanComponentDefinition) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) ManagedMap(org.springframework.beans.factory.support.ManagedMap)

Aggregations

ManagedMap (org.springframework.beans.factory.support.ManagedMap)136 Element (org.w3c.dom.Element)74 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)69 RuntimeBeanReference (org.springframework.beans.factory.config.RuntimeBeanReference)54 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)35 BeanDefinitionBuilder (org.springframework.beans.factory.support.BeanDefinitionBuilder)33 TypedStringValue (org.springframework.beans.factory.config.TypedStringValue)21 Map (java.util.Map)17 BeanComponentDefinition (org.springframework.beans.factory.parsing.BeanComponentDefinition)17 ManagedList (org.springframework.beans.factory.support.ManagedList)14 Node (org.w3c.dom.Node)13 BeanMetadataElement (org.springframework.beans.BeanMetadataElement)11 ConstructorArgumentValues (org.springframework.beans.factory.config.ConstructorArgumentValues)10 Nullable (org.springframework.lang.Nullable)10 MutablePropertyValues (org.springframework.beans.MutablePropertyValues)9 GroovyObject (groovy.lang.GroovyObject)8 AbstractBeanDefinition (org.springframework.beans.factory.support.AbstractBeanDefinition)8 BeanDefinitionHolder (org.springframework.beans.factory.config.BeanDefinitionHolder)7 NamedNodeMap (org.w3c.dom.NamedNodeMap)7 Collection (java.util.Collection)6