freemarker.template.Template Java Examples

The following examples show how to use freemarker.template.Template. 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 File: AttributeExpander.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a (String)TemplateInvoker with compiled Freemarker template for the attribute
 * content inline template.
 * <p>
 * TODO: decide cache... can make CmsAttributeTemplate-specific cache (by id or so, faster) but
 * may get memory duplication with #interpretStd calls (cached by body, because no id/name avail)
 * -> could do both at once maybe? share the Template instance between 2 cache...
 * TODO: subject to refactor/move
 * TODO?: FUTURE: this does NOT wrap the TemplateInvoker in a TemplateModel for time being...
 * we will rely on the default ObjectWrapper(s) to wrap the StringTemplateInvoker
 * in a freemarker StringModel (BeanModel) which renders throughs the ?string built-in
 * or string evaluation.
 */
public static TemplateInvoker getStringTemplateInvokerForContent(String tmplStr, Map<String, Object> ctxVars, CmsPageContext pageContext) throws TemplateException, IOException {
    Configuration config = CmsRenderTemplate.TemplateRenderer.getDefaultCmsConfig();

    // TODO: REVIEW: cache selection is a problem...
    // instead of by template body we could cache by some derivative unique name
    // derived from the CmsAttributeTemplate ID (maybe?)
    // would likely be much faster

    UtilCache<String, Template> cache = TemplateSource.getTemplateInlineSelfCacheForConfig(config, null);
    if (cache == null) {
        Debug.logWarning("Cms: could not determine"
                + " an inline template cache to use; not using cache", module);
    }
    TemplateSource templateSource = TemplateSource.getForInline(null, tmplStr, cache, config, true);

    // NOTE: must get StringInvoker so BeansWrapper's StringModel can invoke toString()
    // NOTE: context parameters could be passed to the template using InvokeOptions.ctxVars...
    // but not yet needed
    TemplateInvoker invoker = TemplateInvoker.getInvoker(templateSource, new InvokeOptions(null, null, null, ctxVars, false), null);
    return invoker;
}
 
Example #2
Source File: FreemarkerParseFactory.java    From jeecg-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 判断模板是否存在
 *
 * @throws Exception
 */
public static boolean isExistTemplate(String tplName) throws Exception {
    try {
        Template mytpl = _tplConfig.getTemplate(tplName, "UTF-8");
        if (mytpl == null) {
            return false;
        }
    } catch (Exception e) {
        //update-begin--Author:scott  Date:20180320 for:解决问题 - 错误提示sql文件不存在,实际问题是sql freemarker用法错误-----
        if (e instanceof ParseException) {
            log.error(e.getMessage(), e.fillInStackTrace());
            throw new Exception(e);
        }
        log.debug("----isExistTemplate----" + e.toString());
        //update-end--Author:scott  Date:20180320 for:解决问题 - 错误提示sql文件不存在,实际问题是sql freemarker用法错误------
        return false;
    }
    return true;
}
 
Example #3
Source File: FreemarkerParseFactory.java    From jeecg-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 解析ftl模板
 *
 * @param tplName 模板名
 * @param paras   参数
 * @return
 */
public static String parseTemplate(String tplName, Map<String, Object> paras) {
    try {
        log.debug(" minidao sql templdate : " + tplName);
        StringWriter swriter = new StringWriter();
        Template mytpl = _tplConfig.getTemplate(tplName, ENCODE);
        if (paras.containsKey(MINI_DAO_FORMAT)) {
            throw new RuntimeException("DaoFormat 是 minidao 保留关键字,不允许使用 ,请更改参数定义!");
        }
        paras.put(MINI_DAO_FORMAT, new SimpleFormat());
        mytpl.process(paras, swriter);
        String sql = getSqlText(swriter.toString());
        paras.remove(MINI_DAO_FORMAT);
        return sql;
    } catch (Exception e) {
        log.error(e.getMessage(), e.fillInStackTrace());
        log.error("发送一次的模板key:{ " + tplName + " }");
        //System.err.println(e.getMessage());
        //System.err.println("模板名:{ "+ tplName +" }");
        throw new RuntimeException("解析SQL模板异常");
    }
}
 
Example #4
Source File: DatabaseGenerator.java    From j-road with Apache License 2.0 6 votes vote down vote up
public static void generate(DatabaseClasses classes, String outputdir) throws IOException, TemplateException {
  Configuration cfg = new Configuration();
  cfg.setClassForTemplateLoading(TypeGen.class, "/");
  cfg.setObjectWrapper(new DefaultObjectWrapper());

  Template interfaceTemp = cfg.getTemplate(DATABASE_TEMPLATE_FILE);
  Template implTemp = cfg.getTemplate(DATABASE_IMPL_TEMPLATE_FILE);

  for (DatabaseClass databaseClass : classes.getClasses().values()) {
    Map<String, DatabaseClass> root = new HashMap<String, DatabaseClass>();
    root.put("databaseClass", databaseClass);

    Writer out = FileUtil.createAndGetOutputStream(databaseClass.getQualifiedInterfaceName(), outputdir);
    interfaceTemp.process(root, out);
    out.flush();

    out = FileUtil.createAndGetOutputStream(databaseClass.getQualifiedImplementationName(), outputdir);
    implTemp.process(root, out);
    out.flush();
  }
}
 
Example #5
Source File: RuleCreator.java    From support-rulesengine with Apache License 2.0 6 votes vote down vote up
public String createDroolRule(Rule rule) throws TemplateException, IOException {
  try {
    Template temp = cfg.getTemplate(templateName);
    Writer out = new StringWriter();
    temp.process(createMap(rule), out);
    return out.toString();
  } catch (IOException iE) {
    logger.error("Problem getting rule template file." + iE.getMessage());
    throw iE;
  } catch (TemplateException tE) {
    logger.error("Problem writing Drool rule." + tE.getMessage());
    throw tE;
  } catch (Exception e) {
    logger.error("Problem creating rule: " + e.getMessage());
    throw e;
  }
}
 
Example #6
Source File: StaticPageServiceImpl.java    From halo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generate tags/index.html.
 *
 * @throws IOException       IOException
 * @throws TemplateException TemplateException
 */
private void generateTags() throws IOException, TemplateException {
    log.info("Generate tags.html");

    ModelMap model = new ModelMap();

    if (!themeService.templateExists("tags.ftl")) {
        log.warn("tags.ftl not found,skip!");
        return;
    }

    model.addAttribute("is_tags", true);
    Template template = freeMarkerConfigurer.getConfiguration().getTemplate(themeService.renderWithSuffix("tags"));
    String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    FileWriter fileWriter = new FileWriter(getPageFile("tags/index.html"), "UTF-8");
    fileWriter.write(html);

    log.info("Generate tags.html succeed.");

    List<Tag> tags = tagService.listAll();
    for (Tag tag : tags) {
        generateTag(1, tag);
    }
}
 
Example #7
Source File: TrasformazioniUtils.java    From govpay with GNU General Public License v3.0 6 votes vote down vote up
private static void _convertFreeMarkerTemplate(String name, byte[] template, Map<String,Object> dynamicMap, Writer writer) throws TrasformazioneException {
	try {
		// ** Aggiungo utility per usare metodi statici ed istanziare oggetti

		// statici
		BeansWrapper wrapper = new BeansWrapper(Configuration.VERSION_2_3_23);
		TemplateModel classModel = wrapper.getStaticModels();
		dynamicMap.put(Costanti.MAP_CLASS_LOAD_STATIC, classModel);

		// newObject
		dynamicMap.put(Costanti.MAP_CLASS_NEW_INSTANCE, new freemarker.template.utility.ObjectConstructor());


		// ** costruisco template
		Template templateFTL = TemplateUtils.buildTemplate(name, template);
		templateFTL.process(dynamicMap, writer);
		writer.flush();

	}catch(Exception e) {
		throw new TrasformazioneException(e.getMessage(),e);
	}
}
 
Example #8
Source File: MavenUtils.java    From camel-kafka-connector with Apache License 2.0 6 votes vote down vote up
public static Template getTemplate(File templateFile) throws IOException {
    Configuration cfg = new Configuration(Configuration.getVersion());

    cfg.setTemplateLoader(new URLTemplateLoader() {
        @Override
        protected URL getURL(String name) {
            try {
                return new URL(name);
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return null;
            }
        }
    });

    cfg.setDefaultEncoding("UTF-8");
    cfg.setLocalizedLookup(false);
    Template template = cfg.getTemplate(templateFile.toURI().toURL().toExternalForm());
    return template;
}
 
Example #9
Source File: FreemarkerTemplateUtils.java    From collect-earth with MIT License 6 votes vote down vote up
public static boolean applyTemplate(File sourceTemplate, File destinationFile, Map<?, ?> data) throws IOException, TemplateException{
	boolean success = false;

	// Console output
	try ( BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destinationFile), Charset.forName("UTF-8"))) ) {

		// Process the template file using the data in the "data" Map
		final Configuration cfg = new Configuration( new Version("2.3.23"));
		cfg.setDirectoryForTemplateLoading(sourceTemplate.getParentFile());

		// Load template from source folder
		final Template template = cfg.getTemplate(sourceTemplate.getName());

		template.process(data, fw);
		success = true;
	}catch (Exception e) {
		logger.error("Error reading FreeMarker template", e);
	} 
	return success;

}
 
Example #10
Source File: MailServiceImpl.java    From SENS with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 发送带有附件的邮件
 *
 * @param to           接收者
 * @param subject      主题
 * @param content      内容
 * @param templateName 模板路径
 * @param attachSrc    附件路径
 */
@Override
public void sendAttachMail(String to, String subject, Map<String, Object> content, String templateName, String attachSrc) {
    //配置邮件服务器
    SensUtils.configMail(
            SensConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_HOST.getProp()),
            SensConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_USERNAME.getProp()),
            SensConst.OPTIONS.get(BlogPropertiesEnum.MAIL_SMTP_PASSWORD.getProp()));
    File file = new File(attachSrc);
    String text = "";
    try {
        Template template = freeMarker.getConfiguration().getTemplate(templateName);
        text = FreeMarkerTemplateUtils.processTemplateIntoString(template, content);
        OhMyEmail.subject(subject)
                .from(SensConst.OPTIONS.get(BlogPropertiesEnum.MAIL_FROM_NAME.getProp()))
                .to(to)
                .html(text)
                .attach(file, file.getName())
                .send();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #11
Source File: FreemarkerExecutor.java    From cantor with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private String doProcess(final String name,
                         final String source,
                         final Context context,
                         final Map<String, String> params)
        throws IOException, TemplateException {

    final Template template = new Template(name, source, this.configuration);
    final StringWriter stringWriter = new StringWriter();

    // pass in context
    final Map<String, Object> model = new HashMap<>();
    model.put("context", context);
    model.put("params", params);
    // process the template
    template.process(model, stringWriter);
    return stringWriter.toString();
}
 
Example #12
Source File: PDFUtil.java    From erp-framework with MIT License 6 votes vote down vote up
/**
 * freemarker渲染html
 */
public static <T> String freeMarkerRender(T data, String htmlTmp) {
    Writer out = new StringWriter();
    try {
        // 获取模板,并设置编码方式
        Template template = freemarkerCfg.getTemplate(htmlTmp);
        template.setEncoding("UTF-8");
        // 合并数据模型与模板,将合并后的数据和模板写入到流中,这里使用的字符流
        template.process(data, out);
        out.flush();
        return out.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return null;
}
 
Example #13
Source File: StaticPageServiceImpl.java    From halo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generate categories/index.html.
 *
 * @throws IOException       IOException
 * @throws TemplateException TemplateException
 */
private void generateCategories() throws IOException, TemplateException {
    log.info("Generate categories.html");

    ModelMap model = new ModelMap();

    if (!themeService.templateExists("categories.ftl")) {
        log.warn("categories.ftl not found,skip!");
        return;
    }

    model.addAttribute("is_categories", true);
    Template template = freeMarkerConfigurer.getConfiguration().getTemplate(themeService.renderWithSuffix("categories"));
    String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    FileWriter fileWriter = new FileWriter(getPageFile("categories/index.html"), "UTF-8");
    fileWriter.write(html);

    List<Category> categories = categoryService.listAll();
    for (Category category : categories) {
        generateCategory(1, category);
    }

    log.info("Generate categories.html succeed.");
}
 
Example #14
Source File: AbstractOutputTestCase.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected void processThroughFreeMarker(String testString,
                                        String expectedResult)
{
	try
	{
		Configuration c = new Configuration(Configuration.VERSION_2_3_28);
		Template t = new Template("test", testString, c);
		StringWriter sw = new StringWriter();
		BufferedWriter bw = new BufferedWriter(sw);
		Map<String, Object> input = OutputDB.buildDataModel(id);
		t.process(input, bw);
		String s = sw.getBuffer().toString();
		assertEquals(expectedResult, s);
	}
	catch (IOException | TemplateException e)
	{
		e.printStackTrace();
		fail(e.getLocalizedMessage());
	}
}
 
Example #15
Source File: TemplateProcessor.java    From contribution with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Generates output file with release notes using FreeMarker.
 *
 * @param variables the map which represents template variables.
 * @param outputFile output file.
 * @param templateFileName the optional file name of the template.
 * @param defaultResource the resource file name to use if no file name was given.
 * @throws IOException if I/O error occurs.
 * @throws TemplateException if an error occurs while generating freemarker template.
 */
public static void generateWithFreemarker(Map<String, Object> variables, String outputFile,
        String templateFileName, String defaultResource) throws IOException, TemplateException {

    final Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
    configuration.setDefaultEncoding("UTF-8");
    configuration.setLocale(Locale.US);
    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    configuration.setNumberFormat("0.######");

    final StringTemplateLoader loader = new StringTemplateLoader();
    loader.putTemplate(TEMPLATE_NAME, loadTemplate(templateFileName, defaultResource));
    configuration.setTemplateLoader(loader);

    final Template template = configuration.getTemplate(TEMPLATE_NAME);
    try (Writer fileWriter = new OutputStreamWriter(
            new FileOutputStream(outputFile), StandardCharsets.UTF_8)) {
        template.process(variables, fileWriter);
    }
}
 
Example #16
Source File: PubsubEmitter.java    From zserio with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void emit(PubsubType pubsubType) throws ZserioEmitException
{
    try
    {
        Template tpl = cfg.getTemplate("doc/pubsub.html.ftl");
        setCurrentFolder(CONTENT_FOLDER);
        openOutputFileFromType(pubsubType);
        tpl.process(new PubsubTemplateData(getExpressionFormatter(), pubsubType, outputPath,
                withSvgDiagrams), writer);
    }
    catch (Throwable exception)
    {
        throw new ZserioEmitException(exception.getMessage());
    }
    finally
    {
        if (writer != null)
            writer.close();
    }
}
 
Example #17
Source File: CodeRenderer.java    From jpa-entity-generator with MIT License 6 votes vote down vote up
/**
 * Renders source code by using Freemarker template engine.
 */
public static String render(String templatePath, RenderingData data) throws IOException, TemplateException {
    Configuration config = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
    StringTemplateLoader templateLoader = new StringTemplateLoader();
    String source;
    try (InputStream is = ResourceReader.getResourceAsStream(templatePath);
         BufferedReader buffer = new BufferedReader(new InputStreamReader(is))) {
        source = buffer.lines().collect(Collectors.joining("\n"));
    }
    templateLoader.putTemplate("template", source);
    config.setTemplateLoader(templateLoader);
    config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    config.setObjectWrapper(new BeansWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
    config.setWhitespaceStripping(true);

    try (Writer writer = new java.io.StringWriter()) {
        Template template = config.getTemplate("template");
        template.process(data, writer);
        return writer.toString();
    }
}
 
Example #18
Source File: FreeMarkerEngine.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Override
public String render(ModelAndView modelAndView) {
    try {
        Template template = configuration.getTemplate(provider.layout(), "utf-8");
        Object model = modelAndView.getModel();
        if (model == null) {
            model = Collections.emptyMap();
        }
        if (model instanceof Map) {
            Map<String, Object> context = initialContextProvider.getContext((Map) model, controller, modelAndView.getViewName());
            StringWriter writer = new StringWriter();
            Object meta = context.get("meta");
            context.put("meta", GSON.toJson(meta));
            template.process(context, writer);
            return writer.toString();
        } else {
            throw new IllegalArgumentException("modelAndView must be of type java.util.Map");
        }
    } catch (IOException | TemplateException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #19
Source File: FreemarkerEmailTemplate.java    From LuckyFrameClient with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * ģ����������
 */
public String getText(String templateId, Map<Object, Object> parameters) {
    @SuppressWarnings("deprecation")
    Configuration configuration = new Configuration();
    configuration.setTemplateLoader(new ClassTemplateLoader(FreemarkerEmailTemplate.class, TEMPLATE_PATH));
    configuration.setDefaultEncoding("gbk");
    //configuration.setEncoding(Locale.getDefault(), "UTF-8");
    configuration.setDateFormat("yyyy-MM-dd HH:mm:ss");
    String templateFile = templateId + SUFFIX;
    try {
        Template template = TEMPLATE_CACHE.get(templateFile);
        if (template == null) {
            template = configuration.getTemplate(templateFile);
            TEMPLATE_CACHE.put(templateFile, template);
        }
        StringWriter stringWriter = new StringWriter();
        parameters.put("webip", WEB_IP);
        parameters.put("webport", WEB_PORT);
        template.process(parameters, stringWriter);
        return stringWriter.toString();
    } catch (Exception e) {
    	LogUtil.APP.error("��ȡ�ʼ�ģ���������ó����쳣",e);
        throw new RuntimeException(e);
    }
}
 
Example #20
Source File: FreemarkerHelper.java    From jeecg with Apache License 2.0 6 votes vote down vote up
/**
 * 解析ftl
 * @param tplName 模板名
 * @param encoding 编码
 * @param paras 参数
 * @return
 */
public String parseTemplate(String tplName, String encoding,
		Map<String, Object> paras) {
	try {
		StringWriter swriter = new StringWriter();
		Template mytpl = null;
		mytpl = _tplConfig.getTemplate(tplName, encoding);
		mytpl.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");  
		mytpl.setDateFormat("yyyy-MM-dd");
		mytpl.setTimeFormat("HH:mm:ss"); 
		mytpl.process(paras, swriter);
		return swriter.toString();
	} catch (Exception e) {
		e.printStackTrace();
		return e.toString();
	}

}
 
Example #21
Source File: FreemarkerParseFactory.java    From jeecg-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 解析ftl
 *
 * @param tplContent 模板内容
 * @param paras      参数
 * @return String 模板解析后内容
 */
public static String parseTemplateContent(String tplContent,
                                          Map<String, Object> paras) {
    try {
        StringWriter swriter = new StringWriter();
        if (stringTemplateLoader.findTemplateSource("sql_" + tplContent.hashCode()) == null) {
            stringTemplateLoader.putTemplate("sql_" + tplContent.hashCode(), tplContent);
        }
        Template mytpl = _sqlConfig.getTemplate("sql_" + tplContent.hashCode(), ENCODE);
        if (paras.containsKey(MINI_DAO_FORMAT)) {
            throw new RuntimeException("DaoFormat 是 minidao 保留关键字,不允许使用 ,请更改参数定义!");
        }
        paras.put(MINI_DAO_FORMAT, new SimpleFormat());
        mytpl.process(paras, swriter);
        String sql = getSqlText(swriter.toString());
        paras.remove(MINI_DAO_FORMAT);
        return sql;
    } catch (Exception e) {
        log.error(e.getMessage(), e.fillInStackTrace());
        log.error("发送一次的模板key:{ " + tplContent + " }");
        //System.err.println(e.getMessage());
        //System.err.println("模板内容:{ "+ tplContent +" }");
        throw new RuntimeException("解析SQL模板异常");
    }
}
 
Example #22
Source File: MagicWebSiteGenerator.java    From MtgDesktopCompanion with GNU General Public License v3.0 6 votes vote down vote up
private void generateEditionsTemplate(Set<MagicEdition> eds, MagicCollection col)throws IOException, SQLException, TemplateException {
	Template cardTemplate = cfg.getTemplate("page-ed.html");
	Map<String,Object> rootEd = new HashMap<>();
	rootEd.put("cols", cols);
	rootEd.put("editions", eds);
	rootEd.put("col", col);
	rootEd.put("colName", col.getName());
	for (MagicEdition ed : eds) {
		rootEd.put("cards", MTGControler.getInstance().getEnabled(MTGDao.class).listCardsFromCollection(col, ed));
		rootEd.put("edition", ed);
		FileWriter out = new FileWriter(
				Paths.get(dest, "page-ed-" + col.getName() + "-" + ed.getId() + ".htm").toFile());
		cardTemplate.process(rootEd, out);
	}

}
 
Example #23
Source File: FreemarkerHelper.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void processTemplate(Template template, Map model, File outputFile,String encoding) throws IOException, TemplateException {
    @Cleanup
    FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
    @Cleanup
    Writer out = new BufferedWriter(new OutputStreamWriter(fileOutputStream,encoding));
	template.process(model,out);
}
 
Example #24
Source File: RasterIngestRunner.java    From geowave with Apache License 2.0 5 votes vote down vote up
protected void processParameters(final OperationParams params) throws Exception {
  // Ensure we have all the required arguments
  if (parameters.size() != 2) {
    throw new ParameterException("Requires arguments: <store name> <comma delimited index list>");
  }
  final String inputStoreName = parameters.get(0);
  final String indexList = parameters.get(1);

  // Config file
  final File configFile = (File) params.getContext().get(ConfigOptions.PROPERTIES_FILE_CONTEXT);

  // Attempt to load input store.
  final StoreLoader inputStoreLoader = new StoreLoader(inputStoreName);
  if (!inputStoreLoader.loadFromConfig(configFile, params.getConsole())) {
    throw new ParameterException("Cannot find store name: " + inputStoreLoader.getStoreName());
  }
  dataStorePluginOptions = inputStoreLoader.getDataStorePlugin();
  store = dataStorePluginOptions.createDataStore();

  // Load the Indices
  indices =
      DataStoreUtils.loadIndices(dataStorePluginOptions.createIndexStore(), indexList).toArray(
          new Index[0]);

  coverageNameTemplate =
      new Template(
          "name",
          new StringReader(ingestOptions.getCoverageName()),
          new Configuration());
}
 
Example #25
Source File: MapperGenerator.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
private static void genMapper(String className,
                              String classComment,
                              String resourcePath,
                              GeneratorConfig generatorConfig) {
    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put("className", className);
    paramMap.put("classComment", classComment);
    paramMap.put("sysTime", new Date());
    paramMap.put("packageName", generatorConfig.getPackageName());
    ;

    Version version = new Version("2.3.27");
    Configuration configuration = new Configuration(version);
    try {
        URL url = MapperGenerator.class.getClassLoader().getResource(resourcePath);
        configuration.setDirectoryForTemplateLoading(new File(url.getPath()));
        configuration.setObjectWrapper(new DefaultObjectWrapper(version));
        String filePath = generatorConfig.getSrcBasePath() + "mapper//";
        String savePath = filePath + className + "Mapper.java";
        File dirPath = new File(filePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        try (FileWriter out = new FileWriter(new File(savePath))) {
            Template template = configuration.getTemplate("mapper.ftl");
            template.process(paramMap, out);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #26
Source File: TemplateFactory.java    From Mario with Apache License 2.0 5 votes vote down vote up
public StringWriter getStringWriter(String ftl, Map<String, Object> map)
		throws IOException, TemplateException {
	Template template = new Template(System.currentTimeMillis() + "",
			new StringReader(ftl), conf);
	StringWriter sw = new StringWriter();
	template.process(map, sw);
	return sw;
}
 
Example #27
Source File: ProjectTemplateLoader.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
public String process(String name, Map<String, Object> parameters) {
    try {
        Template template = myFreemarker.getTemplate(name);
        StringWriter writer = new StringWriter();
        template.process(TemplateUtils.createParameterMap(parameters), writer);
        return writer.toString();
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
    return null;
}
 
Example #28
Source File: DbTableProcess.java    From jeewx with Apache License 2.0 5 votes vote down vote up
public static void createOrDropTable(CgFormHeadEntity table, Session session) throws IOException, TemplateException, HibernateException, SQLException, DBException  {
	Template t;
	t = getConfig("/org/jeecgframework/web/cgform/engine/hibernate").getTemplate("tableTemplate.ftl");
	Writer out = new StringWriter();
	//模板对于数字超过1000,会自动格式为1,,000(禁止转换)
	t.setNumberFormat("0.#####################");
	t.process(getRootMap(table,DbTableUtil.getDataType(session)), out);
	String xml = out.toString();
	logger.info(xml);
	createTable(xml, table, session);
}
 
Example #29
Source File: FreemarkerUtil.java    From fun-generator with MIT License 5 votes vote down vote up
/**
 * process String
 */
public static String processString(String templateName, Map<String, Object> params)
        throws IOException, TemplateException {

    Template template = freemarkerConfig.getTemplate(templateName);
    return processTemplateIntoString(template, params);
}
 
Example #30
Source File: RenderComponentDirective.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
protected Template getTemplate(SiteItem component, Environment env) throws TemplateException {
    try {
        return env.getTemplateForInclusion(getComponentTemplateName(component, env), null, true);
    } catch (IOException e) {
        throw new TemplateException("Unable to retrieve component template", e, env);
    }
}