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:org.openmrs.web.taglib.RequireTag.java

/**
 * This is where all the magic happens. The privileges are checked and the user is redirected if
 * need be. <br>// w  w w. ja va2  s  .c om
 * <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
 * @should set the right session attributes if the authenticated user misses some privileges
 * @should set the referer as the denied page url if no redirect url is specified
 */
public int doStartTag() {

    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("context.is.null", (Object[]) null);
    }

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

    boolean hasPrivilege = hasPrivileges(userContext, privilege, allPrivilegesArray, anyPrivilegeArray);
    if (!hasPrivilege) {
        errorOccurred = true;
        if (userContext.isAuthenticated()) {
            httpSession.setAttribute(WebConstants.INSUFFICIENT_PRIVILEGES, true);
            if (missingPrivilegesBuffer != null) {
                httpSession.setAttribute(WebConstants.REQUIRED_PRIVILEGES, missingPrivilegesBuffer.toString());
            }

            String referer = request.getHeader("Referer");
            httpSession.setAttribute(WebConstants.REFERER_URL, referer);
            if (StringUtils.hasText(redirect)) {
                httpSession.setAttribute(WebConstants.DENIED_PAGE, redirect);
            } else if (StringUtils.hasText(referer)) {
                //This is not exactly correct all the time
                httpSession.setAttribute(WebConstants.DENIED_PAGE, referer);
            }

            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)) {
            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 && !"".equals(redirect)) {
            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.appverse.web.framework.backend.frontfacade.rest.autoconfigure.FrontFacadeRestAutoConfiguration.java

/**
 * Spring4 Cors filter//w w  w  .  jav a  2  s.  co m
 *  By default disabled
 * @return
 */
@Bean
@ConditionalOnProperty(value = "appverse.frontfacade.rest.cors.enabled", matchIfMissing = false)
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            String path = apiPath;
            if (!StringUtils.isEmpty(corsPath)) {
                path = corsPath;
            }
            registry.addMapping(path + "/**")
                    .allowedOrigins(StringUtils.commaDelimitedListToStringArray(allowedOrigins))
                    .allowedMethods(StringUtils.commaDelimitedListToStringArray(allowedMethods))
                    .allowedHeaders(StringUtils.commaDelimitedListToStringArray(allowedHeaders))
                    .allowCredentials(Boolean.valueOf(allowedCredentials)).maxAge(Long.valueOf(maxAge));
        }
    };
}

From source file:org.codehaus.groovy.grails.plugins.acegi.GrailsFilterInvocationDefinition.java

public ConfigAttributeDefinition lookupAttributes(String url) {
    setUpSession();/*from  w  w  w.  jav  a 2  s . c  o  m*/

    //set LowerCase compulsorily
    url = url.toLowerCase();

    int pos = url.indexOf("?");
    if (pos > 0) {
        url = url.substring(0, pos);
    }

    //TODO more better way
    //create query
    url = url.replaceAll("\"", "");
    url = url.replaceAll("'", "");

    //TODO more better way
    if (!url.contains(".") || url.indexOf(".gsp") > -1 || url.indexOf(".jsp") > -1) {
        StringTokenizer stn = new StringTokenizer(url, "/");
        String hql = "from " + requestMapClass + " where " + requestMapPathFieldName + " = '/**' ";
        String path = "/";
        while (stn.hasMoreTokens()) {
            String element = (String) stn.nextToken();
            path += element + "/";
            hql += "or " + requestMapPathFieldName + " ='" + path + "**' ";
        }
        hql += "order by length(" + requestMapPathFieldName + ") desc";

        //find requestMap from DB by using GORM static method.
        GrailsDomainClass requestMapDomainClass = (GrailsDomainClass) getGrailsApplication()
                .getArtefact("Domain", requestMapClass);
        List reqMap = (List) InvokerHelper.invokeStaticMethod(requestMapDomainClass.getClazz(), "findAll", hql);

        if (reqMap != null) {
            Iterator iter = reqMap.iterator();
            while (iter.hasNext()) {
                GroovyObject gobj = (GroovyObject) iter.next();
                String _configAttribute = (String) InvokerHelper.invokeMethod(gobj,
                        requestMapConfigAttributeFieldMethod, null);
                String _url = (String) InvokerHelper.invokeMethod(gobj, requestMapPathFieldMethod, null);
                _url = _url.toLowerCase();
                boolean matched = pathMatcher.match(_url, url);
                if (matched) {
                    ConfigAttributeDefinition cad = new ConfigAttributeDefinition();
                    String[] configAttrs = StringUtils.commaDelimitedListToStringArray(_configAttribute);
                    for (int i = 0; i < configAttrs.length; i++) {
                        String configAttribute = configAttrs[i];
                        cad.addConfigAttribute(new SecurityConfig(configAttribute));
                    }
                    releaseSession();
                    return cad;
                }
            }
        }
    }

    releaseSession();
    return null;
}

From source file:org.appverse.web.framework.backend.frontfacade.websocket.autoconfigure.FrontFacadeWebSocketAutoConfiguration.java

@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {

    logger.info("Initializing websocket standard on path:'{}' ...", defaultWebsocketEndpointPath);
    StompWebSocketEndpointRegistration webSockedEndpoint = stompEndpointRegistry
            .addEndpoint(defaultWebsocketEndpointPath);
    logger.info("Initializing websocket sockJs on path:'{}' ...", defaultSockJsEndpointPath);
    StompWebSocketEndpointRegistration sockJsEndpoint = stompEndpointRegistry
            .addEndpoint(defaultSockJsEndpointPath);
    sockJsEndpoint.withSockJS();//from w ww . j a  v  a 2 s  . co m
    if (Boolean.valueOf(corsEnabled)) {
        logger.info("Initializing cors on websockets");
        webSockedEndpoint.setAllowedOrigins(StringUtils.commaDelimitedListToStringArray(allowedOrigins));
        sockJsEndpoint.setAllowedOrigins(StringUtils.commaDelimitedListToStringArray(allowedOrigins));
    }
}

From source file:tv.arte.resteventapi.core.presentation.decoration.RestEventApiControllerLinkBuilder.java

/**
 * Returns a {@link UriComponentsBuilder} obtained from the current servlet mapping with the host tweaked in case the
 * request contains an {@code X-Forwarded-Host} header and the scheme tweaked in case the request contains an
 * {@code X-Forwarded-Ssl} header// ww w .  jav a 2 s. c o  m
 * 
 * @return
 */
static UriComponentsBuilder getBuilder() {

    HttpServletRequest request = getCurrentRequest();
    ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromServletMapping(request);

    String forwardedSsl = request.getHeader("X-Forwarded-Ssl");

    if (StringUtils.hasText(forwardedSsl) && forwardedSsl.equalsIgnoreCase("on")) {
        builder.scheme("https");
    }

    String host = request.getHeader("X-Forwarded-Host");

    if (!StringUtils.hasText(host)) {
        return builder;
    }

    String[] hosts = StringUtils.commaDelimitedListToStringArray(host);
    String hostToUse = hosts[0];

    if (hostToUse.contains(":")) {

        String[] hostAndPort = StringUtils.split(hostToUse, ":");

        builder.host(hostAndPort[0]);
        builder.port(Integer.parseInt(hostAndPort[1]));

    } else {
        builder.host(hostToUse);
        builder.port(-1); // reset port if it was forwarded from default port
    }

    String port = request.getHeader("X-Forwarded-Port");

    if (StringUtils.hasText(port)) {
        builder.port(Integer.parseInt(port));
    }

    return builder;
}

From source file:grails.plugin.springsecurity.annotation.AuthoritiesTransformation.java

protected String[] getAuthorityNames(final String fieldName, final AnnotationNode rolesNode,
        final SourceUnit sourceUnit) throws IOException {

    Properties properties = new Properties();
    File propertyFile = new File("roles.properties");
    if (!propertyFile.exists()) {
        reportError("Property file roles.properties not found", sourceUnit, rolesNode);
        return null;
    }//from   w  w  w. ja  va  2  s . co  m

    properties.load(new FileReader(propertyFile));

    Object value = properties.getProperty(fieldName);
    if (value == null) {
        reportError("No value for property '" + fieldName + "'", sourceUnit, rolesNode);
        return null;
    }

    List<String> names = new ArrayList<String>();
    for (String auth : StringUtils.commaDelimitedListToStringArray(value.toString())) {
        auth = auth.trim();
        if (auth.length() > 0) {
            names.add(auth);
        }
    }

    return names.toArray(new String[names.size()]);
}

From source file:org.cloudfoundry.identity.uaa.config.YamlServletProfileInitializer.java

private Resource getResource(ServletContext servletContext,
        ConfigurableWebApplicationContext applicationContext, String locations) {
    Resource resource = null;//from w w w .  ja v a2 s.  c  o m
    String[] configFileLocations = locations == null ? DEFAULT_PROFILE_CONFIG_FILE_LOCATIONS
            : StringUtils.commaDelimitedListToStringArray(locations);
    for (String location : configFileLocations) {
        location = applicationContext.getEnvironment().resolvePlaceholders(location);
        servletContext.log("Testing for YAML resources at: " + location);
        resource = applicationContext.getResource(location);
        if (resource != null && resource.exists()) {
            break;
        }
    }
    return resource;
}

From source file:org.elasticsoftware.elasticactors.rabbitmq.RabbitMQMessagingService.java

@PostConstruct
public void start() throws IOException, TimeoutException {
    // millis/*  w  w  w .j  a v  a  2  s.co  m*/
    connectionFactory.setConnectionTimeout(1000);
    // seconds
    connectionFactory.setRequestedHeartbeat(4);
    // lyra reconnect logic
    Config config = new Config()
            .withRecoveryPolicy(new RecoveryPolicy().withMaxAttempts(-1).withInterval(Duration.seconds(1)))
            .withChannelListeners(this);

    ConnectionOptions connectionOptions = new ConnectionOptions(connectionFactory)
            .withHosts(StringUtils.commaDelimitedListToStringArray(rabbitmqHosts)).withPort(rabbitmqPort)
            .withUsername(username).withPassword(password);
    // create single connection
    //clientConnection = connectionFactory.newConnection(Address.parseAddresses(rabbitmqHosts));
    clientConnection = Connections.create(connectionOptions, config);
    // create a seperate producer and a seperate consumer channel
    consumerChannel = clientConnection.createChannel();
    consumerChannel.basicQos(prefetchCount);
    producerChannel = clientConnection.createChannel();
    // ensure the exchange is there
    consumerChannel.exchangeDeclare(exchangeName, "direct", true);
    if (ackType == BUFFERED) {
        messageAcker = new BufferingMessageAcker(consumerChannel);
    } else if (ackType == WRITE_BEHIND) {
        messageAcker = new WriteBehindMessageAcker(consumerChannel);
    } else if (ackType == ASYNC) {
        messageAcker = new AsyncMessageAcker(consumerChannel);
    } else {
        messageAcker = new DirectMessageAcker(consumerChannel);
    }
    messageAcker.start();
}

From source file:org.eclipse.gemini.blueprint.test.AbstractConfigurableBundleCreatorTests.java

/**
 * {@inheritDoc}/*from   w  ww .  jav a 2s  . c  o m*/
 * 
 * <p/>Ant-style patterns for identifying the resources added to the jar.The
 * patterns are considered from the root path when performing the search.
 * 
 * <p/> By default, the content pattern is <code>*&#42;/*</code> which
 * includes all sources from the root. One can configure the pattern to
 * include specific files by using different patterns. For example, to
 * include just the classes, XML and properties files one can use the
 * following patterns:
 * <ol>
 * <li><code>*&#42;/*.class</code> for classes
 * <li><code>*&#42;/*.xml</code> for XML files
 * <li><code>*&#42;/*.properties</code> for properties files
 * </ol>
 * 
 * @return array of Ant-style pattern
 */
protected String[] getBundleContentPattern() {
    return StringUtils.commaDelimitedListToStringArray(jarSettings.getProperty(INCLUDE_PATTERNS));
}

From source file:org.elasticsoftware.elasticactors.rabbitmq.cpt.RabbitMQMessagingService.java

@PostConstruct
public void start() throws IOException, TimeoutException {
    // millis/*from   www  . j a  v a2s.  c o m*/
    connectionFactory.setConnectionTimeout(1000);
    // seconds
    connectionFactory.setRequestedHeartbeat(4);
    // lyra reconnect logic
    Config config = new Config()
            .withRecoveryPolicy(new RecoveryPolicy().withMaxAttempts(-1).withInterval(Duration.seconds(1)))
            .withChannelListeners(this);

    ConnectionOptions connectionOptions = new ConnectionOptions(connectionFactory)
            .withHosts(StringUtils.commaDelimitedListToStringArray(rabbitmqHosts)).withPort(rabbitmqPort)
            .withUsername(username).withPassword(password);
    // create single connection
    //clientConnection = connectionFactory.newConnection(Address.parseAddresses(rabbitmqHosts));
    clientConnection = Connections.create(connectionOptions, config);
    // create a seperate consumer channel
    consumerChannel = clientConnection.createChannel();
    consumerChannel.basicQos(prefetchCount);
    // prepare the consumer channels
    for (int i = 0; i < queueExecutor.getThreadCount(); i++) {
        producerChannels.add(clientConnection.createChannel());
    }
    // ensure the exchange is there
    consumerChannel.exchangeDeclare(exchangeName, "direct", true);
    if (ackType == BUFFERED) {
        messageAcker = new BufferingMessageAcker(consumerChannel);
    } else if (ackType == WRITE_BEHIND) {
        messageAcker = new WriteBehindMessageAcker(consumerChannel);
    } else if (ackType == ASYNC) {
        messageAcker = new AsyncMessageAcker(consumerChannel);
    } else {
        messageAcker = new DirectMessageAcker(consumerChannel);
    }
    messageAcker.start();
}