Java Code Examples for org.springframework.util.StringUtils#tokenizeToStringArray()

The following examples show how to use org.springframework.util.StringUtils#tokenizeToStringArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpHeaders.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the set of allowed {@link HttpMethod HTTP methods},
 * as specified by the {@code Allow} header.
 * <p>Returns an empty set when the allowed methods are unspecified.
 */
public Set<HttpMethod> getAllow() {
	String value = getFirst(ALLOW);
	if (!StringUtils.isEmpty(value)) {
		String[] tokens = StringUtils.tokenizeToStringArray(value, ",");
		List<HttpMethod> result = new ArrayList<HttpMethod>(tokens.length);
		for (String token : tokens) {
			HttpMethod resolved = HttpMethod.resolve(token);
			if (resolved != null) {
				result.add(resolved);
			}
		}
		return EnumSet.copyOf(result);
	}
	else {
		return EnumSet.noneOf(HttpMethod.class);
	}
}
 
Example 2
Source File: HttpEntityMethodProcessor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private List<String> getVaryRequestHeadersToAdd(HttpHeaders responseHeaders, HttpHeaders entityHeaders) {
	List<String> entityHeadersVary = entityHeaders.getVary();
	List<String> vary = responseHeaders.get(HttpHeaders.VARY);
	if (vary != null) {
		List<String> result = new ArrayList<String>(entityHeadersVary);
		for (String header : vary) {
			for (String existing : StringUtils.tokenizeToStringArray(header, ",")) {
				if ("*".equals(existing)) {
					return Collections.emptyList();
				}
				for (String value : entityHeadersVary) {
					if (value.equalsIgnoreCase(existing)) {
						result.remove(value);
					}
				}
			}
		}
		return result;
	}
	return entityHeadersVary;
}
 
Example 3
Source File: DefaultMultipartMessageReader.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Convert the given data buffer into a {@link HttpHeaders} instance. The given string is read
 * as US-ASCII, then split along \r\n line boundaries, each line containing a header name and
 * value(s).
 */
private static HttpHeaders toHeaders(DataBuffer dataBuffer) {
	byte[] bytes = new byte[dataBuffer.readableByteCount()];
	dataBuffer.read(bytes);
	DataBufferUtils.release(dataBuffer);
	String string = new String(bytes, StandardCharsets.US_ASCII);
	String[] lines = string.split(HEADER_SEPARATOR);
	HttpHeaders result = new HttpHeaders();
	for (String line : lines) {
		int idx = line.indexOf(':');
		if (idx != -1) {
			String name = line.substring(0, idx);
			String value = line.substring(idx + 1);
			while (value.startsWith(" ")) {
				value = value.substring(1);
			}
			String[] tokens = StringUtils.tokenizeToStringArray(value, ",");
			for (String token : tokens) {
				result.add(name, token);
			}
		}
	}
	return result;
}
 
Example 4
Source File: WebContentGenerator.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private Collection<String> getVaryRequestHeadersToAdd(HttpServletResponse response, String[] varyByRequestHeaders) {
	if (!response.containsHeader(HttpHeaders.VARY)) {
		return Arrays.asList(varyByRequestHeaders);
	}
	Collection<String> result = new ArrayList<>(varyByRequestHeaders.length);
	Collections.addAll(result, varyByRequestHeaders);
	for (String header : response.getHeaders(HttpHeaders.VARY)) {
		for (String existing : StringUtils.tokenizeToStringArray(header, ",")) {
			if ("*".equals(existing)) {
				return Collections.emptyList();
			}
			for (String value : varyByRequestHeaders) {
				if (value.equalsIgnoreCase(existing)) {
					result.remove(value);
				}
			}
		}
	}
	return result;
}
 
Example 5
Source File: CronSequenceGenerator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parse the given pattern expression.
 */
private void parse(String expression) throws IllegalArgumentException {
	String[] fields = StringUtils.tokenizeToStringArray(expression, " ");
	if (!areValidCronFields(fields)) {
		throw new IllegalArgumentException(String.format(
				"Cron expression must consist of 6 fields (found %d in \"%s\")", fields.length, expression));
	}
	doParse(fields);
}
 
Example 6
Source File: ComponentScanBeanDefinitionParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
	String basePackage = element.getAttribute(BASE_PACKAGE_ATTRIBUTE);
	basePackage = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(basePackage);
	String[] basePackages = StringUtils.tokenizeToStringArray(basePackage,
			ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);

	// Actually scan for bean definitions and register them.
	ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);
	Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);
	registerComponents(parserContext.getReaderContext(), beanDefinitions, element);

	return null;
}
 
Example 7
Source File: AspectJAdviceParameterNameDiscoverer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Match up args against unbound arguments of primitive types
 */
private void maybeBindPrimitiveArgsFromPointcutExpression() {
	int numUnboundPrimitives = countNumberOfUnboundPrimitiveArguments();
	if (numUnboundPrimitives > 1) {
		throw new AmbiguousBindingException("Found '" + numUnboundPrimitives +
				"' unbound primitive arguments with no way to distinguish between them.");
	}
	if (numUnboundPrimitives == 1) {
		// Look for arg variable and bind it if we find exactly one...
		List<String> varNames = new ArrayList<String>();
		String[] tokens = StringUtils.tokenizeToStringArray(this.pointcutExpression, " ");
		for (int i = 0; i < tokens.length; i++) {
			if (tokens[i].equals("args") || tokens[i].startsWith("args(")) {
				PointcutBody body = getPointcutBody(tokens, i);
				i += body.numTokensConsumed;
				maybeExtractVariableNamesFromArgs(body.text, varNames);
			}
		}
		if (varNames.size() > 1) {
			throw new AmbiguousBindingException("Found " + varNames.size() +
					" candidate variable names but only one candidate binding slot when matching primitive args");
		}
		else if (varNames.size() == 1) {
			// 1 primitive arg, and one candidate...
			for (int i = 0; i < this.argumentTypes.length; i++) {
				if (isUnbound(i) && this.argumentTypes[i].isPrimitive()) {
					bindParameterName(i, varNames.get(0));
					break;
				}
			}
		}
	}
}
 
Example 8
Source File: DefaultBeanDefinitionDocumentReader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Register each bean definition within the given root {@code <beans/>} element.
 */
protected void doRegisterBeanDefinitions(Element root) {
	// Any nested <beans> elements will cause recursion in this method. In
	// order to propagate and preserve <beans> default-* attributes correctly,
	// keep track of the current (parent) delegate, which may be null. Create
	// the new (child) delegate with a reference to the parent for fallback purposes,
	// then ultimately reset this.delegate back to its original (parent) reference.
	// this behavior emulates a stack of delegates without actually necessitating one.
	BeanDefinitionParserDelegate parent = this.delegate;
	this.delegate = createDelegate(getReaderContext(), root, parent);

	if (this.delegate.isDefaultNamespace(root)) {
		String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
		if (StringUtils.hasText(profileSpec)) {
			String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
					profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
			if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
				if (logger.isInfoEnabled()) {
					logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
							"] not matching: " + getReaderContext().getResource());
				}
				return;
			}
		}
	}

	preProcessXml(root);
	parseBeanDefinitions(root, this.delegate);
	postProcessXml(root);

	this.delegate = parent;
}
 
Example 9
Source File: MediaType.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parse the given comma-separated string into a list of {@code MediaType} objects.
 * <p>This method can be used to parse an Accept or Content-Type header.
 * @param mediaTypes the string to parse
 * @return the list of media types
 * @throws InvalidMediaTypeException if the media type value cannot be parsed
 */
public static List<MediaType> parseMediaTypes(String mediaTypes) {
	if (!StringUtils.hasLength(mediaTypes)) {
		return Collections.emptyList();
	}
	String[] tokens = StringUtils.tokenizeToStringArray(mediaTypes, ",");
	List<MediaType> result = new ArrayList<MediaType>(tokens.length);
	for (String token : tokens) {
		result.add(parseMediaType(token));
	}
	return result;
}
 
Example 10
Source File: ForwardedHeadersFilter.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
static Forwarded parse(String value) {
	String[] pairs = StringUtils.tokenizeToStringArray(value, ";");

	LinkedCaseInsensitiveMap<String> result = splitIntoCaseInsensitiveMap(pairs);
	if (result == null) {
		return null;
	}

	Forwarded forwarded = new Forwarded(result);

	return forwarded;
}
 
Example 11
Source File: AspectJAdviceParameterNameDiscoverer.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Match up args against unbound arguments of primitive types.
 */
private void maybeBindPrimitiveArgsFromPointcutExpression() {
	int numUnboundPrimitives = countNumberOfUnboundPrimitiveArguments();
	if (numUnboundPrimitives > 1) {
		throw new AmbiguousBindingException("Found '" + numUnboundPrimitives +
				"' unbound primitive arguments with no way to distinguish between them.");
	}
	if (numUnboundPrimitives == 1) {
		// Look for arg variable and bind it if we find exactly one...
		List<String> varNames = new ArrayList<>();
		String[] tokens = StringUtils.tokenizeToStringArray(this.pointcutExpression, " ");
		for (int i = 0; i < tokens.length; i++) {
			if (tokens[i].equals("args") || tokens[i].startsWith("args(")) {
				PointcutBody body = getPointcutBody(tokens, i);
				i += body.numTokensConsumed;
				maybeExtractVariableNamesFromArgs(body.text, varNames);
			}
		}
		if (varNames.size() > 1) {
			throw new AmbiguousBindingException("Found " + varNames.size() +
					" candidate variable names but only one candidate binding slot when matching primitive args");
		}
		else if (varNames.size() == 1) {
			// 1 primitive arg, and one candidate...
			for (int i = 0; i < this.argumentTypes.length; i++) {
				if (isUnbound(i) && this.argumentTypes[i].isPrimitive()) {
					bindParameterName(i, varNames.get(0));
					break;
				}
			}
		}
	}
}
 
Example 12
Source File: HttpHeaders.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the value of the {@code Access-Control-Allow-Methods} response header.
 */
public List<HttpMethod> getAccessControlAllowMethods() {
	List<HttpMethod> result = new ArrayList<HttpMethod>();
	String value = getFirst(ACCESS_CONTROL_ALLOW_METHODS);
	if (value != null) {
		String[] tokens = StringUtils.tokenizeToStringArray(value, ",");
		for (String token : tokens) {
			HttpMethod resolved = HttpMethod.resolve(token);
			if (resolved != null) {
				result.add(resolved);
			}
		}
	}
	return result;
}
 
Example 13
Source File: FaceletsAuthorizeTag.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
void setIfAnyGranted(String ifAnyGranted) {
	String[] roles = StringUtils.tokenizeToStringArray(ifAnyGranted, ",");
	if (!ObjectUtils.isEmpty(roles)) {
		String expression = toHasAnyRoleExpression(roles, false);
		setAccess(getAccess() != null ? getAccess() + " and " + expression : expression);
	}
}
 
Example 14
Source File: Level1CacheSupport.java    From azeroth with Apache License 2.0 5 votes vote down vote up
public void setCacheNames(String cacheNames) {
    if (org.apache.commons.lang3.StringUtils.isBlank(cacheNames)) {
        return;
    }
    String[] tmpcacheNames = StringUtils.tokenizeToStringArray(cacheNames,
            ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
    this.cacheNames = new ArrayList<>(Arrays.asList(tmpcacheNames));
}
 
Example 15
Source File: AbstractTyrusRequestUpgradeStrategy.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public String[] getSupportedVersions() {
	return StringUtils.tokenizeToStringArray(Version.getSupportedWireProtocolVersions(), ",");
}
 
Example 16
Source File: MessageBrokerBeanDefinitionParser.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public BeanDefinition parse(Element element, ParserContext context) {
	Object source = context.extractSource(element);
	CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source);
	context.pushContainingComponent(compDefinition);

	Element channelElem = DomUtils.getChildElementByTagName(element, "client-inbound-channel");
	RuntimeBeanReference inChannel = getMessageChannel("clientInboundChannel", channelElem, context, source);

	channelElem = DomUtils.getChildElementByTagName(element, "client-outbound-channel");
	RuntimeBeanReference outChannel = getMessageChannel("clientOutboundChannel", channelElem, context, source);

	channelElem = DomUtils.getChildElementByTagName(element, "broker-channel");
	RuntimeBeanReference brokerChannel = getMessageChannel("brokerChannel", channelElem, context, source);

	RuntimeBeanReference userRegistry = registerUserRegistry(element, context, source);
	Object userDestHandler = registerUserDestHandler(element, userRegistry, inChannel, brokerChannel, context, source);

	RuntimeBeanReference converter = registerMessageConverter(element, context, source);
	RuntimeBeanReference template = registerMessagingTemplate(element, brokerChannel, converter, context, source);
	registerAnnotationMethodMessageHandler(element, inChannel, outChannel,converter, template, context, source);

	RootBeanDefinition broker = registerMessageBroker(element, inChannel, outChannel, brokerChannel,
			userDestHandler, template, userRegistry, context, source);

	// WebSocket and sub-protocol handling

	ManagedMap<String, Object> urlMap = registerHandlerMapping(element, context, source);
	RuntimeBeanReference stompHandler = registerStompHandler(element, inChannel, outChannel, context, source);
	for (Element endpointElem : DomUtils.getChildElementsByTagName(element, "stomp-endpoint")) {
		RuntimeBeanReference requestHandler = registerRequestHandler(endpointElem, stompHandler, context, source);
		String pathAttribute = endpointElem.getAttribute("path");
		Assert.hasText(pathAttribute, "Invalid <stomp-endpoint> (no path mapping)");
		for (String path : StringUtils.tokenizeToStringArray(pathAttribute, ",")) {
			path = path.trim();
			Assert.hasText(path, () -> "Invalid <stomp-endpoint> path attribute: " + pathAttribute);
			if (DomUtils.getChildElementByTagName(endpointElem, "sockjs") != null) {
				path = (path.endsWith("/") ? path + "**" : path + "/**");
			}
			urlMap.put(path, requestHandler);
		}
	}

	Map<String, Object> scopeMap = Collections.singletonMap("websocket", new SimpSessionScope());
	RootBeanDefinition scopeConfigurer = new RootBeanDefinition(CustomScopeConfigurer.class);
	scopeConfigurer.getPropertyValues().add("scopes", scopeMap);
	registerBeanDefByName("webSocketScopeConfigurer", scopeConfigurer, context, source);

	registerWebSocketMessageBrokerStats(broker, inChannel, outChannel, context, source);

	context.popAndRegisterContainingComponent();
	return null;
}
 
Example 17
Source File: BeanDefinitionParserDelegate.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Parses the supplied {@code <bean>} element. May return {@code null}
 * if there were errors during parse. Errors are reported to the
 * {@link org.springframework.beans.factory.parsing.ProblemReporter}.
 */
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
	String id = ele.getAttribute(ID_ATTRIBUTE);
	String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);

	List<String> aliases = new ArrayList<>();
	if (StringUtils.hasLength(nameAttr)) {
		String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
		aliases.addAll(Arrays.asList(nameArr));
	}

	String beanName = id;
	if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
		beanName = aliases.remove(0);
		if (logger.isTraceEnabled()) {
			logger.trace("No XML 'id' specified - using '" + beanName +
					"' as bean name and " + aliases + " as aliases");
		}
	}

	if (containingBean == null) {
		checkNameUniqueness(beanName, aliases, ele);
	}

	AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
	if (beanDefinition != null) {
		if (!StringUtils.hasText(beanName)) {
			try {
				if (containingBean != null) {
					beanName = BeanDefinitionReaderUtils.generateBeanName(
							beanDefinition, this.readerContext.getRegistry(), true);
				}
				else {
					beanName = this.readerContext.generateBeanName(beanDefinition);
					// Register an alias for the plain bean class name, if still possible,
					// if the generator returned the class name plus a suffix.
					// This is expected for Spring 1.2/2.0 backwards compatibility.
					String beanClassName = beanDefinition.getBeanClassName();
					if (beanClassName != null &&
							beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
							!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
						aliases.add(beanClassName);
					}
				}
				if (logger.isTraceEnabled()) {
					logger.trace("Neither XML 'id' nor 'name' specified - " +
							"using generated bean name [" + beanName + "]");
				}
			}
			catch (Exception ex) {
				error(ex.getMessage(), ele);
				return null;
			}
		}
		String[] aliasesArray = StringUtils.toStringArray(aliases);
		return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
	}

	return null;
}
 
Example 18
Source File: BeanDefinitionParserDelegate.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses the supplied {@code <bean>} element. May return {@code null}
 * if there were errors during parse. Errors are reported to the
 * {@link org.springframework.beans.factory.parsing.ProblemReporter}.
 */
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
	String id = ele.getAttribute(ID_ATTRIBUTE);
	String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);

	List<String> aliases = new ArrayList<String>();
	if (StringUtils.hasLength(nameAttr)) {
		String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
		aliases.addAll(Arrays.asList(nameArr));
	}

	String beanName = id;
	if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
		beanName = aliases.remove(0);
		if (logger.isDebugEnabled()) {
			logger.debug("No XML 'id' specified - using '" + beanName +
					"' as bean name and " + aliases + " as aliases");
		}
	}

	if (containingBean == null) {
		checkNameUniqueness(beanName, aliases, ele);
	}

	AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
	if (beanDefinition != null) {
		if (!StringUtils.hasText(beanName)) {
			try {
				if (containingBean != null) {
					beanName = BeanDefinitionReaderUtils.generateBeanName(
							beanDefinition, this.readerContext.getRegistry(), true);
				}
				else {
					beanName = this.readerContext.generateBeanName(beanDefinition);
					// Register an alias for the plain bean class name, if still possible,
					// if the generator returned the class name plus a suffix.
					// This is expected for Spring 1.2/2.0 backwards compatibility.
					String beanClassName = beanDefinition.getBeanClassName();
					if (beanClassName != null &&
							beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
							!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
						aliases.add(beanClassName);
					}
				}
				if (logger.isDebugEnabled()) {
					logger.debug("Neither XML 'id' nor 'name' specified - " +
							"using generated bean name [" + beanName + "]");
				}
			}
			catch (Exception ex) {
				error(ex.getMessage(), ele);
				return null;
			}
		}
		String[] aliasesArray = StringUtils.toStringArray(aliases);
		return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
	}

	return null;
}
 
Example 19
Source File: MapperLoader.java    From Shop-for-JavaWeb with MIT License 4 votes vote down vote up
public Scanner() {
	basePackages = StringUtils.tokenizeToStringArray(MapperLoader.this.basePackage,
			ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
}
 
Example 20
Source File: AspectJAdviceParameterNameDiscoverer.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private void maybeBindReferencePointcutParameter() {
	if (this.numberOfRemainingUnboundArguments > 1) {
		throw new AmbiguousBindingException("Still " + this.numberOfRemainingUnboundArguments
				+ " unbound args at reference pointcut binding stage, with no way to determine between them");
	}

	List<String> varNames = new ArrayList<>();
	String[] tokens = StringUtils.tokenizeToStringArray(this.pointcutExpression, " ");
	for (int i = 0; i < tokens.length; i++) {
		String toMatch = tokens[i];
		if (toMatch.startsWith("!")) {
			toMatch = toMatch.substring(1);
		}
		int firstParenIndex = toMatch.indexOf('(');
		if (firstParenIndex != -1) {
			toMatch = toMatch.substring(0, firstParenIndex);
		}
		else {
			if (tokens.length < i + 2) {
				// no "(" and nothing following
				continue;
			}
			else {
				String nextToken = tokens[i + 1];
				if (nextToken.charAt(0) != '(') {
					// next token is not "(" either, can't be a pc...
					continue;
				}
			}

		}

		// eat the body
		PointcutBody body = getPointcutBody(tokens, i);
		i += body.numTokensConsumed;

		if (!nonReferencePointcutTokens.contains(toMatch)) {
			// then it could be a reference pointcut
			String varName = maybeExtractVariableName(body.text);
			if (varName != null) {
				varNames.add(varName);
			}
		}
	}

	if (varNames.size() > 1) {
		throw new AmbiguousBindingException("Found " + varNames.size() +
				" candidate reference pointcut variables but only one unbound argument slot");
	}
	else if (varNames.size() == 1) {
		for (int j = 0; j < this.parameterNameBindings.length; j++) {
			if (isUnbound(j)) {
				bindParameterName(j, varNames.get(0));
				break;
			}
		}
	}
	// else varNames.size must be 0 and we have nothing to bind.
}