mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/io/ChunkedInputStream.java

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/io/ChunkedInputStream.java	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,306 @@
     1.4 +/*
     1.5 + * ====================================================================
     1.6 + * Licensed to the Apache Software Foundation (ASF) under one
     1.7 + * or more contributor license agreements.  See the NOTICE file
     1.8 + * distributed with this work for additional information
     1.9 + * regarding copyright ownership.  The ASF licenses this file
    1.10 + * to you under the Apache License, Version 2.0 (the
    1.11 + * "License"); you may not use this file except in compliance
    1.12 + * with the License.  You may obtain a copy of the License at
    1.13 + *
    1.14 + *   http://www.apache.org/licenses/LICENSE-2.0
    1.15 + *
    1.16 + * Unless required by applicable law or agreed to in writing,
    1.17 + * software distributed under the License is distributed on an
    1.18 + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    1.19 + * KIND, either express or implied.  See the License for the
    1.20 + * specific language governing permissions and limitations
    1.21 + * under the License.
    1.22 + * ====================================================================
    1.23 + *
    1.24 + * This software consists of voluntary contributions made by many
    1.25 + * individuals on behalf of the Apache Software Foundation.  For more
    1.26 + * information on the Apache Software Foundation, please see
    1.27 + * <http://www.apache.org/>.
    1.28 + *
    1.29 + */
    1.30 +
    1.31 +package ch.boye.httpclientandroidlib.impl.io;
    1.32 +
    1.33 +import java.io.IOException;
    1.34 +import java.io.InputStream;
    1.35 +
    1.36 +import ch.boye.httpclientandroidlib.Header;
    1.37 +import ch.boye.httpclientandroidlib.HttpException;
    1.38 +import ch.boye.httpclientandroidlib.MalformedChunkCodingException;
    1.39 +import ch.boye.httpclientandroidlib.TruncatedChunkException;
    1.40 +import ch.boye.httpclientandroidlib.io.BufferInfo;
    1.41 +import ch.boye.httpclientandroidlib.io.SessionInputBuffer;
    1.42 +import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
    1.43 +import ch.boye.httpclientandroidlib.util.ExceptionUtils;
    1.44 +
    1.45 +/**
    1.46 + * Implements chunked transfer coding. The content is received in small chunks.
    1.47 + * Entities transferred using this input stream can be of unlimited length.
    1.48 + * After the stream is read to the end, it provides access to the trailers,
    1.49 + * if any.
    1.50 + * <p>
    1.51 + * Note that this class NEVER closes the underlying stream, even when close
    1.52 + * gets called.  Instead, it will read until the "end" of its chunking on
    1.53 + * close, which allows for the seamless execution of subsequent HTTP 1.1
    1.54 + * requests, while not requiring the client to remember to read the entire
    1.55 + * contents of the response.
    1.56 + *
    1.57 + *
    1.58 + * @since 4.0
    1.59 + *
    1.60 + */
    1.61 +public class ChunkedInputStream extends InputStream {
    1.62 +
    1.63 +    private static final int CHUNK_LEN               = 1;
    1.64 +    private static final int CHUNK_DATA              = 2;
    1.65 +    private static final int CHUNK_CRLF              = 3;
    1.66 +
    1.67 +    private static final int BUFFER_SIZE = 2048;
    1.68 +
    1.69 +    /** The session input buffer */
    1.70 +    private final SessionInputBuffer in;
    1.71 +
    1.72 +    private final CharArrayBuffer buffer;
    1.73 +
    1.74 +    private int state;
    1.75 +
    1.76 +    /** The chunk size */
    1.77 +    private int chunkSize;
    1.78 +
    1.79 +    /** The current position within the current chunk */
    1.80 +    private int pos;
    1.81 +
    1.82 +    /** True if we've reached the end of stream */
    1.83 +    private boolean eof = false;
    1.84 +
    1.85 +    /** True if this stream is closed */
    1.86 +    private boolean closed = false;
    1.87 +
    1.88 +    private Header[] footers = new Header[] {};
    1.89 +
    1.90 +    /**
    1.91 +     * Wraps session input stream and reads chunk coded input.
    1.92 +     *
    1.93 +     * @param in The session input buffer
    1.94 +     */
    1.95 +    public ChunkedInputStream(final SessionInputBuffer in) {
    1.96 +        super();
    1.97 +        if (in == null) {
    1.98 +            throw new IllegalArgumentException("Session input buffer may not be null");
    1.99 +        }
   1.100 +        this.in = in;
   1.101 +        this.pos = 0;
   1.102 +        this.buffer = new CharArrayBuffer(16);
   1.103 +        this.state = CHUNK_LEN;
   1.104 +    }
   1.105 +
   1.106 +    public int available() throws IOException {
   1.107 +        if (this.in instanceof BufferInfo) {
   1.108 +            int len = ((BufferInfo) this.in).length();
   1.109 +            return Math.min(len, this.chunkSize - this.pos);
   1.110 +        } else {
   1.111 +            return 0;
   1.112 +        }
   1.113 +    }
   1.114 +
   1.115 +    /**
   1.116 +     * <p> Returns all the data in a chunked stream in coalesced form. A chunk
   1.117 +     * is followed by a CRLF. The method returns -1 as soon as a chunksize of 0
   1.118 +     * is detected.</p>
   1.119 +     *
   1.120 +     * <p> Trailer headers are read automatically at the end of the stream and
   1.121 +     * can be obtained with the getResponseFooters() method.</p>
   1.122 +     *
   1.123 +     * @return -1 of the end of the stream has been reached or the next data
   1.124 +     * byte
   1.125 +     * @throws IOException in case of an I/O error
   1.126 +     */
   1.127 +    public int read() throws IOException {
   1.128 +        if (this.closed) {
   1.129 +            throw new IOException("Attempted read from closed stream.");
   1.130 +        }
   1.131 +        if (this.eof) {
   1.132 +            return -1;
   1.133 +        }
   1.134 +        if (state != CHUNK_DATA) {
   1.135 +            nextChunk();
   1.136 +            if (this.eof) {
   1.137 +                return -1;
   1.138 +            }
   1.139 +        }
   1.140 +        int b = in.read();
   1.141 +        if (b != -1) {
   1.142 +            pos++;
   1.143 +            if (pos >= chunkSize) {
   1.144 +                state = CHUNK_CRLF;
   1.145 +            }
   1.146 +        }
   1.147 +        return b;
   1.148 +    }
   1.149 +
   1.150 +    /**
   1.151 +     * Read some bytes from the stream.
   1.152 +     * @param b The byte array that will hold the contents from the stream.
   1.153 +     * @param off The offset into the byte array at which bytes will start to be
   1.154 +     * placed.
   1.155 +     * @param len the maximum number of bytes that can be returned.
   1.156 +     * @return The number of bytes returned or -1 if the end of stream has been
   1.157 +     * reached.
   1.158 +     * @throws IOException in case of an I/O error
   1.159 +     */
   1.160 +    public int read (byte[] b, int off, int len) throws IOException {
   1.161 +
   1.162 +        if (closed) {
   1.163 +            throw new IOException("Attempted read from closed stream.");
   1.164 +        }
   1.165 +
   1.166 +        if (eof) {
   1.167 +            return -1;
   1.168 +        }
   1.169 +        if (state != CHUNK_DATA) {
   1.170 +            nextChunk();
   1.171 +            if (eof) {
   1.172 +                return -1;
   1.173 +            }
   1.174 +        }
   1.175 +        len = Math.min(len, chunkSize - pos);
   1.176 +        int bytesRead = in.read(b, off, len);
   1.177 +        if (bytesRead != -1) {
   1.178 +            pos += bytesRead;
   1.179 +            if (pos >= chunkSize) {
   1.180 +                state = CHUNK_CRLF;
   1.181 +            }
   1.182 +            return bytesRead;
   1.183 +        } else {
   1.184 +            eof = true;
   1.185 +            throw new TruncatedChunkException("Truncated chunk "
   1.186 +                    + "( expected size: " + chunkSize
   1.187 +                    + "; actual size: " + pos + ")");
   1.188 +        }
   1.189 +    }
   1.190 +
   1.191 +    /**
   1.192 +     * Read some bytes from the stream.
   1.193 +     * @param b The byte array that will hold the contents from the stream.
   1.194 +     * @return The number of bytes returned or -1 if the end of stream has been
   1.195 +     * reached.
   1.196 +     * @throws IOException in case of an I/O error
   1.197 +     */
   1.198 +    public int read (byte[] b) throws IOException {
   1.199 +        return read(b, 0, b.length);
   1.200 +    }
   1.201 +
   1.202 +    /**
   1.203 +     * Read the next chunk.
   1.204 +     * @throws IOException in case of an I/O error
   1.205 +     */
   1.206 +    private void nextChunk() throws IOException {
   1.207 +        chunkSize = getChunkSize();
   1.208 +        if (chunkSize < 0) {
   1.209 +            throw new MalformedChunkCodingException("Negative chunk size");
   1.210 +        }
   1.211 +        state = CHUNK_DATA;
   1.212 +        pos = 0;
   1.213 +        if (chunkSize == 0) {
   1.214 +            eof = true;
   1.215 +            parseTrailerHeaders();
   1.216 +        }
   1.217 +    }
   1.218 +
   1.219 +    /**
   1.220 +     * Expects the stream to start with a chunksize in hex with optional
   1.221 +     * comments after a semicolon. The line must end with a CRLF: "a3; some
   1.222 +     * comment\r\n" Positions the stream at the start of the next line.
   1.223 +     *
   1.224 +     * @param in The new input stream.
   1.225 +     * @param required <tt>true<tt/> if a valid chunk must be present,
   1.226 +     *                 <tt>false<tt/> otherwise.
   1.227 +     *
   1.228 +     * @return the chunk size as integer
   1.229 +     *
   1.230 +     * @throws IOException when the chunk size could not be parsed
   1.231 +     */
   1.232 +    private int getChunkSize() throws IOException {
   1.233 +        int st = this.state;
   1.234 +        switch (st) {
   1.235 +        case CHUNK_CRLF:
   1.236 +            this.buffer.clear();
   1.237 +            int i = this.in.readLine(this.buffer);
   1.238 +            if (i == -1) {
   1.239 +                return 0;
   1.240 +            }
   1.241 +            if (!this.buffer.isEmpty()) {
   1.242 +                throw new MalformedChunkCodingException(
   1.243 +                    "Unexpected content at the end of chunk");
   1.244 +            }
   1.245 +            state = CHUNK_LEN;
   1.246 +            //$FALL-THROUGH$
   1.247 +        case CHUNK_LEN:
   1.248 +            this.buffer.clear();
   1.249 +            i = this.in.readLine(this.buffer);
   1.250 +            if (i == -1) {
   1.251 +                return 0;
   1.252 +            }
   1.253 +            int separator = this.buffer.indexOf(';');
   1.254 +            if (separator < 0) {
   1.255 +                separator = this.buffer.length();
   1.256 +            }
   1.257 +            try {
   1.258 +                return Integer.parseInt(this.buffer.substringTrimmed(0, separator), 16);
   1.259 +            } catch (NumberFormatException e) {
   1.260 +                throw new MalformedChunkCodingException("Bad chunk header");
   1.261 +            }
   1.262 +        default:
   1.263 +            throw new IllegalStateException("Inconsistent codec state");
   1.264 +        }
   1.265 +    }
   1.266 +
   1.267 +    /**
   1.268 +     * Reads and stores the Trailer headers.
   1.269 +     * @throws IOException in case of an I/O error
   1.270 +     */
   1.271 +    private void parseTrailerHeaders() throws IOException {
   1.272 +        try {
   1.273 +            this.footers = AbstractMessageParser.parseHeaders
   1.274 +                (in, -1, -1, null);
   1.275 +        } catch (HttpException e) {
   1.276 +            IOException ioe = new MalformedChunkCodingException("Invalid footer: "
   1.277 +                    + e.getMessage());
   1.278 +            ExceptionUtils.initCause(ioe, e);
   1.279 +            throw ioe;
   1.280 +        }
   1.281 +    }
   1.282 +
   1.283 +    /**
   1.284 +     * Upon close, this reads the remainder of the chunked message,
   1.285 +     * leaving the underlying socket at a position to start reading the
   1.286 +     * next response without scanning.
   1.287 +     * @throws IOException in case of an I/O error
   1.288 +     */
   1.289 +    public void close() throws IOException {
   1.290 +        if (!closed) {
   1.291 +            try {
   1.292 +                if (!eof) {
   1.293 +                    // read and discard the remainder of the message
   1.294 +                    byte buffer[] = new byte[BUFFER_SIZE];
   1.295 +                    while (read(buffer) >= 0) {
   1.296 +                    }
   1.297 +                }
   1.298 +            } finally {
   1.299 +                eof = true;
   1.300 +                closed = true;
   1.301 +            }
   1.302 +        }
   1.303 +    }
   1.304 +
   1.305 +    public Header[] getFooters() {
   1.306 +        return (Header[])this.footers.clone();
   1.307 +    }
   1.308 +
   1.309 +}

mercurial