| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- package com.izouma.codegenerator;
- import com.izouma.awesomeadmin.model.GenCode;
- import org.apache.velocity.Template;
- import org.apache.velocity.VelocityContext;
- import org.apache.velocity.app.Velocity;
- import org.apache.velocity.tools.ToolManager;
- import org.hibernate.validator.internal.util.privilegedactions.GetResource;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.OutputStreamWriter;
- import java.util.*;
- public class ModelGenerator {
- public static void GenModel(GenCode model) {
- try {
- List<String> imports = new ArrayList<>(GeneratorTool.getImports(model));
- imports = GeneratorTool.removeDuplicated(imports);
- String templatePath = GetResource.class.getClassLoader().getResource("templates").getPath();
- Properties pro = new Properties();
- pro.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
- pro.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templatePath);
- Velocity.init(pro);
- ToolManager manager = new ToolManager(true, true);
- VelocityContext context = new VelocityContext(manager.createContext());
- context.put("imports", imports);
- context.put("model", model);
- Template t = Velocity.getTemplate("ModelTemplate.vm");
- String targetFile = model.getClassName() + ".java";
- File file = new File(model.getJavaPath() + "/model", targetFile);
- if (!file.getParentFile().exists())
- file.getParentFile().mkdirs();
- if (!file.exists())
- file.createNewFile();
- FileOutputStream outStream = new FileOutputStream(file);
- OutputStreamWriter writer = new OutputStreamWriter(outStream,
- "UTF-8");
- BufferedWriter sw = new BufferedWriter(writer);
- t.merge(context, sw);
- sw.flush();
- sw.close();
- outStream.close();
- System.out.println("成功生成Model:" + file.getAbsolutePath());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
|