반응형

살다보면


모든 환경에서 쓸일이 있다... -_-...




EchoServer.java 파일(1024 포트 사용 예)

 import java.io.* ;

import java.net.* ;

class EchoServer {

public static void main( String[] args )

 throws IOException {

// 포트 설정

int port = 1024 ;

// 서버 소켓 생성

ServerSocket ss = new ServerSocket(port) ;

System.out.println( "Server Ready" ) ;

// 클라이언트 연결을 계속해서 받는다.

while( true ) {

// 클라이언트 연결을 받는다.

Socket client = ss.accept() ;

// 네트워크 입출력 스트림 설정

BufferedReader net_in = 

new BufferedReader( new InputStreamReader( client.getInputStream() ) ) ;

PrintWriter net_out = 

new PrintWriter( new OutputStreamWriter( client.getOutputStream() ) ) ;

System.out.println( "Client Socket Accepted" + client ) ;

System.out.flush() ;

// 클라이언트의 데이터를 받는다.

String line ;

line = net_in.readLine() ;

// 받은 데이터를 다시 전송한다.

net_out.println( line ) ;

net_out.flush() ;

}

}

}





EchoClient.java 파일 내용


 import java.io.* ;

import java.net.* ;

class EchoClient {

public static void main( String[] args )

 throws IOException {

// 접속 대상 설정

String host = "127.0.0.1" ;

int port = 1024 ;

// 소켓을 생성

Socket s = new Socket( host , port ) ;

System.out.println( "Client Socket Created" + s ) ;

System.out.flush() ;

// 네트워크 통신을 위한 스트림 설정

Reader from_server = new InputStreamReader(s.getInputStream()) ;

PrintWriter to_server = 

new PrintWriter(new OutputStreamWriter(s.getOutputStream()) ) ;

// 콘솔 입출력을 위한 스트림 설정

BufferedReader from_user = 

new BufferedReader( new InputStreamReader( System.in ) ) ;

PrintWriter to_user = 

new PrintWriter( new OutputStreamWriter( System.out ) ) ;

// 사용자의 입력을 받는다.

String line ;

while( (line = from_user.readLine()) != null ) {

// 받은 입력은 네트워크로 전송한다.

to_server.println( line ) ;

to_server.flush() ;

// 네트워크에서 데이터를 받는다.

int char_cnt ;

char[] buffer = new char[1024] ;

char_cnt = from_server.read(buffer) ;

// 받은 데이터를 화면에 뿌린다.

to_user.write( buffer , 0 , char_cnt ) ;

to_user.flush() ;

}

}

}


특정 서버에 대한 포트 스캔 프로그램 (PortScanner.java)


 import java.net.*;

public class PortScanner {

public static void main(String args[]) {

int startPortRange=0;

int stopPortRange=0;

startPortRange = Integer.parseInt(args[0]);

stopPortRange = Integer.parseInt(args[1]);

for (int i=startPortRange; i <=stopPortRange; i++) {

try {

Socket ServerSok = new Socket("127.0.0.1",i);

System.out.println("Port in use: " + i );

ServerSok.close();

}

catch (Exception e) {

}

System.out.println("Port not in use: " + i );

}

}

}



반응형
반응형

자바 ARIA 사용하는 암호화 소스...


뭐 이젠 없어질 꺼지만... 


나중이라도..


크크...


SSO 가격도 비싸고 -_-...


그걸 굳이 쓸 필요가 있을까 싶다...




20120515_cipher.zip


반응형
반응형

Java 성능 모니터링에 대해 모르고 있던 5가지 사항, Part 1



JConsole과 VisualVM을 사용한 Java 성능 프로파일링

Ted Neward, Principal, Neward & Associates

요약:  잘못된 코드(또는 잘못된 코드의 작성자)를 비난하는 것은 성능 병목 현상을 찾아내고 Java™ 애플리케이션의 속도를 향상시키는 데 아무런 도움이 되지 않으며 그 어느 것도 추측할 수 없습니다. 이 기사를 통해 Ted Neward는 Java 성능 모니터링 도구에 대한 관심을 촉구하고 있으며 먼저 Java 5의 내장 프로파일러인 JConsole을 사용하여 성능 데이터를 수집 및 분석하는 방법에 대한 5가지 팁을 소개합니다.

이 기사에 태그:  성능, 애플리케이션_개발

원문 게재일:  2010 년 6 월 29 일 번역 게재일:   2010 년 11 월 02 일 
난이도:  초급 영어로:  보기 PDF:  A4 and Letter (28KB | 7 pages)Get Adobe® Reader® 
페이지뷰:  3707 회 
의견:   0 (보기 | 의견 추가 - 로그인)

평균 평가 등급 3 개 총 2표 평균 평가 등급 (2 투표수)
아티클 순위

이 시리즈의 정보

Java 프로그래밍에 대해 알고 있다고 생각하는가? 하지만 실제로는 대부분의 개발자가 작업을 수행하기에 충분할 정도만 알고 있을 뿐 Java 플랫폼에 대해서는 자세히 알고 있지 않다. 이 시리즈에서 Ted Neward는 Java 플랫폼의 핵심 기능에 대한 자세한 설명을 통해 까다로운 프로그래밍 과제를 해결하는 데 도움이 되는 알려져 있지 않은 사실을 밝힌다.

애플리케이션 성능이 나쁠 경우 많은 개발자는 공황 상태에 빠지고 만다. 그리고 이러한 성능 저하에는 합당한 이유가 있기 마련이다. Java 애플리케이션 병목 현상의 소스를 추적하는 작업은 역사적으로 매우 어려운 작업 중 하나이다. 왜냐하면 Java 가상 머신에 블랙박스 효과가 있을 뿐만 아니라 전통적으로 Java 플랫폼용 프로파일링 도구가 부족하기 때문이다.

하지만 Java 5에서 JConsole이 등장하면서 모든 것이 바뀌었다. JConsole은 명령행과 GUI 쉘에서 작동하는 내장 Java 성능 프로파일러이다. 이 프로파일러는 완벽하지는 않지만 지식이 풍부한 책임자가 성능 문제점을 지적할 때 적절하게 대응할 수 있는 방법을 제공할 뿐만 아니라 Papa Google에 문의하는 것보다 전체적으로 훨씬 더 좋은 결과를 제공한다.

5가지 사항 시리즈의 이 기사에서는 JConsole(또는 유사한 기능을 그래픽으로 제공하는 VisualVM)을 사용하여 Java 애플리케이션 성능을 모니터링하고 Java 코드의 병목 현상을 추적하는 데 사용할 수 있는 5가지 쉬운 방법을 설명한다.

1. JDK의 내장 프로파일러

많은 Java 개발자가 Java 5 이후로 프로파일러 도구가 JDK에 포함되어 있다는 사실을 모르고 있다. JConsole(또는 최근 Java 플랫폼 릴리스의 경우에는 VisualVM)은 Java 컴파일러처럼 쉽게 실행할 수 있는 내장 프로파일러이다. JDK가 PATH에 있는 명령 프롬프트에서 jconsole을 실행하거나 GUI 쉘에서 JDK 설치 디렉토리로 이동한 후 bin 폴더를 열고 jconsole을 두 번 클릭한다.

프로파일러 도구가 실행되면 실행 중인 Java의 버전과 동시에 실행 중인 다른 Java 프로그램의 수에 따라 연결할 프로세스의 URL을 묻는 대화 상자가 표시되거나 연결할 수많은 다른 로컬 Java 프로세스가 나열되며, 나열된 목록에 JConsole 프로세스 자체가 포함되기도 한다.

JConsole 또는 VisualVM

JConsole은 Java 5 이후 모든 Java 플랫폼 릴리스에 포함되어 있다. VisualVM은 NetBeans 플랫폼을 기반으로 업데이트된 프로파일러이며 Java 6 업데이트 12 이후로 처음 포함되었다. 대부분의 작업 환경이 아직까지 Java 6으로 업그레이드되지 않았기 때문에 이 기사에서는 JConsole에 중점을 두고 설명한다. 하지만 대부분의 팁은 두 프로파일러 모두와 관련된다. (참고: Java 6에 포함되고 있는 VisualVM은 독립형 다운로드이기도 하다. VisualVM을 다운로드하려면 참고자료를 참조한다.)

JConsole 작업하기

Java 5에서 Java 프로세스는 기본적으로 프로파일링되도록 설정되지 않는다. 시동 시에 명령행 인수 -Dcom.sun.management.jmxremote를 전달하면 Java 5 VM이 연결을 열게 되며 그러면 프로파일러가 연결을 찾을 수 있다. JConsole에서 프로세스가 선택되면 프로세스를 두 번 클릭하여 프로파일링을 시작할 수 있다.

프로파일러에는 고유한 오버헤드가 있으므로 이 오버헤드를 먼저 확인하는 것이 좋다. JConsole의 오버헤드를 가장 쉽게 확인하는 방법은 먼저 애플리케이션 자체를 실행한 다음 프로파일러 하에서 애플리케이션을 다시 실행하여 그 차이를 측정하는 것이다. (이 경우 애플리케이션이 너무 크거나 작아서도 안 된다. 필자는 주로 JDK에 포함된 SwingSet2 데모 애플리케이션을 사용한다.) 따라서 필자는 먼저 가비지 콜렉션 회수를 보기 위해 -verbose:gc를 사용하여 SwingSet2를 실행했다. 그런 다음 동일한 애플리케이션을 다시 실행한 후 JConsole 프로파일러를 연결했다. JConsole이 연결된 경우에는 GC 회수 스트림이 지속적으로 발생한 반면 그렇지 않은 경우에는 회수 스트림이 발생하지 않았다. 바로 이러한 차이가 프로파일러의 성능 오버헤드이다.

2. 프로세스에 원격으로 연결하기

웹 애플리케이션 프로파일러는 소켓을 통한 프로파일링용 연결을 가정하므로 원격으로 실행 중인 애플리케이션을 모니터링/프로파일링하도록 JConsole(또는 JVMTI 기반 프로파일러)을 설정하는 간단한 구성만 수행하면 된다.

예를 들어, Tomcat이 "webserver"라는 시스템에서 실행 중이고 JVM에서 JMX를 사용하고 있고 포트 9004를 청취하고 있을 경우 JConsole(또는 기타 JMX 클라이언트)에서 JMX에 연결하려면 "service:jmx:rmi:///jndi/rmi://webserver:9004/jmxrmi"라는 JMX URL이 필요하다.

기본적으로 원격 데이터 센터에서 실행 중인 애플리케이션을 프로파일링하는 데 필요한 항목은 JMX URL이다. (JMX와 JConsole을 사용하여 원격 모니터링 및 관리를 수행하는 방법에 대한 자세한 정보는 참고자료를 참조한다.)

3. 통계 추적하기

타성에 젖지 마라!

일반적으로 애플리케이션 코드의 성능 문제점을 찾는 방법은 매우 다양하지만 몇 가지 형태로 예측할 수 있다. 초기 Java 시절부터 프로그래밍해 온 개발자는 오래된 IDE를 시작한 후 코드 베이스의 주요 부분에 대한 코드 검토를 시작하여 소스에서 익숙한 "빨간색 플래그"(예: 동기화된 블록, 오브젝트 할당 등)를 찾는 경향이 있다. 프로그래밍 경력이 수 년 이내인 개발자는 아마도 JVM에서 지원하는-X 플래그를 자세히 보면서 가비지 콜렉터를 최적화하는 방법을 찾을 것이다. 그리고 초보 개발자라면 코드를 다시 작성하는 일이 없도록 하기 위해 누군가가 JVM의 마술 같은 "make it go fast" 스위치를 찾아놓았을 것을 기대하면서 Google을 검색할 것이다.

이러한 접근 방법 모두 본질적으로 잘못된 방법은 아니지만 일종의 무모한 도전이다. 성능 문제점에 대한 가장 효과적으로 대응하는 방법은 프로파일러를 사용하는 것이다. 그리고 오늘날에는 Java 플랫폼에 프로파일러가 내장되어 있으므로 사용하지 않을 이유가 없다.

JConsole에는 다음 탭을 포함하여 통계 수집에 유용한 여러 가지 탭이 있다.

  • Memory: JVM 가비지 콜렉터의 다양한 힙에 대한 활동을 추적한다.
  • Threads: 대상 JVM의 현재 스레드 활동을 조사한다.
  • Classes: 한 VM에 로드된 총 클래스 수를 검사한다.

이러한 탭(및 연관된 그래프)은 모두 Java 5 이상의 모든 VM이 JVM에 내장된 JMX 서버에 등록하는 JMX 오브젝트의 기능이다. 지정된 JVM에서 사용할 수 있는 전체 Bean 목록이 MBeans 탭에 나열되며, 해당 데이터를 보거나 이러한 조작을 실행하는 데 필요한 제한된 사용자 인터페이스와 일부 메타데이터가 함께 제공된다. (하지만 알림 등록은 JConsole 사용자 인터페이스의 범위에 해당되지 않는다.)

통계 사용하기

Tomcat 프로세스에서 OutOfMemoryError가 지속적으로 발생하고 있다고 가정하자. 어떻게 된 일인지 알아보기 위해 JConsole을 열고 Classes 탭을 클릭한 다음 클래스 수를 계속 살펴본다. 클래스 수가 지속적으로 올라가면 애플리케이션 서버 또는 코드의 어느 부분에선가ClassLoader 누수가 발생하고 있으며 머지 않아 PermGen 공간이 소진될 것이라고 간주할 수 있다. 문제점을 자세히 확인할 필요가 있는 경우에는 Memory 탭을 검사한다.

4. 오프라인 분석을 위해 힙 덤프 작성하기

프로덕션 환경에서는 많은 작업이 빠르게 수행되기 때문에 애플리케이션 프로파일러에 할애할 수 있는 시간이 많지 않을 것이다. 대신 Java 환경의 모든 사항에 대한 스냅샷을 작성하여 저장한 후 나중에 살펴볼 수 있다. JConsole에서 이 작업을 수행할 수 있으며 VisualVM에서는 더 효과적으로 수행할 수 있다.

먼저 MBeans 탭으로 이동한 후 com.sun.management 노드와 HotSpotDiagnostic 노드를 차례로 연다. 그런 다음 Operations를 선택하고 오른쪽 분할창에 있는 "dumpHeap" 단추를 누른다. 첫 번째("String") 입력 상자에 덤프할 파일 이름을 입력하여 dumpHeap에 전달하면 전체 JVM 힙에 대한 스냅샷이 작성되어 해당 파일에 기록된다.

나중에 다양한 상용 프로파일러를 사용하여 파일을 분석하거나 VisualVM을 사용하여 스냅샷을 분석할 수 있다. (VisualVM은 Java 6에서 사용할 수 있으며 독립형 다운로드로도 사용할 수 있다.)

5. JConsole이 최고는 아니다.

프로파일러 유틸리티로서 JConsole이 좋은 도구임에 틀림 없지만 그보다 더 좋은 도구도 있다. 분석 추가 기능이나 멋진 사용자 인터페이스를 갖춘 프로파일러도 있고 기본적으로 JConsole보다 더 많은 데이터를 추적하는 프로파일러도 있다.

JConsole의 진정한 매력은 전체 프로그램이 "평범한 구형 Java"로 작성되어 있다는 것이다. 이는 곧 Java 개발자라면 누구나 이와 같은 유틸리티를 작성할 수 있다는 것을 의미한다. 실제로 JDK에는 JConsole용 새 플러그인을 작성하여 JConsole을 사용자 정의하는 방법을 보여 주는 예제가 포함되어 있다(참고자료 참조). NetBeans를 기반으로 빌드된 VisualVM에서는 플러그인 개념을 훨씬 더 잘 활용한다.

JConsole(또는 VisualVM이나 기타 도구)이 원하는 기능을 제공하지 않거나, 추적하려는 항목을 추적하지 않거나, 원하는 방식으로 추적하지 않을 경우 사용자가 직접 코드를 작성할 수 있다. Java 코드가 너무 복잡해 보일지도 모르지만 언제라도 Groovy, JRuby 또는 기타 JVM 언어를 활용하여 코드를 빠르게 작성할 수 있다.

실제로 가장 필요한 것은 JMX를 통해 연결되는 사용하기 편리한 명령 도구이며, 원하는 데이터를 원하는 방식으로 정확히 추적할 수 있다.

결론

Java 성능 모니터링은 JConsole이나 VisualVM에서 끝나지 않는다. JDK에는 대부분의 개발자가 모르고 있는 수많은 도구가 있다. 이 시리즈의 다음 기사에서는 필요한 성능 데이터를 더 자세히 살펴보는 데 도움이 되는 실험 수준의 몇 가지 명령 도구에 대해 살펴본다. 이러한 도구는 일반적으로 특정 데이터를 중점적으로 다루기 때문에 완전한 프로파일러에 비해 규모가 작은 경량 도구이다. 따라서 성능 오버헤드도 발생하지 않는다.


참고자료

교육

  • "모르고 있던 5가지 사항": Java 플랫폼에 대해 모르는 것이 많았다는 것을 일깨워 주는 이 시리즈에서는 사소하게 여겼던 Java 기술을 유용한 프로그래밍 팁으로 바꿔준다. 

  • "Monitoring and management using JMX"(Sun Microsystems): JMX와 JVM의 내장 인스트루멘테이션 도구를 사용하여 Java 애플리케이션 성능을 모니터링 및 관리하는 방법에 대해 알아보자. 

  • "Mustang JConsole"(Mandy Chung 저, Java.net, 2008년 5월): JConsole Plugin API를 사용하여 사용자 정의 플러그인을 빌드하는 방법에 대해 간략하게 소개한다. 

  • "Acquiring JVM Runtime Information"(Dustin Marx 저, Dustin's Software Development Cogitations and Speculations, 2009년 6월): JConsole과 VisualVM을 포함한 JDK의 내장 모니터링 및 관리 도구에 대한 데모를 볼 수 있다. 

  • "Build your own profiler"(Andrew Wilcox 저, developerWorks, 2006년 3월): Java 5 에이전트 인터페이스와 AOP를 사용하여 사용자 정의 프로파일러인 Java Interactive Profiler를 빌드하는 방법을 보여 준다. 

  • IBM Monitoring and Diagnostic Tools for Java: Health Center는 실행 중인 IBM Java Virtual Machine을 모니터링하는 기능을 제공하는 낮은 오버헤드의 진단 도구이다. 

  • developerWorks Java 기술 영역: Java 프로그래밍과 관련된 모든 주제를 다루는 여러 편의 기사를 찾아보자. 

제품 및 기술 얻기

  • VisualVM은 여러 명령행 JDK 도구와 경량 프로파일링 기능을 통합한 비주얼 도구이다. 

토론

필자소개

Ted Neward는 글로벌 컨설팅 업체인 ThoughtWorks의 컨설턴트이자 Neward & Associates의 회장으로 Java, .NET, XML 서비스 및 기타 플랫폼에 대한 컨설팅, 조언, 교육 및 강연을 한다. 워싱턴 주의 시애틀 근교에 살고 있다.


반응형
반응형

개발자의 실수를 줄여주는 java.sql.Connection 만들기







흔히 close()를 하지 않아서 발생하는 자원 누수 현상을 줄여주는 Connection 클래스를 만들어본다.

JDBC API 사용시 흔히 하는 개발자의 실수

JDBC API를 사용하여 데이터베이스 프로그래밍을 할 때 가장 많이 사용되는 코드는 아마도 다음과 같은 형태일 것이다.

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    
    try {
        conn = DBPool.getConnection(); //
        stmt = conn.createStatement();
        rs = stmt.executeQuery(..);
        ...
    } catch(SQLException ex) {
        // 예외 처리
    } finally {
        if (rs != null) try { rs.close(); } catch(SQLException ex) {}
        if (stmt != null) try { stmt.close(); } catch(SQLException ex) {}
        if (conn != null) try { conn.close(); } catch(SQLException ex) {}
    }

그런데 위와 같은 프로그래밍을 할 때 흔히 하는 실수가 close()를 제대로 해 주지 않는 것이다. 특히, 하나의 메소드에서 5-10개의 (PreparedStatement를 포함한)Statement와 ResultSet을 사용하는 경우에는 개발자의 실수로 같은 Statement를 두번 close() 하고 한두개의 Statement나 ResultSet은 닫지 않는 실수를 하곤 한다. 이처럼 close() 메소드를 알맞게 호출해주지 않을 경우에는 다음과 같은 문제가 발생한다.

  1. Statement를 닫지 않을 경우, 생성된 Statement의 개수가 증가하여 더 이상 Statement를 생성할 수 없게 된다.
  2. close() 하지 않으므로 불필요한 자원(네트워크 및 메모리)을 낭비하게 된다.
  3. 커넥션 풀을 사용하지 않는 상황에서 Connection을 닫지 않으면 결국엔 DBMS에 연결된 새로운 Connection을 생성할 수 없게 된다.
위의 문제중 첫번째와 두번째 문제는 시간이 지나면 가비지 콜렉터에 의해서 해결될 수도 있지만, 만약 커넥션 풀을 사용하고 있다면 그나마 가비지 콜렉션도 되지 않는다. 따라서 커넥션 풀을 사용하는 경우 Statement와 ResultSet은 반드시 닫아주어야만 한다. 하지만, 제아무리 실력이 뛰어난 개발자라 할지라도 각각 수십에서 수백줄로 구성된 수십여개의 .java 파일을 모두 완벽하게 코딩할 수는 없으며, 따라서 한두군데는 close()를 안 하기 마련이다. 운이 좋으면 빨리 찾을 수 있겠지만, 그렇지 않다면 close() 안한 부분을 찾는 데 몇십분, 몇시간, 심한 경우 1-2일 정도가 걸리기도 한다.

Statement를 자동으로 닫아주는 MVConnection 클래스 구현

실제로 필자도 앞에서 언근했던 문제들 때문에 고생하는 사람들을 종종 봐 왔었으며, 그때마다 그 버그를 고치기 위해서 소스 코드를 일일이 찾아보는 노가다를 하는 개발자들을 보기도 했다. 그래서 만든 클래스가 있는데, 그 클래스의 이름을 MVConnection이라고 붙였다. 이름이야 여러분의 입맛에 맛게 수정하면 되는 것이므로, 여기서는 원리만 간단하게 설명하도록 하겠다.

먼저, MVConnection을 구현하기 전에 우리가 알고 있어야 하는 기본 사항이 있다. JDBC API를 유심히 읽어본 사람이라면 다음과 같은 내용을 본 적이 있을 것이다.

  • Statement를 close() 하면 Statement의 현재(즉, 가장 최근에 생성한) ResultSet도 close() 된다.
  • ResultSet은 그 ResultSet을 생성한 Statement가 닫히거나, 또는 executeQuery 메소드를 실행하는 경우 close() 된다.
MVConnection은 바로 이 두가지 특성을 사용한다. 위의 두 가지 특징을 정리하면 결국 Statement만 알맞게 닫아주면 그와 관련된 ResultSet은 자동으로 닫힌다는 것을 알 수 있다. 따라서 ConnectionWrapper 클래스는 Connection이 생성한 Statement들만 잘 보관해두었다가 각 Statement를 닫아주기만 하면 되는 것이다. PreparedStatement나 CallableStatement는 Statement를 상속하고 있으므로 따로 처리할 필요 없이 Statement 타입으로 모두 처리할 수 있으므로, PreparedStatement와 CallableStatement를 위한 별도의 코드는 필요하지 않다.

다음은 MVConnection 클래스의 핵심 코드이다.

    public class MVConnection implements Connection {
        
        private Connection conn; // 실제 커넥션
        
        private java.util.List statementList; // statement를 저장
        
        public MVConnection(Connection conn) {
            this.conn = conn;
            statementList = new java.util.ArrayList();
        }
        
        public void closeAll() {
            for (int i = 0 ; i < statementList.size() ; i++) {
                Statement stmt = (Statement)statementList.get(i);
                try {
                    stmt.close();
                } catch(SQLException ex) {}
            }
        }
        
        public void close() throws SQLException {
            this.closeAll();            conn.close();
        }
        
        public Statement createStatement() throws SQLException {
            Statement stmt = conn.createStatement();
            statementList.add(stmt);
            return stmt;
        }
        
        public CallableStatement prepareCall(String sql) throws SQLException {
            CallableStatement cstmt = conn.prepareCall(sql);
            statementList.add(cstmt);
            return cstmt;
        }
        
        public PreparedStatement prepareStatement(String sql) throws SQLException {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            statementList.add(pstmt);
            return pstmt;
        }
        
        ...
    }

위 코드를 보면 Statement를 저장하기 위한 List와 그 List에 저장된 Statement 객체를 모두 닫아주는 closeAll() 이라는 메소드가 정의되어 있다. 바로 이 List와 closeAll() 메소드가 이 MVConnection 클래스의 핵심이다. Statement를 생성해주는 메소드(createStatement, prepareCall, prepareStatement)를 보면 생성된 Statement를 statemetList에 추가해주는 것을 알 수 있다. 이렇게 저장된 Statement는 실제로 Connection을 닫을 때, 즉 Connection의 close() 메소드를 호출할 때 닫힌다. (코드를 보면 close() 메소드에서 closeAll() 메소드를 먼저 호출하고 있다.) 따라서, close() 메소드만 호출하면 그와 관련된 모든 Statement와 ResultSet은 자동으로 닫히게 된다.

위 코드에서 다른 메소드들은 모두 다음과 같이 간단하게 구현된다.

    public boolean getAutoCommit() throws SQLException {
        return conn.getAutoCommit();
    }

MVConnection은 java.sql.Connection을 implements 하기 때문에, 그 자체가 Connection으로 사용될 수 있다. 따라서 MVConnection을 사용한다고 해서 특별히 코드가 많이 변경되지는 않으며 다음과 같이 전체적으로 코드가 단순하게 바뀐다.

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    
    try {
        // MV Connection 생성
        conn = new MVConnection(DBPool.getConnection());
        stmt = conn.createStatement();
        rs = stmt.executeQuery(..);
        ...
    } catch(SQLException ex) {
        // 예외 처리
    } finally {
        // conn 만 close() 해준다.
        if (conn != null) try { conn.close(); } catch(SQLException ex) {}
    }

때에 따라서는 Connection을 close() 하지 않고 커넥션 풀에 되돌려 놔야 할 때가 있다. 그런 경우에는 다음과 같은 형태의 코드를 사용하면 된다.

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    
    try {
        // MV Connection 생성
        conn = new MVConnection(DBPool.getConnection());
        stmt = conn.createStatement();
        rs = stmt.executeQuery(..);
        ...
    } catch(SQLException ex) {
        // 예외 처리
    } finally {
        if (conn != null) try { 
            ((MVConnection)conn).closeAll();
            DBPool.returnConnection(conn);
        } catch(SQLException ex) {}
    }

즉, Connection을 닫지 않는 경우에는 위와 같이 커넥션 풀에 반환하기 전에 closeAll() 메소드 하나만을 호출해주면 된다. 그러면 Connection과 관련된 모든 Statement, ResultSet 등이 닫히게 된다.

결론

필자의 경우는 이 글에서 작성한 MVConnection을 실제 프로젝트에 응용하여 코드 작성의 편리함 뿐만 아니라 실수로 인해서 발생하는 시스템의 버그 문제를 어느 정도 해결할 수 있었다. 특히, Statement를 생성하거나 ResultSet을 생성할 때 발생하는 커서부족 문제를 획기적으로 줄일 수 있었다. 여러분도 이 클래스를 응용하여 보다 나은 방법으로 코딩의 실수 및 자원의 낭비를 줄일 수 있는 클래스를 작성해보기 바란다.

반응형
반응형


참고 사이트 (Reference Site)

  1.MAT (Eclipse Memory Analyzer) 메모리 분석 GUI 툴
    http://www.eclipse.org/mat/downloads.php 

  2. IBM Diagnostic Tool Framework for Java Version 1.5
    http://www.ibm.com/developerworks/java/jdk/tools/dtfj.html  

  3.일본 MAT 적용 참고 사이트   
     http://d.hatena.ne.jp/kakku22/20110910/1315646914 
 


heapdump는 시스템 운영 중 항상 발생할 수 있는 문제이며,

빵빵한 시스템에서는 IBM Heap Analyzer를 사용하여 분석한다

다만,

위와 같은 빵빵한(?) 시스템이 지원되지 않는 환경(Windows 32bit)에서는

분석하는 방법이 없을까 많은 고민을 하였고, 찾다보니 아에 방법이 없지만은 않았다.


1. GUI 툴 다운로드
    - 이클립스 사이트에서 dump 분석을 위한 툴을(MAT) 제공한다.
    - 위의 참고사이트 1번 항목을 방문하면 다운로드 가능하다.

 
     - 다운 받은 파일의 압축을 풀고 해당 디렉토이에 들어가면 MemoryAnlyzer.exe와 MemoryAnalyzer.ini 파일등이 보인다.
     - 32bit 환경에서 최대 할당 가능한 heap 사이즈로 로딩 가능하도록 MemoryAnlyzer.ini 파일을 수정한다.

  -vmargs
 -Xmx1372m
 
2. IBM Heapdump 분석을 위해서는 별도의 plug-in을 추가한다.
   (인터넷 검색하면 많은 내용이 나오지만 위의 DTFJ 파일 방식이 대용량의 힙 덤프 분석에는 최고다..)
   - 2번 사이트 방문하여 다운로드 한다.


위의 클릭을 하면 zip 파일을 받을 수 있다.
   
받은 zip 파일을 MAT 압축을 풀은 디렉토리 내에 DTFJ 폴더를 만들어 그안에 복사하여 놓는다.

3. MAT에 Plug-IN 설치
    - MemoryAnlyzer.exe 더블 클릭하여 MAT 를 실행함.
    - 실행화면
     

 
     -  Help -> Install New Software... 실행


   - Add.. 를 크릭하여 설치 가능한 소프트웨어를 추가함.


     - Name에는 명칭을 적고, Location 부분은 우측의 Archive를 클릭하여 다운받은 dtfj-updatesite.zip를 직접 지정함

 
    - Check 후 Next를 클릭 -> Next

 
 - 라이센스 동의 후 Finish 클릭

 

- local 설치이다 보니 보안 땜시 한번더 묻는거임... ok 살포시 눌러줌

 
 - 다시 시작함(Restart Now를 눌러)

 
  - File -> Open Heap Dump... 를 눌러 IBM Heapdump 파일을 선택하여 분석함..

 
나머지 분석과 관련된 상세한 사항은 인터넷 검색 ㄱㄱ 
반응형
반응형

출처 : http://visualvm.java.net/eclipse-launcher.html


1. 설치방법
   - 위 사이트에서 Visualvm 파일을 다운받아서 이클립스 설치 디렉토리에 압축을 푼다.

2. 환경구성
    - 그림을 보면서 하면됨.


    - JDK 홈 디렉토리의 VisualVM을 사용함(JRE는 아님!, 반드시 JDK가 필요)
    - 위의 경로의 VIsualVM이 실행가능해야 함.

3. 사용법
    - 위의 Application Configuration 설정을 해줌
    - 실행 런처를 VisualVM Launcher로 변경함.
    - VIsualVM 자동 시작되는 구성으로 어플리케이션이 실행과 디버그가 생성된다.

추가로...

Default Launch를 변경하면

모두 모니터링 가능하다..

설정화면 !

참고로 visual VM을 (위의 지정된 경로에있는)

실행하면 바로 모니터링 됨 !

반응형
반응형

출처(Reference) : http://www.javafaq.nu/java-example-code-141.html


// -----------------------------------------------------------------------------
// CLOBFileExample.java
// -----------------------------------------------------------------------------

/*
 * =============================================================================
 * Copyright (c) 1998-2005 Jeffrey M. Hunter. All rights reserved.
 *
 * All source code and material located at the Internet address of
 * http://www.idevelopment.info is the copyright of Jeffrey M. Hunter, 2005 and
 * is protected under copyright laws of the United States. This source code may
 * not be hosted on any other site without my express, prior, written
 * permission. Application to host any of the material elsewhere can be made by
 * contacting me at jhunter@idevelopment.info.
 *
 * I have made every effort and taken great care in making sure that the source
 * code and other content included on my web site is technically accurate, but I
 * disclaim any and all responsibility for any loss, damage or destruction of
 * data or any other property which may arise from relying on it. I will in no
 * case be liable for any monetary damages arising from such loss, damage or
 * destruction.
 *
 * As with any code, ensure to test this code in a development environment
 * before attempting to run it in production.
 * =============================================================================
 */
 
import java.sql.*;
import java.io.*;
import java.util.*;

// Needed since we will be using Oracle's CLOB, part of Oracle's JDBC extended
// classes. Keep in mind that we could have included Java's JDBC interfaces
// java.sql.Clob which Oracle does implement. The oracle.sql.CLOB class
// provided by Oracle does offer better performance and functionality.
import oracle.sql.*;

// Needed for Oracle JDBC Extended Classes
import oracle.jdbc.*;


/**
 * -----------------------------------------------------------------------------
 * Used to test the functionality of how to load and unload text data from an
 * Oracle CLOB.
 *
 * This example uses an Oracle table with the following definition:
 *
 *      CREATE TABLE test_clob (
 *            id               NUMBER(15)
 *          , do*****ent_name    VARCHAR2(1000)
 *          , xml_do*****ent     CLOB
 *          , timestamp        DATE
 *      );
 * -----------------------------------------------------------------------------
 * @version 1.0
 * @author  Jeffrey M. Hunter  (jhunter@idevelopment.info)
 * @author  http://www.idevelopment.info
 * -----------------------------------------------------------------------------
 */
 
public class CLOBFileExample  {

    private String          inputTextFileName   = null;
    private File            inputTextFile       = null;

    private String          outputTextFileName1  = null;
    private File            outputTextFile1      = null;

    private String          outputTextFileName2  = null;
    private File            outputTextFile2      = null;
   
    private String          dbUser              = "SCOTT";
    private String          dbPassword          = "TIGER";
    private Connection      conn                = null;
   

    /**
     * Default constructor used to create this object. Responsible for setting
     * this object's creation date, as well as incrementing the number instances
     * of this object.
     * @param args Array of string arguments passed in from the command-line.
     * @throws java.io.IOException
     */
    public CLOBFileExample(String[] args) throws IOException {
       
        inputTextFileName  = args[0];
        inputTextFile = new File(inputTextFileName);
       
        if (!inputTextFile.exists()) {
            throw new IOException("File not found. " + inputTextFileName);
        }

        outputTextFileName1 = inputTextFileName + ".getChars.out";
        outputTextFileName2 = inputTextFileName + ".Streams.out";
       
    }


    /**
     * Obtain a connection to the Oracle database.
     * @throws java.sql.SQLException
     */
    public void openOracleConnection()
            throws    SQLException
                    , IllegalAccessException
                    , InstantiationException
                    , ClassNotFoundException {

        String driver_class  = "oracle.jdbc.driver.OracleDriver";
        String connectionURL = null;

        try {
            Class.forName (driver_class).newInstance();
            connectionURL = "jdbc:oracle:thin:@melody:1521:JEFFDB";
            conn = DriverManager.getConnection(connectionURL, dbUser, dbPassword);
            conn.setAutoCommit(false);
            System.out.println("Connected.\n");
        } catch (IllegalAccessException e) {
            System.out.println("Illegal Access Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        } catch (InstantiationException e) {
            System.out.println("Instantiation Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        } catch (ClassNotFoundException e) {
            System.out.println("Class Not Found Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        }
           
    }
   
   
    /**
     * Close Oracle database connection.
     * @throws java.sql.SQLException
     */
    public void closeOracleConnection() throws SQLException {
       
        try {
            conn.close();
            System.out.println("Disconnected.\n");
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Closing Connection).");
            e.printStackTrace();
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException e2) {
                    System.out.println("Caught SQL (Rollback Failed) Exception.");
                    e2.printStackTrace();
                }
            }
            throw e;
        }

    }
   
   
    /**
     * Method used to print program usage to the console.
     */
    static public void usage() {
        System.out.println("\nUsage: java CLOBFileExample \"Text File Name\"\n");
    }


    /**
     * Validate command-line arguments to this program.
     * @param args Array of string arguments passed in from the command-line.
     * @return Boolean - value of true if correct arguments, false otherwise.
     */
    static public boolean checkArguments(String[] args) {
       
        if (args.length == 1) {
            return true;
        } else {
            return false;
        }

    }


    /**
     * Override the Object toString method. Used to print a version of this
     * object to the console.
     * @return String - String to be returned by this object.
     */
    public String toString() {
   
        String retValue;

        retValue  = "Input File         : " + inputTextFileName    + "\n" +
                    "Output File (1)    : " + outputTextFileName1  + "\n" +
                    "Output File (2)    : " + outputTextFileName2  + "\n" +
                    "Database User      : " + dbUser;
        return retValue;
   
    }


    /**
     * Method used to write text data contained in a file to an Oracle CLOB
     * column. The method used to write the data to the CLOB uses the putChars()
     * method. This is one of two types of methods used to write text data to
     * a CLOB column. The other method uses Streams.
     *
     * @throws java.io.IOException
     * @throws java.sql.SQLException
     */
    public void writeCLOBPut()
            throws IOException, SQLException {
       
        FileInputStream     inputFileInputStream    = null;
        InputStreamReader   inputInputStreamReader  = null;
        BufferedReader      inputBufferedReader     = null;
        String              sqlText                 = null;
        Statement           stmt                    = null;
        ResultSet           rset                    = null;
        CLOB                xmlDo*****ent             = null;
        int                 chunkSize;
        char[]              textBuffer;
        long                position;
        int                 charsRead               = 0;
        int                 charsWritten            = 0;
        int                 totCharsRead            = 0;
        int                 totCharsWritten         = 0;
       
        try {

            stmt = conn.createStatement();
           
            inputTextFile = new File(inputTextFileName);
            inputFileInputStream = new FileInputStream(inputTextFile);
            inputInputStreamReader = new InputStreamReader(inputFileInputStream);
            inputBufferedReader = new BufferedReader(inputInputStreamReader);
       
            sqlText =
                "INSERT INTO test_clob (id, do*****ent_name, xml_do*****ent, timestamp) " +
                "   VALUES(1, '" + inputTextFile.getName() + "', EMPTY_CLOB(), SYSDATE)";
            stmt.executeUpdate(sqlText);
           
            sqlText =
                "SELECT xml_do*****ent " +
                "FROM   test_clob " +
                "WHERE  id = 1 " +
                "FOR UPDATE";
            rset = stmt.executeQuery(sqlText);
            rset.next();
            xmlDo*****ent = ((OracleResultSet) rset).getCLOB("xml_do*****ent");
           
            chunkSize = xmlDo*****ent.getChunkSize();
            textBuffer = new char[chunkSize];
           
            position = 1;
            while ((charsRead = inputBufferedReader.read(textBuffer)) != -1) {
                charsWritten = xmlDo*****ent.putChars(position, textBuffer, charsRead);
                position        += charsRead;
                totCharsRead    += charsRead;
                totCharsWritten += charsWritten;
            }
           
            inputBufferedReader.close();
            inputInputStreamReader.close();
            inputFileInputStream.close();

            conn.commit();
            rset.close();
            stmt.close();
           
            System.out.println(
                "==========================================================\n" +
                "  PUT METHOD\n" +
                "==========================================================\n" +
                "Wrote file " + inputTextFile.getName() + " to CLOB column.\n" +
                totCharsRead + " characters read.\n" +
                totCharsWritten + " characters written.\n"
            );

        } catch (IOException e) {
            System.out.println("Caught I/O Exception: (Write CLOB value - Put Method).");
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Write CLOB value - Put Method).");
            System.out.println("SQL:\n" + sqlText);
            e.printStackTrace();
            throw e;
        }

    }

   
    /**
     * Method used to write the contents (data) from an Oracle CLOB column to
     * an O/S file. This method uses one of two ways to get data from the CLOB
     * column - namely the getChars() method. The other way to read data from an
     * Oracle CLOB column is to use Streams.
     *
     * @throws java.io.IOException
     * @throws java.sql.SQLException
     */
    public void readCLOBToFileGet()
            throws IOException, SQLException {

        FileOutputStream    outputFileOutputStream      = null;
        OutputStreamWriter  outputOutputStreamWriter    = null;
        BufferedWriter      outputBufferedWriter        = null;
        String              sqlText                     = null;
        Statement           stmt                        = null;
        ResultSet           rset                        = null;
        CLOB                xmlDo*****ent                 = null;
        long                clobLength;
        long                position;
        int                 chunkSize;
        char[]              textBuffer;
        int                 charsRead                   = 0;
        int                 charsWritten                = 0;
        int                 totCharsRead                = 0;
        int                 totCharsWritten             = 0;

        try {

            stmt = conn.createStatement();

            outputTextFile1 = new File(outputTextFileName1);
            outputFileOutputStream = new FileOutputStream(outputTextFile1);
            outputOutputStreamWriter = new OutputStreamWriter(outputFileOutputStream);
            outputBufferedWriter = new BufferedWriter(outputOutputStreamWriter);

            sqlText =
                "SELECT xml_do*****ent " +
                "FROM   test_clob " +
                "WHERE  id = 1 " +
                "FOR UPDATE";
            rset = stmt.executeQuery(sqlText);
            rset.next();
            xmlDo*****ent = ((OracleResultSet) rset).getCLOB("xml_do*****ent");
           
            clobLength = xmlDo*****ent.length();
            chunkSize = xmlDo*****ent.getChunkSize();
            textBuffer = new char[chunkSize];
           
            for (position = 1; position <= clobLength; position += chunkSize) {
               
                // Loop through while reading a chunk of data from the CLOB
                // column using the getChars() method. This data will be stored
                // in a temporary buffer that will be written to disk.
                charsRead = xmlDo*****ent.getChars(position, chunkSize, textBuffer);

                // Now write the buffer to disk.
                outputBufferedWriter.write(textBuffer, 0, charsRead);
               
                totCharsRead += charsRead;
                totCharsWritten += charsRead;

            }

            outputBufferedWriter.close();
            outputOutputStreamWriter.close();
            outputFileOutputStream.close();
           
            conn.commit();
            rset.close();
            stmt.close();
           
            System.out.println(
                "==========================================================\n" +
                "  GET METHOD\n" +
                "==========================================================\n" +
                "Wrote CLOB column data to file " + outputTextFile1.getName() + ".\n" +
                totCharsRead + " characters read.\n" +
                totCharsWritten + " characters written.\n"
            );

        } catch (IOException e) {
            System.out.println("Caught I/O Exception: (Write CLOB value to file - Get Method).");
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Write CLOB value to file - Get Method).");
            System.out.println("SQL:\n" + sqlText);
            e.printStackTrace();
            throw e;
        }

    }
   
   
    /**
     * Method used to write text data contained in a file to an Oracle CLOB
     * column. The method used to write the data to the CLOB uses Streams.
     * This is one of two types of methods used to write text data to
     * a CLOB column. The other method uses the putChars() method.
     *
     * @throws java.io.IOException
     * @throws java.sql.SQLException
     */
    public void writeCLOBStream()
            throws IOException, SQLException {

        FileInputStream     inputFileInputStream    = null;
        OutputStream        clobOutputStream        = null;
        String              sqlText                 = null;
        Statement           stmt                    = null;
        ResultSet           rset                    = null;
        CLOB                xmlDo*****ent             = null;
        int                 bufferSize;
        byte[]              byteBuffer;
        int                 bytesRead               = 0;
        int                 bytesWritten            = 0;
        int                 totBytesRead            = 0;
        int                 totBytesWritten         = 0;

        try {

            stmt = conn.createStatement();

            inputTextFile = new File(inputTextFileName);
            inputFileInputStream = new FileInputStream(inputTextFile);
           
            sqlText =
                "INSERT INTO test_clob (id, do*****ent_name, xml_do*****ent, timestamp) " +
                "   VALUES(2, '" + inputTextFile.getName() + "', EMPTY_CLOB(), SYSDATE)";
            stmt.executeUpdate(sqlText);
           
            sqlText =
                "SELECT xml_do*****ent " +
                "FROM   test_clob " +
                "WHERE  id = 2 " +
                "FOR UPDATE";
            rset = stmt.executeQuery(sqlText);
            rset.next();
            xmlDo*****ent = ((OracleResultSet) rset).getCLOB("xml_do*****ent");
           
            bufferSize = xmlDo*****ent.getBufferSize();
           
            // Notice that we are using an array of bytes as opposed to an array
            // of characters. This is required since we will be streaming the
            // content (to either a CLOB or BLOB) as a stream of bytes using
            // using an OutputStream Object. This requires that a byte array to
            // be used to temporarily store the contents that will be sent to
            // the LOB. Note that they use of the byte array can be used even
            // when reading contents from an ASCII text file that will be sent
            // to a CLOB.
            byteBuffer = new byte[bufferSize];
           
            clobOutputStream = xmlDo*****ent.getAsciiOutputStream();
           
            while ((bytesRead = inputFileInputStream.read(byteBuffer)) != -1) {
           
                // After reading a buffer from the text file, write the contents
                // of the buffer to the output stream using the write()
                // method.
                clobOutputStream.write(byteBuffer, 0, bytesRead);
               
                totBytesRead += bytesRead;
                totBytesWritten += bytesRead;

            }

            // Keep in mind that we still have the stream open. Once the stream
            // gets open, you cannot perform any other database operations
            // until that stream has been closed. This even includes a COMMIT
            // statement. It is possible to loose data from the stream if this
            // rule is not followed. If you were to attempt to put the COMMIT in
            // place before closing the stream, Oracle will raise an
            // "ORA-22990: LOB locators cannot span transactions" error.

            inputFileInputStream.close();
            clobOutputStream.close();
           
            conn.commit();
            rset.close();
            stmt.close();

            System.out.println(
                "==========================================================\n" +
                "  OUTPUT STREAMS METHOD\n" +
                "==========================================================\n" +
                "Wrote file " + inputTextFile.getName() + " to CLOB column.\n" +
                totBytesRead + " bytes read.\n" +
                totBytesWritten + " bytes written.\n"
            );

        } catch (IOException e) {
            System.out.println("Caught I/O Exception: (Write CLOB value - Stream Method).");
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Write CLOB value - Stream Method).");
            System.out.println("SQL:\n" + sqlText);
            e.printStackTrace();
            throw e;
        }

    }
   
   
    /**
     * Method used to write the contents (data) from an Oracle CLOB column to
     * an O/S file. This method uses one of two ways to get data from the CLOB
     * column - namely using Streams. The other way to read data from an
     * Oracle CLOB column is to use getChars() method.
     *
     * @throws java.io.IOException
     * @throws java.sql.SQLException
     */
    public void readCLOBToFileStream()
            throws IOException, SQLException {

        FileOutputStream    outputFileOutputStream      = null;
        InputStream         clobInputStream             = null;
        String              sqlText                     = null;
        Statement           stmt                        = null;
        ResultSet           rset                        = null;
        CLOB                xmlDo*****ent                 = null;
        int                 chunkSize;
        byte[]              textBuffer;
        int                 bytesRead                   = 0;
        int                 bytesWritten                = 0;
        int                 totBytesRead                = 0;
        int                 totBytesWritten             = 0;

        try {

            stmt = conn.createStatement();

            outputTextFile2 = new File(outputTextFileName2);
            outputFileOutputStream = new FileOutputStream(outputTextFile2);

            sqlText =
                "SELECT xml_do*****ent " +
                "FROM   test_clob " +
                "WHERE  id = 2 " +
                "FOR UPDATE";
            rset = stmt.executeQuery(sqlText);
            rset.next();
            xmlDo*****ent = ((OracleResultSet) rset).getCLOB("xml_do*****ent");

            // Will use a Java InputStream object to read data from a CLOB (can
            // also be used for a BLOB) object. In this example, we will use an
            // InputStream to read ASCII characters from a CLOB.
            clobInputStream = xmlDo*****ent.getAsciiStream();
           
            chunkSize = xmlDo*****ent.getChunkSize();
            textBuffer = new byte[chunkSize];
           
            while ((bytesRead = clobInputStream.read(textBuffer)) != -1) {
               
                // Loop through while reading a chunk of data from the CLOB
                // column using an InputStream. This data will be stored
                // in a temporary buffer that will be written to disk.
                outputFileOutputStream.write(textBuffer, 0, bytesRead);
               
                totBytesRead += bytesRead;
                totBytesWritten += bytesRead;

            }

            outputFileOutputStream.close();
            clobInputStream.close();
           
            conn.commit();
            rset.close();
            stmt.close();
           
            System.out.println(
                "==========================================================\n" +
                "  INPUT STREAMS METHOD\n" +
                "==========================================================\n" +
                "Wrote CLOB column data to file " + outputTextFile2.getName() + ".\n" +
                totBytesRead + " characters read.\n" +
                totBytesWritten + " characters written.\n"
            );

        } catch (IOException e) {
            System.out.println("Caught I/O Exception: (Write CLOB value to file - Streams Method).");
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Write CLOB value to file - Streams Method).");
            System.out.println("SQL:\n" + sqlText);
            e.printStackTrace();
            throw e;
        }
       
    }
   
   
    /**
     * Sole entry point to the class and application.
     * @param args Array of string arguments passed in from the command-line.
     */
    public static void main(String[] args) {
   
        CLOBFileExample cLOBFileExample = null;
       
        if (checkArguments(args)) {

            try {
               
                cLOBFileExample = new CLOBFileExample(args);
               
                System.out.println("\n" + cLOBFileExample + "\n");
               
                cLOBFileExample.openOracleConnection();
               
                cLOBFileExample.writeCLOBPut();
                cLOBFileExample.readCLOBToFileGet();
               
                cLOBFileExample.writeCLOBStream();
                cLOBFileExample.readCLOBToFileStream();
               
                cLOBFileExample.closeOracleConnection();

            } catch (IllegalAccessException e) {
                System.out.println("Caught Illegal Accecss Exception. Exiting.");
                e.printStackTrace();
                System.exit(1);
            } catch (InstantiationException e) {
                System.out.println("Instantiation Exception. Exiting.");
                e.printStackTrace();
                System.exit(1);
            } catch (ClassNotFoundException e) {
                System.out.println("Class Not Found Exception. Exiting.");
                e.printStackTrace();
                System.exit(1);
            } catch (SQLException e) {
                System.out.println("Caught SQL Exception. Exiting.");
                e.printStackTrace();
                System.exit(1);
            } catch (IOException e) {
                System.out.println("Caught I/O Exception. Exiting.");
                e.printStackTrace();
                System.exit(1);
            }

        } else {
            System.out.println("\nERROR: Invalid arguments.");
            usage();
            System.exit(1);
        }
       
        System.exit(0);
    }

반응형
반응형

Multifile storage with Zip

The library that supports the Zip format is much more extensive. With it you can easily store multiple files, and there’s even a separate class to make the process of reading a Zip file easy. The library uses the standard Zip format so that it works seamlessly with all the tools currently downloadable on the Internet. The following example has the same form as the previous example, but it handles as many command-line arguments as you want. In addition, it shows the use of the Checksum classes to calculate and verify the checksum for the file. There are two Checksum types: Adler32 (which is faster) and CRC32 (which is slower but slightly more accurate).

//: c12:ZipCompress.java
// Uses Zip compression to compress any
// number of files given on the command line.
// {Args: ZipCompress.java}
// {Clean: test.zip}
import com.bruceeckel.simpletest.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;

public class ZipCompress {
  private static Test monitor = new Test();
  // Throw exceptions to console:
  public static void main(String[] args)
  throws IOException {
    FileOutputStream f = new FileOutputStream("test.zip");
    CheckedOutputStream csum =
      new CheckedOutputStream(f, new Adler32());
     ZipOutputStream zos = new ZipOutputStream(csum);
     BufferedOutputStream out =
      new BufferedOutputStream(zos);
    zos.setComment("A test of Java Zipping");
    // No corresponding getComment(), though.
    for(int i = 0; i < args.length; i++) {
      System.out.println("Writing file " + args[i]);
      BufferedReader in =
        new BufferedReader(new FileReader(args[i]));
      zos.putNextEntry(new ZipEntry(args[i]));
      int c;
      while((c = in.read()) != -1)
        out.write(c);
      in.close();
    }
    out.close();
    // Checksum valid only after the file has been closed!
    System.out.println("Checksum: " +
      csum.getChecksum().getValue());
    // Now extract the files:
    System.out.println("Reading file");
    FileInputStream fi = new FileInputStream("test.zip");
    CheckedInputStream csumi =
      new CheckedInputStream(fi, new Adler32());
    ZipInputStream in2 = new ZipInputStream(csumi);
    BufferedInputStream bis = new BufferedInputStream(in2);
    ZipEntry ze;
    while((ze = in2.getNextEntry()) != null) {
      System.out.println("Reading file " + ze);
      int x;
      while((x = bis.read()) != -1)
        System.out.write(x);
    }
    if(args.length == 1)
      monitor.expect(new String[] {
        "Writing file " + args[0],
        "%% Checksum: \\d+",
        "Reading file",
        "Reading file " + args[0]}, args[0]);
    System.out.println("Checksum: " +
      csumi.getChecksum().getValue());
    bis.close();
    // Alternative way to open and read zip files:
    ZipFile zf = new ZipFile("test.zip");
    Enumeration e = zf.entries();
    while(e.hasMoreElements()) {
      ZipEntry ze2 = (ZipEntry)e.nextElement();
      System.out.println("File: " + ze2);
      // ... and extract the data as before
    }
    if(args.length == 1)
      monitor.expect(new String[] {
        "%% Checksum: \\d+",
        "File: " + args[0]
      });
  }
} ///:~


For each file to add to the archive, you must call putNextEntry( ) and pass it a ZipEntry object. The ZipEntry object contains an extensive interface that allows you to get and set all the data available on that particular entry in your Zip file: name, compressed and uncompressed sizes, date, CRC checksum, extra field data, comment, compression method, and whether it’s a directory entry. However, even though the Zip format has a way to set a password, this is not supported in Java’s Zip library. And although CheckedInputStream and CheckedOutputStream support both Adler32 and CRC32 checksums, the ZipEntry class supports only an interface for CRC. This is a restriction of the underlying Zip format, but it might limit you from using the faster Adler32.

To extract files, ZipInputStream has a getNextEntry( ) method that returns the next ZipEntry if there is one. As a more succinct alternative, you can read the file using a ZipFile object, which has a method entries( ) to return an Enumeration to the ZipEntries.

In order to read the checksum, you must somehow have access to the associated Checksum object. Here, a reference to the CheckedOutputStream and CheckedInputStream objects is retained, but you could also just hold onto a reference to the Checksum object.

A baffling method in Zip streams is setComment( ). As shown in ZipCompress.java, you can set a comment when you’re writing a file, but there’s no way to recover the comment in the ZipInputStream. Comments appear to be supported fully on an entry-by-entry basis only via ZipEntry.

Of course, you are not limited to files when using the GZIP or Zip libraries—you can compress anything, including data to be sent through a network connection.

출처 : http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ314_033.htm

반응형

'Language > JAVA' 카테고리의 다른 글

Heap Dump 분석을 통한 Perm Area Memory Leak 원인 진단  (0) 2010.12.14
Java ARchives (JAR)  (0) 2010.11.17
자바 간단한 GZIP 압축 예제  (0) 2010.11.17
자바 파일 압축  (0) 2010.11.17
JAVA File Locking(자바 파일 잠금)  (0) 2010.11.17
반응형

Simple compression with GZIP

The GZIP interface is simple and thus is probably more appropriate when you have a single stream of data that you want to compress (rather than a container of dissimilar pieces of data). Here’s an example that compresses a single file:

//: c12:GZIPcompress.java
// {Args: GZIPcompress.java}
// {Clean: test.gz}
import com.bruceeckel.simpletest.*;
import java.io.*;
import java.util.zip.*;

public class GZIPcompress {
  private static Test monitor = new Test();
  // Throw exceptions to console:
  public static void main(String[] args)
  throws IOException {
    if(args.length == 0) {
      System.out.println(
        "Usage: \nGZIPcompress file\n" +
        "\tUses GZIP compression to compress " +
        "the file to test.gz");
      System.exit(1);
    }
    BufferedReader in = new BufferedReader(
      new FileReader(args[0]));
    BufferedOutputStream out = new BufferedOutputStream(
      new GZIPOutputStream(
        new FileOutputStream("test.gz")));
    System.out.println("Writing file");
    int c;
    while((c = in.read()) != -1)
      out.write(c);
    in.close();
    out.close();
    System.out.println("Reading file");
    BufferedReader in2 = new BufferedReader(
      new InputStreamReader(new GZIPInputStream(
        new FileInputStream("test.gz"))));
    String s;
    while((s = in2.readLine()) != null)
      System.out.println(s);
    monitor.expect(new String[] {
      "Writing file",
      "Reading file"
    }, args[0]);
  }
} ///:~


The use of the compression classes is straightforward; you simply wrap your output stream in a GZIPOutputStream or ZipOutputStream, and your input stream in a GZIPInputStream or ZipInputStream. All else is ordinary I/O reading and writing. This is an example of mixing the char-oriented streams with the byte-oriented streams; in uses the Reader classes, whereas GZIPOutputStream’s constructor can accept only an OutputStream object, not a Writer object. When the file is opened, the GZIPInputStream is converted to a Reader.

출처 : http://www.linuxtopia.org/

반응형
반응형

Compression

The Java I/O library contains classes to support reading and writing streams in a compressed format. These are wrapped around existing I/O classes to provide compression functionality.

These classes are not derived from the Reader and Writer classes, but instead are part of the InputStream and OutputStream hierarchies. This is because the compression library works with bytes, not characters. However, you might sometimes be forced to mix the two types of streams. (Remember that you can use InputStreamReader and OutputStreamWriter to provide easy conversion between one type and another.)

 

Compression class

Function

CheckedInputStream

GetCheckSum( ) produces checksum for any InputStream (not just decompression).

CheckedOutputStream

GetCheckSum( ) produces checksum for any OutputStream (not just compression).

DeflaterOutputStream

Base class for compression classes.

ZipOutputStream

A DeflaterOutputStream that compresses data into the Zip file format.

GZIPOutputStream

A DeflaterOutputStream that compresses data into the GZIP file format.

InflaterInputStream

Base class for decompression classes.

ZipInputStream

An InflaterInputStream that decompresses data that has been stored in the Zip file format.

GZIPInputStream

An InflaterInputStream that decompresses data that has been stored in the GZIP file format.


Although there are many compression algorithms, Zip and GZIP are possibly the most commonly used. Thus you can easily manipulate your compressed data with the many tools available for reading and writing these formats.

출처 : http://www.linuxtopia.org/

반응형

+ Recent posts