Example usage for org.springframework.util StringUtils commaDelimitedListToStringArray

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

Introduction

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

Prototype

public static String[] commaDelimitedListToStringArray(@Nullable String str) 

Source Link

Document

Convert a comma delimited list (e.g., a row from a CSV file) into an array of strings.

Usage

From source file:com.joyveb.dbpimpl.cass.prepare.core.CassandraClusterFactoryBean.java

@Override
public void afterPropertiesSet() {

    Cluster.Builder builder = Cluster.builder();

    builder.addContactPoints(StringUtils.commaDelimitedListToStringArray(contactPoints)).withPort(port);

    if (compressionType != null) {
        builder.withCompression(convertCompressionType(compressionType));
    }//w ww  . j  av a2s  .  c  o  m

    if (localPoolingOptions != null) {
        builder.withPoolingOptions(configPoolingOptions(HostDistance.LOCAL, localPoolingOptions));
    }

    if (remotePoolingOptions != null) {
        builder.withPoolingOptions(configPoolingOptions(HostDistance.REMOTE, remotePoolingOptions));
    }

    if (socketOptions != null) {
        builder.withSocketOptions(configSocketOptions(socketOptions));
    }

    if (authProvider != null) {
        builder.withAuthProvider(authProvider);
    }

    if (loadBalancingPolicy != null) {
        builder.withLoadBalancingPolicy(loadBalancingPolicy);
    }

    if (reconnectionPolicy != null) {
        builder.withReconnectionPolicy(reconnectionPolicy);
    }

    if (retryPolicy != null) {
        builder.withRetryPolicy(retryPolicy);
    }

    if (!metricsEnabled) {
        builder.withoutMetrics();
    }

    Cluster cluster = null;
    try {
        cluster = builder.build();
    } catch (RuntimeException ex) {
        RuntimeException resolved = translateExceptionIfPossible(ex);
        throw resolved == null ? ex : resolved;
    }

    // initialize property
    this.cluster = cluster;
    cluster.connect();
}

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

/**
 * Split the role names and create {@link GrantedAuthority}s for each.
 * @param authorizationsString  comma-delimited role names
 * @return authorities (possibly empty)/*from  w  w w  . j a va  2  s .  c o m*/
 */
public static Set<GrantedAuthority> parseAuthoritiesString(final String authorizationsString) {
    Set<GrantedAuthority> requiredAuthorities = new HashSet<GrantedAuthority>();
    for (String auth : StringUtils.commaDelimitedListToStringArray(authorizationsString)) {
        auth = auth.trim();
        if (auth.length() > 0) {
            requiredAuthorities.add(new GrantedAuthorityImpl(auth));
        }
    }

    return requiredAuthorities;
}

From source file:org.openmrs.module.formaccesscontrol.web.taglib.RequireTag.java

/**
 * This is where all the magic happens. The privileges are checked and the user is redirected if
 * need be. <br/>// ww w .  j  a  v  a  2s  . c  o m
 * <br/>
 * Returns SKIP_PAGE if the user doesn't have the privilege and SKIP_BODY if it does.
 * 
 * @see javax.servlet.jsp.tagext.TagSupport#doStartTag()
 * @should allow user with the privilege
 * @should allow user to have any privilege
 * @should allow user with all privileges
 * @should reject user without the privilege
 * @should reject user without any of the privileges
 * @should reject user without all of the privileges
 */
@Override
public int doStartTag() {
    if (form == null) {
        return SKIP_BODY;
    }

    errorOccurred = false;
    HttpServletResponse httpResponse = (HttpServletResponse) pageContext.getResponse();
    HttpSession httpSession = pageContext.getSession();
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    String request_ip_addr = request.getLocalAddr();
    String session_ip_addr = (String) httpSession.getAttribute(WebConstants.OPENMRS_CLIENT_IP_HTTPSESSION_ATTR);

    UserContext userContext = Context.getUserContext();

    if (userContext == null && privilege != null) {
        log.error("userContext is null. Did this pass through a filter?");
        //httpSession.removeAttribute(WebConstants.OPENMRS_CONTEXT_HTTPSESSION_ATTR);
        //TODO find correct error to throw 
        throw new APIException("The context is currently null.  Please try reloading the site.");
    }

    // Parse comma-separated list of privileges in allPrivileges and anyPrivileges attributes
    String[] allPrivilegesArray = StringUtils.commaDelimitedListToStringArray(allPrivileges);
    String[] anyPrivilegeArray = StringUtils.commaDelimitedListToStringArray(anyPrivilege);

    FormAccessControlService svc = Context.getService(FormAccessControlService.class);
    boolean hasPrivilege = hasPrivileges(svc, form, privilege, allPrivilegesArray, anyPrivilegeArray);
    if (!hasPrivilege) {
        errorOccurred = true;
        if (userContext.isAuthenticated()) {
            String referer = request.getHeader("Referer");
            // If the user has just authenticated, but is still not authorized to see the page.
            if (referer != null && referer.contains("login.")) {
                try {
                    httpResponse.sendRedirect(request.getContextPath()); // Redirect to the home page.
                    return SKIP_PAGE;
                } catch (IOException e) {
                    // oops, cannot redirect
                    log.error("Unable to redirect to the home page", e);
                    throw new APIException(e);
                }
            }

            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "require.unauthorized");
            log.warn("The user: '" + Context.getAuthenticatedUser() + "' has attempted to access: " + redirect
                    + " which requires privilege: " + privilege + " or one of: " + allPrivileges + " or any of "
                    + anyPrivilege);
        } else {
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "require.login");
        }
    } else if (hasPrivilege && userContext.isAuthenticated()) {
        // redirect users to password change form
        User user = userContext.getAuthenticatedUser();
        log.debug("Login redirect: " + redirect);
        if (new UserProperties(user.getUserProperties()).isSupposedToChangePassword()
                && !redirect.contains("options.form")) {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.password.change");
            errorOccurred = true;
            redirect = request.getContextPath() + "/options.form#Change Login Info";
            otherwise = redirect;
            try {
                httpResponse.sendRedirect(redirect);
                return SKIP_PAGE;
            } catch (IOException e) {
                // oops, cannot redirect
                log.error("Unable to redirect for password change: " + redirect, e);
                throw new APIException(e);
            }
        }
    }

    if (differentIpAddresses(session_ip_addr, request_ip_addr)) {
        errorOccurred = true;
        // stops warning message in IE when refreshing repeatedly
        if ("0.0.0.0".equals(request_ip_addr) == false) {
            log.warn("Invalid ip addr: expected " + session_ip_addr + ", but found: " + request_ip_addr);
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "require.ip_addr");
        }
    }

    log.debug("session ip addr: " + session_ip_addr);

    if (errorOccurred) {

        String url = "";
        if (redirect != null && !redirect.equals("")) {
            url = request.getContextPath() + redirect;
        } else {
            url = request.getRequestURI();
        }

        if (request.getQueryString() != null) {
            url = url + "?" + request.getQueryString();
        }
        httpSession.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, url);
        try {
            httpResponse.sendRedirect(request.getContextPath() + otherwise);
            return SKIP_PAGE;
        } catch (IOException e) {
            // oops, cannot redirect
            throw new APIException(e);
        }
    }

    return SKIP_BODY;
}

From source file:org.codehaus.grepo.core.config.GenericRepositoryScanBeanDefinitionParser.java

/**
 * {@inheritDoc}//from  w w  w .j av  a2s  .com
 */
public BeanDefinition parse(Element element, ParserContext parserContext) {
    Object source = parserContext.extractSource(element);
    GenericRepositoryConfigContext configContext = new GenericRepositoryConfigContext(element);

    // init bean defintion parse delegate...
    BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(parserContext.getReaderContext());
    delegate.initDefaults(element.getOwnerDocument().getDocumentElement());

    GenericRepositoryBeanDefinitionScanner scanner = configureScanner(configContext, parserContext);

    parseBeanNameGenerator(configContext, parserContext);

    String[] basePackages = StringUtils.commaDelimitedListToStringArray(configContext.getBasePackage());
    for (String basePackage : basePackages) {
        Set<BeanDefinition> candidates = scanner.findCandidateComponents(basePackage);
        for (BeanDefinition candidate : candidates) {
            BeanDefinitionBuilder builder = BeanDefinitionParserHelper
                    .createBuilderFromConfigContext(configContext, source, defaultGenericRepositoryFactoryType);

            delegate.parsePropertyElements(configContext.getElement(), builder.getRawBeanDefinition());

            builder.addPropertyValue(GenericRepositoryConfigContext.PROXY_CLASS_PROPERTY,
                    candidate.getBeanClassName());

            String beanName = beanNameGenerator.generateBeanName(candidate, parserContext.getRegistry());
            parserContext
                    .registerBeanComponent(new BeanComponentDefinition(builder.getBeanDefinition(), beanName));
            logger.debug("Registered generic repository bean '{}'", beanName);
        }
    }

    return null;
}

From source file:org.jmxtrans.embedded.spring.EmbeddedJmxTransFactory.java

@Override
public SpringEmbeddedJmxTrans getObject() throws Exception {
    logger.info("Load JmxTrans with configuration '{}'", configurationUrls);
    if (embeddedJmxTrans == null) {

        if (configurationUrls == null) {
            configurationUrls = Collections.singletonList(DEFAULT_CONFIGURATION_URL);
        }/*www .  j  a v  a 2 s.  co m*/
        ConfigurationParser parser = new ConfigurationParser();
        SpringEmbeddedJmxTrans newJmxTrans = new SpringEmbeddedJmxTrans();
        newJmxTrans.setObjectName("org.jmxtrans.embedded:type=EmbeddedJmxTrans,name=" + beanName);

        for (String delimitedConfigurationUrl : configurationUrls) {
            String[] tokens = StringUtils.commaDelimitedListToStringArray(delimitedConfigurationUrl);
            tokens = StringUtils.trimArrayElements(tokens);
            for (String configurationUrl : tokens) {
                configurationUrl = configurationUrl.trim();
                logger.debug("Load configuration {}", configurationUrl);
                Resource configuration = resourceLoader.getResource(configurationUrl);
                if (configuration.exists()) {
                    try {
                        parser.mergeEmbeddedJmxTransConfiguration(configuration.getInputStream(), newJmxTrans);
                    } catch (Exception e) {
                        throw new EmbeddedJmxTransException("Exception loading configuration " + configuration,
                                e);
                    }
                } else if (ignoreConfigurationNotFound) {
                    logger.debug("Ignore missing configuration file {}", configuration);
                } else {
                    throw new EmbeddedJmxTransException("Configuration file " + configuration + " not found");
                }
            }
        }
        embeddedJmxTrans = newJmxTrans;
        logger.info("Created EmbeddedJmxTrans with configuration {})", configurationUrls);
        embeddedJmxTrans.start();
    }
    return embeddedJmxTrans;
}

From source file:mx.edu.um.mateo.general.utils.SpringSecurityUtils.java

/**
 * Split the role names and create {@link GrantedAuthority}s for each.
 * /* w  ww. j av  a2  s  . co m*/
 * @param roleNames
 *            comma-delimited role names
 * @return authorities (possibly empty)
 */
public static List<GrantedAuthority> parseAuthoritiesString(final String roleNames) {
    List<GrantedAuthority> requiredAuthorities = new ArrayList<>();
    for (String auth : StringUtils.commaDelimitedListToStringArray(roleNames)) {
        auth = auth.trim();
        if (auth.length() > 0) {
            requiredAuthorities.add(new GrantedAuthorityImpl(auth));
        }
    }

    return requiredAuthorities;
}

From source file:org.springmodules.cache.provider.ehcache.EhCacheFlushingModelTests.java

public void testSetCacheNamesWithNotEmptyCsv() {
    String cacheNames = "main,test";
    model.setCacheNames(cacheNames);/*from   w w  w. j av  a2s . c  om*/

    String[] expected = StringUtils.commaDelimitedListToStringArray(cacheNames);
    AssertExt.assertEquals(expected, model.getCacheNames());
}

From source file:nu.localhost.tapestry5.springsecurity.components.IfRole.java

private Collection<GrantedAuthority> parseAuthoritiesString(String authorizationsString) {
    final Collection<GrantedAuthority> requiredAuthorities = new ArrayList<GrantedAuthority>();
    final String[] authorities = StringUtils.commaDelimitedListToStringArray(authorizationsString);

    for (int i = 0; i < authorities.length; i++) {
        String authority = authorities[i];

        // Remove the role's whitespace characters without depending on JDK 1.4+
        // Includes space, tab, new line, carriage return and form feed.
        String role = StringUtils.replace(authority, " ", "");
        role = StringUtils.replace(role, "\t", "");
        role = StringUtils.replace(role, "\r", "");
        role = StringUtils.replace(role, "\n", "");
        role = StringUtils.replace(role, "\f", "");

        requiredAuthorities.add(new SimpleGrantedAuthority(role));
    }//from ww  w .  j  av  a  2s.  c o m
    return requiredAuthorities;
}

From source file:nl.surfnet.coin.api.service.JanusClientDetailsService.java

private Set<String> getCallbackUrlCollection(final EntityMetadata metadata) {
    final String callbackUrl = metadata.getOauthCallbackUrl();
    //sensible default
    Set<String> result = Collections.emptySet();
    if (callbackUrl != null) {
        if (callbackUrl.contains(",")) {
            //need to trim, therefore more code then calling StringUtils#commaDelimitedListToSet
            String[] callbacksArray = StringUtils.commaDelimitedListToStringArray(callbackUrl);
            result = new HashSet<String>();
            for (String callback : callbacksArray) {
                result.add(callback.trim());
            }//from  w  w w  . ja  v a  2 s .c  om
        } else {
            result = Collections.singleton(callbackUrl.trim());
        }
    }
    return result;
}

From source file:ch.astina.hesperid.web.components.security.IfRole.java

@SuppressWarnings("unchecked")
private Set parseAuthoritiesString(String authorizationsString) {
    final Set requiredAuthorities = new HashSet();
    final String[] authorities = StringUtils.commaDelimitedListToStringArray(authorizationsString);

    for (int i = 0; i < authorities.length; i++) {
        String authority = authorities[i];

        // Remove the role's whitespace characters without depending on JDK 1.4+
        // Includes space, tab, new line, carriage return and form feed.
        String role = StringUtils.replace(authority, " ", "");
        role = StringUtils.replace(role, "\t", "");
        role = StringUtils.replace(role, "\r", "");
        role = StringUtils.replace(role, "\n", "");
        role = StringUtils.replace(role, "\f", "");

        requiredAuthorities.add(new GrantedAuthorityImpl(role));
    }/*from  w  w  w .  j  a  v  a2 s  . c om*/

    return requiredAuthorities;
}