Introduce ResourcePatternHint#toRegex

This change is done for several reasons:
 - Move the logic where it is documented.
 - Test it with ResourcePatternHintTests.
 - Allow RuntimeHintsPredicates to leverage this logic.

Closes gh-28620
This commit is contained in:
Sébastien Deleuze
2022-06-14 12:00:33 +02:00
parent 77ad4a1428
commit c235ad0b35
3 changed files with 88 additions and 14 deletions

View File

@@ -16,7 +16,10 @@
package org.springframework.aot.hint;
import java.util.Arrays;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.springframework.lang.Nullable;
@@ -58,12 +61,26 @@ public final class ResourcePatternHint implements ConditionalHint {
/**
* Return the pattern to use for identifying the resources to match.
* @return the patterns
* @return the pattern
*/
public String getPattern() {
return this.pattern;
}
/**
* Return the regex {@link Pattern} to use for identifying the resources to match.
* @return the regex pattern
*/
public Pattern toRegex() {
String prefix = (this.pattern.startsWith("*") ? ".*" : "");
String suffix = (this.pattern.endsWith("*") ? ".*" : "");
String regex = Arrays.stream(this.pattern.split("\\*"))
.filter(s -> !s.isEmpty())
.map(Pattern::quote)
.collect(Collectors.joining(".*", prefix, suffix));
return Pattern.compile(regex);
}
@Nullable
@Override
public TypeReference getReachableType() {

View File

@@ -16,13 +16,10 @@
package org.springframework.aot.nativex;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.aot.hint.ConditionalHint;
@@ -77,19 +74,10 @@ class ResourceHintsWriter {
private Map<String, Object> toAttributes(ResourcePatternHint hint) {
Map<String, Object> attributes = new LinkedHashMap<>();
handleCondition(attributes, hint);
attributes.put("pattern", patternToRegexp(hint.getPattern()));
attributes.put("pattern", hint.toRegex().toString());
return attributes;
}
private String patternToRegexp(String pattern) {
String prefix = (pattern.startsWith("*") ? ".*" : "");
String suffix = (pattern.endsWith("*") ? ".*" : "");
return Arrays.stream(pattern.split("\\*"))
.filter(s -> !s.isEmpty())
.map(Pattern::quote)
.collect(Collectors.joining(".*", prefix, suffix));
}
private void addIfNotEmpty(Map<String, Object> attributes, String name, @Nullable Object value) {
if (value instanceof Collection<?> collection) {
if (!collection.isEmpty()) {