1 ////////////////////////////////////////////////////////////////////////////////
2 // checkstyle: Checks Java source code for adherence to a set of rules.
3 // Copyright (C) 2001-2019 the original author or authors.
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 ////////////////////////////////////////////////////////////////////////////////
19
20 package com.puppycrawl.tools.checkstyle.checks.naming;
21
22 import java.util.regex.Pattern;
23
24 import com.puppycrawl.tools.checkstyle.StatelessCheck;
25 import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
26 import com.puppycrawl.tools.checkstyle.api.DetailAST;
27 import com.puppycrawl.tools.checkstyle.api.TokenTypes;
28 import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
29
30 /**
31 * Abstract class for checking that names conform to a specified format.
32 *
33 */
34 @StatelessCheck
35 public abstract class AbstractNameCheck
36 extends AbstractCheck {
37
38 /**
39 * Message key for invalid pattern error.
40 */
41 public static final String MSG_INVALID_PATTERN = "name.invalidPattern";
42
43 /** The regexp to match against. */
44 private Pattern format;
45
46 /**
47 * Creates a new {@code AbstractNameCheck} instance.
48 * @param format format to check with
49 */
50 protected AbstractNameCheck(String format) {
51 this.format = CommonUtil.createPattern(format);
52 }
53
54 /**
55 * Decides whether the name of an AST should be checked against
56 * the format regexp.
57 * @param ast the AST to check.
58 * @return true if the IDENT subnode of ast should be checked against
59 * the format regexp.
60 */
61 protected abstract boolean mustCheckName(DetailAST ast);
62
63 /**
64 * Set the format for the specified regular expression.
65 * @param pattern the new pattern
66 */
67 public final void setFormat(Pattern pattern) {
68 format = pattern;
69 }
70
71 @Override
72 public void visitToken(DetailAST ast) {
73 if (mustCheckName(ast)) {
74 final DetailAST nameAST = ast.findFirstToken(TokenTypes.IDENT);
75 if (!format.matcher(nameAST.getText()).find()) {
76 log(nameAST,
77 MSG_INVALID_PATTERN,
78 nameAST.getText(),
79 format.pattern());
80 }
81 }
82 }
83
84 }