/**
* 批量生成 Hibernate Dao
* @author WangZhen Email: thinkgem@gmail.com
*/

package com.yuchen.test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BatchBuildDao {

String filePath = "D:\\test\\src\\java\\com\\yuchen\\test\\common\\";
String packageName = "com.yuchen.test.common";

public BatchBuildDao() {
List<String> classNameList = new ArrayList<String>();
classNameList = this.getClassNameList(this.filePath + "model\\");
String content = "";
for (String className : classNameList) {
content = "package " + this.packageName + ".dao;\n\n"
+ "import " + this.packageName + ".model." + className + ";\n\n"
+ "public interface " + className + "Dao" + " extends HibernateDao<" + className + "> {\n\n"
+ "}\n";
this.createFile(filePath + "dao\\" + className + "Dao.java", content);
content = "package " + this.packageName + ".dao.impl;\n\n"
+ "import " + this.packageName + ".dao." + className + "Dao;\n"
+ "import " + this.packageName + ".model." + className + ";\n\n"
+ "public class " + className + "DaoImpl extends HibernateDaoSupport<" + className + "> implements " + className + "Dao {\n\n"
+ "}";
this.createFile(filePath + "dao\\impl\\" + className + "DaoImpl.java", content);
content = "<bean id=\"" + className.substring(0, 1).toLowerCase() + className.substring(1) + "Dao\" class=\"" + this.packageName + ".dao.impl." + className + "DaoImpl\">\n"
+ " <property name=\"sessionFactory\"><ref bean=\"sessionFactory\" /></property>\n"
+ "</bean>\n";
System.out.print(content);
}
}

public List<String> getClassNameList(String path) {
List<String> list = new ArrayList<String>();
File file = new File(path);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
String fileName = files[i].getName();
if (".java".equals(fileName
.substring(fileName.lastIndexOf(".")))) {
list.add(fileName.substring(0, fileName.lastIndexOf(".")));
}
}
}
return list;
}

public void createFile(String fileName, String content) {
try {
FileWriter fw = new FileWriter(fileName);
fw.write(content);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
new BatchBuildDao();
}

}