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
|
/*
@VaadinApache2LicenseForJavaFiles@
*/
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.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.MimeResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletContext;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import javax.portlet.PortletSession;
import javax.portlet.PortletURL;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ResourceURL;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import com.liferay.portal.kernel.util.PortalClassInvoker;
import com.liferay.portal.kernel.util.PropsUtil;
import com.vaadin.Application;
import com.vaadin.Application.SystemMessages;
import com.vaadin.terminal.Terminal;
import com.vaadin.terminal.WrappedRequest;
import com.vaadin.terminal.WrappedResponse;
import com.vaadin.terminal.gwt.client.ApplicationConfiguration;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.server.AbstractCommunicationManager.Callback;
import com.vaadin.ui.Root;
/**
* Portlet 2.0 base class. This replaces the servlet in servlet/portlet 1.0
* deployments and handles various portlet requests from the browser.
*
* TODO Document me!
*
* @author peholmst
*/
public abstract class AbstractApplicationPortlet extends GenericPortlet
implements Constants {
private static final Logger logger = Logger
.getLogger(AbstractApplicationPortlet.class.getName());
private static class WrappedHttpAndPortletRequest extends
WrappedPortletRequest {
public WrappedHttpAndPortletRequest(PortletRequest request,
HttpServletRequest originalRequest) {
super(request);
this.originalRequest = originalRequest;
}
private final HttpServletRequest originalRequest;
@Override
public String getParameter(String name) {
String parameter = super.getParameter(name);
if (parameter == null) {
parameter = originalRequest.getParameter(name);
}
return parameter;
}
@Override
public String getRemoteAddr() {
return originalRequest.getRemoteAddr();
}
@Override
public String getHeader(String name) {
String header = super.getHeader(name);
if (header == null) {
header = originalRequest.getHeader(name);
}
return header;
}
@Override
public Map<String, String[]> getParameterMap() {
Map<String, String[]> parameterMap = super.getParameterMap();
if (parameterMap == null) {
parameterMap = originalRequest.getParameterMap();
}
return parameterMap;
}
}
private static class WrappedGateinRequest extends
WrappedHttpAndPortletRequest {
public WrappedGateinRequest(PortletRequest request) {
super(request, getOriginalRequest(request));
}
private static final HttpServletRequest getOriginalRequest(
PortletRequest request) {
try {
Method getRealReq = request.getClass().getMethod(
"getRealRequest");
HttpServletRequestWrapper origRequest = (HttpServletRequestWrapper) getRealReq
.invoke(request);
return origRequest;
} catch (Exception e) {
throw new IllegalStateException("GateIn request not detected",
e);
}
}
}
private static class WrappedLiferayRequest extends
WrappedHttpAndPortletRequest {
public WrappedLiferayRequest(PortletRequest request) {
super(request, getOriginalRequest(request));
}
@Override
public String getPortalProperty(String name) {
return PropsUtil.get(name);
}
private static HttpServletRequest getOriginalRequest(
PortletRequest request) {
try {
// httpRequest = PortalUtil.getHttpServletRequest(request);
HttpServletRequest httpRequest = (HttpServletRequest) PortalClassInvoker
.invoke("com.liferay.portal.util.PortalUtil",
"getHttpServletRequest", request);
// httpRequest =
// PortalUtil.getOriginalServletRequest(httpRequest);
httpRequest = (HttpServletRequest) PortalClassInvoker.invoke(
"com.liferay.portal.util.PortalUtil",
"getOriginalServletRequest", httpRequest);
return httpRequest;
} catch (Exception e) {
throw new IllegalStateException("Liferay request not detected",
e);
}
}
}
private static class AbstractApplicationPortletWrapper implements Callback {
private final AbstractApplicationPortlet portlet;
public AbstractApplicationPortletWrapper(
AbstractApplicationPortlet portlet) {
this.portlet = portlet;
}
public void criticalNotification(WrappedRequest request,
WrappedResponse response, String cap, String msg,
String details, String outOfSyncURL) throws IOException {
PortletRequest portletRequest = ((WrappedPortletRequest) request)
.getPortletRequest();
PortletResponse portletResponse = ((WrappedPortletResponse) response)
.getPortletResponse();
portlet.criticalNotification(portletRequest,
(MimeResponse) portletResponse, cap, msg, details,
outOfSyncURL);
}
public InputStream getThemeResourceAsStream(String themeName,
String resource) throws IOException {
return portlet.getPortletContext().getResourceAsStream(
"/" + AbstractApplicationPortlet.THEME_DIRECTORY_PATH
+ themeName + "/" + resource);
}
}
/**
* This portlet parameter is used to add styles to the main element. E.g
* "height:500px" generates a style="height:500px" to the main element.
*/
public static final String PORTLET_PARAMETER_STYLE = "style";
private static final String PORTAL_PARAMETER_VAADIN_THEME = "vaadin.theme";
// TODO some parts could be shared with AbstractApplicationServlet
// TODO Can we close the application when the portlet is removed? Do we know
// when the portlet is removed?
// TODO What happens when the portlet window is resized? Do we know when the
// window is resized?
private Properties applicationProperties;
private boolean productionMode = false;
@Override
public void init(PortletConfig config) throws PortletException {
super.init(config);
// Stores the application parameters into Properties object
applicationProperties = new Properties();
for (final Enumeration<String> e = config.getInitParameterNames(); e
.hasMoreElements();) {
final String name = e.nextElement();
applicationProperties.setProperty(name,
config.getInitParameter(name));
}
// Overrides with server.xml parameters
final PortletContext context = config.getPortletContext();
for (final Enumeration<String> e = context.getInitParameterNames(); e
.hasMoreElements();) {
final String name = e.nextElement();
applicationProperties.setProperty(name,
context.getInitParameter(name));
}
checkProductionMode();
checkCrossSiteProtection();
}
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);
}
}
/**
* Checks that the version reported by the client (widgetset) matches that
* of the server.
*
* @param request
*/
private void checkWidgetsetVersion(WrappedRequest request) {
if (!AbstractApplicationServlet.VERSION.equals(request
.getParameter("wsver"))) {
logger.warning(String.format(WIDGETSET_MISMATCH_INFO,
AbstractApplicationServlet.VERSION,
request.getParameter("wsver")));
}
}
private void checkProductionMode() {
// TODO Identical code in AbstractApplicationServlet -> refactor
// Check if the application is in production mode.
// We are in production mode if productionMode=true
if (getApplicationOrSystemProperty(SERVLET_PARAMETER_PRODUCTION_MODE,
"false").equals("true")) {
productionMode = true;
}
if (!productionMode) {
/* Print an information/warning message about running in debug mode */
// TODO Maybe we need a different message for portlets?
logger.warning(NOT_PRODUCTION_MODE_INFO);
}
}
/**
* 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
*/
protected 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;
}
protected enum RequestType {
FILE_UPLOAD, UIDL, RENDER, STATIC_FILE, APPLICATION_RESOURCE, DUMMY, EVENT, ACTION, UNKNOWN;
}
protected RequestType getRequestType(PortletRequest request) {
if (request instanceof RenderRequest) {
return RequestType.RENDER;
} else if (request instanceof ResourceRequest) {
if (isUIDLRequest((ResourceRequest) request)) {
return RequestType.UIDL;
} else if (isFileUploadRequest((ResourceRequest) request)) {
return RequestType.FILE_UPLOAD;
} else if (isApplicationResourceRequest((ResourceRequest) request)) {
return RequestType.APPLICATION_RESOURCE;
} else if (isDummyRequest((ResourceRequest) request)) {
return RequestType.DUMMY;
} else {
return RequestType.STATIC_FILE;
}
} else if (request instanceof ActionRequest) {
return RequestType.ACTION;
} else if (request instanceof EventRequest) {
return RequestType.EVENT;
}
return RequestType.UNKNOWN;
}
private boolean isApplicationResourceRequest(ResourceRequest request) {
return request.getResourceID() != null
&& request.getResourceID().startsWith("APP");
}
private boolean isUIDLRequest(ResourceRequest request) {
return request.getResourceID() != null
&& request.getResourceID().equals("UIDL");
}
private boolean isDummyRequest(ResourceRequest request) {
return request.getResourceID() != null
&& request.getResourceID().equals("DUMMY");
}
private boolean isFileUploadRequest(ResourceRequest request) {
return "UPLOAD".equals(request.getResourceID());
}
/**
* 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;
}
protected void handleRequest(PortletRequest request,
PortletResponse response) throws PortletException, IOException {
AbstractApplicationPortletWrapper portletWrapper = new AbstractApplicationPortletWrapper(
this);
WrappedPortletRequest wrappedRequest;
String portalInfo = request.getPortalContext().getPortalInfo()
.toLowerCase();
if (portalInfo.contains("liferay")) {
wrappedRequest = new WrappedLiferayRequest(request);
} else if (portalInfo.contains("gatein")) {
wrappedRequest = new WrappedGateinRequest(request);
} else {
wrappedRequest = new WrappedPortletRequest(request);
}
WrappedPortletResponse wrappedResponse = new WrappedPortletResponse(
response);
RequestType requestType = getRequestType(request);
if (requestType == RequestType.UNKNOWN) {
handleUnknownRequest(request, response);
} else if (requestType == RequestType.DUMMY) {
/*
* This dummy page is used by action responses to redirect to, in
* order to prevent the boot strap code from being rendered into
* strange places such as iframes.
*/
((ResourceResponse) response).setContentType("text/html");
final OutputStream out = ((ResourceResponse) response)
.getPortletOutputStream();
final PrintWriter outWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(out, "UTF-8")));
outWriter.print("<html><body>dummy page</body></html>");
outWriter.close();
} else if (requestType == RequestType.STATIC_FILE) {
serveStaticResources((ResourceRequest) request,
(ResourceResponse) response);
} else {
Application application = null;
boolean transactionStarted = false;
boolean requestStarted = false;
try {
// TODO What about PARAM_UNLOADBURST & redirectToApplication??
/* Find out which application this request is related to */
application = findApplicationInstance(wrappedRequest,
requestType);
if (application == null) {
return;
}
Application.setCurrentApplication(application);
/*
* Get or create an application context and an application
* manager for the session
*/
PortletApplicationContext2 applicationContext = getApplicationContext(request
.getPortletSession());
applicationContext.setResponse(response);
applicationContext.setPortletConfig(getPortletConfig());
PortletCommunicationManager applicationManager = applicationContext
.getApplicationManager(application);
/* Update browser information from request */
applicationContext.getBrowser().updateRequestDetails(
wrappedRequest);
/*
* Call application requestStart before Application.init() is
* called (bypasses the limitation in TransactionListener)
*/
if (application instanceof PortletRequestListener) {
((PortletRequestListener) application).onRequestStart(
request, response);
requestStarted = true;
}
/* Start the newly created application */
startApplication(request, application, applicationContext);
/*
* Transaction starts. Call transaction listeners. Transaction
* end is called in the finally block below.
*/
applicationContext.startTransaction(application, request);
transactionStarted = true;
/* Notify listeners */
// Finds the window within the application
Root root = null;
synchronized (application) {
if (application.isRunning()) {
switch (requestType) {
case FILE_UPLOAD:
// no window
break;
case APPLICATION_RESOURCE:
// use main window - should not need any window
// root = application.getRoot();
break;
default:
root = application
.getRootForRequest(wrappedRequest);
}
// if window not found, not a problem - use null
}
}
// TODO Should this happen before or after the transaction
// starts?
if (request instanceof RenderRequest) {
applicationContext.firePortletRenderRequest(application,
root, (RenderRequest) request,
(RenderResponse) response);
} else if (request instanceof ActionRequest) {
applicationContext.firePortletActionRequest(application,
root, (ActionRequest) request,
(ActionResponse) response);
} else if (request instanceof EventRequest) {
applicationContext.firePortletEventRequest(application,
root, (EventRequest) request,
(EventResponse) response);
} else if (request instanceof ResourceRequest) {
applicationContext.firePortletResourceRequest(application,
root, (ResourceRequest) request,
(ResourceResponse) response);
}
/* Handle the request */
if (requestType == RequestType.FILE_UPLOAD) {
applicationManager.handleFileUpload(wrappedRequest,
wrappedResponse);
return;
} else if (requestType == RequestType.UIDL) {
// Handles AJAX UIDL requests
if (isRepaintAll(request)) {
// warn if versions do not match
checkWidgetsetVersion(wrappedRequest);
}
applicationManager.handleUidlRequest(wrappedRequest,
wrappedResponse, portletWrapper, root);
return;
} else {
/*
* Removes the application if it has stopped
*/
if (!application.isRunning()) {
endApplication(request, response, application);
return;
}
handleOtherRequest(wrappedRequest, wrappedResponse,
requestType, application, root, applicationContext,
applicationManager);
}
} catch (final SessionExpiredException e) {
// TODO Figure out a better way to deal with
// SessionExpiredExceptions
logger.finest("A user session has expired");
} catch (final GeneralSecurityException e) {
// TODO Figure out a better way to deal with
// GeneralSecurityExceptions
logger.fine("General security exception, the security key was probably incorrect.");
} catch (final Throwable e) {
handleServiceException(request, response, application, e);
} finally {
// Notifies transaction end
try {
if (transactionStarted) {
((PortletApplicationContext2) application.getContext())
.endTransaction(application, request);
}
} finally {
try {
if (requestStarted) {
((PortletRequestListener) application)
.onRequestEnd(request, response);
}
} finally {
Root.setCurrentRoot(null);
Application.setCurrentApplication(null);
}
}
}
}
}
private void handleUnknownRequest(PortletRequest request,
PortletResponse response) {
logger.warning("Unknown request type");
}
/**
* Handle a portlet request that is not for static files, UIDL or upload.
* Also render requests are handled here.
*
* This method is called after starting the application and calling portlet
* and transaction listeners.
*
* @param request
* @param response
* @param requestType
* @param application
* @param applicationContext
* @param applicationManager
* @throws PortletException
* @throws IOException
* @throws MalformedURLException
*/
private void handleOtherRequest(WrappedPortletRequest request,
WrappedResponse response, RequestType requestType,
Application application, Root root,
PortletApplicationContext2 applicationContext,
PortletCommunicationManager applicationManager)
throws PortletException, IOException, MalformedURLException {
if (root == null) {
throw new PortletException(ERROR_NO_WINDOW_FOUND);
}
if (requestType == RequestType.APPLICATION_RESOURCE) {
if (!applicationManager.handleApplicationRequest(request, response)) {
response.setStatus(404);
}
} else if (requestType == RequestType.RENDER) {
PortletResponse portletResponse = ((WrappedPortletResponse) response)
.getPortletResponse();
writeAjaxPage(request, (RenderResponse) portletResponse, root,
application);
} else if (requestType == RequestType.EVENT) {
// nothing to do, listeners do all the work
} else if (requestType == RequestType.ACTION) {
// nothing to do, listeners do all the work
} else {
throw new IllegalStateException(
"handleRequest() without anything to do - should never happen!");
}
}
@Override
public void processEvent(EventRequest request, EventResponse response)
throws PortletException, IOException {
handleRequest(request, response);
}
private void serveStaticResources(ResourceRequest request,
ResourceResponse response) throws IOException, PortletException {
final String resourceID = request.getResourceID();
final PortletContext pc = getPortletContext();
InputStream is = pc.getResourceAsStream(resourceID);
if (is != null) {
final String mimetype = pc.getMimeType(resourceID);
if (mimetype != null) {
response.setContentType(mimetype);
}
final OutputStream os = response.getPortletOutputStream();
final byte buffer[] = new byte[DEFAULT_BUFFER_SIZE];
int bytes;
while ((bytes = is.read(buffer)) >= 0) {
os.write(buffer, 0, bytes);
}
} else {
logger.info("Requested resource [" + resourceID
+ "] could not be found");
response.setProperty(ResourceResponse.HTTP_STATUS_CODE,
Integer.toString(HttpServletResponse.SC_NOT_FOUND));
}
}
@Override
public void processAction(ActionRequest request, ActionResponse response)
throws PortletException, IOException {
handleRequest(request, response);
}
@Override
protected void doDispatch(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
try {
// try to let super handle - it'll call methods annotated for
// handling, the default doXYZ(), or throw if a handler for the mode
// is not found
super.doDispatch(request, response);
} catch (PortletException e) {
if (e.getCause() == null) {
// No cause interpreted as 'unknown mode' - pass that trough
// so that the application can handle
handleRequest(request, response);
} else {
// Something else failed, pass on
throw e;
}
}
}
@Override
public void serveResource(ResourceRequest request, ResourceResponse response)
throws PortletException, IOException {
handleRequest(request, response);
}
boolean requestCanCreateApplication(PortletRequest request,
RequestType requestType) {
if (requestType == RequestType.UIDL && isRepaintAll(request)) {
return true;
} else if (requestType == RequestType.RENDER) {
// In most cases the first request is a render request that renders
// the HTML fragment. This should create an application instance.
return true;
} else if (requestType == RequestType.EVENT) {
// A portlet can also be sent an event even though it has not been
// rendered, e.g. portlet on one page sends an event to a portlet on
// another page and then moves the user to that page.
return true;
}
return false;
}
private boolean isRepaintAll(PortletRequest request) {
return (request.getParameter(URL_PARAMETER_REPAINT_ALL) != null)
&& (request.getParameter(URL_PARAMETER_REPAINT_ALL).equals("1"));
}
private void startApplication(PortletRequest request,
Application application, PortletApplicationContext2 context)
throws PortletException, MalformedURLException {
if (!application.isRunning()) {
Locale locale = request.getLocale();
application.setLocale(locale);
// No application URL when running inside a portlet
application.start(null, applicationProperties, context,
isProductionMode());
}
}
private void endApplication(PortletRequest request,
PortletResponse response, Application application)
throws IOException {
final PortletSession session = request.getPortletSession();
if (session != null) {
getApplicationContext(session).removeApplication(application);
}
// Do not send any redirects when running inside a portlet.
}
private Application findApplicationInstance(
WrappedPortletRequest wrappedRequest, RequestType requestType)
throws PortletException, SessionExpiredException,
MalformedURLException {
PortletRequest request = wrappedRequest.getPortletRequest();
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 = (wrappedRequest
.getParameter(URL_PARAMETER_RESTART_APPLICATION) != null);
final boolean closeApplication = (wrappedRequest
.getParameter(URL_PARAMETER_CLOSE_APPLICATION) != null);
if (restartApplication) {
closeApplication(application, request.getPortletSession(false));
return createApplication(request);
} else if (closeApplication) {
closeApplication(application, request.getPortletSession(false));
return null;
} else {
return application;
}
}
// No existing application was found
if (requestCanCreateApplication) {
return createApplication(request);
} else {
throw new SessionExpiredException();
}
}
private void closeApplication(Application application,
PortletSession session) {
if (application == null) {
return;
}
application.close();
if (session != null) {
PortletApplicationContext2 context = getApplicationContext(session);
context.removeApplication(application);
}
}
private Application createApplication(PortletRequest request)
throws PortletException, MalformedURLException {
Application newApplication = getNewApplication(request);
final PortletApplicationContext2 context = getApplicationContext(request
.getPortletSession());
context.addApplication(newApplication, request.getWindowID());
return newApplication;
}
private Application getExistingApplication(PortletRequest request,
boolean allowSessionCreation) throws MalformedURLException,
SessionExpiredException {
final PortletSession session = request
.getPortletSession(allowSessionCreation);
if (session == null) {
throw new SessionExpiredException();
}
PortletApplicationContext2 context = getApplicationContext(session);
Application application = context.getApplicationForWindowId(request
.getWindowID());
if (application == null) {
return null;
}
if (application.isRunning()) {
return application;
}
// application found but not running
context.removeApplication(application);
return null;
}
/**
* Returns the URL from which the widgetset is served on the portal.
*
* @param widgetset
* @param request
* @return
*/
protected String getWidgetsetURL(String widgetset,
WrappedPortletRequest request) {
return request.getStaticFileLocation() + "/" + WIDGETSET_DIRECTORY_PATH
+ widgetset + "/" + widgetset + ".nocache.js?"
+ new Date().getTime();
}
/**
* Returns the theme URI for the named theme on the portal.
*
* Note that this is not the only location referring to the theme URI - also
* e.g. PortletCommunicationManager uses its own way to access the portlet
* 2.0 theme resources.
*
* @param themeName
* @param request
* @return
*/
protected String getThemeURI(String themeName, WrappedPortletRequest request) {
return request.getStaticFileLocation() + "/" + THEME_DIRECTORY_PATH
+ themeName;
}
/**
* Writes the html host page (aka kickstart page) that starts the actual
* Vaadin application.
*
* If one needs to override parts of the portlet HTML contents creation, it
* is suggested that one overrides one of several submethods including:
* <ul>
* <li>
* {@link #writeAjaxPageHtmlMainDiv(RenderRequest, RenderResponse, BufferedWriter, String)}
* <li>
* {@link #getVaadinConfigurationMap(RenderRequest, RenderResponse, Application, String)}
* <li>
* {@link #writeAjaxPageHtmlVaadinScripts(RenderRequest, RenderResponse, BufferedWriter, Application, String)}
* </ul>
*
* @param request
* the portlet request.
* @param response
* the portlet response to write to.
* @param root
* @param application
* @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.
* @throws PortletException
*/
protected void writeAjaxPage(WrappedPortletRequest request,
RenderResponse response, Root root, Application application)
throws IOException, MalformedURLException, PortletException {
response.setContentType("text/html");
final BufferedWriter page = new BufferedWriter(new OutputStreamWriter(
response.getPortletOutputStream(), "UTF-8"));
// TODO Currently, we can only load widgetsets and themes from the
// portal
String themeName = getThemeForRoot(request, root);
writeAjaxPageHtmlVaadinScripts(request, response, page, application,
themeName);
/*- Add classnames;
* .v-app
* .v-app-loading
* .v-app-<simpleName for app class>
* .v-theme-<themeName, remove non-alphanum>
*/
String appClass = "v-app-";
try {
appClass += getApplicationClass().getSimpleName();
} catch (ClassNotFoundException e) {
appClass += "unknown";
logger.log(Level.SEVERE, "Could not find application class", e);
}
String themeClass = "v-theme-"
+ themeName.replaceAll("[^a-zA-Z0-9]", "");
String classNames = "v-app " + themeClass + " " + appClass;
String style = getApplicationProperty(PORTLET_PARAMETER_STYLE);
String divStyle = "";
if (style != null) {
divStyle = "style=\"" + style + "\"";
}
writeAjaxPageHtmlMainDiv(request, response, page,
getApplicationDomId(request.getPortletRequest()), classNames,
divStyle);
page.close();
}
/**
* Creates and returns a unique ID for the DIV where the application is to
* be rendered. We need to generate a unique ID because some portals already
* create a DIV with the portlet's Window ID as the DOM ID.
*
* @param request
* PortletRequest
* @return the id to use in the DOM
*/
private String getApplicationDomId(PortletRequest request) {
return "v-" + request.getWindowID();
}
/**
* This method writes the scripts to load the widgetset and the themes as
* well as define Vaadin configuration parameters on the HTML fragment that
* starts the actual Vaadin application.
*
* @param request
* @param response
* @param writer
* @param application
* @param themeName
* @throws IOException
* @throws PortletException
*/
protected void writeAjaxPageHtmlVaadinScripts(
WrappedPortletRequest request, RenderResponse response,
final BufferedWriter writer, Application application,
String themeName) throws IOException, PortletException {
String themeURI = getThemeURI(themeName, request);
// fixed base theme to use - all portal pages with Vaadin
// applications will load this exactly once
String portalTheme = request
.getPortalProperty(PORTAL_PARAMETER_VAADIN_THEME);
writer.write("<script type=\"text/javascript\">\n");
writer.write("if(!vaadin || !vaadin.vaadinConfigurations) {\n "
+ "if(!vaadin) { var vaadin = {}} \n"
+ "vaadin.vaadinConfigurations = {};\n"
+ "if (!vaadin.themesLoaded) { vaadin.themesLoaded = {}; }\n");
if (!isProductionMode()) {
writer.write("vaadin.debug = true;\n");
}
writeAjaxPageScriptWidgetset(request, response, writer);
Map<String, String> config = getVaadinConfigurationMap(request,
response, application, themeURI);
writeAjaxPageScriptConfigurations(request, response, writer, config);
writer.write("</script>\n");
writeAjaxPageHtmlTheme(request, writer, themeName, themeURI,
portalTheme);
// TODO Warn if widgetset has not been loaded after 15 seconds
}
/**
* Writes the script to load the widgetset on the HTML fragment created by
* the portlet.
*
* @param request
* @param response
* @param writer
* @throws IOException
*/
protected void writeAjaxPageScriptWidgetset(WrappedPortletRequest request,
RenderResponse response, final BufferedWriter writer)
throws IOException {
String requestWidgetset = getApplicationOrSystemProperty(
PARAMETER_WIDGETSET, null);
String sharedWidgetset = request
.getPortalProperty(PORTAL_PARAMETER_VAADIN_WIDGETSET);
String widgetset;
if (requestWidgetset != null) {
widgetset = requestWidgetset;
} else if (sharedWidgetset != null) {
widgetset = sharedWidgetset;
} else {
widgetset = DEFAULT_WIDGETSET;
}
String widgetsetURL = getWidgetsetURL(widgetset, request);
writer.write("document.write('<iframe tabIndex=\"-1\" id=\"__gwt_historyFrame\" "
+ "style=\"position:absolute;width:0;height:0;border:0;overflow:"
+ "hidden;opacity:0;top:-100px;left:-100px;\" src=\"javascript:false\"></iframe>');\n");
writer.write("document.write(\"<script language='javascript' src='"
+ widgetsetURL + "'><\\/script>\");\n}\n");
}
/**
* Returns the configuration parameters to pass to the client.
*
* To add configuration parameters for the client, override, call the super
* method and then modify the map. Overriding this method may also require
* client side changes in {@link ApplicationConnection} and
* {@link ApplicationConfiguration}.
*
* Note that this method must escape and quote the values when appropriate.
*
* The map returned is typically a {@link LinkedHashMap} to preserve
* insertion order, but it is not guaranteed to be one.
*
* @param request
* @param response
* @param application
* @param themeURI
* @return modifiable Map from parameter name to its full value
* @throws PortletException
*/
protected Map<String, String> getVaadinConfigurationMap(
WrappedPortletRequest request, RenderResponse response,
Application application, String themeURI) throws PortletException {
Map<String, String> config = new LinkedHashMap<String, String>();
/*
* We need this in order to get uploads to work. TODO this is not needed
* for uploads anymore, check if this is needed for some other things
*/
PortletURL appUri = response.createActionURL();
config.put("appUri", "'" + appUri.toString() + "'");
config.put("usePortletURLs", "true");
ResourceURL uidlUrlBase = response.createResourceURL();
uidlUrlBase.setResourceID("UIDL");
config.put("portletUidlURLBase", "'" + uidlUrlBase.toString() + "'");
config.put("pathInfo", "''");
config.put("themeUri", "'" + themeURI + "'");
String versionInfo = "{vaadinVersion:\""
+ AbstractApplicationServlet.VERSION
+ "\",applicationVersion:\"" + application.getVersion() + "\"}";
config.put("versionInfo", versionInfo);
// 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 PortletException("Failed to obtain system messages!", e);
}
if (systemMessages != null) {
// Write the CommunicationError -message to client
String caption = systemMessages.getCommunicationErrorCaption();
if (caption != null) {
caption = "\"" + caption + "\"";
}
String message = systemMessages.getCommunicationErrorMessage();
if (message != null) {
message = "\"" + message + "\"";
}
String url = systemMessages.getCommunicationErrorURL();
if (url != null) {
url = "\"" + url + "\"";
}
config.put("\"comErrMsg\"", "{" + "\"caption\":" + caption + ","
+ "\"message\" : " + message + "," + "\"url\" : " + url
+ "}");
// Write the AuthenticationError -message to client
caption = systemMessages.getAuthenticationErrorCaption();
if (caption != null) {
caption = "\"" + caption + "\"";
}
message = systemMessages.getAuthenticationErrorMessage();
if (message != null) {
message = "\"" + message + "\"";
}
url = systemMessages.getAuthenticationErrorURL();
if (url != null) {
url = "\"" + url + "\"";
}
config.put("\"authErrMsg\"", "{" + "\"caption\":" + caption + ","
+ "\"message\" : " + message + "," + "\"url\" : " + url
+ "}");
}
return config;
}
/**
* Constructs the Vaadin configuration section for
* {@link ApplicationConnection} and {@link ApplicationConfiguration}.
*
* Typically this method should not be overridden. Instead, modify
* {@link #getVaadinConfigurationMap(RenderRequest, RenderResponse, Application, String)}
* .
*
* @param request
* @param response
* @param writer
* @param config
* @throws IOException
* @throws PortletException
*/
protected void writeAjaxPageScriptConfigurations(
WrappedPortletRequest request, RenderResponse response,
final BufferedWriter writer, Map<String, String> config)
throws IOException, PortletException {
writer.write("vaadin.vaadinConfigurations[\""
+ getApplicationDomId(request.getPortletRequest()) + "\"] = {");
Iterator<String> keyIt = config.keySet().iterator();
while (keyIt.hasNext()) {
String key = keyIt.next();
writer.write(key + ": " + config.get(key));
if (keyIt.hasNext()) {
writer.write(", ");
}
}
writer.write("};\n");
}
/**
* Writes the Vaadin theme loading section of the portlet HTML. Loads both
* the portal theme and the portlet theme in this order, skipping loading of
* themes that are already loaded (matched by name).
*
* @param request
* @param writer
* @param themeName
* @param themeURI
* @param portalTheme
* @throws IOException
*/
protected void writeAjaxPageHtmlTheme(WrappedPortletRequest request,
final BufferedWriter writer, String themeName, String themeURI,
String portalTheme) throws IOException {
writer.write("<script type=\"text/javascript\">\n");
if (portalTheme == null) {
portalTheme = DEFAULT_THEME_NAME;
}
writer.write("if(!vaadin.themesLoaded['" + portalTheme + "']) {\n");
writer.write("var defaultStylesheet = document.createElement('link');\n");
writer.write("defaultStylesheet.setAttribute('rel', 'stylesheet');\n");
writer.write("defaultStylesheet.setAttribute('type', 'text/css');\n");
writer.write("defaultStylesheet.setAttribute('href', '"
+ getThemeURI(portalTheme, request) + "/styles.css');\n");
writer.write("document.getElementsByTagName('head')[0].appendChild(defaultStylesheet);\n");
writer.write("vaadin.themesLoaded['" + portalTheme + "'] = true;\n}\n");
if (!portalTheme.equals(themeName)) {
writer.write("if(!vaadin.themesLoaded['" + themeName + "']) {\n");
writer.write("var stylesheet = document.createElement('link');\n");
writer.write("stylesheet.setAttribute('rel', 'stylesheet');\n");
writer.write("stylesheet.setAttribute('type', 'text/css');\n");
writer.write("stylesheet.setAttribute('href', '" + themeURI
+ "/styles.css');\n");
writer.write("document.getElementsByTagName('head')[0].appendChild(stylesheet);\n");
writer.write("vaadin.themesLoaded['" + themeName
+ "'] = true;\n}\n");
}
writer.write("</script>\n");
}
/**
* 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 request
* @param response
* @param writer
* @param id
* @param classNames
* @param divStyle
* @throws IOException
*/
protected void writeAjaxPageHtmlMainDiv(WrappedPortletRequest request,
RenderResponse response, final BufferedWriter writer, String id,
String classNames, String divStyle) throws IOException {
writer.write("<div id=\"" + id + "\" class=\"" + classNames + "\" "
+ divStyle + ">");
writer.write("<div class=\"v-app-loading\"></div>");
writer.write("</div>\n");
writer.write("<noscript>" + getNoScriptMessage() + "</noscript>");
}
/**
* 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.";
}
/**
* Returns the theme for given request/window
*
* @param request
* @param window
* @return
*/
protected String getThemeForRoot(WrappedPortletRequest request, Root root) {
// Finds theme name
String themeName;
// theme defined for the window?
themeName = null;// window.getTheme();
if (themeName == null) {
// no, is the default theme defined by the portal?
themeName = request
.getPortalProperty(Constants.PORTAL_PARAMETER_VAADIN_THEME);
}
if (themeName == null) {
// no, using the default theme defined by Vaadin
themeName = DEFAULT_THEME_NAME;
}
return themeName;
}
protected abstract Class<? extends Application> getApplicationClass()
throws ClassNotFoundException;
protected Application getNewApplication(PortletRequest request)
throws PortletException {
try {
final Application application = getApplicationClass().newInstance();
return application;
} catch (final IllegalAccessException e) {
throw new PortletException("getNewApplication failed", e);
} catch (final InstantiationException e) {
throw new PortletException("getNewApplication failed", e);
} catch (final ClassNotFoundException e) {
throw new PortletException("getNewApplication failed", e);
}
}
protected ClassLoader getClassLoader() throws PortletException {
// TODO Add support for custom class loader
return getClass().getClassLoader();
}
/**
* 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();
}
private void handleServiceException(PortletRequest request,
PortletResponse response, Application application, Throwable e)
throws IOException, PortletException {
// TODO Check that this error handler is working when running inside a
// portlet
// if this was an UIDL request, response UIDL back to client
if (getRequestType(request) == RequestType.UIDL) {
Application.SystemMessages ci = getSystemMessages();
criticalNotification(request, (ResourceResponse) response,
ci.getInternalErrorCaption(), ci.getInternalErrorMessage(),
null, ci.getInternalErrorURL());
if (application != null) {
application.getErrorHandler()
.terminalError(new RequestError(e));
} else {
throw new PortletException(e);
}
} else {
// Re-throw other exceptions
throw new PortletException(e);
}
}
@SuppressWarnings("serial")
public class RequestError implements Terminal.ErrorEvent, Serializable {
private final Throwable throwable;
public RequestError(Throwable throwable) {
this.throwable = throwable;
}
public Throwable getThrowable() {
return throwable;
}
}
/**
* Send notification to client's application. Used to notify client of
* critical errors and session expiration due to long inactivity. Server has
* no knowledge of what application client refers to.
*
* @param request
* the Portlet request instance.
* @param response
* the Portlet response to write to.
* @param caption
* for the notification
* @param message
* for the notification
* @param details
* a detail message to show in addition to the passed message.
* Currently shown directly but could be hidden behind a details
* drop down.
* @param url
* url to load after message, null for current page
* @throws IOException
* if the writing failed due to input/output error.
*/
void criticalNotification(PortletRequest request, MimeResponse response,
String caption, String message, String details, String url)
throws IOException {
// clients JS app is still running, but server application either
// no longer exists or it might fail to perform reasonably.
// send a notification to client's application and link how
// to "restart" application.
if (caption != null) {
caption = "\"" + caption + "\"";
}
if (details != null) {
if (message == null) {
message = details;
} else {
message += "<br/><br/>" + details;
}
}
if (message != null) {
message = "\"" + message + "\"";
}
if (url != null) {
url = "\"" + url + "\"";
}
// Set the response type
response.setContentType("application/json; charset=UTF-8");
final OutputStream out = response.getPortletOutputStream();
final PrintWriter outWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(out, "UTF-8")));
outWriter.print("for(;;);[{\"changes\":[], \"meta\" : {"
+ "\"appError\": {" + "\"caption\":" + caption + ","
+ "\"message\" : " + message + "," + "\"url\" : " + url
+ "}}, \"resources\": {}, \"locales\":[]}]");
outWriter.close();
}
/**
*
* Gets the application context for a PortletSession. If no context is
* currently stored in a session a new context is created and stored in the
* session.
*
* @param portletSession
* the portlet session.
* @return the application context for the session.
*/
protected PortletApplicationContext2 getApplicationContext(
PortletSession portletSession) {
return PortletApplicationContext2.getApplicationContext(portletSession);
}
}
|