summaryrefslogtreecommitdiffstats
path: root/src/com/vaadin/terminal/gwt/server/AbstractApplicationServlet.java
blob: 5f06285b1f7afb88d77358e6f0a27811d971deab (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
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
/*
@ITMillApache2LicenseForJavaFiles@
 */
package com.vaadin.terminal.gwt.server;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

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

import com.vaadin.Application;
import com.vaadin.Application.SystemMessages;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.ParameterHandler;
import com.vaadin.terminal.Terminal;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.terminal.URIHandler;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.ui.Window;

/**
 * Abstract implementation of the ApplicationServlet which handles all
 * communication between the client and the server.
 * 
 * It is possible to extend this class to provide own functionality but in most
 * cases this is unnecessary.
 * 
 * 
 * @author IT Mill Ltd.
 * @version
 * @VERSION@
 * @since 6.0
 */

@SuppressWarnings("serial")
public abstract class AbstractApplicationServlet extends HttpServlet implements
        Constants {

    // TODO Move some (all?) of the constants to a separate interface (shared
    // with portlet)

    private static final Logger logger = Logger
            .getLogger(AbstractApplicationServlet.class.getName());

    /**
     * The version number of this release. For example "6.2.0". Always in the
     * format "major.minor.revision[.build]". The build part is optional. All of
     * major, minor, revision must be integers.
     */
    public static final String VERSION;
    /**
     * Major version number. For example 6 in 6.2.0.
     */
    public static final int VERSION_MAJOR;

    /**
     * Minor version number. For example 2 in 6.2.0.
     */
    public static final int VERSION_MINOR;

    /**
     * Version revision number. For example 0 in 6.2.0.
     */
    public static final int VERSION_REVISION;

    /**
     * Build identifier. For example "nightly-20091123-c9963" in
     * 6.2.0.nightly-20091123-c9963.
     */
    public static final String VERSION_BUILD;

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

    /**
     * If the attribute is present in the request, a html fragment will be
     * written instead of a whole page.
     * 
     * It is set to "true" by the {@link ApplicationPortlet} (Portlet 1.0) and
     * read by {@link AbstractApplicationServlet}.
     */
    public static final String REQUEST_FRAGMENT = ApplicationServlet.class
            .getName() + ".fragment";
    /**
     * This request attribute forces widgetsets to be loaded from under the
     * specified base path; e.g shared widgetset for all portlets in a portal.
     * 
     * It is set by the {@link ApplicationPortlet} (Portlet 1.0) based on
     * {@link Constants.PORTAL_PARAMETER_VAADIN_RESOURCE_PATH} and read by
     * {@link AbstractApplicationServlet}.
     */
    public static final String REQUEST_VAADIN_STATIC_FILE_PATH = ApplicationServlet.class
            .getName() + ".widgetsetPath";
    /**
     * This request attribute forces widgetset used; e.g for portlets that can
     * not have different widgetsets.
     * 
     * It is set by the {@link ApplicationPortlet} (Portlet 1.0) based on
     * {@link ApplicationPortlet.PORTLET_PARAMETER_WIDGETSET} and read by
     * {@link AbstractApplicationServlet}.
     */
    public static final String REQUEST_WIDGETSET = ApplicationServlet.class
            .getName() + ".widgetset";
    /**
     * This request attribute indicates the shared widgetset (e.g. portal-wide
     * default widgetset).
     * 
     * It is set by the {@link ApplicationPortlet} (Portlet 1.0) based on
     * {@link Constants.PORTAL_PARAMETER_VAADIN_WIDGETSET} and read by
     * {@link AbstractApplicationServlet}.
     */
    public static final String REQUEST_SHARED_WIDGETSET = ApplicationServlet.class
            .getName() + ".sharedWidgetset";
    /**
     * If set, do not load the default theme but assume that loading it is
     * handled e.g. by ApplicationPortlet.
     * 
     * It is set by the {@link ApplicationPortlet} (Portlet 1.0) based on
     * {@link Constants.PORTAL_PARAMETER_VAADIN_THEME} and read by
     * {@link AbstractApplicationServlet}.
     */
    public static final String REQUEST_DEFAULT_THEME = ApplicationServlet.class
            .getName() + ".defaultThemeUri";
    /**
     * This request attribute is used to add styles to the main element. E.g
     * "height:500px" generates a style="height:500px" to the main element,
     * useful from some embedding situations (e.g portlet include.)
     * 
     * It is typically set by the {@link ApplicationPortlet} (Portlet 1.0) based
     * on {@link ApplicationPortlet.PORTLET_PARAMETER_STYLE} and read by
     * {@link AbstractApplicationServlet}.
     */
    public static final String REQUEST_APPSTYLE = ApplicationServlet.class
            .getName() + ".style";

    private Properties applicationProperties;

    private boolean productionMode = false;

    private final String resourcePath = null;

    private int resourceCacheTime = 3600;
    static final String UPLOAD_URL_PREFIX = "APP/UPLOAD/";

    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    @Override
    public void init(javax.servlet.ServletConfig servletConfig)
            throws javax.servlet.ServletException {
        super.init(servletConfig);

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

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

    private void checkCrossSiteProtection() {
        if (getApplicationOrSystemProperty(
                SERVLET_PARAMETER_DISABLE_XSRF_PROTECTION, "false").equals(
                "true")) {
            /*
             * Print an information/warning message about running with xsrf
             * protection disabled
             */
            logger.warning(WARNING_XSRF_PROTECTION_DISABLED);
        }
    }

    private void checkProductionMode() {
        // Check if the application is in production mode.
        // We are in production mode if Debug=false or productionMode=true
        if (getApplicationOrSystemProperty(SERVLET_PARAMETER_DEBUG, "true")
                .equals("false")) {
            // "Debug=true" is the old way and should no longer be used
            productionMode = true;
        } else if (getApplicationOrSystemProperty(
                SERVLET_PARAMETER_PRODUCTION_MODE, "false").equals("true")) {
            // "productionMode=true" is the real way to do it
            productionMode = true;
        }

        if (!productionMode) {
            /* Print an information/warning message about running in debug mode */
            logger.warning(NOT_PRODUCTION_MODE_INFO);
        }

    }

    private void checkResourceCacheTime() {
        // Check if the browser caching time has been set in web.xml
        try {
            String rct = getApplicationOrSystemProperty(
                    SERVLET_PARAMETER_RESOURCE_CACHE_TIME, "3600");
            resourceCacheTime = Integer.parseInt(rct);
        } catch (NumberFormatException nfe) {
            // Default is 1h
            resourceCacheTime = 3600;
            logger.warning(WARNING_RESOURCE_CACHING_TIME_NOT_NUMERIC);
        }
    }

    /**
     * Gets an application property value.
     * 
     * @param parameterName
     *            the Name or the parameter.
     * @return String value or null if not found
     */
    protected String getApplicationProperty(String parameterName) {

        String val = applicationProperties.getProperty(parameterName);
        if (val != null) {
            return val;
        }

        // Try lower case application properties for backward compatibility with
        // 3.0.2 and earlier
        val = applicationProperties.getProperty(parameterName.toLowerCase());

        return val;
    }

    /**
     * Gets an system property value.
     * 
     * @param parameterName
     *            the Name or the parameter.
     * @return String value or null if not found
     */
    protected String getSystemProperty(String parameterName) {
        String val = null;

        String pkgName;
        final Package pkg = getClass().getPackage();
        if (pkg != null) {
            pkgName = pkg.getName();
        } else {
            final String className = 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());
        return val;
    }

    /**
     * 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) {

        String val = null;

        // Try application properties
        val = getApplicationProperty(parameterName);
        if (val != null) {
            return val;
        }

        // Try system properties
        val = getSystemProperty(parameterName);
        if (val != null) {
            return val;
        }

        return defaultValue;
    }

    /**
     * Returns true if the servlet is running in production mode. Production
     * mode disables all debug facilities.
     * 
     * @return true if in production mode, false if in debug mode
     */
    public boolean isProductionMode() {
        return productionMode;
    }

    /**
     * Returns the amount of milliseconds the browser should cache a file.
     * Default is 1 hour (3600 ms).
     * 
     * @return The amount of milliseconds files are cached in the browser
     */
    public int getResourceCacheTime() {
        return resourceCacheTime;
    }

    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    @Override
    protected void service(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        RequestType requestType = getRequestType(request);
        if (!ensureCookiesEnabled(requestType, request, response)) {
            return;
        }

        if (requestType == RequestType.STATIC_FILE) {
            serveStaticResources(request, response);
            return;
        }

        Application application = null;
        boolean transactionStarted = false;
        boolean requestStarted = false;

        try {
            // If a duplicate "close application" URL is received for an
            // application that is not open, redirect to the application's main
            // page.
            // This is needed as e.g. Spring Security remembers the last
            // URL from the application, which is the logout URL, and repeats
            // it.
            // We can tell apart a real onunload request from a repeated one
            // based on the real one having content (at least the UIDL security
            // key).
            if (requestType == RequestType.UIDL
                    && request.getParameterMap().containsKey(
                            ApplicationConnection.PARAM_UNLOADBURST)
                    && request.getContentLength() < 1
                    && getExistingApplication(request, false) == null) {
                redirectToApplication(request, response);
                return;
            }

            // Find out which application this request is related to
            application = findApplicationInstance(request, requestType);
            if (application == null) {
                return;
            }

            /*
             * Get or create a WebApplicationContext and an ApplicationManager
             * for the session
             */
            WebApplicationContext webApplicationContext = getApplicationContext(request
                    .getSession());
            CommunicationManager applicationManager = webApplicationContext
                    .getApplicationManager(application, this);

            /* Update browser information from the request */
            updateBrowserProperties(webApplicationContext.getBrowser(), request);

            /*
             * Call application requestStart before Application.init() is called
             * (bypasses the limitation in TransactionListener)
             */
            if (application instanceof HttpServletRequestListener) {
                ((HttpServletRequestListener) application).onRequestStart(
                        request, response);
                requestStarted = true;
            }

            // Start the newly created application
            startApplication(request, application, webApplicationContext);

            /*
             * Transaction starts. Call transaction listeners. Transaction end
             * is called in the finally block below.
             */
            webApplicationContext.startTransaction(application, request);
            transactionStarted = true;

            /* Handle the request */
            if (requestType == RequestType.FILE_UPLOAD) {
                applicationManager.handleFileUpload(request, response);
                return;
            } else if (requestType == RequestType.UIDL) {
                // Handles AJAX UIDL requests
                Window window = applicationManager.getApplicationWindow(
                        request, this, application, null);
                applicationManager.handleUidlRequest(request, response, this,
                        window);
                return;
            }

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

            // Finds the window within the application
            Window window = getApplicationWindow(request, applicationManager,
                    application);
            if (window == null) {
                throw new ServletException(ERROR_NO_WINDOW_FOUND);
            }

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

            // Handle parameters
            final Map<String, String[]> parameters = request.getParameterMap();
            if (window != null && parameters != null) {
                window.handleParameters(parameters);
            }

            /*
             * Call the URI handlers and if this turns out to be a download
             * request, send the file to the client
             */
            if (handleURI(applicationManager, window, request, response)) {
                return;
            }

            // Send initial AJAX page that kickstarts a Vaadin application
            writeAjaxPage(request, response, window, application);

        } catch (final SessionExpiredException e) {
            // Session has expired, notify user
            handleServiceSessionExpired(request, response);
        } catch (final GeneralSecurityException e) {
            handleServiceSecurityException(request, response);
        } catch (final Throwable e) {
            handleServiceException(request, response, application, e);
        } finally {
            // Notifies transaction end
            try {
                if (transactionStarted) {
                    ((WebApplicationContext) application.getContext())
                            .endTransaction(application, request);

                }

            } finally {
                if (requestStarted) {
                    ((HttpServletRequestListener) application).onRequestEnd(
                            request, response);
                }

            }

        }
    }

    /**
     * Check that cookie support is enabled in the browser. Only checks UIDL
     * requests.
     * 
     * @param requestType
     *            Type of the request as returned by
     *            {@link #getRequestType(HttpServletRequest)}
     * @param request
     *            The request from the browser
     * @param response
     *            The response to which an error can be written
     * @return false if cookies are disabled, true otherwise
     * @throws IOException
     */
    private boolean ensureCookiesEnabled(RequestType requestType,
            HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        if (requestType == RequestType.UIDL && !isRepaintAll(request)) {
            // In all other but the first UIDL request a cookie should be
            // returned by the browser.
            // This can be removed if cookieless mode (#3228) is supported
            if (request.getRequestedSessionId() == null) {
                // User has cookies disabled
                criticalNotification(request, response, getSystemMessages()
                        .getCookiesDisabledCaption(), getSystemMessages()
                        .getCookiesDisabledMessage(), null, getSystemMessages()
                        .getCookiesDisabledURL());
                return false;
            }
        }
        return true;
    }

    private void updateBrowserProperties(WebBrowser browser,
            HttpServletRequest request) {
        browser.updateBrowserProperties(request.getLocale(),
                request.getRemoteAddr(), request.isSecure(),
                request.getHeader("user-agent"), request.getParameter("sw"),
                request.getParameter("sh"));
    }

    protected ClassLoader getClassLoader() throws ServletException {
        // Gets custom class loader
        final String classLoaderName = getApplicationOrSystemProperty(
                "ClassLoader", null);
        ClassLoader classLoader;
        if (classLoaderName == null) {
            classLoader = getClass().getClassLoader();
        } else {
            try {
                final Class<?> classLoaderClass = getClass().getClassLoader()
                        .loadClass(classLoaderName);
                final Constructor<?> c = classLoaderClass
                        .getConstructor(new Class[] { ClassLoader.class });
                classLoader = (ClassLoader) c
                        .newInstance(new Object[] { getClass().getClassLoader() });
            } catch (final Exception e) {
                throw new ServletException(
                        "Could not find specified class loader: "
                                + classLoaderName, e);
            }
        }
        return classLoader;
    }

    /**
     * Send a notification to client's application. Used to notify client of
     * critical errors, session expiration and more. Server has no knowledge of
     * what application client refers to.
     * 
     * @param request
     *            the HTTP request instance.
     * @param response
     *            the HTTP response to write to.
     * @param caption
     *            the notification caption
     * @param message
     *            to notification body
     * @param details
     *            a detail message to show in addition to the message. Currently
     *            shown directly below the message but could be hidden behind a
     *            details drop down in the future. Mainly used to give
     *            additional information not necessarily useful to the end user.
     * @param url
     *            url to load when the message is dismissed. Null will reload
     *            the current page.
     * @throws IOException
     *             if the writing failed due to input/output error.
     */
    protected final void criticalNotification(HttpServletRequest request,
            HttpServletResponse response, String caption, String message,
            String details, String url) throws IOException {

        if (isUIDLRequest(request)) {

            if (caption != null) {
                caption = "\"" + JsonPaintTarget.escapeJSON(caption) + "\"";
            }
            if (details != null) {
                if (message == null) {
                    message = details;
                } else {
                    message += "<br/><br/>" + details;
                }
            }

            if (message != null) {
                message = "\"" + JsonPaintTarget.escapeJSON(message) + "\"";
            }
            if (url != null) {
                url = "\"" + JsonPaintTarget.escapeJSON(url) + "\"";
            }

            String output = "for(;;);[{\"changes\":[], \"meta\" : {"
                    + "\"appError\": {" + "\"caption\":" + caption + ","
                    + "\"message\" : " + message + "," + "\"url\" : " + url
                    + "}}, \"resources\": {}, \"locales\":[]}]";
            writeResponse(response, "application/json; charset=UTF-8", output);
        } else {
            // Create an HTML reponse with the error
            String output = "";

            if (url != null) {
                output += "<a href=\"" + url + "\">";
            }
            if (caption != null) {
                output += "<b>" + caption + "</b><br/>";
            }
            if (message != null) {
                output += message;
                output += "<br/><br/>";
            }

            if (details != null) {
                output += details;
                output += "<br/><br/>";
            }
            if (url != null) {
                output += "</a>";
            }
            writeResponse(response, "text/html; charset=UTF-8", output);

        }

    }

    /**
     * Writes the response in {@code output} using the contentType given in
     * {@code contentType} to the provided {@link HttpServletResponse}
     * 
     * @param response
     * @param contentType
     * @param output
     *            Output to write (UTF-8 encoded)
     * @throws IOException
     */
    private void writeResponse(HttpServletResponse response,
            String contentType, String output) throws IOException {
        response.setContentType(contentType);
        final ServletOutputStream out = response.getOutputStream();
        // Set the response type
        final PrintWriter outWriter = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(out, "UTF-8")));
        outWriter.print(output);
        outWriter.flush();
        outWriter.close();
        out.flush();

    }

    /**
     * Returns the application instance to be used for the request. If an
     * existing instance is not found a new one is created or null is returned
     * to indicate that the application is not available.
     * 
     * @param request
     * @param requestType
     * @return
     * @throws MalformedURLException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws ServletException
     * @throws SessionExpiredException
     */
    private Application findApplicationInstance(HttpServletRequest request,
            RequestType requestType) throws MalformedURLException,
            ServletException, SessionExpiredException {

        boolean requestCanCreateApplication = requestCanCreateApplication(
                request, requestType);

        /* Find an existing application for this request. */
        Application application = getExistingApplication(request,
                requestCanCreateApplication);

        if (application != null) {
            /*
             * There is an existing application. We can use this as long as the
             * user not specifically requested to close or restart it.
             */

            final boolean restartApplication = (request
                    .getParameter(URL_PARAMETER_RESTART_APPLICATION) != null);
            final boolean closeApplication = (request
                    .getParameter(URL_PARAMETER_CLOSE_APPLICATION) != null);

            if (restartApplication) {
                closeApplication(application, request.getSession(false));
                return createApplication(request);
            } else if (closeApplication) {
                closeApplication(application, request.getSession(false));
                return null;
            } else {
                return application;
            }
        }

        // No existing application was found

        if (requestCanCreateApplication) {
            /*
             * If the request is such that it should create a new application if
             * one as not found, we do that.
             */
            return createApplication(request);
        } else {
            /*
             * The application was not found and a new one should not be
             * created. Assume the session has expired.
             */
            throw new SessionExpiredException();
        }

    }

    /**
     * Check if the request should create an application if an existing
     * application is not found.
     * 
     * @param request
     * @param requestType
     * @return true if an application should be created, false otherwise
     */
    boolean requestCanCreateApplication(HttpServletRequest request,
            RequestType requestType) {
        if (requestType == RequestType.UIDL && isRepaintAll(request)) {
            /*
             * UIDL request contains valid repaintAll=1 event, the user probably
             * wants to initiate a new application through a custom index.html
             * without using writeAjaxPage.
             */
            return true;

        } else if (requestType == RequestType.OTHER) {
            /*
             * I.e URIs that are not application resources or static (theme)
             * files.
             */
            return true;

        }

        return false;
    }

    /**
     * Gets resource path using different implementations. Required to
     * 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 {
                final URL url = servletContext.getResource(path);
                resultPath = url.getFile();
            } catch (final Exception e) {
                // FIXME: Handle exception
                logger.log(Level.INFO, "Could not find resource path " + path,
                        e);
            }
        }
        return resultPath;
    }

    /**
     * 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.
     * @throws IOException
     * 
     * @see com.vaadin.terminal.URIHandler
     */
    private void handleDownload(DownloadStream stream,
            HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        if (stream.getParameter("Location") != null) {
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            response.addHeader("Location", stream.getParameter("Location"));
            return;
        }

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

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

            // Sets cache headers
            final 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.
            final Iterator<String> i = stream.getParameterNames();
            if (i != null) {
                while (i.hasNext()) {
                    final String param = i.next();
                    response.setHeader(param, stream.getParameter(param));
                }
            }

            // suggest local filename from DownloadStream if Content-Disposition
            // not explicitly set
            String contentDispositionValue = stream
                    .getParameter("Content-Disposition");
            if (contentDispositionValue == null) {
                contentDispositionValue = "filename=\"" + stream.getFileName()
                        + "\"";
                response.setHeader("Content-Disposition",
                        contentDispositionValue);
            }

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

            final OutputStream out = response.getOutputStream();

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

    }

    /**
     * Creates a new application and registers it into WebApplicationContext
     * (aka session). This is not meant to be overridden. Override
     * getNewApplication to create the application instance in a custom way.
     * 
     * @param request
     * @return
     * @throws ServletException
     * @throws MalformedURLException
     */
    private Application createApplication(HttpServletRequest request)
            throws ServletException, MalformedURLException {
        Application newApplication = getNewApplication(request);

        final WebApplicationContext context = getApplicationContext(request
                .getSession());
        context.addApplication(newApplication);

        return newApplication;
    }

    private void handleServiceException(HttpServletRequest request,
            HttpServletResponse response, Application application, Throwable e)
            throws IOException, ServletException {
        // if this was an UIDL request, response UIDL back to client
        if (getRequestType(request) == RequestType.UIDL) {
            Application.SystemMessages ci = getSystemMessages();
            criticalNotification(request, response,
                    ci.getInternalErrorCaption(), ci.getInternalErrorMessage(),
                    null, ci.getInternalErrorURL());
            if (application != null) {
                application.getErrorHandler()
                        .terminalError(new RequestError(e));
            } else {
                throw new ServletException(e);
            }
        } else {
            // Re-throw other exceptions
            throw new ServletException(e);
        }

    }

    /**
     * Returns the theme for given request/window
     * 
     * @param request
     * @param window
     * @return
     */
    private String getThemeForWindow(HttpServletRequest request, Window window) {
        // Finds theme name
        String themeName;

        if (request.getParameter(URL_PARAMETER_THEME) != null) {
            themeName = request.getParameter(URL_PARAMETER_THEME);
        } else {
            themeName = window.getTheme();
        }

        if (themeName == null) {
            // no explicit theme for window defined
            if (request.getAttribute(REQUEST_DEFAULT_THEME) != null) {
                // the default theme is defined in request (by portal)
                themeName = (String) request
                        .getAttribute(REQUEST_DEFAULT_THEME);
            } else {
                // using the default theme defined by Vaadin
                themeName = getDefaultTheme();
            }
        }

        // XSS preventation, theme names shouldn't contain special chars anyway.
        // The servlet denies them via url parameter.
        themeName = stripSpecialChars(themeName);

        return themeName;
    }

    /**
     * A helper method to strip away characters that might somehow be used for
     * XSS attacs. Leaves at least alphanumeric characters intact. Also removes
     * eg. ( and ), so values should be safe in javascript too.
     * 
     * @param themeName
     * @return
     */
    protected static String stripSpecialChars(String themeName) {
        StringBuilder sb = new StringBuilder();
        char[] charArray = themeName.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            char c = charArray[i];
            if (!CHAR_BLACKLIST.contains(c)) {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    private static final Collection<Character> CHAR_BLACKLIST = new HashSet<Character>(
            Arrays.asList(new Character[] { '&', '"', '\'', '<', '>', '(', ')',
                    ';' }));

    /**
     * Returns the default theme. Must never return null.
     * 
     * @return
     */
    public static String getDefaultTheme() {
        return DEFAULT_THEME_NAME;
    }

    /**
     * Calls URI handlers for the request. If an URI handler returns a
     * DownloadStream the stream is passed to the client for downloading.
     * 
     * @param applicationManager
     * @param window
     * @param request
     * @param response
     * @return true if an DownloadStream was sent to the client, false otherwise
     * @throws IOException
     */
    protected boolean handleURI(CommunicationManager applicationManager,
            Window window, HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        // Handles the URI
        DownloadStream download = applicationManager.handleURI(window, request,
                response, this);

        // A download request
        if (download != null) {
            // Client downloads an resource
            handleDownload(download, request, response);
            return true;
        }

        return false;
    }

    void handleServiceSessionExpired(HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException {

        if (isOnUnloadRequest(request)) {
            /*
             * Request was an unload request (e.g. window close event) and the
             * client expects no response if it fails.
             */
            return;
        }

        try {
            Application.SystemMessages ci = getSystemMessages();
            if (getRequestType(request) != RequestType.UIDL) {
                // 'plain' http req - e.g. browser reload;
                // just go ahead redirect the browser
                response.sendRedirect(ci.getSessionExpiredURL());
            } else {
                /*
                 * Invalidate session (weird to have session if we're saying
                 * that it's expired, and worse: portal integration will fail
                 * since the session is not created by the portal.
                 * 
                 * Session must be invalidated before criticalNotification as it
                 * commits the response.
                 */
                request.getSession().invalidate();

                // send uidl redirect
                criticalNotification(request, response,
                        ci.getSessionExpiredCaption(),
                        ci.getSessionExpiredMessage(), null,
                        ci.getSessionExpiredURL());

            }
        } catch (SystemMessageException ee) {
            throw new ServletException(ee);
        }

    }

    private void handleServiceSecurityException(HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException {
        if (isOnUnloadRequest(request)) {
            /*
             * Request was an unload request (e.g. window close event) and the
             * client expects no response if it fails.
             */
            return;
        }

        try {
            Application.SystemMessages ci = getSystemMessages();
            if (getRequestType(request) != RequestType.UIDL) {
                // 'plain' http req - e.g. browser reload;
                // just go ahead redirect the browser
                response.sendRedirect(ci.getCommunicationErrorURL());
            } else {
                // send uidl redirect
                criticalNotification(request, response,
                        ci.getCommunicationErrorCaption(),
                        ci.getCommunicationErrorMessage(),
                        INVALID_SECURITY_KEY_MSG, ci.getCommunicationErrorURL());
                /*
                 * Invalidate session. Portal integration will fail otherwise
                 * since the session is not created by the portal.
                 */
                request.getSession().invalidate();
            }
        } catch (SystemMessageException ee) {
            throw new ServletException(ee);
        }

        log("Invalid security key received from " + request.getRemoteHost());
    }

    /**
     * Creates a new application for the given request.
     * 
     * @param request
     *            the HTTP request.
     * @return A new Application instance.
     * @throws ServletException
     */
    protected abstract Application getNewApplication(HttpServletRequest request)
            throws ServletException;

    /**
     * Starts the application if it is not already running.
     * 
     * @param request
     * @param application
     * @param webApplicationContext
     * @throws ServletException
     * @throws MalformedURLException
     */
    private void startApplication(HttpServletRequest request,
            Application application, WebApplicationContext webApplicationContext)
            throws ServletException, MalformedURLException {

        if (!application.isRunning()) {
            // Create application
            final URL applicationUrl = getApplicationUrl(request);

            // Initial locale comes from the request
            Locale locale = request.getLocale();
            application.setLocale(locale);
            application.start(applicationUrl, applicationProperties,
                    webApplicationContext);
        }
    }

    /**
     * Check if this is a request for a static resource and, if it is, serve the
     * resource to the client.
     * 
     * @param request
     * @param response
     * @return true if a file was served and the request has been handled, false
     *         otherwise.
     * @throws IOException
     * @throws ServletException
     */
    private boolean serveStaticResources(HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException {

        // FIXME What does 10 refer to?
        String pathInfo = request.getPathInfo();
        if (pathInfo == null || pathInfo.length() <= 10) {
            return false;
        }

        if ((request.getContextPath() != null)
                && (request.getRequestURI().startsWith("/VAADIN/"))) {
            serveStaticResourcesInVAADIN(request.getRequestURI(), request,
                    response);
            return true;
        } else if (request.getRequestURI().startsWith(
                request.getContextPath() + "/VAADIN/")) {
            serveStaticResourcesInVAADIN(
                    request.getRequestURI().substring(
                            request.getContextPath().length()), request,
                    response);
            return true;
        }

        return false;
    }

    /**
     * Serve resources from VAADIN directory.
     * 
     * @param filename
     *            The filename to serve. Should always start with /VAADIN/.
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void serveStaticResourcesInVAADIN(String filename,
            HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        final ServletContext sc = getServletContext();
        URL resourceUrl = sc.getResource(filename);
        if (resourceUrl == null) {
            // try if requested file is found from classloader

            // strip leading "/" otherwise stream from JAR wont work
            filename = filename.substring(1);
            resourceUrl = getClassLoader().getResource(filename);

            if (resourceUrl == null) {
                // cannot serve requested file
                logger.info("Requested resource ["
                        + filename
                        + "] not found from filesystem or through class loader."
                        + " Add widgetset and/or theme JAR to your classpath or add files to WebContent/VAADIN folder.");
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        }

        // Find the modification timestamp
        long lastModifiedTime = 0;
        try {
            lastModifiedTime = resourceUrl.openConnection().getLastModified();
            // Remove milliseconds to avoid comparison problems (milliseconds
            // are not returned by the browser in the "If-Modified-Since"
            // header).
            lastModifiedTime = lastModifiedTime - lastModifiedTime % 1000;

            if (browserHasNewestVersion(request, lastModifiedTime)) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }
        } catch (Exception e) {
            // Failed to find out last modified timestamp. Continue without it.
            logger.log(
                    Level.FINEST,
                    "Failed to find out last modified timestamp. Continuing without it.",
                    e);
        }

        // Set type mime type if we can determine it based on the filename
        final String mimetype = sc.getMimeType(filename);
        if (mimetype != null) {
            response.setContentType(mimetype);
        }

        // Provide modification timestamp to the browser if it is known.
        if (lastModifiedTime > 0) {
            response.setDateHeader("Last-Modified", lastModifiedTime);
            /*
             * The browser is allowed to cache for 1 hour without checking if
             * the file has changed. This forces browsers to fetch a new version
             * when the Vaadin version is updated. This will cause more requests
             * to the servlet than without this but for high volume sites the
             * static files should never be served through the servlet. The
             * cache timeout can be configured by setting the resourceCacheTime
             * parameter in web.xml
             */
            response.setHeader("Cache-Control",
                    "max-age: " + String.valueOf(resourceCacheTime));
        }

        // Write the resource to the client.
        final OutputStream os = response.getOutputStream();
        final byte buffer[] = new byte[DEFAULT_BUFFER_SIZE];
        int bytes;
        InputStream is = resourceUrl.openStream();
        while ((bytes = is.read(buffer)) >= 0) {
            os.write(buffer, 0, bytes);
        }
        is.close();
    }

    /**
     * Checks if the browser has an up to date cached version of requested
     * resource. Currently the check is performed using the "If-Modified-Since"
     * header. Could be expanded if needed.
     * 
     * @param request
     *            The HttpServletRequest from the browser.
     * @param resourceLastModifiedTimestamp
     *            The timestamp when the resource was last modified. 0 if the
     *            last modification time is unknown.
     * @return true if the If-Modified-Since header tells the cached version in
     *         the browser is up to date, false otherwise
     */
    private boolean browserHasNewestVersion(HttpServletRequest request,
            long resourceLastModifiedTimestamp) {
        if (resourceLastModifiedTimestamp < 1) {
            // We do not know when it was modified so the browser cannot have an
            // up-to-date version
            return false;
        }
        /*
         * The browser can request the resource conditionally using an
         * If-Modified-Since header. Check this against the last modification
         * time.
         */
        try {
            // If-Modified-Since represents the timestamp of the version cached
            // in the browser
            long headerIfModifiedSince = request
                    .getDateHeader("If-Modified-Since");

            if (headerIfModifiedSince >= resourceLastModifiedTimestamp) {
                // Browser has this an up-to-date version of the resource
                return true;
            }
        } catch (Exception e) {
            // Failed to parse header. Fail silently - the browser does not have
            // an up-to-date version in its cache.
        }
        return false;
    }

    protected enum RequestType {
        FILE_UPLOAD, UIDL, OTHER, STATIC_FILE, APPLICATION_RESOURCE;
    }

    protected RequestType getRequestType(HttpServletRequest request) {
        if (isFileUploadRequest(request)) {
            return RequestType.FILE_UPLOAD;
        } else if (isUIDLRequest(request)) {
            return RequestType.UIDL;
        } else if (isStaticResourceRequest(request)) {
            return RequestType.STATIC_FILE;
        } else if (isApplicationRequest(request)) {
            return RequestType.APPLICATION_RESOURCE;
        } else if (request.getHeader("FileId") != null) {
            return RequestType.FILE_UPLOAD;
        }
        return RequestType.OTHER;

    }

    private boolean isApplicationRequest(HttpServletRequest request) {
        String path = getRequestPathInfo(request);
        if (path != null && path.startsWith("/APP/")) {
            return true;
        }
        return false;
    }

    private boolean isStaticResourceRequest(HttpServletRequest request) {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null || pathInfo.length() <= 10) {
            return false;
        }

        if ((request.getContextPath() != null)
                && (request.getRequestURI().startsWith("/VAADIN/"))) {
            return true;
        } else if (request.getRequestURI().startsWith(
                request.getContextPath() + "/VAADIN/")) {
            return true;
        }

        return false;
    }

    private boolean isUIDLRequest(HttpServletRequest request) {
        String pathInfo = getRequestPathInfo(request);

        if (pathInfo == null) {
            return false;
        }

        String compare = AJAX_UIDL_URI;

        if (pathInfo.startsWith(compare + "/") || pathInfo.endsWith(compare)) {
            return true;
        }

        return false;
    }

    private boolean isFileUploadRequest(HttpServletRequest request) {
        String pathInfo = getRequestPathInfo(request);

        if (pathInfo == null) {
            return false;
        }

        if (pathInfo.startsWith("/" + UPLOAD_URL_PREFIX)) {
            return true;
        }

        return false;

    }

    private boolean isOnUnloadRequest(HttpServletRequest request) {
        return request.getParameter(ApplicationConnection.PARAM_UNLOADBURST) != null;
    }

    /**
     * Get system messages from the current application class
     * 
     * @return
     */
    protected SystemMessages getSystemMessages() {
        try {
            Class<? extends Application> appCls = getApplicationClass();
            Method m = appCls.getMethod("getSystemMessages", (Class[]) null);
            return (Application.SystemMessages) m.invoke(null, (Object[]) null);
        } catch (ClassNotFoundException e) {
            // This should never happen
            throw new SystemMessageException(e);
        } catch (SecurityException e) {
            throw new SystemMessageException(
                    "Application.getSystemMessage() should be static public", e);
        } catch (NoSuchMethodException e) {
            // This is completely ok and should be silently ignored
        } catch (IllegalArgumentException e) {
            // This should never happen
            throw new SystemMessageException(e);
        } catch (IllegalAccessException e) {
            throw new SystemMessageException(
                    "Application.getSystemMessage() should be static public", e);
        } catch (InvocationTargetException e) {
            // This should never happen
            throw new SystemMessageException(e);
        }
        return Application.getSystemMessages();
    }

    protected abstract Class<? extends Application> getApplicationClass()
            throws ClassNotFoundException;

    /**
     * Return the URL from where static files, e.g. the widgetset and the theme,
     * are served. In a standard configuration the VAADIN folder inside the
     * returned folder is what is used for widgetsets and themes.
     * 
     * The returned folder is usually the same as the context path and
     * independent of the application.
     * 
     * @param request
     * @return The location of static resources (should contain the VAADIN
     *         directory). Never ends with a slash (/).
     */
    protected String getStaticFilesLocation(HttpServletRequest request) {

        // request may have an attribute explicitly telling location (portal
        // case)
        String staticFileLocation = (String) request
                .getAttribute(REQUEST_VAADIN_STATIC_FILE_PATH);
        if (staticFileLocation != null) {
            // TODO remove trailing slash if any?
            return staticFileLocation;
        }

        return getWebApplicationsStaticFileLocation(request);
    }

    /**
     * The default method to fetch static files location. This method does not
     * check for request attribute {@value #REQUEST_VAADIN_STATIC_FILE_PATH}.
     * 
     * @param request
     * @return
     */
    private String getWebApplicationsStaticFileLocation(
            HttpServletRequest request) {
        String staticFileLocation;
        // if property is defined in configurations, use that
        staticFileLocation = getApplicationOrSystemProperty(
                PARAMETER_VAADIN_RESOURCES, null);
        if (staticFileLocation != null) {
            return staticFileLocation;
        }

        // the last (but most common) option is to generate default location
        // from request

        // if context is specified add it to widgetsetUrl
        String ctxPath = request.getContextPath();

        // FIXME: ctxPath.length() == 0 condition is probably unnecessary and
        // might even be wrong.

        if (ctxPath.length() == 0
                && request.getAttribute("javax.servlet.include.context_path") != null) {
            // include request (e.g portlet), get context path from
            // attribute
            ctxPath = (String) request
                    .getAttribute("javax.servlet.include.context_path");
        }

        // Remove heading and trailing slashes from the context path
        ctxPath = removeHeadingOrTrailing(ctxPath, "/");

        if (ctxPath.equals("")) {
            return "";
        } else {
            return "/" + ctxPath;
        }
    }

    /**
     * Remove any heading or trailing "what" from the "string".
     * 
     * @param string
     * @param what
     * @return
     */
    private static String removeHeadingOrTrailing(String string, String what) {
        while (string.startsWith(what)) {
            string = string.substring(1);
        }

        while (string.endsWith(what)) {
            string = string.substring(0, string.length() - 1);
        }

        return string;
    }

    /**
     * Write a redirect response to the main page of the application.
     * 
     * @param request
     * @param response
     * @throws IOException
     *             if sending the redirect fails due to an input/output error or
     *             a bad application URL
     */
    private void redirectToApplication(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        String applicationUrl = getApplicationUrl(request).toExternalForm();
        response.sendRedirect(response.encodeRedirectURL(applicationUrl));
    }

    /**
     * This method writes the html host page (aka kickstart page) that starts
     * the actual Vaadin application.
     * <p>
     * If one needs to override parts of the host page, it is suggested that one
     * overrides on of several submethods which are called by this method:
     * <ul>
     * <li> {@link #setAjaxPageHeaders(HttpServletResponse)
     * <li> {@link #writeAjaxPageHtmlHeadStart(BufferedWriter, HttpServletRequest)
     * <li> {@link #writeAjaxPageHtmlHeader(BufferedWriter, String, String, HttpServletRequest)
     * <li> {@link #writeAjaxPageHtmlBodyStart(BufferedWriter, HttpServletRequest)
     * <li>
     * {@link #writeAjaxPageHtmlVaadinScripts(Window, String, Application, BufferedWriter, String, String, String, HttpServletRequest)
     * <li>
     * {@link #writeAjaxPageHtmlMainDiv(BufferedWriter, String, String, String, HttpServletRequest)
     * <li> {@link #writeAjaxPageHtmlBodyEnd(BufferedWriter)}
     * </ul>
     * 
     * @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.
     */
    protected void writeAjaxPage(HttpServletRequest request,
            HttpServletResponse response, Window window, Application application)
            throws IOException, MalformedURLException, ServletException {

        // e.g portlets only want a html fragment
        boolean fragment = (request.getAttribute(REQUEST_FRAGMENT) != null);
        if (fragment) {
            // if this is a fragment request, the actual application is put to
            // request so ApplicationPortlet can save it for a later use
            request.setAttribute(Application.class.getName(), application);
        }

        final BufferedWriter page = new BufferedWriter(new OutputStreamWriter(
                response.getOutputStream(), "UTF-8"));

        String title = ((window.getCaption() == null) ? "Vaadin 6" : window
                .getCaption());

        /* Fetch relative url to application */
        // don't use server and port in uri. It may cause problems with some
        // virtual server configurations which lose the server name
        String appUrl = getApplicationUrl(request).getPath();
        if (appUrl.endsWith("/")) {
            appUrl = appUrl.substring(0, appUrl.length() - 1);
        }

        String themeName = getThemeForWindow(request, window);

        String themeUri = getThemeUri(themeName, request);

        if (!fragment) {
            setAjaxPageHeaders(response);
            writeAjaxPageHtmlHeadStart(page, request);
            writeAjaxPageHtmlHeader(page, title, themeUri, request);
            writeAjaxPageHtmlBodyStart(page, request);
        }

        String appId = appUrl;
        if ("".equals(appUrl)) {
            appId = "ROOT";
        }
        appId = appId.replaceAll("[^a-zA-Z0-9]", "");
        // Add hashCode to the end, so that it is still (sort of) predictable,
        // but indicates that it should not be used in CSS and such:
        int hashCode = appId.hashCode();
        if (hashCode < 0) {
            hashCode = -hashCode;
        }
        appId = appId + "-" + hashCode;

        writeAjaxPageHtmlVaadinScripts(window, themeName, application, page,
                appUrl, themeUri, appId, request);

        /*- Add classnames;
         *      .v-app
         *      .v-app-loading
         *      .v-app-<simpleName for app class>
         *      .v-theme-<themeName, remove non-alphanum>
         */

        String appClass = "v-app-" + getApplicationCSSClassName();

        String themeClass = "";
        if (themeName != null) {
            themeClass = "v-theme-" + themeName.replaceAll("[^a-zA-Z0-9]", "");
        } else {
            themeClass = "v-theme-"
                    + getDefaultTheme().replaceAll("[^a-zA-Z0-9]", "");
        }

        String classNames = "v-app v-app-loading " + themeClass + " "
                + appClass;

        String divStyle = null;
        if (request.getAttribute(REQUEST_APPSTYLE) != null) {
            divStyle = "style=\"" + request.getAttribute(REQUEST_APPSTYLE)
                    + "\"";
        }

        writeAjaxPageHtmlMainDiv(page, appId, classNames, divStyle, request);

        if (!fragment) {
            page.write("</body>\n</html>\n");
        }

        page.close();

    }

    /**
     * Returns the application class identifier for use in the application CSS
     * class name in the root DIV. The application CSS class name is of form
     * "v-app-"+getApplicationCSSClassName().
     * 
     * This method should normally not be overridden.
     * 
     * @return The CSS class name to use in combination with "v-app-".
     */
    protected String getApplicationCSSClassName() {
        try {
            return getApplicationClass().getSimpleName();
        } catch (ClassNotFoundException e) {
            logger.log(Level.WARNING, "getApplicationCSSClassName failed", e);
            return "unknown";
        }
    }

    /**
     * Get the URI for the application theme.
     * 
     * A portal-wide default theme is fetched from the portal shared resource
     * directory (if any), other themes from the portlet.
     * 
     * @param themeName
     * @param request
     * @return
     */
    private String getThemeUri(String themeName, HttpServletRequest request) {
        final String staticFilePath;
        if (themeName.equals(request.getAttribute(REQUEST_DEFAULT_THEME))) {
            // our window theme is the portal wide default theme, make it load
            // from portals directory is defined
            staticFilePath = getStaticFilesLocation(request);
        } else {
            /*
             * theme is a custom theme, which is not necessarily located in
             * portals VAADIN directory. Let the default servlet conf decide
             * (omitting request parameter) the location. Note that theme can
             * still be placed to portal directory with servlet parameter.
             */
            staticFilePath = getWebApplicationsStaticFileLocation(request);
        }
        return staticFilePath + "/" + THEME_DIRECTORY_PATH + themeName;
    }

    /**
     * Method to write the div element into which that actual Vaadin application
     * is rendered.
     * <p>
     * Override this method if you want to add some custom html around around
     * the div element into which the actual Vaadin application will be
     * rendered.
     * 
     * @param page
     * @param appId
     * @param classNames
     * @param divStyle
     * @param request 
     * @throws IOException
     */
    protected void writeAjaxPageHtmlMainDiv(final BufferedWriter page,
            String appId, String classNames, String divStyle, HttpServletRequest request)
            throws IOException {
        page.write("<div id=\"" + appId + "\" class=\"" + classNames + "\" "
                + (divStyle != null ? divStyle : "") + "></div>\n");
        page.write("<noscript>" + getNoScriptMessage() + "</noscript>");
    }

    /**
     * Method to write the script part of the page which loads needed Vaadin
     * scripts and themes.
     * <p>
     * Override this method if you want to add some custom html around scripts.
     * 
     * @param window
     * @param themeName
     * @param application
     * @param page
     * @param appUrl
     * @param themeUri
     * @param appId
     * @param request
     * @throws ServletException
     * @throws IOException
     */
    protected void writeAjaxPageHtmlVaadinScripts(Window window,
            String themeName, Application application,
            final BufferedWriter page, String appUrl, String themeUri,
            String appId, HttpServletRequest request) throws ServletException,
            IOException {

        // request widgetset takes precedence (e.g portlet include)
        String requestWidgetset = (String) request
                .getAttribute(REQUEST_WIDGETSET);
        String sharedWidgetset = (String) request
                .getAttribute(REQUEST_SHARED_WIDGETSET);
        if (requestWidgetset == null && sharedWidgetset == null) {
            // Use the value from configuration or DEFAULT_WIDGETSET.
            // If no shared widgetset is specified, the default widgetset is
            // assumed to be in the servlet/portlet itself.
            requestWidgetset = getApplicationOrSystemProperty(
                    PARAMETER_WIDGETSET, DEFAULT_WIDGETSET);
        }

        String widgetset;
        String widgetsetBasePath;
        if (requestWidgetset != null) {
            widgetset = requestWidgetset;
            widgetsetBasePath = getWebApplicationsStaticFileLocation(request);
        } else {
            widgetset = sharedWidgetset;
            widgetsetBasePath = getStaticFilesLocation(request);
        }

        widgetset = stripSpecialChars(widgetset);

        final String widgetsetFilePath = widgetsetBasePath + "/"
                + WIDGETSET_DIRECTORY_PATH + widgetset + "/" + widgetset
                + ".nocache.js?" + new Date().getTime();

        // Get system messages
        Application.SystemMessages systemMessages = null;
        try {
            systemMessages = getSystemMessages();
        } catch (SystemMessageException e) {
            // failing to get the system messages is always a problem
            throw new ServletException("CommunicationError!", e);
        }

        page.write("<script type=\"text/javascript\">\n");
        page.write("//<![CDATA[\n");
        page.write("if(!vaadin || !vaadin.vaadinConfigurations) {\n "
                + "if(!vaadin) { var vaadin = {}} \n"
                + "vaadin.vaadinConfigurations = {};\n"
                + "if (!vaadin.themesLoaded) { vaadin.themesLoaded = {}; }\n");
        if (!isProductionMode()) {
            page.write("vaadin.debug = true;\n");
        }
        page.write("document.write('<iframe tabIndex=\"-1\" id=\"__gwt_historyFrame\" "
                + "style=\"position:absolute;width:0;height:0;border:0;overflow:"
                + "hidden;\" src=\"javascript:false\"></iframe>');\n");
        page.write("document.write(\"<script language='javascript' src='"
                + widgetsetFilePath + "'><\\/script>\");\n}\n");

        page.write("vaadin.vaadinConfigurations[\"" + appId + "\"] = {");
        page.write("appUri:'" + appUrl + "', ");

        if (window != application.getMainWindow()) {
            page.write("windowName: \""
                    + JsonPaintTarget.escapeJSON(window.getName()) + "\", ");
        }
        page.write("themeUri:");
        page.write(themeUri != null ? "\"" + themeUri + "\"" : "null");
        page.write(", versionInfo : {vaadinVersion:\"");
        page.write(VERSION);
        page.write("\",applicationVersion:\"");
        page.write(JsonPaintTarget.escapeJSON(application.getVersion()));
        page.write("\"}");
        if (systemMessages != null) {
            // Write the CommunicationError -message to client
            String caption = systemMessages.getCommunicationErrorCaption();
            if (caption != null) {
                caption = "\"" + JsonPaintTarget.escapeJSON(caption) + "\"";
            }
            String message = systemMessages.getCommunicationErrorMessage();
            if (message != null) {
                message = "\"" + JsonPaintTarget.escapeJSON(message) + "\"";
            }
            String url = systemMessages.getCommunicationErrorURL();
            if (url != null) {
                url = "\"" + JsonPaintTarget.escapeJSON(url) + "\"";
            }

            page.write(",\"comErrMsg\": {" + "\"caption\":" + caption + ","
                    + "\"message\" : " + message + "," + "\"url\" : " + url
                    + "}");

            // Write the AuthenticationError -message to client
            caption = systemMessages.getAuthenticationErrorCaption();
            if (caption != null) {
                caption = "\"" + JsonPaintTarget.escapeJSON(caption) + "\"";
            }
            message = systemMessages.getAuthenticationErrorMessage();
            if (message != null) {
                message = "\"" + JsonPaintTarget.escapeJSON(message) + "\"";
            }
            url = systemMessages.getAuthenticationErrorURL();
            if (url != null) {
                url = "\"" + JsonPaintTarget.escapeJSON(url) + "\"";
            }

            page.write(",\"authErrMsg\": {" + "\"caption\":" + caption + ","
                    + "\"message\" : " + message + "," + "\"url\" : " + url
                    + "}");
        }
        page.write("};\n//]]>\n</script>\n");

        if (themeName != null) {
            // Custom theme's stylesheet, load only once, in different
            // script
            // tag to be dominate styles injected by widget
            // set
            page.write("<script type=\"text/javascript\">\n");
            page.write("//<![CDATA[\n");
            page.write("if(!vaadin.themesLoaded['" + themeName + "']) {\n");
            page.write("var stylesheet = document.createElement('link');\n");
            page.write("stylesheet.setAttribute('rel', 'stylesheet');\n");
            page.write("stylesheet.setAttribute('type', 'text/css');\n");
            page.write("stylesheet.setAttribute('href', '" + themeUri
                    + "/styles.css');\n");
            page.write("document.getElementsByTagName('head')[0].appendChild(stylesheet);\n");
            page.write("vaadin.themesLoaded['" + themeName + "'] = true;\n}\n");
            page.write("//]]>\n</script>\n");
        }

        // Warn if the widgetset has not been loaded after 15 seconds on
        // inactivity
        page.write("<script type=\"text/javascript\">\n");
        page.write("//<![CDATA[\n");
        page.write("setTimeout('if (typeof " + widgetset.replace('.', '_')
                + " == \"undefined\") {alert(\"Failed to load the widgetset: "
                + widgetsetFilePath + "\")};',15000);\n" + "//]]>\n</script>\n");
    }

    /**
     * 
     * Method to open the body tag of the html kickstart page.
     * <p>
     * This method is responsible for closing the head tag and opening the body
     * tag.
     * <p>
     * Override this method if you want to add some custom html to the page.
     * 
     * @param page
     * @param request
     * @throws IOException
     */
    protected void writeAjaxPageHtmlBodyStart(final BufferedWriter page,
            final HttpServletRequest request) throws IOException {
        page.write("\n</head>\n<body scroll=\"auto\" class=\""
                + ApplicationConnection.GENERATED_BODY_CLASSNAME + "\">\n");
    }

    /**
     * Method to write the contents of head element in html kickstart page.
     * <p>
     * Override this method if you want to add some custom html to the header of
     * the page.
     * 
     * @param page
     * @param title
     * @param themeUri
     * @param request
     * @throws IOException
     */
    protected void writeAjaxPageHtmlHeader(final BufferedWriter page,
            String title, String themeUri, final HttpServletRequest request)
            throws IOException {
        page.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\n");

        WebBrowser browser = getApplicationContext(request.getSession())
                .getBrowser();
        if (browser.isIE()) {
            // Chrome frame in all versions of IE (only if Chrome frame is
            // installed)
            if (browser.getBrowserMajorVersion() == 9) {
                // Force IE9 into IE8 mode. Remove when IE 9 mode works (#5546)
                page.write("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=8,chrome=1\"/>\n");
            } else {
                page.write("<meta http-equiv=\"X-UA-Compatible\" content=\"chrome=1\"/>\n");
            }
        }

        page.write("<style type=\"text/css\">"
                + "html, body {height:100%;margin:0;}</style>");

        // Add favicon links
        page.write("<link rel=\"shortcut icon\" type=\"image/vnd.microsoft.icon\" href=\""
                + themeUri + "/favicon.ico\" />");
        page.write("<link rel=\"icon\" type=\"image/vnd.microsoft.icon\" href=\""
                + themeUri + "/favicon.ico\" />");

        page.write("<title>" + safeEscapeForHtml(title) + "</title>");
    }

    /**
     * Method to write the beginning of the html page.
     * <p>
     * This method is responsible for writing appropriate doc type declarations
     * and to open html and head tags.
     * <p>
     * Override this method if you want to add some custom html to the very
     * beginning of the page.
     * 
     * @param page
     * @param request
     * @throws IOException
     */
    protected void writeAjaxPageHtmlHeadStart(final BufferedWriter page,
            final HttpServletRequest request) throws IOException {
        // write html header
        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 xmlns=\"http://www.w3.org/1999/xhtml\""
                + ">\n<head>\n");
    }

    /**
     * Method to set http request headers for the Vaadin kickstart page.
     * <p>
     * Override this method if you need to customize http headers of the page.
     * 
     * @param response
     */
    protected void setAjaxPageHeaders(HttpServletResponse response) {
        // Window renders are not cacheable
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("text/html; charset=UTF-8");
    }

    /**
     * Returns a message printed for browsers without scripting support or if
     * browsers scripting support is disabled.
     */
    protected String getNoScriptMessage() {
        return "You have to enable javascript in your browser to use an application built with Vaadin.";
    }

    /**
     * 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.
     */
    protected URL getApplicationUrl(HttpServletRequest request)
            throws MalformedURLException {
        final 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 = "";
        if (request.getAttribute("javax.servlet.include.servlet_path") != null) {
            // this is an include request
            servletPath = request.getAttribute(
                    "javax.servlet.include.context_path").toString()
                    + request
                            .getAttribute("javax.servlet.include.servlet_path");

        } else {
            servletPath = request.getContextPath() + request.getServletPath();
        }

        if (servletPath.length() == 0
                || servletPath.charAt(servletPath.length() - 1) != '/') {
            servletPath = servletPath + "/";
        }
        URL u = new URL(reqURL, servletPath);
        return u;
    }

    /**
     * Gets the existing application for given request. Looks for application
     * instance for given request based on the requested URL.
     * 
     * @param request
     *            the HTTP request.
     * @param allowSessionCreation
     *            true if a session should be created if no session exists,
     *            false if no session should be created
     * @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.
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws SessionExpiredException
     */
    protected Application getExistingApplication(HttpServletRequest request,
            boolean allowSessionCreation) throws MalformedURLException,
            SessionExpiredException {

        // Ensures that the session is still valid
        final HttpSession session = request.getSession(allowSessionCreation);
        if (session == null) {
            throw new SessionExpiredException();
        }

        WebApplicationContext context = getApplicationContext(session);

        // Gets application list for the session.
        final Collection<Application> applications = context.getApplications();

        // Search for the application (using the application URI) from the list
        for (final Iterator<Application> i = applications.iterator(); i
                .hasNext();) {
            final Application sessionApplication = i.next();
            final String sessionApplicationPath = sessionApplication.getURL()
                    .getPath();
            String requestApplicationPath = getApplicationUrl(request)
                    .getPath();

            if (requestApplicationPath.equals(sessionApplicationPath)) {
                // Found a running application
                if (sessionApplication.isRunning()) {
                    return sessionApplication;
                }
                // Application has stopped, so remove it before creating a new
                // application
                getApplicationContext(session).removeApplication(
                        sessionApplication);
                break;
            }
        }

        // Existing application not found
        return null;
    }

    /**
     * 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();
        }

        final HttpSession session = request.getSession();
        if (session != null) {
            getApplicationContext(session).removeApplication(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 matching 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,
            CommunicationManager applicationManager, Application application)
            throws ServletException {

        // Finds the window where the request is handled
        Window assumedWindow = null;
        String path = getRequestPathInfo(request);

        // Main window as the URI is empty
        if (!(path == null || path.length() == 0 || path.equals("/"))) {
            if (path.startsWith("/APP/")) {
                // Use main window for application resources
                return application.getMainWindow();
            }
            String windowName = null;
            if (path.charAt(0) == '/') {
                path = path.substring(1);
            }
            final int index = path.indexOf('/');
            if (index < 0) {
                windowName = path;
                path = "";
            } else {
                windowName = path.substring(0, index);
            }
            assumedWindow = application.getWindow(windowName);

        }

        return applicationManager.getApplicationWindow(request, this,
                application, assumedWindow);
    }

    /**
     * Returns the path info; note that this _can_ be different than
     * request.getPathInfo() (e.g application runner).
     * 
     * @param request
     * @return
     */
    String getRequestPathInfo(HttpServletRequest request) {
        return request.getPathInfo();
    }

    /**
     * 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();
    }

    private boolean isRepaintAll(HttpServletRequest request) {
        return (request.getParameter(URL_PARAMETER_REPAINT_ALL) != null)
                && (request.getParameter(URL_PARAMETER_REPAINT_ALL).equals("1"));
    }

    private void closeApplication(Application application, HttpSession session) {
        if (application == null) {
            return;
        }

        application.close();
        if (session != null) {
            WebApplicationContext context = getApplicationContext(session);
            context.removeApplication(application);
        }
    }

    /**
     * 
     * Gets the application context from an HttpSession. If no context is
     * currently stored in a session a new context is created and stored in the
     * session.
     * 
     * @param session
     *            the HTTP session.
     * @return the application context for HttpSession.
     */
    protected WebApplicationContext getApplicationContext(HttpSession session) {
        /*
         * TODO the ApplicationContext.getApplicationContext() should be removed
         * and logic moved here. Now overriding context type is possible, but
         * the whole creation logic should be here. MT 1101
         */
        return WebApplicationContext.getApplicationContext(session);
    }

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

        private ParameterHandler owner;

        private Throwable throwable;

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

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

    }

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

        private final URIHandler owner;

        private final Throwable throwable;

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

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

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

    public class RequestError implements Terminal.ErrorEvent, Serializable {

        private final Throwable throwable;

        public RequestError(Throwable throwable) {
            this.throwable = throwable;
        }

        public Throwable getThrowable() {
            return throwable;
        }

    }

    /**
     * Override this method if you need to use a specialized communicaiton
     * mananger implementation.
     * 
     * @deprecated Instead of overriding this method, override
     *             {@link WebApplicationContext} implementation via
     *             {@link AbstractApplicationServlet#getApplicationContext(HttpSession)}
     *             method and in that customized implementation return your
     *             CommunicationManager in
     *             {@link WebApplicationContext#getApplicationManager(Application, AbstractApplicationServlet)}
     *             method.
     * 
     * @param application
     * @return
     */
    @Deprecated
    public CommunicationManager createCommunicationManager(
            Application application) {
        return new CommunicationManager(application);
    }

    /**
     * Escapes characters to html entities. An exception is made for some
     * "safe characters" to keep the text somewhat readable.
     * 
     * @param unsafe
     * @return a safe string to be added inside an html tag
     */
    protected static final String safeEscapeForHtml(String unsafe) {
        StringBuilder safe = new StringBuilder();
        char[] charArray = unsafe.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            char c = charArray[i];
            if (isSafe(c)) {
                safe.append(c);
            } else {
                safe.append("&#");
                safe.append((int) c);
                safe.append(";");
            }
        }

        return safe.toString();
    }

    private static boolean isSafe(char c) {
        return //
        c > 47 && c < 58 || // alphanum
                c > 64 && c < 91 || // A-Z
                c > 96 && c < 123 // a-z
        ;
    }
}