달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

출처 : http://active.tutsplus.com/tutorials/flex/using-as3xls-with-the-flex-framework-excel-import/






This tutorial will cover implementation of the AS3XLS ActionScript 3.0 library for the Flex framework. We will demonstrate loading an Excel .xls file into Flash and parsing the data into a Flex datagrid. 

 
:
Posted by 라면스프
출처 : http://www.ibm.com/developerworks/kr/library/os-javapdf/index.html


자바 애플리케이션에서 동적으로 PDF 파일 생성하기


많은 애플리케이션들이 PDF 문서의 동적 생성을 요구하고 있다. 이 같은 애플리케이션은 이메일 전달용 고객 일람표를 생성하는 은행부터, 책의 특정 챕터를 구매하여 이를 PDF 포맷으로 받는 리더기 까지 다양하다. 그 리스트는 끝이 없다. 이 글에서 iText 자바 라이브러리를 사용하여 PDF 문서를 만들 것이다. 여러분의 이해를 돕기 위해 샘플 애플리케이션도 제공한다.

iText와 친해지기

iText는 Lowagie.com(참고자료)에서 무료로 사용할 수 있는 자바 라이브러리이다. iText 라이브러리는 강력하고, HTML, RTF, XML 문서의 생성 뿐만 아니라 PDF 생성을 지원한다. 문서에 사용될 다양한 폰트를 선택할 수 있다. 또한 iText 구조에서는 같은 코드를 사용하여 앞서 언급한 유형의 문서를 만들 수 있다.

iText 라이브러리에는 다양한 폰트로 PDF 텍스트를 만들고, PDF 문서에 테이블을 생성하고, 워터마크를 페이지에 추가하는 클래스가 포함되어 있다. iText로 사용할 수 있는 더 많은 기능들이 있다. 하지만 그 모든 것을 이 글에서 다 설명하기는 불가능하다. PDF 생성에 필요한 기본적인 것만을 설명하겠다.

샘플 애플리케이션 개발에 Eclipse를 사용할 것이다. 오픈 소스 IDE인 Eclipse는 무료로 사용할 수 있고 매우 강력하다. 지금 Eclipse를 다운로드 하라. (참고자료)

iText API

com.lowagie.text.Document는 PDF 문서 생성을 위한 주 클래스이다. 인스턴스로 만들어질 첫 번째 클래스이다. 문서가 생성되면 라이터는 여기에 작성해야 한다. com.lowagie.text.pdf.PdfWriter는 PDF 라이터이다. 다음은 일반적으로 사용되는 클래스들이다.

  • com.lowagie.text.Paragraph -- 들여쓰기 단락을 나타내는 클래스이다.
  • com.lowagie.text.Chapter -- PDF 문서의 챕터이다. 타이틀로 Paragraph를 사용하고, 챕터 번호로 int를 사용한다.
  • com.lowagie.text.Font -- 폰트, 크기, 스타일, 컬러 같은 모든 폰트 스팩들이 포함되어 있다. 다양한 폰트들은 이 클래스에 정적 상수로서 선언된다.
  • com.lowagie.text.List -- 많은 ListItems를 포함하고 있는 리스트이다.
  • com.lowagie.text.Table -- 매트릭스에서 정렬된 셀들을 포함하고 있는 테이블이다.

Eclipse에서 iText 다운로드 및 설정하기

순수 자바 라이브러리인 아아텍스트는 JAR 파일의 형태로 되어 있다. (참고자료.) 라이브러리를 다운로드 하면(C:\temp) Eclipse 환경에서 iText 라이브러리를 설정한다.

  1. Eclipse에서 iText라는 이름의 새로운 자바 프로젝트를 만든다.
  2. Package Explorer 뷰에서 iText 프로젝트를 오른쪽 클릭하고 Properties를 선택한다.
  3. Java Build Path를 클릭한다. Libraries 탭에서, Add External JARs를 클릭한다.
  4. C:\temp 디렉토리를 검색하여 itext-1.3.jar를 선택한다.
  5. OK를 클릭한다.

iText가 설정되면 Eclipse는 동적인 PDF 문서를 생성하는 자바 애플리케이션을 구현할 준비를 갖춘 것이다.

샘플 애플리케이션

직접 샘플을 만드는 것 만큼 확실한 설명 방법은 없다. 필요한 툴(Eclipse IDE)과 라이브러리(iText 라이브러리)가 준비되었으니 샘플 프로그램을 디자인 및 개발해 보자.

평이한 텍스트, 특별 폰트로 색상을 입힌 텍스트, 테이블, 리스트, 챕터, 섹션 같은 기본적인 엘리먼트를 포함하고 있는 PDF 문서를 만들어 보자. 이 애플리케이션의 목적은 여러분이 iText 라이브러리를 사용하는 방법을 보다 잘 이해할 수 있도록 돕는 것이다. PDF 문서 생성과 관련되어 많은 일을 수행하는 많은 클래스들이 있다. 이 모든 클래스들을 다 다루기는 불가능하다. iText의 javadoc은 이러한 클래스들의 사용법을 잘 이해할 수 있는 좋은 자료이다. 코딩부터 시작해 보자.

첫 번째 단계는 문서를 만드는 것이다. 이 문서는 PDF 문서의 모든 엘리먼트용 컨테이너이다.


Listing 1. 문서 객체의 인스턴스화
				
Document document = new Document(PageSize.A4, 50, 50, 50, 50);

첫 번째 인자는 페이지 크기이다. 다음 인자들은 각각 왼쪽, 오른쪽, 상단, 하단 여백들이다. 이러한 유형의 문서는 아직 정의되지 않았다. 여러분이 만드는 라이터의 유형에 의존한다. 이 샘플에서 우리는 com.lowagie.text.pdf.PdfWriter를 선택했다. 기타 라이터로는 HtmlWriter, RtfWriter, XmlWriter 등이 있다. 이름만으로도 충분히 그 용도를 알 수 있다.


Listing 2. PdfWriter 객체의 생성
				
PdfWriter writer = PdfWriter.getInstance(document, \
new FileOutputStream("C:\\ITextTest.pdf"));
document.open();

첫 번째 인자는 문서 객체에 대한 참조이고, 두 번째 인자는 아웃풋이 작성될 파일의 고유 이름이다. 작성을 위해 문서를 연다.

이제, 문서의 첫 번째 페이지에 몇 가지 텍스트를 추가할 것이다. com.lowagie.text.Paragraph을 사용하여 어떤 텍스트라도 추가된다. 텍스트로 기본 단락을 만들고 폰트, 컬러, 크기 등 기본적인 설정을 할 수 있다. 각자의 고유 폰트를 사용해도 된다. 두 가지 옵션 모두를 살펴보자.


Listing 3. 단락 객체의 생성
				
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("Some more text on the \
first page with different color and font type.", 
FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new Color(255, 150, 200))));

아래 그림은 위 코드의 아웃풋이다. 위 코드 말미에 document.close();을 추가하여 문서를 마감한다.


그림 1. 아웃풋
Sample output of above code 

평이한 텍스트를 PDF 문서에 추가하는 방법을 배웠다. 복잡한 요소들도 문서에 추가해야 한다. 새로운 챕터를 만든다. 이 챕터는 특별 섹션으로서 새로운 페이지로 시작하고 기본적으로 디스플레이 된 숫자가 있다.


Listing 4. 챕터 객체의 생성 
				
Paragraph title1 = new Paragraph("Chapter 1", 
           FontFactory.getFont(FontFactory.HELVETICA, \
           18, Font.BOLDITALIC, new Color(0, 0, 255)));
Chapter chapter1 = new Chapter(title1, 1);
chapter1.setNumberDepth(0);

위 코드에서 chapter1 이라는 새로운 챕터 객체를 만들었다. 제목은 "This is Chapter 1."이다. 숫자 한계를 0으로 설정하면 페이지에 챕터 번호가 디스플레이 되지 않는다.

섹션은 챕터의 하위 요소이다. 다음 코드에서, "This is Section 1 in Chapter 1." 이라는 제목의 섹션을 만들었다. 이 섹션에 텍스트를 추가하기 위해 또 다른 단락 객체인 someSectionText를 만들고 이를 섹션 객체에 추가한다.


Listing 5. 섹션 객체의 생성 
				
Paragraph title11 = new Paragraph("This is Section 1 in Chapter 1", 
           FontFactory.getFont(FontFactory.HELVETICA, 16, \
           Font.BOLD, new Color(255, 0, 0)));
Section section1 = chapter1.addSection(title11);
Paragraph someSectionText = new Paragraph("This \
text comes as part of section 1 of chapter 1.");
section1.add(someSectionText);
someSectionText = new Paragraph("Following is a 3 X 2 table.");
section1.add(someSectionText);

테이블을 추가하기 전에 문서가 어떤 모습인지를 보자. 다음 두 줄을 추가하여 문서를 종료하고 프로그램을 컴파일 및 실행하여 PDF 문서를 만든다. document.add(chapter1);document.close();.


그림 2. 아웃풋
Sample output of chapter 

이제 테이블 객체를 만들어 보자. 테이블에는 열과 칼럼의 매트릭스가 포함된다. 한 열의 셀은 한 개 이상의 칼럼으로 확장될 수 있다. 마찬가지로, 한 칼럼에 있는 셀은 한 개 이상의 열로 확장될 수 있다. 따라서, 3 x 2 테이블은 정확히 6 개의 셀만 가질 필요가 없다.


Listing 6. 테이블 객체의 생성
				
Table t = new Table(3,2);
t.setBorderColor(new Color(220, 255, 100));
t.setPadding(5);
t.setSpacing(5);
t.setBorderWidth(1);
Cell c1 = new Cell("header1");
c1.setHeader(true);
t.addCell(c1);
c1 = new Cell("Header2");
t.addCell(c1);
c1 = new Cell("Header3");
t.addCell(c1);
t.endHeaders();
t.addCell("1.1");
t.addCell("1.2");
t.addCell("1.3");
section1.add(t);

위 코드에서, t라는 테이블 객체를 만들었다. 세 개의 칼럼과 두 개의 열을 갖고 있다. 테이블의 보더 색상을 설정했다. 패딩(padding)은 셀의 텍스트와 셀의 경계간 공간을 만드는데 사용된다. 스페이싱(spacing)은 인접하는 셀의 경계들간 공간이다. 그런 다음, 세 개의 셀 객체를 만든다. 각각 다른 텍스트를 갖고 있다. 이들을 계속해서 테이블에 추가한다. 첫 번째 칼럼에서 시작하여 같은 열의 다음 칼럼으로 이동한다. 열이 완성되면 다음 셀이 다음 열의 첫 번째 칼럼에 추가된다. 셀은 t.addCell("1.1"); 같은 셀의 텍스트를 제공하여 테이블에 추가될 수 있다. 마지막으로 테이블 객체가 섹션 객체에 추가된다.

마지막으로 PDF 문서에 리스트를 추가해 보자. 리스트에는 많은 ListItem들이 추가된다. 리스트에는 번호가 붙을 수도 있고 붙지 않을 수도 있다. 첫 번째 인자를 TRUE로 전달하면 번호가 붙은 리스트를 만들어야 한다.


Listing 7. 리스트 객체의 생성
				
List l = new List(true, false, 10);
l.add(new ListItem("First item of list"));
l.add(new ListItem("Second item of list"));
section1.add(l);

지금까지 chapter1 객체에 모든 것을 추가했다. chapter1에 추가될 더 이상의 객체가 없기 때문에, chapter1을 주 document에 추가해야 한다. 샘플 애플리케이션을 통해 한 개의 문서를 완성했다.


Listing 8. 주 document에 챕터 추가하기 
				
document.add(chapter1);
document.close();

샘플 애플리케이션 실행하기

  1. 샘플 애플리케이션, j-itextsample.jar(Download)을 다운로드 한다.
  2. 디렉토리에 j-itextsample.jar의 압축을 푼다. C:\temp에 추출하면, 소스와 클래스 파일은 C:\temp\com\itext\test에 배치된다.
  3. 명령어 프롬프트를 열고 디렉토리를 C:\temp로 변경한다.
  4. 명령어 프롬프트에 시스템의 classpath를 설정한다. 시스템의 classpath에 C:\temp\itext-1.3.jar를 포함시킨다. Windows®에서는, set classpath=C:\temp\itext-1.3.jar;%classpath%명령어를 실행한다.
  5. java com.itext.test.ITextTest 명령어로 애플리케이션을 실행한다.

이 프로그램은 C:\에 ITextTest.pdf 문서를 생성할 것이다. 아래 그림은 이 PDF 문서의 두 번째 페이지 모습이다.


그림 3. PDF 문서 모습
Screenshot of PDF document 

결론

지금까지 PDF 생성을 위한 기본 요소들을 살펴 보았다. iText의 장점은 같은 엘리먼트의 신택스가 다른 유형의 라이터에도 사용될 수 있다는 점이다. 또한, 이 라이터의 결과는 콘솔( XML과 HTML 라이터), 서블릿의 아웃풋 스트림 (PDF 문서의 웹 요청에 대한 응답), 또는 다른 유형의 OutputStream 으로 리다이렉션 된다. 또한 iText는 응답은 갖지만 PDF, RTF, HTML, XML 등 다양한 응답 유형을 보이는 상황에서 편리하게 사용할 수 있다. iText에서는 워터마크를 만들 수 있고 문서를 암호화 할 수 있으며 아웃풋도 정확하다.

:
Posted by 라면스프
출처 : http://www.ibm.com/developerworks/kr/library/j-5things11/index.html


JVM의 명령행 플래그에 대해 모르고 있던 5가지 사항


 

JVM 성능 및 Java 런타임 정밀 조정하기
 

JVM은 Java 애플리케이션의 기능과 성능을 뒷받침하는 일꾼이지만 대부분의 Java 개발자는 이를 당연한 것으로 여기고 중요하게 생각하지 않는다. 그리고 오브젝트 할당 및 가비지 콜렉션, 스레드 실행, 파일 열기 및 닫기, Java 바이트코드 해석 및/또는 JIT 컴파일 등의 작업이 JVM에서 처리되는 방법을 제대로 이해하고 있는 개발자는 거의 없다.



애플리케이션 성능에 영향을 주는 JVM 기능에 익숙하지 않을 때뿐만 아니라 JVM에서 오류가 발생한 경우에도 문제점을 해결하기가 매우 어려울 수 있다.

5가지 사항 시리즈의 이 기사에서는 Java 가상 머신의 성능을 진단 및 조정하는 데 사용할 수 있는 여러 가지 명령행 Java 플래그를 소개한다.

1. DisableExplicitGC

필자는 애플리케이션 성능 문제점에 대한 상담 의뢰를 받고 코드 전체에 대해 빠른 grep을 수행하여 원래 Java 성능 안티 패턴인 Listing 1과 같은 내용을 발견한 경험이 얼마나 많은지 모른다.


Listing 1. System.gc();
// We just released a bunch of objects, so tell the stupid
// garbage collector to collect them already!
System.gc();

명시적 가비지 콜렉션은 정말로 나쁜 아이디어이다. 이는 마치 공중전화 부스 속에 자기 자신을 광견병에 걸린 개와 함께 가둬놓는 것과 비슷하다. 구현에 따라 호출의 정확한 의미가 달라지기는 하지만 JVM이 제너레이셔널(generational) 가비지 콜렉터(대부분의 가비지 콜렉터가 제너레이셔널 가비지 콜렉터임)를 실행하고 있을 경우 System.gc();를 실행하면 전체 삭제가 필요하지 않더라도 VM이 힙을 "전체 삭제"하게 된다. 일반적으로 전체 삭제에는 일반적인 GC 조작보다 몇 배나 더 높은 비용이 소요된다. 이는 분명 어리석은 방법이다.

하지만 이 말을 그대로 받아들이면 안 된다. 왜냐하면 Sun의 엔지니어가 이 특별한 인적 오류 문제점을 해결하기 위한 JVM 플래그를 제공했기 때문이다. -XX:+DisableExplicitGC 플래그는 자동으로 System.gc() 호출을 무작동으로 전환한다. 따라서 코드를 실행한 후System.gc()가 JVM의 전체 실행에 도움이 되는지 아니면 해가 되는지 여부를 직접 확인할 수 있다.



2. HeapDumpOnOutOfMemoryError

근래에 OutOfMemoryError가 발생하면서 JVM이 종료될 뿐만 아니라 디버거를 사용하여 오류를 찾고 문제점을 확인할 수도 없는 상황을 경험한 적이 있는가? 원인을 알 수 있는 이와 같은 문제점이 발생하면 개발자가 화가 나서 정신을 차리기 어려울 것이다.

사용자 책임

Sun/Oracle의 VM 이외의 다른 VM에서는 일부 명령행 플래그가 지원되지 않을 수도 있다. 플래그의 지원 여부를 가장 효과적으로 확인하는 방법은 무엇보다도 직접 사용해 보고 작동하는지 확인하는 것이다. 하지만 이러한 플래그가 기술적으로 지원되지 않더라도 플래그 사용에 대한 책임은 전적으로 사용자 자신에게 있다. 필자뿐만 아니라 Sun/Oracle 또는 IBM®마저도 이러한 플래그로 인해 코드, 데이터 또는 서버가 크게 손상되더라도 그 어떠한 책임을 지지 않는다. 따라서 미리 주의를 주지만 가상(비프로덕션) 환경에서 먼저 사용해 보기를 권장한다.

JVM이 종료되려는 순간에 힙의 스냅샷을 작성하고 싶은 경우가 있다. 바로 이 기능을 -XX:+HeapDumpOnOutOfMemoryError 명령이 수행한다.

이 명령을 실행하면 JVM이 "힙 덤프 스냅샷"을 작성한 후 처리를 위해 파일에 저장한다. 일반적으로 이 작업에는 jhat 유틸리티(필자의 이전 기사 참조)가 사용된다. 해당 -XX:HeapDumpPath 플래그를 사용하여 파일을 저장할 실제 경로를 지정할 수 있다. (파일이 어느 위치에 저장되던지 상관 없이 파일 시스템 및/또는 Java 프로세스에 해당 위치에 작성할 수 있는 권한이 있는지 확인한다.)




3. bootclasspath

설치된 JRE에 포함되어 있는 경로 또는 JRE를 조금 확장한 경로와는 약간 다른 클래스 경로에 클래스를 주기적으로 저장해 두는 것이 좋다. (새 Java Crypto API 제공자가 예가 될 수 있을 것이다.) JRE를 확장하려고 하면 사용자 정의 구현을 부트스트랩 ClassLoader에서 사용할 수 있어야 하며, 이 클래스 로더는 java.lang.Object 및 rt.jar의 모든 항목을 로드한다.

크랙을 사용하여 rt.jar을 열고 사용자 정의 구현 또는 새 패키지를 넣을 수도 있겠지만 이는 JDK를 다운로드할 때 동의했던 라이센스를 기술적으로 위반하는 것이다.

대신 JVM 자체의 -Xbootclasspath 옵션을 -Xbootclasspath/p 및 -Xbootclasspath/a와 함께 사용한다.

-Xbootclasspath를 사용하면 전체 부트 클래스 경로를 설정할 수 있으며, 이 클래스 경로는 일반적으로 rt.jar에 대한 참조를 포함해야 하며 rt.jar에 포함되지 않은 JDK의 다른 JAR 파일 세트도 포함해야 한다. -Xbootclasspath/p는 값을 기존 부트 클래스 경로 앞에 추가하고, -Xbootclasspath/a는 값을 뒤에 추가한다.

예를 들어, 설치된 java.lang.Integer를 수정한 후 수정 사항을 서브디렉토리 mods에 저장한 경우 -Xbootclasspath/a mods 매개변수는 새 Integer를 기본값 앞에 놓는다.



4. verbose

-verbose는 거의 모든 유형의 Java 애플리케이션에 사용할 수 있는 유용한 1차 진단 유틸리티이다. 이 플래그에는 gcclass 및 jni라는 세 개의 서브플래그가 있다.

gc는 작동 중인 JVM 가비지 콜렉터로 인해 성능이 저하되었는지 확인할 때 가장 먼저 사용되는 도구이다. 아쉽게도 gc의 출력에 대한 해석은 한 권의 책으로 다루어질 정도로 까다롭다. 게다가 명령행에 인쇄되는 출력이 Java 릴리스 또는 JVM별로 다를 수 있기 때문에 올바르게 해석하기가 더욱 어렵다.

일반적으로 말해서, 가비지 콜렉터가 제너레이셔널 콜렉터(대부분의 "엔터프라이즈급" VM)이면 전체 삭제 GC 패스를 나타내는 일종의 시각적 플래그가 표시된다. Sun JVM의 경우에는 플래그가 GC 출력 행의 맨 앞에 "[Full GC ...]"로 표시된다.

class는 ClassLoader 및/또는 일치하지 않는 클래스 충돌을 진단하는 데 도움이 되는 도구이다. 이 플래그는 클래스의 로드 시간뿐만 아니라 JAR 파일에 대한 경로를 포함한 클래스의 원본 위치까지도 보고한다(JAR에서 로드된 것으로 가정).

jni는 JNI 및 네이티브 라이브러리 작업 외에는 거의 사용되지 않는다. 이 플래그를 사용하면 네이티브 라이브러리가 로드되었거나 메소드가 바인드되었다는 등의 다양한 JNI 이벤트가 보고된다. 다시 한번 말하지만 JVM의 릴리스별로 출력이 달라질 수 있다.



5. 명령행 -X

지금까지 JVM에서 제공하는 명령행 옵션 중에서 필자가 좋아하는 몇 가지 옵션을 살펴보았다. 하지만 직접 찾아볼 수 있는 더 많은 옵션이 있다. 명령행 인수 -X는 JVM에서 제공하는 모든 비표준(하지만 대부분 안전한) 인수를 나열한다. 예를 들어, 다음과 같다.

  • -Xint는 JVM을 해석된 모드로 실행한다. (이 인수는 JIT 컴파일러가 코드에 실제로 영향을 주는지 테스트하거나 JIT 컴파일러에 버그가 있는지 확인할 때 유용하다.)
  • -Xloggc:는 -verbose:gc와 동일한 기능을 제공하지만 명령행 창에 표시하는 대신 파일에 로깅한다.

JVM 명령행 옵션은 때때로 변경되므로 주기적으로 확인하는 것이 좋다. 모니터를 보고 있던 늦은 밤 중이나, 가족과 함께 저녁 만찬을 하기 위해 오후 5시에 퇴근하는 중이나 아니면 Mass Effect 2에서 적을 무찌르는 동안에 변경될 수도 있다.



결론

명령행 플래그는 프로덕션 환경에서 지속적으로 사용하기 위한 것이 아니다. JVM 가비지 콜렉터를 조정하기 위해 사용하는 플래그를 제외하고, 비표준 명령행 플래그는 실제로 프로덕션용이 아니다. 하지만 제대로 알기 힘든 가상 머신의 내부 작업을 살펴볼 수 있는 도구라는 점에서 이러한 태그는 매우 유용하다.

5가지 사항 시리즈의 다음 주제는 일상적인 Java 도구이다. 

:
Posted by 라면스프
2012. 3. 9. 15:26

[TOMCAT] Tomcat Performance Tuning Enjoy/etc2012. 3. 9. 15:26

출처 : http://www.solutionhacker.com/tomcat-performance-tuning/


Most companies I have worked for use Tomcat as Servlet Container. It is de facto standard just like how Apache been used as Web Server. However, most of us just drag our war file to the webapp folder and use Tomcat with all the settings as default out of the box. It works fine in development environment but may not in production. This article will give you advice in several areas:

  1. Production Tomcat Architecture
  2. Tuning tomcat for performance
  3. Resolving problems which affect availability

 Production Tomcat Architecture

In production Tomcat relies on a number of resources which can impact its overall performance. Understanding the overall system architecture is key to tuning performance and troubleshooting problems.

  1. Hardware: CPU(s), memory, network IO and file IO
  2. OS: SMP (symmetric multiprocessing) and thread support
  3. JVM: version, tuning memory usage, and tuning GC
  4. Tomcat: version (example, Tomcat 6 supports NIO)
  5. Application: Application design can have the largest impact on overall performance
  6. Database: concurrent db connection is allowed (pooling and object caching)
  7. Web Server: Apache can sit in front of Tomcat and serves the static content. It also can do load balancing across multiple Tomcat instances.
  8. Network: Network delays.
  9. Remote Client: How fast is the communication protocol? Content can be compressed. 

Performance Tuning

How to measure and test performance

  • Request latency is key b/c it reflects the responsiveness of your site for visitors.
  • Test environment should match production as closely as possible.
  • The data volume is important to simulate in database side.
  • Test HTTP requests with different request parameters (test corner cases)
  • Use load test to simulate the traffics (ex. JMeter)
  • Final tests should be over longer periods like days because JVM performance changes over time and can actually improve if using HotSpot. Memory leaks, db temporary unavailable, etc can only be found when running longer tests.

JVM version, memory usage and GC

  • Sun Java 1.3 and later releases inlcude HotSpot profiling optimizer customized for long running server application.
  • Tomcat will freeze processing of all requests while the JVM is performingGC. On a poorly tuned JVM this can last 10′s of seconds. Most GC’s should take < 1 second and never exceed 10 seconds
  • Tune the -Xms (min) and -Xmx (max) java stack memory (set them to the same value can improve GC performance)
  • Make sure the java process always keeps the memory it uses resident in physical memory and not swapped out to virtual memory.
  • Use -Xincgc to enable incremental garbage collection
  • Try reducing -Xss thread stack memory usage

Tomcat version and configuration

  • Tomcat 6 supports NIO.
  • Set “reloadable” false – remove unnecessary detection overhead
  • Set “liveDeploy” to false – liveDeploy controls whether your webapps directory is periodically checked for new war files. This is done using background thread.
  • Set “debug” to 0
  • Set “swallowOutput” to true – This makes sure all output to stdout or stderr for a web application gets directed to the web application log rather than the console or catalina.out. This make it easier to troubleshoot problems.
  • Connector configuration – minProcessor, maxProcessor, acceptCount, enableLookups. Don’t set the acceptCount too high b/c this sets the number of pending requests awaiting processing. It is better deny few requests than overload Tomcat and cause problems for all requests. Set “enableLookups” to false b/c DNS lookups can add significant delays.

Database connection pool

  • We use connection pool provided by Spring instead
  • Using middleware to persist and cache objects from your database can significantly improve performance b/c of fewer db calls, less thrashing of the JVM for creation and subsequent GC of object craeted for resultset.

Application design and profiling

  • If the data used to generate a dynamic page rarely changes, modify it to a static page which you regenerate periodically.
  • Cache dynamic page
  • Use tool like JProble to profle your web applications during development phase
  • Look for possible thread synchronization bottlenecks
  • Date and Time thread synchronization bottleneck 

Troubleshooting

Collecting and analyzing log data

Common problems

  • Broken pipe – For HTTP Connector indicates that the remote client aborted the request. For web server JK Connector indicates that the web server process or thread was terminated. These are normal and rarely due to a problem with Tomcat. However, if you have long request, the connectionTimeout may close the connection before you send your response back.
  • Tomcat freezes or pauses with no request being processed – usually due to a long pause of JVM GC. A long pause can cause a cascading effect and high load once Tomcat starts handling requests again. Don’t set the “acceptCount” too high and use java -verbose:gc startup argument to collect GC data.
  • Out of Memory Exception – look into application code to fix the leak (profile tool can help). Increase available memory on the system via -Xmx. Restart tomcat!
  • Database connection failure – connection used up when traffic is spike.
  • Random connection close exception - when you close your connection twice. First close(), the connection returns to the pool. It may be picked up by another thread. Now, second close() may close a connection that is being used by other thread. Don’t close connection twice, use JDBC Template from Spring to avoid this problem. 

Reference

  1. JavaWorld GC Article
  2. Sun HotSpot Performance Document
  3. Tomcat Performance Slides

  

:
Posted by 라면스프
출처 : http://www.java-tips.org/java-tutorials/tutorials/introduction-to-java-servlets-with-eclipse.html


Introduction

Java Servlet is the one of the most important Java technologies. It is the simplest model to build a complete Java J2EE Web Application. Furthermore, even for complex J2EE Web Application that uses Struts, Spring, EJB and etc, they are still using Servlet for certain purposes such as Servlet Filter, Listener and etc. Thus, it is just a good idea for you to have well-built understanding of Java Servlet. Prior reading this tutorial, it would be excellent if you have mastered the basic Java programming languages.

At the completion of the tutorial, you are expected to comprehend the concept of the Java Servlet, be familiar with the ways to create Java Servlet using Eclipse 3.1.2, differences between POST and GET and should be ready to go to the next level.

In this tutorial, we are going to create one dynamic web application that asks the user for first name and surname. Then the system should response by greeting the users.

The tutorial consists of four main steps.

  1. Introduction to Eclipse 3.1.2
  2. Creating New Web Application Project in Eclipse 3.1.2 with Web Tools Platform (WTP) Plug-in.
  3. Creating Server Definition in Eclipse 3.1.2
  4. Implementation of Tutorial’s Example
  5. How to Start Tomcat Manually
  6. How to Shutdown Tomcat Manually
  7. Conclusion



Introduction to Eclipse 3.1.2

Nowadays, many J2EE developers are using Eclipse as their IDE for Java programming language. One of the reasons is that Eclipse is free and is easily extendable. Yes, that is correct, there are plentiful plugins available in Internet for Eclipse. Additionally, the famous IBM WebSphere Application Developer for developing J2EE application in WebSphere is also implemented above the Eclipse framework.

Besides Java programming, Eclipse can also be used to edit any file such as C++, C or PHP and etc. You need to remember that Eclipse does not have any server embedded in it. Eclipse is just an editor. Well, let’s start to explore on how Eclipse can assist you in creating a Java Servlet.

Creating New Web Application Project in Eclipse 3.1.2 with Web Tools Platform (WTP) Plug-in

Okay, for our tutorial, we are going to exercise Web Tools Platform (WTP) plugin. I would suggest you to download Web Tools Platform (WTP) together with Eclipse so you should not be bothered on how to install the plugin into Eclipse and etc. Ideally, if you download Eclipse without any plugin, it does not have any support for J2EE Development. That is the core reason why various vendors are implementing J2EE plugins for Eclipse. Web Tools Platform is not the only J2EE plugin available for Eclipse. There are numerous J2EE plugins available in Internet such as Lomboz from ObjectLearn, MyEclipse and etc. If you are interested to know deeper on Eclipse plugin, you can visithttp://www.eclipseplugincentral.com/ for the complete list of available plugins for Eclipse.

To download Web Tools Platform (WTP), you can go to http://www.eclipse.org/webtools/ and you can download it together with Eclipse by choosing the download link on the left panel of that particular site. Web Tools Platform (WTP) plugin with Eclipse is approximately 182 MB. It will be in zip file and you will not have installation for it. You can extract it to C:\ and you can directly use Eclipse by double clicking the Eclipse.exe file in the extracted folder.

Unlike NetBeans, Eclipse does not have any server embedded in it thus, in order to create a Java Servlet in Eclipse; you need to install the server (for our tutorial, you need Apache Tomcat) as well as the Java Development Kit (JDK) from Sun.

Before going further to our tutorial, it would be good if you understand the concept of Java Servlet as explained in the next paragraphs.

Creating a Java Servlet means that you are required to deal with JSP (JavaServer Pages). JSP is actually a HTML but unlike HTML, JSP may have Java codes (usually we call it as Scriptlet) embedded in it. In short words, we may represent JSP as dynamic HTML. In Java J2EE Web Application, JSP plays as a front-end while Java Servlet is the controller that contains the business logics, complex algorithms and etc.

For example, consider “Online University Student Registration System” developed in Java J2EE Web Application, the registration page where you fill in your details such as your name, your address, your username and etc are actually a JSP page. Later on, when you have completed filling out all the details and you press the submit button, all the information will be sent to Java Servlet for further processes. Java Servlet receives this information, does the necessary processes such as validations, generating user id and etc and then keeps the information to database. After successfully saving the data to database, Java Servlet redirects the user to the success page where the user can log in to the system. Likewise, if there is an unexpected error occurred happening in the middle of student registration system’s process, the user will be redirected to the error page.

Assuming that you have installed Eclipse with Web Tools Platform (WTP) Plugin, Java Development Kit 1.5 and Tomcat Server 5.5, let’s start to create our first Java Servlet. Start Eclipse and you should see similar to below illustration in your screen. Yes, this is the main page of Eclipse.



Image 

To create our Java Servlet, we are required to create a Project called Dynamic Web Project. Go to your menu, choose New and Project. A wizard will be prompted to you.



Image 

Go to the Web and choose Dynamic Web Project and press Next. If you do not have Dynamic Web Project available, it means that Web Tools Platform (WTP) plugin is not correctly installed to Eclipse. Please re-download it or look at the documentation of Web Tools Platform (WTP) plugin for more details.



Image 

A wizard will be displayed to you. The wizard is mainly used to configure our Dynamic Web Project. You are allowed to name your Dynamic Web Project with any name that you wish but please consider to choose the name that is self-explanatory.

For our tutorial’s sample, I am going to name my Dynamic Web Project as MyFirstServlet. There is an interesting point worth to be looked at in this wizard. You need to provide the Target Runtime. What does it mean? Well, it basically requests you to identify the server that you would like to use for this Dynamic Web Project; in this case, Apache Tomcat. You may try to click on the combo box to observe whether you have any existing server(s) or not. If not, you are required to create one server for your project. If this is the first time you run Eclipse, you should not have any server yet. So, click on the New button on the right side of the Target Runtime combo box. Remember, after defining one server, you can re-use it in other projects so you do not need to define new server in every project unless if you wish to use other servers than Tomcat such as Bea WebLogic and etc.



Image 
:
Posted by 라면스프
2012. 3. 2. 10:33

[Flex] file uploading with return data Enjoy/FLEX2012. 3. 2. 10:33

출처 :  http://dgrigg.com/blog/2007/08/02/Flex-and-Flash-file-uploading-with-return-data/ 

The addition of the FileReference class in AS2 made file uploading significantly easier in Actionscript. However, one issue that remained problematic was the ability to get detailed information back from the server once the upload was complete. The best you could do was to get a ’200′ response saying the file upload had completed, but there was no easy way to return additional data from the server with respect to the uploaded process …. until now.

Adobe has finally added the missing piece to accomplish a nice tight uploading process, theUPLOAD_COMPLETE_DATA event (Flash Player 9.0.28.0). This event fires after the COMPLETE event and contains an important piece of information. The data property of the DataEvent contains the raw data returned from the server after a successful file upload. Finally, a way to return from the server information about the file and/or process. This is especially useful if during the upload process you need to do additional things like create a database record and then return the new database id, or possibly put the file in a different path based on the user, and return the path where the file exists back to the client.

Here’s a quick sample of implementing the new event in Flex and also a Coldfusion and PHP script to upload a file and then output and return data back to the client in a clean consistent fashion.

The Flex code. As you can see, this is a very simple example, you select a file and when the upload has completed the results from the server are output into a text area.

<?xml version="1.0" encoding="utf-8"?>
<!--
Derrick Grigg
derrick@dgrigg.com
http://www.dgrigg.com
created on August 2, 2007

A simple file upload process with data returned from the server
using the UPLOAD_COMPLETE_DATA event.
-->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
public var file:FileReference;

public function selectFile():void
{
file = new FileReference();
file.addEventListener(Event.SELECT, fileSelected);
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadDataComplete);
file.addEventListener(Event.COMPLETE, uploadComplete);
file.addEventListener(IOErrorEvent.IO_ERROR, handleError);
file.browse();
}

public function handleError(event:IOErrorEvent):void
{
status_txt.text = 'ERROR: ' + event.text + ' ';
}
public function fileSelected(event:Event):void
{
file = FileReference(event.target);
file_txt.text = file.name;
status_txt.text = 'upload file: '+ file.name + ' ';

var request:URLRequest = new URLRequest();
request.url = "uploader.cfm";
file.upload(request);
}

public function uploadDataComplete(event:DataEvent):void
{
var result:XML = new XML(event.data);
status_txt.text += 'Upload Data Complete '
status_txt.text += 'RESULT: ' + result.toString() + ' '
status_txt.text += 'STATUS: ' + result.status + ' ';
status_txt.text += 'MESSAGE: '+ result.message;
}

public function uploadComplete(event:Event):void
{
status_txt.text += 'Upload complete ';

}
]]>
</mx:Script>
<mx:VBox>
<mx:TextInput id="file_txt"/>
<mx:Button id="select_btn" label="select" click="selectFile();"/>
<mx:TextArea id="status_txt" width="400" height="200"/>
</mx:VBox>
</mx:Application>

 

The Coldfusion and PHP scripts upload a file and then output a simple XML string stating if the upload worked. You could easily modify this to return back any additional data you needed. The scripts are very simplified for demonstration purposes, you would definitely want to make them more robust in a production environment.

The Coldfusion upload script.

<cfprocessingdirective  suppresswhitespace="true">
<cftry>
<cffile action="upload" fileField="filedata" destination="c:wampwww estflex" nameconflict="overwrite">
<cfxml variable="status"><result><status>OK</status><message><cfoutput>#filename#</cfoutput> uploaded successfully.</message></result></cfxml>
<cfcatch>
<cfxml variable="status"><result><status>Error</status><message><cfoutput>#cfcatch.Message#</cfoutput></message></result></cfxml>
</cfcatch>
</cftry>
<cfoutput>#status#</cfoutput>
</cfprocessingdirective>

 

The PHP upload script

<?php

$upload_dir = $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/';
$upload_url = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']) . '/';
$message ="";

$temp_name = $_FILES['Filedata']['tmp_name'];
$file_name = $_FILES['Filedata']['name'];
$file_name = str_replace("","",$file_name);
$file_name = str_replace("'","",$file_name);
$file_path = $upload_dir.$file_name;

$result = move_uploaded_file($temp_name, $file_path);
if ($result)
{
$message = "<result><status>OK</status><message>$file_name uploaded successfully.</message></result>";
}
else
{
$message = "<result><status>Error</status><message>Somthing is wrong with uploading a file.</message></result>";
}

echo $message;
?>

 

You can download the sample files here.

I’m glad to see Adobe finally added this, it makes life so much easier.


 

:
Posted by 라면스프
2012. 2. 27. 01:01

[인터넷강의] 1과제 내용 2012. 2. 27. 01:01

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

2012. 2. 2. 00:07

[몰디브] 음식 사진 It's Me2012. 2. 2. 00:07


:
Posted by 라면스프
출처 : http://gubok.tistory.com/124


날짜를 나타낼때 변수로 받은 타입이 스트링일 경우가 많다. 이경우 DateFormat을 이용하여 Date 타입으로 컨버팅 하는데 자주 사용하다 보니 유틸리티로 만들어서 사용하곤 한다. 
그러다 보니 그 포맷 형태를 까먹을 때가 많다. 굳이 다 기억하고 싶지는 않지만 그래도 정리하고자 한다.

가장 일반적으로 사용하는 클래스는 java.text.SimpleDateFormat 클래스를 사용하는데, 성능면에서 많이 떨어진다고 한다.(얼마나 떨어지는지는 비교수치를 찾을 수가 없다. 시간 되면 테스트 한번 해보자). 그래서 사용하는 것이 apache.commons 에 있는 FastDateFormat 클래스이다. 
SimpleDateFormat이든 FastDateFormat이든 변수로 사용되는 format 형식은 동일하다.

Letter Date / Time Component Examples
G Era designator AD
y Year 1996; 96
M Month in year July; Jul; 07
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 10
F Day of week in month 2
E Day in week Tuesday; Tue
a Am/pm marker PM
H Hour in day (0-23) 0
k Hour in day (1-24) 24
K Hour in am/pm (0-11) 0
h Hour in am/pm (1-12) 12
m Minute in hour 30
s Second in minute 55
S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone -0800

1. String을 Date 타입으로 변환시 예제
String stringDate = "2009/02/19";
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date newDate = dateFormat.parse(stringDate);

apache.commons의 FastDateFormat 클래스는 다음처럼 사용한다.
FastDateFormat fastdateformat = FastDateFormat.getInstance(format, locale);
locale은 request로 부터 받아도 되고 또는 Default로 new Locale("ko_KR")처럼 지정할수도 있다.

2. 역으로 Date타입을 String타입으로 변환시 예제
String newStringDate = dateFormat.format(newDate)

상황에 따라서 newDate.toString()을 쓰기도 하지만 엉뚱한 값이 나올수도 있으니 유의.

다음엔 Locale에 들어가는 값에 대해 알아보고 정리해 보기로 해야겠다.
:
Posted by 라면스프
출처 : http://wiki.javajigi.net/pages/viewpage.action?pageId=7188


왜 필요한가?

우리들이 일반적으로 개발하고 있는 대부분의 자바 웹 애플리케이션의 디렉토리 구조를 보면 프로젝트마다 제각기 다르다는 것을 알 수 있다. 물론 프로젝트의 성격에 따라 다르게 구성하는 것이 맞겠지만 기본적인 디렉토리 구조에 대한 가이드안을 만든다면 프로젝트에 참여하는 개발자들이 좀 더 빠르게 친숙해 질 수 있을 것으로 생각한다.

여러분들이 지금까지 참여한 프로젝트들의 디렉토리 구조는 어떠한가? 우선 지금까지 자바지기가 진행한 프로젝트의 디렉토리 구조를 예로 들고 각각의 구조에 대한 좀 더 좋은 방안을 찾아보고자 한다.

이 문제를 토론 주제를 빠르게 선정한 이유는?

현재 자바지기에 대한 사이트 개편 작업을 진행할 예정이다. 사이트 개편 작업을 하면서 프로젝트의 디렉토리 구조를 정의할 때 다른 개발자들이 생각하거나 일반적으로 사용하는 디렉토리 구조를 공유하여 사용하기 위함이다. 프로그램에 정답이 없듯이 이 문제 또한 정답은 있을 수 없다. 단지 각각의 구조에 따른 장,단점이 있을 따름이다. 프로젝트의 성격에 따라서 디렉토리 구조를 결정하면 될 것으로 생각한다.

무엇을 얻을 수 있나?

Java 웹 애플리케이션의 프로젝트에 대한 디렉토리 구조를 정의함으로서 신규 프로젝트를 진행할 때 추가적인 고민없이 프로젝트를 진행하는 것이 가능하다.

다양한 디렉토리 구조

디렉토리 구조 공유

여러분들이 지금 사용하고 있는 디렉토리 구조를 공유해주시면 더 좋겠네요. 만약 여러분이 그와 같은 구조를 만들었다면 왜 그와 같은 구조를 만들게 되었는지..지금과 같은 구조로 프로젝트를 진행했을 때의 장,단점은 무엇인지 등에 대해서 공유해주시면 좋겠네요.

해결 방법

  • 최근 대부분의 자바 웹 애플리케이션 개발에서 공통적으로 보이는 경향은 자바 소스 디렉토리와 Web 소스(js, css, jsp, html)를 분리한다.
  • 자바 소스 디렉토리는 실제 구현 소스와 테스트 소스를 분리한다. 또한 실제 구현 소스와 같은 패키지내에 테스트 소스를 구현하는 것을 원칙으로 하고 있다.
  • 빌드 환경까지 제공해줄 수 있어야 한다.

자바지기 개편안을 위한 디렉토리 구조

자바지기 개편안을 위한 디렉토리 구조는 Equinox의 디렉토리 구조를 따르는 것으로 했다. Equinox의 경우 디렉토리 구조 뿐만 아니라 각 프레임워크별로 기본 템플릿 프로젝트를 제공하기 때문에 세팅하기 쉽다.

또 한가지 Equinox를 선택하게 된 이유는 단순한 디렉토리 구조 뿐만아니라 Build 환경까지 제공한다는 것이다. Build 환경이 단순하게 Ant만을 지원했다면 선택하지 않았겠지만 Ant와 Maven의 강점 두가지를 모두 가지고 있는 구조가 마음에 들었다. 이와 같은 구조로 웹 애플리케이션을 개발할 경우 CVS나 SVN을 통하여 라이브러리를 공유하지 않은 상태로 개발하는 것이 가능하다. 또한 경우에 따라서는 Maven을 이용하여 빌드하는 것 또한 가능하기 때문이다.

Ant과 AntLib의 조합, build.xml과 pom.xml의 조합은 그 동안 해결하려고 했던 많은 문제점을 해결해 줄 수 있을 것이라 생각한다. 또한 pom.xml을 가지고 있기 때문에 Eclipse Maven IDE를 이용하여 개발하는 것이 가능하게 된다.

build.xml의 다음 코드를 통하여 Ant와 Maven이 통합되었을 때 라이브러리 관리가 얼마나 편하게 될 수 있는지 확인할 수 있을 것이다.

build.xml
    <artifact:pom file="pom.xml" id="maven.project"/>

    <artifact:dependencies pathId="compile.classpath" filesetId="compile.fileset" useScope="compile">
        <pom refid="maven.project"/>
    </artifact:dependencies>
    
    <artifact:dependencies pathId="test.classpath" filesetId="test.fileset" useScope="test">
        <pom refid="maven.project"/>
    </artifact:dependencies>
    
    <artifact:dependencies pathId="runtime.classpath" filesetId="runtime.fileset" useScope="runtime">
        <pom refid="maven.project"/>
    </artifact:dependencies>

    <target name="compile" description="Compile main source tree java files">
        <mkdir dir="${build.dir}/classes"/>
        <javac destdir="${build.dir}/classes" debug="true" optimize="false"
            deprecation="false" failonerror="true">
            <src path="${src.dir}"/>
            <classpath>
                <path refid="compile.classpath"/>
                <fileset dir="${web.dir}/WEB-INF/lib" includes="*.jar"/>
            </classpath>
        </javac>
        <!-- compile tests -->
        <mkdir dir="${test.dir}/classes"/>
        <javac destdir="${test.dir}/classes" debug="true" optimize="false"
            deprecation="false" failonerror="true">
            <src path="${test.src}"/>
            <classpath>
                <path refid="test.classpath"/>
                <path location="${build.dir}/classes"/>
                <fileset dir="${web.dir}/WEB-INF/lib" includes="*.jar"/>
            </classpath>
        </javac>
        <!-- Copy XML files to ${build.dir}/classes -->
        <copy todir="${build.dir}/classes">
            <fileset dir="${src.dir}" includes="**/*.xml"/>
        </copy>
    </target>

이와 같이 두가지를 통합하여 사용할 경우 라이브러리를 개발자간에 공유할 필요없이 pom.xml만 공유하면 된다.

:
Posted by 라면스프