似非 FeedMail - VelocityFormatter

【注意】ここで紹介しているプログラムは、たまたま名前がカブってますが、UnderDone さんによるサービス FeedMail とはまったくの別物です。以下の内容について、UnderDone さんに問い合わせたりしないようにお願いします。

自作版「RSS→メール」アプリケーションの 4 クラス目。取得した各フィードの内容から、Velocity テンプレートでメール本文を生成する部分。ていうか、張る順番間違えたな。データの流れとしては、FeedInput で入力 → VelocityFormatter で変換 (下記) → MailOutput で出力

import java.io.StringWriter;
import java.io.IOException;
import java.util.*;

import de.nava.informa.core.*;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

public class VelocityFormatter {
	private Template template;
	
	VelocityFormatter(String templateFile) throws FeedMailException {
		try {
			this.template = Velocity.getTemplate(templateFile);
		} catch (ParseErrorException e) {
			throw new FeedMailException(e);
		} catch (ResourceNotFoundException e) {
			throw new FeedMailException(e);
		} catch (Exception e) {
			throw new FeedMailException(e);
		}
	}
	
	public String format(List channels) throws IOException, FeedMailException {
		try {
			VelocityContext ctx = new VelocityContext();
			ctx.put("channels", channels);
			
			StringWriter w = new StringWriter();
			template.merge(ctx, w);
			return w.toString();
		} catch (IOException e) {
			throw e;
		} catch (Exception e) {
			throw new FeedMailException(e);
		}
	}
}

使ってるテンプレート simple.vm はこんな感じだ。

#foreach ( $channel in $channels )
--- ${channel.title} ---

#foreach ( $item in $channel.items )
 - ${item.title} / ${item.subject}
   date: ${item.date}
   desc: ${item.description}
   link: ${item.link}
   
#end

#end

実はこれだけだと見栄えが悪い。データのない項目が "null" と出力されちゃうとか、文章が長くても折り返しがされないとか。でもまぁ、自分が見るだけだからいいかな、と。