BUG-4109: Correct checkstyle dependency and avoid a couple of NPEs
[yangtools.git] / common / checkstyle-logging / src / main / java / org / opendaylight / yangtools / checkstyle / CheckLoggingUtil.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.yangtools.checkstyle;
10
11 import java.util.List;
12
13 import org.slf4j.Logger;
14
15 import com.google.common.collect.Lists;
16 import com.puppycrawl.tools.checkstyle.api.DetailAST;
17 import com.puppycrawl.tools.checkstyle.api.FullIdent;
18 import com.puppycrawl.tools.checkstyle.api.TokenTypes;
19 import com.puppycrawl.tools.checkstyle.checks.CheckUtils;
20
21 public class CheckLoggingUtil {
22
23     public static final String LOGGER_TYPE_NAME = Logger.class.getSimpleName();
24     public static final String LOGGER_TYPE_FULL_NAME = Logger.class.getName();
25     public static final String LOGGER_VAR_NAME = "LOG";
26     private static final List<String> LOG_METHODS = Lists.newArrayList("LOG.debug", "LOG.info", "LOG.error", "LOG.warn", "LOG.trace");
27
28     private CheckLoggingUtil() {}
29
30     public static String getTypeName(final DetailAST aAST) {
31         final FullIdent ident = CheckUtils.createFullType(aAST.findFirstToken(TokenTypes.TYPE));
32         return ident.getText();
33     }
34
35     public static boolean isLoggerType(final DetailAST aAST) {
36         final String typeName = getTypeName(aAST);
37         return typeName.equals(LOGGER_TYPE_FULL_NAME) || typeName.equals(LOGGER_TYPE_NAME);
38     }
39
40     public static String getVariableName(final DetailAST aAST) {
41         DetailAST identifier = aAST.findFirstToken(TokenTypes.IDENT);
42         return identifier.getText();
43     }
44
45     public static boolean isAFieldVariable(final DetailAST aAST) {
46         return aAST.getParent().getType() == TokenTypes.OBJBLOCK;
47     }
48
49     public static String getMethodName(final DetailAST aAST) {
50         if(aAST.getFirstChild().getLastChild() != null) {
51             return aAST.getFirstChild().getFirstChild().getText() + "." + aAST.getFirstChild().getLastChild().getText();
52         }
53         return aAST.getFirstChild().getText();
54     }
55
56     public static boolean isLogMethod(final String methodName) {
57         return LOG_METHODS.contains(methodName);
58     }
59
60     public static String getClassName(final DetailAST aAST) {
61         DetailAST parent = aAST.getParent();
62         while(parent.getType() != TokenTypes.CLASS_DEF && parent.getType() != TokenTypes.ENUM_DEF) {
63             parent = parent.getParent();
64         }
65         return parent.findFirstToken(TokenTypes.IDENT).getText();
66     }
67
68 }