1
22
23 package com.liferay.portal.servlet.filters.strip;
24
25 import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream;
26 import com.liferay.portal.kernel.servlet.StringServletOutputStream;
27 import com.liferay.portal.kernel.util.StringPool;
28
29 import java.io.IOException;
30 import java.io.OutputStreamWriter;
31 import java.io.PrintWriter;
32
33 import javax.servlet.ServletOutputStream;
34 import javax.servlet.http.HttpServletResponse;
35 import javax.servlet.http.HttpServletResponseWrapper;
36
37
42 public class StripResponse extends HttpServletResponseWrapper {
43
44 public StripResponse(HttpServletResponse response) {
45 super(response);
46 }
47
48 public void finishResponse() {
49 try {
50 if (_printWriter != null) {
51 _printWriter.close();
52 }
53 else if (_servletOutputStream != null) {
54 _servletOutputStream.close();
55 }
56 }
57 catch (IOException ioe) {
58 }
59 }
60
61 public void flushBuffer() throws IOException {
62 if (_servletOutputStream != null) {
63 _servletOutputStream.flush();
64 }
65 }
66
67 public String getContentType() {
68 return _contentType;
69 }
70
71 public byte[] getData() {
72 finishResponse();
73
74 if (_unsyncByteArrayOutputStream != null) {
75 return _unsyncByteArrayOutputStream.toByteArray();
76 }
77
78 return null;
79 }
80
81 public ServletOutputStream getOutputStream() {
82 if (_printWriter != null) {
83 throw new IllegalStateException();
84 }
85
86 if (_servletOutputStream == null) {
87 _servletOutputStream = createOutputStream();
88 }
89
90 return _servletOutputStream;
91 }
92
93 public PrintWriter getWriter() throws IOException {
94 if (_printWriter != null) {
95 return _printWriter;
96 }
97
98 if (_servletOutputStream != null) {
99 throw new IllegalStateException();
100 }
101
102 _servletOutputStream = createOutputStream();
103
104 _printWriter = new PrintWriter(
105 new OutputStreamWriter(_servletOutputStream, StringPool.UTF8));
106
107 return _printWriter;
108 }
109
110 public boolean isCommitted() {
111 if (_servletOutputStream != null) {
112 return true;
113 }
114 else {
115 return super.isCommitted();
116 }
117 }
118
119 public void setContentType(String contentType) {
120 _contentType = contentType;
121
122 super.setContentType(contentType);
123 }
124
125 protected ServletOutputStream createOutputStream() {
126 _unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();
127
128 return new StringServletOutputStream(_unsyncByteArrayOutputStream);
129 }
130
131 private String _contentType;
132 private PrintWriter _printWriter;
133 private ServletOutputStream _servletOutputStream;
134 private UnsyncByteArrayOutputStream _unsyncByteArrayOutputStream;
135
136 }