/
Response.java
1328 lines (1170 loc) · 40.7 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
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.channels.IllegalSelectorException;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Locale;
import java.util.function.Supplier;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.ServletResponseWrapper;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import org.eclipse.jetty.http.CookieCompliance;
import org.eclipse.jetty.http.DateGenerator;
import org.eclipse.jetty.http.HttpContent;
import org.eclipse.jetty.http.HttpCookie;
import org.eclipse.jetty.http.HttpCookie.SameSite;
import org.eclipse.jetty.http.HttpCookie.SetCookieHttpField;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpGenerator;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpHeaderValue;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.http.MetaData;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.http.PreEncodedHttpField;
import org.eclipse.jetty.io.RuntimeIOException;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.util.AtomicBiInteger;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/**
* <p>{@link Response} provides the implementation for {@link HttpServletResponse}.</p>
*/
public class Response implements HttpServletResponse
{
private static final Logger LOG = Log.getLogger(Response.class);
private static final int __MIN_BUFFER_SIZE = 1;
private static final HttpField __EXPIRES_01JAN1970 = new PreEncodedHttpField(HttpHeader.EXPIRES, DateGenerator.__01Jan1970);
public enum OutputType
{
NONE, STREAM, WRITER
}
/**
* If a header name starts with this string, the header (stripped of the prefix)
* can be set during include using only {@link #setHeader(String, String)} or
* {@link #addHeader(String, String)}.
*/
public static final String SET_INCLUDE_HEADER_PREFIX = "org.eclipse.jetty.server.include.";
private final HttpChannel _channel;
private final HttpFields _fields = new HttpFields();
private final AtomicBiInteger _errorSentAndIncludes = new AtomicBiInteger(); // hi is errorSent flag, lo is include count
private final HttpOutput _out;
private int _status = HttpStatus.OK_200;
private String _reason;
private Locale _locale;
private MimeTypes.Type _mimeType;
private String _characterEncoding;
private EncodingFrom _encodingFrom = EncodingFrom.NOT_SET;
private String _contentType;
private OutputType _outputType = OutputType.NONE;
private ResponseWriter _writer;
private long _contentLength = -1;
private Supplier<HttpFields> _trailers;
private enum EncodingFrom
{
NOT_SET, INFERRED, SET_LOCALE, SET_CONTENT_TYPE, SET_CHARACTER_ENCODING
}
private static final EnumSet<EncodingFrom> __localeOverride = EnumSet.of(EncodingFrom.NOT_SET, EncodingFrom.INFERRED);
private static final EnumSet<EncodingFrom> __explicitCharset = EnumSet.of(EncodingFrom.SET_LOCALE, EncodingFrom.SET_CHARACTER_ENCODING);
public Response(HttpChannel channel, HttpOutput out)
{
_channel = channel;
_out = out;
}
public HttpChannel getHttpChannel()
{
return _channel;
}
protected void recycle()
{
_status = HttpStatus.OK_200;
_reason = null;
_locale = null;
_mimeType = null;
_characterEncoding = null;
_contentType = null;
_outputType = OutputType.NONE;
_contentLength = -1;
_out.recycle();
_fields.clear();
_encodingFrom = EncodingFrom.NOT_SET;
}
public HttpOutput getHttpOutput()
{
return _out;
}
public void reopen()
{
setErrorSent(false);
_out.reopen();
}
public void softClose()
{
setErrorSent(true);
_out.closedBySendError();
}
/**
* @return true if the response is mutable, ie not errorSent and not included
*/
private boolean isMutable()
{
return _errorSentAndIncludes.get() == 0;
}
private void setErrorSent(boolean errorSent)
{
_errorSentAndIncludes.getAndSetHi(errorSent ? 1 : 0);
}
public boolean isIncluding()
{
return _errorSentAndIncludes.getLo() > 0;
}
public void include()
{
_errorSentAndIncludes.add(0, 1);
}
public void included()
{
_errorSentAndIncludes.add(0, -1);
if (_outputType == OutputType.WRITER)
{
_writer.reopen();
}
_out.reopen();
}
public void addCookie(HttpCookie cookie)
{
if (StringUtil.isBlank(cookie.getName()))
throw new IllegalArgumentException("Cookie.name cannot be blank/null");
// add the set cookie
_fields.add(new SetCookieHttpField(cookie, getHttpChannel().getHttpConfiguration().getResponseCookieCompliance()));
// Expire responses with set-cookie headers so they do not get cached.
_fields.put(__EXPIRES_01JAN1970);
}
/**
* Replace (or add) a cookie.
* Using name, path and domain, look for a matching set-cookie header and replace it.
*
* @param cookie The cookie to add/replace
*/
public void replaceCookie(HttpCookie cookie)
{
for (ListIterator<HttpField> i = _fields.listIterator(); i.hasNext(); )
{
HttpField field = i.next();
if (field.getHeader() == HttpHeader.SET_COOKIE)
{
CookieCompliance compliance = getHttpChannel().getHttpConfiguration().getResponseCookieCompliance();
HttpCookie oldCookie;
if (field instanceof SetCookieHttpField)
oldCookie = ((SetCookieHttpField)field).getHttpCookie();
else
oldCookie = new HttpCookie(field.getValue());
if (!cookie.getName().equals(oldCookie.getName()))
continue;
if (cookie.getDomain() == null)
{
if (oldCookie.getDomain() != null)
continue;
}
else if (!cookie.getDomain().equalsIgnoreCase(oldCookie.getDomain()))
continue;
if (cookie.getPath() == null)
{
if (oldCookie.getPath() != null)
continue;
}
else if (!cookie.getPath().equals(oldCookie.getPath()))
continue;
i.set(new SetCookieHttpField(cookie, compliance));
return;
}
}
// Not replaced, so add normally
addCookie(cookie);
}
@Override
public void addCookie(Cookie cookie)
{
if (StringUtil.isBlank(cookie.getName()))
throw new IllegalArgumentException("Cookie.name cannot be blank/null");
String comment = cookie.getComment();
// HttpOnly was supported as a comment in cookie flags before the java.net.HttpCookie implementation so need to check that
boolean httpOnly = cookie.isHttpOnly() || HttpCookie.isHttpOnlyInComment(comment);
SameSite sameSite = HttpCookie.getSameSiteFromComment(comment);
comment = HttpCookie.getCommentWithoutAttributes(comment);
addCookie(new HttpCookie(
cookie.getName(),
cookie.getValue(),
cookie.getDomain(),
cookie.getPath(),
(long)cookie.getMaxAge(),
httpOnly,
cookie.getSecure(),
comment,
cookie.getVersion(),
sameSite));
}
@Override
public boolean containsHeader(String name)
{
return _fields.containsKey(name);
}
@Override
public String encodeURL(String url)
{
final Request request = _channel.getRequest();
SessionHandler sessionManager = request.getSessionHandler();
if (sessionManager == null)
return url;
HttpURI uri = null;
if (sessionManager.isCheckingRemoteSessionIdEncoding() && URIUtil.hasScheme(url))
{
uri = new HttpURI(url);
String path = uri.getPath();
path = (path == null ? "" : path);
int port = uri.getPort();
if (port < 0)
port = HttpScheme.HTTPS.asString().equalsIgnoreCase(uri.getScheme()) ? 443 : 80;
// Is it the same server?
if (!request.getServerName().equalsIgnoreCase(uri.getHost()))
return url;
if (request.getServerPort() != port)
return url;
if (!path.startsWith(request.getContextPath())) //TODO the root context path is "", with which every non null string starts
return url;
}
String sessionURLPrefix = sessionManager.getSessionIdPathParameterNamePrefix();
if (sessionURLPrefix == null)
return url;
if (url == null)
return null;
// should not encode if cookies in evidence
if ((sessionManager.isUsingCookies() && request.isRequestedSessionIdFromCookie()) || !sessionManager.isUsingURLs())
{
int prefix = url.indexOf(sessionURLPrefix);
if (prefix != -1)
{
int suffix = url.indexOf("?", prefix);
if (suffix < 0)
suffix = url.indexOf("#", prefix);
if (suffix <= prefix)
return url.substring(0, prefix);
return url.substring(0, prefix) + url.substring(suffix);
}
return url;
}
// get session;
HttpSession session = request.getSession(false);
// no session
if (session == null)
return url;
// invalid session
if (!sessionManager.isValid(session))
return url;
String id = sessionManager.getExtendedId(session);
if (uri == null)
uri = new HttpURI(url);
// Already encoded
int prefix = url.indexOf(sessionURLPrefix);
if (prefix != -1)
{
int suffix = url.indexOf("?", prefix);
if (suffix < 0)
suffix = url.indexOf("#", prefix);
if (suffix <= prefix)
return url.substring(0, prefix + sessionURLPrefix.length()) + id;
return url.substring(0, prefix + sessionURLPrefix.length()) + id +
url.substring(suffix);
}
// edit the session
int suffix = url.indexOf('?');
if (suffix < 0)
suffix = url.indexOf('#');
if (suffix < 0)
{
return url +
((HttpScheme.HTTPS.is(uri.getScheme()) || HttpScheme.HTTP.is(uri.getScheme())) && uri.getPath() == null ? "/" : "") + //if no path, insert the root path
sessionURLPrefix + id;
}
return url.substring(0, suffix) +
((HttpScheme.HTTPS.is(uri.getScheme()) || HttpScheme.HTTP.is(uri.getScheme())) && uri.getPath() == null ? "/" : "") + //if no path so insert the root path
sessionURLPrefix + id + url.substring(suffix);
}
@Override
public String encodeRedirectURL(String url)
{
return encodeURL(url);
}
@Override
@Deprecated
public String encodeUrl(String url)
{
return encodeURL(url);
}
@Override
@Deprecated
public String encodeRedirectUrl(String url)
{
return encodeRedirectURL(url);
}
@Override
public void sendError(int sc) throws IOException
{
sendError(sc, null);
}
/**
* Send an error response.
* <p>In addition to the servlet standard handling, this method supports some additional codes:</p>
* <dl>
* <dt>102</dt><dd>Send a partial PROCESSING response and allow additional responses</dd>
* <dt>-1</dt><dd>Abort the HttpChannel and close the connection/stream</dd>
* </dl>
* @param code The error code
* @param message The message
* @throws IOException If an IO problem occurred sending the error response.
*/
@Override
public void sendError(int code, String message) throws IOException
{
if (isIncluding())
return;
switch (code)
{
case -1:
_channel.abort(new IOException(message));
break;
case HttpStatus.PROCESSING_102:
sendProcessing();
break;
default:
_channel.getState().sendError(code, message);
break;
}
}
/**
* Sends a 102-Processing response.
* If the connection is an HTTP connection, the version is 1.1 and the
* request has a Expect header starting with 102, then a 102 response is
* sent. This indicates that the request still be processed and real response
* can still be sent. This method is called by sendError if it is passed 102.
*
* @throws IOException if unable to send the 102 response
* @see javax.servlet.http.HttpServletResponse#sendError(int)
*/
public void sendProcessing() throws IOException
{
if (_channel.isExpecting102Processing() && !isCommitted())
{
_channel.sendResponse(HttpGenerator.PROGRESS_102_INFO, null, true);
}
}
/**
* Sends a response with one of the 300 series redirection codes.
*
* @param code the redirect status code
* @param location the location to send in {@code Location} headers
* @throws IOException if unable to send the redirect
*/
public void sendRedirect(int code, String location) throws IOException
{
if ((code < HttpServletResponse.SC_MULTIPLE_CHOICES) || (code >= HttpServletResponse.SC_BAD_REQUEST))
throw new IllegalArgumentException("Not a 3xx redirect code");
if (!isMutable())
return;
if (location == null)
throw new IllegalArgumentException();
if (!URIUtil.hasScheme(location))
{
StringBuilder buf = _channel.getRequest().getRootURL();
if (location.startsWith("/"))
{
// absolute in context
location = URIUtil.canonicalEncodedPath(location);
}
else
{
// relative to request
String path = _channel.getRequest().getRequestURI();
String parent = (path.endsWith("/")) ? path : URIUtil.parentPath(path);
location = URIUtil.canonicalEncodedPath(URIUtil.addEncodedPaths(parent, location));
if (location != null && !location.startsWith("/"))
buf.append('/');
}
if (location == null)
throw new IllegalStateException("path cannot be above root");
buf.append(location);
location = buf.toString();
}
resetBuffer();
setHeader(HttpHeader.LOCATION, location);
setStatus(code);
closeOutput();
}
@Override
public void sendRedirect(String location) throws IOException
{
sendRedirect(HttpServletResponse.SC_MOVED_TEMPORARILY, location);
}
@Override
public void setDateHeader(String name, long date)
{
if (isMutable())
_fields.putDateField(name, date);
}
@Override
public void addDateHeader(String name, long date)
{
if (isMutable())
_fields.addDateField(name, date);
}
public void setHeader(HttpHeader name, String value)
{
if (isMutable())
{
if (HttpHeader.CONTENT_TYPE == name)
setContentType(value);
else
{
_fields.put(name, value);
if (HttpHeader.CONTENT_LENGTH == name)
{
if (value == null)
_contentLength = -1L;
else
_contentLength = Long.parseLong(value);
}
}
}
}
@Override
public void setHeader(String name, String value)
{
long biInt = _errorSentAndIncludes.get();
if (biInt != 0)
{
boolean errorSent = AtomicBiInteger.getHi(biInt) != 0;
boolean including = AtomicBiInteger.getLo(biInt) > 0;
if (!errorSent && including && name.startsWith(SET_INCLUDE_HEADER_PREFIX))
name = name.substring(SET_INCLUDE_HEADER_PREFIX.length());
else
return;
}
if (HttpHeader.CONTENT_TYPE.is(name))
setContentType(value);
else
{
_fields.put(name, value);
if (HttpHeader.CONTENT_LENGTH.is(name))
{
if (value == null)
_contentLength = -1L;
else
_contentLength = Long.parseLong(value);
}
}
}
@Override
public Collection<String> getHeaderNames()
{
return _fields.getFieldNamesCollection();
}
@Override
public String getHeader(String name)
{
return _fields.get(name);
}
@Override
public Collection<String> getHeaders(String name)
{
Collection<String> i = _fields.getValuesList(name);
if (i == null)
return Collections.emptyList();
return i;
}
@Override
public void addHeader(String name, String value)
{
long biInt = _errorSentAndIncludes.get();
if (biInt != 0)
{
boolean errorSent = AtomicBiInteger.getHi(biInt) != 0;
boolean including = AtomicBiInteger.getLo(biInt) > 0;
if (!errorSent && including && name.startsWith(SET_INCLUDE_HEADER_PREFIX))
name = name.substring(SET_INCLUDE_HEADER_PREFIX.length());
else
return;
}
if (HttpHeader.CONTENT_TYPE.is(name))
{
setContentType(value);
return;
}
if (HttpHeader.CONTENT_LENGTH.is(name))
{
setHeader(name, value);
return;
}
_fields.add(name, value);
}
@Override
public void setIntHeader(String name, int value)
{
if (isMutable())
{
_fields.putLongField(name, value);
if (HttpHeader.CONTENT_LENGTH.is(name))
_contentLength = value;
}
}
@Override
public void addIntHeader(String name, int value)
{
if (isMutable())
{
_fields.add(name, Integer.toString(value));
if (HttpHeader.CONTENT_LENGTH.is(name))
_contentLength = value;
}
}
@Override
public void setStatus(int sc)
{
if (sc <= 0)
throw new IllegalArgumentException();
if (isMutable())
{
// Null the reason only if the status is different. This allows
// a specific reason to be sent with setStatusWithReason followed by sendError.
if (_status != sc)
_reason = null;
_status = sc;
}
}
@Override
@Deprecated
public void setStatus(int sc, String sm)
{
setStatusWithReason(sc, sm);
}
public void setStatusWithReason(int sc, String sm)
{
if (sc <= 0)
throw new IllegalArgumentException();
if (isMutable())
{
_status = sc;
_reason = sm;
}
}
@Override
public String getCharacterEncoding()
{
if (_characterEncoding == null)
{
String encoding = MimeTypes.getCharsetAssumedFromContentType(_contentType);
if (encoding != null)
return encoding;
encoding = MimeTypes.getCharsetInferredFromContentType(_contentType);
if (encoding != null)
return encoding;
return StringUtil.__ISO_8859_1;
}
return _characterEncoding;
}
@Override
public String getContentType()
{
return _contentType;
}
@Override
public ServletOutputStream getOutputStream() throws IOException
{
if (_outputType == OutputType.WRITER)
throw new IllegalStateException("WRITER");
_outputType = OutputType.STREAM;
return _out;
}
public boolean isWriting()
{
return _outputType == OutputType.WRITER;
}
public boolean isStreaming()
{
return _outputType == OutputType.STREAM;
}
public boolean isWritingOrStreaming()
{
return isWriting() || isStreaming();
}
@Override
public PrintWriter getWriter() throws IOException
{
if (_outputType == OutputType.STREAM)
throw new IllegalStateException("STREAM");
if (_outputType == OutputType.NONE)
{
/* get encoding from Content-Type header */
String encoding = _characterEncoding;
if (encoding == null)
{
if (_mimeType != null && _mimeType.isCharsetAssumed())
encoding = _mimeType.getCharsetString();
else
{
encoding = MimeTypes.getCharsetAssumedFromContentType(_contentType);
if (encoding == null)
{
encoding = MimeTypes.getCharsetInferredFromContentType(_contentType);
if (encoding == null)
encoding = StringUtil.__ISO_8859_1;
setCharacterEncoding(encoding, EncodingFrom.INFERRED);
}
}
}
Locale locale = getLocale();
if (_writer != null && _writer.isFor(locale, encoding))
_writer.reopen();
else
{
if (StringUtil.__ISO_8859_1.equalsIgnoreCase(encoding))
_writer = new ResponseWriter(new Iso88591HttpWriter(_out), locale, encoding);
else if (StringUtil.__UTF8.equalsIgnoreCase(encoding))
_writer = new ResponseWriter(new Utf8HttpWriter(_out), locale, encoding);
else
_writer = new ResponseWriter(new EncodingHttpWriter(_out, encoding), locale, encoding);
}
// Set the output type at the end, because setCharacterEncoding() checks for it
_outputType = OutputType.WRITER;
}
return _writer;
}
@Override
public void setContentLength(int len)
{
// Protect from setting after committed as default handling
// of a servlet HEAD request ALWAYS sets _content length, even
// if the getHandling committed the response!
if (isCommitted() || !isMutable())
return;
if (len > 0)
{
long written = _out.getWritten();
if (written > len)
throw new IllegalArgumentException("setContentLength(" + len + ") when already written " + written);
_contentLength = len;
_fields.putLongField(HttpHeader.CONTENT_LENGTH, len);
if (isAllContentWritten(written))
{
try
{
closeOutput();
}
catch (IOException e)
{
throw new RuntimeIOException(e);
}
}
}
else if (len == 0)
{
long written = _out.getWritten();
if (written > 0)
throw new IllegalArgumentException("setContentLength(0) when already written " + written);
_contentLength = len;
_fields.put(HttpHeader.CONTENT_LENGTH, "0");
}
else
{
_contentLength = len;
_fields.remove(HttpHeader.CONTENT_LENGTH);
}
}
public long getContentLength()
{
return _contentLength;
}
public boolean isAllContentWritten(long written)
{
return (_contentLength >= 0 && written >= _contentLength);
}
public boolean isContentComplete(long written)
{
return (_contentLength < 0 || written >= _contentLength);
}
public void closeOutput() throws IOException
{
if (_outputType == OutputType.WRITER)
_writer.close();
else
_out.close();
}
public void closeOutput(Callback callback)
{
if (_outputType == OutputType.WRITER)
_writer.close(callback);
else
_out.close(callback);
}
public long getLongContentLength()
{
return _contentLength;
}
public void setLongContentLength(long len)
{
// Protect from setting after committed as default handling
// of a servlet HEAD request ALWAYS sets _content length, even
// if the getHandling committed the response!
if (isCommitted() || !isMutable())
return;
_contentLength = len;
_fields.putLongField(HttpHeader.CONTENT_LENGTH.toString(), len);
}
@Override
public void setContentLengthLong(long length)
{
setLongContentLength(length);
}
@Override
public void setCharacterEncoding(String encoding)
{
setCharacterEncoding(encoding, EncodingFrom.SET_CHARACTER_ENCODING);
}
private void setCharacterEncoding(String encoding, EncodingFrom from)
{
if (!isMutable() || isWriting())
return;
if (_outputType != OutputType.WRITER && !isCommitted())
{
if (encoding == null)
{
_encodingFrom = EncodingFrom.NOT_SET;
// Clear any encoding.
if (_characterEncoding != null)
{
_characterEncoding = null;
if (_mimeType != null)
{
_mimeType = _mimeType.getBaseType();
_contentType = _mimeType.asString();
_fields.put(_mimeType.getContentTypeField());
}
else if (_contentType != null)
{
_contentType = MimeTypes.getContentTypeWithoutCharset(_contentType);
_fields.put(HttpHeader.CONTENT_TYPE, _contentType);
}
}
}
else
{
// No, so just add this one to the mimetype
_encodingFrom = from;
_characterEncoding = HttpGenerator.__STRICT ? encoding : StringUtil.normalizeCharset(encoding);
if (_mimeType != null)
{
_contentType = _mimeType.getBaseType().asString() + ";charset=" + _characterEncoding;
_mimeType = MimeTypes.CACHE.get(_contentType);
if (_mimeType == null || HttpGenerator.__STRICT)
_fields.put(HttpHeader.CONTENT_TYPE, _contentType);
else
_fields.put(_mimeType.getContentTypeField());
}
else if (_contentType != null)
{
_contentType = MimeTypes.getContentTypeWithoutCharset(_contentType) + ";charset=" + _characterEncoding;
_fields.put(HttpHeader.CONTENT_TYPE, _contentType);
}
}
}
}
@Override
public void setContentType(String contentType)
{
if (isCommitted() || !isMutable())
return;
if (contentType == null)
{
if (isWriting() && _characterEncoding != null)
throw new IllegalSelectorException();
if (_locale == null)
_characterEncoding = null;
_mimeType = null;
_contentType = null;
_fields.remove(HttpHeader.CONTENT_TYPE);
}
else
{
_contentType = contentType;
_mimeType = MimeTypes.CACHE.get(contentType);
String charset;
if (_mimeType != null && _mimeType.getCharset() != null && !_mimeType.isCharsetAssumed())
charset = _mimeType.getCharsetString();
else
charset = MimeTypes.getCharsetFromContentType(contentType);
if (charset == null)
{
switch (_encodingFrom)
{
case NOT_SET:
break;
case INFERRED:
case SET_CONTENT_TYPE:
if (isWriting())
{
_mimeType = null;
_contentType = _contentType + ";charset=" + _characterEncoding;
}
else
{
_encodingFrom = EncodingFrom.NOT_SET;
_characterEncoding = null;
}
break;
case SET_LOCALE:
case SET_CHARACTER_ENCODING:
{
_contentType = contentType + ";charset=" + _characterEncoding;
_mimeType = null;
}
}
}
else if (isWriting() && !charset.equalsIgnoreCase(_characterEncoding))
{
// too late to change the character encoding;
_mimeType = null;
_contentType = MimeTypes.getContentTypeWithoutCharset(_contentType);
if (_characterEncoding != null)
_contentType = _contentType + ";charset=" + _characterEncoding;
}
else
{
_characterEncoding = charset;
_encodingFrom = EncodingFrom.SET_CONTENT_TYPE;
}
if (HttpGenerator.__STRICT || _mimeType == null)
_fields.put(HttpHeader.CONTENT_TYPE, _contentType);
else
{
_contentType = _mimeType.asString();
_fields.put(_mimeType.getContentTypeField());
}