2008年12月9日火曜日

VelocityにてResourceNotFoundException

Velocityを使い始めたのですが,早々にResourceNotFoundExceptionという例外に遭遇してしまいました.ちょっと調べると解決できたので,その方法を以下にメモしておきます.

資料[1]を参考に以下のようなコードを書いて実行すると,テンプレートファイルが置かれた正しいパスをVelocity#getTemplateメソッドに指定しているにもかかわらず(ちなみにこれは自分の間違った解釈です),そのファイルがないことが原因でResourceNotFoundExceptionが発生し,プログラムが異常終了します.

Velocity.init();
VelocityContext context = new VelocityContext();
context.put("sensorName", sensor.getName());
Template template = Velocity.getTemplate(this.rootPath +"chart.vm", "UTF-8");
StringWriter writer = new StringWriter();
template.merge(context, writer);
buffer.append(writer.toString());


ライブラリに添付されていたドキュメントを読むと,Velocity#getTemplateメソッドの引数に指定するテンプレートファイルのパスは,Velocityのfile.resource.loader.pathというプロパティからの相対パスになるとのことでした.

そういうわけで,必要なプロパティ(file.resource.loader.path以外にもいくつかあります)をセットしたPropertiesクラスのインスタンスをVelocity#initに与えてやると,うまくテンプレートファイルを読み込むことができました.

Properties properties = new Properties();
properties.setProperty("resource.loader", "file");
properties.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
properties.setProperty("file.resource.loader.path", this.rootPath);
properties.setProperty("file.resource.loader.cache", "true");
properties.setProperty("file.resource.loader.modificationCheckInterval", "2");
Velocity.init(properties);
VelocityContext context = new VelocityContext();
context.put("sensorName", sensor.getName());
Template template = Velocity.getTemplate("/chart.vm", "UTF-8");
StringWriter writer = new StringWriter();
template.merge(context, writer);
buffer.append(writer.toString());


[1] Velocity
http://www.techscore.com/tech/ApacheJakarta/Velocity/index.html

0 件のコメント: