Skip to content

PatternSyntaxException may be thrown when looking for an environment entry or metric with a name that looks a bit like a regular expression #9730

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
* Utility class that can be used to filter source data using a name regular expression.
Expand All @@ -31,6 +32,7 @@
* @author Phillip Webb
* @author Sergei Egorov
* @author Andy Wilkinson
* @author Dylian Bego
* @since 1.3.0
*/
abstract class NamePatternFilter<T> {
Expand All @@ -44,27 +46,32 @@ abstract class NamePatternFilter<T> {
}

public Map<String, Object> getResults(String name) {
if (!isRegex(name)) {
Pattern pattern = getRegexPattern(name);
if (pattern == null) { // this is not a regex
Object value = getValue(this.source, name);
Map<String, Object> result = new HashMap<>();
result.put(name, value);
return result;
}
Pattern pattern = Pattern.compile(name);
ResultCollectingNameCallback resultCollector = new ResultCollectingNameCallback(
pattern);
getNames(this.source, resultCollector);
return resultCollector.getResults();

}

private boolean isRegex(String name) {
private Pattern getRegexPattern(String name) {
for (String part : REGEX_PARTS) {
if (name.contains(part)) {
return true;
try {
return Pattern.compile(name);
}
catch (PatternSyntaxException e) {
return null;
}
}
}
return false;
return null;
}

protected abstract void getNames(T source, NameCallback callback);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
*
* @author Phillip Webb
* @author Andy Wilkinson
* @author Dylian Bego
*/
public class NamePatternFilterTests {

Expand All @@ -38,6 +39,13 @@ public void nonRegex() throws Exception {
assertThat(filter.isGetNamesCalled()).isFalse();
}

@Test
public void nonRegexThatContainsRegexPart() throws Exception {
MockNamePatternFilter filter = new MockNamePatternFilter();
assertThat(filter.getResults("*")).containsEntry("*", "*");
assertThat(filter.isGetNamesCalled()).isFalse();
}

@Test
public void regexRepetitionZeroOrMore() {
MockNamePatternFilter filter = new MockNamePatternFilter();
Expand Down