freemarker.template.Version#freemarker.template.DefaultObjectWrapper源码实例Demo

下面列出了freemarker.template.Version#freemarker.template.DefaultObjectWrapper 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: fast-family-master   文件: DTOGenerator.java
private static void genDTO(Map<String, Object> paramMap,
                           String reousrcePath,
                           GeneratorConfig generatorConfig) {


    Version version = new Version("2.3.27");
    Configuration configuration = new Configuration(version);
    try {
        URL url = ControllerGenerator.class.getClassLoader().getResource(reousrcePath);
        configuration.setDirectoryForTemplateLoading(new File(url.getPath()));
        configuration.setObjectWrapper(new DefaultObjectWrapper(version));
        String filePath = generatorConfig.getSrcBasePath() + "dto//";
        String savePath = filePath + paramMap.get("className") + "DTO.java";
        File dirPath = new File(filePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        try (FileWriter fileWriter = new FileWriter(new File(savePath))) {
            Template template = configuration.getTemplate("dto.ftl");
            template.process(paramMap, fileWriter);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
源代码2 项目: fast-family-master   文件: MapperGenerator.java
private static void genMapperXml(Map<String, Object> params, String className, String resourcePath,
                                 GeneratorConfig generatorConfig) {

    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.xml";
        File dirPath = new File(filePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        try (FileWriter out = new FileWriter(new File(savePath))) {
            Template template = configuration.getTemplate("mapper_xml.ftl");
            template.process(params, out);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
源代码3 项目: pacbot   文件: MailService.java
@SuppressWarnings("deprecation")
public String processTemplate(String templateUrl, Map<String, Object> model) {
	try {
		if(templateUrl != null) {
			String mailBody = mailContentBuilderService.getRemoteMailContent(templateUrl);
			Configuration cfg = new Configuration();
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			Template t = new Template(UUID.randomUUID().toString(), new StringReader(mailBody), cfg);
		    Writer out = new StringWriter();
			t.process(model, out);
			return out.toString();
		}
	} catch (Exception exception) {
		Log.error(exception.getMessage());
	}
	return null;
}
 
源代码4 项目: sloth   文件: AbstractGeneratorStrategy.java
/**
 * base freemarker genarate method
 * @param templateData
 * @param templateFileRelativeDir
 * @param templateFileName
 * @param targetFileAbsoluteDir
 * @param targetFileName
 */
private void gen(Object templateData, String templateFileRelativeDir, String templateFileName, String targetFileAbsoluteDir, String targetFileName){
    try{
        Configuration configuration = new Configuration();
        configuration.setClassForTemplateLoading(Application.class, templateFileRelativeDir);
        configuration.setObjectWrapper(new DefaultObjectWrapper());
        Template template = configuration.getTemplate(templateFileName);
        template.setEncoding(encoding);
        if(!targetFileAbsoluteDir.endsWith(File.separator))
            targetFileAbsoluteDir+=File.separator;
        FileUtil.mkdir(targetFileAbsoluteDir);
        Writer fw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(targetFileAbsoluteDir + targetFileName)),encoding));
        template.process(templateData, fw);
    }catch (Throwable e){
        logger.error("Can not found the template file, path is \"" + templateFileRelativeDir + templateFileName +".\"");
        e.printStackTrace();
        throw new RuntimeException("IOException occur , please check !! ");
    }
}
 
@Override
protected Configuration getFreemarkerConfiguration(RepoCtx ctx)
{
    if (useRemoteCallbacks)
    {
        // as per 3.0, 3.1
        return super.getFreemarkerConfiguration(ctx);
    } 
    else
    {
        Configuration cfg = new Configuration();
        cfg.setObjectWrapper(new DefaultObjectWrapper());

        cfg.setTemplateLoader(new ClassPathRepoTemplateLoader(nodeService, contentService, defaultEncoding));

        // TODO review i18n
        cfg.setLocalizedLookup(false);
        cfg.setIncompatibleImprovements(new Version(2, 3, 20));
        cfg.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER);

        return cfg;
    }
}
 
@Override
protected ObjectWrapper initialValue()
{
    return new DefaultObjectWrapper()
    {
        /* (non-Javadoc)
         * @see freemarker.template.DefaultObjectWrapper#wrap(java.lang.Object)
         */
        @Override
        public TemplateModel wrap(Object obj) throws TemplateModelException
        {
            if (obj instanceof QNameMap)
            {
                return new QNameHash((QNameMap)obj, this);
            }
            else
            {
                return super.wrap(obj);
            }
        }
    };
}
 
源代码7 项目: myexcel   文件: FreemarkerTemplateHandler.java
private void setObjectWrapper(Configuration configuration) {
    configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23) {
        @Override
        public TemplateModel wrap(Object object) throws TemplateModelException {
            if (object instanceof LocalDate) {
                return new SimpleDate(Date.valueOf((LocalDate) object));
            }
            if (object instanceof LocalTime) {
                return new SimpleDate(Time.valueOf((LocalTime) object));
            }
            if (object instanceof LocalDateTime) {
                return new SimpleDate(Timestamp.valueOf((LocalDateTime) object));
            }
            return super.wrap(object);
        }
    });
}
 
源代码8 项目: Vert.X-generator   文件: CreateFileUtil.java
/**
 * 执行创建文件
 * 
 * @param content
 *          模板所需要的上下文
 * @param templeteName
 *          模板的名字 示例:Entity.ftl
 * @param projectPath
 *          生成的项目路径 示例:D://create
 * @param packageName
 *          包名 示例:com.szmirren
 * @param fileName
 *          文件名 示例:Entity.java
 * @param codeFormat
 *          输出的字符编码格式 示例:UTF-8
 * @throws Exception
 */
public static void createFile(GeneratorContent content, String templeteName, String projectPath, String packageName, String fileName,
		String codeFormat, boolean isOverride) throws Exception {
	String outputPath = projectPath + "/" + packageName.replace(".", "/") + "/";
	if (!isOverride) {
		if (Files.exists(Paths.get(outputPath + fileName))) {
			LOG.debug("设置了文件存在不覆盖,文件已经存在,忽略本文件的创建");
			return;
		}
	}
	Configuration config = new Configuration(Configuration.VERSION_2_3_23);
	String tempPath = Paths.get(Constant.TEMPLATE_DIR_NAME).toFile().getName();
	config.setDirectoryForTemplateLoading(new File(tempPath));
	config.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
	config.setDefaultEncoding("utf-8");
	Template template = config.getTemplate(templeteName);
	Map<String, Object> item = new HashMap<>();
	item.put("content", content);
	if (!Files.exists(Paths.get(outputPath))) {
		Files.createDirectories(Paths.get(outputPath));
	}
	try (Writer writer = new OutputStreamWriter(new FileOutputStream(outputPath + fileName), codeFormat)) {
		template.process(item, writer);
	}
}
 
源代码9 项目: enkan   文件: ValidatableFormAdapter.java
public ValidatableFormAdapter(Validatable form, DefaultObjectWrapper ow) {
    super(form, ow);
    this.hasErrors = arguments -> {
        switch (arguments.size()) {
            case 0:
                return (Boolean) form.hasErrors();
            case 1:
                return (Boolean) form.hasErrors(arguments.get(0).toString());
            default:
                return null;
        }
    };

    this.getErrors = arguments -> {
        switch (arguments.size()) {
            case 0:
                return form.getErrors();
            case 1:
                return form.getErrors(arguments.get(0).toString());
            default:
                return null;
        }
    };
}
 
public SourceReportGenerator(GradeCategories grades, SourceLoader sourceLoader,
    File outputDirectory, CostModel costModel, Date currentTime,
    int worstCount, Configuration cfg) {
  this.grades = grades;
  this.sourceLoader = sourceLoader;
  this.directory = outputDirectory;
  this.costModel = costModel;
  this.cfg = cfg;
  cfg.setTemplateLoader(new ClassPathTemplateLoader(PREFIX));
  cfg.setObjectWrapper(new DefaultObjectWrapper());
  try {
    cfg.setSharedVariable("maxExcellentCost", grades.getMaxExcellentCost());
    cfg.setSharedVariable("maxAcceptableCost", grades.getMaxAcceptableCost());
    cfg.setSharedVariable("currentTime", currentTime);
    cfg.setSharedVariable("computeOverallCost", new OverallCostMethod());
    cfg.setSharedVariable("printCost", new PrintCostMethod());
  } catch (TemplateModelException e) {
    throw new RuntimeException(e);
  }
  projectByClassReport = new ProjectReport("index", grades,
      new WeightedAverage());
  projectByClassReport.setMaxUnitCosts(worstCount);
  projectByPackageReport = new ProjectReport("index", grades,
      new WeightedAverage());
}
 
源代码11 项目: entando-core   文件: AbstractTestExecutorService.java
@Override
protected void setUp() throws Exception {
	super.setUp();
	try {
		Configuration config = new Configuration();
		DefaultObjectWrapper wrapper = new DefaultObjectWrapper();
		config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
		config.setObjectWrapper(wrapper);
		config.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER);
		TemplateModel templateModel = this.createModel(wrapper);
		ExecutorBeanContainer ebc = new ExecutorBeanContainer(config, templateModel);
		super.getRequestContext().addExtraParam(SystemConstants.EXTRAPAR_EXECUTOR_BEAN_CONTAINER, ebc);
	} catch (Throwable t) {
		throw new Exception(t);
	}
}
 
源代码12 项目: j-road   文件: DatabaseGenerator.java
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();
  }
}
 
源代码13 项目: rice   文件: XmlIngesterAftBase.java
protected List<File> buildUserFileUploadList() throws Exception {
    List<File> fileUploadList = new ArrayList<File>();
    try {
        Properties props = loadProperties(PROPS_LOCATION, DEFAULT_PROPS_LOCATION);

        String usersArg = System.getProperty("xmlingester.user.list").replace(".", "").replace("-", "").toLowerCase();
        List<XmlIngesterUser> xmlIngesterUsers = new LinkedList<XmlIngesterUser>();
        StringTokenizer token = new StringTokenizer(usersArg, ",");
        while (token.hasMoreTokens()) {
            xmlIngesterUsers.add(new XmlIngesterUser(token.nextToken()));
        }

        props.put("xmlIngesterUsers", xmlIngesterUsers);

        cfg.setObjectWrapper(new DefaultObjectWrapper());

        // build files and add to array
        fileUploadList.add(
                writeTemplateToFile(newTempFile("userlist-users.xml"), cfg.getTemplate("UserListIngestion.ftl"), props));

    } catch( Exception e) {
        throw new Exception("Unable to generate files for upload " + e.getMessage(), e);
    }

    return fileUploadList;
}
 
源代码14 项目: QuickProject   文件: FilesGenerator.java
public void generate() throws GlobalConfigException {
    Configuration cfg = new Configuration();
    File tmplDir = globalConfig.getTmplFile();
    try {
        cfg.setDirectoryForTemplateLoading(tmplDir);
    } catch (IOException e) {
        throw new GlobalConfigException("tmplPath", e);
    }
    cfg.setObjectWrapper(new DefaultObjectWrapper());
    for (Module module : modules) {
        logger.debug("module:" + module.getName());
        for (Bean bean : module.getBeans()) {
            logger.debug("bean:" + bean.getName());
            Map dataMap = new HashMap();
            dataMap.put("bean", bean);
            dataMap.put("module", module);
            dataMap.put("generate", generate);
            dataMap.put("config", config);
            dataMap.put("now", DateFormatUtils.ISO_DATE_FORMAT.format(new Date()));

            generate(cfg, dataMap);
        }
    }
}
 
源代码15 项目: fast-family-master   文件: ControllerGenerator.java
private static void genController(String className,
                                  String classComment,
                                  String urlStr,
                                  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());
    paramMap.put("url", urlStr);
    Version version = new Version("2.3.27");
    Configuration configuration = new Configuration(version);
    try {
        URL url = ControllerGenerator.class.getClassLoader().getResource(resourcePath);
        configuration.setDirectoryForTemplateLoading(new File(url.getPath()));
        configuration.setObjectWrapper(new DefaultObjectWrapper(version));
        String filePath = generatorConfig.getSrcBasePath() + "controller//";
        String savePath = filePath + className + "Controller.java";
        File dirPath = new File(filePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        try (FileWriter fileWriter = new FileWriter(new File(savePath))) {
            Template template = configuration.getTemplate("/controller.ftl");
            template.process(paramMap, fileWriter);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
源代码16 项目: fast-family-master   文件: EntityGenerator.java
public static void generatorSingleEntity(String tableName, String className,
                                         String classComment, GeneratorConfig generatorConfig) {
    TableInfo tableInfo = AnalysisDB.getTableInfoByName(tableName, generatorConfig);
    Map<String, Object> paramMap = new HashMap<>();

    paramMap.put("className", className);
    paramMap.put("tableInfo", tableInfo);
    paramMap.put("sysTime", new Date());
    paramMap.put("classComment", classComment);
    paramMap.put("packageName", generatorConfig.getPackageName());


    Version version = new Version("2.3.27");
    Configuration configuration = new Configuration(version);
    try {
        configuration.setObjectWrapper(new DefaultObjectWrapper(version));
        configuration.setDirectoryForTemplateLoading(new File(EntityGenerator.class.getClassLoader()
                .getResource("ftl").getPath()));
        String savePath = PackageDirUtils.getPackageEntityDir(generatorConfig.getSrcBasePath());
        String filePath = generatorConfig.getSrcBasePath() + "entity//";
        savePath = filePath + className + ".java";
        File dirPath = new File(filePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        try (FileWriter fileWriter = new FileWriter(savePath)) {
            Template temporal = configuration.getTemplate("entity.ftl");
            temporal.process(paramMap, fileWriter);
        }
        System.out.println("************" + savePath + "************");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
源代码17 项目: fast-family-master   文件: ServiceGenerator.java
private static void genServiceImpl(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 = ServiceGenerator.class.getClassLoader().getResource(resourcePath);
        configuration.setDirectoryForTemplateLoading(new File(url.getPath()));
        configuration.setObjectWrapper(new DefaultObjectWrapper(version));
        String filePath = generatorConfig.getSrcBasePath() + "service//impl//";
        String savePath = filePath + className + "ServiceImpl.java";
        File dirPath = new File(filePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        try (FileWriter fileWriter = new FileWriter(new File(savePath))) {
            Template template = configuration.getTemplate("service_impl.ftl");
            template.process(paramMap, fileWriter);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
源代码18 项目: fast-family-master   文件: ServiceGenerator.java
private static void genServiceInterface(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 = ServiceGenerator.class.getClassLoader().getResource(resourcePath);
        configuration.setDirectoryForTemplateLoading(new File(url.getPath()));
        configuration.setObjectWrapper(new DefaultObjectWrapper(version));
        String filePath = generatorConfig.getSrcBasePath() + "service//";
        String savePath = filePath + className + "Service.java";
        File dirPath = new File(filePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        try (FileWriter fileWriter = new FileWriter(new File(savePath))) {
            Template template = configuration.getTemplate("service.ftl");
            template.process(paramMap, fileWriter);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
源代码19 项目: fast-family-master   文件: MapperGenerator.java
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();
    }
}
 
源代码20 项目: genDoc   文件: TemplateParse.java
private TemplateParse(){
    configuration = new Configuration(Configuration.getVersion());
    StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
    configuration.setTemplateLoader(stringTemplateLoader);
    configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.getVersion()));
    configuration.setDefaultEncoding("UTF-8");

    initTemplateCache();
}
 
源代码21 项目: Spring-generator   文件: CreateFileUtil.java
/**
 * 执行创建文件
 * 
 * @param content
 *          模板所需要的上下文
 * @param templeteName
 *          模板的名字 示例:Entity.ftl
 * @param projectPath
 *          生成的项目路径 示例:D://create
 * @param packageName
 *          包名 示例:com.szmirren
 * @param fileName
 *          文件名 示例:Entity.java
 * @param codeFormat
 *          输出的字符编码格式 示例:UTF-8
 * @throws Exception
 */
public static void createFile(GeneratorContent content, String templeteName, String projectPath, String packageName, String fileName,
		String codeFormat, boolean isOverride) throws Exception {
	String outputPath = projectPath + "/" + packageName.replace(".", "/") + "/";
	if (!isOverride) {
		if (Files.exists(Paths.get(outputPath + fileName))) {
			LOG.debug("设置了文件存在不覆盖,文件已经存在,忽略本文件的创建");
			return;
		}
	}
	Configuration config = new Configuration(Configuration.VERSION_2_3_23);
	// 打包成jar包使用的路径
	String tempPath = Paths.get(Constant.TEMPLATE_DIR_NAME).toFile().getName();
	// 在项目运行的模板路径
	// String tempPath =
	// Thread.currentThread().getContextClassLoader().getResource(Constant.TEMPLATE_DIR_NAME).getFile();
	config.setDirectoryForTemplateLoading(new File(tempPath));
	config.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
	config.setDefaultEncoding("utf-8");
	Template template = config.getTemplate(templeteName);
	Map<String, Object> item = new HashMap<>();
	item.put("content", content);
	if (!Files.exists(Paths.get(outputPath))) {
		Files.createDirectories(Paths.get(outputPath));
	}
	try (Writer writer = new OutputStreamWriter(new FileOutputStream(outputPath + fileName), codeFormat)) {
		template.process(item, writer);
	}
}
 
源代码22 项目: alfresco-repository   文件: FeedTaskProcessor.java
protected Configuration getFreemarkerConfiguration(RepoCtx ctx)
{
    Configuration cfg = new Configuration();
    cfg.setObjectWrapper(new DefaultObjectWrapper());

    // custom template loader
    cfg.setTemplateLoader(new TemplateWebScriptLoader(ctx.getRepoEndPoint(), ctx.getTicket()));

    // TODO review i18n
    cfg.setLocalizedLookup(false);
    cfg.setIncompatibleImprovements(new Version(2, 3, 20));
    cfg.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER);

    return cfg;
}
 
源代码23 项目: opencps-v2   文件: TemplateConfiguration.java
private void init() {
	try {
		Configuration configuration = new Configuration(Configuration.getVersion());
		configuration.setDefaultEncoding("UTF-8");
		configuration.setObjectWrapper(new DefaultObjectWrapper(configuration.getIncompatibleImprovements()));

		this.setConfiguration(configuration);
	} catch (Exception e) {
		_log.error(e);
	}
}
 
源代码24 项目: DWSurvey   文件: FreeMarkertUtil.java
/**
 * 初始化模板配置
 * 
 * @param servletContext
 *            javax.servlet.ServletContext
 * @param templateDir
 *            模板位置
 */
public static void initConfig(ServletContext servletContext,
		String templateDir) {
	config.setLocale(Locale.CHINA);
	config.setDefaultEncoding("utf-8");
	config.setEncoding(Locale.CHINA, "utf-8");
	templateDir="WEB-INF/templates";
	config.setServletContextForTemplateLoading(servletContext, templateDir);
	config.setObjectWrapper(new DefaultObjectWrapper());
}
 
源代码25 项目: abixen-platform   文件: MailService.java
@Async
public void sendMail(String to, Map<String, String> parameters, String template, String subject) {
    log.debug("sendMail() - to: " + to);
    MimeMessage message = mailSender.createMimeMessage();
    try {
        String stringDir = MailService.class.getResource("/templates/freemarker").getPath();
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setDefaultEncoding("UTF-8");

        File dir = new File(stringDir);
        cfg.setDirectoryForTemplateLoading(dir);
        cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_22));

        StringBuffer content = new StringBuffer();
        Template temp = cfg.getTemplate(template + ".ftl");
        content.append(FreeMarkerTemplateUtils.processTemplateIntoString(temp, parameters));

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content.toString(), "text/html;charset=\"UTF-8\"");

        MimeMultipart multipart = new MimeMultipart("related");
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);
        message.setFrom(new InternetAddress(platformMailConfigurationProperties.getUser().getUsername(), platformMailConfigurationProperties.getUser().getName()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        mailSender.send(message);

        log.info("Message has been sent to: " + to);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
源代码26 项目: live-chat-engine   文件: Templates.java
public Templates(String dirPath) throws IOException {
	this.dirPath = dirPath;
	
	cfg = new Configuration();
	cfg.setLocalizedLookup(false);
       cfg.setDirectoryForTemplateLoading(new File(this.dirPath));
       cfg.setObjectWrapper(new DefaultObjectWrapper());
       cfg.setDefaultEncoding("UTF-8");
       cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
       cfg.setIncompatibleImprovements(new Version(2, 3, 20));
}
 
public void testExample() throws Exception {
  IssuesReporter reporter = new IssuesReporter(new LinkedList<ClassIssues>(), costModel);
  ReportModel model = new AboutTestabilityReport(reporter, new SourceLoader(null) {
    @Override
    public Source load(String name) {
      return new Source(asList(
          new Line(1, "Copyright garbage!"),
          new Line(2, "package com.google.test.metric.example;"),
          new Line(3, "import java.util.List;"),
          new Line(4, "  "),
          new Line(5, "class SumOfPrimes {"),
          new Line(6, "  public void sum() {}"),
          new Line(7, "}")));
    }
  });
  Configuration configuration = new Configuration();
  configuration.setTemplateLoader(new ClassPathTemplateLoader(ReportGeneratorProvider.PREFIX));
  BeansWrapper objectWrapper = new DefaultObjectWrapper();
  configuration.setObjectWrapper(objectWrapper);
  ResourceBundleModel bundleModel = new ResourceBundleModel(getBundle("messages"), objectWrapper);
  model.setMessageBundle(bundleModel);
  generator = new FreemarkerReportGenerator(model, new PrintStream(out),
          "about/Report.html", configuration);
  generator.printHeader();
  generator.addClassCost(new ClassCost("com.google.test.metric.example.Lessons.SumOfPrimes1",
      asList(new MethodCost("", "foo()", 1, false, false, false))));
  generator.printFooter();

  String text = out.toString();
  assertTrue(text, text.contains(">SumOfPrimes1<"));
  assertTrue(text, text.contains(">Lessons<"));
  assertTrue(text, text.contains("sum"));
  assertFalse(text, text.contains("Copyright"));
  assertFalse(text, text.contains("package com.google"));
  assertFalse(text, text.contains("import java.util"));
  assertFalse(text, text.contains("<span class=\"nocode\">4:"));
}
 
@Override
protected void setUp() throws Exception {
  super.setUp();
  Configuration cfg = new Configuration();
  cfg.setTemplateLoader(new ClassPathTemplateLoader(ReportGeneratorProvider.PREFIX));
  BeansWrapper objectWrapper = new DefaultObjectWrapper();
  cfg.setObjectWrapper(objectWrapper);
  ResourceBundleModel messageBundleModel =
      new ResourceBundleModel(ResourceBundle.getBundle("messages"), objectWrapper);
  issueQueue = Lists.newLinkedList();
  template = cfg.getTemplate("costDetailBoxTest.ftl");
  model = new HashMap<String, Object>();
  model.put("message", messageBundleModel);
  model.put("sourceLink", new SourceLinkerModel(new SourceLinker("", "")));
}
 
源代码29 项目: entando-core   文件: ControllerServlet.java
protected void initFreemarker(HttpServletRequest request,
		HttpServletResponse response, RequestContext reqCtx)
		throws TemplateModelException {
	Configuration config = new Configuration();
	DefaultObjectWrapper wrapper = new DefaultObjectWrapper();
	config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
	config.setObjectWrapper(wrapper);
	config.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER);
	TemplateModel templateModel = this.createModel(wrapper, this.getServletContext(), request, response);
	ExecutorBeanContainer ebc = new ExecutorBeanContainer(config, templateModel);
	reqCtx.addExtraParam(SystemConstants.EXTRAPAR_EXECUTOR_BEAN_CONTAINER, ebc);
}
 
源代码30 项目: doma-gen   文件: Generator.java
/**
 * インスタンスを構築します。
 *
 * @param templateEncoding テンプレートファイルのエンコーディング
 * @param templatePrimaryDir テンプレートファイルを格納したプライマリディレクトリ、プライマリディレクトリを使用しない場合{@code null}
 */
public Generator(String templateEncoding, File templatePrimaryDir) {
  if (templateEncoding == null) {
    throw new NullPointerException("templateFileEncoding");
  }
  this.configuration = new Configuration();
  configuration.setObjectWrapper(new DefaultObjectWrapper());
  configuration.setSharedVariable("currentDate", new OnDemandDateModel());
  configuration.setEncoding(Locale.getDefault(), templateEncoding);
  configuration.setNumberFormat("0.#####");
  configuration.setTemplateLoader(createTemplateLoader(templatePrimaryDir));
}