2010年10月14日木曜日

H2 DatabaseとApache Commons NetでFTPの指定ディレクトリの隠しファイルも含めてファイルを列挙する関数を作成する

H2 DatabaseとApache Commons NetでFTPの指定ディレクトリの隠しファイルも含めてファイルを列挙する関数を作成するには、以下のスクリプトを実行します。

create alias if not exists ftp_list_hidden_files as $$ 
import java.sql.*;
import org.h2.tools.*;
import org.apache.commons.net.ftp.*;
@CODE
ResultSet ftp_list_hidden_files(String host, Integer port,
String user, String password, String encoding,
String path)
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;

SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("NAME", Types.VARCHAR, 512, 0);

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

// 隠しも含めたファイルの列挙
fc.setListHiddenFiles(true);
FTPFile files[] = fc.listFiles(path);
for(int fi=0;fi<files.length;fi++){
rs.addRow(files[fi].getName());
}

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

return rs;
}
$$


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


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

コメントを投稿