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.springframework.boot.env.RandomValuePropertySource.java

private long getNextLongInRange(String range) {
    String[] tokens = StringUtils.commaDelimitedListToStringArray(range);
    if (tokens.length == 1) {
        return Math.abs(getSource().nextLong() % Long.parseLong(tokens[0]));
    }/* w w w  .  jav a2s .c  om*/
    long lowerBound = Long.parseLong(tokens[0]);
    long upperBound = Long.parseLong(tokens[1]) - lowerBound;
    return lowerBound + Math.abs(getSource().nextLong() % upperBound);
}

From source file:org.springframework.cloud.config.client.ConfigServicePropertySourceLocator.java

@Override
@Retryable(interceptor = "configServerRetryInterceptor")
public org.springframework.core.env.PropertySource<?> locate(
        org.springframework.core.env.Environment environment) {
    ConfigClientProperties properties = this.defaultProperties.override(environment);
    CompositePropertySource composite = new CompositePropertySource("configService");
    RestTemplate restTemplate = this.restTemplate == null ? getSecureRestTemplate(properties)
            : this.restTemplate;
    Exception error = null;/*from  w w w . j av  a2 s  . c  o  m*/
    String errorBody = null;
    logger.info("Fetching config from server at: " + properties.getRawUri());
    try {
        String[] labels = new String[] { "" };
        if (StringUtils.hasText(properties.getLabel())) {
            labels = StringUtils.commaDelimitedListToStringArray(properties.getLabel());
        }

        String state = ConfigClientStateHolder.getState();

        // Try all the labels until one works
        for (String label : labels) {
            Environment result = getRemoteEnvironment(restTemplate, properties, label.trim(), state);
            if (result != null) {
                logger.info(String.format(
                        "Located environment: name=%s, profiles=%s, label=%s, version=%s, state=%s",
                        result.getName(),
                        result.getProfiles() == null ? "" : Arrays.asList(result.getProfiles()),
                        result.getLabel(), result.getVersion(), result.getState()));

                for (PropertySource source : result.getPropertySources()) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> map = (Map<String, Object>) source.getSource();
                    composite.addPropertySource(new MapPropertySource(source.getName(), map));
                }

                if (StringUtils.hasText(result.getState()) || StringUtils.hasText(result.getVersion())) {
                    HashMap<String, Object> map = new HashMap<>();
                    putValue(map, "config.client.state", result.getState());
                    putValue(map, "config.client.version", result.getVersion());
                    composite.addFirstPropertySource(new MapPropertySource("configClient", map));
                }
                return composite;
            }
        }
    } catch (HttpServerErrorException e) {
        error = e;
        if (MediaType.APPLICATION_JSON.includes(e.getResponseHeaders().getContentType())) {
            errorBody = e.getResponseBodyAsString();
        }
    } catch (Exception e) {
        error = e;
    }
    if (properties.isFailFast()) {
        throw new IllegalStateException(
                "Could not locate PropertySource and the fail fast property is set, failing", error);
    }
    logger.warn("Could not locate PropertySource: "
            + (errorBody == null ? error == null ? "label not found" : error.getMessage() : errorBody));
    return null;

}

From source file:org.springframework.cloud.config.server.environment.NativeEnvironmentRepository.java

@Override
public Locations getLocations(String application, String profile, String label) {
    String[] locations = this.searchLocations;
    if (this.searchLocations == null || this.searchLocations.length == 0) {
        locations = DEFAULT_LOCATIONS;//from  ww w.ja va2 s . c  o m
    }
    List<String> output = new ArrayList<String>();
    for (String location : locations) {
        String[] profiles = new String[] { profile };
        if (profile != null) {
            profiles = StringUtils.commaDelimitedListToStringArray(profile);
        }
        String[] apps = new String[] { application };
        if (application != null) {
            apps = StringUtils.commaDelimitedListToStringArray(application);
        }
        for (String prof : profiles) {
            for (String app : apps) {
                String value = location;
                if (application != null) {
                    value = value.replace("{application}", app);
                }
                if (prof != null) {
                    value = value.replace("{profile}", prof);
                }
                if (label != null) {
                    value = value.replace("{label}", label);
                }
                if (!value.endsWith("/")) {
                    value = value + "/";
                }
                if (isDirectory(value)) {
                    output.add(value);
                }
            }
        }
    }
    for (String location : locations) {
        if (StringUtils.hasText(label)) {
            String labelled = location + label.trim() + "/";
            if (isDirectory(labelled)) {
                output.add(labelled);
            }
        }
    }
    return new Locations(application, profile, label, this.version, output.toArray(new String[0]));
}

From source file:org.springframework.cloud.config.server.environment.VaultEnvironmentRepository.java

@Override
public Environment findOne(String application, String profile, String label) {

    String state = request.getHeader(STATE_HEADER);
    String newState = this.watch.watch(state);

    String[] profiles = StringUtils.commaDelimitedListToStringArray(profile);
    List<String> scrubbedProfiles = scrubProfiles(profiles);

    List<String> keys = findKeys(application, scrubbedProfiles);

    Environment environment = new Environment(application, profiles, label, null, newState);

    for (String key : keys) {
        // read raw 'data' key from vault
        String data = read(key);/*from  w  w  w.j a  v a2 s  .c  o m*/
        if (data != null) {
            // data is in json format of which, yaml is a superset, so parse
            final YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
            yaml.setResources(new ByteArrayResource(data.getBytes()));
            Properties properties = yaml.getObject();

            if (!properties.isEmpty()) {
                environment.add(new PropertySource("vault:" + key, properties));
            }
        }
    }

    return environment;
}

From source file:org.springframework.cloud.config.server.NativeEnvironmentRepository.java

protected Environment clean(Environment value) {
    Environment result = new Environment(value.getName(), value.getProfiles(), value.getLabel());
    for (PropertySource source : value.getPropertySources()) {
        String name = source.getName();
        if (environment.getPropertySources().contains(name)) {
            continue;
        }/*from  w w  w. j av a 2 s. com*/
        name = name.replace("applicationConfig: [", "");
        name = name.replace("]", "");
        if (searchLocations != null) {
            boolean matches = false;
            String normal = name;
            if (normal.startsWith("file:")) {
                normal = StringUtils.cleanPath(new File(normal.substring("file:".length())).getAbsolutePath());
            }
            for (String pattern : StringUtils
                    .commaDelimitedListToStringArray(getLocations(searchLocations, result.getLabel()))) {
                if (!pattern.contains(":")) {
                    pattern = "file:" + pattern;
                }
                if (pattern.startsWith("file:")) {
                    pattern = StringUtils
                            .cleanPath(new File(pattern.substring("file:".length())).getAbsolutePath()) + "/";
                }
                if (logger.isTraceEnabled()) {
                    logger.trace("Testing pattern: " + pattern + " with property source: " + name);
                }
                if (normal.startsWith(pattern) && !normal.substring(pattern.length()).contains("/")) {
                    matches = true;
                    break;
                }
            }
            if (!matches) {
                // Don't include this one: it wasn't matched by our search locations
                if (logger.isDebugEnabled()) {
                    logger.debug("Not adding property source: " + name);
                }
                continue;
            }
        }
        logger.info("Adding property source: " + name);
        result.add(new PropertySource(name, source.getSource()));
    }
    return result;
}

From source file:org.springframework.cloud.config.server.support.AbstractScmAccessor.java

protected String[] getSearchLocations(File dir, String application, String profile, String label) {
    String[] locations = this.searchPaths;
    if (locations == null || locations.length == 0) {
        locations = DEFAULT_LOCATIONS;//w  ww  . j a v  a2s  .  c o  m
    } else if (locations != DEFAULT_LOCATIONS) {
        locations = StringUtils.concatenateStringArrays(DEFAULT_LOCATIONS, locations);
    }
    Collection<String> output = new LinkedHashSet<String>();
    for (String location : locations) {
        String[] profiles = new String[] { profile };
        if (profile != null) {
            profiles = StringUtils.commaDelimitedListToStringArray(profile);
        }
        String[] apps = new String[] { application };
        if (application != null) {
            apps = StringUtils.commaDelimitedListToStringArray(application);
        }
        for (String prof : profiles) {
            for (String app : apps) {
                String value = location;
                if (app != null) {
                    value = value.replace("{application}", app);
                }
                if (prof != null) {
                    value = value.replace("{profile}", prof);
                }
                if (label != null) {
                    value = value.replace("{label}", label);
                }
                if (!value.endsWith("/")) {
                    value = value + "/";
                }
                output.addAll(matchingDirectories(dir, value));
            }
        }
    }
    return output.toArray(new String[0]);
}

From source file:org.springframework.cloud.dataflow.app.launcher.ModuleLauncher.java

public void launchAggregatedModules(List<ModuleLaunchRequest> moduleLaunchRequests,
        Map<String, String> aggregateArgs) {
    try {//from w w w . j a v a 2 s.c  o  m
        List<String> mainClassNames = new ArrayList<>();
        LinkedHashSet<URL> jarURLs = new LinkedHashSet<>();
        List<String> seenArchives = new ArrayList<>();
        final List<String[]> arguments = new ArrayList<>();
        final ClassLoader classLoader;
        if (!(aggregateArgs.containsKey(EXCLUDE_DEPENDENCIES_ARG)
                || aggregateArgs.containsKey(INCLUDE_DEPENDENCIES_ARG))) {
            for (ModuleLaunchRequest moduleLaunchRequest : moduleLaunchRequests) {
                Resource resource = resolveModule(moduleLaunchRequest.getModule());
                JarFileArchive jarFileArchive = new JarFileArchive(resource.getFile());
                jarURLs.add(jarFileArchive.getUrl());
                for (Archive archive : jarFileArchive.getNestedArchives(ArchiveMatchingEntryFilter.FILTER)) {
                    // avoid duplication based on unique JAR names
                    String urlAsString = archive.getUrl().toString();
                    String jarNameWithExtension = urlAsString.substring(0, urlAsString.lastIndexOf("!/"));
                    String jarNameWithoutExtension = jarNameWithExtension
                            .substring(jarNameWithExtension.lastIndexOf("/") + 1);
                    if (!seenArchives.contains(jarNameWithoutExtension)) {
                        seenArchives.add(jarNameWithoutExtension);
                        jarURLs.add(archive.getUrl());
                    }
                }
                mainClassNames.add(jarFileArchive.getMainClass());
                arguments.add(toArgArray(moduleLaunchRequest.getArguments()));
            }
            classLoader = ClassloaderUtils.createModuleClassloader(jarURLs.toArray(new URL[jarURLs.size()]));
        } else {
            // First, resolve modules and extract main classes - while slightly less efficient than just
            // doing the same processing after resolution, this ensures that module artifacts are processed
            // correctly for extracting their main class names. It is not possible in the general case to
            // identify, after resolution, whether a resource represents a module artifact which was part of the
            // original request or not. We will include the first module as root and the next as direct dependencies
            Coordinates root = null;
            ArrayList<Coordinates> includeCoordinates = new ArrayList<>();
            for (ModuleLaunchRequest moduleLaunchRequest : moduleLaunchRequests) {
                Coordinates moduleCoordinates = toCoordinates(moduleLaunchRequest.getModule());
                if (root == null) {
                    root = moduleCoordinates;
                } else {
                    includeCoordinates.add(toCoordinates(moduleLaunchRequest.getModule()));
                }
                Resource moduleResource = resolveModule(moduleLaunchRequest.getModule());
                JarFileArchive moduleArchive = new JarFileArchive(moduleResource.getFile());
                mainClassNames.add(moduleArchive.getMainClass());
                arguments.add(toArgArray(moduleLaunchRequest.getArguments()));
            }
            for (String include : StringUtils
                    .commaDelimitedListToStringArray(aggregateArgs.get(INCLUDE_DEPENDENCIES_ARG))) {
                includeCoordinates.add(toCoordinates(include));
            }
            // Resolve all artifacts - since modules have been specified as direct dependencies, they will take
            // precedence in the resolution order, ensuring that the already resolved artifacts will be returned as
            // part of the response.
            Resource[] libraries = moduleResolver.resolve(root,
                    includeCoordinates.toArray(new Coordinates[includeCoordinates.size()]),
                    StringUtils.commaDelimitedListToStringArray(aggregateArgs.get(EXCLUDE_DEPENDENCIES_ARG)));
            for (Resource library : libraries) {
                jarURLs.add(library.getURL());
            }
            classLoader = new URLClassLoader(jarURLs.toArray(new URL[jarURLs.size()]));
        }

        final List<Class<?>> mainClasses = new ArrayList<>();
        for (String mainClass : mainClassNames) {
            mainClasses.add(ClassUtils.forName(mainClass, classLoader));
        }
        Runnable moduleAggregatorRunner = new ModuleAggregatorRunner(classLoader, mainClasses,
                toArgArray(aggregateArgs), arguments);
        Thread moduleAggregatorRunnerThread = new Thread(moduleAggregatorRunner);
        moduleAggregatorRunnerThread.setContextClassLoader(classLoader);
        moduleAggregatorRunnerThread.setName(MODULE_AGGREGATOR_RUNNER_THREAD_NAME);
        moduleAggregatorRunnerThread.start();
    } catch (Exception e) {
        throw new RuntimeException("failed to start aggregated modules: "
                + StringUtils.collectionToCommaDelimitedString(moduleLaunchRequests), e);
    }
}

From source file:org.springframework.cloud.dataflow.app.launcher.ModuleLauncher.java

public void launchIndividualModules(List<ModuleLaunchRequest> moduleLaunchRequests) {
    List<ModuleLaunchRequest> reversed = new ArrayList<>(moduleLaunchRequests);
    Collections.reverse(reversed);
    for (ModuleLaunchRequest moduleLaunchRequest : reversed) {
        String module = moduleLaunchRequest.getModule();
        Map<String, String> arguments = moduleLaunchRequest.getArguments();
        if (arguments.containsKey(INCLUDE_DEPENDENCIES_ARG)
                || arguments.containsKey(EXCLUDE_DEPENDENCIES_ARG)) {
            String includes = arguments.get(INCLUDE_DEPENDENCIES_ARG);
            String excludes = arguments.get(EXCLUDE_DEPENDENCIES_ARG);
            launchModuleWithDependencies(module, toArgArray(arguments),
                    StringUtils.commaDelimitedListToStringArray(includes),
                    StringUtils.commaDelimitedListToStringArray(excludes));
        } else {/*  w  w w . ja  v a 2  s.  c  om*/
            launchModule(module, toArgArray(arguments));
        }
    }
}

From source file:org.springframework.cloud.netflix.eureka.EurekaClientConfigBean.java

@Override
public List<String> getEurekaServerServiceUrls(String myZone) {
    String serviceUrls = this.serviceUrl.get(myZone);
    if (serviceUrls == null || serviceUrls.isEmpty()) {
        serviceUrls = this.serviceUrl.get(DEFAULT_ZONE);
    }/*w w  w.  j a  v a2  s .com*/
    if (!StringUtils.isEmpty(serviceUrls)) {
        final String[] serviceUrlsSplit = StringUtils.commaDelimitedListToStringArray(serviceUrls);
        List<String> eurekaServiceUrls = new ArrayList<>(serviceUrlsSplit.length);
        for (String eurekaServiceUrl : serviceUrlsSplit) {
            if (!endsWithSlash(eurekaServiceUrl)) {
                eurekaServiceUrl += "/";
            }
            eurekaServiceUrls.add(eurekaServiceUrl);
        }
        return eurekaServiceUrls;
    }

    return new ArrayList<>();
}

From source file:org.springframework.cloud.netflix.zuul.filters.pre.PreDecorationFilter.java

private void addProxyHeaders(RequestContext ctx, Route route) {
    HttpServletRequest request = ctx.getRequest();
    String host = toHostHeader(request);
    String port = String.valueOf(request.getServerPort());
    String proto = request.getScheme();
    if (hasHeader(request, X_FORWARDED_HOST_HEADER)) {
        host = request.getHeader(X_FORWARDED_HOST_HEADER) + "," + host;
    }//from ww  w .  j  a v a  2 s.c  o m
    if (!hasHeader(request, X_FORWARDED_PORT_HEADER)) {
        if (hasHeader(request, X_FORWARDED_PROTO_HEADER)) {
            StringBuilder builder = new StringBuilder();
            for (String previous : StringUtils
                    .commaDelimitedListToStringArray(request.getHeader(X_FORWARDED_PROTO_HEADER))) {
                if (builder.length() > 0) {
                    builder.append(",");
                }
                builder.append(HTTPS_SCHEME.equals(previous) ? HTTPS_PORT : HTTP_PORT);
            }
            builder.append(",").append(port);
            port = builder.toString();
        }
    } else {
        port = request.getHeader(X_FORWARDED_PORT_HEADER) + "," + port;
    }
    if (hasHeader(request, X_FORWARDED_PROTO_HEADER)) {
        proto = request.getHeader(X_FORWARDED_PROTO_HEADER) + "," + proto;
    }
    ctx.addZuulRequestHeader(X_FORWARDED_HOST_HEADER, host);
    ctx.addZuulRequestHeader(X_FORWARDED_PORT_HEADER, port);
    ctx.addZuulRequestHeader(X_FORWARDED_PROTO_HEADER, proto);
    addProxyPrefix(ctx, route);
}