2010年10月17日日曜日

H2 DatabaseとApache Commons NetでCLOBをファイルとしてFTPサーバにアップロードする関数を作成する

H2 DatabaseとApache Commons NetでCLOBをファイルとしてFTPサーバにアップロードする関数を作成するには、以下のスクリプトを実行します。

create alias if not exists ftp_put_ascii as $$ 
import java.io.*;
import java.sql.*;
import org.h2.tools.*;
import org.h2.value.*;
import org.apache.commons.net.ftp.*;
@CODE
int ftp_put_ascii(String host, Integer port,
String user, String password, String encoding,
String path, String filename, Clob clob)
throws Exception
{

if( host == null ){
throw new Exception("host is not specified.");
}
int intPort = (port == null)?21:port.intValue();
user = (user == null)?"":user;
password = (password == null)?"":password;
encoding = (encoding == null)?"UTF-8":encoding;
path = (path == null)?".":path;
if( filename == null ){
throw new Exception("filename is not specified.");
}

Reader reader = null;
FTPClient fc = new FTPClient();
try
{
// 接続
fc.connect(host, intPort);
if( !FTPReply.isPositiveCompletion(fc.getReplyCode()) ){
throw new Exception("failed to connect.");
}
// ログイン
if( fc.login(user, password) == false ){
throw new Exception("failed to login.");
}
// エンコーディングの設定
fc.setControlEncoding(encoding);

// ファイル転送モードをasciiに
fc.setFileType(FTP.ASCII_FILE_TYPE);

// ファイルのアップロード
InputStream ais = null;
try
{
ais = clob.getAsciiStream();
if( !fc.storeFile(path + '/' + filename, ais) ){
throw new Exception("failed to upload a file.");
}
}
finally
{
if( ais != null )ais.close();
}

// ログアウト
fc.logout();
}
finally
{
if( fc.isConnected() ){
fc.disconnect();
}
}

return 0;
}
$$


実行例
drop table if exists clobtest;
create table clobtest (c1 numeric(4), c2 clob);
insert into clobtest values (1,
ftp_get_ascii('192.168.1.122', 21,
'ftptest1', 'ftptest1',
'UTF-8', '.', 'readme.txt')
);
select ftp_put_ascii('192.168.1.122', 21,
'ftptest1', 'ftptest1',
'UTF-8', '.', 'uploaded_readme.txt', c2)
from clobtest
where c1 = 1;


※システム環境変数CLASSPATHにtools.jarとApache Commons Netのjar
(commons-net-2.0.jar, commons-net-ftp-2.0.jar)を追加しておくこと。

動作環境
JDK6 Update 21, H2 Database 1.2.143 (2010-09-18), Apache Commons Net 2.0
○関連情報
・H2 Databaseに関する他の記事はこちらを参照してください。

0 件のコメント:

コメントを投稿