Java Code Examples for org.springframework.util.StringUtils.commaDelimitedListToStringArray()

The following are Jave code examples for showing how to use commaDelimitedListToStringArray() of the org.springframework.util.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: gemini.blueprint   File: AbstractDependencyManagerTests.java   View Source Code Vote up 7 votes
/**
 * Locates (through the {@link ArtifactLocator}) an OSGi bundle given as a
 * String.
 * 
 * The default implementation expects the argument to be in Comma Separated
 * Values (CSV) format which indicates an artifact group, id, version and
 * optionally the type.
 * 
 * @param bundleId the bundle identifier in CSV format
 * @return a resource pointing to the artifact location
 */
protected Resource locateBundle(String bundleId) {
	Assert.hasText(bundleId, "bundleId should not be empty");

	// parse the String
	String[] artifactId = StringUtils.commaDelimitedListToStringArray(bundleId);

	Assert.isTrue(artifactId.length >= 3, "the CSV string " + bundleId + " contains too few values");
	// TODO: add a smarter mechanism which can handle 1 or 2 values CSVs
	for (int i = 0; i < artifactId.length; i++) {
		artifactId[i] = StringUtils.trimWhitespace(artifactId[i]);
	}

	ArtifactLocator aLocator = getLocator();

	return (artifactId.length == 3 ? aLocator.locateArtifact(artifactId[0], artifactId[1], artifactId[2])
			: aLocator.locateArtifact(artifactId[0], artifactId[1], artifactId[2], artifactId[3]));
}
 
Example 2
Project: cas-5.1.0   File: CasCoreBootstrapStandaloneConfiguration.java   View Source Code Vote up 6 votes
@ConfigurationPropertiesBinding
@Bean
public Converter<String, List<Class<? extends Throwable>>> commaSeparatedStringToThrowablesCollection() {
    return new Converter<String, List<Class<? extends Throwable>>>() {
        @Override
        public List<Class<? extends Throwable>> convert(final String source) {
            try {
                final List<Class<? extends Throwable>> classes = new ArrayList<>();
                for (final String className : StringUtils.commaDelimitedListToStringArray(source)) {
                    classes.add((Class<? extends Throwable>) ClassUtils.forName(className.trim(), getClass().getClassLoader()));
                }
                return classes;
            } catch (final Exception e) {
                throw new IllegalStateException(e);
            }
        }
    };
}
 
Example 3
Project: lams   File: WebUtils.java   View Source Code Vote up 6 votes
/**
 * Parse the given string with matrix variables. An example string would look
 * like this {@code "q1=a;q1=b;q2=a,b,c"}. The resulting map would contain
 * keys {@code "q1"} and {@code "q2"} with values {@code ["a","b"]} and
 * {@code ["a","b","c"]} respectively.
 *
 * @param matrixVariables the unparsed matrix variables string
 * @return a map with matrix variable names and values, never {@code null}
 */
public static MultiValueMap<String, String> parseMatrixVariables(String matrixVariables) {
	MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>();
	if (!StringUtils.hasText(matrixVariables)) {
		return result;
	}
	StringTokenizer pairs = new StringTokenizer(matrixVariables, ";");
	while (pairs.hasMoreTokens()) {
		String pair = pairs.nextToken();
		int index = pair.indexOf('=');
		if (index != -1) {
			String name = pair.substring(0, index);
			String rawValue = pair.substring(index + 1);
			for (String value : StringUtils.commaDelimitedListToStringArray(rawValue)) {
				result.add(name, value);
			}
		}
		else {
			result.add(pair, "");
		}
	}
	return result;
}
 
Example 4
Project: spring-velocity-adapter   File: SpringResourceLoader.java   View Source Code Vote up 6 votes
@Override
public void init(ExtendedProperties configuration) {
	this.resourceLoader = (org.springframework.core.io.ResourceLoader)
			this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER);
	String resourceLoaderPath = (String) this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER_PATH);
	if (this.resourceLoader == null) {
		throw new IllegalArgumentException(
				"'resourceLoader' application attribute must be present for SpringResourceLoader");
	}
	if (resourceLoaderPath == null) {
		throw new IllegalArgumentException(
				"'resourceLoaderPath' application attribute must be present for SpringResourceLoader");
	}
	this.resourceLoaderPaths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath);
	for (int i = 0; i < this.resourceLoaderPaths.length; i++) {
		String path = this.resourceLoaderPaths[i];
		if (!path.endsWith("/")) {
			this.resourceLoaderPaths[i] = path + "/";
		}
	}
	if (logger.isInfoEnabled()) {
		logger.info("SpringResourceLoader for Velocity: using resource loader [" + this.resourceLoader +
				"] and resource loader paths " + Arrays.asList(this.resourceLoaderPaths));
	}
}
 
Example 5
Project: lams   File: CacheAdviceParser.java   View Source Code Vote up 6 votes
<T extends CacheOperation> T merge(Element element, ReaderContext readerCtx, T op) {
	String cache = element.getAttribute("cache");

	// sanity check
	String[] localCaches = caches;
	if (StringUtils.hasText(cache)) {
		localCaches = StringUtils.commaDelimitedListToStringArray(cache.trim());
	} else {
		if (caches == null) {
			readerCtx.error("No cache specified specified for " + element.getNodeName(), element);
		}
	}
	op.setCacheNames(localCaches);

	op.setKey(getAttributeValue(element, "key", this.key));
	op.setCondition(getAttributeValue(element, "condition", this.condition));

	return op;
}
 
Example 6
Project: lams   File: SpringResourceLoader.java   View Source Code Vote up 6 votes
@Override
public void init(ExtendedProperties configuration) {
	this.resourceLoader = (org.springframework.core.io.ResourceLoader)
			this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER);
	String resourceLoaderPath = (String) this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER_PATH);
	if (this.resourceLoader == null) {
		throw new IllegalArgumentException(
				"'resourceLoader' application attribute must be present for SpringResourceLoader");
	}
	if (resourceLoaderPath == null) {
		throw new IllegalArgumentException(
				"'resourceLoaderPath' application attribute must be present for SpringResourceLoader");
	}
	this.resourceLoaderPaths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath);
	for (int i = 0; i < this.resourceLoaderPaths.length; i++) {
		String path = this.resourceLoaderPaths[i];
		if (!path.endsWith("/")) {
			this.resourceLoaderPaths[i] = path + "/";
		}
	}
	if (logger.isInfoEnabled()) {
		logger.info("SpringResourceLoader for Velocity: using resource loader [" + this.resourceLoader +
				"] and resource loader paths " + Arrays.asList(this.resourceLoaderPaths));
	}
}
 
Example 7
Project: spring-cloud-config-server-data   File: DataEnvironment.java   View Source Code Vote up 5 votes
@Override
public Environment findOne(String application, String profile, String label) {
    String[] profilesArray = StringUtils.commaDelimitedListToStringArray(profile);
    List<String> profilesList = createProfiles(profilesArray);
    List<String> labelsList = createLabels(label);

    try {
        List<DataPropertySource> dataPropertySourceList = sortJdbcPropertySourceBy(
                sortJdbcPropertySourceBy(
                        dataRepository.loadPropertySources(application, profilesList, labelsList),
                        Comparator.comparingInt(source -> labelsList.indexOf(source.getLabel()))
                ),
                Comparator.comparingInt(source -> profilesList.indexOf(source.getProfile()))
        );

        Environment environment = new Environment(application, profilesArray, label, null, null);

        environment.addAll(dataPropertySourceList.stream().
                map(jdbcPropertySource -> new PropertySource(
                                createSourceName(application, jdbcPropertySource),
                                internalYamlProcessor.flattenMap(jdbcPropertySource.getSource())
                        )
                ).
                collect(Collectors.toList())
        );

        return environment;
    } catch (Exception e) {
        throw new IllegalStateException("Unable to load environment configuration", e);
    }
}
 
Example 8
Project: gemini.blueprint   File: OsgiHeaderUtils.java   View Source Code Vote up 5 votes
private static String[] getHeaderAsTrimmedStringArray(Bundle bundle, String header) {
	if (bundle == null || !StringUtils.hasText(header))
		return new String[0];

	String headerContent = (String) bundle.getHeaders().get(header);
	String[] entries = StringUtils.commaDelimitedListToStringArray(headerContent);
	for (int i = 0; i < entries.length; i++) {
		entries[i] = entries[i].trim();
	}

	return entries;
}
 
Example 9
Project: lams   File: CacheAdviceParser.java   View Source Code Vote up 5 votes
Props(Element root) {
	String defaultCache = root.getAttribute("cache");
	key = root.getAttribute("key");
	condition = root.getAttribute("condition");
	method = root.getAttribute(METHOD_ATTRIBUTE);

	if (StringUtils.hasText(defaultCache)) {
		caches = StringUtils.commaDelimitedListToStringArray(defaultCache.trim());
	}
}
 
Example 10
Project: lams   File: MethodExclusionMBeanInfoAssembler.java   View Source Code Vote up 5 votes
/**
 * Set the mappings of bean keys to a comma-separated list of method names.
 * <p>These method names are <b>ignored</b> when creating the management interface.
 * <p>The property key must match the bean key and the property value must match
 * the list of method names. When searching for method names to ignore for a bean,
 * Spring will check these mappings first.
 */
public void setIgnoredMethodMappings(Properties mappings) {
	this.ignoredMethodMappings = new HashMap<String, Set<String>>();
	for (Enumeration<?> en = mappings.keys(); en.hasMoreElements();) {
		String beanKey = (String) en.nextElement();
		String[] methodNames = StringUtils.commaDelimitedListToStringArray(mappings.getProperty(beanKey));
		this.ignoredMethodMappings.put(beanKey, new HashSet<String>(Arrays.asList(methodNames)));
	}
}
 
Example 11
Project: lams   File: MethodNameBasedMBeanInfoAssembler.java   View Source Code Vote up 5 votes
/**
 * Set the mappings of bean keys to a comma-separated list of method names.
 * The property key should match the bean key and the property value should match
 * the list of method names. When searching for method names for a bean, Spring
 * will check these mappings first.
 * @param mappings the mappins of bean keys to method names
 */
public void setMethodMappings(Properties mappings) {
	this.methodMappings = new HashMap<String, Set<String>>();
	for (Enumeration<?> en = mappings.keys(); en.hasMoreElements();) {
		String beanKey = (String) en.nextElement();
		String[] methodNames = StringUtils.commaDelimitedListToStringArray(mappings.getProperty(beanKey));
		this.methodMappings.put(beanKey, new HashSet<String>(Arrays.asList(methodNames)));
	}
}
 
Example 12
Project: lams   File: BeanUtils.java   View Source Code Vote up 5 votes
/**
 * Parse a method signature in the form {@code methodName[([arg_list])]},
 * where {@code arg_list} is an optional, comma-separated list of fully-qualified
 * type names, and attempts to resolve that signature against the supplied {@code Class}.
 * <p>When not supplying an argument list ({@code methodName}) the method whose name
 * matches and has the least number of parameters will be returned. When supplying an
 * argument type list, only the method whose name and argument types match will be returned.
 * <p>Note then that {@code methodName} and {@code methodName()} are <strong>not</strong>
 * resolved in the same way. The signature {@code methodName} means the method called
 * {@code methodName} with the least number of arguments, whereas {@code methodName()}
 * means the method called {@code methodName} with exactly 0 arguments.
 * <p>If no method can be found, then {@code null} is returned.
 * @param signature the method signature as String representation
 * @param clazz the class to resolve the method signature against
 * @return the resolved Method
 * @see #findMethod
 * @see #findMethodWithMinimalParameters
 */
public static Method resolveSignature(String signature, Class<?> clazz) {
	Assert.hasText(signature, "'signature' must not be empty");
	Assert.notNull(clazz, "Class must not be null");
	int firstParen = signature.indexOf("(");
	int lastParen = signature.indexOf(")");
	if (firstParen > -1 && lastParen == -1) {
		throw new IllegalArgumentException("Invalid method signature '" + signature +
				"': expected closing ')' for args list");
	}
	else if (lastParen > -1 && firstParen == -1) {
		throw new IllegalArgumentException("Invalid method signature '" + signature +
				"': expected opening '(' for args list");
	}
	else if (firstParen == -1 && lastParen == -1) {
		return findMethodWithMinimalParameters(clazz, signature);
	}
	else {
		String methodName = signature.substring(0, firstParen);
		String[] parameterTypeNames =
				StringUtils.commaDelimitedListToStringArray(signature.substring(firstParen + 1, lastParen));
		Class<?>[] parameterTypes = new Class<?>[parameterTypeNames.length];
		for (int i = 0; i < parameterTypeNames.length; i++) {
			String parameterTypeName = parameterTypeNames[i].trim();
			try {
				parameterTypes[i] = ClassUtils.forName(parameterTypeName, clazz.getClassLoader());
			}
			catch (Throwable ex) {
				throw new IllegalArgumentException("Invalid method signature: unable to resolve type [" +
						parameterTypeName + "] for argument " + i + ". Root cause: " + ex);
			}
		}
		return findMethod(clazz, methodName, parameterTypes);
	}
}
 
Example 13
Project: spring-velocity-adapter   File: VelocityEngineFactory.java   View Source Code Vote up 4 votes
/**
 * Initialize a Velocity resource loader for the given VelocityEngine:
 * either a standard Velocity FileResourceLoader or a SpringResourceLoader.
 * <p>Called by {@code createVelocityEngine()}.
 * @param velocityEngine the VelocityEngine to configure
 * @param resourceLoaderPath the path to load Velocity resources from
 * @see org.apache.velocity.runtime.resource.loader.FileResourceLoader
 * @see SpringResourceLoader
 * @see #initSpringResourceLoader
 * @see #createVelocityEngine()
 */
protected void initVelocityResourceLoader(VelocityEngine velocityEngine, String resourceLoaderPath) {
	if (isPreferFileSystemAccess()) {
		// Try to load via the file system, fall back to SpringResourceLoader
		// (for hot detection of template changes, if possible).
		try {
			StringBuilder resolvedPath = new StringBuilder();
			String[] paths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath);
			for (int i = 0; i < paths.length; i++) {
				String path = paths[i];
				Resource resource = getResourceLoader().getResource(path);
				File file = resource.getFile();  // will fail if not resolvable in the file system
				if (logger.isDebugEnabled()) {
					logger.debug("Resource loader path [" + path + "] resolved to file [" + file.getAbsolutePath() + "]");
				}
				resolvedPath.append(file.getAbsolutePath());
				if (i < paths.length - 1) {
					resolvedPath.append(',');
				}
			}
			velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
			velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true");
			velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, resolvedPath.toString());
		}
		catch (IOException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Cannot resolve resource loader path [" + resourceLoaderPath +
						"] to [java.io.File]: using SpringResourceLoader", ex);
			}
			initSpringResourceLoader(velocityEngine, resourceLoaderPath);
		}
	}
	else {
		// Always load via SpringResourceLoader
		// (without hot detection of template changes).
		if (logger.isDebugEnabled()) {
			logger.debug("File system access not preferred: using SpringResourceLoader");
		}
		initSpringResourceLoader(velocityEngine, resourceLoaderPath);
	}
}
 
Example 14
Project: lams   File: TransactionAttributeEditor.java   View Source Code Vote up 4 votes
/**
 * Format is PROPAGATION_NAME,ISOLATION_NAME,readOnly,timeout_NNNN,+Exception1,-Exception2.
 * Null or the empty string means that the method is non transactional.
 * @see java.beans.PropertyEditor#setAsText(java.lang.String)
 */
@Override
public void setAsText(String text) throws IllegalArgumentException {
	if (StringUtils.hasLength(text)) {
		// tokenize it with ","
		String[] tokens = StringUtils.commaDelimitedListToStringArray(text);
		RuleBasedTransactionAttribute attr = new RuleBasedTransactionAttribute();
		for (int i = 0; i < tokens.length; i++) {
			// Trim leading and trailing whitespace.
			String token = StringUtils.trimWhitespace(tokens[i].trim());
			// Check whether token contains illegal whitespace within text.
			if (StringUtils.containsWhitespace(token)) {
				throw new IllegalArgumentException(
						"Transaction attribute token contains illegal whitespace: [" + token + "]");
			}
			// Check token type.
			if (token.startsWith(RuleBasedTransactionAttribute.PREFIX_PROPAGATION)) {
				attr.setPropagationBehaviorName(token);
			}
			else if (token.startsWith(RuleBasedTransactionAttribute.PREFIX_ISOLATION)) {
				attr.setIsolationLevelName(token);
			}
			else if (token.startsWith(RuleBasedTransactionAttribute.PREFIX_TIMEOUT)) {
				String value = token.substring(DefaultTransactionAttribute.PREFIX_TIMEOUT.length());
				attr.setTimeout(Integer.parseInt(value));
			}
			else if (token.equals(RuleBasedTransactionAttribute.READ_ONLY_MARKER)) {
				attr.setReadOnly(true);
			}
			else if (token.startsWith(RuleBasedTransactionAttribute.PREFIX_COMMIT_RULE)) {
				attr.getRollbackRules().add(new NoRollbackRuleAttribute(token.substring(1)));
			}
			else if (token.startsWith(RuleBasedTransactionAttribute.PREFIX_ROLLBACK_RULE)) {
				attr.getRollbackRules().add(new RollbackRuleAttribute(token.substring(1)));
			}
			else {
				throw new IllegalArgumentException("Invalid transaction attribute token: [" + token + "]");
			}
		}
		setValue(attr);
	}
	else {
		setValue(null);
	}
}
 
Example 15
Project: lams   File: TxAdviceBeanDefinitionParser.java   View Source Code Vote up 4 votes
private void addRollbackRuleAttributesTo(List<RollbackRuleAttribute> rollbackRules, String rollbackForValue) {
	String[] exceptionTypeNames = StringUtils.commaDelimitedListToStringArray(rollbackForValue);
	for (String typeName : exceptionTypeNames) {
		rollbackRules.add(new RollbackRuleAttribute(StringUtils.trimWhitespace(typeName)));
	}
}
 
Example 16
Project: lams   File: TxAdviceBeanDefinitionParser.java   View Source Code Vote up 4 votes
private void addNoRollbackRuleAttributesTo(List<RollbackRuleAttribute> rollbackRules, String noRollbackForValue) {
	String[] exceptionTypeNames = StringUtils.commaDelimitedListToStringArray(noRollbackForValue);
	for (String typeName : exceptionTypeNames) {
		rollbackRules.add(new NoRollbackRuleAttribute(StringUtils.trimWhitespace(typeName)));
	}
}
 
Example 17
Project: lams   File: BeanDefinitionParserDelegate.java   View Source Code Vote up 4 votes
/**
 * Return any patterns provided in the 'default-autowire-candidates'
 * attribute of the top-level {@code &lt;beans/&gt;} element.
 */
public String[] getAutowireCandidatePatterns() {
	String candidatePattern = this.defaults.getAutowireCandidates();
	return (candidatePattern != null ? StringUtils.commaDelimitedListToStringArray(candidatePattern) : null);
}
 
Example 18
Project: lams   File: AbstractAspectJAdvice.java   View Source Code Vote up 2 votes
/**
 * Set by creator of this advice object if the argument names are known.
 * <p>This could be for example because they have been explicitly specified in XML,
 * or in an advice annotation.
 * @param argNames comma delimited list of arg names
 */
public void setArgumentNames(String argNames) {
	String[] tokens = StringUtils.commaDelimitedListToStringArray(argNames);
	setArgumentNamesFromStringArray(tokens);
}
 
Example 19
Project: gemini.blueprint   File: AbstractConfigurableBundleCreatorTests.java   View Source Code Vote up 2 votes
/**
 * {@inheritDoc}
 * <p/>
 * <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/>
 * <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));
}
 
Example 20
Project: lams   File: ManagedNotification.java   View Source Code Vote up 2 votes
/**
 * Set a single notification type, or a list of notification types
 * as comma-delimited String.
 */
public void setNotificationType(String notificationType) {
	this.notificationTypes = StringUtils.commaDelimitedListToStringArray(notificationType);
}