Use precompiled regular expressions to validate the segments of a UID (#4064)

Signed-off-by: Jörg Sautter <joerg.sautter@gmx.net>
This commit is contained in:
joerg1985
2024-01-24 21:25:14 +01:00
committed by GitHub
parent 718839052a
commit 7ea603c24c
2 changed files with 8 additions and 4 deletions
@@ -78,8 +78,7 @@ public class MetadataSelectorMatcher {
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());
}
}
}
@@ -14,6 +14,7 @@ package org.openhab.core.common;
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;
@@ -26,7 +27,7 @@ import org.eclipse.jdt.annotation.Nullable;
@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 = "";
@@ -95,8 +96,12 @@ public abstract class AbstractUID {
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));