feign.template.Expressions Maven / Gradle / Ivy
The newest version!
/**
* Copyright 2012-2019 The Feign Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package feign.template;
import feign.Util;
import feign.template.UriUtils.FragmentType;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class Expressions {
private static Map> expressions;
static {
expressions = new LinkedHashMap<>();
/*
* basic pattern for variable names. this is compliant with RFC 6570 Simple
* Expressions ONLY with the following additional values allowed without
* required pct-encoding:
*
* - brackets - dashes
*
* see https://tools.ietf.org/html/rfc6570#section-2.3 for more information.
*/
expressions.put(Pattern.compile("(\\w[-\\w.\\[\\]]*[ ]*)(:(.+))?"), SimpleExpression.class);
}
public static Expression create(final String value, final FragmentType type) {
/* remove the start and end braces */
final String expression = stripBraces(value);
if (expression == null || expression.isEmpty()) {
throw new IllegalArgumentException("an expression is required.");
}
Optional>> matchedExpressionEntry = expressions.entrySet().stream()
.filter(entry -> entry.getKey().matcher(expression).matches()).findFirst();
if (!matchedExpressionEntry.isPresent()) {
/* not a valid expression */
return null;
}
Entry> matchedExpression = matchedExpressionEntry.get();
Pattern expressionPattern = matchedExpression.getKey();
/* create a new regular expression matcher for the expression */
String variableName = null;
String variablePattern = null;
Matcher matcher = expressionPattern.matcher(expression);
if (matcher.matches()) {
/* we have a valid variable expression, extract the name from the first group */
variableName = matcher.group(1).trim();
if (matcher.group(2) != null && matcher.group(3) != null) {
/* this variable contains an optional pattern */
variablePattern = matcher.group(3);
}
}
return new SimpleExpression(variableName, variablePattern, type);
}
private static String stripBraces(String expression) {
if (expression == null) {
return null;
}
if (expression.startsWith("{") && expression.endsWith("}")) {
return expression.substring(1, expression.length() - 1);
}
return expression;
}
/**
* Expression that adheres to Simple String Expansion as outlined in