반응형

 

 

 

package kr.co.xxx;

import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;  
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 
 
import org.junit.Before;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult; 
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 

import org.json.simple.JSONObject;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DbserverApplication.class)
@WebAppConfiguration
public class DbserverApplicationTests {

Logger log = LoggerFactory.getLogger(DbserverApplication.class);
 
    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;

  

public void logPrint(String Name) {
log.info(" ");
log.info("=======================================================");
log.info(" ");

log.info(Name);

log.info(" ");
log.info("=======================================================");
log.info(" ");
}

public void endLogPrint() {
log.info(" ");
log.info("=======================================================");
log.info(" ");
}



    @Before 
    public void setUp() throws Exception {  
     logPrint("Set Up");
    
     // 이곳에서 DbserverController를 MockMvc 객체로 만듭니다.   
        
     mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();      
        
        endLogPrint();
         
        
         
    } 

    /*
    @Test
    public void testIsRunning() throws Exception { 
     logPrint("ISRunning");
    
     mockMvc.perform(get("/ping")
            )
     .andDo(print())                // 출력
     .andExpect(status().isOk());   // 정상 결과 예상
    
    
    
     endLogPrint();
    }
      
    

    
    @SuppressWarnings("unchecked")
@Test
    public void testGetVideoInfo() throws Exception { 
     log.info("GetVideoInfo");
    
     // 전체 JSON Object 담을 정보
     //JSONArray mapArray = new JSONArray();
    
     // 한개의 정보가 들어갈 JSONObject 선언
     JSONObject mapInfo = new JSONObject();
    
     // 정보 입력
     mapInfo.put("xmin", "-111.46727710962297");
     mapInfo.put("ymin", "20.462022433054965" );
     mapInfo.put("xmax", "-110.46727710962297");
     mapInfo.put("ymax", "21.96517113846002"  );
    
     // Array 값 추가
     //mapArray.add(mapInfo);  
        
     mockMvc.perform(post("/getVideoInfo") 
     .header("Accept", "application/json")
     .contentType("application/json")
     .characterEncoding("utf-8") 
     .content(mapInfo.toString()) 
     )
.andDo(print())                // 출력
.andExpect(status().isOk())    // 정상결과 예상 
                ;
         
    
     endLogPrint();
    }         
    
    */

    
    @Test
    public void testIsRunning() throws Exception { 
     logPrint("ISRunning");
    
     MvcResult result = this.mockMvc.perform(get("/ping")
                                )
                 //.andDo(print())                // 출력
        .andExpect(status().isOk())    // 정상 결과 예상
        .andReturn()
        ;   
    
    
     // 결과를 받는 String
     String content = result.getResponse().getContentAsString();
      
     // 예상 결과 
     // 첫문장 비교해서 오류 발생하면 문제가 있는 것임
     assertEquals("I'm Alive!", content ); 
    
     endLogPrint();
    }
      
    
    
    @SuppressWarnings({ "unchecked" })
@Test(timeout = 100000)   // Timeout 시간 설정 (단위 : milliseconds)
    public void testGetVideoInfo() throws Exception {
      
    
     log.info("GetVideoInfo");
    
     // 전체 JSON Object 담을 정보
     //JSONArray mapArray = new JSONArray();
    
     // 한개의 정보가 들어갈 JSONObject 선언
     JSONObject mapInfo = new JSONObject();
    
     // 정보 입력
     mapInfo.put("xmin", "-111.46727710962297");
     mapInfo.put("ymin", "20.462022433054965" );
     mapInfo.put("xmax", "-95.15257984399797" );
     mapInfo.put("ymax", "22.96517113846002"  );
    
     // Array 값 추가
     //mapArray.add(mapInfo);   
        
     MvcResult result = this.mockMvc.perform(post("/getVideoInfo")              
     .header("Accept", "application/json")
     .contentType("application/json")
     .characterEncoding("utf-8") 
     .content(mapInfo.toString()) 
     ) 
//.andDo(print())                // 출력 (결과가가 길면 출력을 생략하는 것이 좋음)
.andExpect(status().isOk())    // 정상결과 예상 
.andReturn()
                ;
    
     
     // 결과를 받는 String
     String content = result.getResponse().getContentAsString();
    
     // ,를 기준으로 첫번째 값만 받아옴
     String [] con_list = content.split(",");
    
     // 정상 반환 여부를 확인하기 위해 첫번째 값 별도로 재저장
     String [] first_con = con_list[0].split(":");
    
     //result.
     log.info("first_con[0]  : " + first_con[0]); 
    
     // 예상 결과 
     // 첫문장 비교해서 오류 발생하면 문제가 있는 것임
     assertEquals("[{\"video_sn\"", first_con[0] ); 
    
     endLogPrint();
    }         
 
    
} // end of Class

반응형
반응형

impdp ORA-31640 ORA-31693 ORA-19505 ORA-27037


금일 IMPDP 명령어로


상콤하게 import 작업을 하다가 위와 같은 ora 에러르 만났다...


처음엔 깜놀 했다가


parallel 옵션 을 사용할 때 dump 파일을 모든 rac 노드가  읽지 못하기 때문이라고 알게되었다


cluster=N 옵션을 통해 해결 가능하다


아래는 원문이다.


When I am trying to import schema, The impdp is failed to open dump file. see below script I am using.

$ cat parfile.par
USERID='/ as sysdba'
DIRECTORY=IMP_DP
DUMPFILE=SMARTSUPPY_SCHEMA.dmp
logfile=SMARTSUPPY_SCHEMA_09nov2014.log
parallel=10
SCHEMAS='SMARTSUPPY_SCHEMA'

I got below error while import..

ORA-31693: Table data object "SMARTSUPPY_SCHEMA"."BPM_TRANS_90000":"P297" failed to load/unload and is being skipped due to error:
ORA-31640: unable to open dump file "/export/APSDBSR-1351/SMARTSUPPY_SCHEMA.dmp" for read
ORA-19505: failed to identify file "/export/APSDBSR-1351/SMARTSUPPY_SCHEMA.dmp"
ORA-27037: unable to obtain file status
Linux-x86_64 Error: 2: No such file or directory
Additional information: 3
. . imported "SMARTSUPPY_SCHEMA"."BPM_TRANS_90000":"P315"      265.3 MB 1484775 rows
. . imported "SMARTSUPPY_SCHEMA"."TRC_HOP_T_90000":"P139"      219.7 MB 1402774 rows

The issue is due to I am using PARALLEL=10, so the dump file directory not being accessible from all nodes in the RAC. When we use PARALLEL > 1 option the child thread will be started in other node to complete the job faster, when job started in other node the dump file can't access the file. Due to this we receive this error. To fix the issue either you place the dump file to be accessed from all the nodes in that RAC environment or use cluster=N option.

Added cluster=N parameter in parfile and started the import again. 

$ cat parfile.par
USERID='/ as sysdba'
DIRECTORY=IMP_DP
DUMPFILE=SMARTSUPPY_SCHEMA.dmp
logfile=SMARTSUPPY_SCHEMA_09nov2014.log
parallel=10
SCHEMAS='SMARTSUPPY_SCHEMA'
CLUSTER=N
$

$ nohup impdp parfile=parfile.par &
[1] 27620
> nohup: ignoring input and appending output to `nohup.out'
$
$ jobs -l
[1]+ 27620 Running                 nohup impdp parfile=parfile.par &
$

$ tail -f SMARTSUPPY_SCHEMA_09nov2014.log
Master table "SYS"."SYS_IMPORT_SCHEMA_03" successfully loaded/unloaded
Starting "SYS"."SYS_IMPORT_SCHEMA_03":  /******** AS SYSDBA parfile=parfile.par
Processing object type SCHEMA_EXPORT/USER
Processing object type SCHEMA_EXPORT/SYSTEM_GRANT
Processing object type SCHEMA_EXPORT/ROLE_GRANT
Processing object type SCHEMA_EXPORT/DEFAULT_ROLE
Processing object type SCHEMA_EXPORT/TABLESPACE_QUOTA
Processing object type SCHEMA_EXPORT/PRE_SCHEMA/PROCACT_SCHEMA
Processing object type SCHEMA_EXPORT/SEQUENCE/SEQUENCE
Processing object type SCHEMA_EXPORT/TABLE/TABLE
Processing object type SCHEMA_EXPORT/TABLE/TABLE_DATA
. . imported "SMARTSUPPY_SCHEMA"."BPM_COMPONENTS_90000":"P475"  1.956 GB 6711857 rows
. . imported "SMARTSUPPY_SCHEMA"."BPM_COMPONENTS_90000":"P480"  1.965 GB 6794127 rows
. . imported "SMARTSUPPY_SCHEMA"."BPM_COMPONENTS_90000":"P474"  1.958 GB 6727517 rows
. . imported "SMARTSUPPY_SCHEMA"."BPM_COMPONENTS_90000":"P479"  1.921 GB 6616816 rows
. . imported "SMARTSUPPY_SCHEMA"."BPM_COMPONENTS_90000":"P478"  1.903 GB 6512491 rows
. . imported "SMARTSUPPY_SCHEMA"."BPM_COMPONENTS_90000":"P481"  1.909 GB 6618578 rows

Hope this will help you.. :)

Best Regards,
Chowdari


출처 : http://mbc-dba.blogspot.kr/2014/11/impdp-ora-31640-ora-31693-ora-19505-ora.html

반응형
반응형


ORA-27086: unable to lock file - already in use

In Alert log :

Thu Feb 14 09:34:57 EST 2013
Errors in file /u01/app/oracle/admin/rdmetdev/udump/rdmetdev_ora_6321.trc:
ORA-27050: function called with invalid FIB/IOV structure
Additional information: 2
ORA-27086: unable to lock file - already in use
Linux-x86_64 Error: 37: No locks available
Additional information: 10

usually this problem occurred because NFS is Hanged,and can check OS logs to find "statd: server localhost not responding, timed out".

1- Check rpc.stat is working and you can restart again , and you have to Restart NFS Services also 

Stop : 

# service nfslock stop
# service nfs stop
# service portmap stop
# umount /proc/fs/nfsd
 Start :
# service portmap start
# service nfs start
# service nfslock start
# mount -t nfsd nfsd /proc/fs/nfsd

Please follow the order, also note that when you restart the NFS service the server could hang at most for 1 minute.

Finally you should Reboot your server.


Thank you
Osama Mustafa


출처 : http://osamamustafa.blogspot.kr/2013/02/ora-27086-unable-to-lock-file-already.html

반응형
반응형


FTK Imager 이슈


스마트폰 속 개인정보, 삭제해도 쉽게 복원된다 : http://economy.hankooki.com/lpage/it/201407/e20140710145634117700.htm

AccessData의 Forensic 이미징 도구 : FTK Imager 3.0 : http://solatech.tistory.com/208


위 블로그에 자세한 사항을 찾고하면 되겠다 ^^(포렌식 관련)


난 그중 위의 파일 복구 관련하여 한번 살펴보았다... 속도도 빠르고 검색 능력도 뛰어남....


다운로드 : http://www.accessdata.com/support/product-downloads

https://accessdata.com/product-download

2019.03.27 기준 : 4.2.1 버전이 최신 버전이며 이메일로 다운로드 주소가 보내집니다.



3.1.1 버전을 다운로드 받아 실행함 (일반적인 설치과정이라 별 다를게 없음...)


파일 복구 간단한 사용법...


설치 -> FTK Imager 실행 


1. 특정 드라이브 연결

   - File -> Add Evidence Item... 선택 -> Physical Driver (이동식 USB 연결) -> 60 여 기가의 usb 연결 선택 -> 마침






2. 이동식 USB 연결된 파일의 목록이 좌측에 뜨고

    지워진 (X 표시가 뜬) 파일이나 폴더를 선택하여 마우스 우클릭시 Export Files... 선택하여 복원하면 끝






















 









반응형
반응형



소개글 : http://web-dev.tistory.com/562


위의 글은 아크로 에디터를 다운로드 받는 등 간단한 소개 내역이다.


사실 


울트라 에디터를 사용했던 주된 이유는 


대용량 한글 텍스트 파일(1GB 이상)을 부담없이 열어주며,


정규식 표현으로 특정 단어 + 다음줄 변환이 가능했기 때문이다.


그동안 아크로 에디터에서는 안되는 줄 알았는데,...


제 무지였음을 깨닿고 내용을 남깁니다.



-> 대용량 텍스트 연계 파일의 경우


DxxxxDxxxDxxx 등과 같이 특정 단어로 시작하는 경우가 많다.


그럴 경우


1. 아크로에디트 -> 찾기 -> 바꾸기 실행

    



2. 아래는 바꾼 후의 사진

    - 멋지지 않은가?

      실제 사례로... xml 태그 같은 경우

      찾는 문자열 : ><

      바꿀 문자열 : >\n< 

     정규 표현식 사용 체크, 범위 전체 체크 하면

     깔끔한 형태로 보여진다.


3. 기타 팁

    편집 -> 모두 선택 (전체가 블록 지정된 상태) -> 도구 -> 빈 줄 자동 삭제

    즉 필요없이 엔터가 많은 파일에서는 위의 설정을 선택하면 모든 빈줄이 사라진다 !



   


반응형
반응형

 

출처 : http://uranusk.blog.me/140021060715

 

윈도우 98 이미지 파일...

 

 

 

S640-7672.ima

 

config.sys

 

 [MENU]
MENUITEM=CD, Start Computer with CD-ROM Support
MENUITEM=GHOST, Restore All Data
MENUDEFAULT=CD,30
MENUCOLOR=7,0

[COMMON]
DEVICE=HIMEM.SYS
DEVICE=EMM386.EXE NOEMS
DOS=HIGH,UMB
DEVICEHIGH=OAKCDROM.SYS /D:Lugar
DEVICEHIGH=BILING.SYS


[CD]

[GHOST]

 

 

autoexec.bat

 

 PATH=X:\
LH MSCDEX.EXE /D:Lugar /L:X
LH NLSFUNC.EXE COUNTRY.SYS
GOTO %CONFIG%

:CD
GOTO END

:GHOST1
echo Continue is Press AnyKey
echo waring... All data Delete!!!
Pause > null
GHOST32 -CLONE,MODE=load,SRC=X:\win7.gho,DST=1 -auto -sure -fx
GOTO END

:END

 

삼성 CD롬 안될때.. (또는 DVD ROM 대비)

변경된 파일

 

 

WINDOWS98.ima

 

반응형
반응형

엑셀을 처리하는 방법

1. 일반적인 방법

   - DB <---> WAS (JAVA) 파일 생성 <---> JSP 다운로드

   - 문제점 : WAS에 메모리에서 엑셀 파일을 만들기 때문에 메모리 할당 공간이 부족할 때는 OOM(Out Of Memory)으로

                 힙 덤프를 사정없이 발사 !

 

2. 대용량 엑셀 처리 방법

    - 엑셀을 생성할 때 XML 방식으로 생성함

      http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats#Excel_XML_Spreadsheet_example

    - outputStream으로 행별로 Text를 써야 메모리에 한꺼번에 올리지 않아 WAS가 OOM를 뿜으면서 죽지 않음.

       ※ 첨부된 자바파일을 참고함

    - 대용량이므로 속도에 신경 쓰지 않을 수 없다 !!!

      그러므로 Fetch Size(JAVA에서 Oracle를 사용할 때 가지고오는 row의 양...)을 조절하여 성능향샹의 효과 까지 볼수 있다.

 

후후... 재미있는건... 난 자바를 잘 모른다...

개발자들도 원인을 잘 찾지 않는다...

귀찮은 걸까... 해결하고 싶지 않을껄까...

난 인프라 담당인데 하하하 -_-

 

BigGridDemo.java

반응형
반응형

Firefox Portable Edition

막강한 확장기능 지원과 뛰어난 안정성을 자랑하는 오픈소스 웹 브라우저.

다운로드 Firefox Portable 3.5 (9MB)

 

Google Chrome Portable

빠른 자바스크립트 속도를 자랑하며 탭 별 프로세스 할당 방식으로 안정성을 강화. 쾌적한 인터페이스도 뛰어남.

다운로드 Chronium 3.0.182.3 (17.6MB)

 

OperaUSB

별도의 확장기능이 필요 없을 만큼 많은 기능이 내장된 웹 브라우저. 빠른 구동 속도와 웹페이지 렌더링 속도도 강점.

다운로드 OperaUSB 9.64 (5.1MB)

 

 

텍스트 편집


Notepad++

구문 하이라이트와 자동완성 등 강력한 기능의 텍스트 에디터

다운로드 Notepad++ Portable 5.4.3 (3MB)

 

Web Design Toy

HTML 코드를 입력하면 오른쪽 창에서 바로 바로 확인.

다운로드 Web Design Toy (449KB)

 

Oiko Visual CSS Editor

트리 구조 방식의 CSS 비주얼 에디터.

다운로드 Oiko Visual CSS Editor Portable 1.00 RC3 (1.1MB)

 

KompoZer Portable

드림위버와 비슷한 위지윅 HTML 에디터. 파이어폭스와 썬더버드의 Gecko 렌더링 엔진을 사용함. KompoZer는 NVU 1.0의 상당수 버그를 수정한 비공식 릴리즈.

다운로드 KompoZer Portable 0.7.10 Rev 2 (7.2MB)

 

 

이미지 편집


GIMP Portable

포토샵을 대체하는 오픈소스 비트맵 그래픽 에디터.

다운로드 GIMP Portable 2.6.6 (17MB)

 

Inkscape Portable

일러스트레이터를 대체하는 오픈소스 벡터 그래픽 에디터.

다운로드 Inkscape Portable 45.1 Rev 2 (19.5MB)

 

Fotografix

760KB의 작은 용량에도 레이어, 스크립트, 필터를 지원하며 간편한 이미지 편집에 좋음.

다운로드 Fotografix 1.1 (366KB)

 

Artweaver

다양한 브러쉬를 지원하는 페인팅 프로그램.

다운로드 Artweaver Portable (11.24MB)

 

FastStone Image Viewer Portable

유려한 인터페이스에 빠르고 안정적인 이미지 뷰어. 파일 컨버터와 간편한 에디터 기능도 내장.

다운로드 FastStone Image Viewer Portable 3.9 (5.0MB)

 

 

FTP 클라이언트


FileZilla Portable

빠르고 안정적인 무료 FTP 클라이언트.

다운로드 FileZilla Portable 3.2.6.1 (4MB)

 

WinSCP Portable

오픈소스 FTP/SFTP/SCP 클라이언트. Putty Portable 버전을 내장.

다운로드 WinSCP Portable 4.1.9 (2MB)

 

 

웹 서버


XAMPP Portable

따로 설정할 필요가 없는 웹 서버 패키지.

다운로드 XAMPP Portable 1.7.1 (82MB), Lite Version (50MB)

 

Server2Go

PHP, MySQL, Apache, SQLite, Perl 등을 지원하는 무료 서버 패키지.

다운로드 Server2Go

 

HTTP File Server

간편한 파일 공유 프로그램. 용량이 큰 파일을 클라이언트와 공유할 때 좋음.

다운로드 HFS 2.2f (600KB)

 

 

오피스 & 문서 툴


Foxit Reader

가볍고 빠른 PDF 리더. 포터블로 만들기 위해서는 프로그램을 설치하고 설치 폴더를 USB 드라이브로 복사. 설치 시 ebay 툴바 등 주의.

다운로드 Foxit Reader 3.0 (2.99MB)

 

OpenOffice Portable

마이크로소프트 오피스를 대체하는 워드, 스프레드시트, 프리젠테이션, 드로윙, 데이터베이스 통합 프로그램.

다운로드 OpenOffice Portable 3.1 (87MB)

 

AbiWord Portable

마이크로소프트 워드와 비슷한 가벼운 워드프로세서. 메일 병합 등의 기능과 플러그인도 지원.

다운로드 Abiword Portable 2.6.8 (6.3MB)

 

Thunderbird Portable Edition

막강한 확장기능 지원이 강점인 이메일 툴. 포터블 버전이라 컴퓨터에 흔적을 남기지 않고 이메일과 주소록을 관리함.

다운로드 Thunderbird Portable 2.0.0.22 (6.7MB)

 

 

노트 툴


MemPad

트리 기반의 노트 관리 유틸리티. 모든 페이지는 단일 파일로 저장되고 다이어리 모드를 지원.

다운로드 MemPad 3.32 (97KB)

 

TiddlyWiki

단일 HTML 파일로 구성되어 있지만 다양한 플러그인 지원을 통해 위키, 노트북, GTD 툴 등 여러 용도로 활용할 수 있음.

다운로드 TiddlyWiki (346KB)

 

ToDoList

깔끔한 인터페이스의 할 일 관리 유틸리티. 할 일은 XML 포맷으로 저장하고 프로그램 환경설정은 ini 파일로 저장.

다운로드 ToDoList 5.8 (801KB)

 

 

동기화 & 백업 툴


Toucan

파일 동기화, 백업 & 암호화 유틸리티. 4개의 동기화 모드를 제공하며 7-zip 백업과 256bit 암호화를 지원.

다운로드 Toucan Portable 2.1.0 (2.5MB)

 

FreeFileSync

드래그앤드롭과 4GB 이상의 파일을 지원하는 폴더 비교 & 동기화 툴. 우분투 버전도 있음.

다운로드 FreeFileSync 2.1 (1.2MB)

 

 

유틸리티


KeePass Password Safe Portable

오픈소스 패스워드 관리 유틸리티. 암호 데이터베이스를 하나의 마스터 패스워드로 보호.

다운로드 KeePass Password Safe Portable 1.16 (1.7MB)

 

7-Zip Portable

다양한 포맷을 지원하는 막강한 압축률의 압축 유틸리티.

다운로드 7-ZIP Portable 4.65 Rev 2 (1.4MB)

 

Font Matcher

이미지 속의 폰트를 실제 폰트와 매치해줌. TTF 폰트만 지원.

다운로드 Font Matcher 1.0.3 (160KB)

 

IcoFX

아이콘 변환, 추출 등을 지원하는 아이콘 에디터. 256x256 해상도까지 지원.

다운로드 IcoFX 1.6.4 Portable (1.4MB)

 

PickPick

세계에서 인정받는 자랑스런 국산 스크린 캡쳐 툴. 색상 추출 등의 다양한 기능과 함께 간단한 이미지 편집도 지원.

다운로드 PickPick 1.8.1.0 Portable (957KB)

 

VirtuaWin

작은 리소스의 가상 데스크탑 관리 프로그램.

다운로드 VirtuaWin 4.0.1 Portable (97KB)

[이 게시물은 인천올님에 의해 2010-06-10 14:06:36 추천정보에서 이동 됨]

 

출처 : http://www.incheonall.com/bbs/board.php?bo_table=pds&wr_id=44&page=

반응형

'UTILITY' 카테고리의 다른 글

Acroedit 소개  (0) 2011.06.28
NetDrive 설정해 보기  (0) 2011.06.28
토드 초기화 하기  (0) 2011.03.28
파수 관련 autoit 작성 코드  (0) 2011.03.10
비스타 관리자 권한 실행 파일 만드는 프로그램  (0) 2011.03.10
반응형

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


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

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

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

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


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

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

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

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

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

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


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

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

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

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


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

    }


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

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


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

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

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

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

    }

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

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

        try {

            stmt = conn.createStatement();

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

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

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

            }

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

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

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

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

        try {

            stmt = conn.createStatement();

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

            }

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

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

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

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

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

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

        try {

            stmt = conn.createStatement();

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

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

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

            }

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

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

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

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

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

반응형
반응형
제품 : JDBC

작성날짜 :

FILE을 CLOB에 INSERT하고, 반대로 컬럼을 읽어 FILE로 WRITE하는 JDBC PROGRAM 예제 (JDBC 8.1 이상)



PURPOSE

text file을 읽어서 CLOB column 에 저장하는 방법과, CLOB column의 데이타를
읽어서 file로 write하는 방법을 예제를 통해서 살펴본다.


Explanation



oracle.sql package에서 제공하는 CLOB class를 이용한다.
file의 내용을 읽어 CLOB type에 저장할 때는 CLOB.getCharacterOutputStream을
이용하고, 반대로 file에 write를 위해 CLOB type을 읽을 때는
clob.getCharacterStream() 를 이용한다.

Oracle JDBC driver 8.1.x 이상 version의 classes12.zip file이 CLASSPATH에
지정되어 있어야 한다. JDK는 1.2 이상을 사용한다.

[참고] 화일을 이용하지 않고 직접 text를 CLOB에 입력하고, 입력된 CLOB
데이타를 화면에 display하기 위해서는 아래 bulletin을 참고한다.
<Bulletin No: 19360>: Subject: ORACLE.SQL.CLOB CLASS를 이용하여
4000 BYTES이상의 CLOB TEXT 데이타를 저장하고, 조회하는 예제

Example


1. 테이블의 생성과 데이타 입력

미리 다음 작업이 수행되어 있어야 하며, 이 작업도 java application내에
statement.execute를 통해 포함시킬 수 있다.

sqlplus scott/tiger
SQL> create table test_clob(id number, c clob);
SQL> insert into test_clob values (1, empty_clob());

2. ClobFile.java

다음 내용을 ClobFile.java라는 이름으로 생성한 후,

os>javac ClobFile.java
os>java ClobFile
후 out.txt file내용을 확인하고, scott.TEST_CLOB table의 데이타도 조회하여
수해이 잘 되었는지 확인한다.

import java.sql.*;
import java.io.*;
import java.util.*;
import oracle.jdbc.driver.*;

import oracle.sql.*;

public class ClobFile {

public static void main (String args []) throws Exception {

try {
Connection conn;

DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver() );
conn = DriverManager.getConnection( "jdbc:oracle:thin:@krint-5:1521:ORA920"

, "scott","tiger" );

conn.setAutoCommit (false);

CLOB clob = null;

Statement stmt = conn.createStatement ();

String cmd = "select * from test_clob for update";
ResultSet rset = stmt.executeQuery(cmd);
while (rset.next())
clob = ((OracleResultSet)rset).getCLOB(2);

// 아랫부분에 file로 부터 데이타를 읽어 CLOB column에 저장하는
// readFromFile()이 작성되어 있다.

readFromFile(clob);
stmt.execute("commit");

rset = stmt.executeQuery ("select * from test_clob where id=1");

if (rset.next ())
{
clob = ((OracleResultSet)rset).getCLOB(2);
String st = rset.getString(2);

if (clob != null)
System.out.println ("clob length = "+clob.length ());
}

// 아랫부분의 CLOB 컬럼의 데이타를 읽어 다시 다른 file로 write하는
// writeToFile()을 호출한다.

writeToFile(clob);
}

catch (SQLException sqle) {
System.out.println("SQL Exception occured: " + sqle.getMessage());
sqle.printStackTrace();
}

catch(FileNotFoundException e) {
System.out.println("File Not Found");
}

catch (IOException ioe) {
System.out.println("IO Exception" + ioe.getMessage());
}
}

//


// test.txt file을 읽어 test_clob.c column에 저장한다.

static void readFromFile (CLOB clob) throws Exception {
File file = new File("/home/ora920/eykim/test.txt");
FileReader in = new FileReader(file);
Writer out = clob.getCharacterOutputStream();

int chunk = clob.getChunkSize();
System.out.print("The chunk size is " + chunk);
char[] buffer = new char[chunk];
int length;

while ((length = in.read(buffer,0,chunk)) != -1)
out.write(buffer, 0, length);

in.close();
out.close();
}

//------------------------------------------------------------------
// test.clob.c column의 데이타를 읽어 out.txt file로 write한다.

static void writeToFile (CLOB clob) throws Exception {
int chunk = clob.getChunkSize();

int length;
char[] buffer = new char[chunk];
FileWriter outFile = null;
outFile = new FileWriter("/home/ora920/eykim/out.txt");
Reader instream = clob.getCharacterStream();

while ((length = instream.read(buffer)) != -1) {
outFile.write(buffer, 0, length);
}

instream.close();
outFile.close();
}

}


Reference Documents


SCR #998


반응형

+ Recent posts