[JAVA] 코딩 표준에 맞는지 검사하기(HashMap, Iterator, Properties,StreamTokenizer) :: 소림사의 홍반장!

자바의 식별자(클래스, 메소드, 변수 등)에 이름을 줄 때 코딩 표준에 맞게 영문 대문자를 사용하는지 검사

 

참고용. 분석해볼것.

 

import java.io.*;

import java.util.*;

 

class MultiStringMap extends HashMap<String,ArrayList<String>> {

  public void add(String key, String value) {

    if(!containsKey(key))

      put(key, new ArrayList<String>());

    ((ArrayList<String>)get(key)).add(value);

  }

  public ArrayList<String> getArrayList(String key) {

    if(!containsKey(key)) {

      System.err.println(

        "ERROR: can't find key: " + key);

      System.exit(1);

    }

    return (ArrayList<String>)get(key);

  }

  public void printValues(PrintStream p) {

    Iterator<String> k = keySet().iterator();

    while(k.hasNext()) {

      String oneKey = (String)k.next();

      ArrayList<String> val = getArrayList(oneKey);

      for(int i = 0; i < val.size(); i++)

        p.println((String)val.get(i));

    }

  }

}

 

public class ClassScanner {

  private File path;

  private String[] fileList;

  private Properties classes = new Properties();

  private MultiStringMap

    classMap = new MultiStringMap(),

    identMap = new MultiStringMap();

  private StreamTokenizer in;

  public ClassScanner() throws IOException {

    path = new File("F:/Nexicure/workspace/Test01/src/rt/java/lang");

    fileList = path.list(new JavaFilter());

    for(int i = 0; i < fileList.length; i++) {

      System.out.println(fileList[i]);

      try {

        scanListing(fileList[i]);

      } catch(FileNotFoundException e) {

        System.err.println("Could not open " +

          fileList[i]);

      }

    }

  }

  void scanListing(String fname)

  throws IOException {

    in = new StreamTokenizer(

        new BufferedReader(

          new FileReader(fname)));

    // in.slashStarComments(true);

    // in.slashSlashComments(true);

    in.ordinaryChar('/');

    in.ordinaryChar('.');

    in.wordChars('_', '_');

    in.eolIsSignificant(true);

    while(in.nextToken() !=

          StreamTokenizer.TT_EOF) {

      if(in.ttype == '/')

        eatComments();

      else if(in.ttype ==

              StreamTokenizer.TT_WORD) {

        if(in.sval.equals("class") ||

           in.sval.equals("interface")) {

          // 클래스 이름을 얻는다:

             while(in.nextToken() !=

                   StreamTokenizer.TT_EOF

                   && in.ttype !=

                   StreamTokenizer.TT_WORD)

               ;

             classes.put(in.sval, in.sval);

             classMap.add(fname, in.sval);

        }

        if(in.sval.equals("import") ||

           in.sval.equals("package"))

          discardLine();

        else // 식별자나 키워드인 경우

          identMap.add(fname, in.sval);

      }

    }

  }

  void discardLine() throws IOException {

    while(in.nextToken() !=

          StreamTokenizer.TT_EOF

          && in.ttype !=

          StreamTokenizer.TT_EOL)

      ;

  }

  void eatComments() throws IOException {

    if(in.nextToken() !=

       StreamTokenizer.TT_EOF) {

      if(in.ttype == '/')

        discardLine();

      else if(in.ttype != '*')

        in.pushBack();

      else

        while(true) {

          if(in.nextToken() ==

            StreamTokenizer.TT_EOF)

            break;

          if(in.ttype == '*')

            if(in.nextToken() !=

              StreamTokenizer.TT_EOF

              && in.ttype == '/')

              break;

        }

    }

  }

  public String[] classNames() {

    String[] result = new String[classes.size()];

    Iterator<Object> e = classes.keySet().iterator();

    int i = 0;

    while(e.hasNext())

      result[i++] = (String)e.next();

    return result;

  }

  public void checkClassNames() {

    Iterator<String> files = classMap.keySet().iterator();

    while(files.hasNext()) {

      String file = (String)files.next();

      ArrayList<String> cls = classMap.getArrayList(file);

      for(int i = 0; i < cls.size(); i++) {

        String className = (String)cls.get(i);

        if(Character.isLowerCase(

             className.charAt(0)))

          System.out.println(

            "class capitalization error, file: "

            + file + ", class: "

            + className);

      }

    }

  }

  public void checkIdentNames() {

    Iterator<String> files = identMap.keySet().iterator();

    ArrayList<String> reportSet = new ArrayList<>();

    while(files.hasNext()) {

      String file = (String)files.next();

      ArrayList<String> ids = identMap.getArrayList(file);

      for(int i = 0; i < ids.size(); i++) {

        String id = (String)ids.get(i);

        if(!classes.contains(id)) {

          if(id.length() >= 3 &&

             id.equals(

               id.toUpperCase()))

            continue;

          if(Character.isUpperCase(id.charAt(0))){

            if(reportSet.indexOf(file + id)

                == -1){ // Not reported yet

              reportSet.add(file + id);

              System.out.println(

                "Ident capitalization error in:"

                + file + ", ident: " + id);

            }

          }

        }

      }

    }

  }

  static final String usage =

    "Usage: \n" +

    "ClassScanner classnames -a\n" +

    "\tAdds all the class names in this \n" +

    "\tdirectory to the repository file \n" +

    "\tcalled 'classnames'\n" +

    "ClassScanner classnames\n" +

    "\tChecks all the java files in this \n" +

    "\tdirectory for capitalization errors, \n" +

    "\tusing the repository file 'classnames'";

  private static void usage() {

    System.err.println(usage);

    System.exit(1);

  }

  public static void main(String[] args)

  throws IOException {

    if(args.length < 1 || args.length > 2)

      usage();

    ClassScanner c = new ClassScanner();

    File old = new File(args[0]);

    if(old.exists()) {

      try {

        InputStream oldlist =

          new BufferedInputStream(

            new FileInputStream(old));

        c.classes.load(oldlist);

        oldlist.close();

      } catch(IOException e) {

        System.err.println("Could not open "

          + old + " for reading");

        System.exit(1);

      }

    }

    if(args.length == 1) {

      c.checkClassNames();

      c.checkIdentNames();

    }

    if(args.length == 2) {

      if(!args[1].equals("-a"))

        usage();

      try {

        BufferedOutputStream out =

          new BufferedOutputStream(

            new FileOutputStream(args[0]));

        c.classes.store(out,

          "Classes found by ClassScanner.java");

        out.close();

      } catch(IOException e) {

        System.err.println(

          "Could not write " + args[0]);

        System.exit(1);

      }

    }

  }

}

 

class JavaFilter implements FilenameFilter {

  public boolean accept(File dir, String name) {

    String f = new File(name).getName();

    return f.trim().endsWith(".java");

  }

}

다른 카테고리의 글 목록

Dev. 자바/참고소스 카테고리의 포스트를 톺아봅니다