1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package gov.nist.secauto.oscal.lib.profile.resolver.policy;
28
29 import gov.nist.secauto.metaschema.model.common.util.ObjectUtils;
30 import gov.nist.secauto.oscal.lib.profile.resolver.ProfileResolutionEvaluationException;
31
32 import java.util.Objects;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35
36 import edu.umd.cs.findbugs.annotations.NonNull;
37
38 public class PatternIdentifierParser implements IIdentifierParser {
39 private final Pattern pattern;
40 private final int identifierGroup;
41
42 @SuppressWarnings("null")
43 public PatternIdentifierParser(@NonNull String pattern, int identifierGroup) {
44 this(Pattern.compile(pattern), identifierGroup);
45 }
46
47 public PatternIdentifierParser(@NonNull Pattern pattern, int identifierGroup) {
48 this.pattern = Objects.requireNonNull(pattern, "pattern");
49 this.identifierGroup = identifierGroup;
50 }
51
52 public Pattern getPattern() {
53 return pattern;
54 }
55
56 public int getIdentifierGroup() {
57 return identifierGroup;
58 }
59
60 @Override
61 public String parse(@NonNull String referenceText) {
62 Matcher matcher = getPattern().matcher(referenceText);
63
64 String retval = null;
65 if (matcher.matches()) {
66 retval = matcher.group(getIdentifierGroup());
67 }
68 return retval;
69 }
70
71 @Override
72 public String update(@NonNull String referenceText, @NonNull String newIdentifier) {
73 Matcher matcher = getPattern().matcher(referenceText);
74 if (!matcher.matches()) {
75 throw new ProfileResolutionEvaluationException(
76 String.format("The original reference '%s' did not match the pattern '%s'.",
77 referenceText, getPattern().pattern()));
78 }
79
80 return ObjectUtils.notNull(new StringBuilder(referenceText)
81 .replace(
82 matcher.start(getIdentifierGroup()),
83 matcher.end(getIdentifierGroup()),
84 newIdentifier)
85 .toString());
86 }
87 }