-
Notifications
You must be signed in to change notification settings - Fork 35
/
GSPResponseWriter.java
265 lines (236 loc) · 10.1 KB
/
GSPResponseWriter.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
/*
* Copyright 2004-2005 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 org.grails.web.pages;
import com.opensymphony.module.sitemesh.RequestConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.grails.buffer.StreamCharBuffer;
import org.grails.buffer.StreamCharBuffer.LazyInitializingWriter;
import org.grails.buffer.StreamCharBuffer.StreamCharBufferWriter;
import org.grails.encoder.EncodedAppender;
import org.grails.encoder.EncodedAppenderFactory;
import org.grails.encoder.Encoder;
import org.grails.encoder.EncoderAware;
import org.grails.web.servlet.mvc.GrailsWebRequest;
import org.grails.web.sitemesh.GrailsContentBufferingResponse;
import org.grails.web.sitemesh.GrailsRoutablePrintWriter;
import org.grails.web.util.BoundedCharsAsEncodedBytesCounter;
import org.springframework.objenesis.ObjenesisStd;
import org.springframework.objenesis.instantiator.ObjectInstantiator;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.Writer;
/**
* NOTE: Based on work done by on the GSP standalone project (https://gsp.dev.java.net/)
* A buffered writer that won't commit the response until the buffer has reached the high watermark, or until flush() or close() is called.
* Performance optimizations by Lari Hotari, 13.03.2009
* Calculating the Content-Length has been disabled by default since Jetty ignores it (uses Chunked mode anyways).
* Content-Length mode can be enabled with -DGSPResponseWriter.enableContentLength=true system property.
*
* @author Troy Heninger
* @author Graeme Rocher
* @author Lari Hotari, Sagire Software Oy
*
* Date: Jan 10, 2004
*/
public class GSPResponseWriter extends GrailsRoutablePrintWriter implements EncoderAware, EncodedAppenderFactory {
protected static final Log LOG = LogFactory.getLog(GSPResponseWriter.class);
private ServletResponse response;
private BoundedCharsAsEncodedBytesCounter bytesCounter;
public static final boolean CONTENT_LENGTH_COUNTING_ENABLED = Boolean.getBoolean("GSPResponseWriter.enableContentLength");
public static final boolean BUFFERING_ENABLED = Boolean.valueOf(System.getProperty("GSPResponseWriter.enableBuffering", "true"));
public static final boolean AUTOFLUSH_ENABLED = Boolean.getBoolean("GSPResponseWriter.enableAutoFlush");
private static final int BUFFER_SIZE = Integer.getInteger("GSPResponseWriter.bufferSize", 8042);
private Encoder encoder;
private StreamCharBuffer buffer;
private static ObjectInstantiator<GSPResponseWriter> instantiator = null;
static {
try {
instantiator = new ObjenesisStd(false).getInstantiatorOf(GSPResponseWriter.class);
} catch (Exception e) {
LOG.debug("Couldn't get direct performance optimized instantiator for GSPResponseWriter. Using default instantiation.", e);
}
}
public static GSPResponseWriter getInstance(final ServletResponse response) {
return getInstance(response, BUFFER_SIZE);
}
/**
* Static factory methdirectWritingod to create the writer.
*
* @param response The {@link ServletResponse}
* @param max The chunkSize
* @return A {@link GSPResponseWriter} instance
*/
private static GSPResponseWriter getInstance(final ServletResponse response, final int max) {
final BoundedCharsAsEncodedBytesCounter bytesCounter = new BoundedCharsAsEncodedBytesCounter();
final StreamCharBuffer streamBuffer = new StreamCharBuffer(max, 0, max);
streamBuffer.setChunkMinSize(max / 2);
streamBuffer.setNotifyParentBuffersEnabled(false);
final StreamCharBuffer.LazyInitializingWriter lazyResponseWriter = response::getWriter;
if (!(response instanceof GrailsContentBufferingResponse)) {
streamBuffer.connectTo(new StreamCharBuffer.LazyInitializingMultipleWriter() {
public Writer getWriter() {
return null;
}
public LazyInitializingWriter[] initializeMultiple(StreamCharBuffer buffer, boolean autoFlush) {
final StreamCharBuffer.LazyInitializingWriter[] lazyWriters;
if (CONTENT_LENGTH_COUNTING_ENABLED) {
lazyWriters = new StreamCharBuffer.LazyInitializingWriter[]{() -> {
bytesCounter.setCapacity(max * 2);
bytesCounter.setEncoding(response.getCharacterEncoding());
return bytesCounter.getCountingWriter();
}, lazyResponseWriter};
} else {
lazyWriters = new StreamCharBuffer.LazyInitializingWriter[]{lazyResponseWriter};
}
return lazyWriters;
}
}, AUTOFLUSH_ENABLED);
} else {
streamBuffer.connectTo(lazyResponseWriter);
}
if (instantiator != null) {
GSPResponseWriter instance = instantiator.newInstance();
instance.initialize(streamBuffer, response, bytesCounter);
return instance;
} else {
return new GSPResponseWriter(streamBuffer, response, bytesCounter);
}
}
/**
* Static factory method to create the writer.
* <p>
* TODO: this can be removed?
*
* @param target The target writer to write too
* @param max The chunkSize
* @return A {@link GSPResponseWriter} instance
*/
@SuppressWarnings("unused")
private static GSPResponseWriter getInstance(Writer target, int max) {
if (BUFFERING_ENABLED && !(target instanceof GrailsRoutablePrintWriter) && !(target instanceof StreamCharBufferWriter)) {
StreamCharBuffer streamBuffer = new StreamCharBuffer(max, 0, max);
streamBuffer.connectTo(target, false);
target = streamBuffer.getWriter();
}
if (instantiator == null) {
return new GSPResponseWriter(target);
}
GSPResponseWriter instance = instantiator.newInstance();
instance.initialize(target);
return instance;
}
/**
* Private constructor. Use getInstance() instead.
*
* @param buffer buffered writer
* @param response The servlet response
* @param bytesCounter Keeps count of encoded bytes count
*/
private GSPResponseWriter(final StreamCharBuffer buffer, final ServletResponse response, BoundedCharsAsEncodedBytesCounter bytesCounter) {
super(null);
initialize(buffer, response, bytesCounter);
}
void initialize(final StreamCharBuffer buffer, final ServletResponse response,
BoundedCharsAsEncodedBytesCounter bytesCounter) {
DestinationFactory lazyTargetFactory = () -> {
final GrailsWebRequest webRequest = GrailsWebRequest.lookup();
encoder = webRequest != null ? webRequest.lookupFilteringEncoder() : null;
if (encoder != null) {
return buffer.getWriterForEncoder(encoder, webRequest.getEncodingStateRegistry());
}
return buffer.getWriter();
};
updateDestination(lazyTargetFactory);
this.response = response;
this.bytesCounter = bytesCounter;
setBlockClose(true);
setBlockFlush(false);
}
/**
* Private constructor. Use getInstance() instead.
*
* @param activeWriter buffered writer
*/
private GSPResponseWriter(final Writer activeWriter) {
super(null);
initialize(activeWriter);
}
void initialize(final Writer activeWriter) {
updateDestination(() -> activeWriter);
setBlockClose(true);
setBlockFlush(false);
}
/**
* Close the stream.
*
* @see #checkError()
*/
@Override
public void close() {
flush();
if (canFlushContentLengthAwareResponse()) {
int size = bytesCounter.size();
if (size > 0) {
response.setContentLength(size);
}
flushResponse();
} else if (!isTrouble()) {
GrailsWebRequest webRequest = GrailsWebRequest.lookup();
if (webRequest != null && webRequest.getCurrentRequest().getAttribute(RequestConstants.PAGE) != null) {
// flush the response if its a layout
flushResponse();
}
}
}
private boolean canFlushContentLengthAwareResponse() {
return CONTENT_LENGTH_COUNTING_ENABLED && isDestinationActivated() && bytesCounter != null && bytesCounter.isWriterReferenced() && response != null && !response.isCommitted() && !isTrouble();
}
private void flushResponse() {
try {
if (isDestinationActivated()) {
response.getWriter().flush();
}
} catch (IOException e) {
handleIOException(e);
}
}
@Override
public boolean isAllowUnwrappingOut() {
return false;
}
@Override
public Writer unwrap() {
return this;
}
public EncodedAppender getEncodedAppender() {
if (buffer != null) {
return ((EncodedAppenderFactory) buffer.getWriter()).getEncodedAppender();
}
activateDestination();
try (Writer target = getTarget().unwrap()) {
if (target != this && target instanceof EncodedAppenderFactory) {
return ((EncodedAppenderFactory) target).getEncodedAppender();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
public Encoder getEncoder() {
return encoder;
}
}