반응형
글깨짐 확인 소스..




1. charset의 의미
charset = "coded character set"
charset은 "컴퓨터에서 문자를 표현하기 위해, 각 문자를 정수값에 대응시켜 놓은 체계"를 의미합니다.

예를 들어, euc-kr charset이라면, 영숫자와 한글 그리고 일부 특수문자와 한자들을 정수값에 대응해 놓은 것입니다.
euc-kr환경에서 한글을 입력하면, 컴퓨터는 euc-kr charset에서 각 문자별로 지정한 정수값을 쓰게 됩니다.

2. charset이 달라진다면..
각 charset별로, 표현하고자하는 문자와 대응하는 정수값이 달라질 수 있습니다.
예를들어 euc-kr은 태국문자를 위한 정수값을 정의하지 않았으므로, 태국문자는 표현하거나 입력할 수 없습니다.

그리고, euc-kr charset에 맞춰 한글로 어떤 내용을 작성했는데,
이것을 iso-8859-1 charset 환경에서 열어본다면, 한글 대신에 엉뚱한 특수문자쌍들을 보게 될 것입니다.

이런 문제 때문에, 문자 데이터를 주고 받을 때는 서로 간에 charset을 일치시킬 필요가 있습니다. 그렇지
않으면, 원래 생각했는 내용 대신 "깨진 문자들"을 보게 될테니까요.
( 가끔 charset은 일치되었는데, 사용하는 폰트에 대응하는 문자가 없어서 깨져보이는 경우도 있습니다. )

서블릿 코딩시에, content type의 일부로 charset을 명시하는 것은 웹 브라우저에게 사용하는 charset을
알려주어 오해하지 않게 하기 위해서입니다.

3. 한글을 표현할 수 있는 charset
한글을 표현할 수 있도록 설계된 charset은 euc-kr외에도, ksc5601, cp933, cp949 등등 꽤 많습니다.
그리고, 전세계 모든 문자를 표현할 목적으로 설계된 unicode역시 한글을 지원합니다.
그러나, 한글을 지원하는 charset을 사용하더라도, 문서를 만들 때 사용한 charset과 읽을 때 사용하는
charset이 다르다면, 제대로 그 내용을 볼 수 없을 것입니다. 이 경우에는 따로 conversion로직을 사용하여
원하는 charset에 맞춰 데이터를 가공해야 할 것입니다.
( euc-kr, ksc5601 같은 경우는 거의 차이가 없어 호환가능합니다. )

3. 영문 OS에서 한글 표현
charset에 맞추어 문자데이터를 처리하는 것은 OS나 DBMS, 미들웨어 등 플랫폼이므로, 플랫폼에서
제공해주지 않는 charset을 사용할 수는 없습니다.
다행히도, 최근의 플랫폼 SW들은 다양한 charset 지원을 포함하고 있습니다. 만약 어떤 OS가 euc-kr모드로
작동하고 있다면, 설령 영문OS라 하더라도, 한글 처리에 문제가 없다고 볼 수 있습니다.
문제가 있다면 euc-kr모드로 작동하고 있는 것이 아니겠죠.

저 같은 경우, 영문 OS를 설치하고, 그 위에서 한글을 사용해 본 적이 있습니다.

4. encoding
charset과 비슷한 의미로 사용하는 단어로 encoding이 있습니다.
charset이 문자에 대해 정수값을 지정한 것이라면,
encoding은 "문자를 표현하는 정수값을 어떤 bit배열로 표현할 것"인지를 의미합니다.

대부분의 경우, charset과 encoding을 구별할 필요가 없습니다. 왜냐하면 정수값을 bit배열로 표현하는 방법은
하나만 있을테니까요. 그러나 unicode 경우에는 UTF-8, UTF-16 같이 몇 가지 다른 encoding을 사용합니다.
charset이 같다면, 그 charset을 지원하는 어떤 encoding을 사용하든지, 각 문자에 대응하는 논리적인 정수값은 동일합니다.
그러나 실제로 기록되는 bit배열은 encoding에 따라 달라질 수 있습니다. 이 경우, 제대로 데이터를 주고 받으려면, charset뿐 아니라 encoding까지도 맞춰야 합니다.
반응형
<출처: http://frogdaddy.tistory.com/entry/weblogic61에서charset변경작업 >
1. 작업 환경

OS: Windows2003 
웹브라우저 : ie7.0 
웹서버/WAS : weblogic6.1 
JAVA : jdk1.3
DB : EUC-KR charset 환경 
      ( DB 도 utf-8 로 바뀌어야 완벽한 작업이 될것으로 예상됨 , 
        나중에 기회가 되면 DB 의 charset 변경작업을 하게되면 blog 로 작성하겠음...)


2. 작업내용

(1) web.xml  파일 수정  : euc-kr 을 utf-8 로
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
  <context-param>
    <param-name>weblogic.httpd.inputCharset./*</param-name>
    <param-value>UTF-8</param-value>  
 </context-param>
</web-app>

(2) weblogic.xml  파일 수정  : euc-kr 을 utf-8 로
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web Application 6.1//EN" "http://www.bea.com/servers/wls610/dtd/weblogic-web-jar.dtd">
<weblogic-web-app>
  <jsp-descriptor>
    <jsp-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </jsp-param>
  </jsp-descriptor>
  <charset-params>  
    <input-charset>      
      <resource-path>./*</resource-path>      
      <java-charset-name>UTF-8</java-charset-name>    
    </input-charset>  
  </charset-params>
</weblogic-web-app>
 
(3) JSP 의 charset 지정 : euc-kr 을 utf-8 로
<%@ page language="java" contentType="text/html; charset=utf-8" %>

(4) HTML 의  meta tag 의 charset 지정 : euc-kr 을 utf-8 로
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">



3. 유의사항

* ultraediter, jbuilder 로 charset 을 변경한 후 저장하면, weblogic 에서 null pointer exception 오류가 발생함.
   웹셔핑으로 얻은 지식으로 여러가지 방법을 해보았으나, 잘 되지 않았음 ㅠㅠ'

   (utf-8 로 charset 을 지정하면 위 editor 가 file type 설정을 변경시키는듯 합니다. 
    BOM 의 영향이 있는것 같기도 하고.. 
    eclipse 에서 charset 을 utf-8 로 수정한후 저장한 파일을 ultraedit 에서 수정하면 위 오류 발생하지 않음)

* eclipse 에서 편집한후 저장하면 위 오류는 발생하지 않았음.
   ( 기존 jbuilder 에서 작업한 파일시스템을 eclipse 로 import 작업이 필요함)



4. 기존 File Directory ( 웹 directory ) 를  Eclipse 에서 작업하는 방법

(1) 기존 eclipse 의 프로젝트의 폴더의 '.project' , '.classpath' 를  eclipse 에서 작업할 웹 directory 폴더에 copy 한다.
( '.project' , '.classpath' 의 내용을 적당히 수정한다. 내용 수정없이도 import 가 되긴 했는데... ^^; )

(2) eclipse -> File -> Import 
-> General -> Existing Projects into Workspace 
-> 위에 '.project' , '.classpath' copy 된 폴더 선택
반응형

이기종의 플랫폼과 연동할 이슈가 발생하면, 네트웍을 통한 Byte Ordering과 더불어 스트링의 인코딩/디코딩도 이슈거리입니다.  아래는 자바 API 5의 java.nio.charset.Charset 에 나오는 내용입니다.

표준 캐릭터셋
Java 플랫폼의 구현은 모두 다음의 표준 캐릭터셋를 지원 할 필요가 있습니다. 지원 되고 있는 그 외의 캐릭터셋에 대해서는 구현의 릴리스 노트를 참조하십시오. 그러한 옵션의 캐릭터셋의 동작은 구현 마다 다를 가능성이 있습니다.

캐릭터셋           설명
US-ASCII          7 비트 ASCII (ISO646-US/Unicode 캐릭터셋의 Basic Latin 블록)
ISO-8859-1      ISO Latin Alphabet No. 1 (ISO-LATIN-1)
UTF-8                8 비트 UCS 변환 형식
UTF-16BE        16 비트 UCS 변환 형식, 빅 endian 바이트순서
UTF-16BE        16 비트 UCS 변환 형식, little endian 바이트순서
UTF-16             16 비트 UCS 변환 형식, 옵션의 바이트순서 마크로 식별되는 바이트순서

아래코드는 예제입니다.
class CharSetTest {

    static String aa = "a1";

    static void testAscii() {
        try {
            byte[] bytes = aa.getBytes("US-ASCII");
            for(int i=0; i < bytes.length; i++) {
                System.out.print(bytes[i]);
            }

            System.out.println("");
        }catch(java.io.UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    static void testUTF8() {
        try {
            byte[] bytes = aa.getBytes("UTF-8");
            for(int i=0; i < bytes.length; i++) {
                System.out.print(bytes[i]);
            }

            System.out.println("");
        }catch(java.io.UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    static void testUTF16() {
        try {
            byte[] bytes = aa.getBytes("UTF-16");
            for(int i=0; i < bytes.length; i++) {
                System.out.print(bytes[i]);
            }

            System.out.println("");
        }catch(java.io.UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    static void testUTF16BE() {
        try {
            byte[] bytes = aa.getBytes("UTF-16BE");
            for(int i=0; i < bytes.length; i++) {
                System.out.print(bytes[i]);
            }

            System.out.println("");
        }catch(java.io.UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    static void testUTF16LE() {
        try {
            byte[] bytes = aa.getBytes("UTF-16LE");
            for(int i=0; i < bytes.length; i++) {
                System.out.print(bytes[i]);
            }

            System.out.println("");
        }catch(java.io.UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.println("--- Ascii ---");
        CharSetTest.testAscii();
        System.out.println("--- UTF-8 ---");
        CharSetTest.testUTF8();
        System.out.println("--- UTF-16 ---");
        CharSetTest.testUTF16();
        System.out.println("--- UTF-16BE ---");
        CharSetTest.testUTF16BE();
        System.out.println("--- UTF-16LE ---");
        CharSetTest.testUTF16LE();
    }
}
아래 예는 화면결과 입니다.
--- Ascii ---
9749
--- UTF-8 ---
9749
--- UTF-16 ---
-2-1097049
--- UTF-16BE ---
097049
--- UTF-16LE ---
970490
< 출처: http://www.sjava.net/62 >
반응형
정말 오랫만에 보는 아스키코드다.. 처음 프로그래밍에 입문할때 많이 봤었다.

C로 프로그램을 작성하던 대학생 시절의 감회가 떠오른다.

키코드값을 찾던 중에 보게되어 올린다..



출처: www.LookupTables.com
반응형

Key Code Reference Table

키코드값이 필요 해서 찾던 중에 찾았다.. ㅎㅎ 정리해 놓으면 유용할듯 하다.

매번 찾기는 귀찮으니 잘 포스팅 해놓자 ㅋㅋ

Key Pressed

Javascript Key Code

backspace

8

tab

9

enter

13

shift

16

ctrl

17

alt

18

pause/break

19

caps lock

20

escape

27

page up

33

page down

34

end

35

home

36

left arrow

37

up arrow

38

right arrow

39

down arrow

40

insert

45

delete

46

0

48

1

49

2

50

3

51

4

52

5

53

6

54

7

55

8

56

9

57

a

65

b

66

c

67

d

68

e

69

f

70

g

71

h

72

i

73

j

74

k

75

l

76

m

77

n

78

o

79

p

80

q

81

r

82

s

83

t

84

u

85

v

86

w

87

x

88

y

89

z

90

left window key

91

right window key

92

select key

93

numpad 0

96

numpad 1

97

numpad 2

98

numpad 3

99

numpad 4

100

numpad 5

101

numpad 6

102

numpad 7

103

numpad 8

104

numpad 9

105

multiply

106

add

107

subtract

109

decimal point

110

divide

111

f1

112

f2

113

f3

114

f4

115

f5

116

f6

117

f7

118

f8

119

f9

120

f10

121

f11

122

f12

123

num lock

144

scroll lock

145

semi-colon

186

equal sign

187

comma

188

dash

189

period

190

forward slash

191

grave accent

192

open bracket

219

back slash

220

close braket

221

single quote

222




<출처: http://protocolsofmatrix.blogspot.com/2007/09/javascript-keycode-reference-table-for.html >
반응형

문자 A부터 Z, 표준 숫자 0부터 9

다음 표는 표준 키보드의 문자 A부터 Z 및 숫자 0부터 9까지의 키와 ActionScript에서 해당 키를 식별하는 데 사용하는 키 코드 값의 목록입니다.

문자 또는 숫자 키

키 코드

ASCII 키 코드

A

65

65

B

66

66

C

67

67

D

68

68

E

69

69

F

70

70

G

71

71

H

72

72

I

73

73

J

74

74

K

75

75

L

76

76

M

77

77

N

78

78

O

79

79

P

80

80

Q

81

81

R

82

82

S

83

83

T

84

84

U

85

85

V

86

86

W

87

87

X

88

88

Y

89

89

Z

90

90

0

48

48

1

49

49

2

50

50

3

51

51

4

52

52

5

53

53

6

54

54

7

55

55

8

56

56

9

57

57

a

65

97

b

66

98

c

67

99

d

68

100

e

69

101

f

70

102

g

71

103

h

72

104

i

73

105

j

74

106

k

75

107

l

76

108

m

77

109

n

78

110

o

79

111

p

80

112

q

81

113

r

82

114

s

83

115

t

84

116

u

85

117

v

86

118

w

87

119

x

88

120

y

89

121

z

90

122

숫자 키패드의 키

다음 표는 숫자 키패드의 모든 키와 ActionScript에서 해당 키를 식별하는 데 사용하는 키 코드 값의 목록입니다.

숫자 키패드 키

키 코드

ASCII 키 코드

숫자 패드 0

96

48

숫자 패드 1

97

49

숫자 패드 2

98

50

숫자 패드 3

99

51

숫자 패드 4

100

52

숫자 패드 5

101

53

숫자 패드 6

102

54

숫자 패드 7

103

55

숫자 패드 8

104

56

숫자 패드 9

105

57

곱하기 키

106

42

더하기 키

107

43

Enter

13

13

빼기 키

109

45

소수점 키

110

46

나누기 키

111

47

기능 키

다음 표는 표준 키보드의 기능 키와 ActionScript에서 해당 키를 식별하는 데 사용하는 키 코드 값의 목록입니다.

기능 키

키 코드

ASCII 키 코드

F1

112

0

F2

113

0

F3

114

0

F4

115

0

F5

116

0

F6

117

0

F7

118

0

F8

119

0

F9

120

0

F10

이 키는 시스템에 예약된 키이므로 ActionScript에서 사용할 수 없습니다.

이 키는 시스템에 예약된 키이므로 ActionScript에서 사용할 수 없습니다.

F11

122

0

F12

123

0

F13

124

0

F14

125

0

F15

126

0

기타 키

다음 표는 표준 키보드의 문자, 숫자, 숫자 키패드 키 및 기능 키 이외의 키와 ActionScript에서 해당 키를 식별하는 데 사용하는 키 코드 값의 목록입니다.

키 코드

ASCII 키 코드

Backspace

8

8

Tab

9

9

Enter

13

13

Shift

16

0

Control

17

0

Caps Lock

20

0

Esc

27

27

스페이스바

32

32

Page Up

33

0

Page Down

34

0

End

35

0

Home

36

0

왼쪽 화살표

37

0

위 화살표

38

0

오른쪽 화살표

39

0

아래 화살표

40

0

Insert

45

0

Delete

46

127

Num Lock

144

0

ScrLk

145

0

Pause/Break

19

0

; :

186

59

= +

187

61

- _

189

45

/ ?

191

47

` ~

192

96

[ {

219

91

\ |

220

92

] }

221

93

" '

222

39

,

188

44

.

190

46

/

191

47



<출처: http://livedocs.adobe.com/flash/9.0_kr/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001136.html >
반응형


13일 어제부터 등록이였는데 깜빡 잊고 오늘 등록했다.. ㅡㅡ;

등록신청: http://www.jco.or.kr/ConferenceControl.do?cmd=conferenceApply&sc=applyReauest

이런 역시 인기 세션은 다 꽉 차있고... 흠 혹 빠지는 자리가 생길까 몇번 보았지만 포기 ㅡㅡ;

일단 신청은 해놨지만 현재 참여중인 프로젝트가 막바지라 주말도 출근..

참석할수 있을지 미지수지만 가고 싶다... ㅠㅠ



반응형

루리웹에서 가져온 카툰입니다.. 이거 진짜 쫌 황당한듯.. ㅡㅡ;

나름대로 프로그래머를 동경하며 이 길을 선택 했습니다.

개발자라고 불러지는 것도 조금 속상했습니다.

이제는 소프트웨어 기술자라고 하네요.. 괜찮습니다.
 
내가 하고자 하는 일과 할 수 있는 일이 같기 때문에 그리고...

그것으로 나의 생계를 유지 할 수 있기때문에..

그런데 이게 머야.. 안그래도 3D 업종이네 뭐네 하는데

이렇게 나라에서 도와주시니(?) 몸둘바를 모르겠네..

이렇게 나라에서 잘 해주시니(?)

고급 인력들은 몸둘바를 몰라 다 떠나가는게 아닌가 하는 생각이 드네요.. ㅡㅡ;
반응형

출처: http://cbiscuit.info/114

Java API for CVS
전 우주적으로 가장 활발하게 사용하는 버전컨트롤 도구는 아마도 CVS일지도 모른다아니면 MS SourceSafe 정도보다 강력한 상용 형상관리 도구들이 있지만 발주처 빵빵하고 대규모 프로젝트 아니면 만져볼 기회 조차 없는 것이 현실이다또한, 이런 형상관리 도구는 대부분 Open API를 제공한다지금 몸 담고 있는 프로젝트에서도 CVS 써버를 4대로 구성하여 아주 빵빵하게(?) 돌리고 있는데, 이 마저도 느리고 모자라다고 난리다. 가끔 출몰하는 좀비 cvs.exe때문인데, 그 원인은 아직 밝혀내지 못 하고 있다혹시 아시는 분은 바로 댓글 달아주시면 감사하겠다.

아무튼 이야기가 시작하자마자 바로 옆으로 샛는데, 본론은 Java API를 이용한 CVS 핸들링이다.   CVS와 연계하여 시스템적으로 무엇인가 처리해야 할 일이 있으면 아주 유용하게 쓸 수 있어 소개한다


jar 파일 다운 받는 곳
: 여기
ㅁ 관련 싸이트는 : 여기

사용법은 대충 이렇다.

public class CVSUtil {
  
    private static Log log = LogFactory.getLog(CVSUtil.class);
   
    public static void main(String[] args) {
        String destDir = "
체크아웃 받을 디렉토리";
        //
) D:\\cvs_repository\\test  <- \\ 두개 주의 하삼
!
        String location = "CVSROOT";
        //
) :pserver:anoncvs@localhost:/cvs
        String module = "CVS Module";
        //
) /MyModule
       
        CVSUtil.checkout( destDir, location, module);
    }
   
    public static void checkout(String destDir, String location, String module) {
        CVSRoot cvsroot = CVSRoot.parse(location);
        GlobalOptions globalOptions = new GlobalOptions();
        globalOptions.setCVSRoot(cvsroot.toString());
       
        PServerConnection con = new PServerConnection(cvsroot);
       
        Client client = new Client(con, new StandardAdminHandler());
        client.setLocalPath(destDir);
       
        CheckoutCommand checkout = new CheckoutCommand(true, module);
        try {
            client.executeCommand(checkout, globalOptions);
        } catch (Exception e) {
            log.error("", e);
        }
    }
}


다양한 cvs커맨드를 날릴수 있는 api 사용예제이다. .... 몇일을 인터넷을 뒤져서 겨우 찾은....^^

java cvs functions
Checkout from CVS


public void checkoutFromCVS(String userName, String password, String hostName, String repository) throws ExecutionException{
     PServerConnection c = null;
     try {
      logger.info("entering checkOutImages");
     
      String encryptedPassword = StandardScrambler.getInstance().scramble(password);
     
      CVSRoot root = CVSRoot.parse(":pserver:"+userName+"@"+hostName+":"+SC_PORT+repository);
      c = (PServerConnection)ConnectionFactory.getConnection(root);
      
       c.setEncodedPassword(encryptedPassword);     
      
       logger.info("open connection....");
       c.open();     
       logger.info("after open connection");
      
       Client client = new Client(c, new StandardAdminHandler()); 
       GlobalOptions options = new GlobalOptions();
       options.setCVSRoot(":pserver:"+userName+"@"+hostName+":"+SC_PORT+repository);
      
       client.ensureConnection();
      
       CheckoutCommand checkout = new CheckoutCommand(true,SC_MODULE);
       checkout.setPruneDirectories(true);
       File f = new File(SC_CVS_HOME);
       if(!f.exists())
        f.mkdirs();
      
       client.setLocalPath(SC_CVS_HOME);
       client.getEventManager().addCVSListener(new LogCVSListener());
      
       boolean success = client.executeCommand(checkout,options);
       logger.info("cmd checkout execute success:"+success);
       //client.executeCommand(uc, options);
  } catch (CommandAbortedException e) {
   logger.error("command aborted ex:"+e.getMessage());
   throw new ExecutionException(e.getMessage());
  } catch (AuthenticationException e) {
   logger.error("authenticate ex:"+e.getMessage());
   throw new ExecutionException(e.getMessage());
  }catch (CommandException e) {
   logger.error("command ex:"+e.getCause());
   throw new ExecutionException(e.getMessage());
  }   finally {
   if(null != c) {
    try {
     c.close();
    } catch (IOException e) {
     logger.error(e.getMessage());
    }
   }
  }
    }
 



Add to CVS


public void addToCVS(List filesToAdd, File fileToAdd, String userName, String password, String hostName, String repository)throws ExecutionException{
     logger.info("entering addToCVS");
     PServerConnection c = null;
     try {
      String[] children;
       // It is also possible to filter the list of returned files.
       // This example does not return any files that end with `.txt'.
       FilenameFilter filter = new FilenameFilter() {
           public boolean accept(File dir, String name) {
            if(dir.getName().equals("CVS")){
                return false;
               }

               return true;
           }
       };
      children = fileToAdd.list(filter);    
       File f = null;
     
          for (int i=0; i < children.length; i++) {
          
           f = new File(fileToAdd.getAbsoluteFile()+"/"+children[i]);
          
           try {
      logger.info("file:"+f.getCanonicalFile());
      logger.info("is file:"+f.isFile()+" is dir:"+f.isDirectory());
      if(f.isDirectory() ) {
        if(!f.getName().equals("CVS")){
        logger.info("recursive...");      
        filesToAdd.add(f);
        addToCVS(filesToAdd, f, userName, password, hostName, repository);     
        }
      }else {
       filesToAdd.add(f);
      }
           }catch(IOException e) {
            throw new ExecutionException(e.getMessage());
           }
          }
     
          if(filesToAdd.size() == 0) {
           logger.info("nothing to add....");
           return;
          }
         
      String encryptedPassword = StandardScrambler.getInstance().scramble(password);
     
      CVSRoot root = CVSRoot.parse(":pserver:"+userName+"@"+hostName+":"+SC_PORT+repository);
      c = (PServerConnection)ConnectionFactory.getConnection(root);
      
       c.setEncodedPassword(encryptedPassword);     
      
       logger.info("open connection....");
       c.open();     
       logger.info("after open connection");
      
       Client client = new Client(c, new StandardAdminHandler());       
            
       GlobalOptions options = new GlobalOptions();
       options.setCVSRoot(":pserver:"+userName+"@"+hostName+":"+SC_PORT+repository);          
      
      
       AddCommand add = new AddCommand();           
       add.setMessage("adding images for site portal...");
       add.setKeywordSubst(KeywordSubstitutionOptions.BINARY);
       logger.info("file path:"+fileToAdd.getPath());
       logger.info("file parent:"+fileToAdd.getParent());
       client.setLocalPath(SC_DIR_TO_SAVE);
       client.ensureConnection();
      
       add.setFiles((File[])filesToAdd.toArray(new File[filesToAdd.size()]));
       client.getEventManager().addCVSListener(new LogCVSListener());
      
       logger.info("executing command...");     
       boolean success = client.executeCommand(add,options);
       logger.info("cmd add execute success:"+success);
                                   
  } catch (CommandAbortedException e) {
   logger.error("command aborted ex:"+e.getMessage());
   throw new ExecutionException(e.getMessage());
  } catch (AuthenticationException e) {
   logger.error("authenticate ex:"+e.getMessage());
   throw new ExecutionException(e.getMessage());
  }catch (CommandException e) {
   logger.error("command ex:"+e.getMessage());
   throw new ExecutionException(e.getMessage());
 
  }finally {
 
   if(null != c) {
    try {
     c.close();
    } catch (IOException e) {
     logger.error(e.getMessage());
    }
   }
  }
     logger.info("leaving addToCVS");
    }
   



Commit to CVS


    public void commitToCVS(File fileToCommit, String userName, String password, String hostName, String repository) throws ExecutionException{
     PServerConnection c = null;
     try {
      logger.info("entering commitToCVS");
     
      String encryptedPassword = StandardScrambler.getInstance().scramble(password);
     
      CVSRoot root = CVSRoot.parse(":pserver:"+userName+"@"+hostName+":"+SC_PORT+repository);
      c = (PServerConnection)ConnectionFactory.getConnection(root);
      
       c.setEncodedPassword(encryptedPassword);     
      
       logger.info("open connection....");
       c.open();     
       logger.info("after open connection");
      
       Client client = new Client(c, new StandardAdminHandler()); 
       GlobalOptions options = new GlobalOptions();
       options.setCVSRoot(":pserver:"+userName+"@"+hostName+":"+SC_PORT+repository);
      
      
       client.ensureConnection();
                              
       client.getEventManager().addCVSListener(new BasicListener());
      
       //File file = new File(SC_CVS_HOME+"\\"+SC_MODULE+"\\resize_needed\\"+SC_TESTER);
       File afile[] = new File[] { fileToCommit };
      
       CommitCommand commit = new CommitCommand();      
             commit.setMessage("auto commit adding to cvs...");
             commit.setFiles(afile);
            
            
             commit.setForceCommit(true);
            
       client.getEventManager().addCVSListener(new LogCVSListener());
       client.setLocalPath(SC_DIR_TO_SAVE);
      
       logger.info("executing command...");
       boolean success = client.executeCommand(commit,options);
       logger.info("cmd commit execute success:"+success);

       //client.executeCommand(uc, options);
   }catch (CommandAbortedException e) {
    logger.error("command aborted ex:"+e.getMessage());
    throw new ExecutionException(e.getMessage());
   }catch (AuthenticationException e) {
    logger.error("authenticate ex:"+e.getMessage());
    throw new ExecutionException(e.getMessage());
   }catch (CommandException e) {
    logger.error("command ex:"+e.getCause());
    throw new ExecutionException(e.getMessage());
   }   finally {
    if(null != c) {
     try {
      c.close();
     } catch (IOException e) {
      logger.error(e.getMessage());
     }
    }
   }
   logger.info("leaving commitToCVS");
    }



InnerClass LogCVSListener


static public class LogCVSListener implements CVSListener {
              protected CVSCommandResult result = new CVSCommandResult();
              protected Logger logger  = Logger.getLogger(LogCVSListener.class.getName());
              public LogCVSListener() {
              }
             
              /***
               * @return Returns the result.
               */
              public CVSCommandResult getResult() {
                  return this.result;
              }
             
              /*
               * (non-Javadoc)
               *
               * @see org.netbeans.lib.cvsclient.event.CVSListener#messageSent(org.netbeans.lib.cvsclient.event.MessageEvent)
               */
              public void messageSent(MessageEvent e) {
                  if (e.isError()) {
                      logger.error(e.getMessage());
                      // permet de stocker les traces
                      result.getTrace().append(e.getMessage() + "\n");
                  } else {
                      logger.info(e.getMessage());
                  }
              }
     
              /*
               * (non-Javadoc)
               *
               * @see org.netbeans.lib.cvsclient.event.CVSListener#messageSent(org.netbeans.lib.cvsclient.event.BinaryMessageEvent)
               */
              public void messageSent(BinaryMessageEvent e) {
                  logger.info(e.getMessage());
              }
     
              /*
               * (non-Javadoc)
               *
               * @see org.netbeans.lib.cvsclient.event.CVSListener#fileAdded(org.netbeans.lib.cvsclient.event.FileAddedEvent)
               */
              public void fileAdded(FileAddedEvent e) {
                  logger.debug("File has been added.");
                  result.getFileAdded().add(e.getFilePath());
              }
     
              /* (non-Javadoc)
               * @see org.netbeans.lib.cvsclient.event.CVSListener#fileToRemove(org.netbeans.lib.cvsclient.event.FileToRemoveEvent)
               */
              public void fileToRemove(FileToRemoveEvent e) {
                  logger.debug("File to remove: " + e.getFilePath());
                  //result.getFileToRemove().add(e.getFilePath());
                 
              }
     
              /*
               * (non-Javadoc)
               *
               * @see org.netbeans.lib.cvsclient.event.CVSListener#fileRemoved(org.netbeans.lib.cvsclient.event.FileRemovedEvent)
               */
              public void fileRemoved(FileRemovedEvent e) {
                  logger.debug("File is removed: " + e.getFilePath());
              }
     
              /*
               * (non-Javadoc)
               *
               * @see org.netbeans.lib.cvsclient.event.CVSListener#fileUpdated(org.netbeans.lib.cvsclient.event.FileUpdatedEvent)
               */
              public void fileUpdated(FileUpdatedEvent e) {
                  logger.debug("File has been updated");
                  result.getFileUpdated().add(e.getFilePath());
              }
     
              /*
               * (non-Javadoc)
               *
               * @see org.netbeans.lib.cvsclient.event.CVSListener#fileInfoGenerated(org.netbeans.lib.cvsclient.event.FileInfoEvent)
               */
              public void fileInfoGenerated(FileInfoEvent fileInfoEvent) {
                  logger.debug("File status information has been received");
                  // Avec le diffInfo, possibilité de gestion plus fine des différences.
                  // DiffInformation diffInfo =
                  // ((SimpleDiffBuilder)fileInfoEvent.getSource()).createDiffInformation();
                  result.getFileInfo().add(fileInfoEvent.getInfoContainer());
              }
     
              /*
               * (non-Javadoc)
               *
               * @see org.netbeans.lib.cvsclient.event.CVSListener#commandTerminated(org.netbeans.lib.cvsclient.event.TerminationEvent)
               */
              public void commandTerminated(TerminationEvent e) {
                  if (e.isError()) {
                      logger.error("Server responses has error");
                      result.setError(true);
                  } else {
                      logger.debug("Server responses has OK");
                  }
              }
     
              /*
               * (non-Javadoc)
               *
               * @see org.netbeans.lib.cvsclient.event.CVSListener#moduleExpanded(org.netbeans.lib.cvsclient.event.ModuleExpansionEvent)
               */
              public void moduleExpanded(ModuleExpansionEvent e) {
                  // ne fait rien
              }
     
          }


반응형

g4j - GMail API for Java

GMailer API for Java (g4j) is set of API that allows Java programmer to communicate to GMail. With G4J programmers can made Java based application that based on huge storage of GMail.

An Email application, GMailer for Java is also built to demonstrate the usage of the API. It is planned to include minimalist email capabilities such as browse, search, read, send mail and download attachment.

This software is distributed in GNU General Public Lincense (GPL).

Download

The g4j package includes the library, the Email application and javadocs. The g4j-deps package is required if you want to compile g4j. Current version of API is 0.3.12 and Email application is 0.3.4.

For latest source code you can Browse CVS Repository or get the CVS by:

cvs -d:pserver:anonymous@cvs.sourceforge.net:/cvsroot/g4j login

cvs -z3 -d:pserver:anonymous@cvs.sourceforge.net:/cvsroot/g4j co src

Check the project statistics, woo we've made 10000+ lines of code in a month!

Release Notes 0.3.12

G4J finally support the new contact list interface! (read only)

Matthias fix bug in GMailer that scroll the message to bottom. He have also added open browser function, the links in messages now clickable!

You would need Java Runtime Environment (JRE) to run this software, download it in http://java.sun.com/

To use the software, run g4j.bat on Windows or g4j.sh on Unix. To Use the library include the g4j-lib.jar in your programs.

If you encounter error message: "sun.security.validator.ValidatorException: No trusted certificate found" while connecting gmail, please read the solution.

This program is developed mainly in Windows XP & 2000, it have not been tested on other platforms. If you encounter any problem please post a message in project support page.

G4J

Set of API that allows Java programmer to communicate to GMail. API is avaliable online.

  • Version 0.3.11 - (15-Oct-2004)
    Fixed: Support the new gmail contact interface, GMContact structure changed, new function GMConnector.getContact() replace old requestContact()
  • Version 0.3.10 - (7-Oct-2004)
    Added: GMConnector.fetchOriginalMail(String id) added, download original mail source from gmail
    Added: Preliminary support of send mail.
    Bugfix: "Drafts" mail now being prased correctly
  • Version 0.3.9 (5-Oct-2004)
    Update: GMail new mailbox "Drafts" supported
  • Version 0.3.4 (27-Sep-2004)
    Features: With multi-threaded http client, single connector can send multiple request at the same time
    Features: Parse the java script redirection in request()
  • Version 0.3.3 (22-Sep-2004)
    Bug Fix: Correctly parse escaped characters such as ' " < > \n and \r;
    Features: Implement missing "message body" packets in entries in conversation
  • Version 0.3 (18-Sep-2004)
    API to download conversation and open attachment as InputStream
  • Version 0.2
    API to retrive threads from mailbox/label and search message
  • Version 0.1
    API to connect to GMail

GMailer for Java

Minimalist Email client that retive email from Gmail.

Features:

  • Check and monitor mailboxes
  • Read mail
  • Search mail
  • Minimized to SysTray in Windows and Linux KDE3
  • Message saved to local disk and can be read later offline
  • Version 0.3.4
    (16-Oct-2004)
    Added: Open gmail home page (like original gmail notifier)
    Added: Open links in message
    Bugfix: Scroll to buttom when open a message
  • Version 0.3.3
    (15-Oct-2004)
    Added: Search messages
    Bugfix: Show offline message list correctly
    Bugfix: Click the sys tray icon before the program completely loaded, the program would popup and behave strangly
    Enhance: new toolbar buttons for better looks, across different platform/LAF
  • Version 0.3.2
    (7-Oct-2004)
    Added: Debug console
    Bugfix: Fix the problem that when exit without login, the software might not exiting properly.
    Bugfix: "Drafts" mail now being displayed correctly
  • Version 0.3.1
    (5-Oct-2004)
    Update: GMail new mailbox "Drafts" supported
  • Version 0.3 (3-Oct-2004)
    - BUGFIX: Reformat the message pane so that user can use mouse wheel to scroll message content.
    - ENHANCEMENT: improved performance to apply a LAF
  • Version 0.3-pre3 (1-Oct-2004)
    - FEATURES: Look and Feel chooser avaliable in option, features JGoodies Look and feel and theme
    - ENHANCEMENT: Show or hide message content using a better method, preformance improved
    - BUGFIX: Correctly disable menu items/toolbar buttons
  • Version 0.3-pre2 (27-Sep-2004)
    If a message is already downloaded, now GMailer read message from local disk instead of download again
    With multi-threaded g4j api and rewritten usage of threads, the general performance is improved
    Correct the tooltips of the systray icon
  • Version 0.3-pre1 (26-Sep-2004)
    Save data to local drive, the programs now can work offline to read downloaded message.
    Rewrite UI, now looks more comfortable. Add serveral icons, partly from Eclipse and others are draw by me.
  • Version 0.21 (22-Sep-2004)
    Open message body (partly)
  • Version 0.2 (18-Sep-2004)
    Added support of minimized to SysTray in Windows and KDE3; Support of auto connect and check message and various UI fix (18-Sep-2004)
  • Version 0.1
    This version connect to GMail and listing mailboxes. Searching, Viewing email and download attachment would be included in future release.

Acknowledgement

This project is inspried and motivated by GMailer for PHP and Gmail Agent API , their great works make me want to have an Java Implementation of their kind. Their open sources also made the understanding of GMail's protocol much easier, Thank You!

This project is not possible without following open source softwares:

  • Apache Jakarta Commons HTTPClient to access web page
  • Apache Jakrata Commons Codec to decode email
  • SysTray for Java to make the System Tray tricks
  • SIXBS (Simple XML Bean Serialization) from tagtraum industries, for saving document in XML
  • JGoodies for better UI looks
  • Concurrent Utilities from Doug Lea
  • BeanShell for embbed scripting engine
  • Eclipse for their nice icons
  • Google for their GMail, of course

Support and Contribution

If you have any problem, opinion, or software that built on g4j, please tell me via email or Sourceforge Forum!

Thanks Teodor and Samanth to join this project! They would help me to make GMailer more usable and I can focus more on the G4J API.

If you can join us, send me an email. You can also browse the todo list and give us suggestions!

Related Projects

  • Rishabh made gavamail , a POP3 inetrface for gmail in Java

About Me

I am a tiny programmer in a big enterprise in Hong Kong.

Read my blog in www.siuying.net ( Chinese Content )

[출처] g4j - GMail API for Java|작성자 후니


+ Recent posts