Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/sun/net/www/http/ChunkedOutputStream.java
41161 views
1
/*
2
* Copyright (c) 2004, 2020, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
package sun.net.www.http;
26
27
import java.io.*;
28
import java.util.concurrent.locks.Lock;
29
import java.util.concurrent.locks.ReentrantLock;
30
31
import sun.nio.cs.US_ASCII;
32
33
/**
34
* OutputStream that sends the output to the underlying stream using chunked
35
* encoding as specified in RFC 2068.
36
*/
37
public class ChunkedOutputStream extends OutputStream {
38
39
/* Default chunk size (including chunk header) if not specified */
40
static final int DEFAULT_CHUNK_SIZE = 4096;
41
private static final byte[] CRLF = {'\r', '\n'};
42
private static final int CRLF_SIZE = CRLF.length;
43
private static final byte[] FOOTER = CRLF;
44
private static final int FOOTER_SIZE = CRLF_SIZE;
45
private static final byte[] EMPTY_CHUNK_HEADER = getHeader(0);
46
private static final int EMPTY_CHUNK_HEADER_SIZE = getHeaderSize(0);
47
48
/* internal buffer */
49
private byte buf[];
50
/* size of data (excluding footers and headers) already stored in buf */
51
private int size;
52
/* current index in buf (i.e. buf[count] */
53
private int count;
54
/* number of bytes to be filled up to complete a data chunk
55
* currently being built */
56
private int spaceInCurrentChunk;
57
58
/* underlying stream */
59
private PrintStream out;
60
61
/* the chunk size we use */
62
private int preferredChunkDataSize;
63
private int preferedHeaderSize;
64
private int preferredChunkGrossSize;
65
/* header for a complete Chunk */
66
private byte[] completeHeader;
67
68
private final Lock writeLock = new ReentrantLock();
69
70
/* return the size of the header for a particular chunk size */
71
private static int getHeaderSize(int size) {
72
return (Integer.toHexString(size)).length() + CRLF_SIZE;
73
}
74
75
/* return a header for a particular chunk size */
76
private static byte[] getHeader(int size) {
77
String hexStr = Integer.toHexString(size);
78
byte[] hexBytes = hexStr.getBytes(US_ASCII.INSTANCE);
79
byte[] header = new byte[getHeaderSize(size)];
80
for (int i=0; i<hexBytes.length; i++)
81
header[i] = hexBytes[i];
82
header[hexBytes.length] = CRLF[0];
83
header[hexBytes.length+1] = CRLF[1];
84
return header;
85
}
86
87
public ChunkedOutputStream(PrintStream o) {
88
this(o, DEFAULT_CHUNK_SIZE);
89
}
90
91
public ChunkedOutputStream(PrintStream o, int size) {
92
out = o;
93
94
if (size <= 0) {
95
size = DEFAULT_CHUNK_SIZE;
96
}
97
98
/* Adjust the size to cater for the chunk header - eg: if the
99
* preferred chunk size is 1k this means the chunk size should
100
* be 1017 bytes (differs by 7 from preferred size because of
101
* 3 bytes for chunk size in hex and CRLF (header) and CRLF (footer)).
102
*
103
* If headerSize(adjusted_size) is shorter then headerSize(size)
104
* then try to use the extra byte unless headerSize(adjusted_size+1)
105
* increases back to headerSize(size)
106
*/
107
if (size > 0) {
108
int adjusted_size = size - getHeaderSize(size) - FOOTER_SIZE;
109
if (getHeaderSize(adjusted_size+1) < getHeaderSize(size)){
110
adjusted_size++;
111
}
112
size = adjusted_size;
113
}
114
115
if (size > 0) {
116
preferredChunkDataSize = size;
117
} else {
118
preferredChunkDataSize = DEFAULT_CHUNK_SIZE -
119
getHeaderSize(DEFAULT_CHUNK_SIZE) - FOOTER_SIZE;
120
}
121
122
preferedHeaderSize = getHeaderSize(preferredChunkDataSize);
123
preferredChunkGrossSize = preferedHeaderSize + preferredChunkDataSize
124
+ FOOTER_SIZE;
125
completeHeader = getHeader(preferredChunkDataSize);
126
127
/* start with an initial buffer */
128
buf = new byte[preferredChunkGrossSize];
129
reset();
130
}
131
132
/*
133
* Flush a buffered, completed chunk to an underlying stream. If the data in
134
* the buffer is insufficient to build up a chunk of "preferredChunkSize"
135
* then the data do not get flushed unless flushAll is true. If flushAll is
136
* true then the remaining data builds up a last chunk which size is smaller
137
* than preferredChunkSize, and then the last chunk gets flushed to
138
* underlying stream. If flushAll is true and there is no data in a buffer
139
* at all then an empty chunk (containing a header only) gets flushed to
140
* underlying stream.
141
*/
142
private void flush(boolean flushAll) {
143
if (spaceInCurrentChunk == 0) {
144
/* flush a completed chunk to underlying stream */
145
out.write(buf, 0, preferredChunkGrossSize);
146
out.flush();
147
reset();
148
} else if (flushAll){
149
/* complete the last chunk and flush it to underlying stream */
150
if (size > 0) {
151
/* adjust a header start index in case the header of the last
152
* chunk is shorter then preferedHeaderSize */
153
154
int adjustedHeaderStartIndex = preferedHeaderSize -
155
getHeaderSize(size);
156
157
/* write header */
158
System.arraycopy(getHeader(size), 0, buf,
159
adjustedHeaderStartIndex, getHeaderSize(size));
160
161
/* write footer */
162
buf[count++] = FOOTER[0];
163
buf[count++] = FOOTER[1];
164
165
//send the last chunk to underlying stream
166
out.write(buf, adjustedHeaderStartIndex, count - adjustedHeaderStartIndex);
167
} else {
168
//send an empty chunk (containing just a header) to underlying stream
169
out.write(EMPTY_CHUNK_HEADER, 0, EMPTY_CHUNK_HEADER_SIZE);
170
}
171
172
out.flush();
173
reset();
174
}
175
}
176
177
public boolean checkError() {
178
var out = this.out;
179
return out == null || out.checkError();
180
}
181
182
/* Check that the output stream is still open */
183
private void ensureOpen() throws IOException {
184
if (out == null)
185
throw new IOException("closed");
186
}
187
188
/*
189
* Writes data from b[] to an internal buffer and stores the data as data
190
* chunks of a following format: {Data length in Hex}{CRLF}{data}{CRLF}
191
* The size of the data is preferredChunkSize. As soon as a completed chunk
192
* is read from b[] a process of reading from b[] suspends, the chunk gets
193
* flushed to the underlying stream and then the reading process from b[]
194
* continues. When there is no more sufficient data in b[] to build up a
195
* chunk of preferredChunkSize size the data get stored as an incomplete
196
* chunk of a following format: {space for data length}{CRLF}{data}
197
* The size of the data is of course smaller than preferredChunkSize.
198
*/
199
@Override
200
public void write(byte b[], int off, int len) throws IOException {
201
writeLock.lock();
202
try {
203
ensureOpen();
204
if ((off < 0) || (off > b.length) || (len < 0) ||
205
((off + len) > b.length) || ((off + len) < 0)) {
206
throw new IndexOutOfBoundsException();
207
} else if (len == 0) {
208
return;
209
}
210
211
/* if b[] contains enough data then one loop cycle creates one complete
212
* data chunk with a header, body and a footer, and then flushes the
213
* chunk to the underlying stream. Otherwise, the last loop cycle
214
* creates incomplete data chunk with empty header and with no footer
215
* and stores this incomplete chunk in an internal buffer buf[]
216
*/
217
int bytesToWrite = len;
218
int inputIndex = off; /* the index of the byte[] currently being written */
219
220
do {
221
/* enough data to complete a chunk */
222
if (bytesToWrite >= spaceInCurrentChunk) {
223
224
/* header */
225
for (int i = 0; i < completeHeader.length; i++)
226
buf[i] = completeHeader[i];
227
228
/* data */
229
System.arraycopy(b, inputIndex, buf, count, spaceInCurrentChunk);
230
inputIndex += spaceInCurrentChunk;
231
bytesToWrite -= spaceInCurrentChunk;
232
count += spaceInCurrentChunk;
233
234
/* footer */
235
buf[count++] = FOOTER[0];
236
buf[count++] = FOOTER[1];
237
spaceInCurrentChunk = 0; //chunk is complete
238
239
flush(false);
240
if (checkError()) {
241
break;
242
}
243
}
244
245
/* not enough data to build a chunk */
246
else {
247
/* header */
248
/* do not write header if not enough bytes to build a chunk yet */
249
250
/* data */
251
System.arraycopy(b, inputIndex, buf, count, bytesToWrite);
252
count += bytesToWrite;
253
size += bytesToWrite;
254
spaceInCurrentChunk -= bytesToWrite;
255
bytesToWrite = 0;
256
257
/* footer */
258
/* do not write header if not enough bytes to build a chunk yet */
259
}
260
} while (bytesToWrite > 0);
261
} finally {
262
writeLock.unlock();
263
}
264
}
265
266
@Override
267
public void write(int _b) throws IOException {
268
writeLock.lock();
269
try {
270
byte b[] = {(byte) _b};
271
write(b, 0, 1);
272
} finally {
273
writeLock.unlock();
274
}
275
}
276
277
public void reset() {
278
writeLock.lock();
279
try {
280
count = preferedHeaderSize;
281
size = 0;
282
spaceInCurrentChunk = preferredChunkDataSize;
283
} finally {
284
writeLock.unlock();
285
}
286
}
287
288
public int size() {
289
return size;
290
}
291
292
@Override
293
public void close() {
294
writeLock.lock();
295
try {
296
if (out == null) return;
297
298
/* if we have buffer a chunked send it */
299
if (size > 0) {
300
flush(true);
301
}
302
303
/* send a zero length chunk */
304
flush(true);
305
306
/* don't close the underlying stream */
307
out = null;
308
} finally {
309
writeLock.unlock();
310
}
311
}
312
313
@Override
314
public void flush() throws IOException {
315
writeLock.lock();
316
try {
317
ensureOpen();
318
if (size > 0) {
319
flush(true);
320
}
321
} finally {
322
writeLock.unlock();
323
}
324
}
325
}
326
327