My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
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
/*
* Copyright 2008 Google Inc.
*
* 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 com.google.gwt.dev.shell.jetty;

import com.google.gwt.core.ext.ServletContainer;
import com.google.gwt.core.ext.ServletContainerLauncher;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.dev.util.InstalledHelpInfo;

import org.mortbay.component.AbstractLifeCycle;
import org.mortbay.jetty.AbstractConnector;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.RequestLog;
import org.mortbay.jetty.Response;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.HttpFields.Field;
import org.mortbay.jetty.handler.RequestLogHandler;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppClassLoader;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.log.Log;
import org.mortbay.log.Logger;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Iterator;

/**
* A {@link ServletContainerLauncher} for an embedded Jetty server.
*/
public class JettyLauncher extends ServletContainerLauncher {

/**
* Log jetty requests/responses to TreeLogger.
*/
public static class JettyRequestLogger extends AbstractLifeCycle implements
RequestLog {

private final TreeLogger logger;

public JettyRequestLogger(TreeLogger logger) {
this.logger = logger;
}

/**
* Log an HTTP request/response to TreeLogger.
*/
@SuppressWarnings("unchecked")
public void log(Request request, Response response) {
int status = response.getStatus();
if (status < 0) {
// Copied from NCSARequestLog
status = 404;
}
TreeLogger.Type logStatus, logHeaders;
if (status >= 500) {
logStatus = TreeLogger.ERROR;
logHeaders = TreeLogger.INFO;
} else if (status >= 400) {
logStatus = TreeLogger.WARN;
logHeaders = TreeLogger.INFO;
} else {
logStatus = TreeLogger.INFO;
logHeaders = TreeLogger.DEBUG;
}
String userString = request.getRemoteUser();
if (userString == null) {
userString = "";
} else {
userString += "@";
}
String bytesString = "";
if (response.getContentCount() > 0) {
bytesString = " " + response.getContentCount() + " bytes";
}
if (logger.isLoggable(logStatus)) {
TreeLogger branch = logger.branch(logStatus, String.valueOf(status)
+ " - " + request.getMethod() + ' ' + request.getUri() + " ("
+ userString + request.getRemoteHost() + ')' + bytesString);
if (branch.isLoggable(logHeaders)) {
// Request headers
TreeLogger headers = branch.branch(logHeaders, "Request headers");
Iterator<Field> headerFields = request.getConnection().getRequestFields().getFields();
while (headerFields.hasNext()) {
Field headerField = headerFields.next();
headers.log(logHeaders, headerField.getName() + ": "
+ headerField.getValue());
}
// Response headers
headers = branch.branch(logHeaders, "Response headers");
headerFields = response.getHttpFields().getFields();
while (headerFields.hasNext()) {
Field headerField = headerFields.next();
headers.log(logHeaders, headerField.getName() + ": "
+ headerField.getValue());
}
}
}
}
}

/**
* An adapter for the Jetty logging system to GWT's TreeLogger. This
* implementation class is only public to allow {@link Log} to instantiate it.
*
* The weird static data / default construction setup is a game we play with
* {@link Log}'s static initializer to prevent the initial log message from
* going to stderr.
*/
public static class JettyTreeLogger implements Logger {
private final TreeLogger logger;

public JettyTreeLogger(TreeLogger logger) {
if (logger == null) {
throw new NullPointerException();
}
this.logger = logger;
}

public void debug(String msg, Object arg0, Object arg1) {
logger.log(TreeLogger.SPAM, format(msg, arg0, arg1));
}

public void debug(String msg, Throwable th) {
logger.log(TreeLogger.SPAM, msg, th);
}

public Logger getLogger(String name) {
return this;
}

public void info(String msg, Object arg0, Object arg1) {
logger.log(TreeLogger.INFO, format(msg, arg0, arg1));
}

public boolean isDebugEnabled() {
return logger.isLoggable(TreeLogger.SPAM);
}

public void setDebugEnabled(boolean enabled) {
// ignored
}

public void warn(String msg, Object arg0, Object arg1) {
logger.log(TreeLogger.WARN, format(msg, arg0, arg1));
}

public void warn(String msg, Throwable th) {
logger.log(TreeLogger.WARN, msg, th);
}

/**
* Copied from org.mortbay.log.StdErrLog.
*/
private String format(String msg, Object arg0, Object arg1) {
int i0 = msg.indexOf("{}");
int i1 = i0 < 0 ? -1 : msg.indexOf("{}", i0 + 2);

if (arg1 != null && i1 >= 0) {
msg = msg.substring(0, i1) + arg1 + msg.substring(i1 + 2);
}
if (arg0 != null && i0 >= 0) {
msg = msg.substring(0, i0) + arg0 + msg.substring(i0 + 2);
}
return msg;
}
}

/**
* The resulting {@link ServletContainer} this is launched.
*/
protected static class JettyServletContainer extends ServletContainer {
private final int actualPort;
private final File appRootDir;
private final TreeLogger logger;
private final Server server;
private final WebAppContext wac;

public JettyServletContainer(TreeLogger logger, Server server,
WebAppContext wac, int actualPort, File appRootDir) {
this.logger = logger;
this.server = server;
this.wac = wac;
this.actualPort = actualPort;
this.appRootDir = appRootDir;
}

public int getPort() {
return actualPort;
}

public void refresh() throws UnableToCompleteException {
String msg = "Reloading web app to reflect changes in "
+ appRootDir.getAbsolutePath();
TreeLogger branch = logger.branch(TreeLogger.INFO, msg);
// Temporarily log Jetty on the branch.
Log.setLog(new JettyTreeLogger(branch));
try {
wac.stop();
wac.start();
branch.log(TreeLogger.INFO, "Reload completed successfully");
} catch (Exception e) {
branch.log(TreeLogger.ERROR, "Unable to restart embedded Jetty server",
e);
throw new UnableToCompleteException();
} finally {
// Reset the top-level logger.
Log.setLog(new JettyTreeLogger(logger));
}
}

public void stop() throws UnableToCompleteException {
TreeLogger branch = logger.branch(TreeLogger.INFO,
"Stopping Jetty server");
// Temporarily log Jetty on the branch.
Log.setLog(new JettyTreeLogger(branch));
try {
server.stop();
server.setStopAtShutdown(false);
branch.log(TreeLogger.INFO, "Stopped successfully");
} catch (Exception e) {
branch.log(TreeLogger.ERROR, "Unable to stop embedded Jetty server", e);
throw new UnableToCompleteException();
} finally {
// Reset the top-level logger.
Log.setLog(new JettyTreeLogger(logger));
}
}
}

/**
* A {@link WebAppContext} tailored to GWT hosted mode. Features hot-reload
* with a new {@link WebAppClassLoader} to pick up disk changes. The default
* Jetty {@code WebAppContext} will create new instances of servlets, but it
* will not create a brand new {@link ClassLoader}. By creating a new {@code
* ClassLoader} each time, we re-read updated classes from disk.
*
* Also provides special class filtering to isolate the web app from the GWT
* hosting environment.
*/
protected final class WebAppContextWithReload extends WebAppContext {

/**
* Specialized {@link WebAppClassLoader} that allows outside resources to be
* brought in dynamically from the system path. A warning is issued when
* this occurs.
*/
private class WebAppClassLoaderExtension extends WebAppClassLoader {

private static final String META_INF_SERVICES = "META-INF/services/";

public WebAppClassLoaderExtension() throws IOException {
super(bootStrapOnlyClassLoader, WebAppContextWithReload.this);
}

@Override
public URL findResource(String name) {
// Specifically for META-INF/services/javax.xml.parsers.SAXParserFactory
String checkName = name;
if (checkName.startsWith(META_INF_SERVICES)) {
checkName = checkName.substring(META_INF_SERVICES.length());
}

// For a system path, load from the outside world.
URL found;
if (isSystemPath(checkName)) {
found = systemClassLoader.getResource(name);
if (found != null) {
return found;
}
}

// Always check this ClassLoader first.
found = super.findResource(name);
if (found != null) {
return found;
}

// See if the outside world has it.
found = systemClassLoader.getResource(name);
if (found == null) {
return null;
}

// Warn, add containing URL to our own ClassLoader, and retry the call.
String warnMessage = "Server resource '"
+ name
+ "' could not be found in the web app, but was found on the system classpath";
if (!addContainingClassPathEntry(warnMessage, found, name)) {
return null;
}
return super.findResource(name);
}

/**
* Override to additionally consider the most commonly available JSP and
* XML implementation as system resources. (In fact, Jasper is in gwt-dev
* via embedded Tomcat, so we always hit this case.)
*/
@Override
public boolean isSystemPath(String name) {
name = name.replace('/', '.');
return super.isSystemPath(name)
|| name.startsWith("org.apache.jasper.")
|| name.startsWith("org.apache.xerces.");
}

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
// For system path, always prefer the outside world.
if (isSystemPath(name)) {
try {
return systemClassLoader.loadClass(name);
} catch (ClassNotFoundException e) {
}
}

try {
return super.findClass(name);
} catch (ClassNotFoundException e) {
// Don't allow server classes to be loaded from the outside.
if (isServerPath(name)) {
throw e;
}
}

// See if the outside world has a URL for it.
String resourceName = name.replace('.', '/') + ".class";
URL found = systemClassLoader.getResource(resourceName);
if (found == null) {
return null;
}

// Warn, add containing URL to our own ClassLoader, and retry the call.
String warnMessage = "Server class '"
+ name
+ "' could not be found in the web app, but was found on the system classpath";
if (!addContainingClassPathEntry(warnMessage, found, resourceName)) {
throw new ClassNotFoundException(name);
}
return super.findClass(name);
}

private boolean addContainingClassPathEntry(String warnMessage,
URL resource, String resourceName) {
TreeLogger.Type logLevel = (System.getProperty(PROPERTY_NOWARN_WEBAPP_CLASSPATH) == null)
? TreeLogger.WARN : TreeLogger.DEBUG;
TreeLogger branch = logger.branch(logLevel, warnMessage);
String classPathURL;
String foundStr = resource.toExternalForm();
if (resource.getProtocol().equals("file")) {
assert foundStr.endsWith(resourceName);
classPathURL = foundStr.substring(0, foundStr.length()
- resourceName.length());
} else if (resource.getProtocol().equals("jar")) {
assert foundStr.startsWith("jar:");
assert foundStr.endsWith("!/" + resourceName);
classPathURL = foundStr.substring(4, foundStr.length()
- (2 + resourceName.length()));
} else {
branch.log(TreeLogger.ERROR,
"Found resouce but unrecognized URL format: '" + foundStr + '\'');
return false;
}
branch = branch.branch(logLevel, "Adding classpath entry '"
+ classPathURL + "' to the web app classpath for this session",
null, new InstalledHelpInfo("webAppClassPath.html"));
try {
addClassPath(classPathURL);
return true;
} catch (IOException e) {
branch.log(TreeLogger.ERROR, "Failed add container URL: '"
+ classPathURL + '\'', e);
return false;
}
}
}

/**
* Parent ClassLoader for the Jetty web app, which can only load JVM
* classes. We would just use <code>null</code> for the parent ClassLoader
* except this makes Jetty unhappy.
*/
private final ClassLoader bootStrapOnlyClassLoader = new ClassLoader(null) {
};

private final TreeLogger logger;

/**
* In the usual case of launching {@link com.google.gwt.dev.HostedMode},
* this will always by the system app ClassLoader.
*/
private final ClassLoader systemClassLoader = Thread.currentThread().getContextClassLoader();

@SuppressWarnings("unchecked")
private WebAppContextWithReload(TreeLogger logger, String webApp,
String contextPath) {
super(webApp, contextPath);
this.logger = logger;

// Prevent file locking on Windows; pick up file changes.
getInitParams().put(
"org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false");

// Since the parent class loader is bootstrap-only, prefer it first.
setParentLoaderPriority(true);
}

@Override
protected void doStart() throws Exception {
setClassLoader(new WebAppClassLoaderExtension());
super.doStart();
}

@Override
protected void doStop() throws Exception {
super.doStop();
setClassLoader(null);
}
}

/**
* System property to suppress warnings about loading web app classes from the
* system classpath.
*/
private static final String PROPERTY_NOWARN_WEBAPP_CLASSPATH = "gwt.nowarn.webapp.classpath";

static {
// Suppress spammy Jetty log initialization.
System.setProperty("org.mortbay.log.class", JettyNullLogger.class.getName());
Log.getLog();

/*
* Make JDT the default Ant compiler so that JSP compilation just works
* out-of-the-box. If we don't set this, it's very, very difficult to make
* JSP compilation work.
*/
String antJavaC = System.getProperty("build.compiler",
"org.eclipse.jdt.core.JDTCompilerAdapter");
System.setProperty("build.compiler", antJavaC);
}

public ServletContainer start(TreeLogger logger, int port, File appRootDir)
throws Exception {
TreeLogger branch = logger.branch(TreeLogger.INFO,
"Starting Jetty on port " + port, null);

checkStartParams(branch, port, appRootDir);

// Setup our branch logger during startup.
Log.setLog(new JettyTreeLogger(branch));

// Turn off XML validation.
System.setProperty("org.mortbay.xml.XmlParser.Validating", "false");

AbstractConnector connector = getConnector();
connector.setPort(port);

// Don't share ports with an existing process.
connector.setReuseAddress(false);

// Linux keeps the port blocked after shutdown if we don't disable this.
connector.setSoLingerTime(0);

Server server = new Server();
server.addConnector(connector);

// Create a new web app in the war directory.
WebAppContext wac = new WebAppContextWithReload(logger,
appRootDir.getAbsolutePath(), "/");

RequestLogHandler logHandler = new RequestLogHandler();
logHandler.setRequestLog(new JettyRequestLogger(logger));
logHandler.setHandler(wac);
server.setHandler(logHandler);
server.start();
server.setStopAtShutdown(true);

// Now that we're started, log to the top level logger.
Log.setLog(new JettyTreeLogger(logger));

return new JettyServletContainer(logger, server, wac,
connector.getLocalPort(), appRootDir);
}

protected AbstractConnector getConnector() {
return new SelectChannelConnector();
}

private void checkStartParams(TreeLogger logger, int port, File appRootDir) {
if (logger == null) {
throw new NullPointerException("logger cannot be null");
}

if (port < 0 || port > 65535) {
throw new IllegalArgumentException(
"port must be either 0 (for auto) or less than 65536");
}

if (appRootDir == null) {
throw new NullPointerException("app root direcotry cannot be null");
}
}

}

Change log

r5411 by j...@google.com on May 18, 2009   Diff
Merging c5194 from trunk into
releases/1.6.
Go to: 
Project members, sign in to write a code review

Older revisions

r5109 by sco...@google.com on Mar 30, 2009   Diff
Make JDT Ant's default compiler.  This
makes JSPs work out of the box.

Review by: tobyr
r5078 by sco...@google.com on Mar 25, 2009   Diff
Amending r5077:
- Catch ClassNotFound in outside
loader and allow internal load
- Allow "system" resources to be
loaded internally if they're not found
...
r5077 by sco...@google.com on Mar 25, 2009   Diff
Ensure that system classes are always
loaded from the external classloader
and never copied into the
WebAppClassLoader.

...
All revisions of this file

File info

Size: 17686 bytes, 520 lines

File properties

svn:mime-type
text/x-java
svn:eol-style
native
Powered by Google Project Hosting