Example usage for org.springframework.beans.factory.support BeanDefinitionBuilder getBeanDefinition

List of usage examples for org.springframework.beans.factory.support BeanDefinitionBuilder getBeanDefinition

Introduction

In this page you can find the example usage for org.springframework.beans.factory.support BeanDefinitionBuilder getBeanDefinition.

Prototype

public AbstractBeanDefinition getBeanDefinition() 

Source Link

Document

Validate and return the created BeanDefinition object.

Usage

From source file:org.springframework.security.config.http.FilterInvocationSecurityMetadataSourceParser.java

private static ManagedMap<BeanMetadataElement, BeanDefinition> parseInterceptUrlsForFilterInvocationRequestMap(
        MatcherType matcherType, List<Element> urlElts, boolean useExpressions, boolean addAuthenticatedAll,
        ParserContext parserContext) {//  ww  w.  j a va2s .co m

    ManagedMap<BeanMetadataElement, BeanDefinition> filterInvocationDefinitionMap = new ManagedMap<>();

    for (Element urlElt : urlElts) {
        String access = urlElt.getAttribute(ATT_ACCESS);
        if (!StringUtils.hasText(access)) {
            continue;
        }

        String path = urlElt.getAttribute(ATT_PATTERN);
        String matcherRef = urlElt.getAttribute(ATT_REQUEST_MATCHER_REF);
        boolean hasMatcherRef = StringUtils.hasText(matcherRef);

        if (!hasMatcherRef && !StringUtils.hasText(path)) {
            parserContext.getReaderContext().error("path attribute cannot be empty or null", urlElt);
        }

        String method = urlElt.getAttribute(ATT_HTTP_METHOD);
        if (!StringUtils.hasText(method)) {
            method = null;
        }

        String servletPath = urlElt.getAttribute(ATT_SERVLET_PATH);
        if (!StringUtils.hasText(servletPath)) {
            servletPath = null;
        } else if (!MatcherType.mvc.equals(matcherType)) {
            parserContext.getReaderContext().error(
                    ATT_SERVLET_PATH + " is not applicable for request-matcher: '" + matcherType.name() + "'",
                    urlElt);
        }

        BeanMetadataElement matcher = hasMatcherRef ? new RuntimeBeanReference(matcherRef)
                : matcherType.createMatcher(parserContext, path, method, servletPath);
        BeanDefinitionBuilder attributeBuilder = BeanDefinitionBuilder.rootBeanDefinition(SecurityConfig.class);

        if (useExpressions) {
            logger.info("Creating access control expression attribute '" + access + "' for " + path);
            // The single expression will be parsed later by the
            // ExpressionBasedFilterInvocationSecurityMetadataSource
            attributeBuilder.addConstructorArgValue(new String[] { access });
            attributeBuilder.setFactoryMethod("createList");

        } else {
            attributeBuilder.addConstructorArgValue(access);
            attributeBuilder.setFactoryMethod("createListFromCommaDelimitedString");
        }

        if (filterInvocationDefinitionMap.containsKey(matcher)) {
            logger.warn(
                    "Duplicate URL defined: " + path + ". The original attribute values will be overwritten");
        }

        filterInvocationDefinitionMap.put(matcher, attributeBuilder.getBeanDefinition());
    }

    if (addAuthenticatedAll && filterInvocationDefinitionMap.isEmpty()) {

        BeanDefinition matcher = matcherType.createMatcher(parserContext, "/**", null);
        BeanDefinitionBuilder attributeBuilder = BeanDefinitionBuilder.rootBeanDefinition(SecurityConfig.class);
        attributeBuilder.addConstructorArgValue(new String[] { "authenticated" });
        attributeBuilder.setFactoryMethod("createList");
        filterInvocationDefinitionMap.put(matcher, attributeBuilder.getBeanDefinition());
    }

    return filterInvocationDefinitionMap;
}

From source file:org.springframework.security.config.http.FormLoginBeanDefinitionParser.java

public BeanDefinition parse(Element elt, ParserContext pc) {
    String loginUrl = null;/*from w ww.  ja v  a 2 s. c  o m*/
    String defaultTargetUrl = null;
    String authenticationFailureUrl = null;
    String alwaysUseDefault = null;
    String successHandlerRef = null;
    String failureHandlerRef = null;
    // Only available with form-login
    String usernameParameter = null;
    String passwordParameter = null;
    String authDetailsSourceRef = null;
    String authenticationFailureForwardUrl = null;
    String authenticationSuccessForwardUrl = null;

    Object source = null;

    if (elt != null) {
        source = pc.extractSource(elt);
        loginUrl = elt.getAttribute(ATT_LOGIN_URL);
        WebConfigUtils.validateHttpRedirect(loginUrl, pc, source);
        defaultTargetUrl = elt.getAttribute(ATT_FORM_LOGIN_TARGET_URL);
        WebConfigUtils.validateHttpRedirect(defaultTargetUrl, pc, source);
        authenticationFailureUrl = elt.getAttribute(ATT_FORM_LOGIN_AUTHENTICATION_FAILURE_URL);
        WebConfigUtils.validateHttpRedirect(authenticationFailureUrl, pc, source);
        alwaysUseDefault = elt.getAttribute(ATT_ALWAYS_USE_DEFAULT_TARGET_URL);
        loginPage = elt.getAttribute(ATT_LOGIN_PAGE);
        successHandlerRef = elt.getAttribute(ATT_SUCCESS_HANDLER_REF);
        failureHandlerRef = elt.getAttribute(ATT_FAILURE_HANDLER_REF);
        authDetailsSourceRef = elt.getAttribute(AuthenticationConfigBuilder.ATT_AUTH_DETAILS_SOURCE_REF);
        authenticationFailureForwardUrl = elt.getAttribute(ATT_FORM_LOGIN_AUTHENTICATION_FAILURE_FORWARD_URL);
        WebConfigUtils.validateHttpRedirect(authenticationFailureForwardUrl, pc, source);
        authenticationSuccessForwardUrl = elt.getAttribute(ATT_FORM_LOGIN_AUTHENTICATION_SUCCESS_FORWARD_URL);
        WebConfigUtils.validateHttpRedirect(authenticationSuccessForwardUrl, pc, source);

        if (!StringUtils.hasText(loginPage)) {
            loginPage = null;
        }
        WebConfigUtils.validateHttpRedirect(loginPage, pc, source);
        usernameParameter = elt.getAttribute(ATT_USERNAME_PARAMETER);
        passwordParameter = elt.getAttribute(ATT_PASSWORD_PARAMETER);
    }

    filterBean = createFilterBean(loginUrl, defaultTargetUrl, alwaysUseDefault, loginPage,
            authenticationFailureUrl, successHandlerRef, failureHandlerRef, authDetailsSourceRef,
            authenticationFailureForwardUrl, authenticationSuccessForwardUrl);

    if (StringUtils.hasText(usernameParameter)) {
        filterBean.getPropertyValues().addPropertyValue("usernameParameter", usernameParameter);
    }
    if (StringUtils.hasText(passwordParameter)) {
        filterBean.getPropertyValues().addPropertyValue("passwordParameter", passwordParameter);
    }

    filterBean.setSource(source);

    BeanDefinitionBuilder entryPointBuilder = BeanDefinitionBuilder
            .rootBeanDefinition(LoginUrlAuthenticationEntryPoint.class);
    entryPointBuilder.getRawBeanDefinition().setSource(source);
    entryPointBuilder.addConstructorArgValue(loginPage != null ? loginPage : DEF_LOGIN_PAGE);
    entryPointBuilder.addPropertyValue("portMapper", portMapper);
    entryPointBuilder.addPropertyValue("portResolver", portResolver);
    entryPointBean = (RootBeanDefinition) entryPointBuilder.getBeanDefinition();

    return null;
}

From source file:org.springframework.security.config.http.FormLoginBeanDefinitionParser.java

private RootBeanDefinition createFilterBean(String loginUrl, String defaultTargetUrl, String alwaysUseDefault,
        String loginPage, String authenticationFailureUrl, String successHandlerRef, String failureHandlerRef,
        String authDetailsSourceRef, String authenticationFailureForwardUrl,
        String authenticationSuccessForwardUrl) {

    BeanDefinitionBuilder filterBuilder = BeanDefinitionBuilder.rootBeanDefinition(filterClassName);

    if (!StringUtils.hasText(loginUrl)) {
        loginUrl = defaultLoginProcessingUrl;
    }/*from www.j a v  a  2  s.  c om*/

    this.loginProcessingUrl = loginUrl;

    BeanDefinitionBuilder matcherBuilder = BeanDefinitionBuilder
            .rootBeanDefinition("org.springframework.security.web.util.matcher.AntPathRequestMatcher");
    matcherBuilder.addConstructorArgValue(loginUrl);
    if (loginMethod != null) {
        matcherBuilder.addConstructorArgValue("POST");
    }

    filterBuilder.addPropertyValue("requiresAuthenticationRequestMatcher", matcherBuilder.getBeanDefinition());

    if (StringUtils.hasText(successHandlerRef)) {
        filterBuilder.addPropertyReference("authenticationSuccessHandler", successHandlerRef);
    } else if (StringUtils.hasText(authenticationSuccessForwardUrl)) {
        BeanDefinitionBuilder forwardSuccessHandler = BeanDefinitionBuilder
                .rootBeanDefinition(ForwardAuthenticationSuccessHandler.class);
        forwardSuccessHandler.addConstructorArgValue(authenticationSuccessForwardUrl);
        filterBuilder.addPropertyValue("authenticationSuccessHandler",
                forwardSuccessHandler.getBeanDefinition());
    } else {
        BeanDefinitionBuilder successHandler = BeanDefinitionBuilder
                .rootBeanDefinition(SavedRequestAwareAuthenticationSuccessHandler.class);
        if ("true".equals(alwaysUseDefault)) {
            successHandler.addPropertyValue("alwaysUseDefaultTargetUrl", Boolean.TRUE);
        }
        successHandler.addPropertyValue("requestCache", requestCache);
        successHandler.addPropertyValue("defaultTargetUrl",
                StringUtils.hasText(defaultTargetUrl) ? defaultTargetUrl : DEF_FORM_LOGIN_TARGET_URL);
        filterBuilder.addPropertyValue("authenticationSuccessHandler", successHandler.getBeanDefinition());
    }

    if (StringUtils.hasText(authDetailsSourceRef)) {
        filterBuilder.addPropertyReference("authenticationDetailsSource", authDetailsSourceRef);
    }

    if (sessionStrategy != null) {
        filterBuilder.addPropertyValue("sessionAuthenticationStrategy", sessionStrategy);
    }

    if (StringUtils.hasText(failureHandlerRef)) {
        filterBuilder.addPropertyReference("authenticationFailureHandler", failureHandlerRef);
    } else if (StringUtils.hasText(authenticationFailureForwardUrl)) {
        BeanDefinitionBuilder forwardFailureHandler = BeanDefinitionBuilder
                .rootBeanDefinition(ForwardAuthenticationFailureHandler.class);
        forwardFailureHandler.addConstructorArgValue(authenticationFailureForwardUrl);
        filterBuilder.addPropertyValue("authenticationFailureHandler",
                forwardFailureHandler.getBeanDefinition());
    } else {
        BeanDefinitionBuilder failureHandler = BeanDefinitionBuilder
                .rootBeanDefinition(SimpleUrlAuthenticationFailureHandler.class);
        if (!StringUtils.hasText(authenticationFailureUrl)) {
            // Fall back to re-displaying the custom login page, if one was specified.
            if (StringUtils.hasText(loginPage)) {
                authenticationFailureUrl = loginPage + "?"
                        + DefaultLoginPageGeneratingFilter.ERROR_PARAMETER_NAME;
            } else {
                authenticationFailureUrl = DEF_FORM_LOGIN_AUTHENTICATION_FAILURE_URL;
            }
        }
        failureHandler.addPropertyValue("defaultFailureUrl", authenticationFailureUrl);
        failureHandler.addPropertyValue("allowSessionCreation", allowSessionCreation);
        filterBuilder.addPropertyValue("authenticationFailureHandler", failureHandler.getBeanDefinition());
    }

    return (RootBeanDefinition) filterBuilder.getBeanDefinition();
}

From source file:org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.java

private BeanReference createSecurityFilterChainBean(Element element, ParserContext pc, List<?> filterChain) {
    BeanMetadataElement filterChainMatcher;

    String requestMatcherRef = element.getAttribute(ATT_REQUEST_MATCHER_REF);
    String filterChainPattern = element.getAttribute(ATT_PATH_PATTERN);

    if (StringUtils.hasText(requestMatcherRef)) {
        if (StringUtils.hasText(filterChainPattern)) {
            pc.getReaderContext().error(
                    "You can't define a pattern and a request-matcher-ref for the " + "same filter chain",
                    pc.extractSource(element));
        }/*  w ww  .  j av a2 s. com*/
        filterChainMatcher = new RuntimeBeanReference(requestMatcherRef);

    } else if (StringUtils.hasText(filterChainPattern)) {
        filterChainMatcher = MatcherType.fromElement(element).createMatcher(pc, filterChainPattern, null);
    } else {
        filterChainMatcher = new RootBeanDefinition(AnyRequestMatcher.class);
    }

    BeanDefinitionBuilder filterChainBldr = BeanDefinitionBuilder
            .rootBeanDefinition(DefaultSecurityFilterChain.class);
    filterChainBldr.addConstructorArgValue(filterChainMatcher);
    filterChainBldr.addConstructorArgValue(filterChain);

    BeanDefinition filterChainBean = filterChainBldr.getBeanDefinition();

    String id = element.getAttribute("name");
    if (!StringUtils.hasText(id)) {
        id = element.getAttribute("id");
        if (!StringUtils.hasText(id)) {
            id = pc.getReaderContext().generateBeanName(filterChainBean);
        }
    }

    pc.registerBeanComponent(new BeanComponentDefinition(filterChainBean, id));

    return new RuntimeBeanReference(id);
}

From source file:org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.java

/**
 * Creates the internal AuthenticationManager bean which uses either the externally
 * registered (global) one as a parent or the bean specified by
 * "authentication-manager-ref"./* w  w w .  j  a v a2s.c  o  m*/
 *
 * All the providers registered by this &lt;http&gt; block will be registered with the
 * internal authentication manager.
 */
private BeanReference createAuthenticationManager(Element element, ParserContext pc,
        ManagedList<BeanReference> authenticationProviders) {
    String parentMgrRef = element.getAttribute(ATT_AUTHENTICATION_MANAGER_REF);
    BeanDefinitionBuilder authManager = BeanDefinitionBuilder.rootBeanDefinition(ProviderManager.class);
    authManager.addConstructorArgValue(authenticationProviders);

    if (StringUtils.hasText(parentMgrRef)) {
        RuntimeBeanReference parentAuthManager = new RuntimeBeanReference(parentMgrRef);
        authManager.addConstructorArgValue(parentAuthManager);
        RootBeanDefinition clearCredentials = new RootBeanDefinition(
                ClearCredentialsMethodInvokingFactoryBean.class);
        clearCredentials.getPropertyValues().addPropertyValue("targetObject", parentAuthManager);
        clearCredentials.getPropertyValues().addPropertyValue("targetMethod",
                "isEraseCredentialsAfterAuthentication");

        authManager.addPropertyValue("eraseCredentialsAfterAuthentication", clearCredentials);
    } else {
        RootBeanDefinition amfb = new RootBeanDefinition(AuthenticationManagerFactoryBean.class);
        amfb.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        String amfbId = pc.getReaderContext().generateBeanName(amfb);
        pc.registerBeanComponent(new BeanComponentDefinition(amfb, amfbId));
        RootBeanDefinition clearCredentials = new RootBeanDefinition(MethodInvokingFactoryBean.class);
        clearCredentials.getPropertyValues().addPropertyValue("targetObject", new RuntimeBeanReference(amfbId));
        clearCredentials.getPropertyValues().addPropertyValue("targetMethod",
                "isEraseCredentialsAfterAuthentication");

        authManager.addConstructorArgValue(new RuntimeBeanReference(amfbId));
        authManager.addPropertyValue("eraseCredentialsAfterAuthentication", clearCredentials);
    }

    authManager.getRawBeanDefinition().setSource(pc.extractSource(element));
    BeanDefinition authMgrBean = authManager.getBeanDefinition();
    String id = pc.getReaderContext().generateBeanName(authMgrBean);
    pc.registerBeanComponent(new BeanComponentDefinition(authMgrBean, id));

    return new RuntimeBeanReference(id);
}

From source file:org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.java

static void registerFilterChainProxyIfNecessary(ParserContext pc, Object source) {
    if (pc.getRegistry().containsBeanDefinition(BeanIds.FILTER_CHAIN_PROXY)) {
        return;//from   ww w.ja va 2  s. c  o m
    }
    // Not already registered, so register the list of filter chains and the
    // FilterChainProxy
    BeanDefinition listFactoryBean = new RootBeanDefinition(ListFactoryBean.class);
    listFactoryBean.getPropertyValues().add("sourceList", new ManagedList());
    pc.registerBeanComponent(new BeanComponentDefinition(listFactoryBean, BeanIds.FILTER_CHAINS));

    BeanDefinitionBuilder fcpBldr = BeanDefinitionBuilder.rootBeanDefinition(FilterChainProxy.class);
    fcpBldr.getRawBeanDefinition().setSource(source);
    fcpBldr.addConstructorArgReference(BeanIds.FILTER_CHAINS);
    fcpBldr.addPropertyValue("filterChainValidator", new RootBeanDefinition(DefaultFilterChainValidator.class));
    BeanDefinition fcpBean = fcpBldr.getBeanDefinition();
    pc.registerBeanComponent(new BeanComponentDefinition(fcpBean, BeanIds.FILTER_CHAIN_PROXY));
    pc.getRegistry().registerAlias(BeanIds.FILTER_CHAIN_PROXY, BeanIds.SPRING_SECURITY_FILTER_CHAIN);
}

From source file:org.springframework.security.config.http.RememberMeBeanDefinitionParser.java

public BeanDefinition parse(Element element, ParserContext pc) {
    CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(),
            pc.extractSource(element));/*  ww w.j a  v  a2 s.c om*/
    pc.pushContainingComponent(compositeDef);

    String tokenRepository = element.getAttribute(ATT_TOKEN_REPOSITORY);
    String dataSource = element.getAttribute(ATT_DATA_SOURCE);
    String userServiceRef = element.getAttribute(ATT_USER_SERVICE_REF);
    String successHandlerRef = element.getAttribute(ATT_SUCCESS_HANDLER_REF);
    String rememberMeServicesRef = element.getAttribute(ATT_SERVICES_REF);
    String tokenValiditySeconds = element.getAttribute(ATT_TOKEN_VALIDITY);
    String useSecureCookie = element.getAttribute(ATT_SECURE_COOKIE);
    String remembermeParameter = element.getAttribute(ATT_FORM_REMEMBERME_PARAMETER);
    String remembermeCookie = element.getAttribute(ATT_REMEMBERME_COOKIE);
    Object source = pc.extractSource(element);

    RootBeanDefinition services = null;

    boolean dataSourceSet = StringUtils.hasText(dataSource);
    boolean tokenRepoSet = StringUtils.hasText(tokenRepository);
    boolean servicesRefSet = StringUtils.hasText(rememberMeServicesRef);
    boolean userServiceSet = StringUtils.hasText(userServiceRef);
    boolean useSecureCookieSet = StringUtils.hasText(useSecureCookie);
    boolean tokenValiditySet = StringUtils.hasText(tokenValiditySeconds);
    boolean remembermeParameterSet = StringUtils.hasText(remembermeParameter);
    boolean remembermeCookieSet = StringUtils.hasText(remembermeCookie);

    if (servicesRefSet && (dataSourceSet || tokenRepoSet || userServiceSet || tokenValiditySet
            || useSecureCookieSet || remembermeParameterSet || remembermeCookieSet)) {
        pc.getReaderContext()
                .error(ATT_SERVICES_REF + " can't be used in combination with attributes "
                        + ATT_TOKEN_REPOSITORY + "," + ATT_DATA_SOURCE + ", " + ATT_USER_SERVICE_REF + ", "
                        + ATT_TOKEN_VALIDITY + ", " + ATT_SECURE_COOKIE + ", " + ATT_FORM_REMEMBERME_PARAMETER
                        + " or " + ATT_REMEMBERME_COOKIE, source);
    }

    if (dataSourceSet && tokenRepoSet) {
        pc.getReaderContext()
                .error("Specify " + ATT_TOKEN_REPOSITORY + " or " + ATT_DATA_SOURCE + " but not both", source);
    }

    boolean isPersistent = dataSourceSet | tokenRepoSet;

    if (isPersistent) {
        Object tokenRepo;
        services = new RootBeanDefinition(PersistentTokenBasedRememberMeServices.class);

        if (tokenRepoSet) {
            tokenRepo = new RuntimeBeanReference(tokenRepository);
        } else {
            tokenRepo = new RootBeanDefinition(JdbcTokenRepositoryImpl.class);
            ((BeanDefinition) tokenRepo).getPropertyValues().addPropertyValue("dataSource",
                    new RuntimeBeanReference(dataSource));
        }
        services.getConstructorArgumentValues().addIndexedArgumentValue(2, tokenRepo);
    } else if (!servicesRefSet) {
        services = new RootBeanDefinition(TokenBasedRememberMeServices.class);
    }

    String servicesName;

    if (services != null) {
        RootBeanDefinition uds = new RootBeanDefinition();
        uds.setFactoryBeanName(BeanIds.USER_DETAILS_SERVICE_FACTORY);
        uds.setFactoryMethodName("cachingUserDetailsService");
        uds.getConstructorArgumentValues().addGenericArgumentValue(userServiceRef);

        services.getConstructorArgumentValues().addGenericArgumentValue(key);
        services.getConstructorArgumentValues().addGenericArgumentValue(uds);
        // tokenRepo is already added if it is a
        // PersistentTokenBasedRememberMeServices

        if (useSecureCookieSet) {
            services.getPropertyValues().addPropertyValue("useSecureCookie", Boolean.valueOf(useSecureCookie));
        }

        if (tokenValiditySet) {
            boolean isTokenValidityNegative = tokenValiditySeconds.startsWith("-");
            if (isTokenValidityNegative && isPersistent) {
                pc.getReaderContext().error(ATT_TOKEN_VALIDITY + " cannot be negative if using"
                        + " a persistent remember-me token repository", source);
            }
            services.getPropertyValues().addPropertyValue("tokenValiditySeconds", tokenValiditySeconds);
        }

        if (remembermeParameterSet) {
            services.getPropertyValues().addPropertyValue("parameter", remembermeParameter);
        }

        if (remembermeCookieSet) {
            services.getPropertyValues().addPropertyValue("cookieName", remembermeCookie);
        }

        services.setSource(source);
        servicesName = pc.getReaderContext().generateBeanName(services);
        pc.registerBeanComponent(new BeanComponentDefinition(services, servicesName));
    } else {
        servicesName = rememberMeServicesRef;
    }

    if (StringUtils.hasText(element.getAttribute(ATT_SERVICES_ALIAS))) {
        pc.getRegistry().registerAlias(servicesName, element.getAttribute(ATT_SERVICES_ALIAS));
    }

    this.rememberMeServicesId = servicesName;

    BeanDefinitionBuilder filter = BeanDefinitionBuilder
            .rootBeanDefinition(RememberMeAuthenticationFilter.class);
    filter.getRawBeanDefinition().setSource(source);

    if (StringUtils.hasText(successHandlerRef)) {
        filter.addPropertyReference("authenticationSuccessHandler", successHandlerRef);
    }

    filter.addConstructorArgValue(authenticationManager);
    filter.addConstructorArgReference(servicesName);

    pc.popAndRegisterContainingComponent();

    return filter.getBeanDefinition();
}

From source file:org.springframework.security.config.ldap.LdapProviderBeanDefinitionParser.java

public BeanDefinition parse(Element elt, ParserContext parserContext) {
    RuntimeBeanReference contextSource = LdapUserServiceBeanDefinitionParser.parseServerReference(elt,
            parserContext);/* w  w w  .j  av  a  2 s.  co  m*/

    BeanDefinition searchBean = LdapUserServiceBeanDefinitionParser.parseSearchBean(elt, parserContext);
    String userDnPattern = elt.getAttribute(ATT_USER_DN_PATTERN);

    String[] userDnPatternArray = new String[0];

    if (StringUtils.hasText(userDnPattern)) {
        userDnPatternArray = new String[] { userDnPattern };
        // TODO: Validate the pattern and make sure it is a valid DN.
    } else if (searchBean == null) {
        logger.info("No search information or DN pattern specified. Using default search filter '"
                + DEF_USER_SEARCH_FILTER + "'");
        BeanDefinitionBuilder searchBeanBuilder = BeanDefinitionBuilder
                .rootBeanDefinition(LdapUserServiceBeanDefinitionParser.LDAP_SEARCH_CLASS);
        searchBeanBuilder.getRawBeanDefinition().setSource(elt);
        searchBeanBuilder.addConstructorArgValue("");
        searchBeanBuilder.addConstructorArgValue(DEF_USER_SEARCH_FILTER);
        searchBeanBuilder.addConstructorArgValue(contextSource);
        searchBean = searchBeanBuilder.getBeanDefinition();
    }

    BeanDefinitionBuilder authenticatorBuilder = BeanDefinitionBuilder.rootBeanDefinition(BIND_AUTH_CLASS);
    Element passwordCompareElt = DomUtils.getChildElementByTagName(elt, Elements.LDAP_PASSWORD_COMPARE);

    if (passwordCompareElt != null) {
        authenticatorBuilder = BeanDefinitionBuilder.rootBeanDefinition(PASSWD_AUTH_CLASS);

        String passwordAttribute = passwordCompareElt.getAttribute(ATT_USER_PASSWORD);
        if (StringUtils.hasText(passwordAttribute)) {
            authenticatorBuilder.addPropertyValue("passwordAttributeName", passwordAttribute);
        }

        Element passwordEncoderElement = DomUtils.getChildElementByTagName(passwordCompareElt,
                Elements.PASSWORD_ENCODER);
        String hash = passwordCompareElt.getAttribute(ATT_HASH);

        if (passwordEncoderElement != null) {
            if (StringUtils.hasText(hash)) {
                parserContext.getReaderContext().warning(
                        "Attribute 'hash' cannot be used with 'password-encoder' and " + "will be ignored.",
                        parserContext.extractSource(elt));
            }
            PasswordEncoderParser pep = new PasswordEncoderParser(passwordEncoderElement, parserContext);
            authenticatorBuilder.addPropertyValue("passwordEncoder", pep.getPasswordEncoder());
        } else if (StringUtils.hasText(hash)) {
            authenticatorBuilder.addPropertyValue("passwordEncoder",
                    PasswordEncoderParser.createPasswordEncoderBeanDefinition(hash, false));
        }
    }

    authenticatorBuilder.addConstructorArgValue(contextSource);
    authenticatorBuilder.addPropertyValue("userDnPatterns", userDnPatternArray);

    if (searchBean != null) {
        authenticatorBuilder.addPropertyValue("userSearch", searchBean);
    }

    BeanDefinitionBuilder ldapProvider = BeanDefinitionBuilder.rootBeanDefinition(PROVIDER_CLASS);
    ldapProvider.addConstructorArgValue(authenticatorBuilder.getBeanDefinition());
    ldapProvider.addConstructorArgValue(
            LdapUserServiceBeanDefinitionParser.parseAuthoritiesPopulator(elt, parserContext));
    ldapProvider.addPropertyValue("userDetailsContextMapper",
            LdapUserServiceBeanDefinitionParser.parseUserDetailsClassOrUserMapperRef(elt, parserContext));

    return ldapProvider.getBeanDefinition();
}

From source file:org.springframework.security.config.ldap.LdapServerBeanDefinitionParser.java

/**
 * Will be called if no url attribute is supplied.
 *
 * Registers beans to create an embedded apache directory server.
 *
 * @return the BeanDefinition for the ContextSource for the embedded server.
 *
 * @see ApacheDSContainer//from  w  w w. j a va2s . co  m
 */
private RootBeanDefinition createEmbeddedServer(Element element, ParserContext parserContext) {
    Object source = parserContext.extractSource(element);

    String suffix = element.getAttribute(ATT_ROOT_SUFFIX);

    if (!StringUtils.hasText(suffix)) {
        suffix = OPT_DEFAULT_ROOT_SUFFIX;
    }

    String port = element.getAttribute(ATT_PORT);

    if (!StringUtils.hasText(port)) {
        port = getDefaultPort();
        if (logger.isDebugEnabled()) {
            logger.debug("Using default port of " + port);
        }
    }

    String url = "ldap://127.0.0.1:" + port + "/" + suffix;

    BeanDefinitionBuilder contextSource = BeanDefinitionBuilder.rootBeanDefinition(CONTEXT_SOURCE_CLASS);
    contextSource.addConstructorArgValue(url);
    contextSource.addPropertyValue("userDn", "uid=admin,ou=system");
    contextSource.addPropertyValue("password", "secret");

    RootBeanDefinition apacheContainer = new RootBeanDefinition(
            "org.springframework.security.ldap.server.ApacheDSContainer", null, null);
    apacheContainer.setSource(source);
    apacheContainer.getConstructorArgumentValues().addGenericArgumentValue(suffix);

    String ldifs = element.getAttribute(ATT_LDIF_FILE);
    if (!StringUtils.hasText(ldifs)) {
        ldifs = OPT_DEFAULT_LDIF_FILE;
    }

    apacheContainer.getConstructorArgumentValues().addGenericArgumentValue(ldifs);
    apacheContainer.getPropertyValues().addPropertyValue("port", port);

    logger.info("Embedded LDAP server bean definition created for URL: " + url);

    if (parserContext.getRegistry().containsBeanDefinition(BeanIds.EMBEDDED_APACHE_DS)) {
        parserContext.getReaderContext()
                .error("Only one embedded server bean is allowed per application context", element);
    }

    parserContext.getRegistry().registerBeanDefinition(BeanIds.EMBEDDED_APACHE_DS, apacheContainer);

    return (RootBeanDefinition) contextSource.getBeanDefinition();
}

From source file:org.springframework.security.config.message.MessageSecurityBeanDefinitionParser.java

/**
 * @param element/*  w w w.j a v  a2  s .  c  o  m*/
 * @param parserContext
 * @return
 */
public BeanDefinition parse(Element element, ParserContext parserContext) {
    BeanDefinitionRegistry registry = parserContext.getRegistry();
    XmlReaderContext context = parserContext.getReaderContext();

    ManagedMap<BeanDefinition, String> matcherToExpression = new ManagedMap<BeanDefinition, String>();

    String id = element.getAttribute(ID_ATTR);

    List<Element> interceptMessages = DomUtils.getChildElementsByTagName(element, Elements.INTERCEPT_MESSAGE);
    for (Element interceptMessage : interceptMessages) {
        String matcherPattern = interceptMessage.getAttribute(PATTERN_ATTR);
        String accessExpression = interceptMessage.getAttribute(ACCESS_ATTR);
        BeanDefinitionBuilder matcher = BeanDefinitionBuilder
                .rootBeanDefinition(SimpDestinationMessageMatcher.class);
        matcher.addConstructorArgValue(matcherPattern);
        matcherToExpression.put(matcher.getBeanDefinition(), accessExpression);
    }

    BeanDefinitionBuilder mds = BeanDefinitionBuilder
            .rootBeanDefinition(ExpressionBasedMessageSecurityMetadataSourceFactory.class);
    mds.setFactoryMethod("createExpressionMessageMetadataSource");
    mds.addConstructorArgValue(matcherToExpression);

    String mdsId = context.registerWithGeneratedName(mds.getBeanDefinition());

    ManagedList<BeanDefinition> voters = new ManagedList<BeanDefinition>();
    voters.add(new RootBeanDefinition(MessageExpressionVoter.class));
    BeanDefinitionBuilder adm = BeanDefinitionBuilder.rootBeanDefinition(ConsensusBased.class);
    adm.addConstructorArgValue(voters);

    BeanDefinitionBuilder inboundChannelSecurityInterceptor = BeanDefinitionBuilder
            .rootBeanDefinition(ChannelSecurityInterceptor.class);
    inboundChannelSecurityInterceptor.addConstructorArgValue(registry.getBeanDefinition(mdsId));
    inboundChannelSecurityInterceptor.addPropertyValue("accessDecisionManager", adm.getBeanDefinition());
    String inSecurityInterceptorName = context
            .registerWithGeneratedName(inboundChannelSecurityInterceptor.getBeanDefinition());

    if (StringUtils.hasText(id)) {
        registry.registerAlias(inSecurityInterceptorName, id);
    } else {
        BeanDefinitionBuilder mspp = BeanDefinitionBuilder
                .rootBeanDefinition(MessageSecurityPostProcessor.class);
        mspp.addConstructorArgValue(inSecurityInterceptorName);
        context.registerWithGeneratedName(mspp.getBeanDefinition());
    }

    return null;
}