Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 5th, 2012  |  syntax: None  |  size: 2.06 KB  |  hits: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Custom Rules in Checkstyle for ensuring Logger is declared as a Static Final Class Attribute
  2. package com.mystuff.checkstyle.hecks;
  3.  
  4. import com.puppycrawl.tools.checkstyle.api.Check;
  5. import com.puppycrawl.tools.checkstyle.api.DetailAST;
  6. import com.puppycrawl.tools.checkstyle.api.FullIdent;
  7. import com.puppycrawl.tools.checkstyle.api.TokenTypes;
  8. import com.puppycrawl.tools.checkstyle.checks.CheckUtils;
  9.  
  10. /**
  11.  *
  12.  *
  13.  * This package provides the custom checks that were required outside
  14.  * of the standard checks provided
  15.  *
  16.  */
  17. public class LoggerAttrCheck extends Check
  18. {
  19.    /**
  20.     *  
  21.     *
  22.     * The Logger must be declared as a static final class attribute
  23.     *
  24.     */
  25.     @Override
  26.     public int[] getDefaultTokens()
  27.     {
  28.         return new int[] { TokenTypes.VARIABLE_DEF};
  29.     }
  30.  
  31.     @Override
  32.     public void visitToken(DetailAST aAST)
  33.     {
  34.         if(aAST.getType()==TokenTypes.VARIABLE_DEF)
  35.           visitVariableDef(aAST);
  36.  
  37.     }
  38.     /**
  39.      * Checks type of given variable.
  40.      * @param aAST variable to check.
  41.      */
  42.     private void visitVariableDef(DetailAST aAST)
  43.     {
  44.         checkVariableDefn(aAST);
  45.     }
  46.  
  47.     /**
  48.      *
  49.      * Checks variable to see if its a Logger and static final
  50.      *      * @param aAST node to check.
  51.      */
  52.     private void checkVariableDefn(DetailAST aAST)
  53.     {
  54.         final DetailAST type = aAST.findFirstToken(TokenTypes.TYPE);
  55.         final FullIdent ident = CheckUtils.createFullType(type);
  56.  
  57.         if ((ident.getText().equals("Logger")))
  58.         {
  59.               if((!aAST.branchContains(TokenTypes.FINAL))||(!aAST.branchContainsTokenTypes.LITERAL_STATIC)))
  60.           {
  61.           log(type.getLineNo(), type.getColumnNo(),
  62.                     "Logger not defined as static final class attribute", type.getText());
  63.           }    
  64.         }
  65.     }
  66. }
  67.        
  68. <?xml version="1.0" encoding="UTF-8"?>
  69.  
  70.     <!DOCTYPE checkstyle-packages PUBLIC
  71.     "-//Puppy Crawl//DTD Package Names 1.3//EN"
  72.     "http://www.puppycrawl.com/dtds/packages_1_3.dtd">
  73.  
  74. <checkstyle-packages>
  75.     <package name="com.mystuff.checkstyle.checks"/>
  76. </checkstyle-packages>