Search in sources :

Example 6 with TypedStringValue

use of org.springframework.beans.factory.config.TypedStringValue in project spring-framework by spring-projects.

the class ScriptingDefaultsParser method parse.

@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
    BeanDefinition bd = LangNamespaceUtils.registerScriptFactoryPostProcessorIfNecessary(parserContext.getRegistry());
    String refreshCheckDelay = element.getAttribute(REFRESH_CHECK_DELAY_ATTRIBUTE);
    if (StringUtils.hasText(refreshCheckDelay)) {
        bd.getPropertyValues().add("defaultRefreshCheckDelay", Long.valueOf(refreshCheckDelay));
    }
    String proxyTargetClass = element.getAttribute(PROXY_TARGET_CLASS_ATTRIBUTE);
    if (StringUtils.hasText(proxyTargetClass)) {
        bd.getPropertyValues().add("defaultProxyTargetClass", new TypedStringValue(proxyTargetClass, Boolean.class));
    }
    return null;
}
Also used : TypedStringValue(org.springframework.beans.factory.config.TypedStringValue) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition)

Example 7 with TypedStringValue

use of org.springframework.beans.factory.config.TypedStringValue 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)) {
            try {
                attribute.setTimeout(Integer.parseInt(timeout));
            } catch (NumberFormatException ex) {
                parserContext.getReaderContext().error("Timeout must be an integer value: [" + timeout + "]", methodEle);
            }
        }
        if (StringUtils.hasText(readOnly)) {
            attribute.setReadOnly(Boolean.valueOf(methodEle.getAttribute(READ_ONLY_ATTRIBUTE)));
        }
        List<RollbackRuleAttribute> rollbackRules = new LinkedList<>();
        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) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue) ManagedMap(org.springframework.beans.factory.support.ManagedMap) LinkedList(java.util.LinkedList)

Example 8 with TypedStringValue

use of org.springframework.beans.factory.config.TypedStringValue in project spring-security-oauth by spring-projects.

the class ResourceBeanDefinitionParser method doParse.

@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    String id = element.getAttribute("id");
    if (!StringUtils.hasText(id)) {
        parserContext.getReaderContext().error("An id must be supplied on a resource element.", element);
    }
    builder.addPropertyValue("id", id);
    String type = element.getAttribute("type");
    if (!StringUtils.hasText(type)) {
        type = "client_credentials";
    }
    builder.addPropertyValue("grantType", type);
    String accessTokenUri = element.getAttribute("access-token-uri");
    if (!StringUtils.hasText(accessTokenUri) && !"implicit".equals(type)) {
        parserContext.getReaderContext().error("An accessTokenUri must be supplied on a resource element of type " + type, element);
    }
    builder.addPropertyValue("accessTokenUri", accessTokenUri);
    String clientId = element.getAttribute("client-id");
    if (!StringUtils.hasText(clientId)) {
        parserContext.getReaderContext().error("An clientId must be supplied on a resource element", element);
    }
    builder.addPropertyValue("clientId", clientId);
    String clientSecret = element.getAttribute("client-secret");
    if (StringUtils.hasText(clientSecret)) {
        builder.addPropertyValue("clientSecret", clientSecret);
    }
    String clientAuthenticationScheme = element.getAttribute("client-authentication-scheme");
    if (StringUtils.hasText(clientAuthenticationScheme)) {
        builder.addPropertyValue("clientAuthenticationScheme", clientAuthenticationScheme);
    }
    String userAuthorizationUri = element.getAttribute("user-authorization-uri");
    if (StringUtils.hasText(userAuthorizationUri)) {
        if (needsUserAuthorizationUri(type)) {
            builder.addPropertyValue("userAuthorizationUri", userAuthorizationUri);
        } else {
            parserContext.getReaderContext().error("The " + type + " grant type does not accept an authorization URI", element);
        }
    } else {
        if (needsUserAuthorizationUri(type)) {
            parserContext.getReaderContext().error("An authorization URI must be supplied for a resource of type " + type, element);
        }
    }
    String preEstablishedRedirectUri = element.getAttribute("pre-established-redirect-uri");
    if (StringUtils.hasText(preEstablishedRedirectUri)) {
        builder.addPropertyValue("preEstablishedRedirectUri", preEstablishedRedirectUri);
    }
    String requireImmediateAuthorization = element.getAttribute("require-immediate-authorization");
    if (StringUtils.hasText(requireImmediateAuthorization)) {
        builder.addPropertyValue("requireImmediateAuthorization", requireImmediateAuthorization);
    }
    String useCurrentUri = element.getAttribute("use-current-uri");
    if (StringUtils.hasText(useCurrentUri)) {
        builder.addPropertyValue("useCurrentUri", useCurrentUri);
    }
    String scope = element.getAttribute("scope");
    if (StringUtils.hasText(scope)) {
        BeanDefinitionBuilder scopesBuilder = BeanDefinitionBuilder.genericBeanDefinition(StringListFactoryBean.class);
        scopesBuilder.addConstructorArgValue(new TypedStringValue(scope));
        builder.addPropertyValue("scope", scopesBuilder.getBeanDefinition());
    }
    AuthenticationScheme btm = AuthenticationScheme.header;
    String bearerTokenMethod = element.getAttribute("authentication-scheme");
    if (StringUtils.hasText(bearerTokenMethod)) {
        btm = AuthenticationScheme.valueOf(bearerTokenMethod);
    }
    builder.addPropertyValue("authenticationScheme", btm);
    String bearerTokenName = element.getAttribute("token-name");
    if (!StringUtils.hasText(bearerTokenName)) {
        bearerTokenName = OAuth2AccessToken.ACCESS_TOKEN;
    }
    builder.addPropertyValue("tokenName", bearerTokenName);
    if (type.equals("password")) {
        String[] attributeNames = { "username", "password" };
        for (String attributeName : attributeNames) {
            String attribute = element.getAttribute(attributeName);
            if (StringUtils.hasText(attribute)) {
                builder.addPropertyValue(attributeName, attribute);
            } else {
                parserContext.getReaderContext().error("A " + attributeName + " must be supplied on a resource element of type " + type, element);
            }
        }
    }
}
Also used : AuthenticationScheme(org.springframework.security.oauth2.common.AuthenticationScheme) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue)

Example 9 with TypedStringValue

use of org.springframework.beans.factory.config.TypedStringValue 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 10 with TypedStringValue

use of org.springframework.beans.factory.config.TypedStringValue in project dubbo by alibaba.

the class DubboBeanDefinitionParser method parse.

@SuppressWarnings("unchecked")
private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) {
    RootBeanDefinition beanDefinition = new RootBeanDefinition();
    beanDefinition.setBeanClass(beanClass);
    beanDefinition.setLazyInit(false);
    String id = element.getAttribute("id");
    if ((id == null || id.length() == 0) && required) {
        String generatedBeanName = element.getAttribute("name");
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            if (ProtocolConfig.class.equals(beanClass)) {
                generatedBeanName = "dubbo";
            } else {
                generatedBeanName = element.getAttribute("interface");
            }
        }
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            generatedBeanName = beanClass.getName();
        }
        id = generatedBeanName;
        int counter = 2;
        while (parserContext.getRegistry().containsBeanDefinition(id)) {
            id = generatedBeanName + (counter++);
        }
    }
    if (id != null && id.length() > 0) {
        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 = element.getAttribute("class");
        if (className != null && className.length() > 0) {
            RootBeanDefinition classDefinition = new RootBeanDefinition();
            classDefinition.setBeanClass(ReflectUtils.forName(className));
            classDefinition.setLazyInit(false);
            parseProperties(element.getChildNodes(), classDefinition);
            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<String>();
    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 property = StringUtils.camelToSplitName(name.substring(3, 4).toLowerCase() + name.substring(4), "-");
            props.add(property);
            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) {
                }
            }
            if (getter == null || !Modifier.isPublic(getter.getModifiers()) || !type.equals(getter.getReturnType())) {
                continue;
            }
            if ("parameters".equals(property)) {
                parameters = parseParameters(element.getChildNodes(), beanDefinition);
            } 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 = element.getAttribute(property);
                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(property, registryConfig);
                        } else if ("registry".equals(property) && value.indexOf(',') != -1) {
                            parseMultiRef("registries", value, beanDefinition, parserContext);
                        } else if ("provider".equals(property) && value.indexOf(',') != -1) {
                            parseMultiRef("providers", value, beanDefinition, parserContext);
                        } else if ("protocol".equals(property) && value.indexOf(',') != -1) {
                            parseMultiRef("protocols", value, beanDefinition, parserContext);
                        } 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)) {
                                    // 兼容旧版本xsd中的default值
                                    value = null;
                                }
                                reference = value;
                            } else if ("protocol".equals(property) && ExtensionLoader.getExtensionLoader(Protocol.class).hasExtension(value) && (!parserContext.getRegistry().containsBeanDefinition(value) || !ProtocolConfig.class.getName().equals(parserContext.getRegistry().getBeanDefinition(value).getBeanClassName()))) {
                                if ("dubbo:provider".equals(element.getTagName())) {
                                    logger.warn("Recommended replace <dubbo:provider protocol=\"" + value + "\" ... /> to <dubbo:protocol name=\"" + value + "\" ... />");
                                }
                                // 兼容旧版本配置
                                ProtocolConfig protocol = new ProtocolConfig();
                                protocol.setName(value);
                                reference = protocol;
                            } else if ("monitor".equals(property) && (!parserContext.getRegistry().containsBeanDefinition(value) || !MonitorConfig.class.getName().equals(parserContext.getRegistry().getBeanDefinition(value).getBeanClassName()))) {
                                // 兼容旧版本配置
                                reference = convertMonitor(value);
                            } else if ("onreturn".equals(property)) {
                                int index = value.lastIndexOf(".");
                                String returnRef = value.substring(0, index);
                                String returnMethod = value.substring(index + 1);
                                reference = new RuntimeBeanReference(returnRef);
                                beanDefinition.getPropertyValues().addPropertyValue("onreturnMethod", returnMethod);
                            } else if ("onthrow".equals(property)) {
                                int index = value.lastIndexOf(".");
                                String throwRef = value.substring(0, index);
                                String throwMethod = value.substring(index + 1);
                                reference = new RuntimeBeanReference(throwRef);
                                beanDefinition.getPropertyValues().addPropertyValue("onthrowMethod", throwMethod);
                            } 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(property, 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(com.alibaba.dubbo.config.RegistryConfig) Node(org.w3c.dom.Node) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) ServiceBean(com.alibaba.dubbo.config.spring.ServiceBean) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) ConsumerConfig(com.alibaba.dubbo.config.ConsumerConfig) ProtocolConfig(com.alibaba.dubbo.config.ProtocolConfig) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) Protocol(com.alibaba.dubbo.rpc.Protocol) ManagedMap(org.springframework.beans.factory.support.ManagedMap) HashSet(java.util.HashSet) NamedNodeMap(org.w3c.dom.NamedNodeMap) PropertyValue(org.springframework.beans.PropertyValue) Method(java.lang.reflect.Method) ReferenceBean(com.alibaba.dubbo.config.spring.ReferenceBean) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue)

Aggregations

TypedStringValue (org.springframework.beans.factory.config.TypedStringValue)24 Element (org.w3c.dom.Element)9 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)7 RuntimeBeanReference (org.springframework.beans.factory.config.RuntimeBeanReference)6 ManagedMap (org.springframework.beans.factory.support.ManagedMap)6 Test (org.junit.Test)5 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)5 Node (org.w3c.dom.Node)5 BeanDefinitionHolder (org.springframework.beans.factory.config.BeanDefinitionHolder)4 Method (java.lang.reflect.Method)3 BeanMetadataElement (org.springframework.beans.BeanMetadataElement)3 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 HashSet (java.util.HashSet)2 Mockito (org.mockito.Mockito)2 PropertyValue (org.springframework.beans.PropertyValue)2 BeanCreationException (org.springframework.beans.factory.BeanCreationException)2 BeanDefinitionBuilder (org.springframework.beans.factory.support.BeanDefinitionBuilder)2 ManagedList (org.springframework.beans.factory.support.ManagedList)2 NamedNodeMap (org.w3c.dom.NamedNodeMap)2