Search in sources :

Example 31 with ManagedMap

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

the class TxAdviceBeanDefinitionParser method parseAttributeSource.

private RootBeanDefinition parseAttributeSource(Element attrEle, ParserContext parserContext) {
    List<Element> methods = DomUtils.getChildElementsByTagName(attrEle, METHOD_ELEMENT);
    ManagedMap<TypedStringValue, RuleBasedTransactionAttribute> transactionAttributeMap = new ManagedMap<>(methods.size());
    transactionAttributeMap.setSource(parserContext.extractSource(attrEle));
    for (Element methodEle : methods) {
        String name = methodEle.getAttribute(METHOD_NAME_ATTRIBUTE);
        TypedStringValue nameHolder = new TypedStringValue(name);
        nameHolder.setSource(parserContext.extractSource(methodEle));
        RuleBasedTransactionAttribute attribute = new RuleBasedTransactionAttribute();
        String propagation = methodEle.getAttribute(PROPAGATION_ATTRIBUTE);
        String isolation = methodEle.getAttribute(ISOLATION_ATTRIBUTE);
        String timeout = methodEle.getAttribute(TIMEOUT_ATTRIBUTE);
        String readOnly = methodEle.getAttribute(READ_ONLY_ATTRIBUTE);
        if (StringUtils.hasText(propagation)) {
            attribute.setPropagationBehaviorName(RuleBasedTransactionAttribute.PREFIX_PROPAGATION + propagation);
        }
        if (StringUtils.hasText(isolation)) {
            attribute.setIsolationLevelName(RuleBasedTransactionAttribute.PREFIX_ISOLATION + isolation);
        }
        if (StringUtils.hasText(timeout)) {
            attribute.setTimeoutString(timeout);
        }
        if (StringUtils.hasText(readOnly)) {
            attribute.setReadOnly(Boolean.parseBoolean(methodEle.getAttribute(READ_ONLY_ATTRIBUTE)));
        }
        List<RollbackRuleAttribute> rollbackRules = new ArrayList<>(1);
        if (methodEle.hasAttribute(ROLLBACK_FOR_ATTRIBUTE)) {
            String rollbackForValue = methodEle.getAttribute(ROLLBACK_FOR_ATTRIBUTE);
            addRollbackRuleAttributesTo(rollbackRules, rollbackForValue);
        }
        if (methodEle.hasAttribute(NO_ROLLBACK_FOR_ATTRIBUTE)) {
            String noRollbackForValue = methodEle.getAttribute(NO_ROLLBACK_FOR_ATTRIBUTE);
            addNoRollbackRuleAttributesTo(rollbackRules, noRollbackForValue);
        }
        attribute.setRollbackRules(rollbackRules);
        transactionAttributeMap.put(nameHolder, attribute);
    }
    RootBeanDefinition attributeSourceDefinition = new RootBeanDefinition(NameMatchTransactionAttributeSource.class);
    attributeSourceDefinition.setSource(parserContext.extractSource(attrEle));
    attributeSourceDefinition.getPropertyValues().add("nameMap", transactionAttributeMap);
    return attributeSourceDefinition;
}
Also used : RollbackRuleAttribute(org.springframework.transaction.interceptor.RollbackRuleAttribute) NoRollbackRuleAttribute(org.springframework.transaction.interceptor.NoRollbackRuleAttribute) RuleBasedTransactionAttribute(org.springframework.transaction.interceptor.RuleBasedTransactionAttribute) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue) ManagedMap(org.springframework.beans.factory.support.ManagedMap)

Example 32 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 33 with ManagedMap

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

the class ClientDetailsServiceBeanDefinitionParser method doParse.

@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    List<Element> clientElements = DomUtils.getChildElementsByTagName(element, "client");
    ManagedMap<String, BeanMetadataElement> clients = new ManagedMap<String, BeanMetadataElement>();
    for (Element clientElement : clientElements) {
        BeanDefinitionBuilder client = BeanDefinitionBuilder.rootBeanDefinition(BaseClientDetails.class);
        String clientId = clientElement.getAttribute("client-id");
        if (StringUtils.hasText(clientId)) {
            client.addConstructorArgValue(clientId);
        } else {
            parserContext.getReaderContext().error("A client id must be supplied with the definition of a client.", clientElement);
        }
        String secret = clientElement.getAttribute("secret");
        if (StringUtils.hasText(secret)) {
            client.addPropertyValue("clientSecret", secret);
        }
        String resourceIds = clientElement.getAttribute("resource-ids");
        if (StringUtils.hasText(clientId)) {
            client.addConstructorArgValue(resourceIds);
        } else {
            client.addConstructorArgValue("");
        }
        String redirectUri = clientElement.getAttribute("redirect-uri");
        String tokenValidity = clientElement.getAttribute("access-token-validity");
        if (StringUtils.hasText(tokenValidity)) {
            client.addPropertyValue("accessTokenValiditySeconds", tokenValidity);
        }
        String refreshValidity = clientElement.getAttribute("refresh-token-validity");
        if (StringUtils.hasText(refreshValidity)) {
            client.addPropertyValue("refreshTokenValiditySeconds", refreshValidity);
        }
        client.addConstructorArgValue(clientElement.getAttribute("scope"));
        client.addConstructorArgValue(clientElement.getAttribute("authorized-grant-types"));
        client.addConstructorArgValue(clientElement.getAttribute("authorities"));
        if (StringUtils.hasText(redirectUri)) {
            client.addConstructorArgValue(redirectUri);
        }
        client.addPropertyValue("autoApproveScopes", clientElement.getAttribute("autoapprove"));
        clients.put(clientId, client.getBeanDefinition());
    }
    builder.addPropertyValue("clientDetailsStore", clients);
}
Also used : BeanMetadataElement(org.springframework.beans.BeanMetadataElement) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) BeanMetadataElement(org.springframework.beans.BeanMetadataElement) Element(org.w3c.dom.Element) ManagedMap(org.springframework.beans.factory.support.ManagedMap)

Example 34 with ManagedMap

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

the class InternalInterceptMethodsBeanDefinitionDecorator method createInterceptorDefinition.

protected BeanDefinition createInterceptorDefinition(Node node) {
    Element interceptMethodsElt = (Element) node;
    BeanDefinitionBuilder interceptor = BeanDefinitionBuilder.rootBeanDefinition(MethodSecurityInterceptor.class);
    // Default to autowiring to pick up after invocation mgr
    interceptor.setAutowireMode(RootBeanDefinition.AUTOWIRE_BY_TYPE);
    String accessManagerId = interceptMethodsElt.getAttribute(ATT_ACCESS_MGR);
    if (!StringUtils.hasText(accessManagerId)) {
        accessManagerId = BeanIds.METHOD_ACCESS_MANAGER;
    }
    interceptor.addPropertyValue("accessDecisionManager", new RuntimeBeanReference(accessManagerId));
    interceptor.addPropertyValue("authenticationManager", new RuntimeBeanReference(BeanIds.AUTHENTICATION_MANAGER));
    // Lookup parent bean information
    String parentBeanClass = ((Element) node.getParentNode()).getAttribute("class");
    // Parse the included methods
    List<Element> methods = DomUtils.getChildElementsByTagName(interceptMethodsElt, Elements.PROTECT);
    Map<String, BeanDefinition> mappings = new ManagedMap<String, BeanDefinition>();
    for (Element protectmethodElt : methods) {
        BeanDefinitionBuilder attributeBuilder = BeanDefinitionBuilder.rootBeanDefinition(SecurityConfig.class);
        attributeBuilder.setFactoryMethod("createListFromCommaDelimitedString");
        attributeBuilder.addConstructorArgValue(protectmethodElt.getAttribute(ATT_ACCESS));
        // Support inference of class names
        String methodName = protectmethodElt.getAttribute(ATT_METHOD);
        if (methodName.lastIndexOf(".") == -1) {
            if (parentBeanClass != null && !"".equals(parentBeanClass)) {
                methodName = parentBeanClass + "." + methodName;
            }
        }
        mappings.put(methodName, attributeBuilder.getBeanDefinition());
    }
    BeanDefinition metadataSource = new RootBeanDefinition(MapBasedMethodSecurityMetadataSource.class);
    metadataSource.getConstructorArgumentValues().addGenericArgumentValue(mappings);
    interceptor.addPropertyValue("securityMetadataSource", metadataSource);
    return interceptor.getBeanDefinition();
}
Also used : BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) Element(org.w3c.dom.Element) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) ManagedMap(org.springframework.beans.factory.support.ManagedMap)

Example 35 with ManagedMap

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

the class AuthenticationConfigBuilder method createOpenIDLoginFilter.

void createOpenIDLoginFilter(BeanReference sessionStrategy, BeanReference authManager) {
    Element openIDLoginElt = DomUtils.getChildElementByTagName(httpElt, Elements.OPENID_LOGIN);
    RootBeanDefinition openIDFilter = null;
    if (openIDLoginElt != null) {
        FormLoginBeanDefinitionParser parser = new FormLoginBeanDefinitionParser("/login/openid", null, OPEN_ID_AUTHENTICATION_PROCESSING_FILTER_CLASS, requestCache, sessionStrategy, allowSessionCreation, portMapper, portResolver);
        parser.parse(openIDLoginElt, pc);
        openIDFilter = parser.getFilterBean();
        openIDEntryPoint = parser.getEntryPointBean();
        openidLoginProcessingUrl = parser.getLoginProcessingUrl();
        openIDLoginPage = parser.getLoginPage();
        List<Element> attrExElts = DomUtils.getChildElementsByTagName(openIDLoginElt, Elements.OPENID_ATTRIBUTE_EXCHANGE);
        if (!attrExElts.isEmpty()) {
            // Set up the consumer with the required attribute list
            BeanDefinitionBuilder consumerBldr = BeanDefinitionBuilder.rootBeanDefinition(OPEN_ID_CONSUMER_CLASS);
            BeanDefinitionBuilder axFactory = BeanDefinitionBuilder.rootBeanDefinition(OPEN_ID_ATTRIBUTE_FACTORY_CLASS);
            ManagedMap<String, ManagedList<BeanDefinition>> axMap = new ManagedMap<String, ManagedList<BeanDefinition>>();
            for (Element attrExElt : attrExElts) {
                String identifierMatch = attrExElt.getAttribute("identifier-match");
                if (!StringUtils.hasText(identifierMatch)) {
                    if (attrExElts.size() > 1) {
                        pc.getReaderContext().error("You must supply an identifier-match attribute if using more" + " than one " + Elements.OPENID_ATTRIBUTE_EXCHANGE + " element", attrExElt);
                    }
                    // Match anything
                    identifierMatch = ".*";
                }
                axMap.put(identifierMatch, parseOpenIDAttributes(attrExElt));
            }
            axFactory.addConstructorArgValue(axMap);
            consumerBldr.addConstructorArgValue(axFactory.getBeanDefinition());
            openIDFilter.getPropertyValues().addPropertyValue("consumer", consumerBldr.getBeanDefinition());
        }
    }
    if (openIDFilter != null) {
        openIDFilter.getPropertyValues().addPropertyValue("allowSessionCreation", allowSessionCreation);
        openIDFilter.getPropertyValues().addPropertyValue("authenticationManager", authManager);
        // Required by login page filter
        openIDFilterId = pc.getReaderContext().generateBeanName(openIDFilter);
        pc.registerBeanComponent(new BeanComponentDefinition(openIDFilter, openIDFilterId));
        injectRememberMeServicesRef(openIDFilter, rememberMeServicesId);
        createOpenIDProvider();
    }
}
Also used : BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) BeanMetadataElement(org.springframework.beans.BeanMetadataElement) Element(org.w3c.dom.Element) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) ManagedList(org.springframework.beans.factory.support.ManagedList) BeanComponentDefinition(org.springframework.beans.factory.parsing.BeanComponentDefinition) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) ManagedMap(org.springframework.beans.factory.support.ManagedMap)

Aggregations

ManagedMap (org.springframework.beans.factory.support.ManagedMap)63 Element (org.w3c.dom.Element)37 BeanDefinitionBuilder (org.springframework.beans.factory.support.BeanDefinitionBuilder)25 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)25 RuntimeBeanReference (org.springframework.beans.factory.config.RuntimeBeanReference)24 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)23 BeanMetadataElement (org.springframework.beans.BeanMetadataElement)11 Map (java.util.Map)10 TypedStringValue (org.springframework.beans.factory.config.TypedStringValue)9 HashMap (java.util.HashMap)6 BeanDefinitionHolder (org.springframework.beans.factory.config.BeanDefinitionHolder)6 Node (org.w3c.dom.Node)6 ManagedList (org.springframework.beans.factory.support.ManagedList)5 AbstractBeanDefinition (org.springframework.beans.factory.support.AbstractBeanDefinition)4 NamedNodeMap (org.w3c.dom.NamedNodeMap)4 GroovyObject (groovy.lang.GroovyObject)3 Method (java.lang.reflect.Method)3 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 BeanComponentDefinition (org.springframework.beans.factory.parsing.BeanComponentDefinition)3