2 * InputStream associated with HttpURLConnection with counter
4 * License : The MIT License
5 * Copyright(c) 2009 olyutorskii
8 package jp.sfjp.jindolf.net;
10 import java.io.BufferedInputStream;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.net.HttpURLConnection;
14 import java.util.logging.Logger;
17 * 読み込みバイト数を記録するHTTPコネクション由来のInputStream。
20 public class TallyInputStream extends InputStream{
22 private static final int BUFSIZE = 2 * 1024;
24 private static final Logger LOGGER = Logger.getAnonymousLogger();
27 private final HttpURLConnection conn;
28 private final InputStream in;
31 private boolean hasClosed;
36 * @param conn HTTPコネクション
37 * @throws java.io.IOException 入出力エラー
39 protected TallyInputStream(HttpURLConnection conn) throws IOException{
47 is = this.conn.getInputStream();
48 is = new BufferedInputStream(is, BUFSIZE);
51 this.hasClosed = false;
58 * HTTPコネクションから入力ストリームを得る。
59 * @param conn HTTPコネクション
61 * @throws java.io.IOException 入出力エラー
63 public static InputStream getInputStream(HttpURLConnection conn)
65 return new TallyInputStream(conn);
72 protected long getCount(){
79 * @return {@inheritDoc}
80 * @throws java.io.IOException {@inheritDoc}
83 public int available() throws IOException{
84 int bytes = this.in.available();
90 * 今までに読み込んだバイト数のスループットをログ出力する。
91 * @throws java.io.IOException {@inheritDoc}
94 public void close() throws IOException{
95 if(this.hasClosed) return;
99 long size = getCount();
100 long span = System.nanoTime() - this.nanoLap;
102 String message = HttpUtils.formatHttpStat(this.conn, size, span);
103 LOGGER.info(message);
105 this.hasClosed = true;
113 * @return {@inheritDoc}
114 * @throws java.io.IOException {@inheritDoc}
117 public int read() throws IOException{
118 if(this.counter <= 0) this.nanoLap = System.nanoTime();
120 int byteData = this.in.read();
121 if(byteData >= 0) this.counter++;
129 * @param buf {@inheritDoc}
130 * @return {@inheritDoc}
131 * @throws java.io.IOException {@inheritDoc}
134 public int read(byte[] buf) throws IOException{
135 if(this.counter <= 0) this.nanoLap = System.nanoTime();
137 int count = this.in.read(buf);
138 if(count >= 0) this.counter += count;
146 * @param buf {@inheritDoc}
147 * @param off {@inheritDoc}
148 * @param len {@inheritDoc}
149 * @return {@inheritDoc}
150 * @throws java.io.IOException {@inheritDoc}
153 public int read(byte[] buf, int off, int len) throws IOException{
154 if(this.counter <= 0) this.nanoLap = System.nanoTime();
156 int count = this.in.read(buf, off, len);
157 if(count >= 0) this.counter += count;
165 * @param n {@inheritDoc}
166 * @return {@inheritDoc}
167 * @throws java.io.IOException {@inheritDoc}
170 public long skip(long n) throws IOException{
171 if(this.counter <= 0) this.nanoLap = System.nanoTime();
173 long skipped = this.in.skip(n);
174 this.counter += skipped;