Example usage for org.springframework.util StringUtils collectionToCommaDelimitedString

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

Introduction

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

Prototype

public static String collectionToCommaDelimitedString(@Nullable Collection<?> coll) 

Source Link

Document

Convert a Collection into a delimited String (e.g., CSV).

Usage

From source file:org.springframework.boot.context.initializer.VcapApplicationContextInitializer.java

private void flatten(Properties properties, Map<String, Object> input, String path) {
    for (Entry<String, Object> entry : input.entrySet()) {
        String key = entry.getKey();
        if (StringUtils.hasText(path)) {
            if (key.startsWith("[")) {
                key = path + key;//from  w  w  w  . ja v a 2s . co m
            } else {
                key = path + "." + key;
            }
        }
        Object value = entry.getValue();
        if (value instanceof String) {
            properties.put(key, value);
        } else if (value instanceof Map) {
            // Need a compound key
            @SuppressWarnings("unchecked")
            Map<String, Object> map = (Map<String, Object>) value;
            flatten(properties, map, key);
        } else if (value instanceof Collection) {
            // Need a compound key
            @SuppressWarnings("unchecked")
            Collection<Object> collection = (Collection<Object>) value;
            properties.put(key, StringUtils.collectionToCommaDelimitedString(collection));
            int count = 0;
            for (Object object : collection) {
                flatten(properties, Collections.singletonMap("[" + (count++) + "]", object), key);
            }
        } else {
            properties.put(key, value == null ? "" : value);
        }
    }
}

From source file:org.springframework.boot.devtools.restart.ChangeableUrls.java

private static List<URL> getUrlsFromManifestClassPathAttribute(URL jarUrl, JarFile jarFile) throws IOException {
    Manifest manifest = jarFile.getManifest();
    if (manifest == null) {
        return Collections.emptyList();
    }/* w w  w  .j  a v  a2 s.c o m*/
    String classPath = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
    if (!StringUtils.hasText(classPath)) {
        return Collections.emptyList();
    }
    String[] entries = StringUtils.delimitedListToStringArray(classPath, " ");
    List<URL> urls = new ArrayList<>(entries.length);
    List<URL> nonExistentEntries = new ArrayList<>();
    for (String entry : entries) {
        try {
            URL referenced = new URL(jarUrl, entry);
            if (new File(referenced.getFile()).exists()) {
                urls.add(referenced);
            } else {
                nonExistentEntries.add(referenced);
            }
        } catch (MalformedURLException ex) {
            throw new IllegalStateException("Class-Path attribute contains malformed URL", ex);
        }
    }
    if (!nonExistentEntries.isEmpty()) {
        System.out.println("The Class-Path manifest attribute in " + jarFile.getName()
                + " referenced one or more files that do not exist: "
                + StringUtils.collectionToCommaDelimitedString(nonExistentEntries));
    }
    return urls;
}

From source file:org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext.java

private void registerBeans(AnnotatedBeanDefinitionReader reader) {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Registering supplied beans: ["
                + StringUtils.collectionToCommaDelimitedString(this.registeredBeans) + "]");
    }//from w  ww  . j  a  v  a  2  s. c  o m
    this.registeredBeans.forEach(
            (reg) -> reader.registerBean(reg.getAnnotatedClass(), reg.getSupplier(), reg.getQualifiers()));
}

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

private String getLocations(String[] locations, String label) {
    List<String> output = new ArrayList<String>();
    for (String location : locations) {
        output.add(location);//ww w.  j  a  v a2 s.c om
    }
    for (String location : locations) {
        if (isDirectory(location) && StringUtils.hasText(label)) {
            output.add(location + label.trim() + "/");
        }
    }
    return StringUtils.collectionToCommaDelimitedString(output);
}

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

public void launchAggregatedModules(List<ModuleLaunchRequest> moduleLaunchRequests,
        Map<String, String> aggregateArgs) {
    try {// w  w  w.  j  a  va  2s. 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.resolver.AetherModuleResolver.java

/**
 * Create an instance specifying the locations of the local and remote repositories.
 * @param localRepository the root path of the local maven repository
 * @param remoteRepositories a Map containing pairs of (repository ID,repository URL). This
 * may be null or empty if the local repository is off line.
 * @param mavenProperties the properties for the maven repository, proxy settings.
 *///from  ww w  .  j  av  a 2  s .  co m
public AetherModuleResolver(File localRepository, Map<String, String> remoteRepositories,
        final MavenProperties mavenProperties) {
    Assert.notNull(localRepository, "Local repository path cannot be null");
    if (log.isDebugEnabled()) {
        log.debug("Local repository: " + localRepository);
        if (!CollectionUtils.isEmpty(remoteRepositories)) {
            // just listing the values, ids are simply informative
            log.debug("Remote repositories: "
                    + StringUtils.collectionToCommaDelimitedString(remoteRepositories.values()));
        }
    }
    if (mavenProperties != null) {
        this.proxyProperties = mavenProperties.getProxy();
    }
    if (isProxyEnabled() && proxyHasCredentials()) {
        this.authentication = new Authentication() {
            @Override
            public void fill(AuthenticationContext context, String key, Map<String, String> data) {
                context.put(AuthenticationContext.USERNAME, mavenProperties.getProxy().getAuth().getUsername());
                context.put(AuthenticationContext.PASSWORD, mavenProperties.getProxy().getAuth().getPassword());
            }

            @Override
            public void digest(AuthenticationDigest digest) {
                digest.update(AuthenticationContext.USERNAME, proxyProperties.getAuth().getUsername(),
                        AuthenticationContext.PASSWORD, proxyProperties.getAuth().getPassword());
            }
        };
    }
    if (!localRepository.exists()) {
        Assert.isTrue(localRepository.mkdirs(),
                "Unable to create directory for local repository: " + localRepository);
    }
    this.localRepository = localRepository;
    this.remoteRepositories = new LinkedList<>();
    if (!CollectionUtils.isEmpty(remoteRepositories)) {
        for (Map.Entry<String, String> remoteRepo : remoteRepositories.entrySet()) {
            RemoteRepository.Builder remoteRepositoryBuilder = new RemoteRepository.Builder(remoteRepo.getKey(),
                    DEFAULT_CONTENT_TYPE, remoteRepo.getValue());
            if (isProxyEnabled()) {
                if (this.authentication != null) {
                    remoteRepositoryBuilder.setProxy(new Proxy(proxyProperties.getProtocol(),
                            proxyProperties.getHost(), proxyProperties.getPort(), authentication));
                } else {
                    //If proxy doesn't need authentication to use it
                    remoteRepositoryBuilder.setProxy(new Proxy(proxyProperties.getProtocol(),
                            proxyProperties.getHost(), proxyProperties.getPort()));
                }
            }
            this.remoteRepositories.add(remoteRepositoryBuilder.build());
        }
    }
    repositorySystem = newRepositorySystem();
}

From source file:org.springframework.cloud.deployer.resource.maven.MavenArtifactResolver.java

/**
 * Create an instance using the provided properties.
 *
 * @param properties the properties for the maven repositories, proxies, and authentication
 *//*ww  w. j a  v a2s  . c  om*/
public MavenArtifactResolver(final MavenProperties properties) {
    Assert.notNull(properties, "MavenProperties must not be null");
    Assert.notNull(properties.getLocalRepository(), "Local repository path cannot be null");
    if (log.isDebugEnabled()) {
        log.debug("Local repository: " + properties.getLocalRepository());
        log.debug("Remote repositories: "
                + StringUtils.collectionToCommaDelimitedString(properties.getRemoteRepositories().keySet()));
    }
    this.properties = properties;
    if (isProxyEnabled() && proxyHasCredentials()) {
        final String username = this.properties.getProxy().getAuth().getUsername();
        final String password = this.properties.getProxy().getAuth().getPassword();
        this.authentication = newAuthentication(username, password);
    } else {
        this.authentication = null;
    }
    File localRepository = new File(this.properties.getLocalRepository());
    if (!localRepository.exists()) {
        boolean created = localRepository.mkdirs();
        // May have been created by another thread after above check. Double check.
        Assert.isTrue(created || localRepository.exists(),
                "Unable to create directory for local repository: " + localRepository);
    }
    for (Map.Entry<String, MavenProperties.RemoteRepository> entry : this.properties.getRemoteRepositories()
            .entrySet()) {
        MavenProperties.RemoteRepository remoteRepository = entry.getValue();
        RemoteRepository.Builder remoteRepositoryBuilder = new RemoteRepository.Builder(entry.getKey(),
                DEFAULT_CONTENT_TYPE, remoteRepository.getUrl());
        // Update policies when set.
        if (remoteRepository.getPolicy() != null) {
            remoteRepositoryBuilder.setPolicy(new RepositoryPolicy(remoteRepository.getPolicy().isEnabled(),
                    remoteRepository.getPolicy().getUpdatePolicy(),
                    remoteRepository.getPolicy().getChecksumPolicy()));
        }
        if (remoteRepository.getReleasePolicy() != null) {
            remoteRepositoryBuilder
                    .setReleasePolicy(new RepositoryPolicy(remoteRepository.getReleasePolicy().isEnabled(),
                            remoteRepository.getReleasePolicy().getUpdatePolicy(),
                            remoteRepository.getReleasePolicy().getChecksumPolicy()));
        }
        if (remoteRepository.getSnapshotPolicy() != null) {
            remoteRepositoryBuilder
                    .setSnapshotPolicy(new RepositoryPolicy(remoteRepository.getSnapshotPolicy().isEnabled(),
                            remoteRepository.getSnapshotPolicy().getUpdatePolicy(),
                            remoteRepository.getSnapshotPolicy().getChecksumPolicy()));
        }
        if (isProxyEnabled()) {
            MavenProperties.Proxy proxyProperties = this.properties.getProxy();
            if (this.authentication != null) {
                remoteRepositoryBuilder.setProxy(new Proxy(proxyProperties.getProtocol(),
                        proxyProperties.getHost(), proxyProperties.getPort(), this.authentication));
            } else {
                // if proxy does not require authentication
                remoteRepositoryBuilder.setProxy(new Proxy(proxyProperties.getProtocol(),
                        proxyProperties.getHost(), proxyProperties.getPort()));
            }
        }
        if (remoteRepositoryHasCredentials(remoteRepository)) {
            final String username = remoteRepository.getAuth().getUsername();
            final String password = remoteRepository.getAuth().getPassword();
            remoteRepositoryBuilder.setAuthentication(newAuthentication(username, password));
        }
        this.remoteRepositories.add(remoteRepositoryBuilder.build());
    }
    this.repositorySystem = newRepositorySystem();
}

From source file:org.springframework.cloud.stream.app.yahoo.quotes.source.YahooQuotesClientImpl.java

private String wouldbeSimplerWithLambdas(List<String> symbols) {
    for (int i = 0; i < symbols.size(); i++) {
        if (!symbols.get(i).startsWith("'") && !symbols.get(i).startsWith("\\"))
            symbols.set(i, StringUtils.quote(symbols.get(i)));
    }//from   w ww . java  2  s  .co m
    return StringUtils.collectionToCommaDelimitedString(symbols);
}

From source file:org.springframework.cloud.stream.binding.BindableProxyFactory.java

private BindingTargetFactory getBindingTargetFactory(Class<?> bindingTargetType) {
    List<String> candidateBindingTargetFactories = new ArrayList<>();
    for (Map.Entry<String, BindingTargetFactory> bindingTargetFactoryEntry : this.bindingTargetFactories
            .entrySet()) {//w ww .ja  v  a  2 s.  c  o  m
        if (bindingTargetFactoryEntry.getValue().canCreate(bindingTargetType)) {
            candidateBindingTargetFactories.add(bindingTargetFactoryEntry.getKey());
        }
    }
    if (candidateBindingTargetFactories.size() == 1) {
        return this.bindingTargetFactories.get(candidateBindingTargetFactories.get(0));
    } else {
        if (candidateBindingTargetFactories.size() == 0) {
            throw new IllegalStateException("No factory found for binding target type: "
                    + bindingTargetType.getName() + " among registered factories: "
                    + StringUtils.collectionToCommaDelimitedString(bindingTargetFactories.keySet()));
        } else {
            throw new IllegalStateException(
                    "Multiple factories found for binding target type: " + bindingTargetType.getName() + ": "
                            + StringUtils.collectionToCommaDelimitedString(candidateBindingTargetFactories));
        }
    }
}

From source file:org.springframework.cloud.stream.module.resolver.AetherModuleResolver.java

/**
 * Create an instance specifying the locations of the local and remote repositories.
 * @param localRepository the root path of the local maven repository
 * @param remoteRepositories a Map containing pairs of (repository ID,repository URL). This
 * may be null or empty if the local repository is off line.
 * @param proxyProperties the proxy properties for the maven proxy settings.
 *///from   w  ww .j a  va2  s .c  o m
public AetherModuleResolver(File localRepository, Map<String, String> remoteRepositories,
        final AetherProxyProperties proxyProperties) {
    Assert.notNull(localRepository, "Local repository path cannot be null");
    if (log.isDebugEnabled()) {
        log.debug("Local repository: " + localRepository);
        if (!CollectionUtils.isEmpty(remoteRepositories)) {
            // just listing the values, ids are simply informative
            log.debug("Remote repositories: "
                    + StringUtils.collectionToCommaDelimitedString(remoteRepositories.values()));
        }
    }
    this.proxyProperties = proxyProperties;
    if (isProxyEnabled() && proxyHasCredentials()) {
        this.authentication = new Authentication() {
            @Override
            public void fill(AuthenticationContext context, String key, Map<String, String> data) {
                context.put(context.USERNAME, proxyProperties.getAuth().getUsername());
                context.put(context.PASSWORD, proxyProperties.getAuth().getPassword());
            }

            @Override
            public void digest(AuthenticationDigest digest) {
                digest.update(AuthenticationContext.USERNAME, proxyProperties.getAuth().getUsername(),
                        AuthenticationContext.PASSWORD, proxyProperties.getAuth().getPassword());
            }
        };
    }
    if (!localRepository.exists()) {
        Assert.isTrue(localRepository.mkdirs(),
                "Unable to create directory for local repository: " + localRepository);
    }
    this.localRepository = localRepository;
    this.remoteRepositories = new LinkedList<>();
    if (!CollectionUtils.isEmpty(remoteRepositories)) {
        for (Map.Entry<String, String> remoteRepo : remoteRepositories.entrySet()) {
            RemoteRepository.Builder remoteRepositoryBuilder = new RemoteRepository.Builder(remoteRepo.getKey(),
                    DEFAULT_CONTENT_TYPE, remoteRepo.getValue());
            if (this.authentication != null) {
                //todo: Set direct authentication for the remote repositories
                remoteRepositoryBuilder.setProxy(new Proxy(proxyProperties.getProtocol(),
                        proxyProperties.getHost(), proxyProperties.getPort(), authentication));
            } else {
                remoteRepositoryBuilder.setProxy(new Proxy(proxyProperties.getProtocol(),
                        proxyProperties.getHost(), proxyProperties.getPort()));
            }
            this.remoteRepositories.add(remoteRepositoryBuilder.build());
        }
    }
    repositorySystem = newRepositorySystem();
}