summaryrefslogtreecommitdiffstats
path: root/src/com/itmill/toolkit/terminal/web/ApplicationServlet.java
blob: 6aa8753fc9deae380ab2790f6ce627fb86b8d4c5 (plain)
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
/* *************************************************************************
 
 IT Mill Toolkit 

 Development of Browser User Interfaces Made Easy

 Copyright (C) 2000-2006 IT Mill Ltd
 
 *************************************************************************

 This product is distributed under commercial license that can be found
 from the product package on license.pdf. Use of this product might 
 require purchasing a commercial license from IT Mill Ltd. For guidelines 
 on usage, see licensing-guidelines.html

 *************************************************************************
 
 For more information, contact:
 
 IT Mill Ltd                           phone: +358 2 4802 7180
 Ruukinkatu 2-4                        fax:   +358 2 4802 7181
 20540, Turku                          email:  info@itmill.com
 Finland                               company www: www.itmill.com
 
 Primary source for information and releases: www.itmill.com

 ********************************************************************** */

package com.itmill.toolkit.terminal.web;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.WeakHashMap;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import org.xml.sax.SAXException;

import com.itmill.toolkit.Application;
import com.itmill.toolkit.Application.WindowAttachEvent;
import com.itmill.toolkit.Application.WindowDetachEvent;
import com.itmill.toolkit.service.FileTypeResolver;
import com.itmill.toolkit.service.License;
import com.itmill.toolkit.service.License.InvalidLicenseFile;
import com.itmill.toolkit.service.License.LicenseFileHasAlreadyBeenRead;
import com.itmill.toolkit.service.License.LicenseFileHasNotBeenRead;
import com.itmill.toolkit.service.License.LicenseSignatureIsInvalid;
import com.itmill.toolkit.service.License.LicenseViolation;
import com.itmill.toolkit.terminal.DownloadStream;
import com.itmill.toolkit.terminal.Paintable;
import com.itmill.toolkit.terminal.ParameterHandler;
import com.itmill.toolkit.terminal.ThemeResource;
import com.itmill.toolkit.terminal.URIHandler;
import com.itmill.toolkit.terminal.Paintable.RepaintRequestEvent;
import com.itmill.toolkit.terminal.web.ThemeSource.ThemeException;
import com.itmill.toolkit.terminal.web.WebBrowser;
import com.itmill.toolkit.ui.Window;

/**
 * This servlet connects IT Mill Toolkit Application to Web. This servlet
 * replaces both WebAdapterServlet and AjaxAdapterServlet.
 * 
 * @author IT Mill Ltd.
 * @version
 * @VERSION@
 * @since 4.0
 */

public class ApplicationServlet extends HttpServlet implements
		Application.WindowAttachListener, Application.WindowDetachListener,
		Paintable.RepaintRequestListener {

	private static final long serialVersionUID = -4937882979845826574L;

	/**
	 * Version number of this release. For example "4.0.0".
	 */
	public static final String VERSION;

	/**
	 * Major version number. For example 4 in 4.1.0.
	 */
	public static final int VERSION_MAJOR;

	/**
	 * Minor version number. For example 1 in 4.1.0.
	 */
	public static final int VERSION_MINOR;

	/**
	 * Builds number. For example 0-beta1 in 4.0.0-beta1.
	 */
	public static final String VERSION_BUILD;

	/* Initialize version numbers from string replaced by build-script. */
	static {
		if ("@VERSION@".equals("@" + "VERSION" + "@"))
			VERSION = "4.0.0-INTERNAL-NONVERSIONED-DEBUG-BUILD";
		else
			VERSION = "@VERSION@";
		String[] digits = VERSION.split("\\.");
		VERSION_MAJOR = Integer.parseInt(digits[0]);
		VERSION_MINOR = Integer.parseInt(digits[1]);
		VERSION_BUILD = digits[2];
	}

	// Configurable parameter names
	private static final String PARAMETER_DEBUG = "Debug";

	private static final String PARAMETER_DEFAULT_THEME_JAR = "DefaultThemeJar";

	private static final String PARAMETER_THEMESOURCE = "ThemeSource";

	private static final String PARAMETER_THEME_CACHETIME = "ThemeCacheTime";

	private static final String PARAMETER_MAX_TRANSFORMERS = "MaxTransformers";

	private static final String PARAMETER_TRANSFORMER_CACHETIME = "TransformerCacheTime";

	private static final int DEFAULT_THEME_CACHETIME = 1000 * 60 * 60 * 24;

	private static final int DEFAULT_BUFFER_SIZE = 32 * 1024;

	private static final int DEFAULT_MAX_TRANSFORMERS = 1;

	private static final int MAX_BUFFER_SIZE = 64 * 1024;

	// TODO: these should be moved to session object and stored directly into
	// session
	private static final String SESSION_ATTR_VARMAP = "itmill-toolkit-varmap";

	private static final String SESSION_ATTR_CONTEXT = "itmill-toolkit-context";

	protected static final String SESSION_ATTR_APPS = "itmill-toolkit-apps";

	private static final String SESSION_BINDING_LISTENER = "itmill-toolkit-bindinglistener";

	private WeakHashMap applicationToDirtyWindowSetMap = new WeakHashMap();

	private WeakHashMap applicationToServerCommandStreamLock = new WeakHashMap();

	private static WeakHashMap applicationToLastRequestDate = new WeakHashMap();

	private static WeakHashMap applicationToAjaxAppMgrMap = new WeakHashMap();

	private WeakHashMap licenseForApplicationClass = new WeakHashMap();

	private static WeakHashMap licensePrintedForApplicationClass = new WeakHashMap();

	// TODO Should default or base theme be the default?
	protected static final String DEFAULT_THEME = "base";

	private static final String RESOURCE_URI = "/RES/";

	private static final String AJAX_UIDL_URI = "/UIDL/";

	private static final String THEME_DIRECTORY_PATH = "/WEB-INF/lib/themes/";

	private static final String THEME_LISTING_FILE = THEME_DIRECTORY_PATH
			+ "themes.txt";

	private static final String DEFAULT_THEME_JAR_PREFIX = "itmill-toolkit-themes";

	private static final String DEFAULT_THEME_JAR = "/WEB-INF/lib/"
			+ DEFAULT_THEME_JAR_PREFIX + "-" + VERSION + ".jar";

	private static final String DEFAULT_THEME_TEMP_FILE_PREFIX = "ITMILL_TMP_";

	private static final String SERVER_COMMAND_PARAM = "SERVER_COMMANDS";

	private static final int SERVER_COMMAND_STREAM_MAINTAIN_PERIOD = 15000;

	private static final int SERVER_COMMAND_HEADER_PADDING = 2000;

	// Maximum delay between request for an user to be considered active (in ms)
	private static final long ACTIVE_USER_REQUEST_INTERVAL = 1000 * 45;

	// Private fields
	private Class applicationClass;

	private Properties applicationProperties;

	private UIDLTransformerFactory transformerFactory;

	private CollectionThemeSource themeSource;

	private String resourcePath = null;

	private String debugMode = "";

	private int maxConcurrentTransformers;

	private long transformerCacheTime;

	private long themeCacheTime;

	/**
	 * Called by the servlet container to indicate to a servlet that the servlet
	 * is being placed into service.
	 * 
	 * @param servletConfig
	 *            the object containing the servlet's configuration and
	 *            initialization parameters
	 * @throws javax.servlet.ServletException
	 *             if an exception has occurred that interferes with the
	 *             servlet's normal operation.
	 */
	public void init(javax.servlet.ServletConfig servletConfig)
			throws javax.servlet.ServletException {
		super.init(servletConfig);

		// Gets the application class name
		String applicationClassName = servletConfig
				.getInitParameter("application");
		if (applicationClassName == null) {
			Log.error("Application not specified in servlet parameters");
		}

		// Stores the application parameters into Properties object
		this.applicationProperties = new Properties();
		for (Enumeration e = servletConfig.getInitParameterNames(); e
				.hasMoreElements();) {
			String name = (String) e.nextElement();
			this.applicationProperties.setProperty(name, servletConfig
					.getInitParameter(name));
		}

		// Overrides with server.xml parameters
		ServletContext context = servletConfig.getServletContext();
		for (Enumeration e = context.getInitParameterNames(); e
				.hasMoreElements();) {
			String name = (String) e.nextElement();
			this.applicationProperties.setProperty(name, context
					.getInitParameter(name));
		}

		// Gets the debug window parameter
		String debug = getApplicationOrSystemProperty(PARAMETER_DEBUG, "")
				.toLowerCase();

		// Enables application specific debug
		if (!"".equals(debug) && !"true".equals(debug)
				&& !"false".equals(debug))
			throw new ServletException(
					"If debug parameter is given for an application, it must be 'true' or 'false'");
		this.debugMode = debug;

		// Gets the maximum number of simultaneous transformers
		this.maxConcurrentTransformers = Integer
				.parseInt(getApplicationOrSystemProperty(
						PARAMETER_MAX_TRANSFORMERS, "-1"));
		if (this.maxConcurrentTransformers < 1)
			this.maxConcurrentTransformers = DEFAULT_MAX_TRANSFORMERS;

		// Gets cache time for transformers
		this.transformerCacheTime = Integer
				.parseInt(getApplicationOrSystemProperty(

				PARAMETER_TRANSFORMER_CACHETIME, "-1")) * 1000;

		// Gets cache time for theme resources
		this.themeCacheTime = Integer.parseInt(getApplicationOrSystemProperty(
				PARAMETER_THEME_CACHETIME, "-1")) * 1000;
		if (this.themeCacheTime < 0) {
			this.themeCacheTime = DEFAULT_THEME_CACHETIME;
		}

		// Adds all specified theme sources
		this.themeSource = new CollectionThemeSource();
		List directorySources = getThemeSources();
		for (Iterator i = directorySources.iterator(); i.hasNext();) {
			this.themeSource.add((ThemeSource) i.next());
		}

		// Adds the default theme source
		String[] defaultThemeFiles = new String[] { getApplicationOrSystemProperty(
				PARAMETER_DEFAULT_THEME_JAR, DEFAULT_THEME_JAR) };
		File f = findDefaultThemeJar(defaultThemeFiles);
		boolean defaultThemeFound = false;
		try {
			// Adds themes.jar if exists
			if (f != null && f.exists()) {
				this.themeSource.add(new JarThemeSource(f, this, ""));
				defaultThemeFound = true;
			}
		} catch (Exception e) {
			throw new ServletException("Failed to load default theme from "
					+ Arrays.asList(defaultThemeFiles), e);
		}

		// Checks that at least one themesource was loaded
		if (this.themeSource.getThemes().size() <= 0) {
			throw new ServletException(
					"No themes found in specified themesources. "
							+ Theme.MESSAGE_CONFIGURE_HELP);
		}

		// Warn if default theme not found
		if (this.themeSource.getThemeByName(DEFAULT_THEME) == null) {
			if (!defaultThemeFound)
				Log.warn("Default theme JAR not found in: "
						+ Arrays.asList(defaultThemeFiles));
		}

		// Initializes the transformer factory, if not initialized
		if (this.transformerFactory == null) {
			this.transformerFactory = new UIDLTransformerFactory(
					this.themeSource, this, this.maxConcurrentTransformers,
					this.transformerCacheTime);
		}

		// Loads the application class using the same class loader
		// as the servlet itself
		ClassLoader loader = this.getClass().getClassLoader();
		try {
			this.applicationClass = loader.loadClass(applicationClassName);
		} catch (ClassNotFoundException e) {
			throw new ServletException("Failed to load application class: "
					+ applicationClassName);
		}
	}

	/**
	 * Gets an application or system property value.
	 * 
	 * @param parameterName
	 *            the Name or the parameter.
	 * @param defaultValue
	 *            the Default to be used.
	 * @return String value or default if not found
	 */
	private String getApplicationOrSystemProperty(String parameterName,
			String defaultValue) {

		// Try application properties
		String val = this.applicationProperties.getProperty(parameterName);
		if (val != null) {
			return val;
		}

		// Try lowercased application properties for backward compability with
		// 3.0.2 and earlier
		val = this.applicationProperties.getProperty(parameterName
				.toLowerCase());
		if (val != null) {
			return val;
		}

		// Try system properties
		String pkgName;
		Package pkg = this.getClass().getPackage();
		if (pkg != null) {
			pkgName = pkg.getName();
		} else {
			String className = this.getClass().getName();
			pkgName = new String(className.toCharArray(), 0, className
					.lastIndexOf('.'));
		}
		val = System.getProperty(pkgName + "." + parameterName);
		if (val != null) {
			return val;
		}

		// Try lowercased system properties
		val = System.getProperty(pkgName + "." + parameterName.toLowerCase());
		if (val != null) {
			return val;
		}

		return defaultValue;
	}

	/**
	 * Gets ThemeSources from given path. Construct the list of avalable themes
	 * in path using the following sources:
	 * <p>
	 * 1. Content of <code>THEME_PATH</code> directory (if available).
	 * </p>
	 * <p>
	 * 2. The themes listed in <code>THEME_LIST_FILE</code>.
	 * </p>
	 * <p>
	 * 3. "themesource" application parameter - "ThemeSource" system property.
	 * </p>
	 * 
	 * @return the List
	 * @throws ServletException
	 *             if an exception has occurred that interferes with the
	 *             servlet's normal operation.
	 */
	private List getThemeSources() throws ServletException {

		List returnValue = new LinkedList();

		// Check the list file in theme directory
		List sourcePaths = new LinkedList();
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					this.getServletContext().getResourceAsStream(
							THEME_LISTING_FILE)));
			String line = null;
			while ((line = reader.readLine()) != null) {
				sourcePaths.add(THEME_DIRECTORY_PATH + line.trim());
			}
			if (this.isDebugMode(null)) {
				Log.debug("Listed " + sourcePaths.size() + " themes in "
						+ THEME_LISTING_FILE + ". Loading " + sourcePaths);
			}
		} catch (Exception ignored) {
			// If the file reading fails, just skip to next method
		}

		// If no file was found or it was empty,
		// try to add themes filesystem directory if it is accessible
		if (sourcePaths.size() <= 0) {
			if (this.isDebugMode(null)) {
				Log.debug("No themes listed in " + THEME_LISTING_FILE
						+ ". Trying to read the content of directory "
						+ THEME_DIRECTORY_PATH);
			}

			try {
				String path = getResourcePath(getServletContext(),
						THEME_DIRECTORY_PATH);
				if (path != null) {
					File f = new File(path);
					if (f != null && f.exists())
						returnValue.add(new DirectoryThemeSource(f, this));
				}
			} catch (java.io.IOException je) {
				Log.info("Theme directory " + THEME_DIRECTORY_PATH
						+ " not available. Skipped.");
			} catch (ThemeException e) {
				throw new ServletException("Failed to load themes from "
						+ THEME_DIRECTORY_PATH, e);
			}
		}

		// Adds the theme sources from application properties
		String paramValue = getApplicationOrSystemProperty(
				PARAMETER_THEMESOURCE, null);
		if (paramValue != null) {
			StringTokenizer st = new StringTokenizer(paramValue, ";");
			while (st.hasMoreTokens()) {
				sourcePaths.add(st.nextToken());
			}
		}

		// Constructs appropriate theme source instances for each path
		for (Iterator i = sourcePaths.iterator(); i.hasNext();) {
			String source = (String) i.next();
			File sourceFile = new File(source);
			try {

				// Relative files are treated as streams (to support
				// resource inside WAR files)
				if (!sourceFile.isAbsolute()) {
					returnValue.add(new ServletThemeSource(this
							.getServletContext(), this, source));
				} else if (sourceFile.isDirectory()) {

					// Absolute directories are read from filesystem
					returnValue.add(new DirectoryThemeSource(sourceFile, this));
				} else {

					// Absolute JAR-files are read from filesystem
					returnValue.add(new JarThemeSource(sourceFile, this, ""));
				}
			} catch (Exception e) {
				// Any exception breaks the the init
				throw new ServletException("Invalid theme source: " + source, e);
			}
		}

		// Returns the constructed list of theme sources
		return returnValue;
	}

	/**
	 * Receives standard HTTP requests from the public service method and
	 * dispatches them.
	 * 
	 * @param request
	 *            the object that contains the request the client made of the
	 *            servlet.
	 * @param response
	 *            the object that contains the response the servlet returns to
	 *            the client.
	 * @throws ServletException
	 *             if an input or output error occurs while the servlet is
	 *             handling the TRACE request.
	 * @throws IOException
	 *             if the request for the TRACE cannot be handled.
	 */
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// Transformer and output stream for the result
		UIDLTransformer transformer = null;
		HttpVariableMap variableMap = null;
		OutputStream out = response.getOutputStream();
		HashMap currentlyDirtyWindowsForThisApplication = new HashMap();
		Application application = null;
		try {

			// Handles resource requests
			if (handleResourceRequest(request, response))
				return;

			// Handles server commands
			if (handleServerCommands(request, response))
				return;

			// Gets the application
			application = getApplication(request);

			// Creates application if it doesn't exist
			if (application == null)
				application = createApplication(request);

			// Sets the last application request date
			applicationToLastRequestDate.put(application, new Date());

			// Invokes context transaction listeners
			((WebApplicationContext) application.getContext())
					.startTransaction(application, request);

			// Is this a download request from application
			DownloadStream download = null;

			// The rest of the process is synchronized with the application
			// in order to guarantee that no parallel variable handling is
			// made
			synchronized (application) {

				// Handles AJAX UIDL requests
				String resourceId = request.getPathInfo();
				if (resourceId != null && resourceId.startsWith(AJAX_UIDL_URI)) {
					getApplicationManager(application).handleUidlRequest(
							request, response, themeSource);
					return;
				}

				// Gets the variable map
				variableMap = getVariableMap(application, request);
				if (variableMap == null)
					return;

				// Change all variables based on request parameters
				Map unhandledParameters = variableMap.handleVariables(request,
						application);

				// Check/handle client side feature checks
				WebBrowserProbe
						.handleProbeRequest(request, unhandledParameters);

				// If rendering mode is not defined or detecting requested
				// try to detect it
				WebBrowser wb = WebBrowserProbe.getTerminalType(request
						.getSession());

				boolean detect = false;
				if (unhandledParameters.get("renderingMode") != null) {
					detect = ((String) ((Object[]) unhandledParameters
							.get("renderingMode"))[0]).equals("detect");
				}
				if (detect
						|| wb.getRenderingMode() == WebBrowser.RENDERING_MODE_UNDEFINED) {
					String themeName = application.getTheme();
					if (themeName == null)
						themeName = DEFAULT_THEME;
					if (unhandledParameters.get("theme") != null) {
						themeName = (String) ((Object[]) unhandledParameters
								.get("theme"))[0];
					}

					Theme theme = themeSource.getThemeByName(themeName);
					if (theme == null)
						throw new ServletException(
								"Failed to load theme with name " + themeName
										+ ". " + Theme.MESSAGE_CONFIGURE_HELP);

					String renderingMode = theme.getPreferredMode(wb,
							themeSource);
					if (Theme.MODE_AJAX.equals(renderingMode)) {
						wb.setRenderingMode(WebBrowser.RENDERING_MODE_AJAX);
					} else {
						wb.setRenderingMode(WebBrowser.RENDERING_MODE_HTML);
					}
				}
				if (unhandledParameters.get("renderingMode") != null) {
					String renderingMode = (String) ((Object[]) unhandledParameters
							.get("renderingMode"))[0];
					if (renderingMode.equals("html")) {
						wb.setRenderingMode(WebBrowser.RENDERING_MODE_HTML);
					} else if (renderingMode.equals("ajax")) {
						wb.setRenderingMode(WebBrowser.RENDERING_MODE_AJAX);
					}
				}

				// Handles the URI if the application is still running
				if (application.isRunning())
					download = handleURI(application, request, response);

				// If this is not a download request
				if (download == null) {

					// Window renders are not cacheable
					response.setHeader("Cache-Control", "no-cache");
					response.setHeader("Pragma", "no-cache");
					response.setDateHeader("Expires", 0);

					// Finds the window within the application
					Window window = null;
					if (application.isRunning())
						window = getApplicationWindow(request, application,
								unhandledParameters);

					// Handles the unhandled parameters if the application is
					// still running
					if (window != null && unhandledParameters != null
							&& !unhandledParameters.isEmpty()) {
						try {
							window.handleParameters(unhandledParameters);
						} catch (Throwable t) {
							application
									.terminalError(new ParameterHandlerErrorImpl(
											window, t));
						}
					}

					// Removes application if it has stopped
					if (!application.isRunning()) {
						endApplication(request, response, application);
						return;
					}

					// Returns blank page, if no window found
					if (window == null) {
						response.setContentType("text/html");
						BufferedWriter page = new BufferedWriter(
								new OutputStreamWriter(out));
						page.write("<html><head><script>");
						page
								.write(ThemeFunctionLibrary
										.generateWindowScript(
												null,
												application,
												this,
												WebBrowserProbe
														.getTerminalType(request
																.getSession())));
						page.write("</script></head><body>");
						page
								.write("The requested window has been removed from application.");
						page.write("</body></html>");
						page.close();

						return;
					}

					// Sets terminal type for the window, if not already set
					if (window.getTerminal() == null) {
						window.setTerminal(wb);
					}

					// Finds theme
					String themeName = window.getTheme() != null ? window
							.getTheme() : DEFAULT_THEME;
					if (unhandledParameters.get("theme") != null) {
						themeName = (String) ((Object[]) unhandledParameters
								.get("theme"))[0];
					}
					Theme theme = themeSource.getThemeByName(themeName);
					if (theme == null)
						throw new ServletException("Theme (named '" + themeName
								+ "') can not be found");

					// If in ajax rendering mode, print an html page for it
					if (wb.getRenderingMode() == WebBrowser.RENDERING_MODE_AJAX) {
						writeAjaxPage(request, response, out,
								unhandledParameters, window, wb, theme);
						return;
					}

					// If other than html or ajax mode is requested
					if (wb.getRenderingMode() == WebBrowser.RENDERING_MODE_UNDEFINED
							&& !(window instanceof DebugWindow)) {
						// TODO More informal message should be given is browser
						// is not supported
						response.setContentType("text/html");
						BufferedWriter page = new BufferedWriter(
								new OutputStreamWriter(out));
						page.write("<html><head></head><body>");
						page.write("Unsupported browser.");
						page.write("</body></html>");
						page.close();

						return;
					}

					// Initialize Transformer
					UIDLTransformerType transformerType = new UIDLTransformerType(
							wb, theme);

					transformer = this.transformerFactory
							.getTransformer(transformerType);

					// Sets the response type
					response.setContentType(wb.getContentType());

					// Creates UIDL writer
					WebPaintTarget paintTarget = transformer
							.getPaintTarget(variableMap);

					// Assures that the correspoding debug window will be
					// repainted property
					// by clearing it before the actual paint.
					DebugWindow debugWindow = (DebugWindow) application
							.getWindow(DebugWindow.WINDOW_NAME);
					if (debugWindow != null && debugWindow != window) {
						debugWindow.setWindowUIDL(window, "Painting...");
					}

					// Paints window
					window.paint(paintTarget);
					paintTarget.close();

					// For exception handling, memorize the current dirty status
					WeakHashMap dirtyWindows = (WeakHashMap) applicationToDirtyWindowSetMap
							.get(application);

					if (dirtyWindows == null) {
						dirtyWindows = new WeakHashMap();
						applicationToDirtyWindowSetMap.put(application,
								dirtyWindows);
					}
					currentlyDirtyWindowsForThisApplication
							.putAll((Map) dirtyWindows);

					// Window is now painted
					windowPainted(application, window);

					// Debug
					if (debugWindow != null && debugWindow != window) {
						debugWindow
								.setWindowUIDL(window, paintTarget.getUIDL());
					}

					// Sets the function library state for this thread
					ThemeFunctionLibrary.setState(application, window,
							transformerType.getWebBrowser(), request
									.getSession(), this, transformerType
									.getTheme().getName());

				}
			}

			// For normal requests, transform the window
			if (download == null) {

				// Transform and output the result to browser
				// Note that the transform and transfer of the result is
				// not synchronized with the variable map. This allows
				// parallel transfers and transforms for better performance,
				// but requires that all calls from the XSL to java are
				// thread-safe
				transformer.transform(out);
			}

			// For download request, transfer the downloaded data
			else {

				handleDownload(download, request, response);
			}

		} catch (UIDLTransformerException te) {
			// Print stacktrace
			te.printStackTrace();

			try {
				// Writes the error report to client
				response.setContentType("text/html");
				BufferedWriter err = new BufferedWriter(new OutputStreamWriter(
						out));
				err
						.write("<html><head><title>Application Internal Error</title></head><body>");
				err.write("<h1>" + te.getMessage() + "</h1>");
				err.write(te.getHTMLDescription());
				err.write("</body></html>");
				err.close();
			} catch (Throwable t) {
				Log.except("Failed to write error page: " + t
						+ ". Original exception was: ", te);
			}

			// Adds previously dirty windows to dirtyWindowList in order
			// to make sure that eventually they are repainted
			Application currentApplication = getApplication(request);
			for (Iterator iter = currentlyDirtyWindowsForThisApplication
					.keySet().iterator(); iter.hasNext();) {
				Window dirtyWindow = (Window) iter.next();
				addDirtyWindow(currentApplication, dirtyWindow);
			}

		} catch (Throwable e) {
			// Print stacktrace
			e.printStackTrace();
			// Re-throw other exceptions
			throw new ServletException(e);
		} finally {

			// Releases transformer
			if (transformer != null)
				transformerFactory.releaseTransformer(transformer);

			// Notifies transaction end
			if (application != null)
				((WebApplicationContext) application.getContext())
						.endTransaction(application, request);

			// Cleans the function library state for this thread
			// for security reasons
			ThemeFunctionLibrary.cleanState();
		}
	}

	/**
	 * 
	 * @param request
	 *            the HTTP request.
	 * @param response
	 *            the HTTP response to write to.
	 * @param out
	 * @param unhandledParameters
	 * @param window
	 * @param terminalType
	 * @param theme
	 * @throws IOException
	 *             if the writing failed due to input/output error.
	 * @throws MalformedURLException
	 *             if the application is denied access the persistent data store
	 *             represented by the given URL.
	 */
	private void writeAjaxPage(HttpServletRequest request,
			HttpServletResponse response, OutputStream out,
			Map unhandledParameters, Window window, WebBrowser terminalType,
			Theme theme) throws IOException, MalformedURLException {
		response.setContentType("text/html");
		BufferedWriter page = new BufferedWriter(new OutputStreamWriter(out));

		page
				.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
						+ "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");

		page
				.write("<html><head>\n<title>" + window.getCaption()
						+ "</title>\n");
		page
				.write("<NOSCRIPT><META http-equiv=\"refresh\" content=\"0; url=?WA_NOSCRIPT=1\" /></NOSCRIPT>\n");
		Theme t = theme;
		Vector themes = new Vector();
		themes.add(t);
		while (t.getParent() != null) {
			String parentName = t.getParent();
			t = themeSource.getThemeByName(parentName);
			themes.add(t);
		}
		for (int k = themes.size() - 1; k >= 0; k--) {
			t = (Theme) themes.get(k);
			Collection files = t.getFileNames(terminalType, Theme.MODE_AJAX);
			for (Iterator i = files.iterator(); i.hasNext();) {
				String file = (String) i.next();
				if (file.endsWith(".css"))
					page.write("<link rel=\"stylesheet\" href=\""
							+ getResourceLocation(t.getName(),
									new ThemeResource(file))
							+ "\" type=\"text/css\" />\n");
				else if (file.endsWith(".js")) {
					page.write("<script src=\"");

					// TODO remove this and implement behaviour in themes
					// description.xml files
					if (file.endsWith("firebug.js")
							&& !isDebugMode(unhandledParameters)) {
						file = file.replaceFirst("bug.js", "bugx.js");
					}
					page.write(getResourceLocation(t.getName(),
							new ThemeResource(file)));
					page.write("\" type=\"text/javascript\"></script>\n");
				}
			}

		}

		page.write("</head><body class=\"itmtk\">\n");

		page.write("<div id=\"ajax-wait\">Loading...</div>\n");

		page.write("<div id=\"ajax-window\"></div>\n");

		page.write("<script language=\"JavaScript\">\n");

		String[] urlParts = getApplicationUrl(request).toString().split("\\/");
		String appUrl = "";
		// don't use server and port in uri. It may cause problems with some
		// virtual server configurations which lose the server name
		for (int i = 3; i < urlParts.length; i++)
			appUrl += "/" + urlParts[i];
		if (appUrl.endsWith("/"))
			appUrl = appUrl.substring(0, appUrl.length() - 1);
		page.write("itmill.tmp = new itmill.Client("
				+ "document.getElementById('ajax-window')," + "\"" + appUrl
				+ "/UIDL/" + "\",\"" + resourcePath
				+ ((Theme) themes.get(themes.size() - 1)).getName() + "/"

				+ "client/\",document.getElementById('ajax-wait'));\n");

		// TODO Only current theme is registered to the client
		// for (int k = themes.size() - 1; k >= 0; k--) {
		// t = (Theme) themes.get(k);
		t = theme;
		String themeObjName = "itmill.themes."
				+ t.getName().substring(0, 1).toUpperCase()
				+ t.getName().substring(1);
		page.write(" (new " + themeObjName + "(\"" + resourcePath + t.getName()
				+ "/\")).registerTo(itmill.tmp);\n");
		// }

		if (isDebugMode(unhandledParameters))
			page.write("itmill.tmp.debugEnabled =true;\n");
		page.write("itmill.tmp.start();\n");
		page.write("delete itmill.tmp;\n");

		page.write("</script>\n");

		page.write("</body></html>\n");
		page.close();
	}

	/**
	 * Handles the requested URI. An application can add handlers to do special
	 * processing, when a certain URI is requested. The handlers are invoked
	 * before any windows URIs are processed and if a DownloadStream is returned
	 * it is sent to the client.
	 * 
	 * @param application
	 *            the Application owning the URI.
	 * @param request
	 *            the HTTP request instance.
	 * @param response
	 *            the HTTP response to write to.
	 * @return boolean <code>true</code> if the request was handled and
	 *         further processing should be suppressed, <code>false</code>
	 *         otherwise.
	 * @see com.itmill.toolkit.terminal.URIHandler
	 */
	private DownloadStream handleURI(Application application,
			HttpServletRequest request, HttpServletResponse response) {

		String uri = request.getPathInfo();

		// If no URI is available
		if (uri == null || uri.length() == 0 || uri.equals("/"))
			return null;

		// Removes the leading /
		while (uri.startsWith("/") && uri.length() > 0)
			uri = uri.substring(1);

		// Handles the uri
		DownloadStream stream = null;
		try {
			stream = application.handleURI(application.getURL(), uri);
		} catch (Throwable t) {
			application.terminalError(new URIHandlerErrorImpl(application, t));
		}

		return stream;
	}

	/**
	 * Handles the requested URI. An application can add handlers to do special
	 * processing, when a certain URI is requested. The handlers are invoked
	 * before any windows URIs are processed and if a DownloadStream is returned
	 * it is sent to the client.
	 * 
	 * @param stream
	 *            the download stream.
	 * 
	 * @param request
	 *            the HTTP request instance.
	 * @param response
	 *            the HTTP response to write to.
	 * 
	 * @see com.itmill.toolkit.terminal.URIHandler
	 */
	private void handleDownload(DownloadStream stream,
			HttpServletRequest request, HttpServletResponse response) {

		// Download from given stream
		InputStream data = stream.getStream();
		if (data != null) {

			// Sets content type
			response.setContentType(stream.getContentType());

			// Sets cache headers
			long cacheTime = stream.getCacheTime();
			if (cacheTime <= 0) {
				response.setHeader("Cache-Control", "no-cache");
				response.setHeader("Pragma", "no-cache");
				response.setDateHeader("Expires", 0);
			} else {
				response.setHeader("Cache-Control", "max-age=" + cacheTime
						/ 1000);
				response.setDateHeader("Expires", System.currentTimeMillis()
						+ cacheTime);
				response.setHeader("Pragma", "cache"); // Required to apply
				// caching in some
				// Tomcats
			}

			// Copy download stream parameters directly
			// to HTTP headers.
			Iterator i = stream.getParameterNames();
			if (i != null) {
				while (i.hasNext()) {
					String param = (String) i.next();
					response.setHeader((String) param, stream
							.getParameter(param));
				}
			}

			int bufferSize = stream.getBufferSize();
			if (bufferSize <= 0 || bufferSize > MAX_BUFFER_SIZE)
				bufferSize = DEFAULT_BUFFER_SIZE;
			byte[] buffer = new byte[bufferSize];
			int bytesRead = 0;

			try {
				OutputStream out = response.getOutputStream();

				while ((bytesRead = data.read(buffer)) > 0) {
					out.write(buffer, 0, bytesRead);
					out.flush();
				}
				out.close();
			} catch (IOException ignored) {
			}

		}

	}

	/**
	 * Looks for default theme JAR file.
	 * 
	 * @param fileList
	 * @return Jar file or null if not found.
	 */
	private File findDefaultThemeJar(String[] fileList) {

		// Try to find the default theme JAR file based on the given path
		for (int i = 0; i < fileList.length; i++) {
			String path = getResourcePath(getServletContext(), fileList[i]);
			File file = null;
			if (path != null && (file = new File(path)).exists()) {
				return file;
			}
		}

		// If we do not have access to individual files, create a temporary
		// file from named resource.
		for (int i = 0; i < fileList.length; i++) {
			InputStream defaultTheme = this.getServletContext()
					.getResourceAsStream(fileList[i]);
			// Read the content to temporary file and return it
			if (defaultTheme != null) {
				return createTemporaryFile(defaultTheme, ".jar");
			}
		}

		// Try to find the default theme JAR file based on file naming scheme
		// NOTE: This is for backward compability with 3.0.2 and earlier.
		String path = getResourcePath(getServletContext(), "/WEB-INF/lib");
		if (path != null) {
			File lib = new File(path);
			String[] files = lib.list();
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					if (files[i].toLowerCase().endsWith(".jar")
							&& files[i].startsWith(DEFAULT_THEME_JAR_PREFIX)) {
						return new File(lib, files[i]);
					}
				}
			}
		}

		// If no file was found return null
		return null;
	}

	/**
	 * Creates a temporary file for given stream.
	 * 
	 * @param stream
	 *            the Stream to be stored into temporary file.
	 * @param extension
	 *            the File type extension.
	 * @return the temporary File.
	 */
	private File createTemporaryFile(InputStream stream, String extension) {
		File tmpFile;
		try {
			tmpFile = File.createTempFile(DEFAULT_THEME_TEMP_FILE_PREFIX,
					extension);
			FileOutputStream out = new FileOutputStream(tmpFile);
			byte[] buf = new byte[1024];
			int bytes = 0;
			while ((bytes = stream.read(buf)) > 0) {
				out.write(buf, 0, bytes);
			}
			out.close();
		} catch (IOException e) {
			System.err
					.println("Failed to create temporary file for default theme: "
							+ e);
			tmpFile = null;
		}

		return tmpFile;
	}

	/**
	 * Handles theme resource file requests. Resources supplied with the themes
	 * are provided by the WebAdapterServlet.
	 * 
	 * @param request
	 *            the HTTP request.
	 * @param response
	 *            the HTTP response.
	 * @return boolean <code>true</code> if the request was handled and
	 *         further processing should be suppressed, <code>false</code>
	 *         otherwise.
	 * @throws ServletException
	 *             if an exception has occurred that interferes with the
	 *             servlet's normal operation.
	 */
	private boolean handleResourceRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException {

		// If the resource path is unassigned, initialize it
		if (resourcePath == null) {
			resourcePath = request.getContextPath() + request.getServletPath()
					+ RESOURCE_URI;
			// WebSphere Application Server related fix
			resourcePath = resourcePath.replaceAll("//", "/");
		}

		String resourceId = request.getPathInfo();

		// Checks if this really is a resource request
		if (resourceId == null || !resourceId.startsWith(RESOURCE_URI))
			return false;

		// Checks the resource type
		resourceId = resourceId.substring(RESOURCE_URI.length());
		InputStream data = null;
		// Gets theme resources
		try {
			data = themeSource.getResource(resourceId);
		} catch (ThemeSource.ThemeException e) {
			Log.info(e.getMessage());
			data = null;
		}

		// Writes the response
		try {
			if (data != null) {
				response.setContentType(FileTypeResolver
						.getMIMEType(resourceId));

				// Use default cache time for theme resources
				if (this.themeCacheTime > 0) {
					response.setHeader("Cache-Control", "max-age="
							+ this.themeCacheTime / 1000);
					response.setDateHeader("Expires", System
							.currentTimeMillis()
							+ this.themeCacheTime);
					response.setHeader("Pragma", "cache"); // Required to apply
					// caching in some
					// Tomcats
				}
				// Writes the data to client
				byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
				int bytesRead = 0;
				OutputStream out = response.getOutputStream();
				while ((bytesRead = data.read(buffer)) > 0) {
					out.write(buffer, 0, bytesRead);
				}
				out.close();
				data.close();
			} else {
				response.sendError(HttpServletResponse.SC_NOT_FOUND);
			}

		} catch (java.io.IOException e) {
			Log.info("Resource transfer failed:  " + request.getRequestURI()
					+ ". (" + e.getMessage() + ")");
		}

		return true;
	}

	/**
	 * Gets the variable map for the session.
	 * 
	 * @param application
	 * @param request
	 *            the HTTP request.
	 * @return the variable map.
	 * 
	 */
	private static synchronized HttpVariableMap getVariableMap(
			Application application, HttpServletRequest request) {

		HttpSession session = request.getSession();

		// Gets the application to variablemap map
		Map varMapMap = (Map) session.getAttribute(SESSION_ATTR_VARMAP);
		if (varMapMap == null) {
			varMapMap = new WeakHashMap();
			session.setAttribute(SESSION_ATTR_VARMAP, varMapMap);
		}

		// Creates a variable map, if it does not exists.
		HttpVariableMap variableMap = (HttpVariableMap) varMapMap
				.get(application);
		if (variableMap == null) {
			variableMap = new HttpVariableMap();
			varMapMap.put(application, variableMap);
		}

		return variableMap;
	}

	/**
	 * Gets the current application URL from request.
	 * 
	 * @param request
	 *            the HTTP request.
	 * @throws MalformedURLException
	 *             if the application is denied access to the persistent data
	 *             store represented by the given URL.
	 */
	private URL getApplicationUrl(HttpServletRequest request)
			throws MalformedURLException {

		URL applicationUrl;
		try {
			URL reqURL = new URL(
					(request.isSecure() ? "https://" : "http://")
							+ request.getServerName()
							+ ((request.isSecure() && request.getServerPort() == 443)
									|| (!request.isSecure() && request
											.getServerPort() == 80) ? "" : ":"
									+ request.getServerPort())
							+ request.getRequestURI());
			String servletPath = request.getContextPath()
					+ request.getServletPath();
			if (servletPath.length() == 0
					|| servletPath.charAt(servletPath.length() - 1) != '/')
				servletPath = servletPath + "/";
			applicationUrl = new URL(reqURL, servletPath);
		} catch (MalformedURLException e) {
			Log.error("Error constructing application url "
					+ request.getRequestURI() + " (" + e + ")");
			throw e;
		}

		return applicationUrl;
	}

	/**
	 * Gets the existing application for given request. Looks for application
	 * instance for given request based on the requested URL.
	 * 
	 * @param request
	 *            the HTTP request.
	 * @return Application instance, or null if the URL does not map to valid
	 *         application.
	 * @throws MalformedURLException
	 *             if the application is denied access to the persistent data
	 *             store represented by the given URL.
	 */
	private Application getApplication(HttpServletRequest request)
			throws MalformedURLException {

		// Ensures that the session is still valid
		HttpSession session = request.getSession(false);
		if (session == null)
			return null;

		// Gets application list for the session.
		LinkedList applications = (LinkedList) session
				.getAttribute(SESSION_ATTR_APPS);
		if (applications == null)
			return null;

		// Search for the application (using the application URI) from the list
		Application application = null;
		for (Iterator i = applications.iterator(); i.hasNext()
				&& application == null;) {
			Application a = (Application) i.next();
			String aPath = a.getURL().getPath();
			String servletPath = request.getContextPath()
					+ request.getServletPath();
			if (servletPath.length() < aPath.length())
				servletPath += "/";
			if (servletPath.equals(aPath))
				application = a;
		}

		// Removes stopped applications from the list
		if (application != null && !application.isRunning()) {
			applications.remove(application);
			application = null;
		}

		return application;
	}

	/**
	 * Creates a new application.
	 * 
	 * @param request
	 *            the HTTP request.
	 * @return the New application instance.
	 * @throws MalformedURLException
	 *             if the application is denied access to the persistent data
	 *             store represented by the given URL.
	 * @throws InstantiationException
	 *             if a new instance of the class cannot be instantiated.
	 * @throws IllegalAccessException
	 *             if it does not have access to the property accessor method.
	 * @throws LicenseFileHasNotBeenRead
	 *             if the license file has not been read.
	 * @throws LicenseSignatureIsInvalid
	 *             if the license file has been changed or signature is
	 *             otherwise invalid.
	 * @throws InvalidLicenseFile
	 *             if the license file is not of correct XML format.
	 * @throws LicenseViolation
	 * 
	 * @throws SAXException
	 *             the Error parsing the license file.
	 */
	private Application createApplication(HttpServletRequest request)
			throws MalformedURLException, InstantiationException,
			IllegalAccessException, LicenseFileHasNotBeenRead,
			LicenseSignatureIsInvalid, InvalidLicenseFile, LicenseViolation,
			SAXException {

		Application application = null;

		// Gets the application url
		URL applicationUrl = getApplicationUrl(request);

		// Gets application list.
		HttpSession session = request.getSession();
		if (session == null)
			return null;
		LinkedList applications = (LinkedList) session
				.getAttribute(SESSION_ATTR_APPS);
		if (applications == null) {
			applications = new LinkedList();
			session.setAttribute(SESSION_ATTR_APPS, applications);
			HttpSessionBindingListener sessionBindingListener = new SessionBindingListener(
					applications);
			session.setAttribute(SESSION_BINDING_LISTENER,
					sessionBindingListener);
		}

		// Creates new application and start it
		try {
			application = (Application) this.applicationClass.newInstance();
			applications.add(application);

			// Listens to window add/removes (for web mode)
			application.addListener((Application.WindowAttachListener) this);
			application.addListener((Application.WindowDetachListener) this);

			// Sets locale
			application.setLocale(request.getLocale());

			// Gets application context for this session
			WebApplicationContext context = (WebApplicationContext) session
					.getAttribute(SESSION_ATTR_CONTEXT);
			if (context == null) {
				context = new WebApplicationContext(session);
				session.setAttribute(SESSION_ATTR_CONTEXT, context);
			}

			// Starts application and check license
			initializeLicense(application);
			application.start(applicationUrl, this.applicationProperties,
					context);
			checkLicense(application);

		} catch (IllegalAccessException e) {
			Log.error("Illegal access to application class "
					+ this.applicationClass.getName());
			throw e;
		} catch (InstantiationException e) {
			Log.error("Failed to instantiate application class: "
					+ this.applicationClass.getName());
			throw e;
		}

		return application;
	}

	/**
	 * 
	 * @param application
	 */
	private void initializeLicense(Application application) {

		License license = (License) licenseForApplicationClass.get(application
				.getClass());
		if (license == null) {
			license = new License();
			licenseForApplicationClass.put(application.getClass(), license);
		}
		application.setToolkitLicense(license);
	}

	/**
	 * 
	 * @param application
	 * @throws LicenseFileHasNotBeenRead
	 *             if the license file has not been read.
	 * @throws LicenseSignatureIsInvalid
	 *             if the license file has been changed or signature is
	 *             otherwise invalid.
	 * @throws InvalidLicenseFile
	 *             if the license file is not of correct XML format.
	 * @throws LicenseViolation
	 * 
	 * @throws SAXException
	 *             the Error parsing the license file.
	 */
	private void checkLicense(Application application)
			throws LicenseFileHasNotBeenRead, LicenseSignatureIsInvalid,
			InvalidLicenseFile, LicenseViolation, SAXException {
		License license = application.getToolkitLicense();
		if (!license.hasBeenRead()) {
			InputStream lis;
			try {
				URL url = getServletContext().getResource(
						"/WEB-INF/itmill-toolkit-license.xml");
				if (url == null) {
					throw new RuntimeException(
							"License file could not be read. "
									+ "You can install it to "
									+ "WEB-INF/itmill-toolkit-license.xml.");
				}
				lis = url.openStream();
				license.readLicenseFile(lis);
			} catch (MalformedURLException e) {
				// This should not happen
				throw new RuntimeException(e);
			} catch (IOException e) {
				// This should not happen
				throw new RuntimeException(e);
			} catch (LicenseFileHasAlreadyBeenRead e) {
				// This should not happen
				throw new RuntimeException(e);
			}
		}

		// For each application class, print license description - once
		if (!licensePrintedForApplicationClass.containsKey(applicationClass)) {
			licensePrintedForApplicationClass.put(applicationClass,
					Boolean.TRUE);
			if (license.shouldLimitsBePrintedOnInit())
				System.out.print(license.getDescription());
		}

		// Checks license validity
		try {
			license.check(applicationClass, getNumberOfActiveUsers() + 1,
					VERSION_MAJOR, VERSION_MINOR, "IT Mill Toolkit", null);
		} catch (LicenseFileHasNotBeenRead e) {
			application.close();
			throw e;
		} catch (LicenseSignatureIsInvalid e) {
			application.close();
			throw e;
		} catch (InvalidLicenseFile e) {
			application.close();
			throw e;
		} catch (LicenseViolation e) {
			application.close();
			throw e;
		}
	}

	/**
	 * Gets the number of active application-user pairs.
	 * 
	 * This returns total number of all applications in the server that are
	 * considered to be active. For an application to be active, it must have
	 * been accessed less than ACTIVE_USER_REQUEST_INTERVAL ms.
	 * 
	 * @return the Number of active application instances in the server.
	 */
	private int getNumberOfActiveUsers() {

		Set apps = applicationToLastRequestDate.keySet();
		int active = 0;
		long now = System.currentTimeMillis();
		for (Iterator i = apps.iterator(); i.hasNext();) {
			Date lastReq = (Date) applicationToLastRequestDate.get(i.next());
			if (now - lastReq.getTime() < ACTIVE_USER_REQUEST_INTERVAL)
				active++;
		}

		return active;
	}

	/**
	 * Ends the application.
	 * 
	 * @param request
	 *            the HTTP request.
	 * @param response
	 *            the HTTP response to write to.
	 * @param application
	 *            the application to end.
	 * @throws IOException
	 *             if the writing failed due to input/output error.
	 */
	private void endApplication(HttpServletRequest request,
			HttpServletResponse response, Application application)
			throws IOException {

		String logoutUrl = application.getLogoutURL();
		if (logoutUrl == null)
			logoutUrl = application.getURL().toString();

		HttpSession session = request.getSession();
		if (session != null) {
			LinkedList applications = (LinkedList) session
					.getAttribute(SESSION_ATTR_APPS);
			if (applications != null)
				applications.remove(application);
		}

		response.sendRedirect(response.encodeRedirectURL(logoutUrl));
	}

	/**
	 * Gets the existing application or create a new one. Get a window within an
	 * application based on the requested URI.
	 * 
	 * @param request
	 *            the HTTP Request.
	 * @param application
	 *            the Application to query for window.
	 * @return Window mathing the given URI or null if not found.
	 * @throws ServletException
	 *             if an exception has occurred that interferes with the
	 *             servlet's normal operation.
	 */
	private Window getApplicationWindow(HttpServletRequest request,
			Application application, Map params) throws ServletException {

		Window window = null;

		// Finds the window where the request is handled
		String path = request.getPathInfo();

		// Main window as the URI is empty
		if (path == null || path.length() == 0 || path.equals("/"))
			window = application.getMainWindow();

		// Try to search by window name
		else {
			String windowName = null;
			if (path.charAt(0) == '/')
				path = path.substring(1);
			int index = path.indexOf('/');
			if (index < 0) {
				windowName = path;
				path = "";
			} else {
				windowName = path.substring(0, index);
				path = path.substring(index + 1);
			}
			window = application.getWindow(windowName);

			if (window == null) {
				// By default, we use main window
				window = application.getMainWindow();
			} else if (!window.isVisible()) {
				// Implicitly painting without actually invoking paint()
				window.requestRepaintRequests();

				// If the window is invisible send a blank page
				return null;
			}
		}
		// Creates and open new debug window for application if requested
		Window debugWindow = application.getWindow(DebugWindow.WINDOW_NAME);
		if (debugWindow == null) {
			if (isDebugMode(params)
					&& WebBrowserProbe.getTerminalType(request.getSession())
							.getRenderingMode() != WebBrowser.RENDERING_MODE_AJAX) {
				try {
					debugWindow = new DebugWindow(application, request
							.getSession(false), this);
					debugWindow.setWidth(370);
					debugWindow.setHeight(480);
					application.addWindow(debugWindow);
				} catch (Exception e) {
					throw new ServletException(
							"Failed to create debug window for application", e);
				}
			}
		} else if (window != debugWindow) {
			if (isDebugMode(params))
				debugWindow.requestRepaint();
			else
				application.removeWindow(debugWindow);
		}

		return window;
	}

	/**
	 * Gets relative location of a theme resource.
	 * 
	 * @param theme
	 *            the Theme name.
	 * @param resource
	 *            the Theme resource.
	 * @return External URI specifying the resource
	 */
	public String getResourceLocation(String theme, ThemeResource resource) {

		if (resourcePath == null)
			return resource.getResourceId();
		return resourcePath + theme + "/" + resource.getResourceId();
	}

	/**
	 * Checks if web adapter is in debug mode. Extra output is generated to log
	 * when debug mode is enabled.
	 * 
	 * @param parameters
	 * @return <code>true</code> if the web adapter is in debug mode.
	 *         otherwise <code>false</code>.
	 */
	public boolean isDebugMode(Map parameters) {
		if (parameters != null) {
			Object[] debug = (Object[]) parameters.get("debug");
			if (debug != null && !"false".equals(debug[0].toString())
					&& !"false".equals(debugMode))
				return true;
		}
		return "true".equals(debugMode);
	}

	/**
	 * Returns the theme source.
	 * 
	 * @return ThemeSource
	 */
	public ThemeSource getThemeSource() {
		return themeSource;
	}

	/**
	 * 
	 * @param application
	 * @param window
	 */
	protected void addDirtyWindow(Application application, Window window) {
		synchronized (applicationToDirtyWindowSetMap) {
			WeakHashMap dirtyWindows = (WeakHashMap) applicationToDirtyWindowSetMap
					.get(application);
			if (dirtyWindows == null) {
				dirtyWindows = new WeakHashMap();
				applicationToDirtyWindowSetMap.put(application, dirtyWindows);
			}
			dirtyWindows.put(window, Boolean.TRUE);
		}
	}

	/**
	 * 
	 * @param application
	 * @param window
	 */
	protected void removeDirtyWindow(Application application, Window window) {
		synchronized (applicationToDirtyWindowSetMap) {
			WeakHashMap dirtyWindows = (WeakHashMap) applicationToDirtyWindowSetMap
					.get(application);
			if (dirtyWindows != null)
				dirtyWindows.remove(window);
		}
	}

	/**
	 * @see com.itmill.toolkit.Application.WindowAttachListener#windowAttached(Application.WindowAttachEvent)
	 */
	public void windowAttached(WindowAttachEvent event) {
		Window win = event.getWindow();
		win.addListener((Paintable.RepaintRequestListener) this);

		// Add window to dirty window references if it is visible
		// Or request the window to pass on the repaint requests
		if (win.isVisible())
			addDirtyWindow(event.getApplication(), win);
		else
			win.requestRepaintRequests();

	}

	/**
	 * @see com.itmill.toolkit.Application.WindowDetachListener#windowDetached(Application.WindowDetachEvent)
	 */
	public void windowDetached(WindowDetachEvent event) {
		event.getWindow().removeListener(
				(Paintable.RepaintRequestListener) this);

		// Adds dirty window reference for closing the window
		addDirtyWindow(event.getApplication(), event.getWindow());
	}

	/**
	 * Receives repaint request events.
	 * 
	 * @see com.itmill.toolkit.terminal.Paintable.RepaintRequestListener#repaintRequested(Paintable.RepaintRequestEvent)
	 */
	public void repaintRequested(RepaintRequestEvent event) {

		Paintable p = event.getPaintable();
		Application app = null;
		if (p instanceof Window)
			app = ((Window) p).getApplication();

		if (app != null)
			addDirtyWindow(app, ((Window) p));

		Object lock = applicationToServerCommandStreamLock.get(app);
		if (lock != null)
			synchronized (lock) {
				lock.notifyAll();
			}
	}

	/**
	 * Gets the list of dirty windows in application.
	 * 
	 * @param app
	 * @return
	 */
	protected Map getDirtyWindows(Application app) {
		WeakHashMap dirtyWindows;
		synchronized (applicationToDirtyWindowSetMap) {
			dirtyWindows = (WeakHashMap) applicationToDirtyWindowSetMap
					.get(app);
		}
		return (Map) dirtyWindows;
	}

	/**
	 * Removes a window from the list of dirty windows.
	 * 
	 * @param app
	 * @param window
	 */
	private void windowPainted(Application app, Window window) {
		removeDirtyWindow(app, window);
	}

	/**
	 * Generates server commands stream. If the server commands are not
	 * requested, return false.
	 * 
	 * @param request
	 *            the HTTP request instance.
	 * @param response
	 *            the HTTP response to write to.
	 */
	private boolean handleServerCommands(HttpServletRequest request,
			HttpServletResponse response) {

		// Server commands are allways requested with certain parameter
		if (request.getParameter(SERVER_COMMAND_PARAM) == null)
			return false;

		// Gets the application
		Application application;
		try {
			application = getApplication(request);
		} catch (MalformedURLException e) {
			return false;
		}
		if (application == null)
			return false;

		// Creates continuous server commands stream
		try {

			// Writer for writing the stream
			PrintWriter w = new PrintWriter(response.getOutputStream());

			// Prints necessary http page headers and padding
			w.println("<html><head></head><body>");
			for (int i = 0; i < SERVER_COMMAND_HEADER_PADDING; i++)
				w.print(' ');

			// Clock for synchronizing the stream
			Object lock = new Object();
			synchronized (applicationToServerCommandStreamLock) {
				Object oldlock = applicationToServerCommandStreamLock
						.get(application);
				if (oldlock != null)
					synchronized (oldlock) {
						oldlock.notifyAll();
					}
				applicationToServerCommandStreamLock.put(application, lock);
			}
			while (applicationToServerCommandStreamLock.get(application) == lock
					&& application.isRunning()) {
				synchronized (application) {

					// Session expiration
					Date lastRequest = (Date) applicationToLastRequestDate
							.get(application);
					if (lastRequest != null
							&& lastRequest.getTime()
									+ request.getSession()
											.getMaxInactiveInterval() * 1000 < System
									.currentTimeMillis()) {

						// Session expired, close application
						application.close();
					} else {

						// Application still alive - keep updating windows
						Map dws = getDirtyWindows(application);
						if (dws != null && !dws.isEmpty()) {

							// For one of the dirty windows (in each
							// application)
							// request redraw
							Window win = (Window) dws.keySet().iterator()
									.next();
							w
									.println("<script>\n"
											+ ThemeFunctionLibrary
													.getWindowRefreshScript(
															application,
															win,
															WebBrowserProbe
																	.getTerminalType(request
																			.getSession()))
											+ "</script>");

							removeDirtyWindow(application, win);

							// Windows that are closed immediately are "painted"
							// now
							if (win.getApplication() == null
									|| !win.isVisible())
								win.requestRepaintRequests();
						}
					}
				}

				// Sends the generated commands and newline immediately to
				// browser
				// TODO why space in here? why not plain ln?
				w.println(" ");
				w.flush();
				response.flushBuffer();

				synchronized (lock) {
					try {
						lock.wait(SERVER_COMMAND_STREAM_MAINTAIN_PERIOD);
					} catch (InterruptedException ignored) {
					}
				}
			}
		} catch (IOException ignore) {

			// In case of an Exceptions the server command stream is
			// terminated
			synchronized (applicationToServerCommandStreamLock) {
				if (applicationToServerCommandStreamLock.get(application) == application)
					applicationToServerCommandStreamLock.remove(application);
			}
		}

		return true;
	}

	/**
	 * 
	 * SessionBindingListener performs Application cleanups after sessions are
	 * expired. For each session exists one SessionBindingListener. It contains
	 * references to all applications related to single session.
	 * 
	 * @author IT Mill Ltd.
	 * @version
	 * @VERSION@
	 * @since 4.0
	 */

	private class SessionBindingListener implements HttpSessionBindingListener {
		private LinkedList applications;

		/**
		 * 
		 * @param applications
		 */
		protected SessionBindingListener(LinkedList applications) {
			this.applications = applications;
		}

		/**
		 * @see javax.servlet.http.HttpSessionBindingListener#valueBound(HttpSessionBindingEvent)
		 */
		public void valueBound(HttpSessionBindingEvent arg0) {
			// We are not interested in bindings
		}

		/**
		 * @see javax.servlet.http.HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent)
		 */
		public void valueUnbound(HttpSessionBindingEvent event) {
			// If the binding listener is unbound from the session, the
			// session must be closing
			if (event.getName().equals(SESSION_BINDING_LISTENER)) {
				// Close all applications related to given session
				Object[] apps = applications.toArray();
				for (int i = 0; i < apps.length; i++) {
					if (apps[i] != null) {
						// Close application
						((Application) apps[i]).close();

						// Stops application server commands stream
						Object lock = applicationToServerCommandStreamLock
								.get(apps[i]);
						if (lock != null)
							synchronized (lock) {
								lock.notifyAll();
							}
						applicationToServerCommandStreamLock.remove(apps[i]);

						// Remove application from applications list
						applications.remove(apps[i]);

						// Remove application from hashmap
						// TODO remove check
						if (applicationToAjaxAppMgrMap
								.get((Application) apps[i]) == null) {
							System.out
									.println("ERROR: tried to remove nonexistent application ("
											+ (Application) apps[i] + ")");
						} else {
							applicationToAjaxAppMgrMap
									.remove((Application) apps[i]);
						}
					}
				}
			}
		}
	}

	/**
	 * Implementation of ParameterHandler.ErrorEvent interface.
	 */
	public class ParameterHandlerErrorImpl implements
			ParameterHandler.ErrorEvent {

		private ParameterHandler owner;

		private Throwable throwable;

		/**
		 * 
		 * @param owner
		 * @param throwable
		 */
		private ParameterHandlerErrorImpl(ParameterHandler owner,
				Throwable throwable) {
			this.owner = owner;
			this.throwable = throwable;
		}

		/**
		 * Gets the contained throwable.
		 * 
		 * @see com.itmill.toolkit.terminal.Terminal.ErrorEvent#getThrowable()
		 */
		public Throwable getThrowable() {
			return this.throwable;
		}

		/**
		 * Gets the source ParameterHandler.
		 * 
		 * @see com.itmill.toolkit.terminal.ParameterHandler.ErrorEvent#getParameterHandler()
		 */
		public ParameterHandler getParameterHandler() {
			return this.owner;
		}

	}

	/**
	 * Implementation of URIHandler.ErrorEvent interface.
	 */
	public class URIHandlerErrorImpl implements URIHandler.ErrorEvent {

		private URIHandler owner;

		private Throwable throwable;

		/**
		 * 
		 * @param owner
		 * @param throwable
		 */
		private URIHandlerErrorImpl(URIHandler owner, Throwable throwable) {
			this.owner = owner;
			this.throwable = throwable;
		}

		/**
		 * Gets the contained throwable.
		 * 
		 * @see com.itmill.toolkit.terminal.Terminal.ErrorEvent#getThrowable()
		 */
		public Throwable getThrowable() {
			return this.throwable;
		}

		/**
		 * Gets the source URIHandler.
		 * 
		 * @see com.itmill.toolkit.terminal.URIHandler.ErrorEvent#getURIHandler()
		 */
		public URIHandler getURIHandler() {
			return this.owner;
		}
	}

	/**
	 * Gets AJAX application manager for an application.
	 * 
	 * If this application has not been running in ajax mode before, new manager
	 * is created and web adapter stops listening to changes.
	 * 
	 * @param application
	 * @return AJAX Application Manager
	 */
	private AjaxApplicationManager getApplicationManager(Application application) {
		AjaxApplicationManager mgr = (AjaxApplicationManager) applicationToAjaxAppMgrMap
				.get(application);

		// This application is going from Web to AJAX mode, create new manager
		if (mgr == null) {
			// Creates new manager
			mgr = new AjaxApplicationManager(application);
			applicationToAjaxAppMgrMap.put(application, mgr);

			// Stops sending changes to this servlet because manager will take
			// control
			application.removeListener((Application.WindowAttachListener) this);
			application.removeListener((Application.WindowDetachListener) this);

			// Deregister all window listeners
			for (Iterator wins = application.getWindows().iterator(); wins
					.hasNext();)
				((Window) wins.next())
						.removeListener((Paintable.RepaintRequestListener) this);

			// Manager takes control over the application
			mgr.takeControl();
		}

		return mgr;
	}

	/**
	 * Gets resource path using different implementations. Required fo
	 * supporting different servlet container implementations (application
	 * servers).
	 * 
	 * @param servletContext
	 * @param path
	 *            the resource path.
	 * @return the resource path.
	 */
	protected static String getResourcePath(ServletContext servletContext,
			String path) {
		String resultPath = null;
		resultPath = servletContext.getRealPath(path);
		if (resultPath != null) {
			return resultPath;
		} else {
			try {
				URL url = servletContext.getResource(path);
				resultPath = url.getFile();
			} catch (Exception e) {
				// ignored
			}
		}
		return resultPath;
	}

}