Example usage for org.springframework.util StringUtils delimitedListToStringArray

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

Introduction

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

Prototype

public static String[] delimitedListToStringArray(@Nullable String str, @Nullable String delimiter) 

Source Link

Document

Take a String that is a delimited list and convert it into a String array.

Usage

From source file:org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices.java

public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();

    if ((cookies == null) || (cookies.length == 0)) {
        return null;
    }//from   w  ww .  jav a2 s  .  c  o m

    for (int i = 0; i < cookies.length; i++) {
        if (cookieName.equals(cookies[i].getName())) {
            String cookieValue = cookies[i].getValue();

            for (int j = 0; j < cookieValue.length() % 4; j++) {
                cookieValue = cookieValue + "=";
            }

            if (Base64.isArrayByteBase64(cookieValue.getBytes())) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Remember-me cookie detected");
                }

                // Decode token from Base64
                // format of token is:
                // username + ":" + expiryTime + ":" +
                // Md5Hex(username + ":" + expiryTime + ":" + password + ":"
                // + key)
                String cookieAsPlainText = new String(Base64.decodeBase64(cookieValue.getBytes()));
                String[] cookieTokens = StringUtils.delimitedListToStringArray(cookieAsPlainText, ":");

                if (cookieTokens.length == 3) {

                    long tokenExpiryTime;

                    try {
                        tokenExpiryTime = new Long(cookieTokens[1]).longValue();
                    } catch (NumberFormatException nfe) {
                        cancelCookie(request, response,
                                "Cookie token[1] did not contain a valid number (contained '" + cookieTokens[1]
                                        + "')");

                        return null;
                    }

                    if (isTokenExpired(tokenExpiryTime)) {
                        cancelCookie(request, response, "Cookie token[1] has expired (expired on '"
                                + new Date(tokenExpiryTime) + "'; current time is '" + new Date() + "')");

                        return null;
                    }

                    // Check the user exists
                    // Defer lookup until after expiry time checked, to
                    // possibly avoid expensive lookup
                    UserDetails userDetails = loadUserDetails(request, response, cookieTokens);

                    if (userDetails == null) {
                        cancelCookie(request, response, "Cookie token[0] contained username '" + cookieTokens[0]
                                + "' but was not found");
                        return null;
                    }

                    if (!isValidUserDetails(request, response, userDetails, cookieTokens)) {
                        return null;
                    }

                    // Check signature of token matches remaining details
                    // Must do this after user lookup, as we need the
                    // DAO-derived password
                    // If efficiency was a major issue, just add in a
                    // UserCache implementation,
                    // but recall this method is usually only called one per
                    // HttpSession
                    // (as if the token is valid, it will cause
                    // SecurityContextHolder population, whilst
                    // if invalid, will cause the cookie to be cancelled)
                    String expectedTokenSignature = makeTokenSignature(tokenExpiryTime, userDetails);

                    if (!expectedTokenSignature.equals(cookieTokens[2])) {
                        cancelCookie(request, response, "Cookie token[2] contained signature '"
                                + cookieTokens[2] + "' but expected '" + expectedTokenSignature + "'");

                        return null;
                    }

                    // By this stage we have a valid token
                    if (logger.isDebugEnabled()) {
                        logger.debug("Remember-me cookie accepted");
                    }

                    RememberMeAuthenticationToken auth = new RememberMeAuthenticationToken(this.key,
                            userDetails, userDetails.getAuthorities());
                    auth.setDetails(authenticationDetailsSource.buildDetails((HttpServletRequest) request));

                    return auth;
                } else {
                    cancelCookie(request, response, "Cookie token did not contain 3 tokens; decoded value was '"
                            + cookieAsPlainText + "'");

                    return null;
                }
            } else {
                cancelCookie(request, response,
                        "Cookie token was not Base64 encoded; value was '" + cookieValue + "'");

                return null;
            }
        }
    }

    return null;
}

From source file:org.alfresco.repo.importer.ImporterComponent.java

/**
 * Create a valid qname-based xpath/*from   w  w  w .j a va  2 s  .  co m*/
 * 
 * Note: 
 * - the localname will be truncated to 100 chars
 * - the localname should already be encoded for ISO 9075 (in case of MT bootstrap, the @ sign will be auto-encoded, see below)
 * 
 * Some examples:
 *      /
 *      sys:people/cm:admin
 *      /app:company_home/app:dictionary
 *      ../../cm:people_x0020_folder
 *      sys:people/cm:admin_x0040_test
 *      
 * @param path String
 * @return String
 */
private String createValidPath(String path) {
    StringBuffer validPath = new StringBuffer(path.length());
    String[] segments = StringUtils.delimitedListToStringArray(path, "/");
    for (int i = 0; i < segments.length; i++) {
        if (segments[i] != null && segments[i].length() > 0) {
            int colonIndex = segments[i].indexOf(QName.NAMESPACE_PREFIX);
            if (colonIndex == -1) {
                // eg. ".."
                validPath.append(segments[i]);
            } else {
                String[] qnameComponents = QName.splitPrefixedQName(segments[i]);

                String localName = QName.createValidLocalName(qnameComponents[1]);

                // MT: bootstrap of "alfrescoUserStore.xml" requires 'sys:people/cm:admin@tenant' to be encoded as 'sys:people/cm:admin_x0040_tenant' (for XPath)
                localName = localName.replace("@", "_x0040_");

                QName segmentQName = QName.createQName(qnameComponents[0], localName, namespaceService);
                validPath.append(segmentQName.toPrefixString());
            }
        }
        if (i < (segments.length - 1)) {
            validPath.append("/");
        }
    }
    return validPath.toString();
}

From source file:org.apache.roller.weblogger.ui.rendering.plugins.comments.LdapCommentAuthenticator.java

/**
 * Get the username string LDAP expects.
 * @param ldapDc// w w  w.  j a  v  a  2  s.  c  o m
 * @param ldapOu
 * @param ldapUser
 * @return
 */
private String getQualifedDc(String ldapDc, String ldapOu, String ldapUser) {
    String qualifedDc = "";
    for (String token : StringUtils.delimitedListToStringArray(ldapDc, ",")) {
        if (!qualifedDc.isEmpty()) {
            qualifedDc += ",";
        }
        qualifedDc += "dc=" + token;
    }

    String qualifedUser = "uid=" + ldapUser + ", ou=" + ldapOu + "," + qualifedDc;
    return qualifedUser;
}

From source file:org.eclipse.gemini.blueprint.extender.support.internal.ConfigUtils.java

/**
 * Return the directive value as a String. If the directive does not exist
 * or is invalid (wrong format) a null string will be returned.
 * //w ww . j a  v  a2s .  c o  m
 * @param header
 * @param directive
 * @return
 */
public static String getDirectiveValue(String header, String directive) {
    Assert.notNull(header, "not-null header required");
    Assert.notNull(directive, "not-null directive required");
    String[] directives = StringUtils.tokenizeToStringArray(header, DIRECTIVE_SEPARATOR);

    for (int i = 0; i < directives.length; i++) {
        String[] splittedDirective = StringUtils.delimitedListToStringArray(directives[i].trim(), EQUALS);
        if (splittedDirective.length == 2 && splittedDirective[0].equals(directive))
            return splittedDirective[1];
    }

    return null;
}

From source file:org.flowable.app.filter.FlowableCookieFilter.java

protected String[] decodeCookie(String cookieValue) throws InvalidCookieException {
    for (int j = 0; j < cookieValue.length() % 4; j++) {
        cookieValue = cookieValue + "=";
    }/*from  w  w  w.j av a2s.c  o  m*/

    if (!Base64.isBase64(cookieValue.getBytes())) {
        throw new InvalidCookieException(
                "Cookie token was not Base64 encoded; value was '" + cookieValue + "'");
    }

    String cookieAsPlainText = new String(Base64.decodeBase64(cookieValue.getBytes()));

    String[] tokens = StringUtils.delimitedListToStringArray(cookieAsPlainText, DELIMITER);

    if ((tokens[0].equalsIgnoreCase("http") || tokens[0].equalsIgnoreCase("https"))
            && tokens[1].startsWith("//")) {
        // Assume we've accidentally split a URL (OpenID identifier)
        String[] newTokens = new String[tokens.length - 1];
        newTokens[0] = tokens[0] + ":" + tokens[1];
        System.arraycopy(tokens, 2, newTokens, 1, newTokens.length - 1);
        tokens = newTokens;
    }

    return tokens;
}

From source file:org.impalaframework.web.servlet.ResourceServlet.java

private URL[] getRequestResourceURLs(HttpServletRequest request) throws MalformedURLException {

    String rawResourcePath = rawResourcePath(request);
    String appendedPaths = request.getParameter("appended");
    if (StringUtils.hasText(appendedPaths)) {
        rawResourcePath = rawResourcePath + "," + appendedPaths;
    }//  w w w. j  a v  a2 s .  c o m
    String[] localResourcePaths = StringUtils.delimitedListToStringArray(rawResourcePath, ",");
    URL[] resources = new URL[localResourcePaths.length];
    for (int i = 0; i < localResourcePaths.length; i++) {
        String localResourcePath = localResourcePaths[i];
        if (!isAllowed(localResourcePath)) {
            if (log.isWarnEnabled()) {
                log.warn("An attempt to access a protected resource at " + localResourcePath
                        + " was disallowed.");
            }
            return null;
        }
        URL resource = getServletContext().getResource(localResourcePath);
        if (resource == null) {
            String jarResourcePath = jarPathPrefix + localResourcePath;
            if (!isAllowed(jarResourcePath)) {
                if (log.isWarnEnabled()) {
                    log.warn("An attempt to access a protected resource at " + jarResourcePath
                            + " was disallowed.");
                }
                return null;
            }
            if (jarResourcePath.startsWith("/")) {
                jarResourcePath = jarResourcePath.substring(1);
            }
            if (log.isDebugEnabled()) {
                log.debug("Searching classpath for resource: " + jarResourcePath);
            }
            resource = ClassUtils.getDefaultClassLoader().getResource(jarResourcePath);
        }
        if (resource == null) {
            if (resources.length > 1) {
                log.debug("Combined resource not found: " + localResourcePath);
            }
            return null;
        } else {
            resources[i] = resource;
        }
    }
    return resources;
}

From source file:org.kuali.continuity.security.SecurityUtil.java

/**
 * Decodes the cookie and splits it into a set of token strings using the ":" delimiter.
 *
 * @param cookieValue the value obtained from the submitted cookie
 * @return the array of tokens./*from  ww  w.j  a v a 2s  . c om*/
 * @throws InvalidCookieException if the cookie was not base64 encoded.
 */
private static String[] decodeCookie(String cookieValue) throws InvalidCookieException {
    for (int j = 0; j < cookieValue.length() % 4; j++) {
        cookieValue = cookieValue + "=";
    }
    if (!Base64.isArrayByteBase64(cookieValue.getBytes())) {
        throw new InvalidCookieException(
                "Cookie token was not Base64 encoded; value was '" + cookieValue + "'");
    }
    String cookieAsPlainText = decode(cookieValue);
    return StringUtils.delimitedListToStringArray(cookieAsPlainText, "::");
}

From source file:org.lexevs.dao.database.utility.DefaultDatabaseUtility.java

/**
 * Do execute script.//from w  ww  . java  2 s  .  c o  m
 * 
 * @param scriptResource the script resource
 */
private void doExecuteScript(final String scriptResource) {
    if (scriptResource == null) {
        return;
    }
    TransactionTemplate transactionTemplate = new TransactionTemplate(
            new DataSourceTransactionManager(getDataSource()));
    transactionTemplate.execute(new TransactionCallback() {

        @SuppressWarnings("unchecked")
        public Object doInTransaction(TransactionStatus status) {
            JdbcTemplate jdbcTemplate = getJdbcTemplate();
            String[] scripts;
            try {
                scripts = StringUtils.delimitedListToStringArray(
                        stripComments(IOUtils.readLines(new StringReader(scriptResource))), ";");
            } catch (IOException e) {
                throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e);
            }
            for (int i = 0; i < scripts.length; i++) {
                String script = scripts[i].trim();
                if (StringUtils.hasText(script)) {
                    try {
                        jdbcTemplate.execute(script);
                    } catch (DataAccessException e) {
                        throw e;
                    }
                }
            }
            return null;
        }

    });

}

From source file:org.rill.bpm.api.support.XpathVarConvertTaskLifecycleInterceptor.java

protected static void generateByXpath(Map<String, Object> workflowParams, String engineRelateDataname,
        Map<String, Object> convertAndFilter) {

    String expressionText = engineRelateDataname.substring(ENGINE_VARIABLE_DEFINITION_PREFIX.length());
    String[] split = StringUtils.delimitedListToStringArray(expressionText, ENGINE_VARIABLE_DEFINITION_SPLIT);
    if (split.length > 1 && workflowParams.containsKey(split[0]) && workflowParams.get(split[0]) != null
            && ClassUtils.isPrimitiveOrWrapper(workflowParams.get(split[0]).getClass())) {
        throw new ProcessException("Can not generate engine variable " + engineRelateDataname
                + " from workflow param" + workflowParams.get(split[0]));
    }//  w  w  w  .jav a  2 s. c o  m

    try {
        if (split.length > 1 && workflowParams.containsKey(split[0]) && workflowParams.get(split[0]) != null) {
            String workflowParamValue = (workflowParams.get(split[0]) instanceof String)
                    ? workflowParams.get(split[0]).toString()
                    : XStreamSerializeHelper.serializeXml(split[0], workflowParams.get(split[0]));
            log.debug("After XStream serialize :" + workflowParamValue);
            // Check it is XML or not
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new ByteArrayInputStream(workflowParamValue.getBytes("UTF-8")));
            XPathFactory xFactory = XPathFactory.newInstance();
            XPath xpath = xFactory.newXPath();
            StringBuilder sb = new StringBuilder();
            sb.append("//");
            for (int i = 1; i < split.length; i++) {
                sb.append(split[i]);
                sb.append("/");
            }
            sb.append("text()");
            log.debug("Build xPath:" + sb.toString());
            XPathExpression expr = xpath.compile(sb.toString());
            String value = (String) expr.evaluate(doc, XPathConstants.STRING);
            if (StringUtils.hasText(value.toString())) {
                log.debug("Parse xPath:" + sb.toString() + " and save value:" + value);
                convertAndFilter.put(engineRelateDataname, value);
            } else {
                log.warn("Can not get value using XPath because invalid engine data name: "
                        + engineRelateDataname);
            }
        } else {
            log.warn("Can not get value using XPath because invalid engine data name:" + engineRelateDataname);
        }
    } catch (Exception e) {
        log.warn("Exception occurred when parse expression using Xpath. Do next one.", e);
    }

}

From source file:org.sipfoundry.sipxconfig.security.DigestProcessingFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("Can only process HttpServletRequest");
    }//  w w w  .jav a2  s  . c  om

    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException("Can only process HttpServletResponse");
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    String header = httpRequest.getHeader("Authorization");

    if (logger.isDebugEnabled()) {
        logger.debug("Authorization header received from user agent: " + header);
    }

    if ((header != null) && header.startsWith("Digest ")) {
        String section212response = header.substring(7);

        String[] headerEntries = StringSplitUtils.splitIgnoringQuotes(section212response, ',');
        Map headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");

        String username = (String) headerMap.get("username");
        String realm = (String) headerMap.get("realm");
        String nonce = (String) headerMap.get("nonce");
        String uri = (String) headerMap.get("uri");
        String responseDigest = (String) headerMap.get("response");
        String qop = (String) headerMap.get("qop"); // RFC 2617 extension
        String nc = (String) headerMap.get("nc"); // RFC 2617 extension
        String cnonce = (String) headerMap.get("cnonce"); // RFC 2617 extension

        // Check all required parameters were supplied (ie RFC 2069)
        if ((username == null) || (realm == null) || (nonce == null) || (uri == null) || (response == null)) {
            if (logger.isDebugEnabled()) {
                logger.debug("extracted username: '" + username + "'; realm: '" + username + "'; nonce: '"
                        + username + "'; uri: '" + username + "'; response: '" + username + "'");
            }

            fail(request, response,
                    new BadCredentialsException(messages.getMessage("DigestProcessingFilter.missingMandatory",
                            new Object[] { section212response },
                            "Missing mandatory digest value; received header {0}")));

            return;
        }

        // Check all required parameters for an "auth" qop were supplied (ie RFC 2617)
        if ("auth".equals(qop)) {
            if ((nc == null) || (cnonce == null)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("extracted nc: '" + nc + "'; cnonce: '" + cnonce + "'");
                }

                fail(request, response,
                        new BadCredentialsException(messages.getMessage("DigestProcessingFilter.missingAuth",
                                new Object[] { section212response },
                                "Missing mandatory digest value; received header {0}")));

                return;
            }
        }

        // Check realm name equals what we expected
        if (!this.getAuthenticationEntryPoint().getRealmName().equals(realm)) {
            fail(request, response,
                    new BadCredentialsException(messages.getMessage("DigestProcessingFilter.incorrectRealm",
                            new Object[] { realm, this.getAuthenticationEntryPoint().getRealmName() },
                            "Response realm name '{0}' does not match system realm name of '{1}'")));

            return;
        }

        // Check nonce was a Base64 encoded (as sent by DigestProcessingFilterEntryPoint)
        if (!Base64.isArrayByteBase64(nonce.getBytes())) {
            fail(request, response,
                    new BadCredentialsException(messages.getMessage("DigestProcessingFilter.nonceEncoding",
                            new Object[] { nonce }, "Nonce is not encoded in Base64; received nonce {0}")));

            return;
        }

        // Decode nonce from Base64
        // format of nonce is:
        //   base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key))
        String nonceAsPlainText = new String(Base64.decodeBase64(nonce.getBytes()));
        String[] nonceTokens = StringUtils.delimitedListToStringArray(nonceAsPlainText, ":");

        if (nonceTokens.length != 2) {
            fail(request, response,
                    new BadCredentialsException(messages.getMessage("DigestProcessingFilter.nonceNotTwoTokens",
                            new Object[] { nonceAsPlainText },
                            "Nonce should have yielded two tokens but was {0}")));

            return;
        }

        // Extract expiry time from nonce
        long nonceExpiryTime;

        try {
            nonceExpiryTime = new Long(nonceTokens[0]).longValue();
        } catch (NumberFormatException nfe) {
            fail(request, response,
                    new BadCredentialsException(messages.getMessage("DigestProcessingFilter.nonceNotNumeric",
                            new Object[] { nonceAsPlainText },
                            "Nonce token should have yielded a numeric first token, but was {0}")));

            return;
        }

        // Check signature of nonce matches this expiry time
        String expectedNonceSignature = DigestUtils
                .md5Hex(nonceExpiryTime + ":" + this.getAuthenticationEntryPoint().getKey());

        if (!expectedNonceSignature.equals(nonceTokens[1])) {
            fail(request, response,
                    new BadCredentialsException(messages.getMessage("DigestProcessingFilter.nonceCompromised",
                            new Object[] { nonceAsPlainText }, "Nonce token compromised {0}")));

            return;
        }

        // Lookup password for presented username
        // NB: DAO-provided password MUST be clear text - not encoded/salted
        // (unless this instance's passwordAlreadyEncoded property is 'false')
        boolean loadedFromDao = false;
        UserDetails user = userCache.getUserFromCache(username);

        if (user == null) {
            loadedFromDao = true;

            try {
                user = userDetailsService.loadUserByUsername(username);
            } catch (UsernameNotFoundException notFound) {
                fail(request, response,
                        new BadCredentialsException(
                                messages.getMessage("DigestProcessingFilter.usernameNotFound",
                                        new Object[] { username }, "Username {0} not found")));

                return;
            }

            if (user == null) {
                throw new AuthenticationServiceException(
                        "AuthenticationDao returned null, which is an interface contract violation");
            }

            userCache.putUserInCache(user);
        }

        // Compute the expected response-digest (will be in hex form)
        String serverDigestMd5;

        // Don't catch IllegalArgumentException (already checked validity)
        serverDigestMd5 = generateDigest(passwordAlreadyEncoded, username, realm, user.getPassword(),
                ((HttpServletRequest) request).getMethod(), uri, qop, nonce, nc, cnonce);

        // If digest is incorrect, try refreshing from backend and recomputing
        if (!serverDigestMd5.equals(responseDigest) && !loadedFromDao) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Digest comparison failure; trying to refresh user from DAO in case password had changed");
            }

            try {
                user = userDetailsService.loadUserByUsername(username);
            } catch (UsernameNotFoundException notFound) {
                // Would very rarely happen, as user existed earlier
                fail(request, response,
                        new BadCredentialsException(
                                messages.getMessage("DigestProcessingFilter.usernameNotFound",
                                        new Object[] { username }, "Username {0} not found")));
            }

            userCache.putUserInCache(user);

            // Don't catch IllegalArgumentException (already checked validity)
            serverDigestMd5 = generateDigest(passwordAlreadyEncoded, username, realm, user.getPassword(),
                    ((HttpServletRequest) request).getMethod(), uri, qop, nonce, nc, cnonce);
        }

        // If digest is still incorrect, definitely reject authentication attempt
        if (!serverDigestMd5.equals(responseDigest)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Expected response: '" + serverDigestMd5 + "' but received: '" + responseDigest
                        + "'; is AuthenticationDao returning clear text passwords?");
            }

            fail(request, response, new BadCredentialsException(
                    messages.getMessage("DigestProcessingFilter.incorrectResponse", "Incorrect response")));

            return;
        }

        // To get this far, the digest must have been valid
        // Check the nonce has not expired
        // We do this last so we can direct the user agent its nonce is stale
        // but the request was otherwise appearing to be valid
        if (nonceExpiryTime < System.currentTimeMillis()) {
            fail(request, response, new NonceExpiredException(
                    messages.getMessage("DigestProcessingFilter.nonceExpired", "Nonce has expired/timed out")));

            return;
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Authentication success for user: '" + username + "' with response: '" + responseDigest
                    + "'");
        }

        // START SIPXECS CUSTOM CODE: XX-8253
        // commented original code
        //UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(user,
        //        user.getPassword());

        // creates digest token to be handled by org.sipfoundry.sipxconfig.security.DaoAuthenticationProvider
        UsernamePasswordAuthenticationToken authRequest = new DigestUsernamePasswordAuthenticationToken(user,
                user.getPassword());
        // END SIPXECS CUSTOM CODE: XX-8253
        authRequest.setDetails(authenticationDetailsSource.buildDetails((HttpServletRequest) request));

        SecurityContextHolder.getContext().setAuthentication(authRequest);
    }

    chain.doFilter(request, response);
}