JavaのWriterは、文字列の出力を文字ストリームという概念で扱って、データ出力先と出力の手続きを隠ぺいし、出力先が何であろうと同じメソッド呼び出しで出力することができるようにする抽象クラス。一般的に出力先となるのは標準出力やファイルだが、ネットワーク上であってもいい。というか出力先ってTwitterのコメントでもよかったりするんじゃないと思ってwriteしてflushすると、TwitterにPOSTされてしまう謎のWriterクラス、TwitterWriterクラスを作ってみた。適当に書いたソースコードはこれ。
import java.io.*; import java.net.*; import org.apache.commons.codec.binary.Base64; public class TwitterWriter extends Writer { protected StringBuffer buffer = new StringBuffer(); private String username; private String password; public TwitterWriter(String u, String p) { this(); this.password = p; this.username = u; } protected TwitterWriter() { super(); } @Override public void close() throws IOException { flush(); } @Override public void flush() throws IOException { post(); this.buffer.delete(0, this.buffer.length()); } private void post() throws IOException { HttpURLConnection conn = (HttpURLConnection)new URL("http://twitter.com/statuses/update.xml").openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("Authorization", "Basic " + this.getAuthString()); Writer w = new OutputStreamWriter(conn.getOutputStream(), "ASCII"); try { String text = URLEncoder.encode(buffer.toString(), "UTF-8") ; w.write("status="); w.write(text); w.flush(); } finally { w.close(); } conn.connect(); int code = conn.getResponseCode(); if (code != 200) { throw new IOException("TwittterへのPOSTに失敗したよ。 Status=" + conn.getResponseMessage()); } conn.disconnect(); } private String getAuthString() throws UnsupportedEncodingException { byte[] b = Base64.encodeBase64((this.username + ":" + this.password).getBytes("ASCII")); return new String(b); } @Override public void write(char[] cbuf, int off, int len) throws IOException { buffer.append(cbuf, off, len); } }
自分が所属している開発部では20%ルールを実験的に適用している。そこでこういう意味のないものを沢山を作って過ごしているのだけど、どうみても時間の無駄遣い。もっと生産的に使わなくては。