packagezzz.study.utils;import java.io.*;import java.util.*;importjava.util.regex.Matcher;importjava.util.regex.Pattern;/*** Created by shuqin on 16/5/4.*/
public classBaseTool {public static final String ALLIN_PROJ_PATH = System.getProperty("user.dir");public static final String ALLIN_PROJ_PATH_SRC = ALLIN_PROJ_PATH + "/src/main/java";public staticString strip(String origin, String toStrip) {int index =origin.indexOf(toStrip);if (index == -1) {returnorigin;
}else{return origin.substring(0, index);
}
}public staticString firstToLower(String doClassName) {return "" + String.valueOf(doClassName.charAt(0)).toLowerCase() + doClassName.substring(1);
}public staticString firstToUpper(String fieldName) {return "" + String.valueOf(fieldName.charAt(0)).toUpperCase() + fieldName.substring(1);
}public staticString getBizType(String packageName) {int preIndex = packageName.indexOf("common.");if (preIndex == -1) {return "";
}
String bizPart= packageName.substring(preIndex+"common.".length());int bizIndex = bizPart.indexOf(".");if (bizIndex == -1) {return "";
}return bizPart.substring(0, bizIndex);
}public static String indent(intn) {
StringBuilder spaces= newStringBuilder();for (int i=0; i
spaces.append(' ');
}returnspaces.toString();
}public staticString readFile(String filePath) {
String fileContent= "";try{
BufferedReader reader= new BufferedReader(new FileReader(newFile(filePath)));
StringBuilder doClsContentBuilder= newStringBuilder();
String line= "";while ((line = reader.readLine()) != null) {
doClsContentBuilder.append(line+ "\n");
}
fileContent=doClsContentBuilder.toString();
}catch(IOException ioe) {
System.err.println("Failed to Read File " + filePath + " : " +ioe.getMessage());
}returnfileContent;
}public static ListreadLines(String filePath) {
List lines = new ArrayList();try{
BufferedReader reader= new BufferedReader(new FileReader(newFile(filePath)));
String line= "";while ((line = reader.readLine()) != null) {
lines.add(line);
}
}catch(IOException ioe) {
System.err.println("Failed to Read File " + filePath + " : " +ioe.getMessage());
}returnlines;
}public static voidwriteFile(String filePath, String fileContent) {try{
BufferedWriter modelFileW= new BufferedWriter(new FileWriter(newFile(filePath)));
modelFileW.write(fileContent);
modelFileW.close();
}catch(IOException ioe) {
System.err.println("Failed to write Java File " + filePath + " : " +ioe.getMessage());
}
}public static ListfetchAllFiles(String path) {
List fetchedFiles = new ArrayList();
fetchFiles(path, fetchedFiles);returnfetchedFiles;
}public static void fetchFiles(String path, ListfetchedFiles) {
File[] dirAndfiles= (newFile(path)).listFiles();if (dirAndfiles!=null && dirAndfiles.length > 0) {for(File file: dirAndfiles) {if(file.isFile()) {
fetchedFiles.add(file.getAbsolutePath());
}
}for(File file: dirAndfiles) {if(file.isDirectory()) {
fetchFiles(file.getAbsolutePath(), fetchedFiles);
}
}
}
}public static ListgetClasses(String path) {
List files =fetchAllFiles(path);
List result = new ArrayList();
ClassLoader cld=Thread.currentThread().getContextClassLoader();for(String fname: files) {
String fn= fname.replace(ALLIN_PROJ_PATH_SRC + "/", "").replace(".java", "");
String qualifiedClassName= fn.replaceAll("/", ".");try{
Class> cls =cld.loadClass(qualifiedClassName);
result.add(cls);
}catch(ClassNotFoundException cnfe) {
System.err.println("Failed to load class " + qualifiedClassName + " : " +cnfe.getMessage());
}
}returnresult;
}public static final String methodNameRegexStr = "\\s*(?:\\w+\\s+)?\\w+\\w+>?\\s+(\\w+)";public static final String singleParamRegexStr = "[^,]*\\w+\\w+>?\\s+(\\w+)\\s*";public static final String simpleMethodSignRexStr = methodNameRegexStr + "\\(" + singleParamRegexStr + "\\)\\s*;\\s*";public static final String twoParamMethodSignRegStr = methodNameRegexStr + "\\(" + singleParamRegexStr + "," + singleParamRegexStr + "\\);\\s*";//val generalParamMethodSignRegStr = methodNameRegexStr + "\\((" + singleParamRegexStr + "(?:," + singleParamRegexStr + ")*)\\);\\s*";
public static final String generalParamMethodSignRegStr = methodNameRegexStr + "\\((.*)\\);\\s*";public static final Pattern singleParamPattern =Pattern.compile(singleParamRegexStr);public static final Pattern generalParamMethodSignPattern =Pattern.compile(generalParamMethodSignRegStr);/*** 从方法签名中解析出方法名称\参数列表
*@parammethodSign 方法签名
*@return["方法名称", "参数1, 参数2, ..., 参数N"]*/
public static ListparseMethod(String methodSign) {
Matcher m=generalParamMethodSignPattern.matcher(methodSign);
String methodName= "";
String args= "";
List parsed = new ArrayList();if(m.find()) {
methodName= m.group(1);
args= m.group(2);
}else{return Arrays.asList(new String[]{"", ""});
}
parsed.add(methodName);
String[] params= args.split(",");for(String param: params) {
String arg=extractArgName(param);
parsed.add(arg);
}returnparsed;
}public staticString extractArgName(String singleParam) {
Matcher m=singleParamPattern.matcher(singleParam);return m.find() ? m.group(1) : "";
}public static List transform(Listparsed) {if (parsed == null ||parsed.isEmpty()) {returnparsed;
}
List result = new ArrayList();
result.add(parsed.get(0));if (parsed.size() == 2) {
result.add(parsed.get(1));
}else{int size =parsed.size();
StringBuilder argBuilder= newStringBuilder();for (int i=1; i< size-1; i++) {
argBuilder.append(parsed.get(i)+ ", ");
}
argBuilder.append(parsed.get(size-1));
result.add(argBuilder.toString());
}returnresult;
}public static voidtestParseMethod() {
Map> testMethods = new HashMap>();
testMethods.put(" List queryOrder(int kdtId); ", Arrays.asList(new String[]{"queryOrder", "kdtId"}));
testMethods.put(" List queryOrder( int kdtId ); ", Arrays.asList(new String[]{"queryOrder", "kdtId"}));
testMethods.put(" OrderDO queryOrder(@Param(\"kdtId\") int kdtId); ", Arrays.asList(new String[]{"queryOrder", "kdtId"}));
testMethods.put(" List queryOrder(List orderNos); " , Arrays.asList(new String[]{"queryOrder", "orderNos"}));
testMethods.put(" List queryOrder(@Param(\"orderNos\") List orderNos); ", Arrays.asList(new String[]{"queryOrder", "orderNos"}));
testMethods.put(" OrderDO queryOrder(String orderNo, Integer kdtId); ", Arrays.asList(new String[]{"queryOrder", "orderNo, kdtId"}));
testMethods.put(" OrderDO queryOrder(String orderNo, @Param(\"kdtId\") Integer kdtId); ", Arrays.asList(new String[]{"queryOrder", "orderNo, kdtId"}));
testMethods.put(" OrderDO queryOrder(@Param(\"orderNo\") String orderNo, Integer kdtId); ", Arrays.asList(new String[]{"queryOrder", "orderNo, kdtId"}));
testMethods.put(" OrderDO queryOrder(@Param(\"orderNo\") String orderNo, @Param(\"kdtId\") Integer kdtId); ", Arrays.asList(new String[]{"queryOrder", "orderNo, kdtId"}));
testMethods.put(" OrderDO queryOrder(List orderNos, Integer kdtId); \n", Arrays.asList(new String[]{"queryOrder", "orderNos, kdtId"}));
testMethods.put(" OrderDO queryOrder(@Param(\"orderNos\") List orderNos, Integer kdtId); ", Arrays.asList(new String[]{"queryOrder", "orderNos, kdtId"}));
testMethods.put(" OrderDO queryOrder(List orderNos, @Param(\"kdtId\") Integer kdtId); ", Arrays.asList(new String[]{"queryOrder", "orderNos, kdtId"}));
testMethods.put(" OrderDO queryOrder(@Param(\"orderNos\") List orderNos, @Param(\"kdtId\") Integer kdtId); ", Arrays.asList(new String[]{"queryOrder", "orderNos, kdtId"}));
testMethods.put(" OrderDO queryOrder(@Param(\"orderNos\") List orderNos, @Param(\"page\") Integer page, @Param(\"pageSize\") Integer pageSize); ", Arrays.asList(new String[]{"queryOrder", "orderNos, page, pageSize"}));
Set>> entries =testMethods.entrySet();for(Map.Entry entry: entries) {
String methodSign=(String)entry.getKey();
List expected = (List)entry.getValue();
List actual =transform(parseMethod(methodSign));if (!assertListEqual(actual, expected)) {
System.err.println("failed: " +methodSign);
System.err.println("expected: " +expected);
System.err.println("actual: " +actual);
}
}
System.out.println("Test ParseMethod passed");
}public static boolean assertListEqual(List list1, Listlist2) {if (list1 == null && list2 == null) {return true;
}if ((list1 == null && list2 !=null) || (list1 != null && list2 ==null)) {return false;
}if (list1.size() !=list2.size()) {return false;
}for (int i=0; i< list1.size(); i++) {if (!list1.get(i).equals(list2.get(i))) {return false;
}
}return true;
}
}