//获取所有参数 {xxx} xxx为参数名
public static List getParamNames(String s) throws Exception {
//List list = new ArrayList();
List list = null;
Map map = new HashMap();
if (s == null) {
return new ArrayList();
}
Pattern p = Pattern.compile("\\{([0-9A-Za-z._-]{0,50})\\}");
Matcher m = p.matcher(s);
String paramName = null;
while (m.find()) {
paramName = m.group(1);
//list.add(paramName);
map.put(paramName,"1");
}
//return list;
return StringUtil.getMapKey(map);
}
//替换参数,全部替换
public static String setParam(String s, Map map)
throws Exception {
if (map == null) {
return s;
}
List list = getParamNames(s);
if (list == null) {
return s;
}
int i = 0;
int num = 0;
String paramName = null;
String v = null;
Object obj = null;
num = list.size();
for (i = 0; i < num; i++) {
paramName = (String) list.get(i);
//System.out.println(paramName);
obj = map.get(paramName);
if(obj==null){
v="";
}else{
v = obj+"";
}
//s = setParamSingle(s, paramName, (String)map.get(paramName));
//System.out.println(v);
//s = StringUtil.setParam(s, paramName, v);
s = setParamSingle(s, paramName, v);
//System.out.println(s);
}
return s;
}
//根据 <notempty name="xxx">content</notempty> 动态生成 sql
//参数xxx不为空时,才输出 content,实现动态sql
//目前只支持常见的notempty判断
//可使用模板来动态生成sql语句,这样将非常强大,常见的模板工具有 freemark,velocity等
//还是比较喜欢简单,就不使用第三方的模板工具了
public static String getParamSql(String s,Map map)throws Exception{
if(s==null){return "null";}
if(map==null){return s;}
String ps = "<notempty[\\s]{1,100}name=\\\"([0-9A-Za-z._-]{1,50})\\\">([^/]{1,500})</notempty>";
Pattern p = Pattern.compile(ps);
Matcher m = p.matcher(s);
StringBuffer sb = new StringBuffer();
String v = null;
String rs = null;
String name = null;
while (m.find()) {
name=m.group(1);
rs=m.group(2);
v = (String)map.get(name);
if(StringUtil.isempty(v)){
m.appendReplacement(sb, "");
}else{
m.appendReplacement(sb, rs);
}
}
m.appendTail(sb);
return sb.toString();
}
//根据名称获取原始的sql语句
public static String getSqlByName(String name)
throws Exception{
String s = null;
if(StringUtil.isempty(name)){
throw new Exception("sql name is empty");
}
s = getSqlConfigProp().getProperty(name);
if(StringUtil.isempty(s)){
throw new Exception("no sql names ["+name+"]");
}
return s;
}
//根据名称获取sql语句,动态生成,参数替换后的sql,可直接执行
public static String getSqlByName(String name,Map map)
throws Exception{
String sql = null;
sql = getSqlByName(name);
sql=getParamSql(sql,map);
if(map==null){return sql;}
return getSql(sql,map);
}
public static String getSql(String s,Map map)throws Exception{
if(map==null){return s;}
if(map.isEmpty()){return s;}
List list = getParamNames(s);
return setParam(s,map);
}
