今日ここで書きとめておくのは、インターセプタそのもの。
呼び出し側から隠蔽するところ。
残りは、アノテーションの記述とインターセプタにバインド定義するもの。
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FtpInterceptor implements MethodInterceptor{
private Class<?> cls;
public FtpInterceptor(Class<?> cls){
this.cls = cls;
}
/*
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
*/
@Override
public Object invoke(MethodInvocation m) throws Throwable{
String hostname = null;
String user = null;
String passwd = null;
Object args = m.getArguments();
Annotation anos = m.getMethod().getParameterAnnotations();
for(int n=0;n < anos.length;n++){
for(int k=0;k < anos[n].length;k++){
if (anos[n][k].annotationType().equals(FtpHost.class)){
hostname = (String)args[n];
}else if(anos[n][k].annotationType().equals(FtpUser.class)){
user = (String)args[n];
}else if(anos[n][k].annotationType().equals(FtpPasswd.class)){
passwd = (String)args[n];
}
}
}
FTPClient ftpClient = new FTPClient();
ftpClient.connect(hostname);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
throw new Exception("FTPClient not Positive reply!! value = "+String.valueOf(reply));
}
if (!ftpClient.login(user,passwd)){
throw new Exception("FTPClient Login NG!! user = "+user);
}
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
Field ftpclientField = null;
Field fls = this.cls.getDeclaredFields();
for(int i=0;i < fls.length;i++){
FTPClientDefine defineFTPClint = fls[i].getAnnotation(FTPClientDefine.class);
if (defineFTPClint != null){
if (fls[i].getType().getName().equals("org.apache.commons.net.ftp.FTPClient")){
ftpclientField = fls[i];
ftpclientField.setAccessible(true);
}else{
throw new RuntimeException("must be FTPClientDefine annotation String Field");
}
}
}
if (ftpclientField==null){
throw new RuntimeException("must be FTPClientDefine annotation String Field");
}
ftpclientField.set(m.getThis(),ftpClient);
Object rtn = m.proceed();
if (ftpClient.isConnected()){
//ftpClient.logout();
ftpClient.disconnect();
}
return rtn;
}
}