前回のつづき、次はインタセプタで処理実行を横取りである。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
class CsvparseInterceptor implements MethodInterceptor{
private Class<? extends Csvparser> csvpCls;
protected CsvparseInterceptor(Class<? extends Csvparser> csvpCls){
this.csvpCls = csvpCls;
}
/* (非 Javadoc)
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
*/
public Object invoke(MethodInvocation m) throws Throwable{
// 解析結果配列セット先 Field を特定する ---> farray
Field farray=null;
Field fls = this.csvpCls.getDeclaredFields();
boolean quotSwitch = false; // 括り文字有無のスイッチ
for(int i=0;i < fls.length;i++){
CsvArray csvarryAnotate = fls[i].getAnnotation(CsvArray.class);
if (csvarryAnotate != null){
quotSwitch = csvarryAnotate.value();
if (fls[i].getType().getName().equals("[Ljava.lang.String;")){
farray = fls[i];
farray.setAccessible(true);
}else{
throw new RuntimeException("must be CsvArray annotation String array Field ");
}
}
}
if (farray==null){
throw new RuntimeException("must be CsvArray annotation String array Field ");
}
Object params = m.getArguments();
File file = (File)params[0];
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
if (quotSwitch){
String _strs;
while((line=br.readLine())!=null){
_strs = this.splitAry(',',line);
for(int i=0;i < _strs.length;i++){
if (_strs[i].length() > 1){
_strs[i] = _strs[i].substring(1,_strs[i].length()-1);
}
}
farray.set(m.getThis(),_strs);
m.proceed();
}
}else{
while((line=br.readLine())!=null){
farray.set(m.getThis(),this.splitAry(',',line));
m.proceed();
}
}
br.close();
return null;
}
/**
* 文字列split(列の縮小を回避).
*/
private String splitAry(char sep,String str){
String rtn = new String[0];
List<String> list = new ArrayList<String>();
StringBuffer sb = new StringBuffer();
char spc = { sep };
String ns = str + new String(spc);
char ch = ns.toCharArray();
int k=0;
for(int i=0;i < ch.length;i++){
if (ch[i]==sep){
list.add(sb.toString());
sb.delete(0,k);
}else{
sb.append(ch[i]);
k++;
}
}
if (list.size() > 0){
Object objs = list.toArray();
rtn = new String[objs.length];
for(int i=0;i < rtn.length;i++){
rtn[i] = (String)objs[i];
}
}
return rtn;
}
}