46d0d17c3eec5dfac2644d8db1eeb058e2f2094a
[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 ast) {
30         if (ast.getType() == TokenTypes.VARIABLE_DEF) {
31             if (CheckLoggingUtil.isAFieldVariable(ast)) {
32                 final String typeName = CheckLoggingUtil.getTypeName(ast);
33                 if (typeName.contains("." + LOGGER_TYPE_NAME) && !typeName.equals(LOGGER_TYPE_FULL_NAME)) {
34                     log(ast.getLineNo(), LOG_MESSAGE);
35                 }
36             }
37         } else if (ast.getType() == TokenTypes.IMPORT) {
38             final DetailAST typeToken = ast.getFirstChild().findFirstToken(TokenTypes.IDENT);
39             if (typeToken != null) {
40                 final String importType = typeToken.getText();
41                 if (CheckLoggingUtil.LOGGER_TYPE_NAME.equals(importType)) {
42                     final String importIdent = ast.getFirstChild().getFirstChild().getLastChild().getText();
43                     if (!importIdent.equals(SLF4J)) {
44                         log(ast.getLineNo(), LOG_MESSAGE);
45                     }
46                 }
47             }
48         }
49     }
50 }