2011. 11. 29. 15:35 IT

SQL Inspection 을 다루다보니 필요해진게 iBatis Framework의 XML파일에서 SQL 문장을 추출하는일.

이리저리 찾아보다보니 나오더라.



import java.io.Reader;
import groovy.lang.Singleton;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.ibatis.sqlmap.client.SqlMapException
import com.ibatis.sqlmap.engine.impl.SqlMapClientImpl;
import com.ibatis.sqlmap.engine.mapping.sql.Sql;
import com.ibatis.sqlmap.engine.mapping.statement.MappedStatement;
import com.ibatis.sqlmap.engine.scope.RequestScope;
@Singleton
class IbatisUtil {
static SqlMapClientImpl mapClient;
static RequestScope request;
static{
request = new RequestScope(); // 고정값으로 미리 생성해둔다. 
}
       // 초기화 작업 (sqlmapImpl 생성) 
public static void init(String file){
getIbatisMapClient(file);

        // ibatis의 SqlMapClientImpl을 생성한다.  
private static void getIbatisMapClient(String resource) {
Reader reader = getDynamicReader(resource);
try{
mapClient = (SqlMapClientImpl) SqlMapClientBuilder.buildSqlMapClient(reader);
}catch(Exception e){ 
// classpath 상에 VO 가 없을 경우 예외가 발생할 수 있다. 
}
}
        // 특정 ID에 대하여 sql 을 반환한다. 
public static String getSql(String id){
if(mapClient==null){
return null;
}else{
try{
MappedStatement mappedStatement = mapClient.getMappedStatement(id); 
mappedStatement.initRequest(request);
Sql sql = mappedStatement.getSql();
return sql.getSql(request,null);
}catch(Exception e){ // 동적변수의 값이 null이거나, ID가 없거나 등의 예외가 발생할 수 있다. 
return null;
}
}
}
        // 더미로 sqlMapConfig을 생성해준다. 여기서는 로컬 sqlMap 파일을 연결하므로 url=file 방식을 사용한다. 
private static Reader getDynamicReader(String resource) {
StringBuffer value = new StringBuffer();
value.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
value.append("<!DOCTYPE sqlMapConfig PUBLIC \"-//ibatis.apache.org//DTD SQL Map Config 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-config-2.dtd\">");
value.append("<sqlMapConfig>");
println resource.replaceAll("\\\\", "/")
value.append("<sqlMap url=\"file:///" + resource.replaceAll("\\\\", "/") + "\"/>");
value.append("</sqlMapConfig>");
return new java.io.StringReader(value.toString());
}
}
posted by smplnote