Java Code Examples for org.apache.velocity.Template

The following examples show how to use org.apache.velocity.Template. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: supplierShop   Source File: GenTableServiceImpl.java    License: MIT License 6 votes vote down vote up
/**
 * 预览代码
 * 
 * @param tableId 表编号
 * @return 预览数据列表
 */
public Map<String, String> previewCode(Long tableId)
{
    Map<String, String> dataMap = new LinkedHashMap<>();
    // 查询表信息
    GenTable table = genTableMapper.selectGenTableById(tableId);
    // 查询列信息
    List<GenTableColumn> columns = table.getColumns();
    setPkColumn(table, columns);
    VelocityInitializer.initVelocity();

    VelocityContext context = VelocityUtils.prepareContext(table);

    // 获取模板列表
    List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
    for (String template : templates)
    {
        // 渲染模板
        StringWriter sw = new StringWriter();
        Template tpl = Velocity.getTemplate(template, Constants.UTF8);
        tpl.merge(context, sw);
        dataMap.put(template, sw.toString());
    }
    return dataMap;
}
 
Example 2
Source Project: XBatis-Code-Generator   Source File: VelocityTemplate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 根据模版和参数生成指定的文件
 * @param template
 * @param outfileName
 * @param context
 * @throws Exception
 */
private static void mergeTemplate(Template template, String outfileName,
		VelocityContext context) throws Exception {
	/*
	 * Now have the template engine process your template using the data
	 * placed into the context. Think of it as a 'merge' of the template and
	 * the data to produce the output stream.
	 */
	BufferedWriter writer = new BufferedWriter(new FileWriter(outfileName));

	if (template != null)
		template.merge(context, writer);

	/*
	 * flush and cleanup
	 */
	writer.flush();
	writer.close();
}
 
Example 3
Source Project: zheng   Source File: VelocityUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 根据模板生成文件
 * @param inputVmFilePath 模板路径
 * @param outputFilePath 输出文件路径
 * @param context
 * @throws Exception
 */
public static void generate(String inputVmFilePath, String outputFilePath, VelocityContext context) throws Exception {
	try {
		Properties properties = new Properties();
		properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, getPath(inputVmFilePath));
		Velocity.init(properties);
		//VelocityEngine engine = new VelocityEngine();
		Template template = Velocity.getTemplate(getFile(inputVmFilePath), "utf-8");
		File outputFile = new File(outputFilePath);
		FileWriterWithEncoding writer = new FileWriterWithEncoding(outputFile, "utf-8");
		template.merge(context, writer);
		writer.close();
	} catch (Exception ex) {
		throw ex;
	}
}
 
Example 4
Source Project: sc-generator   Source File: AbstractGenerator.java    License: Apache License 2.0 6 votes vote down vote up
protected void writePom(String srcPom, String destPom, String project, String packagePath) throws IOException {
    Template tempate = VelocityUtil.getTempate(srcPom);
    VelocityContext ctx = new VelocityContext();
    ctx.put("packagePath", packagePath);
    ctx.put("project", project);
    ctx.put("application", packagePath + "." + this.applicationName);
    ctx.put("driverClass", driverClass);
    ctx.put("serviceProject", serviceProject);
    ctx.put("serviceApiProject", serviceApiProject);
    ctx.put("parentProject", parentProject);
    ctx.put("springCloudVersion", springCloudVersion);
    ctx.put("springBootVersion", springBootVersion);
    for (Map.Entry<String, Object> entry : options.entrySet()) {
        ctx.put(entry.getKey(), entry.getValue());
    }
    StringWriter writer = new StringWriter();
    tempate.merge(ctx, writer);
    writer.close();
    write(writer.toString(), destPom);
}
 
Example 5
Source Project: java-course-ee   Source File: Test3.java    License: MIT License 6 votes vote down vote up
public Test3() throws Exception {
    //init
    Velocity.init("Velocity/GS_Velocity_1/src/main/java/velocity.properties");
    // get Template
    Template template = Velocity.getTemplate("Test3.vm");
    // getContext
    Context context = new VelocityContext();

    String name = "Vova";
    int age = 21;
    boolean flag = true;

    context.put("name", name);
    context.put("age", age);
    context.put("flag", flag);

    context.put("today", new Date());
    context.put("product", new Product("Book", 12.3));

    // get Writer
    Writer writer = new StringWriter();
    // merge
    template.merge(context, writer);

    System.out.println(writer.toString());
}
 
Example 6
Source Project: velocity-tools   Source File: VelocityViewTag.java    License: Apache License 2.0 6 votes vote down vote up
protected void renderContent(Writer out) throws Exception
{
    if (getTemplate() != null)
    {
        VelocityView view = getVelocityView();
        ViewToolContext context = getViewToolContext();

        // get the actual Template
        Template template = view.getTemplate(getTemplate());

        if (getBodyContent() != null)
        {
            context.put(getBodyContentKey(), getRenderedBody());
        }

        // render the template into the writer
        template.merge(context, out);
    }
    else
    {
        // render the body into the writer
        renderBody(out);
    }
}
 
Example 7
Source Project: velocity-engine   Source File: CustomParserTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMarkdownTemplate() throws Exception
{
    VelocityContext ctx = new VelocityContext();
    ctx.put("some", "value");
    Template tmpl = engine.getTemplate("test.md", "UTF-8");

    String resultFile = RESULTS_DIR + File.separator + "test.md";
    String referenceFile = REFERENCE_DIR + File.separator + "test.md";

    new File(resultFile).getParentFile().mkdirs();

    FileWriter writer = new FileWriter(resultFile);
    tmpl.merge(ctx, writer);
    writer.flush();
    writer.close();

    String result = IOUtils.toString(new FileInputStream(resultFile), "UTF-8");
    String reference = IOUtils.toString(new FileInputStream(referenceFile), "UTF-8");
    assertEquals(reference, result);
}
 
Example 8
Source Project: ueboot   Source File: CodeGenerator.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private String getTemplateString(String templateName, VelocityContext context) {
    Properties p = new Properties();
    String path = Thread.currentThread().getContextClassLoader().getResource("velocity").getFile();
    p.setProperty(Velocity.RESOURCE_LOADER, "class");
    p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
    p.setProperty("class.resource.loader.path", path);
    p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
    p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
    Velocity.init(p);

    Template template = Velocity.getTemplate("velocity" + separator + "uebootv2" + separator + templateName, "UTF-8");
    StringWriter writer = new StringWriter();
    template.merge(context, writer);
    return writer.toString();
}
 
Example 9
Source Project: sc-generator   Source File: AbstractGenerator.java    License: Apache License 2.0 6 votes vote down vote up
protected void writeBin(String destDir, String project, String packagePath) throws IOException {
    String binPath = getBinPath();
    List<String> files = getBinFiles();
    for (String fileName : files) {
        String file = binPath + fileName;
        Template template = VelocityUtil.getTempate(file);
        VelocityContext ctx = new VelocityContext();
        ctx.put("packagePath", packagePath);
        ctx.put("project", project);
        if (file.contains("shutdown")) {
            ctx.put("application", this.applicationName);

        } else {
            ctx.put("application", packagePath + "." + this.applicationName);
        }
        StringWriter writer = new StringWriter();
        template.merge(ctx, writer);
        writer.close();
        write(writer.toString(), destDir + fileName);
    }
}
 
Example 10
public String generateSubstituteSwaggerForService(InstanceInfo service,
                                                  ApiInfo api,
                                                  String gatewayScheme, String gatewayHost) {
    String title = service.getMetadata().get(SERVICE_TITLE);
    String description = service.getMetadata().get(SERVICE_DESCRIPTION);
    String basePath = (api.getGatewayUrl().startsWith("/") ? "" : "/") + api.getGatewayUrl()
        + (api.getGatewayUrl().endsWith("/") ? "" : "/") + service.getAppName().toLowerCase();

    Template t = ve.getTemplate("substitute_swagger.json");
    VelocityContext context = new VelocityContext();
    context.put("title", title);
    context.put("description", description);
    context.put("version", api.getVersion());
    context.put("scheme", gatewayScheme);
    context.put("host", gatewayHost);
    context.put("basePath", basePath);
    context.put("documentationUrl", api.getDocumentationUrl());

    StringWriter w = new StringWriter();
    t.merge(context, w);

    return w.toString();
}
 
Example 11
Source Project: titan1withtp3.1   Source File: AbstractTitanAssemblyIT.java    License: Apache License 2.0 6 votes vote down vote up
protected void parseTemplateAndRunExpect(String expectTemplateName, Map<String, String> contextVars) throws IOException, InterruptedException {
    VelocityContext context = new VelocityContext();
    for (Map.Entry<String, String> ent : contextVars.entrySet()) {
        context.put(ent.getKey(), ent.getValue());
    }

    Template template = Velocity.getTemplate(expectTemplateName);
    String inputPath = EXPECT_DIR + File.separator + expectTemplateName;
    String outputPath = inputPath.substring(0, inputPath.length() - 3);

    Writer output = new FileWriter(outputPath);
    template.merge(context, output);
    output.close();

    expect(ZIPFILE_EXTRACTED, outputPath);
}
 
Example 12
Source Project: testgrid   Source File: ScenarioExecutor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method prepares the content of the run-scenario script which will include complete shell commands including
 * script file names.
 * @param  files sorted list of files needs to be added to the script
 * @return content of the run-scenario.sh script
 */
private String prepareScriptContent(List<String> files) {
        VelocityEngine velocityEngine = new VelocityEngine();
        //Set velocity class loader as to refer templates from resources directory.
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());

        velocityEngine.init();
        VelocityContext context = new VelocityContext();
        context.put("scripts", files);

        Template template = velocityEngine.getTemplate(RUN_SCENARIO_SCRIPT_TEMPLATE);
        StringWriter writer = new StringWriter();
        template.merge(context, writer);
        return writer.toString();
}
 
Example 13
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String method=retriveMethod(req);
	if(method!=null){
		invokeMethod(method, req, resp);
	}else{
		VelocityContext context = new VelocityContext();
		context.put("contextPath", req.getContextPath());
		String file=req.getParameter("file");
		String project = buildProjectNameFromFile(file);
		if(project!=null){
			context.put("project", project);
		}
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		Template template=ve.getTemplate("html/scriptdecisiontable-editor.html","utf-8");
		PrintWriter writer=resp.getWriter();
		template.merge(context, writer);
		writer.close();
	}
}
 
Example 14
Source Project: urule   Source File: PermissionConfigServletHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	if(!((PermissionService)permissionStore).isAdmin()){
		throw new NoPermissionException();
	}
	String method=retriveMethod(req);
	if(method!=null){
		invokeMethod(method, req, resp);
	}else{
		VelocityContext context = new VelocityContext();
		context.put("contextPath", req.getContextPath());
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		Template template=ve.getTemplate("html/permission-config-editor.html","utf-8");
		PrintWriter writer=resp.getWriter();
		template.merge(context, writer);
		writer.close();
	}
}
 
Example 15
Source Project: urule   Source File: RuleFlowDesignerServletHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String method=retriveMethod(req);
	if(method!=null){
		invokeMethod(method, req, resp);
	}else{
		VelocityContext context = new VelocityContext();
		context.put("contextPath", req.getContextPath());
		String file=req.getParameter("file");
		String project = buildProjectNameFromFile(file);
		if(project!=null){
			context.put("project", project);
		}
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		Template template=ve.getTemplate("html/rule-flow-designer.html","utf-8");
		PrintWriter writer=resp.getWriter();
		template.merge(context, writer);
		writer.close();
	}
}
 
Example 16
public static void main(String args[]) {
	/* 1.初始化 Velocity */
	VelocityEngine velocityEngine = new VelocityEngine();
	velocityEngine.setProperty(VelocityEngine.RESOURCE_LOADER, "file");
	velocityEngine.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH,
		"D:/01_Workspace/Project/zp/javaparty/src/toolbox/template/src/main/resources");
	velocityEngine.init();

	/* 2.创建一个上下文对象 */
	VelocityContext context = new VelocityContext();

	/* 3.添加你的数据对象到上下文 */
	context.put("name", "Victor Zhang");
	context.put("project", "Velocity");

	/* 4.选择一个模板 */
	Template template = velocityEngine.getTemplate("template/hello.vm");

	/* 5.将你的数据与模板合并,产生输出内容 */
	StringWriter sw = new StringWriter();
	template.merge(context, sw);
	System.out.println("final output:\n" + sw);
}
 
Example 17
public void testLogResult()
    throws Exception
{
    VelocityContext context = new VelocityContext();
    Template template = Velocity.getTemplate("macros.vm");

    // try to get only messages during merge
    logger.startCapture();
    template.merge(context, new StringWriter());
    logger.stopCapture();

    String resultLog = logger.getLog();
    if ( !isMatch(resultLog, COMPARE_DIR, "velocity.log", "cmp"))
    {
        String compare = getFileContents(COMPARE_DIR, "velocity.log", CMP_FILE_EXT);

        String msg = "Log output was incorrect\n"+
            "-----Result-----\n"+ resultLog +
            "----Expected----\n"+ compare +
            "----------------";

        fail(msg);
    }
}
 
Example 18
Source Project: sunbird-lms-service   Source File: OTPService.java    License: MIT License 6 votes vote down vote up
public static String getSmsBody(String templateFile, Map<String, String> smsTemplate) {
  try {
    String sms = getOTPSMSTemplate(templateFile);
    RuntimeServices rs = RuntimeSingleton.getRuntimeServices();
    SimpleNode sn = rs.parse(sms, "Sms Information");
    Template t = new Template();
    t.setRuntimeServices(rs);
    t.setData(sn);
    t.initDocument();
    VelocityContext context = new VelocityContext();
    context.put(JsonKey.OTP, smsTemplate.get(JsonKey.OTP));
    context.put(
        JsonKey.OTP_EXPIRATION_IN_MINUTES, smsTemplate.get(JsonKey.OTP_EXPIRATION_IN_MINUTES));
    context.put(
        JsonKey.INSTALLATION_NAME,
        ProjectUtil.getConfigValue(JsonKey.SUNBIRD_INSTALLATION_DISPLAY_NAME));

    StringWriter writer = new StringWriter();
    t.merge(context, writer);
    return writer.toString();
  } catch (Exception ex) {
    ProjectLogger.log(
        "OTPService:getSmsBody: Exception occurred with error message = " + ex.getMessage(), ex);
  }
  return "";
}
 
Example 19
Source Project: springboot-learn   Source File: MailUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 获取velocity邮件模板内容
 *
 * @param map 模板中需替换的参数内容
 * @return
 */
public static String getTemplateText(String templatePath, String charset, Map<String, Object> map) {
    String templateText;
    // 设置velocity资源加载器
    Properties prop = new Properties();
    prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    Velocity.init(prop);
    VelocityContext context = new VelocityContext(map);
    // 渲染模板
    StringWriter sw = new StringWriter();
    Template template = Velocity.getTemplate(templatePath, charset);
    template.merge(context, sw);
    try {
        templateText = sw.toString();
        sw.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("模板渲染失败");
    }
    return templateText;
}
 
Example 20
@Override
protected void writeUIOther(String destResourcePath, List<String> tables, List<String> modelNames,List<String> varModelNames) throws IOException {
    Template indexHtml = VelocityUtil.getTempate("/templates/pom/ui/thymeleaf/index.vm");
    Template indexJs = VelocityUtil.getTempate("/templates/pom/ui/thymeleaf/indexjs.vm");
    Template commonJs = VelocityUtil.getTempate("/templates/pom/ui/thymeleaf/common.vm");
    VelocityContext ctx= new VelocityContext();
    ctx.put("modelNames",modelNames);
    ctx.put("tables",tables);
    ctx.put("varModelNames",varModelNames);
    ctx.put("project", VelocityUtil.tableNameConvertModelName(this.project.split("-")[0]));
    ctx.put("miniProject", VelocityUtil.tableNameConvertModelName(this.project.split("-")[0]).substring(0, 1));
    write(merge(indexHtml,ctx),destResourcePath+"/static/index.html");
    write(merge(indexJs,ctx),destResourcePath+"/static/js/index.js");
    write(merge(commonJs,ctx),destResourcePath+"/static/js/common.js");
}
 
Example 21
Source Project: supplierShop   Source File: GenTableServiceImpl.java    License: MIT License 5 votes vote down vote up
/**
 * 查询表信息并生成代码
 */
private void generatorCode(String tableName, ZipOutputStream zip)
{
    // 查询表信息
    GenTable table = genTableMapper.selectGenTableByName(tableName);
    // 查询列信息
    List<GenTableColumn> columns = table.getColumns();
    setPkColumn(table, columns);

    VelocityInitializer.initVelocity();

    VelocityContext context = VelocityUtils.prepareContext(table);

    // 获取模板列表
    List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
    for (String template : templates)
    {
        // 渲染模板
        StringWriter sw = new StringWriter();
        Template tpl = Velocity.getTemplate(template, Constants.UTF8);
        tpl.merge(context, sw);
        try
        {
            // 添加到zip
            zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
            IOUtils.write(sw.toString(), zip, Constants.UTF8);
            IOUtils.closeQuietly(sw);
            zip.closeEntry();
        }
        catch (IOException e)
        {
            log.error("渲染模板失败,表名:" + table.getTableName(), e);
        }
    }
}
 
Example 22
Source Project: erp-framework   Source File: Generator.java    License: MIT License 5 votes vote down vote up
public void generateMapper(String targetDir, Table table) {
    VelocityEngine velocityEngine = createVelocityEngine();
    VelocityContext context = createContext(table);
    Writer writer = createWriter(targetDir, configure.getMapperPackage()
            .replace(".", "/") + "/" + table.getBeanName() + "Mapper.java");
    Template t = velocityEngine.getTemplate("mapperTemplate.vm");

    t.merge(context, writer);
    flushWriter(writer);
}
 
Example 23
Source Project: sc-generator   Source File: VelocityUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Template getTempate(String path) {
	VelocityEngine ve = new VelocityEngine();
	ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
	ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
	ve.init();
	Template t = ve.getTemplate(path, "utf-8");
	return t;
}
 
Example 24
Source Project: erp-framework   Source File: Generator.java    License: MIT License 5 votes vote down vote up
public void generateServiceImpl(String targetDir, Table table) {
    VelocityEngine velocityEngine = createVelocityEngine();
    VelocityContext context = createContext(table);
    Writer writer = createWriter(targetDir, configure.getServiceImplPackage()
            .replace(".", "/") + "/" + table.getBeanName() + "ServiceImpl.java");
    Template t = velocityEngine.getTemplate("serviceImplTemplate.vm");

    t.merge(context, writer);
    flushWriter(writer);
}
 
Example 25
public void writeAuditResultConsoleBeanGenerate(VelocityContext context,
        Template temp) throws IOException {
    StringWriter wr = new StringWriter();
    context.put("themes", vpc.getThemes());
    temp.merge(context, wr);
    File beansAuditResultConsoleFile = new File(vpc.getDestinationFolder()
            + "/src/main/resources/conf/context/"
            + vpc.getReferential().replace(".", "").toLowerCase()
            + "/web-app/mvc/form/" + "tgol-beans-"
            + vpc.getReferential().replace(".", "").toLowerCase()
            + "-audit-result-console-form.xml");
    FileUtils.writeStringToFile(beansAuditResultConsoleFile, wr.toString());
}
 
Example 26
Source Project: velocity-engine   Source File: DBContextTest.java    License: Apache License 2.0 5 votes vote down vote up
public DBContextTest(String templateFile)
{
    try
    {
        RuntimeSingleton.init( new Properties() );

        Template template = RuntimeSingleton.getTemplate(templateFile);

        DBContext dbc = new DBContext();

        Hashtable h = new Hashtable();
        h.put("Bar", "this is from a hashtable!");

        dbc.put( "string", "Hello!");
        dbc.put( "hashtable", h );

        Writer writer = new BufferedWriter(new OutputStreamWriter(System.out));

        template.merge(dbc, writer);

        writer.flush();
        writer.close();
    }
    catch( Exception e )
    {
        RuntimeSingleton.getLog().error("Something funny happened", e);
    }
}
 
Example 27
/**
 * 根据绝对路径加载,vm文件置于硬盘某分区中
 */
public static void loadByFilepath() {
	System.out.println("========== loadByFilepath ==========");

	Properties p = new Properties();
	p.put(VelocityEngine.FILE_RESOURCE_LOADER_PATH,
		"D:\\01_Workspace\\Project\\zp\\javaparty\\src\\toolbox\\template\\src\\main\\resources");
	VelocityEngine ve = new VelocityEngine();
	ve.init(p);
	Template t = ve.getTemplate("hello.vm");

	System.out.println(fillTemplate(t));
}
 
Example 28
Source Project: neoprofiler   Source File: HTMLMaker.java    License: Apache License 2.0 5 votes vote down vote up
public void html(DBProfile profile, Writer writer) throws IOException {
	VelocityEngine ve = new VelocityEngine();
       
	ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); 
	ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
	
	ve.init();
       
	Template t = null;
	
	if(ve.resourceExists("/template.html"))
		t = ve.getTemplate("/template.html");
	else {
		try { 
			t = ve.getTemplate("src/main/resources/template.html");				
		} catch(Exception exc) { 
			System.err.println("The application could not find a needed HTML template.");
			System.err.println("This is an unusual problem; please report it as an issue, and provide details of your configuration.");
			throw new RuntimeException("Could not find HTML template as resource.");
		}
	}
	
       VelocityContext context = new VelocityContext();

       StringWriter markdownContent = new StringWriter();
       
       // Write markdown content....
       new MarkdownMaker().markdown(profile, markdownContent);
       
       context.put("title", profile.getName());
       context.put("markdown", markdownContent.getBuffer().toString());
       context.put("links", generateGraph(profile)); 
       //context.put("d3graph", d3graph.toString());

       // Dump the contents of the template merged with the context.  That's it!
       t.merge(context, writer);
}
 
Example 29
Source Project: velocity-engine   Source File: TemplateTestCase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Runs the test.
 */
public void runTest ()
    throws Exception
{
    Template template = RuntimeSingleton.getTemplate
        (getFileName(null, baseFileName, TMPL_FILE_EXT));

    assureResultsDirectoryExists(RESULT_DIR);

    /* get the file to write to */
    FileOutputStream fos =
        new FileOutputStream (getFileName(
            RESULT_DIR, baseFileName, RESULT_FILE_EXT));

    Writer writer = new BufferedWriter(new OutputStreamWriter(fos));

    /* process the template */
    template.merge( context, writer);

    /* close the file */
    writer.flush();
    writer.close();

    if (!isMatch(RESULT_DIR,COMPARE_DIR,baseFileName,
            RESULT_FILE_EXT,CMP_FILE_EXT))
    {
        fail("Processed template "+getFileName(
            RESULT_DIR, baseFileName, RESULT_FILE_EXT)+" did not match expected output");
    }
}
 
Example 30
Source Project: NutzSite   Source File: GenServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * 生成代码
     *
     * @param table
     * @param columns
     * @param zip
     * @param templates 模板列表
     */
    private static void coding(TableInfo table, List<ColumnInfo> columns, ZipOutputStream zip, List<String> templates) {
        // 表名转换成Java属性名
        String className = GenUtils.tableToJava(table.getTableName());
        table.setClassName(className);
        table.setClassname(StringUtils.uncapitalize(className));
        // 列信息
        table.setColumns(GenUtils.transColums(columns));
        // 设置主键
        table.setPrimaryKey(table.getColumnsLast());

        VelocityInitializer.initVelocity();
        String packageName = GenConfig.getPackageName();
        String moduleName = GenUtils.getModuleName(packageName);
        VelocityContext context = GenUtils.getVelocityContext(table);

        // 获取模板列表
//        List<String> templates = GenUtils.getListTemplates();
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Globals.UTF8);
            tpl.merge(context, sw);
            try {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(GenUtils.getFileName(template, table, moduleName)));
                IOUtils.write(sw.toString(), zip, Globals.UTF8);
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                e.printStackTrace();
                throw new ErrorException("渲染模板失败,表名:" + table.getTableName());
            }
        }
    }