-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpWorker.java
More file actions
297 lines (236 loc) · 6.42 KB
/
Copy pathHttpWorker.java
File metadata and controls
297 lines (236 loc) · 6.42 KB
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
package threadbook.ch13;
import java.io.*;
import java.net.*;
import java.util.*;
import threadbook.ch18.*;
// uses class ObjectFIFO from chapter 18
public class HttpWorker extends Object {
private static int nextWorkerID = 0;
private File docRoot;
private ObjectFIFO idleWorkers;
private int workerID;
private ObjectFIFO handoffBox;
private Thread internalThread;
private volatile boolean noStopRequested;
public HttpWorker(
File docRoot,
int workerPriority,
ObjectFIFO idleWorkers
) {
this.docRoot = docRoot;
this.idleWorkers = idleWorkers;
workerID = getNextWorkerID();
handoffBox = new ObjectFIFO(1); // only one slot
// Just before returning, the thread should be
// created and started.
noStopRequested = true;
Runnable r = new Runnable() {
public void run() {
try {
runWork();
} catch ( Exception x ) {
// in case ANY exception slips through
x.printStackTrace();
}
}
};
internalThread = new Thread(r);
internalThread.setPriority(workerPriority);
internalThread.start();
}
public static synchronized int getNextWorkerID() {
// synchronized at the class level to ensure uniqueness
int id = nextWorkerID;
nextWorkerID++;
return id;
}
public void processRequest(Socket s)
throws InterruptedException {
handoffBox.add(s);
}
private void runWork() {
Socket s = null;
InputStream in = null;
OutputStream out = null;
while ( noStopRequested ) {
try {
// Worker is ready to receive new service
// requests, so it adds itself to the idle
// worker queue.
idleWorkers.add(this);
// Wait here until the server puts a request
// into the handoff box.
s = (Socket) handoffBox.remove();
in = s.getInputStream();
out = s.getOutputStream();
generateResponse(in, out);
out.flush();
} catch ( IOException iox ) {
System.err.println(
"I/O error while processing request, " +
"ignoring and adding back to idle " +
"queue - workerID=" + workerID);
} catch ( InterruptedException x ) {
// re-assert the interrupt
Thread.currentThread().interrupt();
} finally {
// Try to close everything, ignoring
// any IOExceptions that might occur.
if ( in != null ) {
try {
in.close();
} catch ( IOException iox ) {
// ignore
} finally {
in = null;
}
}
if ( out != null ) {
try {
out.close();
} catch ( IOException iox ) {
// ignore
} finally {
out = null;
}
}
if ( s != null ) {
try {
s.close();
} catch ( IOException iox ) {
// ignore
} finally {
s = null;
}
}
}
}
}
private void generateResponse(
InputStream in,
OutputStream out
) throws IOException {
BufferedReader reader =
new BufferedReader(new InputStreamReader(in));
String requestLine = reader.readLine();
if ( ( requestLine == null ) ||
( requestLine.length() < 1 )
) {
throw new IOException("could not read request");
}
System.out.println("workerID=" + workerID +
", requestLine=" + requestLine);
StringTokenizer st = new StringTokenizer(requestLine);
String filename = null;
try {
// request method, typically 'GET', but ignored
st.nextToken();
// the second token should be the filename
filename = st.nextToken();
} catch ( NoSuchElementException x ) {
throw new IOException(
"could not parse request line");
}
File requestedFile = generateFile(filename);
BufferedOutputStream buffOut =
new BufferedOutputStream(out);
if ( requestedFile.exists() ) {
System.out.println("workerID=" + workerID +
", 200 OK: " + filename);
int fileLen = (int) requestedFile.length();
BufferedInputStream fileIn =
new BufferedInputStream(
new FileInputStream(requestedFile));
// Use this utility to make a guess obout the
// content type based on the first few bytes
// in the stream.
String contentType =
URLConnection.guessContentTypeFromStream(
fileIn);
byte[] headerBytes = createHeaderBytes(
"HTTP/1.0 200 OK",
fileLen,
contentType
);
buffOut.write(headerBytes);
byte[] buf = new byte[2048];
int blockLen = 0;
while ( ( blockLen = fileIn.read(buf) ) != -1 ) {
buffOut.write(buf, 0, blockLen);
}
fileIn.close();
} else {
System.out.println("workerID=" + workerID +
", 404 Not Found: " + filename );
byte[] headerBytes = createHeaderBytes(
"HTTP/1.0 404 Not Found",
-1,
null
);
buffOut.write(headerBytes);
}
buffOut.flush();
}
private File generateFile(String filename) {
File requestedFile = docRoot; // start at the base
// Build up the path to the requested file in a
// platform independent way. URL's use '/' in their
// path, but this platform may not.
StringTokenizer st = new StringTokenizer(filename, "/");
while ( st.hasMoreTokens() ) {
String tok = st.nextToken();
if ( tok.equals("..") ) {
// Silently ignore parts of path that might
// lead out of the document root area.
continue;
}
requestedFile =
new File(requestedFile, tok);
}
if ( requestedFile.exists() &&
requestedFile.isDirectory()
) {
// If a directory was requested, modify the request
// to look for the "index.html" file in that
// directory.
requestedFile =
new File(requestedFile, "index.html");
}
return requestedFile;
}
private byte[] createHeaderBytes(
String resp,
int contentLen,
String contentType
) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(baos));
// Write the first line of the response, followed by
// the RFC-specified line termination sequence.
writer.write(resp + "\r\n");
// If a length was specified, add it to the header
if ( contentLen != -1 ) {
writer.write(
"Content-Length: " + contentLen + "\r\n");
}
// If a type was specified, add it to the header
if ( contentType != null ) {
writer.write(
"Content-Type: " + contentType + "\r\n");
}
// A blank line is required after the header.
writer.write("\r\n");
writer.flush();
byte[] data = baos.toByteArray();
writer.close();
return data;
}
public void stopRequest() {
noStopRequested = false;
internalThread.interrupt();
}
public boolean isAlive() {
return internalThread.isAlive();
}
}