Java Code Examples for org.apache.velocity.app.Velocity

The following examples show how to use org.apache.velocity.app.Velocity. 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: tomee   Source File: Container.java    License: Apache License 2.0 6 votes vote down vote up
private void copyTemplateTo(final File targetDir, final String filename) throws Exception {
    final File file = new File(targetDir, filename);
    if (file.exists()) {
        return;
    }

    // don't break apps using Velocity facade
    final VelocityEngine engine = new VelocityEngine();
    engine.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, new NullLogChute());
    engine.setProperty(Velocity.RESOURCE_LOADER, "class");
    engine.setProperty("class.resource.loader.description", "Velocity Classpath Resource Loader");
    engine.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());
    engine.init();
    final Template template = engine.getTemplate("/org/apache/tomee/configs/" + filename);
    final VelocityContext context = new VelocityContext();
    context.put("tomcatHttpPort", Integer.toString(configuration.getHttpPort()));
    context.put("tomcatShutdownPort", Integer.toString(configuration.getStopPort()));
    final Writer writer = new FileWriter(file);
    template.merge(context, writer);
    writer.flush();
    writer.close();
}
 
Example 2
Source Project: olingo-odata4   Source File: AbstractPOJOGenMojo.java    License: Apache License 2.0 6 votes vote down vote up
protected void parseObj(
    final File base,
    final boolean append,
    final String pkg,
    final String name,
    final String out,
    final Map<String, Object> objs)
    throws MojoExecutionException {

  final VelocityContext ctx = newContext();
  ctx.put("package", pkg);

  if (objs != null) {
    for (Map.Entry<String, Object> obj : objs.entrySet()) {
      if (StringUtils.isNotBlank(obj.getKey()) && obj.getValue() != null) {
        ctx.put(obj.getKey(), obj.getValue());
      }
    }
  }

  final Template template = Velocity.getTemplate(name + ".vm");
  writeFile(out, base, ctx, template, append);
}
 
Example 3
Source Project: feiqu-opensource   Source File: VelocityUtil.java    License: Apache License 2.0 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();
		String path = getPath(inputVmFilePath);
		properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, path);
		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: velocity-engine   Source File: BaseTestCase.java    License: Apache License 2.0 6 votes vote down vote up
protected void info(String msg, Throwable t)
{
    if (DEBUG)
    {
        try
        {
            if (engine == null)
            {
                Velocity.getLog().info(msg, t);
            }
            else
            {
                engine.getLog().info(msg, t);
            }
        }
        catch (Throwable t2)
        {
            System.out.println("Failed to log: "+msg+(t!=null?" - "+t: ""));
            System.out.println("Cause: "+t2);
            t2.printStackTrace();
        }
    }
}
 
Example 5
Source Project: java-course-ee   Source File: Test1.java    License: MIT License 6 votes vote down vote up
public Test1() throws Exception {

        //init
        Velocity.init("Velocity/GS_Velocity_1/src/main/java/velocity.properties");
        // get Template
        Template template = Velocity.getTemplate("Test1.vm");
        // getContext
        Context context = new VelocityContext();
        // get Writer
        Writer writer = new StringWriter();
        // merge
        template.merge(context, writer);

        System.out.println(writer.toString());

    }
 
Example 6
Source Project: ruoyiplus   Source File: VelocityInitializer.java    License: MIT License 6 votes vote down vote up
/**
 * 初始化vm方法
 */
public static void initVelocity()
{
    Properties p = new Properties();
    try
    {
        // 加载classpath目录下的vm文件
        p.setProperty("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        // 定义字符集
        p.setProperty(Velocity.ENCODING_DEFAULT, Constants.UTF8);
        p.setProperty(Velocity.OUTPUT_ENCODING, Constants.UTF8);
        // 初始化Velocity引擎,指定配置Properties
        Velocity.init(p);
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}
 
Example 7
Source Project: NutzSite   Source File: VelocityInitializer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 初始化vm方法
 */
public static void initVelocity()
{
    Properties p = new Properties();
    try
    {
        // 加载classpath目录下的vm文件
        p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        // 定义字符集
        p.setProperty(Velocity.ENCODING_DEFAULT, Globals.UTF8);
        p.setProperty(Velocity.OUTPUT_ENCODING, Globals.UTF8);
        // 初始化Velocity引擎,指定配置Properties
        Velocity.init(p);
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source Project: sofa-acts   Source File: VelocityUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Render text
 * 
 * @param context
 * @param template
 * @return
 */
public static synchronized String evaluateString(Map<String, Object> context, String template) {
    Writer writer = new StringWriter();
    try {
        VelocityContext velocityContext = new VelocityContext(context);

        addExtendProperties(velocityContext);

        Velocity.evaluate(velocityContext, writer, StringUtils.EMPTY, template);
        return writer.toString();
    } catch (Exception e) {
        throw new ActsException("velocity evaluate error[template=" + template + "]", e);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}
 
Example 9
Source Project: java-course-ee   Source File: Test2.java    License: MIT License 6 votes vote down vote up
public Test2() throws Exception {
    //init
    Velocity.init("Velocity/GS_Velocity_1/src/main/java/velocity.properties");
    // get Template
    Template template = Velocity.getTemplate("Test2.vm");
    // getContext
    Context context = new VelocityContext();

    String name = "Vova";

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

    System.out.println(writer.toString());
}
 
Example 10
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 11
public void usage1(String inputFile) throws FileNotFoundException {
   Velocity.init();

    VelocityContext context = new VelocityContext();

    context.put("author", "Elliot A.");
    context.put("address", "217 E Broadway");
    context.put("phone", "555-1337");

    FileInputStream file = new FileInputStream(inputFile);

    //Evaluate
    StringWriter swOut = new StringWriter();
    Velocity.evaluate(context, swOut, "test", file);

    String result =  swOut.getBuffer().toString();
    System.out.println(result);
}
 
Example 12
public void setUp()
        throws Exception
{

    ResourceLoader rl = new FileResourceLoader();

    // pass in an instance to Velocity
    Velocity.reset();
    Velocity.setProperty( "resource.loader", "testrl" );
    Velocity.setProperty( "testrl.resource.loader.instance", rl );
    Velocity.setProperty( "testrl.resource.loader.path", FILE_RESOURCE_LOADER_PATH );

    // actual instance of logger
    logger.on();
    Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, logger);
    Velocity.setProperty("runtime.log.logsystem.test.level", "debug");

    Velocity.init();
}
 
Example 13
public void setUp() throws Exception
{
    Velocity.reset();
    Velocity.setProperty(Velocity.RESOURCE_LOADERS, "string");
    Velocity.addProperty("string.resource.loader.class", StringResourceLoader.class.getName());
    Velocity.addProperty("string.resource.loader.modificationCheckInterval", "1");
    Velocity.setProperty(Velocity.RUNTIME_LOG_INSTANCE, new TestLogger());
    Velocity.init();

    StringResourceRepository repo = getRepo(null, null);
    repo.putStringResource("foo", "This is $foo");
    repo.putStringResource("bar", "This is $bar");

    context = new VelocityContext();
    context.put("foo", "wonderful!");
    context.put("bar", "horrible!");
    context.put("woogie", "a woogie");
}
 
Example 14
Source Project: velocity-tools   Source File: RenderTool.java    License: Apache License 2.0 6 votes vote down vote up
protected String internalEval(Context ctx, String vtl) throws Exception
{
    if (vtl == null)
    {
        return null;
    }
    StringWriter sw = new StringWriter();
    boolean success;
    if (engine == null)
    {
        success = Velocity.evaluate(ctx, sw, "RenderTool.eval()", vtl);
    }
    else
    {
        success = engine.evaluate(ctx, sw, "RenderTool.eval()", vtl);
    }
    if (success)
    {
        return sw.toString();
    }
    /* or would it be preferable to return the original? */
    return null;
}
 
Example 15
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 16
/**
 * Return and initialize engine
 * @return
 */
private VelocityEngine createEngine(boolean cache, boolean local)
throws Exception
{
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty( Velocity.VM_PERM_INLINE_LOCAL, Boolean.TRUE);
    ve.setProperty("velocimacro.permissions.allow.inline.to.replace.global",
        local);
    ve.setProperty("file.resource.loader.cache", cache);
    ve.setProperty(
            Velocity.RUNTIME_LOG_INSTANCE, new TestLogger());
    ve.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file");
    ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,
            TEST_COMPARE_DIR + "/parsemacros");
    ve.init();

    return ve;
}
 
Example 17
Source Project: DCMonitor   Source File: VelocityConfiguration.java    License: MIT License 6 votes vote down vote up
@Bean
VelocityViewResolver velocityViewResolver() {
  VelocityViewResolver resolver = new VelocityViewResolver();
  resolver.setSuffix(this.environment.getProperty("suffix", ".vm"));
  resolver.setPrefix(this.environment.getProperty("prefix", "/public/"));
  // Needs to come before any fallback resolver (e.g. a
  // InternalResourceViewResolver)
  resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 20);
  Properties p = new Properties();
  p.put(Velocity.FILE_RESOURCE_LOADER_PATH, "/public/");
  p.put("input.encoding", "utf-8");
  p.put("output.encoding", "utf-8");
  resolver.setAttributes(p);
  resolver.setContentType("text/html;charset=utf-8");
  return resolver;
}
 
Example 18
Source Project: eagle   Source File: VelocityTemplateParser.java    License: Apache License 2.0 6 votes vote down vote up
public VelocityTemplateParser(String templateString) throws ParseErrorException {
    VelocityEngine engine = new VelocityEngine();
    engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute");
    engine.setProperty("runtime.log.logsystem.log4j.logger", LOG.getName());
    engine.setProperty(Velocity.RESOURCE_LOADER, "string");
    engine.addProperty("string.resource.loader.class", StringResourceLoader.class.getName());
    engine.addProperty("string.resource.loader.repository.static", "false");
    engine.addProperty("runtime.references.strict", "true");
    engine.init();
    StringResourceRepository resourceRepository = (StringResourceRepository) engine.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT);
    resourceRepository.putStringResource(TEMPLATE_NAME, templateString);
    template = engine.getTemplate(TEMPLATE_NAME);
    ASTprocess data = (ASTprocess) template.getData();
    visitor = new ParserNodeVisitor();
    data.jjtAccept(visitor, null);
}
 
Example 19
Source Project: cxf   Source File: VelocityGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private static synchronized void initVelocity(boolean log) throws ToolException {
        if (initialized) {
            return;
        }
        initialized = true;
        try {
            Properties props = new Properties();
            String clzName = "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader";
            props.put("resource.loaders", "class");
            props.put("resource.loader.class.class", clzName);
            props.put("runtime.log", getVelocityLogFile("velocity.log"));
//            if (!log) {
//                props.put(VelocityEngine.RUNTIME_LOG_INSTANCE,
//                          "org.apache.velocity.runtime.log.NullLogSystem");
//            }
            Velocity.init(props);
        } catch (Exception e) {
            Message msg = new Message("FAIL_TO_INITIALIZE_VELOCITY_ENGINE", LOG);
            LOG.log(Level.SEVERE, msg.toString());
            throw new ToolException(msg, e);
        }
    }
 
Example 20
protected void log(String out)
{
    Velocity.getLog().debug(out);
    if (DEBUG)
    {
        System.out.println(out);
    }
}
 
Example 21
Source Project: das   Source File: TransController.java    License: Apache License 2.0 5 votes vote down vote up
private String mergeTemplate(Context context) {
    java.util.Properties property = new java.util.Properties();
    property.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS,
            "org.apache.velocity.runtime.log.NullLogChute");
    property.setProperty(VelocityEngine.RESOURCE_LOADER, "class");
    property.setProperty("class.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    Velocity.init(property);

    StringWriter writer = new StringWriter();
    Velocity.mergeTemplate("templates/convert/convert1.tpl", "UTF-8", context, writer);
    return  writer.toString();
}
 
Example 22
Source Project: velocity-engine   Source File: EncodingTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void testHighByteChinese()
        throws Exception
{
    VelocityContext context = new VelocityContext();

    assureResultsDirectoryExists(RESULT_DIR);

    /*
     *  a 'high-byte' chinese example from Michael Zhou
     */

    Template template = Velocity.getTemplate(
          getFileName( null, "encodingtest2", TMPL_FILE_EXT), "UTF-8");

    FileOutputStream fos =
        new FileOutputStream (
            getFileName(RESULT_DIR, "encodingtest2", RESULT_FILE_EXT));

    Writer writer = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));

    template.merge(context, writer);
    writer.flush();
    writer.close();

    if (!isMatch(RESULT_DIR,COMPARE_DIR,"encodingtest2",
            RESULT_FILE_EXT,CMP_FILE_EXT) )
    {
        fail("Output 2 incorrect.");
    }

}
 
Example 23
Source Project: easy-httpserver   Source File: VelocityUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 渲染Velocity模板
 * @param path
 * @param map
 */
public static String mergeTemplate(String path, Map<String, Object> map) throws IOException {
	VelocityContext vc = new VelocityContext();
	if (null != map) {
		for (String key : map.keySet()) {
			vc.put(key, map.get(key));
		}
	}
	StringWriter w = new StringWriter();
	Velocity.mergeTemplate(path, "utf-8", vc, w);
	String content = w.toString();
	w.close();
	return content;
}
 
Example 24
Source Project: velocity-engine   Source File: ClasspathResourceTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void setUp()
        throws Exception
{
    assureResultsDirectoryExists(RESULTS_DIR);

    Velocity.reset();
    Velocity.setProperty(Velocity.RESOURCE_LOADERS, "classpath");

    /*
     * I don't think I should have to do this, these should
     * be in the default config file.
     */

    Velocity.addProperty(
            "classpath." + Velocity.RESOURCE_LOADER + ".class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

    Velocity.setProperty(
            "classpath." + Velocity.RESOURCE_LOADER + ".cache", "false");

    Velocity.setProperty(
            "classpath." + Velocity.RESOURCE_LOADER + ".modificationCheckInterval",
            "2");

    Velocity.setProperty(
            Velocity.RUNTIME_LOG_INSTANCE, new TestLogger());

    Velocity.init();
}
 
Example 25
Source Project: RuoYi-Vue   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.flush();
            zip.closeEntry();
        }
        catch (IOException e)
        {
            log.error("渲染模板失败,表名:" + table.getTableName(), e);
        }
    }
}
 
Example 26
Source Project: ruoyiplus   Source File: GenServiceImpl.java    License: MIT License 5 votes vote down vote up
/**
 * 生成代码
 */
private void generatorCode(TableInfo table, ZipOutputStream zip) {
    // 设置主键
    table.setPrimaryKey(table.getColumnsLast());
    VelocityInitializer.initVelocity();
    String packageName = Global.getPackageName();
    String moduleName = GenUtils.getModuleName(packageName);

    VelocityContext context = GenUtils.getVelocityContext(table);

    // 获取模板列表
    List<String> templates = GenUtils.getTemplates();
    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(GenUtils.getFileName(template, table, moduleName)));
            IOUtils.write(sw.toString(), zip, Constants.UTF8);
            IOUtils.closeQuietly(sw);
            zip.closeEntry();
        } catch (IOException e) {
            log.error("渲染模板失败,表名:" + table.getTableName(), e);
        }
    }
}
 
Example 27
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());
            }
        }
    }
 
Example 28
Source Project: NutzSite   Source File: GenServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 生成代码预览
 * @param tableName
 * @param templates
 * @return
 */
@Override
public Map<String, String> previewCode(String tableName, List<String> templates){
    Map<String, String> dataMap = new LinkedHashMap<>();
    // 查询表信息
    TableInfo table = this.selectTableByName(tableName);
    // 查询列信息
    List<ColumnInfo> columns = this.selectTableColumnsByName(tableName);
    if (Lang.isNotEmpty(table) && Lang.isNotEmpty(columns)) {
        // 生成代码

        // 表名转换成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);
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Globals.UTF8);
            tpl.merge(context, sw);
            dataMap.put(template, sw.toString());
        }
        return dataMap;
    }
    return null;
}
 
Example 29
public void testGetterMethodInvocationException ()
        throws Exception
{
    VelocityContext vc = new VelocityContext();
    vc.put("woogie", this );

    StringWriter w = new StringWriter();

    /*
     *  second test - to ensure that methods accessed via get+ construction
     *  also work
     */

    String template = "$woogie.foo boing!";

    try
    {
        Velocity. evaluate( vc,  w, "test", template );
        fail("No exception thrown, second test.");
    }
    catch( MethodInvocationException mie )
    {
        log("Caught MIE (good!) :" );
        log("  reference = " + mie.getReferenceName() );
        log("  method    = " + mie.getMethodName() );

        Throwable t = mie.getCause();
        log("  throwable = " + t );

        if( t instanceof Exception)
        {
            log("  exception = " + t.getMessage() );
        }
    }
}
 
Example 30
Source Project: velocity-engine   Source File: EncodingTestCase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Runs the test.
 */
public void testChineseEncoding ()
        throws Exception
{
    VelocityContext context = new VelocityContext();

    assureResultsDirectoryExists(RESULT_DIR);

    /*
     *  get the template and the output
     */

    /*
     *  Chinese and spanish
     */

    Template template = Velocity.getTemplate(
        getFileName(null, "encodingtest", TMPL_FILE_EXT), "UTF-8");

    FileOutputStream fos =
        new FileOutputStream (
            getFileName(RESULT_DIR, "encodingtest", RESULT_FILE_EXT));

    Writer writer = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));

    template.merge(context, writer);
    writer.flush();
    writer.close();

    if (!isMatch(RESULT_DIR,COMPARE_DIR,"encodingtest",
            RESULT_FILE_EXT,CMP_FILE_EXT) )
    {
        fail("Output 1 incorrect.");
    }
}