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