//VO 객체의 독립성을 유지 하기 위해 변경 처리. 

//사용법은 주석 확인. 



package module.common.otherinterface ;


import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.HashMap;

import java.util.Map;


import com.base.SystemException;

import com.component.parameter.IParameterManagement;

import com.framework.core.Workspace;


/**

 * 각 프로세스(메소드 단위) 시간 1/10000 단위로 점검 프로그램 

 * procTSOBegin -> procTSOWork procTSOWork procTSOWork(프로세스 숫자 만큼) -> procTSOEnd

 * 

 * 1. 로직 instance 호출

 *  ProcessTimeSysOut procTSO = new ProcessTimeSysOut();

 * 

 * 2. 최초 호출

 *  procTSO.procTSOBegin("국내출장);

 * 

 * 3. 각 프로세스 단위로 각 각 사이에 계속 추가. 

 *    procTSO.procTSOWork("신규:신청번호 채번 or 기 신청서 변경 체크");

 *    .

 *    .

 *    procTSO.procTSOWork("출장신청기본/출장예산정보");

 *    .

 *    .

 *    procTSO.procTSOWork("출장자 및 여비정보");

 *    

 * 4. 로직 instance 종료

 *    procTSO.procTSOEnd();

 * 

 * 싱글톤 패턴 구현

 * @since 1.0

 */

public class ProcessTimeSysOut extends Workspace {

PTSOVO ptsovo;

//private static ProcessTimeSysOut procTSO;

/* 복수의 프로그램에서 사용 가능 함에 따라 싱글톤 패턴 사용시 프로세스 누적 시간등이 혼합될 가능성이 있어

 *  싱글톤 패턴 해제함.

 * 

 * private ProcessTimeSysOut(){}

public static ProcessTimeSysOut getInstance(){

if(procTSO==null){

procTSO = new ProcessTimeSysOut();

procTSO.proCnt = 0;

procTSO.fullTime = 0;

procTSO.beforTime = 0;

}

return procTSO;

}

*/

//프로세스 최초시작 및 타이틀 설정

public void procTSOBegin(String processNameParam){

long time = System.currentTimeMillis(); 

this.ptsovo = new PTSOVO();

this.ptsovo.setProcTSOKEY(time);

System.out.println("============================"+processNameParam+" 프로세스 검토 로직 시작 ============================\n");

System.out.println("process key number : "+this.ptsovo.getProcTSOKEY());

this.ptsovo.setBeforTime(time);

this.ptsovo.setProcTitle(processNameParam);

SimpleDateFormat dayTime = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");

System.out.println("시작 시간 : "+dayTime.format(new Date(time))+"\n");

}

//프로세스 내의 작업 구분 요청(out 처리)

public void procTSOWork(String workName){

if(this.ptsovo!=null){

long nowtTime  = System.currentTimeMillis(); 

long processTime  = nowtTime - this.ptsovo.getBeforTime();

this.ptsovo.setFullTime(this.ptsovo.getFullTime()+processTime); 

this.ptsovo.setProCnt(this.ptsovo.getProCnt()+1);

//하단 sysout도출시 내용의 길이는 변경 하지 않도록 처리(30글자).

System.out.println(String.format("%03d",this.ptsovo.getProCnt())+"("+this.ptsovo.getProcTSOKEY()+")||"+this.ptsovo.getProcTitle()+" ==> "+String.format("%-30s",workName)+"======>"+processTime+" / "+this.ptsovo.getFullTime()+"\n");

this.ptsovo.setBeforTime(nowtTime);

}

}

//프로세스 검토 종료 로직

public void procTSOEnd(){

if(this.ptsovo!=null){

System.out.println("process key number : "+ptsovo.getProcTSOKEY());

long time = System.currentTimeMillis(); 

//최초 시작시 프로세스 시작 시간을 넣도록 함.

SimpleDateFormat dayTime = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");

System.out.println("종료 시간 : "+dayTime.format(new Date(time)));

System.out.println("총 누적 시간: " +this.ptsovo.getFullTime());

System.out.println("검토 프로세스 숫자: "+this.ptsovo.getProCnt()+"\n");

System.out.println("============================"+this.ptsovo.getProcTitle()+" 프로세스 검토 로직 종료 ============================\n");

System.out.println();

}

}


}




package module.common.otherinterface;


import java.math.BigDecimal;

import java.util.ArrayList;


import module.mis.trans.TransItem;

import module.mis.trans.TransVat;




public class PTSOVO {// 프로세스 분석 구조 객체

private int  proCnt = 0;  //프로세스 순번 

private long fullTime =0; //총 누적 소요 시간 

private long beforTime=0; //프로세스 시작 시간

private long procTSOKEY =0 ; //프로세스 생성시 주요키 값 (차후 조회시 대상 키값을 기준으로 조회 할수 있도록 처리.

private String procTitle ;  //프로세스 타이틀

public int getProCnt() {

return proCnt;

}

public void setProCnt(int proCnt) {

this.proCnt = proCnt;

}

public long getFullTime() {

return fullTime;

}

public void setFullTime(long fullTime) {

this.fullTime = fullTime;

}

public long getBeforTime() {

return beforTime;

}

public void setBeforTime(long beforTime) {

this.beforTime = beforTime;

}

public long getProcTSOKEY() {

return procTSOKEY;

}

public void setProcTSOKEY(long procTSOKEY) {

this.procTSOKEY = procTSOKEY;

}

public String getProcTitle() {

return procTitle;

}

public void setProcTitle(String procTitle) {

this.procTitle = procTitle;

}

}















//선언 및 만들어둬야 할것 소스 . 


//class 전역 변수 


int  proCnt = 0;  //프로세스 순번 

long fullTime =0; //총 누적 소요 시간 

long beforTime=0; //프로세스 시작 시간


//class 내 추가메소드 / 별도의 class 로 만들어 외부 접근 해도 무방


public void proTimeSysOut(String processNameParam,String type){

//시작 처리 type : S

if("S".equals(type)){

System.out.println("============================"+processNameParam+" 프로세스 검토 로직 시작 ============================\n");

long time = System.currentTimeMillis(); 

//최초 시작시 프로세스 시작 시간을 넣도록 함.

beforTime = time; 

SimpleDateFormat dayTime = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");

System.out.println("시작 시간 : "+dayTime.format(new Date(time))+"\n");

//종료 처리 type : E 

}else if("E".equals(type)){

System.out.println("============================"+processNameParam+" 프로세스 검토 로직 종료 ============================\n");

long time = System.currentTimeMillis(); 

//최초 시작시 프로세스 시작 시간을 넣도록 함.

SimpleDateFormat dayTime = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");

System.out.println("종료 시간 : "+dayTime.format(new Date(time))+"\n");

System.out.println("총 누적 시간: " +fullTime+"\n");

System.out.println("검토 프로세스 숫자: "+proCnt);

//종료시 전역 변수 long ,cnt 값을 초기화 한다. 

proCnt = 0;  //프로세스 순번 

fullTime =0; //총 누적 소요 시간 

beforTime=0; //프로세스 시작 시간

//각 프로세스 검토 type : P

}else if("P".equals(type)) {

if(beforTime==0){

System.out.println("프로세스 검토 로직 시작 이 누락 되었습니다.");

}else {

long nowtTime  = System.currentTimeMillis(); 

long processTime  = nowtTime - beforTime;

fullTime += processTime;

//하단 sysout도출시 내용의 길이는 변경 하지 않도록 처리(30글자).

System.out.println(String.format("%03d",++proCnt)+"||"+String.format("%-30s",processNameParam)+"======>"+processTime+" / "+fullTime+"\n");

beforTime = nowtTime;

}

}

}



// 사용법!!!


//성능 검증내 에서 해당 메소드를 호출 . 

//최초

  proTimeSysOut("국내출장","S");


// 각프로세스 마다 첫번째 파라미터에 프로세스 명을 입력  2번째 파라미터는 무조건 "P"

proTimeSysOut("신규:신청번호 채번 or 기 신청서 변경 체크","P");


//종료 

   proTimeSysOut("국내출장","E");




// sysout log 확인시. 아래와 같이 나오면 정상. 



[16. 9. 23   13:20:31:458 KST] 00000272 SystemOut     O ======================================

[16. 9. 23   13:20:31:458 KST] 00000272 SystemOut     O [ module.mis.hrm.main.Hrm_4071]

[16. 9. 23   13:20:31:458 KST] 00000272 SystemOut     O [2016.09.23 13:20:31(458)]

[16. 9. 23   13:20:31:458 KST] 00000272 ExtendAction  I module.common.action.ExtendAction execute 트랜잭션 시작.....

[16. 9. 23   13:20:31:459 KST] 00000272 SystemOut     O [ tmSetTrpRqst ] Transaction Start

[16. 9. 23   13:20:31:459 KST] 00000272 SystemOut     O ============================국내출장 프로세스 검토 로직 시작 ============================


[16. 9. 23   13:20:31:459 KST] 00000272 SystemOut     O 시작 시간 : 2016-20-23 01:20:31


[16. 9. 23   13:20:31:500 KST] 00000272 SystemOut     O 001||신규:신청번호 채번 or 기 신청서 변경 체크     ======>41 / 41


[16. 9. 23   13:20:31:781 KST] 00000272 SystemOut     O 002||출장신청기본/출장예산정보                 ======>281 / 322


[16. 9. 23   13:20:31:964 KST] 00000272 SystemOut     O 003||출장자 및 여비정보                    ======>183 / 505


[16. 9. 23   13:20:32:006 KST] 00000272 SystemOut     O 004||출장지 및 경유지                     ======>41 / 546


[16. 9. 23   13:20:32:055 KST] 00000272 SystemOut     O 005||출장내용                          ======>50 / 596


[16. 9. 23   13:20:32:055 KST] 00000272 SystemOut     O 006||첨부파일 저장                       ======>0 / 596






'JAVA' 카테고리의 다른 글

펌) immutable 이란  (0) 2013.10.15
grid I U D 포멧 JAVA 셋팅 [티폼 기준]  (0) 2013.06.27
디폴트 생성자에 대하여 알아 봅시닥.  (0) 2012.07.10
Swing - windowBuilder 설치 하기.  (0) 2012.06.13
패키지 컴파일러  (0) 2012.05.15
Posted by 사라링

펌) immutable 이란

 | JAVA
2013. 10. 15. 14:30


Immutable이란 생성후 변경 불가한 객체입니다. 그래서 immutable에는 set 메쏘드가 없습니다. 멤버 변수를 변경할 수 없습니다. return type이 void인 메쏘드도 없습니다. 주로 void 메쏘드는 뭔가를 하고(하지 않을 수도 있고.. ) 멤버변수를 변경하는 역할을 하는 것이기 때문에 쓸 일이 거의 없습니다. (물론, 콘솔에 뭔가를 찍는 것과 같은 예외적인 void는 있을 수 있습니다.)

Immutable을 쓰면, 멀티 쓰레드 환경에서 좀 더 신뢰할 수 있는 코드를 만들어 내기가 쉽습니다. 멀티 쓰레드 프로그램을 짜보셨다면 아시겠지만, 멀테 쓰레드 환경에서는 에러보다 비정상적 작동의 경우가 많습니다. 에러도 아니기 때문에 찾아내기도 어렵습니다. 게다가 항상 생기는 것도 아니고 백번에 한번 천번에 한번 식으로 문제가 생겨 정말 머리 아픈 경우가 한 두번이 아닙니다.

Immutable을 쓰게 되면, 이런 요소들을 많이 줄일 수 있습니다.


대표적인 Immutable 클래스


String, Boolean, Integer, Float, Long 등등이 있습니다. 여기서 주의할 점은 변경불가라는 것은 heap 영역에서의 변경불가라는 뜻입니다. String a="a"; a="b"; 와 같이 재할당은 가능합니다. 이는 a가 reference하고 있는 heap 영역의 객체가 바뀌는 것이지 heap영역에 있는 값이 바뀌는 것이 아닙니다.


String vs StringBuffer


String과 StringBuffer에는 비슷한 메쏘드들이 많이 있어서 비슷해 보이지만, 결정적인 차이가 있습니다. String은 Immutable 입니다. StringBuffer는 아닙니다. StringBuffer가 String에 비해서 훨씬 빠르다는 얘기를 들어보셨나요? 그건 객체를 새로 생성할 필요가 없기 때문입니다. 


String에는 없고 StringBuffer에만 있는 대표적인 메쏘드는 append, delete 등일 겁니다. 멤버 변수를 변화시켜 값을 바꿀 수 있는 거죠. 그런데 잘 보며 이들의 리턴은 StringBuffer 타입입니다. 어차피 얘네도 객체를 새로 만들어낸다면, String과 별 차이가 없어보입니다. 그러나 객체를 새로 만들어 내는 것이 아닙니다. 

아래 코드를 실행시켜보세요.

StringBuffer b = new StringBuffer();

StringBuffer a = b.append("test");

System.out.println(a == b);

true가 나옵니다. 객체를 새로 만드는 것이 아니라 return this 로 되어있습니다. 굳이 리턴을 하는 이유는 아래와 같은 코딩을 가능하게 해주려는 것 같습니다.


StringBuffer test = new StringBuffer();

test.append("a").append("b").append("c").append("d");


와 같은 식으로 여러줄 코딩을 한 줄로 할 수 있게 해주려는 것 같습니다.. 아님 말구요.-_-;


Immutable의 유용성과 위험성


멀티쓰레드 환경에서 하나의 객체에 접근을 하는데 각각의 쓰레드끼리는 영향을 받으면 안 되는 경우가 있습니다. 그럴 때 한 번 만들어진 객체의 값이 변하지 않는다는 게 보장이 되면 편하겠죠.


String a  = "";

while(어떤 조건문){

    a += "머시기";

    if(딴 조건문){

        break;

    }

}


위와 같은 코드는 쓰면 안 됩니다. a+= "머시기" 구문이 문젭니다. 객체를 계속 생성해 냅니다. Immutable은 값이 계속 변경될 수 있는 곳에 쓰면 메모리 왕창 잡아먹습니다. 값이 완전히 정리된 후에 한 큐에 immutable로 만들어 내셔야 합니다. (물론, 가비지 컬레션이 돌면서 정리를 하기 때문에 치명적으로 위험한 수준의 행동은 아닙니다.)


java.util.Collections 에 unmodifiable머시기 하는 메쏘드들이 있습니다. 얘네들을 이용하면, Set, List, Map 등을 immutable로 사용할 수 있습니다. 다만, add, put과 같은 메쏘드를 호출할 경우에는 UnsupportedOperationException 가 발생합니다. 예외 상황을 고려해야 합니다.


Immutable은 보통 final 클래스로 정의합니다.


처음에 자바를 할 때 String이란 객체에 ltrim이란 메쏘드를 추가하고 싶었습니다. (왼쪽만 trim하는 메쏘듭니다.) 상속을 받아 새로운 클래스를 만들어 해결하려고 했습니다. 헛, 그런데 final로 정의가 되어있어서 상속을 받을 수가 없더군요. 

final로 정의가 되지 않으면, 상속을 받은 클래스가 Immutable을 깨버릴 수가 있기 때문입니다.


잘못된 Immutable의 구현


package immutable;


import java.text.SimpleDateFormat;

import java.util.Date;


public final class WrongImmutable {

    private final Date date;

    private final SimpleDateFormat dateFormat;

    public WrongImmutable(Date date){

        this.date = date;

        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    }

    public String getMessage(){

        return dateFormat.format(date);

    }

}


위의 소스를 보세요. date라는 변수가 final로 정의 되어있으며, setter가 없어 오직 생성자에서만 값을 지정할 수 있는 것 같아보입니다. 그러나 아래와 같은 테스트 클래스를 실행시켜보시면, 위의 코드가 잘못되었음을 알 수 있습니다.


package immutable;


import java.util.Date;


public class WrongImmutableTest {

    public static void main(String[] args) {

        Date testDate = new Date();

        WrongImmutable wrongImmutable = new WrongImmutable(testDate);

        testDate.setTime(testDate.getTime() + 10000000);

        System.out.println(wrongImmutable.getMessage());

    }

}


WrongImmutable의 생성자에 인자로 넣은 Date를 외부에서 값을 변경시키면 WrongImmutable의 멤버 변수의 값이 변경이 되고 맙니다. Immutable에서는 멤버 변수가 외부로 공개되어 변경이 가능하면 안 됩니다. 

그럼 처음에 원했던 대로 정상적인 Immutable이 되도록 하려면 인자로 받은 Date 객체를 그대로 사용하는 것이 아니라, 어떤 식으로든 복사를 해서 써야 합니다. 생성자에서 멤버 변수의 값을 할당하는 부분을


this.date = new Date(date.getTime());

와 같이 바꿔야 합니다.


자바에 진짜 Immutable이란 건 없다!


java의 reflection을 이용하면 변경 가능합니다. 다음 코드를 실행시켜 보세요.


import java.lang.reflect.Field;


public class EditUsingReflection {

    public static void main(String[] args) throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException {

        String s = "string!";

        edit(s);

        System.out.println(s);

    }

    public static void edit(String s) throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException {

        Field stringValue = String.class.getDeclaredField("value");

        stringValue.setAccessible(true);

        stringValue.set(s, s.toUpperCase().toCharArray());

    }

}


String 객체는 내부적으로 value라는 이름의 char[]로 그 값을 관리합니다. 물론 private으로 선언되어있지요. 

reflection을 이용하면 멤버변수에 걸려있는 private을 무시하고 접근해 버릴 수가 있습니다. 결국 reflection을 이용하면 모든 멤버변수에 대한 수정이 가능합니다. Immutable이란 건 reflection을 제외시켜 놓고 생각할 때만 가능합니다.



출처 :  -- http://iilii.egloos.com/3809685

Posted by 사라링

List checkList = request.getGridCheckedList("listInfo");

for(Iterator all = checkList.iterator(); all.hasNext();){

Map gMap = (Map) all.next();

gMap.put("RQST_NO", rqstNo);

gMap.put("SESS_USER_ID", userId);

if ("I".equals(gMap.get("tmHeader"))){

createObject("pur.main.pur0010.saveDetail", gMap);

}else if("U".equals(gMap.get("tmHeader"))){

createObject("pur.main.pur0010.upDetail", gMap);

}else if("D".equals(gMap.get("tmHeader"))){

// 예산내역삭제

deleteObject("pur.main.pur0010.delBudg", gMap);

//품목내역삭제

createObject("pur.main.pur0010.delDetail", gMap);

}

}

Posted by 사라링

26-2.여러 가지 생성자

26-2-가.디폴트 생성자

디폴트 생성자(또는 기본 생성자라고도 한다)란 인수를 가지지 않는 생성자이다. 생성자는 오버로딩이 가능하므로 여러 개를 둘 수 있는데 그 중 인수가 없는 생성자를 디폴트 생성자라고 부른다. 즉 인수 목록이 void인 생성자인데 Position 클래스의 경우 디폴트 생성자의 원형은 Position()이 된다. 다음 예제의 Position 클래스는 디폴트 생성자 하나만 정의하고 있다.

 

  : DefConstructor

#include <Turboc.h>

 

class Position

{

private:

     int x;

     int y;

     char ch;

 

public:

     Position() {

          x=0;

          y=0;

          ch=' ';

     }

     void OutPosition() {

          if (ch != ' ') {

              gotoxy(x, y);

               putch(ch);

          }

     }

};

 

void main()

{

     Position Here;

    

     Here.OutPosition();

}

 

디폴트 생성자는 호출부에서 어떤 값으로 초기화하고 싶은지를 전달하는 수단인 인수가 없다. 인수를 받아들이지 않기 때문에 객체의 멤버에 의미있는 어떤 값을 대입하지는 못하며 주로 모든 멤버를 0이나 -1 또는 NULL이나 빈문자열로 초기화한다. 여기서 0이라는 값은 실용적인 의미를 가지는 값이라기보다는 단순히 아직 초기화되지 않았음을 분명히 표시하는 역할을 한다. 어떤 값인지 알지도 못하는 쓰레기값보다는 그래도 0이라도 대입해 놓는 것이 더 나은데 이렇게 하면 멤버 함수에서 이 값을 사용하기 전에 초기화 되어 있는지를 점검할 수 있기 때문이다.

 

if (ptr == NULL) { ... }

if (value == 0) { ... }

 

디폴트 생성자가 포인터 변수를 NULL로 초기화해 놓으면 멤버 함수가 이 변수를 사용하기 전에 NULL인지 조사해 보고 NULL이면 그때 초기화를 할 수 있다. 즉 디폴트 생성자의 임무는 쓰레기를 치우는 것이며 멤버의 초기화는 이 멤버를 사용하는 멤버 함수가 호출될때까지 연기된다. 위 예제의 Position() 디폴트 생성자는 x, y는 0으로 초기화하고 ch에는 공백 문자를 대입하며 OutPosition 함수는 ch가 공백 문자를 가질 때 이 객체가 아직 초기화되지 않은 것으로 판단하고 문자 출력을 하지 않는다. 디폴트 생성자가 있는 객체를 선언할 때는 다음과 같은 여러 가지 방법을 사용할 수 있다.

 

① Position Here;

② Position Here=Position();

③ Position *pPos=new Position;

④ Position *pPos=new Position();

⑤ Position Here();

 

①번 형식이 가장 간단하며 예제에서 사용한 방법이다. 생성자에게 전달할 인수가 없으므로 타입 다음에 객체 이름만 밝히면 된다. 기본 타입의 int i; 선언문과 형식이 동일하다. ②번 형식은 디폴트 생성자를 명시적으로 호출하는 구문인데 효과는 동일하다. ③, ④번은 객체를 동적으로 생성할 때 new연산자와 함께 사용하는 방법인데 ③번이 더 일반적이다.

그러나 ⑤번 형식은 허용되지 않는다. 왜냐하면 이 선언문은 Position 객체를 리턴하고 인수를 가지지 않는 Here 함수의 원형을 선언하는 것이지 객체 선언문이 아니기 때문이다. 생성자로 전달할 인수가 없으면 아예 괄호도 없어야 한다. 일반 함수는 인수가 없을 때 빈 괄호를 써 함수임을 분명히 표시하지만 객체 선언문의 경우는 반대로 생성자의 인수가 없을 때 괄호를 생략해 함수가 아님을 분명히 해야 한다. 잘 이해가 안되고 순간적으로 헷갈린다면 정수형으로 바꿔 생각해 보자.

 

int func;        // 이건 변수

int func();     // 요건 함수

 

만약 클래스가 생성자를 전혀 정의하지 않으면 어떻게 될까? 이 경우 컴파일러가 자동으로 디폴트 디폴트 생성자(그러니까 컴파일러가 기본적으로 정의하는 디폴트 생성자)를 만든다. 컴파일러가 만들어주는 디폴트 생성자는 아무 것도 하지 않는 빈 함수이다. 이 때 객체의 초기화 방식은 일반 변수와 같은 규칙이 적용되는데 전역이나 정적 객체라면 모든 멤버가 0으로 초기화되고 지역 객체라면 초기화되지 않는 쓰레기값을 가진다.

생성자가 없을 경우 컴파일러가 디폴트 생성자를 만들기 때문에 생성자를 전혀 정의하지 않아도 객체를 선언할 수 있는 것이다. 위 예제에서 Position() 디폴트 생성자를 삭제하면 컴파일러가 내부적으로 다음과 같은 디폴트 생성자를 만들 것이다.

 

Position()

{

}

 

비록 아무 것도 하지는 않지만 생성자가 있으므로 Position Here; 선언문으로 Here 객체를 선언할 수 있다. 그러나 이 객체는 쓰레기값을 가지고 있기 때문에 OutPosition이 어떤 동작을 할 것인지는 예측할 수 없다. 일반적으로 예측할 수 없는 동작은 항상 말썽의 소지가 되며 이런 잠재적인 말썽의 소지를 없애기 위해 디폴트 생성자를 직접 정의하고 모든 멤버의 쓰레기를 치우는 것이다.

컴파일러가 디폴트 생성자를 만드는 경우는 클래스가 생성자를 전혀 정의하지 않을 때 뿐이다. 다른 생성자가 하나라도 정의되어 있으면 컴파일러는 디폴트 생성자를 만들지 않는다. 다음 코드를 보자.

 

class Position

{

public:

     int x;

     int y;

     char ch;

 

     Position(int ax) { x=ax; }

     void OutPosition() { ... }

};

 

정수 하나를 인수로 취하는 생성자가 정의되어 있으므로 이 클래스는 디폴트 생성자를 가지지 않는다. 이 경우 Position Here; 선언문은 적절한 생성자를 찾을 수 없으므로 에러로 처리될 것이다. 별도의 생성자를 제공했다는 것은 클래스를 만든 사람이 이 객체는 이런 식으로 초기화해야 한다는 것을 분명히 명시한 것이므로 컴파일러는 이 규칙을 어긴 코드에 대해 사정없이 에러로 처리한다. 이 객체는 개발자의 의도에 따라 반드시 Position Here(12); 형식으로 생성해야 한다.

만약 Position Here; 형태로 꼭 객체를 선언하고 싶다면 Position(int) 생성자를 없애 컴파일러가 디폴트 생성자를 만들도록 내 버려 두든가 아니면 Position() 디폴트 생성자를 오버로딩해야한다. 생성자가 인수를 가지고 있더라도 디폴트 인수 기능에 의해 디폴트 생성자가 되는 경우도 있다. 다음과 같은 원형을 가지는 생성자는 인수없이도 호출할 수 있으므로 디폴트 생성자를 겸한다.

 

Position(int ax=0, int ay=0, char ach=' ')

 

디폴트 생성자가 없는 클래스는 객체 배열을 선언할 수 없다. 왜 그런지 다음 예제로 이유를 알아보자.

 

  : NoDefCon

#include <Turboc.h>

 

class Position

{

public:

     int x;

     int y;

     char ch;

 

     Position(int ax, int ay, char ach) {

          x=ax;

          y=ay;

          ch=ach;

     }

     void OutPosition() {

          gotoxy(x, y);

          putch(ch);

     }

};

 

void main()

{

     Position There[3];

}

 

이 예제의 Position 클래스는 디폴트 생성자를 정의하지 않으며 세 개의 인수를 취하는 생성자만 정의되어 있다. 개발자가 별도의 생성자를 정의했으므로 컴파일러는 디폴트 생성자를 만들지 않는다. 따라서 Position형의 객체를 만들려면 Position A(1,2,'A'); 식으로 생성자에게 세 개의 인수를 전달해야 한다. 그렇다면 main의 Position There[3]; 선언문은 어떻게 처리될까?

Position형의 객체 3개를 배열로 생성하되 이때 각 객체의 생성자가 호출될 것이다. 그러나 선언문에 인수가 없기 때문에 호출할만한 생성자를 찾을 수 없으며 에러로 처리된다. Position There[3]; 선언문이 처리되려면 인수를 취하지 않는 디폴트 생성자(컴파일러가 만든 것이든 개발자가 직접 정의한 것이든)가 반드시 있어야 하는 것이다. 다음과 같은 선언문이 가능하리라 생각해 볼 수도 있다.

 

Position There[3]={{1,2,'x'},{3,4,'y'},{5,6,'z'}};

 

구조체 배열처럼 ={ } 다음에 각 배열 요소의 초기값을 나열하는 형식이다. {1,2,'x'} 초기식에 있는 값을 클래스 선언문에 나타나는 멤버의 순서대로 대입하면 될 것처럼 보인다. 객체 배열을 초기화할 때도 이런 문법이 지원된다면 좋겠지만 이 문장은 에러로 처리된다. 왜 컴파일러가 객체 배열에 대한 이런 편리한 초기식을 지원하지 못하는지 생각해 보자.

객체는 단순히 정보의 집합인 구조체보다는 훨씬 더 복잡하기 때문에 단순한 대입만으로는 초기화할 수 없다. 생성 단계에서 둘 이상의 입력값을 계산한 결과가 초기값이 될 수도 있고 Person 예제처럼 인수의 길이만큼 메모리를 동적으로 할당해야 하는 경우도 있다. 또한 멤버가 프라이비트 영역에 있을 경우 외부 선언문에서 함부로 멤버값을 변경하는 것도 허락되지 않는다. 이런 능동적인 동작을 하려면 결국 객체 초기화를 위해 생성자가 호출되어야 하는 것이다.

그렇다면 초기식의 값을 그대로 생성자의 인수로 전달하면 되지 않을까? 초기식에 {1,2,'x'}라고 되어 있으니 Position(1,2,'x') 생성자를 호출하면 일단 될 것처럼 보이지만 이것도 불가능하다. 왜냐하면 생성자가 반드시 모든 멤버를 선언된 순서대로 다 받아들여야 한다는 제약이 없기 때문이다. Position(char ach, int ax, int ay) 요런 식으로 생성자가 정의되어 있다면 컴파일러가 초기식의 값과 생성자 인수와의 대응관계를 잘못 판단하게 될 것이고 객체는 제대로 초기화되지 않는다.

그래서 컴파일러는 애매한 초기식으로부터 대충 비슷해 보이는 생성자를 호출하는 쓸데없는 서비스를 하기보다는 차라리 에러로 처리하는 것이 더 깔끔하다고 생각하는 것이다. 만약 객체의 배열을 선언하면서 각 객체를 꼭 초기화하려면 다음과 같이 ={ }괄호안에서 생성자를 일일이 호출해야 한다.

 

void main()

{

     int i;

     Position There[3]={Position(1,2,'x'),Position(3,4,'y'),Position(5,6,'z')};   

     for (i=0;i<3;i++) {

          There[i].OutPosition();

     }

}

 

이 선언문은 초기식에서 명시적으로 생성자를 호출했고 생성자로 전달되는 인수의 순서를 컴파일러가 분명하게 알 수 있으므로 문법적으로 문제도 없고 애매하지도 않다. 객체 배열을 선언하면서 초기화할 때는 이 방법이 정석이며 초기식없이 선언만 하려면 반드시 디폴트 생성자가 정의되어 있어야 한다.

생성자가 없을 때 컴파일러가 디폴트를 만드는 것처럼 파괴자의 경우도 디폴트가 있다. 컴파일러가 만드는 디폴트 파괴자도 생성자의 경우와 마찬가지로 아무 일도 하지 않는 빈 함수이다. 그래서 뒷정리를 할 필요가 없는 클래스라면 디폴트 파괴자를 그냥 사용하는 것도 가능하다. 즉, 파괴자가 없어도 된다는 얘기인데 사실 파괴자는 필요없는 경우가 훨씬 더 많다. 생성자가 특별한 처리를 하지 않고 단순히 멤버 변수에 값만 대입한다면 뒷정리를 할 필요가 없다. Position은 파괴자가 전혀 불필요한 클래스이다.

 

'JAVA' 카테고리의 다른 글

펌) immutable 이란  (0) 2013.10.15
grid I U D 포멧 JAVA 셋팅 [티폼 기준]  (0) 2013.06.27
Swing - windowBuilder 설치 하기.  (0) 2012.06.13
패키지 컴파일러  (0) 2012.05.15
자바로 컴퓨터 종료  (0) 2012.05.15
Posted by 사라링

GUI : 그래픽 유저 인터페이스 .

  1. 교육 과정 AWT SWING
  2. NETWORK(소켓, 패킷 ~
  3. 도킹 : 기본 적으로 움직이는 메뉴바. /
  4.  뷰 : 로 만들어짐 이클립스.
  5. 보는 방법에 따라 보여지는것이 다르게 나오는것 을 perspective 라고 함.
  6. perspective미국/영국 [pərspéktiv]

    전망, 원근법, 견해 뜻(5개) 더보기

    오버로딩    : 다중정의 /  ㅠㅠ // 과적 해서 쌓는것 부하가 증가/ 같은 메서드 인데 파라미터가 여러개 인경우 중첩 설계 되는것.

    오버라이딩 :  // 상속 관계에서 가장 가까운 부모 클래스의 디폴트생성자를 갖게 되는것.

윈도우 빌더 설치 하기. // ecliptse -GUI plug-in

http://www.eclipse.org/windowbuilder/download.php  // 위지위그 드래그 drop 하여 사용.

플로그인 방법.

 

help -> Instal new software~ -> add-> ach~..선택 설치. 리스타트.

Eclipse 3.7 (Indigo)

http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7


Eclipse 3.6 (Helios)

http://dl.google.com/eclipse/inst/d2wbpro/latest/3.6


Eclipse 3.5 (Galileo)

http://dl.google.com/eclipse/inst/d2wbpro/latest/3.5

실행 결과 -> new other 시에 windows builder 가 있으면 성공.


Posted by 사라링

패키지 컴파일러

 | JAVA
2012. 5. 15. 18:37
  • 패키지 컴파일 방법
  1.  cmd> java -classpath classes;. com.example.model.BeerExpert

    - -classpath classes;. --> 뒤에 나올 클래스의 위치

    - com.example.model 은 classpath을 루트로 했을때 순서대로 있어야할 디렉토리(패키지는 디렉토리임)

 

Collection Class Sorting

  1. public class Pnode {
        private int start;
        private int end;
        private int max_vd_idx;
        private double max_vd_value;

        static public class PnodeComparator implements Comparator<Pnode>{

            public int compare(Pnode o1, Pnode o2) {
                return o1.start - o2.start;
            }

        }

    static void Main(String args[]){

  2. /* split_queue : list of pnodes */

  3. Collections.sort(split_queue, new Pnode.PnodeComparator());

  4. }

    }

이 글은 스프링노트에서 작성되었습니다.

Posted by 사라링

자바로 컴퓨터 종료

 | JAVA
2012. 5. 15. 18:36

 

import java.io.IOException;
import java.io.OutputStream;

public class Deepak {
 
 public static void main(String[] args) throws InterruptedException {
  Runtime runtime = Runtime.getRuntime();
  try {
   Process process = runtime.exec("C:\\WINDOWS\\system32\\cmd.exe");
   OutputStream os = process.getOutputStream();
   os.write("shutdown -s -f -t 90 \n\r".getBytes());
   os.close();
   process.waitFor();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

 

 

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

Swing - windowBuilder 설치 하기.  (0) 2012.06.13
패키지 컴파일러  (0) 2012.05.15
자바( 스크립트 사용 하여 리턴값 받기)  (0) 2012.05.15
어트리뷰트(애플릿)  (0) 2012.05.15
실시간 파일 변경 알림  (0) 2012.05.15
Posted by 사라링

 import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
 
public class RunJavaScript {
  public static void main(String args[]) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
    try {
      Double hour = (Doubleengine.eval("var date = new Date();" "date.getHours();");
      String msg;
      if (hour < 10) {
        msg = "Good morning";
      else if (hour < 16) {
        msg = "Good afternoon";
      else if (hour < 20) {
        msg = "Good evening";
      else {
        msg = "Good night";
      }
      System.out.println(hour);
      System.out.println(msg);
    catch (ScriptException e) {
      System.err.println(e);
    }
  }
}

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

패키지 컴파일러  (0) 2012.05.15
자바로 컴퓨터 종료  (0) 2012.05.15
어트리뷰트(애플릿)  (0) 2012.05.15
실시간 파일 변경 알림  (0) 2012.05.15
간단 수식계산기  (0) 2012.05.15
Posted by 사라링

어트리뷰트(애플릿)

 | JAVA
2012. 5. 15. 18:36

 

// AttribStringDemo.java

import java.applet.Applet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import java.awt.font.TextAttribute;

import java.text.AttributedString;

public class AttribStringDemo extends Applet
{
   AttributedString as;

   public void init()
   {
      as = new AttributedString("An AttributedString holds text and related "+
                                "attribute information.");
      as.addAttribute(TextAttribute.FONT,
                      new Font("Courier New"Font.BOLD, 12), 319);
      as.addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 319);
   }

   public void paint(Graphics g)
   {
      if (as != null)
      {
         ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                           RenderingHints.VALUE_ANTIALIAS_ON);
         g.drawString(as.getIterator(), 3030);
      }
   }
}




이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

자바로 컴퓨터 종료  (0) 2012.05.15
자바( 스크립트 사용 하여 리턴값 받기)  (0) 2012.05.15
실시간 파일 변경 알림  (0) 2012.05.15
간단 수식계산기  (0) 2012.05.15
String(문자열)내의 한글 확인  (0) 2012.05.15
Posted by 사라링

실시간 파일 변경 알림

 | JAVA
2012. 5. 15. 18:36

 테스트 파일 변경 소스 .

How to write Java code to listen runtime changes in text file

 
I had a requirement to write a java code to listen continues changing text file.i have used following code to do that.

public void listenServer() throws IOException {
Reader fileReader = new FileReader("/home/chamara/server.log");
BufferedReader input = new BufferedReader(fileReader);
String line = null;
while (true) {
if ((line = input.readLine()) != null) {
System.out.println(line);
continue;
}
try {
Thread.sleep(1000L);
} catch (InterruptedException x) {
Thread.currentThread().interrupt();
break;
}
}
input.close();
return isException;
}

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

자바( 스크립트 사용 하여 리턴값 받기)  (0) 2012.05.15
어트리뷰트(애플릿)  (0) 2012.05.15
간단 수식계산기  (0) 2012.05.15
String(문자열)내의 한글 확인  (0) 2012.05.15
Socket Simple 채팅 프로그램  (0) 2012.05.15
Posted by 사라링

간단 수식계산기

 | JAVA
2012. 5. 15. 18:35
Parse postfix arithmetic expressions
 
Parse
 
import java.io.IOException;
 
public class ParsePost {
  private Stack theStack;
 
  private String input;
 
  public ParsePost(String s) {
    input = s;
  }
 
  public int doParse() {
    theStack = new Stack(20);
    char ch;
    int j;
    int num1, num2, interAns;
 
    for (j = 0; j < input.length(); j++) {
      ch = input.charAt(j)
      theStack.displayStack("" + ch + " ");
      if (ch >= '0' && ch <= '9'// if a number push it
        theStack.push((int) (ch - '0'));   
      else // it's an operator
      {
        num2 = theStack.pop();
        num1 = theStack.pop();
        switch (ch) {
        case '+':
          interAns = num1 + num2;
          break;
        case '-':
          interAns = num1 - num2;
          break;
        case '*':
          interAns = num1 * num2;
          break;
        case '/':
          interAns = num1 / num2;
          break;
        default:
          interAns = 0;
        }
        theStack.push(interAns);
      }
    }
    interAns = theStack.pop();
    return interAns;
  }
 
  public static void main(String[] argsthrows IOException {
    String input = "1-2+3*4+5/6-7+8*9";
    int output;
    ParsePost aParser = new ParsePost(input);
    output = aParser.doParse();
    System.out.println("Evaluates to " + output);
  }
  class Stack {
    private int maxSize;
  
    private int[] stackArray;
  
    private int top;
  
    public Stack(int size) {
      maxSize = size;
      stackArray = new int[maxSize];
      top = -1;
    }
  
    public void push(int j) {
      stackArray[++top= j;
    }
  
    public int pop() {
      return stackArray[top--];
    }
  
    public int peek() {
      return stackArray[top];
    }
  
    public boolean isEmpty() {
      return (top == -1);
    }
  
    public boolean isFull() {
      return (top == maxSize - 1);
    }
  
    public int size() {
      return top + 1;
    }
  
    public int peekN(int n) {
      return stackArray[n];
    }
  
    public void displayStack(String s) {
      System.out.print(s);
      System.out.print("Stack (bottom>top): ");
      for (int j = 0; j < size(); j++) {
        System.out.print(peekN(j));
        System.out.print(' ');
      }
      System.out.println("");
    }
  }
}
 

 출처: http://www.java2s.com/Code/Java/Collections-Data-Structure/Parsepostfixarithmeticexpressions.htm

Parse postfix arithmetic expressions
 
Parse
 
import java.io.IOException;
 
public class ParsePost {
  private Stack theStack;
 
  private String input;
 
  public ParsePost(String s) {
    input = s;
  }
 
  public int doParse() {
    theStack = new Stack(20);
    char ch;
    int j;
    int num1, num2, interAns;
 
    for (j = 0; j < input.length(); j++) {
      ch = input.charAt(j)
      theStack.displayStack("" + ch + " ");
      if (ch >= '0' && ch <= '9'// if a number push it
        theStack.push((int) (ch - '0'));   
      else // it's an operator
      {
        num2 = theStack.pop();
        num1 = theStack.pop();
        switch (ch) {
        case '+':
          interAns = num1 + num2;
          break;
        case '-':
          interAns = num1 - num2;
          break;
        case '*':
          interAns = num1 * num2;
          break;
        case '/':
          interAns = num1 / num2;
          break;
        default:
          interAns = 0;
        }
        theStack.push(interAns);
      }
    }
    interAns = theStack.pop();
    return interAns;
  }
 
  public static void main(String[] argsthrows IOException {
    String input = "1-2+3*4+5/6-7+8*9";
    int output;
    ParsePost aParser = new ParsePost(input);
    output = aParser.doParse();
    System.out.println("Evaluates to " + output);
  }
  class Stack {
    private int maxSize;
  
    private int[] stackArray;
  
    private int top;
  
    public Stack(int size) {
      maxSize = size;
      stackArray = new int[maxSize];
      top = -1;
    }
  
    public void push(int j) {
      stackArray[++top= j;
    }
  
    public int pop() {
      return stackArray[top--];
    }
  
    public int peek() {
      return stackArray[top];
    }
  
    public boolean isEmpty() {
      return (top == -1);
    }
  
    public boolean isFull() {
      return (top == maxSize - 1);
    }
  
    public int size() {
      return top + 1;
    }
  
    public int peekN(int n) {
      return stackArray[n];
    }
  
    public void displayStack(String s) {
      System.out.print(s);
      System.out.print("Stack (bottom>top): ");
      for (int j = 0; j < size(); j++) {
        System.out.print(peekN(j));
        System.out.print(' ');
      }
      System.out.println("");
    }
  }
}
 
 

 

 

import java.io.IOException;
 
public class ParsePost {
  private Stack theStack;
 
  private String input;
 
  public ParsePost(String s) {
    input = s;
  }
 
  public int doParse() {
    theStack = new Stack(20);
    char ch;
    int j;
    int num1, num2, interAns;
 
    for (j = 0; j < input.length(); j++) {
      ch = input.charAt(j)
      theStack.displayStack("" + ch + " ");
      if (ch >= '0' && ch <= '9'// if a number push it
        theStack.push((int) (ch - '0'));   
      else // it's an operator
      {
        num2 = theStack.pop();
        num1 = theStack.pop();
        switch (ch) {
        case '+':
          interAns = num1 + num2;
          break;
        case '-':
          interAns = num1 - num2;
          break;
        case '*':
          interAns = num1 * num2;
          break;
        case '/':
          interAns = num1 / num2;
          break;
        default:
          interAns = 0;
        }
        theStack.push(interAns);
      }
    }
    interAns = theStack.pop();
    return interAns;
  }
 
  public static void main(String[] argsthrows IOException {
    String input = "1-2+3*4+5/6-7+8*9";
    int output;
    ParsePost aParser = new ParsePost(input);
    output = aParser.doParse();
    System.out.println("Evaluates to " + output);
  }
  class Stack {
    private int maxSize;
  
    private int[] stackArray;
  
    private int top;
  
    public Stack(int size) {
      maxSize = size;
      stackArray = new int[maxSize];
      top = -1;
    }
  
    public void push(int j) {
      stackArray[++top= j;
    }
  
    public int pop() {
      return stackArray[top--];
    }
  
    public int peek() {
      return stackArray[top];
    }
  
    public boolean isEmpty() {
      return (top == -1);
    }
  
    public boolean isFull() {
      return (top == maxSize - 1);
    }
  
    public int size() {
      return top + 1;
    }
  
    public int peekN(int n) {
      return stackArray[n];
    }
  
    public void displayStack(String s) {
      System.out.print(s);
      System.out.print("Stack (bottom>top): ");
      for (int j = 0; j < size(); j++) {
        System.out.print(peekN(j));
        System.out.print(' ');
      }
      System.out.println("");
    }
  }
}
 

 

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

어트리뷰트(애플릿)  (0) 2012.05.15
실시간 파일 변경 알림  (0) 2012.05.15
String(문자열)내의 한글 확인  (0) 2012.05.15
Socket Simple 채팅 프로그램  (0) 2012.05.15
SMS 보내기  (0) 2012.05.15
Posted by 사라링

 

public boolean containsHangul(String str)
{
    for(int i = 0 ; i < str.length() ; i++)
    {
        char ch = str.charAt(i);
        Character.UnicodeBlock unicodeBlock = Character.UnicodeBlock.of(ch);
        if(UnicodeBlock.HANGUL_SYLLABLES.equals(unicodeBlock) ||
                UnicodeBlock.HANGUL_COMPATIBILITY_JAMO.equals(unicodeBlock) ||
                UnicodeBlock.HANGUL_JAMO.equals(unicodeBlock))
            return true;
    }
    return false;
}

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

실시간 파일 변경 알림  (0) 2012.05.15
간단 수식계산기  (0) 2012.05.15
Socket Simple 채팅 프로그램  (0) 2012.05.15
SMS 보내기  (0) 2012.05.15
Printf 수식 모음  (0) 2012.05.15
Posted by 사라링

Socket Simple 채팅 프로그램

 | JAVA
2012. 5. 15. 18:35

서버

 

package kr.hun.mesange;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class ServerMessinger {
    ArrayList<EachThread> clients=new ArrayList<EachThread>();

    public static void main(String[] args) {
        new ServerMessinger();
    }
    public ServerMessinger(){
        try {
           
            ServerSocket serverSocket= new ServerSocket(7777);
            System.out.println("nomally Server Turn ON");
           
           
            while (true) {
               
                Socket socket = serverSocket.accept();
                EachThread buff=new EachThread(socket);
                clients.add(buff);
                buff.start();
                System.out.println("client"+socket);
                   
            }
           
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
   
    class EachThread extends Thread{
        Socket socket=null;
    public     DataInputStream dis = null;
    public     DataOutputStream dos = null;
       
       
        public EachThread(Socket socket){
            this.socket=socket;
        }
       
        public void run(){
           
           
            try {
                dis=new DataInputStream(socket.getInputStream());
                dos=new DataOutputStream(socket.getOutputStream());
               
                while (true) {
                    String msg=dis.readUTF();
                   
                    for(int i =0;i<clients.size();i++){
                        clients.get(i).dos.writeUTF(msg);
                    }
                   
                    if(msg.equals("exit")){
                        break;
                    }
                }
                clients.remove(this);
                System.out.println("exit by user's request ");
               
            } catch (Exception e) {
                // TODO Auto-generated catch block
                clients.remove(this);
                System.out.println("exit by system's error");
            }
       
       
        }
    }
   
}

클라이언트

package kr.hun.mesange;

import java.awt.EventQueue;

public class MessangerTest extends JFrame {
    public DataInputStream dis=null;
    public DataOutputStream dos=null;;
    private JPanel contentPane;
    private JTextField tfIP;
    private JScrollPane scrollPane;
    private JTextField tfword;
    private JTextField tfPORT;
   
    boolean connect =false;
    private JTextArea taResult;
   
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MessangerTest frame = new MessangerTest();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public MessangerTest() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 384, 547);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
       
        JButton btnSocket = new JButton("\uC811\uC18D");
        btnSocket.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                btnSocketGo();
            }
        });
        btnSocket.setBounds(261, 15, 73, 44);
        contentPane.add(btnSocket);
       
        tfIP = new JTextField();
        tfIP.setText("127.0.0.1");
        tfIP.setBounds(90, 15, 159, 22);
        contentPane.add(tfIP);
        tfIP.setColumns(10);
       
        scrollPane = new JScrollPane();
        scrollPane.setViewportBorder(null);
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setBounds(12, 85, 340, 354);
        contentPane.add(scrollPane);
       
        taResult = new JTextArea();
        taResult.setEnabled(false);
        scrollPane.add(taResult);
        scrollPane.setViewportView(taResult);
       
       
       
        tfword = new JTextField();
        tfword.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
            if(e.getKeyCode()==10){
                btnWordSend();
            }
            }
        });
       
        tfword.setFont(new Font("굴림", Font.PLAIN, 15));
        tfword.setBounds(12, 449, 340, 30);
        contentPane.add(tfword);
        tfword.setColumns(10);
       
        tfPORT = new JTextField();
        tfPORT.setText("7777");
        tfPORT.setColumns(10);
        tfPORT.setBounds(90, 47, 159, 22);
        contentPane.add(tfPORT);
       
        JLabel lblIP = new JLabel("I P       :");
        lblIP.setBounds(12, 20, 57, 15);
        contentPane.add(lblIP);
       
        JLabel lblPort = new JLabel("PORT   :");
        lblPort.setBounds(12, 50, 57, 15);
        contentPane.add(lblPort);
       
       
       
    }
    public void btnWordSend(){
        if(connect==true){
       
            String msg=tfword.getText();
            tfword.setText("");
            try {
                dos.writeUTF("ID:sararing :: "+msg);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(msg.equals("exit"))System.exit(0);
        }else {
            tfword.setText("");
            taResult.append("서버에 접속 해야만 채팅이 가능 합니다. \n");
        }
       
    }
    public void btnSocketGo(){
        String str=tfIP.getText();

        int port = Integer.parseInt(tfPORT.getText());
       
        try {
           
            Socket socket = new Socket(str,port);
            taResult.append("서버에 성공적으로 접속되었습니다...\n");
           
            connect=true;
            dis=new DataInputStream(socket.getInputStream());
            dos=new DataOutputStream(socket.getOutputStream());
            new EachThread().start();


        } catch (Exception e) {
            taResult.append("서버가 작동 하지 않거나.\n IP,PORT 를 확인해주세요.\n ");
        }
    }

    class EachThread extends Thread{
        public void run(){
            while(true){
            try {
                String msg=    dis.readUTF();
                taResult.append(msg+"\n");
                taResult.setSelectionStart(taResult.getText().length());  // 스크롤펜이 내려 가면서 최신화 시켜서 밑에 줄에 위치 할수 있도록 한다.
               
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }
        }
    }
}

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

간단 수식계산기  (0) 2012.05.15
String(문자열)내의 한글 확인  (0) 2012.05.15
SMS 보내기  (0) 2012.05.15
Printf 수식 모음  (0) 2012.05.15
passwd 암호화  (0) 2012.05.15
Posted by 사라링

SMS 보내기

 | JAVA
2012. 5. 15. 18:35

HTTP POST 프로토콜로 모 휴대폰 문자 서비스 웹사이트로 자동접속 하여 휴대폰으로 문자 메시지를 보내 주는 소스 입니다.

고가의 SMS 단문메시지 전송 솔루션이 있지만 간단하게 웹사이트 장애나, 모니터링 용도로 자신의 시스템에 SMS 기능을 간단히 접목 시킬수 있습니다.

 

 

 

 

/**
 * @(#) SMS.java
 * Copyright 1999-2003 by  Java Service Network Community, KOREA.
 * All rights reserved.  http://www.javaservice.net
 *
 * NOTICE !      You can copy or redistribute this code freely,
 * but you should not remove the information about the copyright notice
 * and the author.
 *
 * @author  WonYoung Lee, javaservice@hanmail.net
 */
import java.net.*;
import java.io.*;
import java.util.StringTokenizer;
public class SMS {
    public final static String SERVER =  "www.smsphone.co.kr";
    public final static int PORT =  80;
    public static boolean TRACE = false;

    public static void main(String[] args) throws Exception
    {
        if ( args.length < 5 ) {
            System.out.println("Copyright 1999-2003 by  Java Service Network Community, KOREA.");
            System.out.println("All rights reserved. http://www.javaservice.net, javaservice@hanmail.net");
            System.out.println("Note: you shoud have id/passwd on http://www.smsphone.co.kr");
            System.out.println("      But, I hove no relationship with the SMSPHONE.co.kr web site.");
            System.out.println();
            System.out.println("Usage: java SMS <id> <passwd> <sender> <tolist> \"<message>\"");
            System.out.println("Ex: java SMS 0118987904 MyPasswd 0118987904 0118987904 재밌지?");
            System.out.println("Ex: java SMS 0118987904 MyPasswd 0118987904 0118987904;0118986266 \"햐~ 신기하지?\"");
            System.out.println("Ex: java -Dsms.trace=true SMS 0118987904 MyPasswd 0118987904 0118987904 \"trace할려구?\"");
            System.out.println("Ex: java -DproxySet=true -DproxyHost=proxy.our.com -DproxyPort=80 SMS \\");
            System.out.println("       0118987904 MyPasswd 0118987904 0118987904 \"프락시서버가 있다구?\"");
            System.out.println();
            System.exit(1);
        }
        if( "true".equals(System.getProperty("sms.trace"))) TRACE = true;
        sendsms(args[0], args[1], args[2], args[3],args[4]);
        System.out.println("Message sent to " + args[3] + " successfully.\n");
        System.out.println("Copyright 1999-2003 by  Java Service Network Community, KOREA.");
        System.out.println("All rights reserved. http://www.javaservice.net, javaservice@hanmail.net");
        System.out.println("Note: I hove no relationship with the SMSPHONE.co.kr web site.");
    }

    public static void sendsms(String id, String pwd, String returnphone, String tolist, String msg) throws Exception
    {
        if(TRACE) System.out.print("> login to http://" + SERVER + "/login_ok.asp");
        Socket socket =  new Socket(SERVER,PORT);
        if(TRACE) System.out.println("connected");
        InputStream in = null;
        OutputStream out = null;
        try{
            in = socket.getInputStream();
            out = socket.getOutputStream();
            //==========================================================
            // 1. login to www.smsphone.co.kr
            String sessionid = null;
            try{
                java.util.Hashtable data = new java.util.Hashtable();
                data.put("id", id); 
                data.put("pwd", pwd);
                //sessionid = http_post_send(in,out,"/login_ok.asp","",url_encoding(data),"parent.location.href='index.asp'");
            }
            catch(Exception e){
                throw new Exception( "login failed: " + e.toString());
            }

            //==========================================================
            // 2. SMS send to www.smsphone.co.kr
            try{
                java.util.Hashtable data = new java.util.Hashtable();
                data.put("mode", "1"); 
                data.put("ResGubn", "0");
    tolist = tolist.endsWith(";") ? tolist : tolist + ";"; // bug(?) patch ....
                data.put("SendList", tolist);
                data.put("SendLenCount", ""+(new StringTokenizer(tolist,";")).countTokens());
                data.put("returnNumber", returnphone);
                data.put("Message", msg);
                data.put("msgLen", ""+msg.getBytes().length );
                //http_post_send(in,out,"/send_msg.asp", sessionid, url_encoding(data),":"+id);
    System.out.println(data.toString());
            }
            catch(Exception e){
                throw new Exception( "login success but message send failed: " + e.toString());
            }
            //==========================================================
        }
        finally {
            if ( in != null ) try{in.close();}catch(Exception e){}
            if ( out != null ) try{out.close();}catch(Exception e){}
            if ( socket != null ) try{socket.close();}catch(Exception e){}
        }
    }

    private static String url_encoding(java.util.Hashtable hash){
        if ( hash == null ) throw new IllegalArgumentException("argument is null");
        java.util.Enumeration enum = hash.keys();
        StringBuffer buf = new StringBuffer();
        boolean isFirst = true;
        while(enum.hasMoreElements()){
          if (isFirst) isFirst = false;
          else buf.append('&');
          String key = (String)enum.nextElement();
          String value = (String)hash.get(key);
          buf.append(java.net.URLEncoder.encode(key));
          buf.append('=');
          buf.append(java.net.URLEncoder.encode(value));
        }
        return buf.toString();
    }
  

    public void setProxy(String host, String port, String id, String password) {
        // java -DproxySet=true -DproxyHost=proxy.our.com -DproxyPort=80 SMS \
        // Ex:       0118987904 MyPasswd 0118987904 0118987904 "프락시서버가 있다구?"
        java.util.Properties props = System.getProperties();
        props.put( "proxySet", "true" );
        props.put( "proxyHost", host );
        props.put( "proxyPort", port );
        System.setProperties(props);
        /*
        if ( id != null ) {
            String pw = id + ":" + password;
            String encodedPassword = com.sun.mail.imap.protocol.BASE64MailboxEncoder.encode( pw );
            httpURLConn.setRequestProperty( "Proxy-Authorization", encodedPassword );
        }
        */
    }

    private static String http_post_send(InputStream in, OutputStream out, String url, String sessionid, String body, String return_ok_str ) throws Exception
    {
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)));
        String header =
            "POST " + url + " HTTP/1.0\n" +
            //"Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*\n" +
            "Accept-Language: ko\n" +
            "Content-Type: application/x-www-form-urlencoded\n" +
            "Accept-Encoding: gzip, deflate\n" +
            "User-Agent: SMS_API(http://www.javaservice.net)\n" +
            "Host: " + SERVER + "\n" +
            "Content-Length: " + body.getBytes().length + "\n" +
            "Cookie: " + sessionid + "\n" +
            "Connection: Keep-Alive\n" +
            "Cache-Control: no-cache\n";
        if(TRACE){
          System.out.println("> -----------------------------------------------------------------------------");
          System.out.print(header);
          System.out.println(); // dummy line
        }
        pw.print(header);
        pw.println(); // dummy line
        pw.flush();

        if(TRACE) System.out.println(body);
        pw.print(body);
        pw.flush();
        if(TRACE){
          System.out.println("> -----------------------------------------------------------------------------");
          System.out.println("> header & data flushed");
          System.out.println("> now, wait response .....");
          System.out.println("> -----------------------------------------------------------------------------");
        }

        StringBuffer buf = new StringBuffer();
        int length = -1;
        String line = null;
        while( ( line = read_line(in)) != null ) {
            if(TRACE) System.out.println(line);
            if ( line.length() == 0 ) break;
            int x = line.indexOf("Content-Length:");
            if ( x > -1 ) {
                length = Integer.valueOf(line.substring(x+16)).intValue();
                if(TRACE) System.out.println("LENGTH:" + length);
            }
            int y = line.indexOf("Set-Cookie:");
            if ( y > -1 ) {
                sessionid = line.substring(y+12);
                int z = sessionid.indexOf("path");
                if ( z > -1 ) sessionid = sessionid.substring(0, z);
                if(TRACE) System.out.println("COOKIE:" + sessionid);
            }
        }
        if ( line == null ) throw new Exception("unexcepted header data format");

        if ( length != -1 ) {
            // (mayby) HTTP 1.1 "Content-Length" field exist in the header.
            byte[] d = read_data(in,length);
            buf.append(new String(d));
            if(TRACE) System.out.println(new String(d));
        }
        else {
            // NO "Content-Length" field exist in the header
            String length_hex = read_line(in);
            if ( length_hex == null ) throw new Exception("there is no HTTP body data");
            try{
                length = Integer.valueOf(length_hex.trim(),16).intValue();
            }
            catch(Exception e){
                //This means, the following data is just normal BODY data.
                //And length is still -1.
            }
            if ( length != -1 ) {
                // Yap. WebSphere 3.0.x, 3.5.x
                read_line(in); // dummy line
                byte[] d = read_data(in,length);
                buf.append(new String(d));
                if(TRACE) System.out.println(new String(d));
            }
            else {
                byte[] d = read_data(in);
                buf.append(new String(d));
                if(TRACE) System.out.println(new String(d));
            }
        }
        if( buf.toString().indexOf(return_ok_str) == -1) throw new Exception("No Excepted Result.\n"+ buf.toString());
        return sessionid;
    }
   
    public static final int INTPUTSTREAM_READ_RETRY_COUNT = 10;

    /**
     * The <code>read_data</code> method of <code>SocketUtil</code> reads the
     * specified length of bytes from the given input stream.
     *
     * @param      in   an inputstream
     * @param      len  the number of bytes read.
     * @return     The specified number of bytes read until the end of
     *             the stream is reached.
     * @exception  Exception  if an I/O error or unexpected EOF occurs
     */
    private static byte[] read_data(InputStream in, int len) throws Exception {
        java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
        int bcount = 0;
        byte[] buf = new byte[2048];
        int read_retry_count = 0;
        while( bcount < len ) {
            int n = in.read(buf,0, len-bcount < 2048 ? len-bcount : 2048 );
            // What would like to do if you've got an unexpected EOF before
            // reading all data ?
            //if (n == -1) break;
            if ( n == -1 ) throw
                 new java.io.IOException("inputstream has returned an unexpected EOF");

            if ( n == 0 && (++read_retry_count == INTPUTSTREAM_READ_RETRY_COUNT) )
                throw new java.io.IOException("inputstream-read-retry-count( " +
                    INTPUTSTREAM_READ_RETRY_COUNT + ") exceed !");
            if ( n != 0 ) {
                bcount += n;
                bout.write(buf,0,n);
            }
        }
        bout.flush();
        return bout.toByteArray();
    }

    /**
     * The <code>read_data</code> method of <code>SocketUtil</code> reads all
     * the bytes from the given inputstream until the given input stream
     * has not returned an EOF(end-of-stream) indicator.
     *
     * @param      in   an inputstream
     * @return     all bytes read if the end of the stream is reached.
     * @exception  Exception  if an I/O error occurs
     */
    private static byte[] read_data(InputStream in) throws Exception {
        java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
        int bcount = 0;
        byte[] buf = new byte[2048];
        int read_retry_count = 0;
        while( true ) {
            int n = in.read(buf);
            if (n == -1) break;
            if ( n == 0 && (++read_retry_count == INTPUTSTREAM_READ_RETRY_COUNT) )
                throw new java.io.IOException("inputstream-read-retry-count( " +
                    INTPUTSTREAM_READ_RETRY_COUNT + ") exceed !");
            if ( n != 0 ) {
                bcount += n;
                bout.write(buf,0,n);
            }
        }
        bout.flush();
        return bout.toByteArray();
    }
 
    /**
     * Read a line of text.  A line is considered to be terminated by a line
     * feed ('\n') or a carriage return followed immediately by a linefeed.
     *
     * @return     A String containing the contents of the line, not including
     *             any line-termination characters, or null if the end of the
     *             stream has been reached
     *
     * @exception  IOException  If an I/O error occurs
     */
    private static String read_line(InputStream in) throws Exception {
        java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
        boolean eof = false;
        while( true ) {
            int b = in.read();
            if (b == -1) { eof = true; break;}
            if ( b != '\r' && b != '\n' ) bout.write((byte)b);
            if (b == '\n') break;
        }
        bout.flush();
        if ( eof && bout.size() == 0 ) return null;
        //Or return ""; ? what's fit for you?
        return bout.toString();
    }
}

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

String(문자열)내의 한글 확인  (0) 2012.05.15
Socket Simple 채팅 프로그램  (0) 2012.05.15
Printf 수식 모음  (0) 2012.05.15
passwd 암호화  (0) 2012.05.15
OS CPU MEMORY 값 보여주기  (0) 2012.05.15
Posted by 사라링

Printf 수식 모음

 | JAVA
2012. 5. 15. 18:33

java_printf.jpg 

Printf 와 SimpleFormatDate

http://blog.naver.com/burberry5/90132916326

달력

http://blog.naver.com/burberry5/90132916893

 

public class PrintEx {
 public static void main(String[] args) {
 char ch = '가';
 int i = 77;
 float f= 3.33f;
 String str="가나다";
 System.out.printf("문자 ch=%c입니다\n",ch);
 System.out.printf("문자열 str=%s입니다\n",str);
 System.out.printf("실수 f=%f, %e입니다\n",f,f);
 System.out.printf("문자 ch=%c입니다\n문자열 str=%s입니다\n 실수 f=%f, %e입니다\n",ch,str,f,f);
//"10진수 100은 8진수로 xx이고, 16진수는 xx입니다.)  
 System.out.printf("10진수 %d은 8진수로 %o이고, 16진수로 %x \n",i,i,i);
 
 }
}

 

 

 

 

 

 

 

 

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

Socket Simple 채팅 프로그램  (0) 2012.05.15
SMS 보내기  (0) 2012.05.15
passwd 암호화  (0) 2012.05.15
OS CPU MEMORY 값 보여주기  (0) 2012.05.15
유니코드 표  (0) 2012.05.08
Posted by 사라링

passwd 암호화

 | JAVA
2012. 5. 15. 18:33

 

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 *
 * @author
 */
public class strEnDeConvert {

    private  byte[] hexaMap = {0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68};

    protected  byte[] getHexaEncodingBytes(byte[] src)
 {
        byte[] buffer=new byte[src.length*2];
        int index=0;

  System.out.println("src.length="+ src.length);  

        for (int i=0; i < src.length; i++)
  {   buffer[index++] = hexaMap[ ( (src[i]&0xf0) >> 4 ) ];
            buffer[index++] = hexaMap[ ( src[i]&0x0f ) ];
        }
  return buffer;
    }

    protected  String getHexaEncoding(byte[] src,String charSet) throws UnsupportedEncodingException
 {
        byte[] strBytes=getHexaEncodingBytes(src);
        return new String(strBytes,charSet);
    }

    protected  String getHexaEncoding(byte[] src)
 {
        byte[] strBytes=getHexaEncodingBytes(src);
        return new String(strBytes);
    }

    /**
     * Digest 알고리즘을 수행한다.
     */
    public String getDigest(String str, String digest, String charset) {
        try
  {   MessageDigest md = MessageDigest.getInstance(digest);
            try
   {   byte[]      raw = str.getBytes(charset);
                byte[] digested = md.digest(raw);
                System.out.println("digested.length="+ digested.length); 
    System.out.println("str.length="+ str.length());

    return getHexaEncoding(digested, charset);
            } catch (UnsupportedEncodingException e) {
            } 
  } catch (NoSuchAlgorithmException e) {
        }       
        return str;
    }
 
 // Test
 public static void main(String[] args) throws Exception
 {
  strEnDeConvert ec = new strEnDeConvert();
  Defines        df = new Defines();
  System.out.println(ec.getDigest("1111122222333334445",df.PASSWORD_DIGEST, df.PASSWORD_CHARSET));
 }

}

 

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

SMS 보내기  (0) 2012.05.15
Printf 수식 모음  (0) 2012.05.15
OS CPU MEMORY 값 보여주기  (0) 2012.05.15
유니코드 표  (0) 2012.05.08
SqlExploler(eclipse)  (0) 2012.05.08
Posted by 사라링

OS CPU MEMORY 값 보여주기

 | JAVA
2012. 5. 15. 18:33

 

[소스]

import java.io.File;
import java.lang.management.ClassLoadingMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadMXBean;

import com.sun.management.OperatingSystemMXBean;

/**
 * @co.kr.codein
 * @author yonghoon
 * 
 */

public class UseMxBean
{

  
/**
 * @param args
 */

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    new UseMxBean();
  }

  
/*
 * 디스크용량
 */

  private void showDisk() {
    File root = null;

    try {
      root = new File("/");

      System.out.println("Total Space: " + toMB(root.getTotalSpace()));
      System.out.println("Usable Space: " + toMB(root.getUsableSpace()));
      
      /* added by cafe mocha */
      System.exit(0);

    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  
/*
 * cpu 사용량
 */

  private void showCPU() {
    OperatingSystemMXBean osbean = (OperatingSystemMXBean) ManagementFactory
      .getOperatingSystemMXBean();
    RuntimeMXBean runbean = (RuntimeMXBean) ManagementFactory
      .getRuntimeMXBean();

    long bfprocesstime = osbean.getProcessCpuTime();
    long bfuptime = runbean.getUptime();
    long ncpus = osbean.getAvailableProcessors();

    for (int i = 0; i < 1000000; ++i) {
      ncpus = osbean.getAvailableProcessors();
    }

    long afprocesstime = osbean.getProcessCpuTime();
    long afuptime = runbean.getUptime();

    float cal = (afprocesstime - bfprocesstime)
      / ((afuptime - bfuptime) * 10000f);

    float usage = Math.min(99f, cal);

    System.out.println("Calculation: " + cal);
    System.out.println("CPU Usage: " + usage);

  }

  private void showRuntime() {
    RuntimeMXBean runbean = (RuntimeMXBean) ManagementFactory
      .getRuntimeMXBean();

  }

  
/*
 * 메모리 사용량
 */

  private void showMemory() {
    MemoryMXBean membean = (MemoryMXBean) ManagementFactory
      .getMemoryMXBean();

    MemoryUsage heap = membean.getHeapMemoryUsage();
    System.out.println("Heap Memory: " + heap.toString());

    MemoryUsage nonheap = membean.getNonHeapMemoryUsage();
    System.out.println("NonHeap Memory: " + nonheap.toString());

  }

  private void showClassLoading() {
    ClassLoadingMXBean classbean = (ClassLoadingMXBean) ManagementFactory
      .getClassLoadingMXBean();

    System.out.println("TotalLoadedClassCount: "
        + classbean.getTotalLoadedClassCount());
    System.out.println("LoadedClassCount: "
        + classbean.getLoadedClassCount());
    System.out.println("UnloadedClassCount: "
        + classbean.getUnloadedClassCount());

  }

  private void showThreadBean() {
    ThreadMXBean tbean = (ThreadMXBean) ManagementFactory.getThreadMXBean();

    long[] ids = tbean.getAllThreadIds();

    System.out.println("Thread Count: " + tbean.getThreadCount());

    for (long id : ids) {
      System.out.println("Thread CPU Time(" + id + ")"
          + tbean.getThreadCpuTime(id));
      System.out.println("Thread User Time(" + id + ")"
          + tbean.getThreadCpuTime(id));
    }

  }

  
/**
 * OS 정보
 */

  private void showOSBean() {

    OperatingSystemMXBean osbean = (OperatingSystemMXBean) ManagementFactory
      .getOperatingSystemMXBean();

    System.out.println("OS Name: " + osbean.getName());
    System.out.println("OS Arch: " + osbean.getArch());
    System.out.println("Available Processors: "
        + osbean.getAvailableProcessors());
    System.out.println("TotalPhysicalMemorySize: "
        + toMB(osbean.getTotalPhysicalMemorySize()));
    System.out.println("FreePhysicalMemorySize: "
        + toMB(osbean.getFreePhysicalMemorySize()));
    System.out.println("TotalSwapSpaceSize: "
        + toMB(osbean.getTotalSwapSpaceSize()));
    System.out.println("FreeSwapSpaceSize: "
        + toMB(osbean.getFreeSwapSpaceSize()));
    System.out.println("CommittedVirtualMemorySize: "
        + toMB(osbean.getCommittedVirtualMemorySize()));
    System.out.println("SystemLoadAverage: "
        + osbean.getSystemLoadAverage());

  }

  public UseMxBean() {
    seperator(); showOSBean();
    seperator(); showThreadBean();
    seperator(); showClassLoading();
    seperator(); showMemory();
    seperator(); showDisk();
    seperator(); showCPU();
    seperator();
  }
  
  /* added cafe mocha 2009-06 */
  private void seperator() {
    System.out.println("-----------------------------------------------");
  }
  /* added cafe mocha 2009-06 */
  private String toMB(long size)
  {
    return (int)(size/(1024*1024))+"(MB)";
  }


 

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

Printf 수식 모음  (0) 2012.05.15
passwd 암호화  (0) 2012.05.15
유니코드 표  (0) 2012.05.08
SqlExploler(eclipse)  (0) 2012.05.08
자바 EXE 만들기.  (0) 2012.05.08
Posted by 사라링

유니코드 표

 | JAVA
2012. 5. 8. 18:32

유니코드표.png 

이 글은 스프링노트에서 작성되었습니다.


'JAVA' 카테고리의 다른 글

passwd 암호화  (0) 2012.05.15
OS CPU MEMORY 값 보여주기  (0) 2012.05.15
SqlExploler(eclipse)  (0) 2012.05.08
자바 EXE 만들기.  (0) 2012.05.08
JDBC  (0) 2012.05.08
Posted by 사라링

SqlExploler(eclipse)

 | JAVA
2012. 5. 8. 18:32

== 이클립스에 JDBC 에 연동 하여 sqlplus 처럼 사용 하는 것이다.

http://sourceforge.net/projects/eclipsesql/  에서 다운 받아 이클립스 폴더 에 덮어 쒸운다. 무거 우므로 따로 이클립스를 만든후 사용 하는게 좋다.

이클립스를 사용 중이라면 사용 종료후 재시작 을 한다./ 맨처음 로딩에 시간이 좀 걸린다...

 

SqlExploer.jpg

 

preperenc-> SQL Exploler  -> auto commit  제거

 

오른쪽 위에 open perspective -> other ->Sql Exploler 선택

 

왼쪽에 Connection 에서 마우스 오른쪽 버튼 -> new Connect 클립 한다. Name 은 사용자의 이름 적고 (아무거나.)

나머지는 그림 따라서 알아서 하삼.

user 에는 사용자 계정 아이디를 반드시 적어야함.

SqlExploer_00005.jpg SqlExploer_00005_00000.jpg SqlExploer_00005_00001.jpg SqlExploer_00005_00002.jpg SqlExploer_00005_00003.jpg   

 

 

    

 

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

OS CPU MEMORY 값 보여주기  (0) 2012.05.15
유니코드 표  (0) 2012.05.08
자바 EXE 만들기.  (0) 2012.05.08
JDBC  (0) 2012.05.08
VisualSVN  (0) 2012.05.08
Posted by 사라링

자바 EXE 만들기.

 | JAVA
2012. 5. 8. 18:32
 


 




준비물

1. JDK 설치와 환경변수 설정 (http://heartcrack.tistory.com/entry/JDK-다운로드와-환경변수-설정)

링크참조


2. 이클립스 다운로드(http://www.eclipse.org/downloads/)


3. JSmooth 를 다운로드 한뒤 컴퓨터에 설치




실행방법

1. 이클립스를 들어가서 해당하는 소스 파일을 연다.




2. FILE - EXPORT를 클릭한다. 그리고 Runnable jar file을 클릭 --> Next !

 

 

 

 

3.Launch Configuration에서 적절한 파일을 찾아 주고 추출 목적지에는 Jar파일이 저장될 곳을


지정해준다. 그다음 Finish를 눌러서 JAR파일을 생성해준다

 



4. JAR파일이 생성된것을 확인하고 이제 JSmooth를 실행해보자!

JSmooth의 첫페이지.



5. (불러오기를 하지 않은채로) 왼쪽탭에서 Skeleton을 클릭한다.

console wrapper는 콘솔 프로그램이고 windows wrapper는 윈도우 프로그램이다.

윈도우 프로그램을 선택했다면 첫번째 박스를 체크해준다. 나는 콘솔프로그램으로 진행



6. 그다음으로 이제 Executable탭에서

binary에는 저장될 파일명을 기록해 준다( exe확장자로 끝나도록)

그담에 icon에서는 ...을 눌러서 그림같은것들을 지정할수 있다.

이것이 exe파일의 아이콘이 되는데 바로가기 같은것을 해버리면,

컴파일이 실패 해버리므로. 적당한게 없으면 그냥 공백으로 두어도 좋다.


7. 그다음엔 Application 탭에 들어가서

   1번의 추가 버튼으로 2번의 JAR파일을 class path에 등록시킨 다음

   3번의 탭을 클릭해서 밑에 보이는 스샷처럼 메인 클래스(실행클래스 -public class)를 지정해준다.

 

 

    Embbeded jar 는 jar파일을 실행 파일에 포함시키는지에 대한 여부이다.



8. 그다음탭에 들어가서는 자바 VM ware의 버전을 적어 준다.

나는 1.7 버전을 기입.




9. 메모리에 대한 세팅을 한다 . 안해주어도 무방하다.


 11. 표시된 해골모양 또는, 프로젝트-컴파일을 클릭한다.

컴파일이 실패했다고 메시지가 떴다면 앞의 과정중에서 다른것이 잘못된것이다.


12. 바탕화면에 jsmooth로 확장자가 끝나는 파일과

 


exe파일이 생성되었다(나는 아이콘을 지정하지 않아서 기본모양으로 생성됨)

더블클릭해보면 잘 실행되는것을 알수있다.


이렇게 해서 JAVA파일 EXE 만들기 끗 ^ㅅ^

(참고: JDK가 설치된 컴퓨터에서만 EXE파일이 유효하니 알아두길)

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

유니코드 표  (0) 2012.05.08
SqlExploler(eclipse)  (0) 2012.05.08
JDBC  (0) 2012.05.08
VisualSVN  (0) 2012.05.08
JAVA 에러코드  (0) 2012.05.08
Posted by 사라링

BLOG main image
.. by 사라링

카테고리

사라링님의 노트 (301)
JSP (31)
J-Query (41)
JAVA (24)
VM-WARE (0)
디자인패턴 (1)
스크랩 (0)
스트러츠 (3)
안드로이드 (11)
오라클 (45)
우분투-오라클 (1)
이클립스메뉴얼 (6)
스프링3.0 (23)
자바스크립트 (10)
HTML5.0 (17)
정보처리기사 (1)
기타(컴퓨터 관련) (1)
문제점 해결 (3)
프로젝트 (2)
AJAX (4)
하이버네이트 (3)
트러스트폼 (11)
Jeus (2)
재무관리(회계) (5)
정규식 (5)
아이바티스 (8)
취미 (2)
소프트웨어 보안 관련모음 (0)
정보보안기사 (6)
C언어 베이직 및 프로그램 (3)
보안 관련 용어 정리 (2)
넥사크로 (6)
Total :
Today : Yesterday :