/
Response.java
1219 lines (1049 loc) · 33.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) 2014-present the original author or authors.
*
* Licensed 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 ro.pippo.core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ro.pippo.core.gzip.GZipResponseWrapper;
import ro.pippo.core.route.RouteContext;
import ro.pippo.core.route.RouteDispatcher;
import ro.pippo.core.util.DateUtils;
import ro.pippo.core.util.IoUtils;
import ro.pippo.core.util.MimeTypes;
import ro.pippo.core.util.StringUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author Decebal Suiu
*/
public final class Response {
private static final Logger log = LoggerFactory.getLogger(Response.class);
private HttpServletResponse httpServletResponse;
private ContentTypeEngines contentTypeEngines;
private TemplateEngine templateEngine;
private Map<String, Object> locals;
private Map<String, String> headers;
private Map<String, Cookie> cookies;
private String contextPath;
private String applicationPath;
private ResponseFinalizeListenerList finalizeListeners;
private MimeTypes mimeTypes;
private int status;
private boolean chunked;
public Response(HttpServletResponse httpServletResponse, Application application) {
this.httpServletResponse = httpServletResponse;
this.contentTypeEngines = application.getContentTypeEngines();
this.templateEngine = application.getTemplateEngine();
this.httpServletResponse.setCharacterEncoding(StandardCharsets.UTF_8.toString());
this.contextPath = application.getRouter().getContextPath();
this.applicationPath = StringUtils.removeEnd(application.getRouter().getApplicationPath(), "/");
this.mimeTypes = application.getMimeTypes();
this.status = 0;
}
/**
* Map of bound objects which can be stored and shared between all handlers
* for the current request/response cycle.
* <p>
* All bound objects are made available to the template engine during parsing.
* </p>
*
* @return the bound objects map
*/
public Map<String, Object> getLocals() {
if (locals == null) {
locals = new HashMap<>();
}
return locals;
}
/**
* Shortcut for <code>getLocals().get("flash")</code>.
* @return
*/
public Flash getFlash() {
return (Flash) getLocals().get("flash");
}
/**
* Binds an object to the response.
*
* @param name
* @param model
* @return the response
*/
public Response bind(String name, Object model) {
getLocals().put(name, model);
return this;
}
/**
* Returns the servlet response.
*
* @return the servlet response
*/
public HttpServletResponse getHttpServletResponse() {
return httpServletResponse;
}
/**
* Gets the character encoding of the response.
*
* @return the character encoding
*/
public String getCharacterEncoding() {
return getHttpServletResponse().getCharacterEncoding();
}
/**
* Sets the character encoding of the response.
*
* @param charset
* @return the response
*/
public Response characterEncoding(String charset) {
checkCommitted();
getHttpServletResponse().setCharacterEncoding(charset);
return this;
}
private void addCookie(Cookie cookie) {
checkCommitted();
if (StringUtils.isNullOrEmpty(cookie.getPath())) {
cookie.setPath(StringUtils.addStart(contextPath, "/"));
}
getCookieMap().put(cookie.getName(), cookie);
}
/**
* Adds a cookie to the response.
*
* @param cookie
* @return the response
*/
public Response cookie(Cookie cookie) {
addCookie(cookie);
return this;
}
/**
* Adds a cookie to the response.
*
* @param name
* @param value
* @return the response
*/
public Response cookie(String name, String value) {
Cookie cookie = new Cookie(name, value);
cookie.setSecure(true);
addCookie(cookie);
return this;
}
/**
* Adds a cookie to the response.
*
* @param name
* @param value
* @param maxAge
* @return the response
*/
public Response cookie(String name, String value, int maxAge) {
Cookie cookie = new Cookie(name, value);
cookie.setSecure(true);
cookie.setMaxAge(maxAge);
addCookie(cookie);
return this;
}
/**
* Adds a cookie to the response.
*
* @param path
* @param domain
* @param name
* @param value
* @param maxAge
* @param secure
* @return the response
*/
public Response cookie(String path, String domain, String name, String value, int maxAge, boolean secure) {
Cookie cookie = new Cookie(name, value);
cookie.setPath(path);
cookie.setDomain(domain);
cookie.setMaxAge(maxAge);
cookie.setSecure(secure);
addCookie(cookie);
return this;
}
/**
* Returns all cookies added to the response.
*
* @return the cookies added to the response
*/
public Collection<Cookie> getCookies() {
return getCookieMap().values();
}
/**
* Gets the specified cookie by name.
*
* @param name
* @return the cookie or null
*/
public Cookie getCookie(String name) {
return getCookieMap().get(name);
}
/**
* Removes the specified cookie by name.
*
* @param name
* @return the response
*/
public Response removeCookie(String name) {
Cookie cookie = new Cookie(name, "");
cookie.setSecure(true);
cookie.setMaxAge(0);
addCookie(cookie);
return this;
}
private Map<String, Cookie> getCookieMap() {
if (cookies == null) {
cookies = new HashMap<>();
}
return cookies;
}
private boolean isHeaderEmpty(String name) {
return StringUtils.isNullOrEmpty(getHeaderMap().get(name));
}
/**
* Sets a header.
*
* @param name
* @param value
* @return the response
*/
public Response header(String name, String value) {
checkCommitted();
getHeaderMap().put(name, value);
return this;
}
/**
* Sets a header.
*
* @param name
* @param value
* @return the response
*/
public Response header(String name, Date value) {
checkCommitted();
getHeaderMap().put(name, DateUtils.formatForHttpHeader(value));
return this;
}
/**
* Sets a filename header. It's a shortcut for {@code header(HttpConstants.Header.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")}.
*
* @param filename
* @return
*/
public Response filenameHeader(String filename) {
if (filename != null && !filename.isEmpty()) {
header(HttpConstants.Header.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"");
} else {
header(HttpConstants.Header.CONTENT_DISPOSITION, "attachment; filename=\"\"");
}
return this;
}
/**
* Returns a header value, if set in the Response.
*
* @param name
* @return the header value or null
*/
public String getHeader(String name) {
return getHeaderMap().get(name);
}
private Map<String, String> getHeaderMap() {
if (headers == null) {
headers = new HashMap<>();
}
return headers;
}
/**
* Sets this response as not cacheable.
*
* @return the response
*/
public Response noCache() {
checkCommitted();
// no-cache headers for HTTP/1.1
header(HttpConstants.Header.CACHE_CONTROL, "no-store, no-cache, must-revalidate");
// no-cache headers for HTTP/1.1 (IE)
header(HttpConstants.Header.CACHE_CONTROL, "post-check=0, pre-check=0");
// no-cache headers for HTTP/1.0
header(HttpConstants.Header.PRAGMA, "no-cache");
// set the expires to past
httpServletResponse.setDateHeader("Expires", 0);
return this;
}
/**
* Gets the status code of the response.
*
* @return the status code
*/
public int getStatus() {
return status;
}
/**
* Sets the status code of the response.
*
* @param status
* @return the response
*/
public Response status(int status) {
checkCommitted();
httpServletResponse.setStatus(status);
this.status = status;
return this;
}
/**
* Sets the chunked transfer encoding.
*
* @return the response
*/
public Response chunked() {
return chunked(true);
}
/**
* Controls the chunked transfer encoding.
*
* @param chunked
* @return the response
*/
public Response chunked(boolean chunked) {
checkCommitted();
this.chunked = chunked;
return this;
}
/**
* Redirect the browser to a location which may be...
* <ul>
* <li>relative to the current request
* <li>relative to the servlet container root (if location starts with '/')
* <li>an absolute url
* </ul>
* If you want a context-relative redirect, use the
* {@link ro.pippo.core.Response#redirectToContextPath(String)} method.
* If you want an application-relative redirect, use the
* {@link ro.pippo.core.Response#redirectToApplicationPath(String)} method.
* <p>This method commits the response.</p>
*
* @param location
* Where to redirect
*/
public void redirect(String location) {
checkCommitted();
finalizeResponse();
try {
httpServletResponse.sendRedirect(location);
} catch (IOException e) {
throw new PippoRuntimeException(e);
}
}
/**
* Redirects the browser to a path relative to the application context. For
* example, redirectToContextPath("/contacts") might redirect the browser to
* http://localhost/myContext/contacts
* <p>This method commits the response.</p>
*
* @param path
*/
public void redirectToContextPath(String path) {
if ("".equals(contextPath)) {
// context path is the root
redirect(path);
} else {
redirect(contextPath + StringUtils.addStart(path, "/"));
}
}
/**
* Redirects the browser to a path relative to the Pippo application root. For
* example, redirectToApplicationPath("/contacts") might redirect the browser to
* http://localhost/myContext/myApp/contacts
* <p>This method commits the response.</p>
*
* @param path
*/
public void redirectToApplicationPath(String path) {
if ("".equals(applicationPath)) {
// application path is the root
redirect(path);
} else {
redirect(applicationPath + StringUtils.addStart(path, "/"));
}
}
/**
* A permanent (3XX status code) redirect.
* <p>This method commits the response.</p>
*
* @param location
* @param statusCode
*/
public void redirect(String location, int statusCode) {
checkCommitted();
finalizeResponse();
status(statusCode);
header(HttpConstants.Header.LOCATION, location);
header(HttpConstants.Header.CONNECTION, "close");
try {
httpServletResponse.sendError(statusCode);
} catch (IOException e) {
throw new PippoRuntimeException(e);
}
}
/**
* Set the response status to OK (200).
* <p>
* Standard response for successful HTTP requests. The actual response will
* depend on the request method used. In a GET request, the response will
* contain an entity corresponding to the requested resource. In a POST
* request the response will contain an entity describing or containing the
* result of the action.
* </p>
*
*/
public Response ok() {
status(HttpConstants.StatusCode.OK);
return this;
}
/**
* Set the response status to CREATED (201).
* <p>
* The request has been fulfilled and resulted in a new resource being created.
* </p>
*
*/
public Response created() {
status(HttpConstants.StatusCode.CREATED);
return this;
}
/**
* Set the response status to ACCEPTED (202).
* <p>
* The request has been accepted for processing, but the processing has not
* been completed. The request might or might not eventually be acted upon,
* as it might be disallowed when processing actually takes place.
* </p>
*
*/
public Response accepted() {
status(HttpConstants.StatusCode.ACCEPTED);
return this;
}
/**
* Set the response status to BAD REQUEST (400).
* <p>
* The server cannot or will not process the request due to something that
* is perceived to be a client error.
* </p>
*
*/
public Response badRequest() {
status(HttpConstants.StatusCode.BAD_REQUEST);
return this;
}
/**
* Set the response status to UNAUTHORIZED (401).
* <p>
* Similar to 403 Forbidden, but specifically for use when authentication is
* required and has failed or has not yet been provided. The response must
* include a WWW-Authenticate header field containing a challenge applicable
* to the requested resource.
* </p>
*/
public Response unauthorized() {
status(HttpConstants.StatusCode.UNAUTHORIZED);
return this;
}
/**
* Set the response status to PAYMENT REQUIRED (402).
* <p>
* Reserved for future use. The original intention was that this code might
* be used as part of some form of digital cash or micropayment scheme, but
* that has not happened, and this code is not usually used.
* </p>
*/
public Response paymentRequired() {
status(HttpConstants.StatusCode.PAYMENT_REQUIRED);
return this;
}
/**
* Set the response status to FORBIDDEN (403).
* <p>
* The request was a valid request, but the server is refusing to respond to
* it. Unlike a 401 Unauthorized response, authenticating will make no
* difference.
* </p>
*
*/
public Response forbidden() {
status(HttpConstants.StatusCode.FORBIDDEN);
return this;
}
/**
* Set the response status to NOT FOUND (404).
* <p>
* The requested resource could not be found but may be available again in
* the future. Subsequent requests by the client are permissible.
* </p>
*
*/
public Response notFound() {
status(HttpConstants.StatusCode.NOT_FOUND);
return this;
}
/**
* Set the response status to METHOD NOT ALLOWED (405).
* <p>
* A request was made of a resource using a request method not supported
* by that resource; for example, using GET on a form which requires data
* to be presented via POST, or using PUT on a read-only resource.
* </p>
*
*/
public Response methodNotAllowed() {
status(HttpConstants.StatusCode.METHOD_NOT_ALLOWED);
return this;
}
/**
* Set the response status to CONFLICT (409).
* <p>
* Indicates that the request could not be processed because of conflict in
* the request, such as an edit conflict in the case of multiple updates.
* </p>
*
*/
public Response conflict() {
status(HttpConstants.StatusCode.CONFLICT);
return this;
}
/**
* Set the response status to GONE (410).
* <p>
* Indicates that the resource requested is no longer available and will not
* be available again. This should be used when a resource has been
* intentionally removed and the resource should be purged. Upon receiving a
* 410 status code, the client should not request the resource again in the
* future.
* </p>
*
*/
public Response gone() {
status(HttpConstants.StatusCode.GONE);
return this;
}
/**
* Set the response status to INTERNAL ERROR (500).
* <p>
* A generic error message, given when an unexpected condition was
* encountered and no more specific message is suitable.
* </p>
*
*/
public Response internalError() {
status(HttpConstants.StatusCode.INTERNAL_ERROR);
return this;
}
/**
* Set the response status to NOT IMPLEMENTED (501).
* <p>
* The server either does not recognize the request method, or it lacks the
* ability to fulfil the request. Usually this implies future availability
* (e.g., a new feature of a web-service API).
* </p>
*
*/
public Response notImplemented() {
status(HttpConstants.StatusCode.NOT_IMPLEMENTED);
return this;
}
/**
* Set the response status to OVERLOADED (502).
* <p>
* The server is currently unavailable (because it is overloaded or down
* for maintenance). Generally, this is a temporary state.
* </p>
*/
public Response overloaded() {
status(HttpConstants.StatusCode.OVERLOADED);
return this;
}
/**
* Set the response status to SERVICE UNAVAILABLE (503).
* <p>
* The server is currently unavailable (because it is overloaded or down
* for maintenance). Generally, this is a temporary state.
* </p>
*/
public Response serviceUnavailable() {
status(HttpConstants.StatusCode.SERVICE_UNAVAILABLE);
return this;
}
/**
* Sets the content length of the response.
*
* @param length
* @return the response
*/
public Response contentLength(long length) {
checkCommitted();
httpServletResponse.setContentLength((int) length);
return this;
}
/**
* Returns the content type of the response.
*
* @return the content type
*/
public String getContentType() {
String contentType = getHeader(HttpConstants.Header.CONTENT_TYPE);
if (contentType == null) {
contentType = httpServletResponse.getContentType();
}
return contentType;
}
/**
* Sets the content type of the response.
*
* @param contentType
* @return the response
*/
public Response contentType(String contentType) {
checkCommitted();
header(HttpConstants.Header.CONTENT_TYPE, contentType);
httpServletResponse.setContentType(contentType);
return this;
}
/**
* Attempts to set the Content-Type of the Response based on Request
* headers.
* <p>
* The Accept header is preferred for negotiation but the Content-Type
* header may also be used if an agreeable engine can not be determined.
* </p>
* <p>
* If no Content-Type can not be negotiated then the response will not be
* modified. This behavior allows specification of a default Content-Type
* using one of the methods such as <code>xml()</code> or <code>json()</code>.
* <p>
* For example, <code>response.xml().contentType(request).send(myObject);</code>
* would set the default Content-Type as <code>application/xml</code> and
* then attempt to negotiate the client's preferred type. If negotiation failed,
* then the default <code>application/xml</code> would be sent and used to
* serialize the outgoing object.
*
* @param request
* @return the response
*/
public Response contentType(Request request) {
// prefer the Accept header
if ("*/*".equals(request.getAcceptType())) {
// client accepts all types
return this;
}
ContentTypeEngine engine = contentTypeEngines.getContentTypeEngine(request.getAcceptType());
if (engine != null) {
log.debug("Negotiated '{}' from request Accept header", engine.getContentType());
} else if (!StringUtils.isNullOrEmpty(request.getContentType())) {
// try to match the Request content-type
engine = contentTypeEngines.getContentTypeEngine(request.getContentType());
if (engine != null) {
log.debug("Negotiated '{}' from request Content-Type header", engine.getContentType());
}
}
if (engine == null) {
log.debug("Failed to negotiate a content type for Accept='{}' and Content-Type='{}'",
request.getAcceptType(), request.getContentType());
return this;
}
return contentType(engine.getContentType());
}
/**
* Sets the Response content-type to text/plain.
*/
public Response text() {
return contentType(HttpConstants.ContentType.TEXT_PLAIN);
}
/**
* Sets the Response content-type to text/html.
*/
public Response html() {
return contentType(HttpConstants.ContentType.TEXT_HTML);
}
/**
* Sets the Response content-type to application/json.
*/
public Response json() {
return contentType(HttpConstants.ContentType.APPLICATION_JSON);
}
/**
* Sets the Response content-type to application/xml.
*/
public Response xml() {
return contentType(HttpConstants.ContentType.APPLICATION_XML);
}
/**
* Sets the Response content-type to application/x-yaml.
*/
public Response yaml() {
return contentType(HttpConstants.ContentType.APPLICATION_X_YAML);
}
/**
* Writes the string content directly to the response.
* <p>This method commits the response.</p>
*
* @param content
*/
public void send(CharSequence content) {
checkCommitted();
commit(content);
}
/**
* Replaces '{}' in the format string with the supplied arguments and
* writes the string content directly to the response.
* <p>This method commits the response.</p>
*
* @param format
* @param args
*/
public void send(String format, Object... args) {
checkCommitted();
commit(StringUtils.format(format, args));
}
/**
* Serializes the object as JSON using the registered <code>application/json</code>
* ContentTypeEngine and writes it to the response.
* <p>This method commits the response.</p>
*
* @param object
*/
public void json(Object object) {
send(object, HttpConstants.ContentType.APPLICATION_JSON);
}
/**
* Serializes the object as XML using the registered <code>application/xml</code>
* ContentTypeEngine and writes it to the response.
* <p>This method commits the response.</p>
*
* @param object
*/
public void xml(Object object) {
send(object, HttpConstants.ContentType.APPLICATION_XML);
}
/**
* Serializes the object as YAML using the registered <code>application/x-yaml</code>
* ContentTypeEngine and writes it to the response.
* <p>This method commits the response.</p>
*
* @param object
*/
public void yaml(Object object) {
send(object, HttpConstants.ContentType.APPLICATION_X_YAML);
}
/**
* Serializes the object as plain text using the registered <code>text/plain</code>
* ContentTypeEngine and writes it to the response.
* <p>This method commits the response.</p>
*
* @param object
*/
public void text(Object object) {
send(object, HttpConstants.ContentType.TEXT_PLAIN);
}
/**
* Serializes the object using the registered ContentTypeEngine matching
* the pre-specified content-type.
* <p>This method commits the response.</p>
*
* @param object
*/
public void send(Object object) {
if (object instanceof File) {
file((File) object);
} else {
send(object, getContentType());
}
}
private void send(Object object, String contentType) {
if (StringUtils.isNullOrEmpty(contentType)) {
throw new PippoRuntimeException("You must specify a content type!");
}
ContentTypeEngine contentTypeEngine = contentTypeEngines.getContentTypeEngine(contentType);
if (contentTypeEngine == null) {
throw new PippoRuntimeException("You must set a content type engine for '{}'", contentType);
}
header(HttpConstants.Header.CONTENT_TYPE, contentTypeEngine.getContentType());
send(contentTypeEngine.toString(object));
}
/**
* Copies the input stream to the response output stream and closes the input stream upon completion.
* <p>This method commits the response.</p>
*
* @param input
*/
public void resource(InputStream input) {
checkCommitted();
finalizeResponse();
// content type to OCTET_STREAM if it's not set
if (getContentType() == null) {
contentType(HttpConstants.ContentType.APPLICATION_OCTET_STREAM);
}
try {
send(input);
} catch (IOException e) {
throw new PippoRuntimeException(e);
}
}
/**
* Writes the specified file directly to the response.
* <p>This method commits the response.</p>
*
* @param file
*/
public void file(File file) {
try {
contentLength(file.length());
file(file.getName(), new FileInputStream(file));
} catch (FileNotFoundException e) {
throw new PippoRuntimeException(e);
}
}
/**
* Copies the input stream to the response output stream as a download and closes the input stream upon completion.
* <p>This method commits the response.</p>
*
* @param filename
* @param input
*/
public void file(String filename, InputStream input) {
checkCommitted();
// content type to OCTET_STREAM if it's not set
if (getContentType() == null) {
contentType(mimeTypes.getContentType(filename, HttpConstants.ContentType.APPLICATION_OCTET_STREAM));
}
if (isHeaderEmpty(HttpConstants.Header.CONTENT_DISPOSITION)) {
filenameHeader(filename);
}
finalizeResponse();
try {
send(input);
} catch (IOException e) {
throw new PippoRuntimeException(e);
}
}
private void send(InputStream input) throws IOException {
try {
// by calling httpServletResponse.getOutputStream() we are committing the response
IoUtils.copy(input, httpServletResponse.getOutputStream());
if (chunked) {
// flushing the buffer forces chunked-encoding
httpServletResponse.flushBuffer();
}
} finally {