Fixed some major sonar issues
[yangtools.git] / common / checkstyle-logging / src / main / java / org / opendaylight / yangtools / checkstyle / LoggerMustBeSlf4jCheck.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 static org.opendaylight.yangtools.checkstyle.CheckLoggingUtil.LOGGER_TYPE_FULL_NAME;
12 import static org.opendaylight.yangtools.checkstyle.CheckLoggingUtil.LOGGER_TYPE_NAME;
13
14 import com.puppycrawl.tools.checkstyle.api.Check;
15 import com.puppycrawl.tools.checkstyle.api.DetailAST;
16 import com.puppycrawl.tools.checkstyle.api.TokenTypes;
17
18 public class LoggerMustBeSlf4jCheck extends Check {
19
20     private static final String LOG_MESSAGE = "Logger must be slf4j.";
21     private static final String SLF4J = "slf4j";
22
23     @Override
24     public int[] getDefaultTokens() {
25         return new int[]{TokenTypes.VARIABLE_DEF, TokenTypes.IMPORT};
26     }
27
28     @Override
29     public void visitToken(DetailAST aAST) {
30         if (aAST.getType() == TokenTypes.VARIABLE_DEF) {
31             if (CheckLoggingUtil.isAFieldVariable(aAST)) {
32                 final String typeName = CheckLoggingUtil.getTypeName(aAST);
33                 if (typeName.contains("." + LOGGER_TYPE_NAME) && !typeName.equals(LOGGER_TYPE_FULL_NAME)) {
34                     log(aAST.getLineNo(), LOG_MESSAGE);
35                 }
36             }
37         } else if (aAST.getType() == TokenTypes.IMPORT) {
38             final String importType = aAST.getFirstChild().findFirstToken(TokenTypes.IDENT).getText();
39             if (importType.equals(CheckLoggingUtil.LOGGER_TYPE_NAME)) {
40                 final String importIdent = aAST.getFirstChild().getFirstChild().getLastChild().getText();
41                 if (!importIdent.equals(SLF4J)) {
42                     log(aAST.getLineNo(), LOG_MESSAGE);
43                 }
44             }
45         }
46     }
47 }