Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/net/www/http/ChunkedOutputStream.java
38923 views
/*1* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/24package sun.net.www.http;2526import java.io.*;2728/**29* OutputStream that sends the output to the underlying stream using chunked30* encoding as specified in RFC 2068.31*/32public class ChunkedOutputStream extends PrintStream {3334/* Default chunk size (including chunk header) if not specified */35static final int DEFAULT_CHUNK_SIZE = 4096;36private static final byte[] CRLF = {'\r', '\n'};37private static final int CRLF_SIZE = CRLF.length;38private static final byte[] FOOTER = CRLF;39private static final int FOOTER_SIZE = CRLF_SIZE;40private static final byte[] EMPTY_CHUNK_HEADER = getHeader(0);41private static final int EMPTY_CHUNK_HEADER_SIZE = getHeaderSize(0);4243/* internal buffer */44private byte buf[];45/* size of data (excluding footers and headers) already stored in buf */46private int size;47/* current index in buf (i.e. buf[count] */48private int count;49/* number of bytes to be filled up to complete a data chunk50* currently being built */51private int spaceInCurrentChunk;5253/* underlying stream */54private PrintStream out;5556/* the chunk size we use */57private int preferredChunkDataSize;58private int preferedHeaderSize;59private int preferredChunkGrossSize;60/* header for a complete Chunk */61private byte[] completeHeader;6263/* return the size of the header for a particular chunk size */64private static int getHeaderSize(int size) {65return (Integer.toHexString(size)).length() + CRLF_SIZE;66}6768/* return a header for a particular chunk size */69private static byte[] getHeader(int size){70try {71String hexStr = Integer.toHexString(size);72byte[] hexBytes = hexStr.getBytes("US-ASCII");73byte[] header = new byte[getHeaderSize(size)];74for (int i=0; i<hexBytes.length; i++)75header[i] = hexBytes[i];76header[hexBytes.length] = CRLF[0];77header[hexBytes.length+1] = CRLF[1];78return header;79} catch (java.io.UnsupportedEncodingException e) {80/* This should never happen */81throw new InternalError(e.getMessage(), e);82}83}8485public ChunkedOutputStream(PrintStream o) {86this(o, DEFAULT_CHUNK_SIZE);87}8889public ChunkedOutputStream(PrintStream o, int size) {90super(o);91out = o;9293if (size <= 0) {94size = DEFAULT_CHUNK_SIZE;95}9697/* Adjust the size to cater for the chunk header - eg: if the98* preferred chunk size is 1k this means the chunk size should99* be 1017 bytes (differs by 7 from preferred size because of100* 3 bytes for chunk size in hex and CRLF (header) and CRLF (footer)).101*102* If headerSize(adjusted_size) is shorter then headerSize(size)103* then try to use the extra byte unless headerSize(adjusted_size+1)104* increases back to headerSize(size)105*/106if (size > 0) {107int adjusted_size = size - getHeaderSize(size) - FOOTER_SIZE;108if (getHeaderSize(adjusted_size+1) < getHeaderSize(size)){109adjusted_size++;110}111size = adjusted_size;112}113114if (size > 0) {115preferredChunkDataSize = size;116} else {117preferredChunkDataSize = DEFAULT_CHUNK_SIZE -118getHeaderSize(DEFAULT_CHUNK_SIZE) - FOOTER_SIZE;119}120121preferedHeaderSize = getHeaderSize(preferredChunkDataSize);122preferredChunkGrossSize = preferedHeaderSize + preferredChunkDataSize123+ FOOTER_SIZE;124completeHeader = getHeader(preferredChunkDataSize);125126/* start with an initial buffer */127buf = new byte[preferredChunkGrossSize];128reset();129}130131/*132* Flush a buffered, completed chunk to an underlying stream. If the data in133* the buffer is insufficient to build up a chunk of "preferredChunkSize"134* then the data do not get flushed unless flushAll is true. If flushAll is135* true then the remaining data builds up a last chunk which size is smaller136* than preferredChunkSize, and then the last chunk gets flushed to137* underlying stream. If flushAll is true and there is no data in a buffer138* at all then an empty chunk (containing a header only) gets flushed to139* underlying stream.140*/141private void flush(boolean flushAll) {142if (spaceInCurrentChunk == 0) {143/* flush a completed chunk to underlying stream */144out.write(buf, 0, preferredChunkGrossSize);145out.flush();146reset();147} else if (flushAll){148/* complete the last chunk and flush it to underlying stream */149if (size > 0){150/* adjust a header start index in case the header of the last151* chunk is shorter then preferedHeaderSize */152153int adjustedHeaderStartIndex = preferedHeaderSize -154getHeaderSize(size);155156/* write header */157System.arraycopy(getHeader(size), 0, buf,158adjustedHeaderStartIndex, getHeaderSize(size));159160/* write footer */161buf[count++] = FOOTER[0];162buf[count++] = FOOTER[1];163164//send the last chunk to underlying stream165out.write(buf, adjustedHeaderStartIndex, count - adjustedHeaderStartIndex);166} else {167//send an empty chunk (containing just a header) to underlying stream168out.write(EMPTY_CHUNK_HEADER, 0, EMPTY_CHUNK_HEADER_SIZE);169}170171out.flush();172reset();173}174}175176@Override177public boolean checkError() {178return out.checkError();179}180181/* Check that the output stream is still open */182private void ensureOpen() {183if (out == null)184setError();185}186187/*188* Writes data from b[] to an internal buffer and stores the data as data189* chunks of a following format: {Data length in Hex}{CRLF}{data}{CRLF}190* The size of the data is preferredChunkSize. As soon as a completed chunk191* is read from b[] a process of reading from b[] suspends, the chunk gets192* flushed to the underlying stream and then the reading process from b[]193* continues. When there is no more sufficient data in b[] to build up a194* chunk of preferredChunkSize size the data get stored as an incomplete195* chunk of a following format: {space for data length}{CRLF}{data}196* The size of the data is of course smaller than preferredChunkSize.197*/198@Override199public synchronized void write(byte b[], int off, int len) {200ensureOpen();201if ((off < 0) || (off > b.length) || (len < 0) ||202((off + len) > b.length) || ((off + len) < 0)) {203throw new IndexOutOfBoundsException();204} else if (len == 0) {205return;206}207208/* if b[] contains enough data then one loop cycle creates one complete209* data chunk with a header, body and a footer, and then flushes the210* chunk to the underlying stream. Otherwise, the last loop cycle211* creates incomplete data chunk with empty header and with no footer212* and stores this incomplete chunk in an internal buffer buf[]213*/214int bytesToWrite = len;215int inputIndex = off; /* the index of the byte[] currently being written */216217do {218/* enough data to complete a chunk */219if (bytesToWrite >= spaceInCurrentChunk) {220221/* header */222for (int i=0; i<completeHeader.length; i++)223buf[i] = completeHeader[i];224225/* data */226System.arraycopy(b, inputIndex, buf, count, spaceInCurrentChunk);227inputIndex += spaceInCurrentChunk;228bytesToWrite -= spaceInCurrentChunk;229count += spaceInCurrentChunk;230231/* footer */232buf[count++] = FOOTER[0];233buf[count++] = FOOTER[1];234spaceInCurrentChunk = 0; //chunk is complete235236flush(false);237if (checkError()){238break;239}240}241242/* not enough data to build a chunk */243else {244/* header */245/* do not write header if not enough bytes to build a chunk yet */246247/* data */248System.arraycopy(b, inputIndex, buf, count, bytesToWrite);249count += bytesToWrite;250size += bytesToWrite;251spaceInCurrentChunk -= bytesToWrite;252bytesToWrite = 0;253254/* footer */255/* do not write header if not enough bytes to build a chunk yet */256}257} while (bytesToWrite > 0);258}259260@Override261public synchronized void write(int _b) {262byte b[] = {(byte)_b};263write(b, 0, 1);264}265266public synchronized void reset() {267count = preferedHeaderSize;268size = 0;269spaceInCurrentChunk = preferredChunkDataSize;270}271272public int size() {273return size;274}275276@Override277public synchronized void close() {278ensureOpen();279280/* if we have buffer a chunked send it */281if (size > 0) {282flush(true);283}284285/* send a zero length chunk */286flush(true);287288/* don't close the underlying stream */289out = null;290}291292@Override293public synchronized void flush() {294ensureOpen();295if (size > 0) {296flush(true);297}298}299}300301302