ラベル velocity の投稿を表示しています。 すべての投稿を表示
ラベル velocity の投稿を表示しています。 すべての投稿を表示

2011/09/11

[Java] Velocityのログを無効化する方法について

概要

Velocityを使用すると、「velocity.log」というのが勝手に作成されます。
それを作成しないようにする方法について説明します。

内容

以下のようにVelocityの初期処理前にログを設定しないようプロパティを設定すればよいです。
        Velocity.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.NullLogSystem");
        Velocity.init();

[Java] Velocityを使用してファイルを作成する方法

概要

Velocityというテンプレートエンジンを使用して、ファイルを作成する方法について説明します。

内容

以下の手順でテンプレートエンジンからファイルを作成することができます。
1.テンプレートエンジンを初期化する
2.テンプレートに渡すパラメータを設定する
3.テンプレートのマージ結果をStringWriterに設定する

以下サンプルコードです。
private File createGroovyScript(FormulaDTO dto) throws Exception {

        File file = File.createTempFile("priceCalc", ".groovy", new File("."));

        // Velocityテンプレートエンジンを初期化する
        Velocity.init();

        // テンプレートに渡すパラメータを設定する
        VelocityContext context = new VelocityContext();
        context.put("formula", dto);

        // テンプレートのマージ結果をStringWriterに設定する
        StringWriter sw = new StringWriter();
        Template template = Velocity.getTemplate("/template/template_groovy.vm", "UTF-8");
        template.merge(context,sw);

        // 結果を一時ファイルに設定する
        FileWriter writer = new FileWriter(file);
        writer.write(sw.toString());
        writer.close();

        return file;
    }

template_groovy.vm
import jp.co.technos.common.dto.FormulaDTO;

def calculate(FormulaDTO data) {
    data.setResult(${formula.formula})
}

FormulaDTO data = (FormulaDTO) formula
calculate(data)