View Javadoc
1   package org.bitbucket.jrsofty.parser.logging.api;
2   
3   import java.util.regex.Matcher;
4   import java.util.regex.Pattern;
5   
6   /**
7    * A container class for holding the regex pattern and token marker used for mapping the token.
8    *
9    * @author jrsofty
10   *
11   */
12  public class TokenMatcher {
13  
14    private final Pattern regexPattern;
15    private final String tokenMarker;
16  
17    public TokenMatcher(final String regex, final String tokenMarker) {
18      this.tokenMarker = tokenMarker;
19      this.regexPattern = Pattern.compile(regex);
20    }
21  
22    /**
23     * The regex pattern that was used for creating the regex used.
24     * 
25     * @return the regex pattern as String.
26     */
27    public String getPattern() {
28      return this.regexPattern.toString();
29    }
30  
31    /**
32     * Delivers the token marker used for mapping. Token markers are not always exactly as they were
33     * entered in the formatting string. Every token marker will be extended with an instance number.
34     * 
35     * @return this TokenMatcher's token marker.
36     */
37    public String getTokenMarker() {
38      return this.tokenMarker;
39    }
40  
41    /**
42     * Validates the given token with the compiled regex pattern. Returns null if there is not a
43     * match.
44     *
45     * @param token
46     *          a portion of the log line as String
47     * @return the token value if a match, otherwise returns null.
48     * @throws TokenParseException
49     *           when a match fails.
50     */
51    public String validateToken(final String token) throws TokenParseException {
52  
53      final Matcher matcher = this.regexPattern.matcher(token);
54      matcher.find();
55      try {
56        final String result = matcher.group(0);
57        return result;
58      } catch (final IllegalStateException e) {
59        throw new TokenParseException(token, this.tokenMarker, this.regexPattern.toString(), e);
60      }
61  
62    }
63  
64  }