2010年10月22日金曜日

H2 DatabaseとApache Commons NetでFTPサーバ上のディレクトリを削除する関数を作成する

H2 DatabaseとApache Commons NetでFTPサーバ上のディレクトリを削除する関数を作成するには、以下のスクリプトを実行します。

create alias if not exists ftp_delete_dir as $$ 
import java.io.*;
import java.sql.*;
import org.h2.tools.*;
import org.h2.value.*;
import org.apache.commons.net.ftp.*;
@CODE
int ftp_delete_dir(String host, Integer port,
String user, String password, String encoding,
String path, String dir)
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( dir == null ){
throw new Exception("directory 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);

// ディレクトリの削除
if( !fc.removeDirectory(path + '/' + dir) ){
throw new Exception("failed to delete a directory.");
}

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

return 0;
}
$$


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


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

コメントを投稿