BLOG ARTICLE 프로그래밍/Java | 69 ARTICLE FOUND

  1. 2009.08.06 자바 로그 관련...
  2. 2009.06.12 ini 파일 분석 Java Class
  3. 2009.05.13 외부 실행화일 자바 Tread로 돌리는 방법
  4. 2009.05.13 자바 한글 셋팅
  5. 2009.03.30 자바 PreparedStatement setBytes()


1. 로그 관련 성능
다음코드는 로그레벨에 관계없이 String 객체의 값을 연결하는 + 연산이 실행된다.

logger.warn("blar blar. some="+some+". other="+other+".and another"+another);

+연산은 오직 로그를 위한 것이고 warn() 메소드는 실제 로그레벨이 warn미만일 경우에만
전달된 값을 로그에 남긴다. 만약 로그레벨이 warn보다 크다면 결과적으로 필요없는 연산을 하게 된 것이다. 아쉽게도 자바에서는 이를 피할수 있는 근본적인 방법이 없다. 다음과 같이 logger의 로그 메소드를 호출하기 전에 로그 레벨을 파악해 불필요한 연산을 피해야 한다.

logger.isWarnEnabled(){
logger.warn("...");
}

대부분의 로그 프레임워크는 이와 같은 로그레벨을 확인하기 위한 방법을 제공하고 있다.


2. track stack을 String 으로 받기
Writer writer=new StringWriter();
e.printStackTrace(new PrintWriter(writer));
String stackTrace=writer.toString();

3.로그레벨에 따른 쓰임새
 DEBUG : 디버깅을 위한 목적이며 평상시라면 보이지 않을 내용이다. 자세할 수록 좋다.
 INFO : 관리자에게 정보를 제공한다. 버그와 관계없는 내용이다.
 WARN : 뭔가 잘못됐다는 것을 나타낸다. 이경우 비정상적인 상황은 발생했지만 정상적인   상황으로 처리했다는 것을 의미한다.
 ERROR : 시스템 운영에 문제가 있을 경우다. 예외를 처리하지 못하고 로그로 남기는 경우가 여기에 속한다.
 FATAL : 시스템 운영조차 불가능한 경우다. 로그조차 남기지 못하기도 한다.

출처 : 마소 2009년 07월호
AND

import java.util.*;
import java.io.*;

public class IniProperties {
    private Properties globalProperties;
    private Map<String,Properties> properties;

    enum ParseState {
        NORMAL,
        ESCAPE,
        ESC_CRNL,
        COMMENT
    }

    public IniProperties() {
        globalProperties = new Properties();
        properties = new HashMap<String,Properties>();
    }

    /**
     * Load ini as properties from input stream.
     */
    public void load(InputStream in) throws IOException {
        int bufSize = 4096;
        byte[] buffer = new byte[bufSize];
        int n = in.read(buffer, 0, bufSize);

        ParseState state = ParseState.NORMAL;
        boolean section_open = false;
        String current_section = null;
        String key = null, value = null;
        StringBuilder sb = new StringBuilder();
        while (n >= 0) {
            for (int i = 0; i < n; i++) {
                char c = (char) buffer[i];

                if (state == ParseState.COMMENT) { // comment, skip to end of line
                    if ((c == '\r') ||(c == '\n')) {
                        state = ParseState.NORMAL;
                    }
                    else {
                        continue;
                    }
                }

                if (state == ParseState.ESCAPE) {
                    sb.append(c);
                    if (c == '\r') {
                        // if the EOL is \r\n, \ escapes both chars
                        state = ParseState.ESC_CRNL;
                    }
                    else {
                        state = ParseState.NORMAL;
                    }
                    continue;
                }

                switch (c) {
                    case '[': // start section
                        sb = new StringBuilder();
                        section_open = true;
                        break;
                   
                    case ']': // end section
                        if (section_open) {
                            current_section = sb.toString().trim();
                            sb = new StringBuilder();
                            properties.put(current_section, new Properties());
                            section_open = false;
                        }
                        else {
                            sb.append(c);
                        }
                        break;

                    case '\\': // escape char, take the next char as is
                        state = ParseState.ESCAPE;
                        break;

                    case '#':
                    case ';':
                        state = ParseState.COMMENT;
                        break;

                    case '=': // assignment operator
                    case ':':
                        if (key == null) {
                            key = sb.toString().trim();
                            sb = new StringBuilder();
                        }
                        else {
                            sb.append(c);
                        }
                        break;

                    case '\r':
                    case '\n':
                        if ((state == ParseState.ESC_CRNL) && (c == '\n')) {
                            sb.append(c);
                            state = ParseState.NORMAL;
                        }
                        else {
                            if (sb.length() > 0) {
                                value = sb.toString().trim();
                                sb = new StringBuilder();
                       
                                if (key != null) {
                                    if (current_section == null) {
                                        this.setProperty(key, value);
                                    }
                                    else {
                                        this.setProperty(current_section, key, value);
                                    }
                                }
                            }
                            key = null;
                            value = null;
                        }
                        break;

                    default:
                        sb.append(c);
                }
            }
            n = in.read(buffer, 0, bufSize);
        }
    }

    /**
     * Get global property by name.
     */
    public String getProperty(String name) {
        return globalProperties.getProperty(name);
    }

    /**
     * Set global property.
     */
    public void setProperty(String name, String value) {
        globalProperties.setProperty(name, value);
    }

    /**
     * Return iterator of global properties.
     */
    @SuppressWarnings("unchecked")
    public Iterator<String> properties() {
        return new IteratorFromEnumeration<String>(
                   (Enumeration<String>)globalProperties.propertyNames());
    }

    /**
     * Get property value for specified section and name. Returns null
     * if section or property does not exist.
     */
    public String getProperty(String section, String name) {
        Properties p = properties.get(section);
        return p == null ? null : p.getProperty(name);
    }

    /**
     * Set property value for specified section and name. Creates section
     * if not existing.
     */
    public void setProperty(String section, String name, String value) {
        Properties p = properties.get(section);
        if (p == null) {
            properties.put(section, new Properties());
        }
        p.setProperty(name, value);
    }

    /**
     * Return property iterator for specified section. Returns null if
     * specified section does not exist.
     */
    @SuppressWarnings("unchecked")
    public Iterator<String> properties(String section) {
        Properties p = properties.get(section);
        if (p == null) {
            return null;
        }
        return new IteratorFromEnumeration<String>(
                   (Enumeration<String>)p.propertyNames());
    }

    /**
     * Return iterator of names of section.
     */
    public Iterator<String> sections() {
        return properties.keySet().iterator();
    }

    /**
     * Dumps properties to output stream.
     */
    public void dump(PrintStream out) throws IOException {
        // Global properties
        Iterator<String> props = this.properties();
        while (props.hasNext()) {
            String name = props.next();
            out.printf("%s = %s\n", name, dumpEscape(getProperty(name)));
        }

        // sections
        Iterator<String> sections = this.sections();
        while (sections.hasNext()) {
            String section = sections.next();
            out.printf("\n[%s]\n", section);
            props = this.properties(section);
            while (props.hasNext()) {
                String name = props.next();
                out.printf("%s = %s\n", name, dumpEscape(getProperty(section, name)));
            }
        }
    }

    private static String dumpEscape(String s) {
        return s.replaceAll("\\\\", "\\\\\\\\")
                .replaceAll(";", "\\\\;")
                .replaceAll("#", "\\\\#")
                .replaceAll("(\r?\n|\r)", "\\\\$1");
    }

    // private class used to coerce Enumerator to Iterator.
    private static class IteratorFromEnumeration<E> implements Iterator {
        private Enumeration<E> e;

        public IteratorFromEnumeration(Enumeration<E> e) {
            this.e = e;
        }

        public boolean hasNext() {
            return e.hasMoreElements();
        }

        public E next() {
            return e.nextElement();
        }

        public void remove() {
            throw new UnsupportedOperationException("Can't change underlying enumeration");
        }
    }
}


===========================================================================

사용법 :

java.io.FileInputStream fis = new java.io.FileInputStream
          (new java.io.File( 파일경로+파일명 ));
       iniProp.load(fis);

String strVFormat=iniProp.getProperty("VALIDITY","Format");

AND


import java.io.*;

public class runThread implements Runnable{
 protected Runtime rt;
 protected String cmd;
 static int nSuc=0;
 public runThread(){
  rt=Runtime.getRuntime();
  cmd="java Test";
  
 }
 public void run(){
  try{
   Process proc=rt.exec(cmd);
   InputStream in=proc.getInputStream();
   byte buffer[]=new byte[12000];
   int n=-1;   
   String Temp = "";
   
   ;
   //System.out.println(n);
   
   while ( (n=in.read(buffer)) != -1 || (n=in.read(buffer)) !=0 ) {
    //System.out.println(n);
    if (n<=0) break;
    Temp=new String(buffer,0,n);
    
    if ( Temp == null ) {
     return ;
    }
    
    if ( Temp.indexOf("성공")>=0 ) {
     nSuc++;
     System.out.print(Temp);
     System.out.println(String.valueOf(nSuc) + "/50");
    }
    //n=in.read(buffer);
   }
   in.close();
   return ;
  }catch(Exception ex){
   ex.printStackTrace();
  }
 }
 public static void main(String[]args){
  for(int i = 0; i < 20; i++){
   Thread t = new Thread(new runThread());
   t.start();
  }
 }
}

AND


1. Test.java 소스

[root@image01 wsloader]# cat Test.java
import java.io.*;

public class Test {
        public static void main(String[] args) throws Exception {
                System.out.println("file.encoding="+System.getProperty("file.encoding"));
                System.out.println("테스트");
        }
}

2.테스트

[root@image01 wsloader]# env | grep LANG
LANG=ko_KR.eucKR
[root@image01 wsloader]# javac Test.java
[root@image01 wsloader]# java Test
file.encoding=EUC-KR
테스트
[root@image01 wsloader]# export LANG=c
[root@image01 wsloader]# java Test
file.encoding=ANSI_X3.4-1968
???
[root@image01 wsloader]# export LANG=ko_KR.eucKR
[root@image01 wsloader]# java Test
file.encoding=EUC-KR
테스트

AND

public void setBytes(int parameterIndex,byte[] x)
              throws SQLException
AND