2010年10月23日土曜日

H2 DatabaseとApache Commons NetでFTPサーバ上のファイルのサイズを返す関数を作成する

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

create alias if not exists ftp_get_filesize as $$ 
import java.io.*;
import java.sql.*;
import org.h2.tools.*;
import org.h2.value.*;
import org.apache.commons.net.ftp.*;
@CODE
long ftp_get_filesize(String host, Integer port,
String user, String password, String encoding,
String path, String filename)
throws Exception
{
long result = -1;
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.");
}

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);

// ファイルサイズの取得
FTPFile files[] = fc.listFiles(filename);
if( files.length > 1 ){
throw new Exception("too many files!");
}
result = files[0].getSize();
// ログアウト
fc.logout();
}
finally
{
if( fc.isConnected() ){
fc.disconnect();
}
}

return result;
}
$$


実行例
call ftp_get_filesize('192.168.1.122', 21, 
'ftptest1', 'ftptest1',
'UTF-8', '.', 'SF.JPG');


※システム環境変数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 件のコメント:

コメントを投稿