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

The following are Jave code examples for showing how to use trimWhitespace() 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: lams   File: AspectJAdviceParameterNameDiscoverer.java   View Source Code Vote up 6 votes
/**
 * Given an args pointcut body (could be {@code args} or {@code at_args}),
 * add any candidate variable names to the given list.
 */
private void maybeExtractVariableNamesFromArgs(String argsSpec, List<String> varNames) {
	if (argsSpec == null) {
		return;
	}
	String[] tokens = StringUtils.tokenizeToStringArray(argsSpec, ",");
	for (int i = 0; i < tokens.length; i++) {
		tokens[i] = StringUtils.trimWhitespace(tokens[i]);
		String varName = maybeExtractVariableName(tokens[i]);
		if (varName != null) {
			varNames.add(varName);
		}
	}
}
 
Example 3
Project: lams   File: AbstractAspectJAdvice.java   View Source Code Vote up 6 votes
public void setArgumentNamesFromStringArray(String[] args) {
	this.argumentNames = new String[args.length];
	for (int i = 0; i < args.length; i++) {
		this.argumentNames[i] = StringUtils.trimWhitespace(args[i]);
		if (!isVariableName(this.argumentNames[i])) {
			throw new IllegalArgumentException(
					"'argumentNames' property of AbstractAspectJAdvice contains an argument name '" +
					this.argumentNames[i] + "' that is not a valid Java identifier");
		}
	}
	if (argumentNames != null) {
		if (aspectJAdviceMethod.getParameterTypes().length == argumentNames.length + 1) {
			// May need to add implicit join point arg name...
			Class<?> firstArgType = aspectJAdviceMethod.getParameterTypes()[0];
			if (firstArgType == JoinPoint.class ||
					firstArgType == ProceedingJoinPoint.class ||
					firstArgType == JoinPoint.StaticPart.class) {
				String[] oldNames = argumentNames;
				argumentNames = new String[oldNames.length + 1];
				argumentNames[0] = "THIS_JOIN_POINT";
				System.arraycopy(oldNames, 0, argumentNames, 1, oldNames.length);
			}
		}
	}
}
 
Example 4
Project: gemini.blueprint   File: ManifestUtils.java   View Source Code Vote up 5 votes
/**
 * Determine the Import-Package value based on the Export-Package entries in
 * the jars given as Resources.
 * @param resources
 * @return
 */
public static String[] determineImportPackages(Resource[] resources) {
	Set collection = new LinkedHashSet();
	// for each resource
	for (int i = 0; i < resources.length; i++) {
		Resource resource = resources[i];
		Manifest man = JarUtils.getManifest(resource);
		if (man != null) {
			// read the manifest
			// get the Export-Package
			Attributes attrs = man.getMainAttributes();
			String exportedPackages = attrs.getValue(Constants.EXPORT_PACKAGE);
			// add it to the StringBuilder
			if (StringUtils.hasText(exportedPackages)) {
				collection.addAll(StringUtils.commaDelimitedListToSet(exportedPackages));
			}
		}
	}
	// return the result as string
	String[] array = (String[]) collection.toArray(new String[collection.size()]);

	// clean whitespace just in case
	for (int i = 0; i < array.length; i++) {
		array[i] = StringUtils.trimWhitespace(array[i]);
	}
	return array;
}
 
Example 5
Project: lams   File: AbstractRegexpMethodPointcut.java   View Source Code Vote up 5 votes
/**
 * Set the regular expressions defining methods to match.
 * Matching will be the union of all these; if any match, the pointcut matches.
 * @see #setPattern
 */
public void setPatterns(String... patterns) {
	Assert.notEmpty(patterns, "'patterns' must not be empty");
	this.patterns = new String[patterns.length];
	for (int i = 0; i < patterns.length; i++) {
		this.patterns[i] = StringUtils.trimWhitespace(patterns[i]);
	}
	initPatternRepresentation(this.patterns);
}
 
Example 6
Project: lams   File: AbstractRegexpMethodPointcut.java   View Source Code Vote up 5 votes
/**
 * Set the regular expressions defining methods to match for exclusion.
 * Matching will be the union of all these; if any match, the pointcut matches.
 * @see #setExcludedPattern
 */
public void setExcludedPatterns(String... excludedPatterns) {
	Assert.notEmpty(excludedPatterns, "'excludedPatterns' must not be empty");
	this.excludedPatterns = new String[excludedPatterns.length];
	for (int i = 0; i < excludedPatterns.length; i++) {
		this.excludedPatterns[i] = StringUtils.trimWhitespace(excludedPatterns[i]);
	}
	initExcludedPatternRepresentation(this.excludedPatterns);
}
 
Example 7
Project: alfresco-data-model   File: SearchLanguageConversion.java   View Source Code Vote up 5 votes
public static String[] tokenizeString(String query)
{
    String trimmed = StringUtils.trimWhitespace(query);
    if (trimmed == null || trimmed.length() < 1) return new String[]{query};
    List<String> split = new ArrayList<String>();
    
    char[] toSplit = trimmed.toCharArray();
    StringBuffer buff = new StringBuffer();
    
    for (char c : toSplit) {
        if (Character.isWhitespace(c))
        {
            if (buff.length() > 0)
            {
                split.add(buff.toString());
                buff = new StringBuffer();
            }
        }
        else 
        {
            buff.append(c);
        }
    }
    
    if (buff.length() > 0)
    {
        split.add(buff.toString());
    }

    return split.toArray(new String[split.size()]);
}
 
Example 8
Project: gemini.blueprint   File: ConfigUtils.java   View Source Code Vote up 4 votes
public static boolean matchExtenderVersionRange(Bundle bundle, String header, Version versionToMatch) {
	Assert.notNull(bundle);
	// get version range
	String range = (String) bundle.getHeaders().get(header);

	boolean trace = log.isTraceEnabled();

	// empty value = empty version = *
	if (!StringUtils.hasText(range))
		return true;

	if (trace)
		log.trace("discovered " + header + " header w/ value=" + range);

	// do we have a range or not ?
	range = StringUtils.trimWhitespace(range);

	// a range means one comma
	int commaNr = StringUtils.countOccurrencesOf(range, COMMA);

	// no comma, no intervals
	if (commaNr == 0) {
		Version version = Version.parseVersion(range);

		return versionToMatch.equals(version);
	}

	if (commaNr == 1) {

		// sanity check
		if (!((range.startsWith(LEFT_CLOSED_INTERVAL) || range.startsWith(LEFT_OPEN_INTERVAL)) && (range.endsWith(RIGHT_CLOSED_INTERVAL) || range.endsWith(RIGHT_OPEN_INTERVAL)))) {
			throw new IllegalArgumentException("range [" + range + "] is invalid");
		}

		boolean equalMin = range.startsWith(LEFT_CLOSED_INTERVAL);
		boolean equalMax = range.endsWith(RIGHT_CLOSED_INTERVAL);

		// remove interval brackets
		range = range.substring(1, range.length() - 1);

		// split the remaining string in two pieces
		String[] pieces = StringUtils.split(range, COMMA);

		if (trace)
			log.trace("discovered low/high versions : " + ObjectUtils.nullSafeToString(pieces));

		Version minVer = Version.parseVersion(pieces[0]);
		Version maxVer = Version.parseVersion(pieces[1]);

		if (trace)
			log.trace("comparing version " + versionToMatch + " w/ min=" + minVer + " and max=" + maxVer);

		boolean result = true;

		int compareMin = versionToMatch.compareTo(minVer);

		if (equalMin)
			result = (result && (compareMin >= 0));
		else
			result = (result && (compareMin > 0));

		int compareMax = versionToMatch.compareTo(maxVer);

		if (equalMax)
			result = (result && (compareMax <= 0));
		else
			result = (result && (compareMax < 0));

		return result;
	}

	// more then one comma means incorrect range

	throw new IllegalArgumentException("range [" + range + "] is invalid");
}
 
Example 9
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 10
Project: lams   File: SimpleConstructorNamespaceHandler.java   View Source Code Vote up 4 votes
@Override
public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) {
	if (node instanceof Attr) {
		Attr attr = (Attr) node;
		String argName = StringUtils.trimWhitespace(parserContext.getDelegate().getLocalName(attr));
		String argValue = StringUtils.trimWhitespace(attr.getValue());

		ConstructorArgumentValues cvs = definition.getBeanDefinition().getConstructorArgumentValues();
		boolean ref = false;

		// handle -ref arguments
		if (argName.endsWith(REF_SUFFIX)) {
			ref = true;
			argName = argName.substring(0, argName.length() - REF_SUFFIX.length());
		}

		ValueHolder valueHolder = new ValueHolder(ref ? new RuntimeBeanReference(argValue) : argValue);
		valueHolder.setSource(parserContext.getReaderContext().extractSource(attr));

		// handle "escaped"/"_" arguments
		if (argName.startsWith(DELIMITER_PREFIX)) {
			String arg = argName.substring(1).trim();

			// fast default check
			if (!StringUtils.hasText(arg)) {
				cvs.addGenericArgumentValue(valueHolder);
			}
			// assume an index otherwise
			else {
				int index = -1;
				try {
					index = Integer.parseInt(arg);
				} catch (NumberFormatException ex) {
					parserContext.getReaderContext().error(
							"Constructor argument '" + argName + "' specifies an invalid integer", attr);
				}
				if (index < 0) {
					parserContext.getReaderContext().error(
							"Constructor argument '" + argName + "' specifies a negative index", attr);
				}

				if (cvs.hasIndexedArgumentValue(index)){
					parserContext.getReaderContext().error(
							"Constructor argument '" + argName + "' with index "+ index+" already defined using <constructor-arg>." +
							" Only one approach may be used per argument.", attr);
				}

				cvs.addIndexedArgumentValue(index, valueHolder);
			}
		}
		// no escaping -> ctr name
		else {
			String name = Conventions.attributeNameToPropertyName(argName);
			if (containsArgWithName(name, cvs)){
				parserContext.getReaderContext().error(
						"Constructor argument '" + argName + "' already defined using <constructor-arg>." +
						" Only one approach may be used per argument.", attr);
			}
			valueHolder.setName(Conventions.attributeNameToPropertyName(argName));
			cvs.addGenericArgumentValue(valueHolder);
		}
	}
	return definition;
}