USTREAM のチャンネルIDや配信情報を取得

USTREAM のチャンネルIDや配信情報を取得する処理をJavaで書いてみた。

HTTP-GET で下記のように番組名と http://developer.ustream.tv/ でアカウントを
取得して貰える API-Key で以下のような URLでHTTP-GET を実行する。

http://api.ustream.tv/xml/channel/channel名/getInfo?key=API-Key

Java での HTTP 送信はいくらでも例があるのでここでは省略するが、
応答レスポンスのストリームを XML解析ハンドラで読み取ることになる。

ここでは、取得できる情報のうち、チャンネルIDと配信番組のURL だけを
取得するハンドラの実行だけを紹介する。

// 取得情報 object
public class Info{
   public String id;
   public String url;
}
--------------------------
public abstract class AbstractXmlHandler<T> extends DefaultHandler{
   public abstract T result();
}

--------------------------
import java.util.Stack;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
 * Handler
 */

public class Handler extends AbstractXmlHandler<Info>{
   private Stack<String> stack;
   private Stack<Info> infos = new Stack<Info>();
   private StringBuffer body = null;

   @Override
   public Info result(){
      return this.infos.pop();
   }

   @Override
   public void startElement(String uri,String localName,String name,Attributes attributes) throws SAXException{
      this.stack.push(name);
      this.body = new StringBuffer();
      StringBuffer sb = new StringBuffer();
      for(String s : this.stack){
         sb.append("/"+s);
      }
      // xml path "/xml/results" で Info 生成して stack に push
      if ("/xml/results".equals(sb.toString())){
         this.infos.push(new Info());
      }
   }
   @Override
   public void characters(char[] ch,int start,int length) throws SAXException{
      if ( this.body != null){
         this.body.append(new String(ch,start,length));
      }
   }
   @Override
   public void endElement(String uri,String localName,String name) throws SAXException{
      StringBuffer sb = new StringBuffer();
      for(String s : this.stack){
         sb.append("/"+s);
      }
      if ("/xml/results/id".equals(sb.toString())){
         if (this.body != null){
            Info info = this.infos.pop();
            info.id = this.body.toString().trim();
            this.infos.push(info);
            this.body = null;
         }
      }else if("/xml/results/url".equals(sb.toString())){
         if (this.body != null){
            Info info = this.infos.pop();
            info.url = this.body.toString().trim();
            this.infos.push(info);
            this.body = null;
         }
      }
      this.stack.pop();
   }
   @Override
   public void startDocument() throws SAXException{
      this.stack = new Stack<String>();
   }
   @Override
   public void endDocument() throws SAXException{
   }
}
=========================================

Handler handler = new Handler();
HttpURLConnection uc;
//
//  HTTP接続して上記URLで送信したとする。
//

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(uc.getInputStream(),handler);

Info info = handler.result();