Example usage for org.apache.shiro.util StringUtils hasText

List of usage examples for org.apache.shiro.util StringUtils hasText

Introduction

In this page you can find the example usage for org.apache.shiro.util StringUtils hasText.

Prototype

public static boolean hasText(String str) 

Source Link

Document

Check whether the given String has actual text.

Usage

From source file:au.org.theark.study.model.dao.LdapUserDao.java

License:Open Source License

/**
 * Use when you want to return ALL users from LDAP. Applies for a Super User and Study Admin only. The criteria is supplied in the userVO
 * /*from   w w w. j ava2 s  .c  o  m*/
 * @param userCriteriaVO
 * @return
 * @throws InvalidNameException
 */
public List<ArkUserVO> searchAllUsers(ArkUserVO userCriteriaVO) throws ArkSystemException {

    SecurityManager securityManager = ThreadContext.getSecurityManager();
    Subject currentUser = SecurityUtils.getSubject();
    List<ArkUserVO> userList = new ArrayList<ArkUserVO>();

    try {
        List<ArkUserRole> adminUserNameList = arkAuthorisationService.getArkSuperAdministratorList();
        if (securityManager.isPermitted(currentUser.getPrincipals(), PermissionConstants.CREATE)
                && securityManager.isPermitted(currentUser.getPrincipals(), PermissionConstants.UPDATE)
                && securityManager.isPermitted(currentUser.getPrincipals(), PermissionConstants.READ)) {

            log.debug("getBaseDn() " + ldapDataContextSource.getBasePeopleDn());// ou=arkUsers or whatever is configured in the context file.
            LdapName ldapName;
            try {

                AndFilter andFilter = new AndFilter();
                andFilter.and(new EqualsFilter("objectClass", "person"));

                ldapName = new LdapName(ldapDataContextSource.getBasePeopleDn());
                // if userId was specified
                /* User ID */
                if (StringUtils.hasText(userCriteriaVO.getUserName())) {
                    ldapName.add(new Rdn(Constants.CN, userCriteriaVO.getUserName()));
                    andFilter.and(new WhitespaceWildcardsFilter(Constants.CN, userCriteriaVO.getUserName()));
                }
                /* Given Name */
                if (StringUtils.hasText(userCriteriaVO.getFirstName())) {
                    ldapName.add(new Rdn(Constants.GIVEN_NAME, userCriteriaVO.getFirstName()));
                    andFilter.and(
                            new WhitespaceWildcardsFilter(Constants.GIVEN_NAME, userCriteriaVO.getFirstName()));
                }

                /* Surname Name */
                if (StringUtils.hasText(userCriteriaVO.getLastName())) {
                    ldapName.add(new Rdn(Constants.LAST_NAME, userCriteriaVO.getLastName()));
                    andFilter.and(
                            new WhitespaceWildcardsFilter(Constants.LAST_NAME, userCriteriaVO.getLastName()));
                }

                /* Email */
                if (StringUtils.hasText(userCriteriaVO.getEmail())) {
                    ldapName.add(new Rdn(Constants.EMAIL, userCriteriaVO.getEmail()));
                    andFilter.and(new WhitespaceWildcardsFilter(Constants.EMAIL, userCriteriaVO.getEmail()));
                }

                for (ArkUserRole superAdmin : adminUserNameList) {
                    ldapName.add(new Rdn(Constants.CN, superAdmin.getArkUser().getLdapUserName()));
                    Filter filter = new NotFilter(
                            new EqualsFilter(Constants.CN, superAdmin.getArkUser().getLdapUserName()));
                    andFilter.and(filter);
                }

                /* Status is not defined as yet in the schema */
                userList = ldapDataContextSource.getLdapTemplate().search(
                        ldapDataContextSource.getBasePeopleDn(), andFilter.encode(), new PersonContextMapper());
                log.debug("Size of list " + userList.size());
            } catch (InvalidNameException ine) {

                log.error("Exception occured in searchAllUsers " + ine);
                throw new ArkSystemException("A system errror occured");
            }
        }

    } catch (EntityNotFoundException e) {

        log.error("Exception occured in searchAllUsers " + e);
        throw new ArkSystemException("A system errror occured. ");
    }

    return userList;
}

From source file:au.org.theark.study.model.dao.LdapUserDao.java

License:Open Source License

/**
 * Retrieves a sub-set of users from LDAP. The memberCnList List<String> contains the list of userNames or CN, and ArkUserVO acts as a criteria
 * that will be applied when looking up the user. Not all users in the memberCnList will be returned, it also depends if the criteria matches with
 * the sub-set of users./*from   w  w w  . ja v a  2s . c o m*/
 * 
 * @param memberCnList
 * @param userCriteriaVO
 * @return
 */
public List<ArkUserVO> getPersonsByCn(List<String> memberCnList, ArkUserVO userCriteriaVO) {

    if (memberCnList == null || memberCnList.size() < 0) {
        return new ArrayList<ArkUserVO>();
    }

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", "person"));

    if (StringUtils.hasText(userCriteriaVO.getUserName())) {
        filter.and(new EqualsFilter(Constants.CN, userCriteriaVO.getUserName()));
    }

    /* Given Name */
    if (StringUtils.hasText(userCriteriaVO.getFirstName())) {
        filter.and(new EqualsFilter(Constants.GIVEN_NAME, userCriteriaVO.getFirstName()));
    }

    /* Surname Name */
    if (StringUtils.hasText(userCriteriaVO.getLastName())) {

        filter.and(new EqualsFilter(Constants.LAST_NAME, userCriteriaVO.getLastName()));
    }

    /* Email */
    if (StringUtils.hasText(userCriteriaVO.getEmail())) {

        filter.and(new EqualsFilter(Constants.EMAIL, userCriteriaVO.getEmail()));
    }

    OrFilter orFilter = new OrFilter();
    filter.and(orFilter);
    // Build the filter that matches the cn's and then apply the criteria
    for (Iterator<String> iterator = memberCnList.iterator(); iterator.hasNext();) {
        String userDN = iterator.next();
        orFilter.or(new EqualsFilter("cn", userDN));

        if (StringUtils.hasText(userCriteriaVO.getUserName())) {
            filter.and(new EqualsFilter(Constants.CN, userCriteriaVO.getUserName()));
        }
        /* Given Name */
        if (StringUtils.hasText(userCriteriaVO.getFirstName())) {
            filter.and(new EqualsFilter(Constants.GIVEN_NAME, userCriteriaVO.getFirstName()));
        }

        /* Surname Name */
        if (StringUtils.hasText(userCriteriaVO.getLastName())) {

            filter.and(new EqualsFilter(Constants.LAST_NAME, userCriteriaVO.getLastName()));
        }

        /* Email */
        if (StringUtils.hasText(userCriteriaVO.getEmail())) {

            filter.and(new EqualsFilter(Constants.EMAIL, userCriteriaVO.getEmail()));
        }
    }
    // TODO NN User a light version of PersonContextMapper, dont need to map password details.
    return ldapDataContextSource.getLdapTemplate().search(ldapDataContextSource.getBasePeopleDn(),
            filter.encode(), new PersonContextMapper());
}

From source file:au.org.theark.study.model.dao.LdapUserDao.java

License:Open Source License

/**
 * Looks up a particular user from LDAP using the username/login name for Ark System
 * //  w  ww  .j a v  a 2 s. c  o m
 * @param arkUserName
 * @return ArkUserVO
 * @throws ArkSystemException
 */
public ArkUserVO lookupArkUser(String arkUserName) throws ArkSystemException {

    SecurityManager securityManager = ThreadContext.getSecurityManager();
    Subject currentUser = SecurityUtils.getSubject();
    List<ArkUserVO> userList = new ArrayList<ArkUserVO>();

    if (securityManager.isPermitted(currentUser.getPrincipals(), PermissionConstants.CREATE)
            && securityManager.isPermitted(currentUser.getPrincipals(), PermissionConstants.UPDATE)
            && securityManager.isPermitted(currentUser.getPrincipals(), PermissionConstants.READ)) {

        log.debug("getBaseDn() " + ldapDataContextSource.getBasePeopleDn());// ou=arkUsers or whatever is configured in the context file.
        LdapName ldapName;
        try {

            AndFilter andFilter = new AndFilter();
            andFilter.and(new EqualsFilter("objectClass", "person"));

            ldapName = new LdapName(ldapDataContextSource.getBasePeopleDn());
            // if userId was specified
            /* User ID */
            if (StringUtils.hasText(arkUserName)) {
                ldapName.add(new Rdn(Constants.CN, arkUserName));
                andFilter.and(new EqualsFilter(Constants.CN, arkUserName));
            }

            userList = ldapDataContextSource.getLdapTemplate().search(ldapDataContextSource.getBasePeopleDn(),
                    andFilter.encode(), new PersonContextMapper());
            log.debug("Size of list " + userList.size());
        } catch (InvalidNameException ine) {

            log.error("Exception occured in lookupArkUser(String arkUserName) " + ine);
            throw new ArkSystemException("A system errror occured");
        }
    }
    ArkUserVO arkUserVO = new ArkUserVO();
    if (userList != null && userList.size() > 0) {
        arkUserVO = userList.get(0);
    }
    return arkUserVO;
}

From source file:com.ceecloud.shiro.CasRealm.java

License:Apache License

/**
 * Authenticates a user and retrieves its information.
 * //from   w ww.  ja v a  2  s.c  o  m
 * @param token the authentication token
 * @throws AuthenticationException if there is an error during authentication.
 */
@Override
@SuppressWarnings("unchecked")
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    CasToken casToken = (CasToken) token;
    if (token == null) {
        return null;
    }

    String ticket = (String) casToken.getCredentials();
    if (!StringUtils.hasText(ticket)) {
        return null;
    }

    TicketValidator ticketValidator = ensureTicketValidator();

    try {
        // contact CAS server to validate service ticket
        Assertion casAssertion = ticketValidator.validate(ticket, getCasService());
        // get principal, user id and attributes
        AttributePrincipal casPrincipal = casAssertion.getPrincipal();
        String userId = casPrincipal.getName();
        log.debug("Validate ticket : {} in CAS server : {} to retrieve user : {}",
                new Object[] { ticket, getCasServerUrlPrefix(), userId });

        Map<String, Object> attributes = casPrincipal.getAttributes();
        // refresh authentication token (user id + remember me)
        casToken.setUserId(userId);
        String rememberMeAttributeName = getRememberMeAttributeName();
        String rememberMeStringValue = (String) attributes.get(rememberMeAttributeName);
        boolean isRemembered = rememberMeStringValue != null && Boolean.parseBoolean(rememberMeStringValue);
        if (isRemembered) {
            casToken.setRememberMe(true);
        }
        // create simple authentication info
        List<Object> principals = CollectionUtils.asList(userId, attributes);
        PrincipalCollection principalCollection = new SimplePrincipalCollection(principals, getName());
        return new SimpleAuthenticationInfo(principalCollection, ticket);
    } catch (TicketValidationException e) {
        throw new CasAuthenticationException("Unable to validate ticket [" + ticket + "]", e);
    }
}

From source file:com.ceecloud.shiro.CasRealm.java

License:Apache License

/**
 * Split a string into a list of not empty and trimmed strings, delimiter is a comma.
 * /*from  w  w w .  j ava 2  s .co m*/
 * @param s the input string
 * @return the list of not empty and trimmed strings
 */
private List<String> split(String s) {
    List<String> list = new ArrayList<String>();
    String[] elements = StringUtils.split(s, ',');
    if (elements != null && elements.length > 0) {
        for (String element : elements) {
            if (StringUtils.hasText(element)) {
                list.add(element.trim());
            }
        }
    }
    return list;
}

From source file:com.centfor.frame.shiro.FrameShiroFilterFactoryBean.java

License:Apache License

private void applyLoginUrlIfNecessary(Filter filter) {
    String loginUrl = getLoginUrl();
    if (StringUtils.hasText(loginUrl) && (filter instanceof AccessControlFilter)) {
        AccessControlFilter acFilter = (AccessControlFilter) filter;
        //only apply the login url if they haven't explicitly configured one already:
        String existingLoginUrl = acFilter.getLoginUrl();
        if (AccessControlFilter.DEFAULT_LOGIN_URL.equals(existingLoginUrl)) {
            acFilter.setLoginUrl(loginUrl);
        }//from  w w  w .  j a va2  s.co m
    }
}

From source file:com.centfor.frame.shiro.FrameShiroFilterFactoryBean.java

License:Apache License

private void applySuccessUrlIfNecessary(Filter filter) {
    String successUrl = getSuccessUrl();
    if (StringUtils.hasText(successUrl) && (filter instanceof AuthenticationFilter)) {
        AuthenticationFilter authcFilter = (AuthenticationFilter) filter;
        //only apply the successUrl if they haven't explicitly configured one already:
        String existingSuccessUrl = authcFilter.getSuccessUrl();
        if (AuthenticationFilter.DEFAULT_SUCCESS_URL.equals(existingSuccessUrl)) {
            authcFilter.setSuccessUrl(successUrl);
        }/*from ww w  .ja  v  a2  s. c om*/
    }
}

From source file:com.centfor.frame.shiro.FrameShiroFilterFactoryBean.java

License:Apache License

private void applyUnauthorizedUrlIfNecessary(Filter filter) {
    String unauthorizedUrl = getUnauthorizedUrl();
    if (StringUtils.hasText(unauthorizedUrl) && (filter instanceof AuthorizationFilter)) {
        AuthorizationFilter authzFilter = (AuthorizationFilter) filter;
        //only apply the unauthorizedUrl if they haven't explicitly configured one already:
        String existingUnauthorizedUrl = authzFilter.getUnauthorizedUrl();
        if (existingUnauthorizedUrl == null) {
            authzFilter.setUnauthorizedUrl(unauthorizedUrl);
        }/*from   www.jav a2  s  .c  om*/
    }
}

From source file:com.dylan.shiro.infrastructure.shiro.CasRealm.java

License:Apache License

/**
 * Authenticates a user and retrieves its information.
 * /*from www.  j  a  v  a  2s .c  om*/
 * @param token the authentication token
 * @throws AuthenticationException if there is an error during authentication.
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    CasToken casToken = (CasToken) token;
    if (token == null) {
        return null;
    }

    String ticket = (String) casToken.getCredentials();
    if (!StringUtils.hasText(ticket)) {
        return null;
    }

    TicketValidator ticketValidator = ensureTicketValidator();

    try {
        // contact CAS server to validate service ticket
        Assertion casAssertion = ticketValidator.validate(ticket, getCasService());
        // get principal, user id and attributes
        AttributePrincipal casPrincipal = casAssertion.getPrincipal();
        String userId = casPrincipal.getName();
        log.debug("Validate ticket : {} in CAS server : {} to retrieve user : {}",
                new Object[] { ticket, getCasServerUrlPrefix(), userId });

        Map<String, Object> attributes = casPrincipal.getAttributes();
        // refresh authentication token (user id + remember me)
        casToken.setUserId(userId);
        String rememberMeAttributeName = getRememberMeAttributeName();
        String rememberMeStringValue = (String) attributes.get(rememberMeAttributeName);
        boolean isRemembered = rememberMeStringValue != null && Boolean.parseBoolean(rememberMeStringValue);
        if (isRemembered) {
            casToken.setRememberMe(true);
        }
        // create simple authentication info
        List<Object> principals = CollectionUtils.asList(userId, attributes);
        PrincipalCollection principalCollection = new SimplePrincipalCollection(principals, getName());
        return new SimpleAuthenticationInfo(principalCollection, ticket);
    } catch (TicketValidationException e) {
        throw new CasAuthenticationException("Unable to validate ticket [" + ticket + "]", e);
    }
}

From source file:com.enioka.jqm.tools.Helpers.java

License:Open Source License

static void checkConfiguration(String nodeName, EntityManager em) {
    // Node/* w w  w .  ja v  a 2s  . c  om*/
    long n = em.createQuery("SELECT COUNT(n) FROM Node n WHERE n.name = :l", Long.class)
            .setParameter("l", nodeName).getSingleResult();
    if (n == 0L) {
        throw new JqmInitError(
                "The node does not exist. It must be referenced (CLI option createnode) before it can be used");
    }
    Node nn = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName)
            .getSingleResult();

    if (!StringUtils.hasText(nn.getDlRepo()) || !StringUtils.hasText(nn.getRepo())
            || !StringUtils.hasText(nn.getTmpDirectory())) {
        throw new JqmInitError(
                "The node does not have all its paths specified. Check node configuration (or recreate it with the CLI).");
    }

    // Default queue
    long i = (Long) em.createQuery("SELECT COUNT(qu) FROM Queue qu where qu.defaultQueue = true")
            .getSingleResult();
    if (i == 0L) {
        throw new JqmInitError(
                "There is no default queue. Correct this (for example with CLI option -u, or with the web admin)");
    }
    if (i > 1L) {
        throw new JqmInitError(
                "There is more than one default queue. Correct this (for example with CLI option -u, or with the web admin)");
    }

    // Deployment parameters
    i = (Long) em.createQuery("SELECT COUNT(dp) FROM DeploymentParameter dp WHERE dp.node.name = :localnode",
            Long.class).setParameter("localnode", nodeName).getSingleResult();
    if (i == 0L) {
        jqmlogger.warn(
                "This node is not bound to any queue. Either use the GUI to bind it or use CLI option -u to bind it to the default queue");
    }

    // Roles
    i = em.createQuery("SELECT count(rr) from RRole rr WHERE rr.name = :rr", Long.class)
            .setParameter("rr", "administrator").getSingleResult();
    if (i == 0L) {
        throw new JqmInitError(
                "The 'administrator' role does not exist. It is needed for the APIs. Run CLI option -u to create it.");
    }

    // Mail session
    i = (Long) em.createQuery("SELECT COUNT(r) FROM JndiObjectResource r WHERE r.name = :nn")
            .setParameter("nn", "mail/default").getSingleResult();
    if (i == 0L) {
        throw new JqmInitError(
                "Mail session named mail/default does not exist but is required for the engine to run"
                        + ". Use CLI option -u to create an empty one or use the admin web GUI to create it.");
    }
}