-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Response.java
767 lines (621 loc) · 20.5 KB
/
Response.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.coyote;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import javax.servlet.WriteListener;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.buf.B2CConverter;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.http.parser.MediaType;
import org.apache.tomcat.util.res.StringManager;
/**
* Response object.
*
* @author James Duncan Davidson [duncan@eng.sun.com]
* @author Jason Hunter [jch@eng.sun.com]
* @author James Todd [gonzo@eng.sun.com]
* @author Harish Prabandham
* @author Hans Bergsten [hans@gefionsoftware.com]
* @author Remy Maucherat
*/
public final class Response {
private static final StringManager sm = StringManager.getManager(Response.class);
private static final Log log = LogFactory.getLog(Response.class);
// ----------------------------------------------------- Class Variables
/**
* Default locale as mandated by the spec.
*/
private static final Locale DEFAULT_LOCALE = Locale.getDefault();
// ----------------------------------------------------- Instance Variables
/**
* Status code.
*/
int status = 200;
/**
* Status message.
*/
String message = null;
/**
* Response headers.
*/
final MimeHeaders headers = new MimeHeaders();
private Supplier<Map<String,String>> trailerFieldsSupplier = null;
/**
* Associated output buffer.
*/
OutputBuffer outputBuffer;
/**
* Notes.
*/
final Object notes[] = new Object[Constants.MAX_NOTES];
/**
* Committed flag.
*/
volatile boolean commited = false;
/**
* Action hook.
*/
volatile ActionHook hook;
/**
* HTTP specific fields.
*/
String contentType = null;
String contentLanguage = null;
Charset charset = null;
// Retain the original name used to set the charset so exactly that name is
// used in the ContentType header. Some (arguably non-specification
// compliant) user agents are very particular
String characterEncoding = null;
long contentLength = -1;
private Locale locale = DEFAULT_LOCALE;
// General informations
private long contentWritten = 0;
private long commitTime = -1;
/**
* Holds request error exception.
*/
Exception errorException = null;
/**
* With the introduction of async processing and the possibility of
* non-container threads calling sendError() tracking the current error
* state and ensuring that the correct error page is called becomes more
* complicated. This state attribute helps by tracking the current error
* state and informing callers that attempt to change state if the change
* was successful or if another thread got there first.
*
* <pre>
* The state machine is very simple:
*
* 0 - NONE
* 1 - NOT_REPORTED
* 2 - REPORTED
*
*
* -->---->-- >NONE
* | | |
* | | | setError()
* ^ ^ |
* | | \|/
* | |-<-NOT_REPORTED
* | |
* ^ | report()
* | |
* | \|/
* |----<----REPORTED
* </pre>
*/
private final AtomicInteger errorState = new AtomicInteger(0);
Request req;
// ------------------------------------------------------------- Properties
public Request getRequest() {
return req;
}
public void setRequest( Request req ) {
this.req=req;
}
public void setOutputBuffer(OutputBuffer outputBuffer) {
this.outputBuffer = outputBuffer;
}
public MimeHeaders getMimeHeaders() {
return headers;
}
protected void setHook(ActionHook hook) {
this.hook = hook;
}
// -------------------- Per-Response "notes" --------------------
public final void setNote(int pos, Object value) {
notes[pos] = value;
}
public final Object getNote(int pos) {
return notes[pos];
}
// -------------------- Actions --------------------
public void action(ActionCode actionCode, Object param) {
if (hook != null) {
if (param == null) {
hook.action(actionCode, this);
} else {
hook.action(actionCode, param);
}
}
}
// -------------------- State --------------------
public int getStatus() {
return status;
}
/**
* Set the response status.
*
* @param status The status value to set
*/
public void setStatus(int status) {
if (this.status > 399) {
// Don't overwrite first recorded error status
return;
}
this.status = status;
}
/**
* Get the status message.
*
* @return The message associated with the current status
*/
public String getMessage() {
return message;
}
/**
* Set the status message.
*
* @param message The status message to set
*/
public void setMessage(String message) {
this.message = message;
}
public boolean isCommitted() {
return commited;
}
public void setCommitted(boolean v) {
if (v && !this.commited) {
this.commitTime = System.currentTimeMillis();
}
this.commited = v;
}
/**
* Return the time the response was committed (based on System.currentTimeMillis).
*
* @return the time the response was committed
*/
public long getCommitTime() {
return commitTime;
}
// -----------------Error State --------------------
/**
* Set the error Exception that occurred during request processing.
*
* @param ex The exception that occurred
*/
public void setErrorException(Exception ex) {
errorException = ex;
}
/**
* Get the Exception that occurred during request processing.
*
* @return The exception that occurred
*/
public Exception getErrorException() {
return errorException;
}
public boolean isExceptionPresent() {
return ( errorException != null );
}
/**
* Set the error flag.
*
* @return <code>false</code> if the error flag was already set
*/
public boolean setError() {
return errorState.compareAndSet(0, 1);
}
/**
* Error flag accessor.
*
* @return <code>true</code> if the response has encountered an error
*/
public boolean isError() {
return errorState.get() > 0;
}
public boolean isErrorReportRequired() {
return errorState.get() == 1;
}
public boolean setErrorReported() {
return errorState.compareAndSet(1, 2);
}
// -------------------- Methods --------------------
public void reset() throws IllegalStateException {
if (commited) {
throw new IllegalStateException();
}
recycle();
}
// -------------------- Headers --------------------
/**
* Does the response contain the given header.
* <br>
* Warning: This method always returns <code>false</code> for Content-Type
* and Content-Length.
*
* @param name The name of the header of interest
*
* @return {@code true} if the response contains the header.
*/
public boolean containsHeader(String name) {
return headers.getHeader(name) != null;
}
public void setHeader(String name, String value) {
char cc=name.charAt(0);
if( cc=='C' || cc=='c' ) {
if( checkSpecialHeader(name, value) )
return;
}
headers.setValue(name).setString( value);
}
public void addHeader(String name, String value) {
addHeader(name, value, null);
}
public void addHeader(String name, String value, Charset charset) {
char cc=name.charAt(0);
if( cc=='C' || cc=='c' ) {
if( checkSpecialHeader(name, value) )
return;
}
MessageBytes mb = headers.addValue(name);
if (charset != null) {
mb.setCharset(charset);
}
mb.setString(value);
}
public void setTrailerFields(Supplier<Map<String, String>> supplier) {
AtomicBoolean trailerFieldsSupported = new AtomicBoolean(false);
action(ActionCode.IS_TRAILER_FIELDS_SUPPORTED, trailerFieldsSupported);
if (!trailerFieldsSupported.get()) {
throw new IllegalStateException(sm.getString("response.noTrailers.notSupported"));
}
this.trailerFieldsSupplier = supplier;
}
public Supplier<Map<String, String>> getTrailerFields() {
return trailerFieldsSupplier;
}
/**
* Set internal fields for special header names.
* Called from set/addHeader.
* Return true if the header is special, no need to set the header.
*/
private boolean checkSpecialHeader( String name, String value) {
// XXX Eliminate redundant fields !!!
// ( both header and in special fields )
if( name.equalsIgnoreCase( "Content-Type" ) ) {
setContentType( value );
return true;
}
if( name.equalsIgnoreCase( "Content-Length" ) ) {
try {
long cL=Long.parseLong( value );
setContentLength( cL );
return true;
} catch( NumberFormatException ex ) {
// Do nothing - the spec doesn't have any "throws"
// and the user might know what he's doing
return false;
}
}
return false;
}
/** Signal that we're done with the headers, and body will follow.
* Any implementation needs to notify ContextManager, to allow
* interceptors to fix headers.
*/
public void sendHeaders() {
action(ActionCode.COMMIT, this);
setCommitted(true);
}
// -------------------- I18N --------------------
public Locale getLocale() {
return locale;
}
/**
* Called explicitly by user to set the Content-Language and the default
* encoding.
*
* @param locale The locale to use for this response
*/
public void setLocale(Locale locale) {
if (locale == null) {
return; // throw an exception?
}
// Save the locale for use by getLocale()
this.locale = locale;
// Set the contentLanguage for header output
contentLanguage = locale.toLanguageTag();
}
/**
* Return the content language.
*
* @return The language code for the language currently associated with this
* response
*/
public String getContentLanguage() {
return contentLanguage;
}
/**
* Overrides the character encoding used in the body of the response. This
* method must be called prior to writing output using getWriter().
*
* @param characterEncoding The name of character encoding.
*
* @throws UnsupportedEncodingException If the specified name is not
* recognised
*/
public void setCharacterEncoding(String characterEncoding) throws UnsupportedEncodingException {
if (isCommitted()) {
return;
}
if (characterEncoding == null) {
return;
}
this.charset = B2CConverter.getCharset(characterEncoding);
this.characterEncoding = characterEncoding;
}
public Charset getCharset() {
return charset;
}
public String getCharacterEncoding() {
return characterEncoding;
}
/**
* Sets the content type.
*
* This method must preserve any response charset that may already have
* been set via a call to response.setContentType(), response.setLocale(),
* or response.setCharacterEncoding().
*
* @param type the content type
*/
public void setContentType(String type) {
if (type == null) {
this.contentType = null;
return;
}
MediaType m = null;
try {
m = MediaType.parseMediaType(new StringReader(type));
} catch (IOException e) {
// Ignore - null test below handles this
}
if (m == null) {
// Invalid - Assume no charset and just pass through whatever
// the user provided.
this.contentType = type;
return;
}
this.contentType = m.toStringNoCharset();
String charsetValue = m.getCharset();
if (charsetValue != null) {
charsetValue = charsetValue.trim();
if (charsetValue.length() > 0) {
try {
charset = B2CConverter.getCharset(charsetValue);
} catch (UnsupportedEncodingException e) {
log.warn(sm.getString("response.encoding.invalid", charsetValue), e);
}
}
}
}
public void setContentTypeNoCharset(String type) {
this.contentType = type;
}
public String getContentType() {
String ret = contentType;
if (ret != null
&& charset != null) {
ret = ret + ";charset=" + characterEncoding;
}
return ret;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public int getContentLength() {
long length = getContentLengthLong();
if (length < Integer.MAX_VALUE) {
return (int) length;
}
return -1;
}
public long getContentLengthLong() {
return contentLength;
}
/**
* Write a chunk of bytes.
*
* @param chunk The ByteBuffer to write
*
* @throws IOException If an I/O error occurs during the write
*/
public void doWrite(ByteBuffer chunk) throws IOException {
int len = chunk.remaining();
outputBuffer.doWrite(chunk);
contentWritten += len - chunk.remaining();
}
// --------------------
public void recycle() {
contentType = null;
contentLanguage = null;
locale = DEFAULT_LOCALE;
charset = null;
characterEncoding = null;
contentLength = -1;
status = 200;
message = null;
commited = false;
commitTime = -1;
errorException = null;
errorState.set(0);
headers.clear();
trailerFieldsSupplier = null;
// Servlet 3.1 non-blocking write listener
listener = null;
fireListener = false;
registeredForWrite = false;
// update counters
contentWritten=0;
}
/**
* Bytes written by application - i.e. before compression, chunking, etc.
*
* @return The total number of bytes written to the response by the
* application. This will not be the number of bytes written to the
* network which may be more or less than this value.
*/
public long getContentWritten() {
return contentWritten;
}
/**
* Bytes written to socket - i.e. after compression, chunking, etc.
*
* @param flush Should any remaining bytes be flushed before returning the
* total? If {@code false} bytes remaining in the buffer will
* not be included in the returned value
*
* @return The total number of bytes written to the socket for this response
*/
public long getBytesWritten(boolean flush) {
if (flush) {
action(ActionCode.CLIENT_FLUSH, this);
}
return outputBuffer.getBytesWritten();
}
/*
* State for non-blocking output is maintained here as it is the one point
* easily reachable from the CoyoteOutputStream and the Processor which both
* need access to state.
*/
volatile WriteListener listener;
private boolean fireListener = false;
private boolean registeredForWrite = false;
private final Object nonBlockingStateLock = new Object();
public WriteListener getWriteListener() {
return listener;
}
public void setWriteListener(WriteListener listener) {
if (listener == null) {
throw new NullPointerException(
sm.getString("response.nullWriteListener"));
}
if (getWriteListener() != null) {
throw new IllegalStateException(
sm.getString("response.writeListenerSet"));
}
// Note: This class is not used for HTTP upgrade so only need to test
// for async
AtomicBoolean result = new AtomicBoolean(false);
action(ActionCode.ASYNC_IS_ASYNC, result);
if (!result.get()) {
throw new IllegalStateException(
sm.getString("response.notAsync"));
}
this.listener = listener;
// The container is responsible for the first call to
// listener.onWritePossible(). If isReady() returns true, the container
// needs to call listener.onWritePossible() from a new thread. If
// isReady() returns false, the socket will be registered for write and
// the container will call listener.onWritePossible() once data can be
// written.
if (isReady()) {
synchronized (nonBlockingStateLock) {
// Ensure we don't get multiple write registrations if
// ServletOutputStream.isReady() returns false during a call to
// onDataAvailable()
registeredForWrite = true;
// Need to set the fireListener flag otherwise when the
// container tries to trigger onWritePossible, nothing will
// happen
fireListener = true;
}
action(ActionCode.DISPATCH_WRITE, null);
if (!ContainerThreadMarker.isContainerThread()) {
// Not on a container thread so need to execute the dispatch
action(ActionCode.DISPATCH_EXECUTE, null);
}
}
}
public boolean isReady() {
if (listener == null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("response.notNonBlocking"));
}
return false;
}
// Assume write is not possible
boolean ready = false;
synchronized (nonBlockingStateLock) {
if (registeredForWrite) {
fireListener = true;
return false;
}
ready = checkRegisterForWrite();
fireListener = !ready;
}
return ready;
}
public boolean checkRegisterForWrite() {
AtomicBoolean ready = new AtomicBoolean(false);
synchronized (nonBlockingStateLock) {
if (!registeredForWrite) {
action(ActionCode.NB_WRITE_INTEREST, ready);
registeredForWrite = !ready.get();
}
}
return ready.get();
}
public void onWritePossible() throws IOException {
// Any buffered data left over from a previous non-blocking write is
// written in the Processor so if this point is reached the app is able
// to write data.
boolean fire = false;
synchronized (nonBlockingStateLock) {
registeredForWrite = false;
if (fireListener) {
fireListener = false;
fire = true;
}
}
if (fire) {
listener.onWritePossible();
}
}
}