forked from jruby/jruby-rack
/
RackRewindableInput.java
256 lines (228 loc) · 8.7 KB
/
RackRewindableInput.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
/*
* Copyright (c) 2010-2011 Engine Yard, Inc.
* Copyright (c) 2007-2009 Sun Microsystems, Inc.
* This source code is available under the MIT license.
* See the file LICENSE.txt for details.
*/
package org.jruby.rack.input;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyString;
import org.jruby.RubyTempfile;
import org.jruby.anno.JRubyMethod;
import org.jruby.rack.RackEnvironment;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.rack.RackInput;
/**
* Suitable env['rack.input'] object for servlet environments, allowing to rewind the
* input per the Rack specification.
* @author nicksieger
*/
public class RackRewindableInput extends RackBaseInput {
private static final ObjectAllocator ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RackRewindableInput(runtime, klass);
}
};
public static RubyClass getRackRewindableInputClass(Ruby runtime) {
return RackBaseInput.getClass(runtime, "RackRewindableInput",
RackBaseInput.getRackBaseInputClass(runtime), ALLOCATOR,
RackRewindableInput.class);
}
public static int getDefaultThreshold() {
return DEFAULT_THRESHOLD;
}
public static void setDefaultThreshold(int thresh) {
DEFAULT_THRESHOLD = thresh;
}
/** 64k is the default cutoff for buffering in memory. */
private static int DEFAULT_THRESHOLD = 64 * 1024;
private int threshold = DEFAULT_THRESHOLD;
public RackRewindableInput(Ruby runtime, RubyClass klass) {
super(runtime, klass);
}
public RackRewindableInput(Ruby runtime, RackEnvironment env) throws IOException {
super(runtime, getRackRewindableInputClass(runtime), env);
}
private class MemoryBufferRackInput implements RackInput {
private ByteBuffer memoryBuffer;
private boolean full;
@SuppressWarnings("empty-statement")
private MemoryBufferRackInput(ReadableByteChannel input) throws IOException {
memoryBuffer = ByteBuffer.allocate(getBufferSize());
while (input.read(memoryBuffer) > 0 && memoryBuffer.hasRemaining());
full = !memoryBuffer.hasRemaining();
memoryBuffer.flip();
}
public IRubyObject gets(ThreadContext context) {
try {
final int NEWLINE = 10;
byte[] bytes = readUntil(NEWLINE, 0);
if (bytes != null) {
return getRuntime().newString(new ByteList(bytes));
} else {
return getRuntime().getNil();
}
} catch (IOException io) {
throw getRuntime().newIOErrorFromException(io);
}
}
public IRubyObject read(ThreadContext context, IRubyObject[] args) {
long count = 0;
if (args.length > 0) {
count = args[0].convertToInteger("to_i").getLongValue();
}
RubyString string = null;
if (args.length == 2) {
string = args[1].convertToString();
}
try {
byte[] bytes = readUntil(Integer.MAX_VALUE, count);
if (bytes != null) {
if (string != null) {
string.clear();
string.cat(bytes);
return string;
}
return getRuntime().newString(new ByteList(bytes));
} else {
if (count > 0) {
return getRuntime().getNil();
} else {
return RubyString.newEmptyString(getRuntime());
}
}
} catch (IOException io) {
throw getRuntime().newIOErrorFromException(io);
}
}
public IRubyObject each(ThreadContext context, Block block) {
IRubyObject nil = getRuntime().getNil();
IRubyObject line = null;
while ((line = gets(context)) != nil) {
block.yield(context, line);
}
return nil;
}
public IRubyObject rewind(ThreadContext context) {
memoryBuffer.rewind();
return getRuntime().getNil();
}
public void close() {
}
private boolean isFull() {
return full;
}
private ByteBuffer getBuffer() {
return memoryBuffer;
}
private byte[] readUntil(int match, long count) throws IOException {
ByteArrayOutputStream bs = null;
byte b;
long i = 0;
do {
if (memoryBuffer.hasRemaining()) {
b = memoryBuffer.get();
} else {
break;
}
if (bs == null) {
bs = new ByteArrayOutputStream();
}
bs.write(b);
if (count > 0 && ++i == count) {
break;
}
} while (b != match);
if (bs == null) {
return null;
}
return bs.toByteArray();
}
}
private class RubyTempfileRackInput extends RubyIORackInput {
private RubyTempfileRackInput(ReadableByteChannel input, ByteBuffer memoryBuffer) {
super(getRuntime(), createTempfile(input, memoryBuffer));
}
@Override
public void close() {
((RubyTempfile) io).close_bang(getRuntime().getCurrentContext());
}
}
/**
* For testing, to allow the input threshold to be set from Ruby.
*/
@JRubyMethod(name = "threshold=", visibility = Visibility.PRIVATE)
public IRubyObject set_threshold(IRubyObject threshold) {
this.threshold = (int) threshold.convertToInteger().getLongValue();
return getRuntime().getNil();
}
protected RackInput getDelegateInput() {
if (delegateInput == null) {
try {
ReadableByteChannel input = Channels.newChannel(inputStream);
if (contentLength > threshold) {
delegateInput = new RubyTempfileRackInput(input, null);
} else {
MemoryBufferRackInput memoryBufferInput = new MemoryBufferRackInput(input);
if (memoryBufferInput.isFull()) {
delegateInput = new RubyTempfileRackInput(input,
memoryBufferInput.getBuffer());
} else {
delegateInput = memoryBufferInput;
}
}
} catch (IOException io) {
throw getRuntime().newIOErrorFromException(io);
}
}
return delegateInput;
}
private RubyTempfile createTempfile(ReadableByteChannel input, ByteBuffer memoryBuffer) {
getRuntime().getLoadService().require("tempfile");
RubyTempfile tempfile = (RubyTempfile) RubyTempfile.open(getRuntime().getCurrentContext(),
getRuntime().getClass("Tempfile"),
new IRubyObject[]{getRuntime().newString("jruby-rack")},
Block.NULL_BLOCK);
try {
FileChannel tempfileChannel = (FileChannel) tempfile.getChannel();
long transferPosition = 0, bytesRead = 0;
if (memoryBuffer != null) {
transferPosition = tempfileChannel.write(memoryBuffer);
}
tempfileChannel.position(0);
while ((bytesRead = tempfileChannel.transferFrom(input, transferPosition, 1024 * 1024)) > 0) {
transferPosition += bytesRead;
}
} catch (IOException io) {
throw getRuntime().newIOErrorFromException(io);
}
return tempfile;
}
/**
* Favor content length over threshold to determine buffer size. In the case
* of content length, set the buffer 1 larger so as to be able to detect
* overflow/incorrect content length issues.
*
* NOTE: It's assumed that content length has already been verified to be
* less than threshold.
*/
private int getBufferSize() {
int bufSize = threshold;
if (contentLength > 0) {
bufSize = contentLength + 1;
}
return bufSize;
}
}