package FreeMarker;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class Test {
/**
* @param args
*/
@SuppressWarnings({ "deprecation", "unchecked", "rawtypes" })
public static void main(String[] args) {
//System.out.println(System.getProperty("user.dir")+"============");
Configuration cfg = new Configuration();
try {
cfg.setClassForTemplateLoading(Test.class, "/FreeMarker");//指定模板所在的classpath目录
cfg.setEncoding(Locale.CHINA, "gbk");
cfg.setSharedVariable("upperFC", new UpperFirstCharacter());//添加一个"宏"共享变量用来将属性名首字母大写
Template t = cfg.getTemplate("javabean.html");//指定模板
cfg.setSharedVariable("upperFC", new UpperFirstCharacter());//添加一个"宏"共享变量用来将属性名首字母大写
FileOutputStream fos = new FileOutputStream(new File("Item.java"));//java文件的生成目录
//模拟数据源
Map data = new HashMap();
data.put("basepackage", "com.ook");//包名
data.put("collection", "item");
data.put("entity", "Item");
data.put("entityDes", "商品entity");
SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
data.put("entityCt", df.format(new Date()));
List propertyList = new ArrayList();
Map proMap = new HashMap();
proMap.put("proType", String.class.getSimpleName());
proMap.put("proName", "name");
proMap.put("des", "");
propertyList.add(proMap);
proMap = new HashMap();
proMap.put("proType", Date.class.getSimpleName());
proMap.put("proName", "ct");
proMap.put("des", "//添加时间");
propertyList.add(proMap);
proMap = new HashMap();
proMap.put("proType", int.class.getSimpleName());
proMap.put("proName", "hotCnt");
proMap.put("des", "//阅读量");
propertyList.add(proMap);
data.put("properties", propertyList);
t.process(data, new OutputStreamWriter(fos,"utf-8"));//
fos.flush();
fos.close();
System.out.println("文件生成完毕~");
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
}
package FreeMarker;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
public class UpperFirstCharacter implements TemplateDirectiveModel{
@SuppressWarnings("rawtypes")
public void execute(Environment env,
Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body)
throws TemplateException, IOException {
// Check if no parameters were given:
if (!params.isEmpty()) {
throw new TemplateModelException(
"This directive doesn't allow parameters." );
}
if (loopVars.length != 0 ) {
throw new TemplateModelException(
"This directive doesn't allow loop variables." );
}
// If there is non-empty nested content:
if (body != null ) {
// Executes the nested body. Same as <#nested> in FTL, except
// that we use our own writer instead of the current output writer.
body.render(new UpperCaseFilterWriter(env.getOut()));
} else {
throw new RuntimeException( "missing body" );
}
}
/**
* A {@link Writer} that transforms the character stream to upper case
* and forwards it to another {@link Writer}.
*/
private static class UpperCaseFilterWriter extends Writer {
private final Writer out;
UpperCaseFilterWriter (Writer out) {
this .out = out;
}
public void write( char [] cbuf, int off, int len)
throws IOException {
// char[] transformedCbuf = new char[len];
// for (int i = 0; i < len; i++) {
// transformedCbuf[i] = Character.toUpperCase(cbuf[i + off]);
// }
// out.write(transformedCbuf);
cbuf[0 ] = Character.toUpperCase(cbuf[ 0 ]);
out.write(String.valueOf(cbuf).trim());///把右边空格去掉
}
public void flush() throws IOException {
out.flush();
}
public void close() throws IOException {
out.close();
}
}
}
package ${basepackage}.entity;
import java.util.Date;
import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* ${entityDes}
* @date ${entityCt}
*/
@Document(collection="${collection}")
public class ${entity} implements Serializable{
private static final long serialVersionUID = 1L;
@Id
private String id;
<#list properties as pro>
private ${pro.proType} ${pro.proName};${pro.des}
</#list>
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
<#list properties as pro>
public void set<@upperFC>${pro.proName}</@upperFC>(${pro.proType} ${pro.proName}){
this.${pro.proName}=${pro.proName};
}
public ${pro.proType} get<@upperFC>${pro.proName}</@upperFC>(){
return this.${pro.proName};
}
</#list>
}