Example usage for org.springframework.util StringUtils hasLength

List of usage examples for org.springframework.util StringUtils hasLength

Introduction

In this page you can find the example usage for org.springframework.util StringUtils hasLength.

Prototype

public static boolean hasLength(@Nullable String str) 

Source Link

Document

Check that the given String is neither null nor of length 0.

Usage

From source file:org.apache.roller.weblogger.ui.core.security.CrowdAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                    "Only UsernamePasswordAuthenticationToken is supported"));

    UsernamePasswordAuthenticationToken authenticationToken = null;
    if (crowdClient != null) {
        UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;
        String password = (String) authentication.getCredentials();
        String username = userToken.getName();

        Assert.notNull(password, "Null password was supplied in authentication token");

        if (!StringUtils.hasLength(username)) {
            throw new BadCredentialsException(
                    messages.getMessage("CrowdAuthenticationProvider.emptyUsername", "Empty Username"));
        }/*  w w  w . j av a  2  s . c o m*/

        if (password.length() == 0) {
            LOG.debug("Rejecting empty password for user " + username);
            throw new BadCredentialsException(
                    messages.getMessage("CrowdAuthenticationProvider.emptyPassword", "Empty Password"));
        }

        try {

            User user = crowdClient.authenticateUser(authentication.getName(),
                    authentication.getCredentials().toString());

            GrantedAuthority[] grantedAuthorities = getGrantedAuthorities(user);
            // this is the required constructor, since we don't know any of the boolean values
            // and we can assume if the employee is active and we have gotten this far, these values
            // can be set to the isActive() field on the crowd User object.
            // NOTE: null values for timeZone and locale are okay, they are dealt with at another level.
            CrowdRollerUserDetails crowdRollerUserDetails = new CrowdRollerUserDetails(user,
                    authentication.getCredentials().toString(), crowdTimezone, crowdLocale, grantedAuthorities);

            authenticationToken = new UsernamePasswordAuthenticationToken(crowdRollerUserDetails,
                    authentication.getCredentials(), grantedAuthorities);

        } catch (UserNotFoundException e) {
            throw new UsernameNotFoundException(e.getMessage(), e);
        } catch (InactiveAccountException e) {
            throw new DisabledException(e.getMessage(), e);
        } catch (ExpiredCredentialException e) {
            throw new CredentialsExpiredException(e.getMessage(), e);
        } catch (InvalidAuthenticationException e) {
            throw new BadCredentialsException(e.getMessage(), e);
        } catch (ApplicationPermissionException e) {
            throw new AuthenticationServiceException(e.getMessage(), e);
        } catch (OperationFailedException e) {
            throw new AuthenticationServiceException(e.getMessage(), e);
        }
    }
    return authenticationToken;
}

From source file:org.beangle.security.web.auth.logout.LogoutFilter.java

/**
 * Returns the target URL to redirect to after logout.
 * <p>//  ww w.j  a  v a  2 s  .  co  m
 * By default it will check for a <tt>logoutSuccessUrl</tt> parameter in the request and use
 * this. If that isn't present it will use the configured <tt>logoutSuccessUrl</tt>. If this
 * hasn't been set it will check the Referer header and use the URL from there.
 */
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
    String targetUrl = request.getParameter("logoutSuccessUrl");

    if (!StringUtils.hasLength(targetUrl)) {
        targetUrl = getLogoutSuccessUrl();
    }

    if (!StringUtils.hasLength(targetUrl)) {
        targetUrl = request.getHeader("Referer");
    }

    if (!StringUtils.hasLength(targetUrl)) {
        targetUrl = "/";
    }

    return targetUrl;
}

From source file:org.cloudfoundry.identity.uaa.client.ClientAdminEndpoints.java

@RequestMapping(value = "/oauth/clients", method = RequestMethod.GET)
@ResponseBody/*  w ww. ja v  a  2s.  c o m*/
public SearchResults<?> listClientDetails(
        @RequestParam(value = "attributes", required = false) String attributesCommaSeparated,
        @RequestParam(required = false, defaultValue = "client_id pr") String filter,
        @RequestParam(required = false, defaultValue = "client_id") String sortBy,
        @RequestParam(required = false, defaultValue = "ascending") String sortOrder,
        @RequestParam(required = false, defaultValue = "1") int startIndex,
        @RequestParam(required = false, defaultValue = "100") int count) throws Exception {
    List<ClientDetails> result = new ArrayList<ClientDetails>();
    List<ClientDetails> clients;
    try {
        clients = clientDetailsService.query(filter, sortBy, "ascending".equalsIgnoreCase(sortOrder));
        if (count > clients.size()) {
            count = clients.size();
        }
    } catch (IllegalArgumentException e) {
        String msg = "Invalid filter expression: [" + filter + "]";
        if (StringUtils.hasText(sortBy)) {
            msg += " [" + sortBy + "]";
        }
        throw new UaaException(msg, HttpStatus.BAD_REQUEST.value());
    }
    for (ClientDetails client : UaaPagingUtils.subList(clients, startIndex, count)) {
        result.add(removeSecret(client));
    }

    if (!StringUtils.hasLength(attributesCommaSeparated)) {
        return new SearchResults<ClientDetails>(Arrays.asList(SCIM_CLIENTS_SCHEMA_URI), result, startIndex,
                count, clients.size());
    }

    String[] attributes = attributesCommaSeparated.split(",");
    try {
        return SearchResultsFactory.buildSearchResultFrom(result, startIndex, count, clients.size(), attributes,
                attributeNameMapper, Arrays.asList(SCIM_CLIENTS_SCHEMA_URI));
    } catch (SpelParseException e) {
        throw new UaaException("Invalid attributes: [" + attributesCommaSeparated + "]",
                HttpStatus.BAD_REQUEST.value());
    } catch (SpelEvaluationException e) {
        throw new UaaException("Invalid attributes: [" + attributesCommaSeparated + "]",
                HttpStatus.BAD_REQUEST.value());
    }
}

From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenServices.java

@Override
public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {

    OAuth2RefreshToken refreshToken = createRefreshToken(authentication);

    String userId = null;/*  ww w  .  j av  a  2 s.c  o m*/
    String username = null;
    String userEmail = null;

    Collection<GrantedAuthority> clientScopes = null;
    // Clients should really by different kinds of users
    if (authentication.isClientOnly()) {
        ClientDetails client = clientDetailsService.loadClientByClientId(authentication.getName());
        userId = client.getClientId();
        clientScopes = client.getAuthorities();
    } else {
        userId = getUserId(authentication);
        UaaUser user = userDatabase.retrieveUserById(userId);
        username = user.getUsername();
        userEmail = user.getEmail();
    }

    String clientId = authentication.getOAuth2Request().getClientId();
    Set<String> userScopes = authentication.getOAuth2Request().getScope();
    String grantType = authentication.getOAuth2Request().getRequestParameters().get("grant_type");

    Set<String> modifiableUserScopes = new LinkedHashSet<String>();
    modifiableUserScopes.addAll(userScopes);
    String externalScopes = authentication.getOAuth2Request().getRequestParameters().get("external_scopes");
    if (null != externalScopes && StringUtils.hasLength(externalScopes)) {
        modifiableUserScopes.addAll(OAuth2Utils.parseParameterList(externalScopes));
    }

    Map<String, String> additionalAuthorizationAttributes = getAdditionalAuthorizationAttributes(
            authentication.getOAuth2Request().getRequestParameters().get("authorities"));

    ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
    Integer validity = client.getAccessTokenValiditySeconds();
    Set<String> responseTypes = extractResponseTypes(authentication);
    OAuth2AccessToken accessToken = createAccessToken(userId, username, userEmail,
            validity != null ? validity.intValue() : accessTokenValiditySeconds, clientScopes,
            modifiableUserScopes, clientId, authentication.getOAuth2Request().getResourceIds(), grantType,
            refreshToken != null ? refreshToken.getValue() : null, additionalAuthorizationAttributes,
            responseTypes);

    return accessToken;
}

From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenServices.java

/**
 * This method searches the authorities in the request for
 * additionalAuthorizationAttributes/*from  w  w  w. java2  s  .c o m*/
 * and returns a map of these attributes that will later be added to the
 * token
 * 
 * @param authoritiesJson
 * @return
 */
private Map<String, String> getAdditionalAuthorizationAttributes(String authoritiesJson) {
    if (StringUtils.hasLength(authoritiesJson)) {
        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> authorities = mapper.readValue(authoritiesJson.getBytes(), Map.class);
            @SuppressWarnings("unchecked")
            Map<String, String> additionalAuthorizationAttributes = (Map<String, String>) authorities
                    .get("az_attr");

            return additionalAuthorizationAttributes;
        } catch (Throwable t) {
            logger.error("Unable to read additionalAuthorizationAttributes", t);
        }
    }

    return null;
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServices.java

private Map<String, ?> createJWTAccessToken(OAuth2AccessToken token, String userId, UaaUser user,
        Date userAuthenticationTime, Collection<GrantedAuthority> clientScopes, Set<String> requestedScopes,
        String clientId, Set<String> resourceIds, String grantType, String refreshToken,
        String revocableHashSignature, boolean revocable) {

    Map<String, Object> response = new LinkedHashMap<String, Object>();

    response.put(JTI, token.getAdditionalInformation().get(JTI));
    response.putAll(token.getAdditionalInformation());

    response.put(SUB, clientId);/*from  w ww  . j av  a 2s  .  com*/
    if (null != clientScopes) {
        response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(clientScopes));
    }

    response.put(OAuth2AccessToken.SCOPE, requestedScopes);
    response.put(CLIENT_ID, clientId);
    response.put(CID, clientId);
    response.put(AZP, clientId); //openId Connect
    if (revocable) {
        response.put(REVOCABLE, true);
    }

    if (null != grantType) {
        response.put(GRANT_TYPE, grantType);
    }
    if (user != null && userId != null) {
        response.put(USER_ID, userId);
        String origin = user.getOrigin();
        if (StringUtils.hasLength(origin)) {
            response.put(ORIGIN, origin);
        }
        String username = user.getUsername();
        response.put(USER_NAME, username == null ? userId : username);
        String userEmail = user.getEmail();
        if (userEmail != null) {
            response.put(EMAIL, userEmail);
        }
        if (userAuthenticationTime != null) {
            response.put(AUTH_TIME, userAuthenticationTime.getTime() / 1000);
        }
        response.put(SUB, userId);
    }

    if (StringUtils.hasText(revocableHashSignature)) {
        response.put(REVOCATION_SIGNATURE, revocableHashSignature);
    }

    response.put(IAT, System.currentTimeMillis() / 1000);
    response.put(EXP, token.getExpiration().getTime() / 1000);

    if (getTokenEndpoint() != null) {
        response.put(ISS, getTokenEndpoint());
        response.put(ZONE_ID, IdentityZoneHolder.get().getId());
    }

    // TODO: different values for audience in the AT and RT. Need to sync
    // them up
    response.put(AUD, resourceIds);

    for (String excludedClaim : getExcludedClaims()) {
        response.remove(excludedClaim);
    }

    return response;
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServices.java

/**
 * This method searches the authorities in the request for
 * additionalAuthorizationAttributes/*ww  w. ja v a  2  s .c om*/
 * and returns a map of these attributes that will later be added to the
 * token
 *
 * @param authoritiesJson
 * @return
 */
private Map<String, String> getAdditionalAuthorizationAttributes(String authoritiesJson) {
    if (StringUtils.hasLength(authoritiesJson)) {
        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> authorities = JsonUtils.readValue(authoritiesJson,
                    new TypeReference<Map<String, Object>>() {
                    });
            @SuppressWarnings("unchecked")
            Map<String, String> additionalAuthorizationAttributes = (Map<String, String>) authorities
                    .get("az_attr");

            return additionalAuthorizationAttributes;
        } catch (Throwable t) {
            logger.error("Unable to read additionalAuthorizationAttributes", t);
        }
    }

    return null;
}

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.ScimGroupEndpoints.java

@RequestMapping(value = { "/Groups" }, method = RequestMethod.GET)
@ResponseBody/*from w ww  . j a v  a  2 s .  c o  m*/
public SearchResults<?> listGroups(
        @RequestParam(value = "attributes", required = false) String attributesCommaSeparated,
        @RequestParam(required = false, defaultValue = "id pr") String filter,
        @RequestParam(required = false, defaultValue = "created") String sortBy,
        @RequestParam(required = false, defaultValue = "ascending") String sortOrder,
        @RequestParam(required = false, defaultValue = "1") int startIndex,
        @RequestParam(required = false, defaultValue = "100") int count) {

    List<ScimGroup> result;
    try {
        result = dao.query(filter, sortBy, "ascending".equalsIgnoreCase(sortOrder));
    } catch (IllegalArgumentException e) {
        throw new ScimException("Invalid filter expression: [" + filter + "]", HttpStatus.BAD_REQUEST);
    }

    List<ScimGroup> input = filterForCurrentUser(result, startIndex, count);

    if (!StringUtils.hasLength(attributesCommaSeparated)) {
        return new SearchResults<>(Arrays.asList(ScimCore.SCHEMAS), input, startIndex, count, result.size());
    }

    AttributeNameMapper mapper = new SimpleAttributeNameMapper(Collections.emptyMap());

    String[] attributes = attributesCommaSeparated.split(",");
    try {
        return SearchResultsFactory.buildSearchResultFrom(input, startIndex, count, result.size(), attributes,
                mapper, Arrays.asList(ScimCore.SCHEMAS));
    } catch (JsonPathException e) {
        throw new ScimException("Invalid attributes: [" + attributesCommaSeparated + "]",
                HttpStatus.BAD_REQUEST);
    }
}

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.ScimUserEndpoints.java

@RequestMapping(value = "/Users", method = RequestMethod.GET)
@ResponseBody//from w  ww . ja v a 2  s . c  om
public SearchResults<?> findUsers(
        @RequestParam(value = "attributes", required = false) String attributesCommaSeparated,
        @RequestParam(required = false, defaultValue = "id pr") String filter,
        @RequestParam(required = false, defaultValue = "created") String sortBy,
        @RequestParam(required = false, defaultValue = "ascending") String sortOrder,
        @RequestParam(required = false, defaultValue = "1") int startIndex,
        @RequestParam(required = false, defaultValue = "100") int count) {

    if (startIndex < 1) {
        startIndex = 1;
    }

    List<ScimUser> input = new ArrayList<ScimUser>();
    List<ScimUser> result;
    try {
        result = dao.query(filter, sortBy, sortOrder.equals("ascending"));
        for (ScimUser user : UaaPagingUtils.subList(result, startIndex, count)) {
            if (attributesCommaSeparated == null || attributesCommaSeparated.matches("(?i)groups")
                    || attributesCommaSeparated.isEmpty()) {
                syncGroups(user);
            }
            if (attributesCommaSeparated == null || attributesCommaSeparated.matches("(?i)approvals")
                    || attributesCommaSeparated.isEmpty()) {
                syncApprovals(user);
            }
            input.add(user);
        }
    } catch (IllegalArgumentException e) {
        String msg = "Invalid filter expression: [" + filter + "]";
        if (StringUtils.hasText(sortBy)) {
            msg += " [" + sortBy + "]";
        }
        throw new ScimException(msg, HttpStatus.BAD_REQUEST);
    }

    if (!StringUtils.hasLength(attributesCommaSeparated)) {
        // Return all user data
        return new SearchResults<ScimUser>(Arrays.asList(ScimCore.SCHEMAS), input, startIndex, count,
                result.size());
    }

    Map<String, String> attributeMap = new HashMap<>();
    attributeMap.put("^emails\\.", "emails[*].");
    attributeMap.put("familyName", "name.familyName");
    attributeMap.put("givenName", "name.givenName");
    AttributeNameMapper mapper = new SimpleAttributeNameMapper(attributeMap);

    String[] attributes = attributesCommaSeparated.split(",");
    try {
        return SearchResultsFactory.buildSearchResultFrom(input, startIndex, count, result.size(), attributes,
                mapper, Arrays.asList(ScimCore.SCHEMAS));
    } catch (JsonPathException e) {
        throw new ScimException("Invalid attributes: [" + attributesCommaSeparated + "]",
                HttpStatus.BAD_REQUEST);
    }
}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.AnnotationFilterInvocationDefinition.java

@Override
protected String determineUrl(final FilterInvocation filterInvocation) {
    HttpServletRequest request = filterInvocation.getHttpRequest();
    HttpServletResponse response = filterInvocation.getHttpResponse();
    ServletContext servletContext = ServletContextHolder.getServletContext();
    GrailsApplication application = ApplicationHolder.getApplication();

    GrailsWebRequest existingRequest = WebUtils.retrieveGrailsWebRequest();

    String requestUrl = request.getRequestURI().substring(request.getContextPath().length());

    String url = null;//  w ww  .  j a v a 2 s  .c  o m
    try {
        GrailsWebRequest grailsRequest = new GrailsWebRequest(request, response, servletContext);
        WebUtils.storeGrailsWebRequest(grailsRequest);

        Map<String, Object> savedParams = copyParams(grailsRequest);

        for (UrlMappingInfo mapping : _urlMappingsHolder.matchAll(requestUrl)) {
            configureMapping(mapping, grailsRequest, savedParams);

            url = findGrailsUrl(mapping, application);
            if (url != null) {
                break;
            }
        }
    } finally {
        if (existingRequest == null) {
            WebUtils.clearGrailsWebRequest();
        } else {
            WebUtils.storeGrailsWebRequest(existingRequest);
        }
    }

    if (!StringUtils.hasLength(url)) {
        // probably css/js/image
        url = requestUrl;
    }

    return lowercaseAndStripQuerystring(url);
}