Skip to content

Commit

Permalink
Use precompiled regular expressions to validate the segments of a UID
Browse files Browse the repository at this point in the history
Signed-off-by: Jörg Sautter <joerg.sautter@gmx.net>
  • Loading branch information
joerg1985 committed Jan 24, 2024
1 parent 7188390 commit 48addeb
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,7 @@ public Set<String> filterNamespaces(@Nullable String namespaceSelector, @Nullabl
result.addAll(metadataNamespaces);

// filter all name spaces which do not match the UID segment pattern (this will be the regex tokens):
return result.stream().filter(namespace -> namespace.matches(AbstractUID.SEGMENT_PATTERN))
.collect(Collectors.toSet());
return result.stream().filter(AbstractUID::isValid).collect(Collectors.toSet());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
Expand All @@ -26,7 +27,7 @@
@NonNullByDefault
public abstract class AbstractUID {

public static final String SEGMENT_PATTERN = "[\\w-]*";
private static final Pattern SEGMENT_PATTERN = Pattern.compile("[\\w-]*");
public static final String SEPARATOR = ":";
private final List<String> segments;
private String uid = "";
Expand Down Expand Up @@ -95,8 +96,12 @@ protected String getSegment(int segment) {
return segments.get(segment);
}

public static boolean isValid(@Nullable String segment) {
return segment != null && SEGMENT_PATTERN.matcher(segment).matches();
}

protected void validateSegment(String segment, int index, int length) {
if (!segment.matches(SEGMENT_PATTERN)) {
if (!isValid(segment)) {
throw new IllegalArgumentException(String.format(
"ID segment '%s' contains invalid characters. Each segment of the ID must match the pattern %s.",
segment, SEGMENT_PATTERN));
Expand Down

0 comments on commit 48addeb

Please sign in to comment.