You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AbstractApplicationPortlet.java 43KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal.gwt.server;
  5. import java.io.BufferedWriter;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. import java.io.OutputStreamWriter;
  10. import java.io.PrintWriter;
  11. import java.io.Serializable;
  12. import java.lang.reflect.InvocationTargetException;
  13. import java.lang.reflect.Method;
  14. import java.net.MalformedURLException;
  15. import java.security.GeneralSecurityException;
  16. import java.util.Enumeration;
  17. import java.util.Locale;
  18. import java.util.Map;
  19. import java.util.Properties;
  20. import java.util.logging.Logger;
  21. import javax.portlet.ActionRequest;
  22. import javax.portlet.ActionResponse;
  23. import javax.portlet.EventRequest;
  24. import javax.portlet.EventResponse;
  25. import javax.portlet.GenericPortlet;
  26. import javax.portlet.MimeResponse;
  27. import javax.portlet.PortletConfig;
  28. import javax.portlet.PortletContext;
  29. import javax.portlet.PortletException;
  30. import javax.portlet.PortletRequest;
  31. import javax.portlet.PortletResponse;
  32. import javax.portlet.PortletSession;
  33. import javax.portlet.RenderRequest;
  34. import javax.portlet.RenderResponse;
  35. import javax.portlet.ResourceRequest;
  36. import javax.portlet.ResourceResponse;
  37. import javax.servlet.http.HttpServletRequest;
  38. import javax.servlet.http.HttpServletRequestWrapper;
  39. import javax.servlet.http.HttpServletResponse;
  40. import com.liferay.portal.kernel.util.PortalClassInvoker;
  41. import com.liferay.portal.kernel.util.PropsUtil;
  42. import com.vaadin.Application;
  43. import com.vaadin.Application.ApplicationStartEvent;
  44. import com.vaadin.Application.SystemMessages;
  45. import com.vaadin.RootRequiresMoreInformationException;
  46. import com.vaadin.terminal.DeploymentConfiguration;
  47. import com.vaadin.terminal.Terminal;
  48. import com.vaadin.terminal.WrappedRequest;
  49. import com.vaadin.terminal.WrappedResponse;
  50. import com.vaadin.terminal.gwt.server.AbstractCommunicationManager.Callback;
  51. import com.vaadin.ui.Root;
  52. /**
  53. * Portlet 2.0 base class. This replaces the servlet in servlet/portlet 1.0
  54. * deployments and handles various portlet requests from the browser.
  55. *
  56. * TODO Document me!
  57. *
  58. * @author peholmst
  59. */
  60. public abstract class AbstractApplicationPortlet extends GenericPortlet
  61. implements Constants {
  62. private static final Logger logger = Logger
  63. .getLogger(AbstractApplicationPortlet.class.getName());
  64. private static class WrappedHttpAndPortletRequest extends
  65. WrappedPortletRequest {
  66. public WrappedHttpAndPortletRequest(PortletRequest request,
  67. HttpServletRequest originalRequest,
  68. DeploymentConfiguration deploymentConfiguration) {
  69. super(request, deploymentConfiguration);
  70. this.originalRequest = originalRequest;
  71. }
  72. private final HttpServletRequest originalRequest;
  73. @Override
  74. public String getParameter(String name) {
  75. String parameter = super.getParameter(name);
  76. if (parameter == null) {
  77. parameter = originalRequest.getParameter(name);
  78. }
  79. return parameter;
  80. }
  81. @Override
  82. public String getRemoteAddr() {
  83. return originalRequest.getRemoteAddr();
  84. }
  85. @Override
  86. public String getHeader(String name) {
  87. String header = super.getHeader(name);
  88. if (header == null) {
  89. header = originalRequest.getHeader(name);
  90. }
  91. return header;
  92. }
  93. @Override
  94. public Map<String, String[]> getParameterMap() {
  95. Map<String, String[]> parameterMap = super.getParameterMap();
  96. if (parameterMap == null) {
  97. parameterMap = originalRequest.getParameterMap();
  98. }
  99. return parameterMap;
  100. }
  101. }
  102. private static class WrappedGateinRequest extends
  103. WrappedHttpAndPortletRequest {
  104. public WrappedGateinRequest(PortletRequest request,
  105. DeploymentConfiguration deploymentConfiguration) {
  106. super(request, getOriginalRequest(request), deploymentConfiguration);
  107. }
  108. private static final HttpServletRequest getOriginalRequest(
  109. PortletRequest request) {
  110. try {
  111. Method getRealReq = request.getClass().getMethod(
  112. "getRealRequest");
  113. HttpServletRequestWrapper origRequest = (HttpServletRequestWrapper) getRealReq
  114. .invoke(request);
  115. return origRequest;
  116. } catch (Exception e) {
  117. throw new IllegalStateException("GateIn request not detected",
  118. e);
  119. }
  120. }
  121. }
  122. private static class WrappedLiferayRequest extends
  123. WrappedHttpAndPortletRequest {
  124. public WrappedLiferayRequest(PortletRequest request,
  125. DeploymentConfiguration deploymentConfiguration) {
  126. super(request, getOriginalRequest(request), deploymentConfiguration);
  127. }
  128. @Override
  129. public String getPortalProperty(String name) {
  130. return PropsUtil.get(name);
  131. }
  132. private static HttpServletRequest getOriginalRequest(
  133. PortletRequest request) {
  134. try {
  135. // httpRequest = PortalUtil.getHttpServletRequest(request);
  136. HttpServletRequest httpRequest = (HttpServletRequest) PortalClassInvoker
  137. .invoke("com.liferay.portal.util.PortalUtil",
  138. "getHttpServletRequest", request);
  139. // httpRequest =
  140. // PortalUtil.getOriginalServletRequest(httpRequest);
  141. httpRequest = (HttpServletRequest) PortalClassInvoker.invoke(
  142. "com.liferay.portal.util.PortalUtil",
  143. "getOriginalServletRequest", httpRequest);
  144. return httpRequest;
  145. } catch (Exception e) {
  146. throw new IllegalStateException("Liferay request not detected",
  147. e);
  148. }
  149. }
  150. }
  151. private static class AbstractApplicationPortletWrapper implements Callback {
  152. private final AbstractApplicationPortlet portlet;
  153. public AbstractApplicationPortletWrapper(
  154. AbstractApplicationPortlet portlet) {
  155. this.portlet = portlet;
  156. }
  157. public void criticalNotification(WrappedRequest request,
  158. WrappedResponse response, String cap, String msg,
  159. String details, String outOfSyncURL) throws IOException {
  160. PortletRequest portletRequest = WrappedPortletRequest.cast(request)
  161. .getPortletRequest();
  162. PortletResponse portletResponse = ((WrappedPortletResponse) response)
  163. .getPortletResponse();
  164. portlet.criticalNotification(portletRequest,
  165. (MimeResponse) portletResponse, cap, msg, details,
  166. outOfSyncURL);
  167. }
  168. }
  169. /**
  170. * This portlet parameter is used to add styles to the main element. E.g
  171. * "height:500px" generates a style="height:500px" to the main element.
  172. */
  173. public static final String PORTLET_PARAMETER_STYLE = "style";
  174. /**
  175. * This portal parameter is used to define the name of the Vaadin theme that
  176. * is used for all Vaadin applications in the portal.
  177. */
  178. public static final String PORTAL_PARAMETER_VAADIN_THEME = "vaadin.theme";
  179. // TODO some parts could be shared with AbstractApplicationServlet
  180. // TODO Can we close the application when the portlet is removed? Do we know
  181. // when the portlet is removed?
  182. private Properties applicationProperties;
  183. private boolean productionMode = false;
  184. private DeploymentConfiguration deploymentConfiguration = new DeploymentConfiguration() {
  185. public String getConfiguredWidgetset(WrappedRequest request) {
  186. String widgetset = getApplicationOrSystemProperty(
  187. PARAMETER_WIDGETSET, null);
  188. if (widgetset == null) {
  189. // If no widgetset defined for the application, check the portal
  190. // property
  191. widgetset = WrappedPortletRequest.cast(request)
  192. .getPortalProperty(PORTAL_PARAMETER_VAADIN_WIDGETSET);
  193. }
  194. if (widgetset == null) {
  195. // If no widgetset defined for the portal, use the default
  196. widgetset = DEFAULT_WIDGETSET;
  197. }
  198. return widgetset;
  199. }
  200. public String getConfiguredTheme(WrappedRequest request) {
  201. // is the default theme defined by the portal?
  202. String themeName = WrappedPortletRequest.cast(request)
  203. .getPortalProperty(Constants.PORTAL_PARAMETER_VAADIN_THEME);
  204. if (themeName == null) {
  205. // no, using the default theme defined by Vaadin
  206. themeName = DEFAULT_THEME_NAME;
  207. }
  208. return themeName;
  209. }
  210. public String getApplicationOrSystemProperty(String propertyName,
  211. String defaultValue) {
  212. return AbstractApplicationPortlet.this
  213. .getApplicationOrSystemProperty(propertyName, defaultValue);
  214. }
  215. public boolean isStandalone(WrappedRequest request) {
  216. return false;
  217. }
  218. /*
  219. * (non-Javadoc)
  220. *
  221. * @see
  222. * com.vaadin.terminal.DeploymentConfiguration#getStaticFileLocation
  223. * (com.vaadin.terminal.WrappedRequest)
  224. *
  225. * Return the URL from where static files, e.g. the widgetset and the
  226. * theme, are served. In a standard configuration the VAADIN folder
  227. * inside the returned folder is what is used for widgetsets and themes.
  228. *
  229. * @return The location of static resources (inside which there should
  230. * be a VAADIN directory). Does not end with a slash (/).
  231. */
  232. public String getStaticFileLocation(WrappedRequest request) {
  233. String staticFileLocation = WrappedPortletRequest.cast(request)
  234. .getPortalProperty(
  235. Constants.PORTAL_PARAMETER_VAADIN_RESOURCE_PATH);
  236. if (staticFileLocation != null) {
  237. // remove trailing slash if any
  238. while (staticFileLocation.endsWith(".")) {
  239. staticFileLocation = staticFileLocation.substring(0,
  240. staticFileLocation.length() - 1);
  241. }
  242. return staticFileLocation;
  243. } else {
  244. // default for Liferay
  245. return "/html";
  246. }
  247. }
  248. public ClassLoader getClassLoader() {
  249. // Custom class loaders not currently supported in portlets (see
  250. // #8574)
  251. return null;
  252. }
  253. };
  254. @Override
  255. public void init(PortletConfig config) throws PortletException {
  256. super.init(config);
  257. applicationProperties = new Properties();
  258. // Read default parameters from the context
  259. final PortletContext context = config.getPortletContext();
  260. for (final Enumeration<String> e = context.getInitParameterNames(); e
  261. .hasMoreElements();) {
  262. final String name = e.nextElement();
  263. applicationProperties.setProperty(name,
  264. context.getInitParameter(name));
  265. }
  266. // Override with application settings from portlet.xml
  267. for (final Enumeration<String> e = config.getInitParameterNames(); e
  268. .hasMoreElements();) {
  269. final String name = e.nextElement();
  270. applicationProperties.setProperty(name,
  271. config.getInitParameter(name));
  272. }
  273. checkProductionMode();
  274. checkCrossSiteProtection();
  275. }
  276. private void checkCrossSiteProtection() {
  277. if (getApplicationOrSystemProperty(
  278. SERVLET_PARAMETER_DISABLE_XSRF_PROTECTION, "false").equals(
  279. "true")) {
  280. /*
  281. * Print an information/warning message about running with xsrf
  282. * protection disabled
  283. */
  284. logger.warning(WARNING_XSRF_PROTECTION_DISABLED);
  285. }
  286. }
  287. private void checkProductionMode() {
  288. // TODO Identical code in AbstractApplicationServlet -> refactor
  289. // Check if the application is in production mode.
  290. // We are in production mode if productionMode=true
  291. if (getApplicationOrSystemProperty(SERVLET_PARAMETER_PRODUCTION_MODE,
  292. "false").equals("true")) {
  293. productionMode = true;
  294. }
  295. if (!productionMode) {
  296. /* Print an information/warning message about running in debug mode */
  297. // TODO Maybe we need a different message for portlets?
  298. logger.warning(NOT_PRODUCTION_MODE_INFO);
  299. }
  300. }
  301. /**
  302. * Gets an application property value.
  303. *
  304. * @param parameterName
  305. * the Name or the parameter.
  306. * @return String value or null if not found
  307. */
  308. protected String getApplicationProperty(String parameterName) {
  309. String val = applicationProperties.getProperty(parameterName);
  310. if (val != null) {
  311. return val;
  312. }
  313. // Try lower case application properties for backward compatibility with
  314. // 3.0.2 and earlier
  315. val = applicationProperties.getProperty(parameterName.toLowerCase());
  316. return val;
  317. }
  318. /**
  319. * Gets an system property value.
  320. *
  321. * @param parameterName
  322. * the Name or the parameter.
  323. * @return String value or null if not found
  324. */
  325. protected String getSystemProperty(String parameterName) {
  326. String val = null;
  327. String pkgName;
  328. final Package pkg = getClass().getPackage();
  329. if (pkg != null) {
  330. pkgName = pkg.getName();
  331. } else {
  332. final String className = getClass().getName();
  333. pkgName = new String(className.toCharArray(), 0,
  334. className.lastIndexOf('.'));
  335. }
  336. val = System.getProperty(pkgName + "." + parameterName);
  337. if (val != null) {
  338. return val;
  339. }
  340. // Try lowercased system properties
  341. val = System.getProperty(pkgName + "." + parameterName.toLowerCase());
  342. return val;
  343. }
  344. /**
  345. * Gets an application or system property value.
  346. *
  347. * @param parameterName
  348. * the Name or the parameter.
  349. * @param defaultValue
  350. * the Default to be used.
  351. * @return String value or default if not found
  352. */
  353. protected String getApplicationOrSystemProperty(String parameterName,
  354. String defaultValue) {
  355. String val = null;
  356. // Try application properties
  357. val = getApplicationProperty(parameterName);
  358. if (val != null) {
  359. return val;
  360. }
  361. // Try system properties
  362. val = getSystemProperty(parameterName);
  363. if (val != null) {
  364. return val;
  365. }
  366. return defaultValue;
  367. }
  368. protected enum RequestType {
  369. FILE_UPLOAD, UIDL, RENDER, STATIC_FILE, APPLICATION_RESOURCE, DUMMY, EVENT, ACTION, UNKNOWN, BROWSER_DETAILS;
  370. }
  371. protected RequestType getRequestType(PortletRequest request) {
  372. if (request instanceof RenderRequest) {
  373. return RequestType.RENDER;
  374. } else if (request instanceof ResourceRequest) {
  375. ResourceRequest resourceRequest = (ResourceRequest) request;
  376. if (isUIDLRequest(resourceRequest)) {
  377. return RequestType.UIDL;
  378. } else if (isBrowserDetailsRequeset(resourceRequest)) {
  379. return RequestType.BROWSER_DETAILS;
  380. } else if (isFileUploadRequest(resourceRequest)) {
  381. return RequestType.FILE_UPLOAD;
  382. } else if (isApplicationResourceRequest(resourceRequest)) {
  383. return RequestType.APPLICATION_RESOURCE;
  384. } else if (isDummyRequest(resourceRequest)) {
  385. return RequestType.DUMMY;
  386. } else {
  387. return RequestType.STATIC_FILE;
  388. }
  389. } else if (request instanceof ActionRequest) {
  390. return RequestType.ACTION;
  391. } else if (request instanceof EventRequest) {
  392. return RequestType.EVENT;
  393. }
  394. return RequestType.UNKNOWN;
  395. }
  396. private boolean isBrowserDetailsRequeset(ResourceRequest request) {
  397. return request.getResourceID() != null
  398. && request.getResourceID().equals("browserDetails");
  399. }
  400. private boolean isApplicationResourceRequest(ResourceRequest request) {
  401. return request.getResourceID() != null
  402. && request.getResourceID().startsWith("APP");
  403. }
  404. private boolean isUIDLRequest(ResourceRequest request) {
  405. return request.getResourceID() != null
  406. && request.getResourceID().equals("UIDL");
  407. }
  408. private boolean isDummyRequest(ResourceRequest request) {
  409. return request.getResourceID() != null
  410. && request.getResourceID().equals("DUMMY");
  411. }
  412. private boolean isFileUploadRequest(ResourceRequest request) {
  413. return "UPLOAD".equals(request.getResourceID());
  414. }
  415. /**
  416. * Returns true if the servlet is running in production mode. Production
  417. * mode disables all debug facilities.
  418. *
  419. * @return true if in production mode, false if in debug mode
  420. */
  421. public boolean isProductionMode() {
  422. return productionMode;
  423. }
  424. protected void handleRequest(PortletRequest request,
  425. PortletResponse response) throws PortletException, IOException {
  426. RequestTimer requestTimer = new RequestTimer();
  427. requestTimer.start();
  428. AbstractApplicationPortletWrapper portletWrapper = new AbstractApplicationPortletWrapper(
  429. this);
  430. WrappedPortletRequest wrappedRequest;
  431. String portalInfo = request.getPortalContext().getPortalInfo()
  432. .toLowerCase();
  433. if (portalInfo.contains("liferay")) {
  434. wrappedRequest = new WrappedLiferayRequest(request,
  435. getDeploymentConfiguration());
  436. } else if (portalInfo.contains("gatein")) {
  437. wrappedRequest = new WrappedGateinRequest(request,
  438. getDeploymentConfiguration());
  439. } else {
  440. wrappedRequest = new WrappedPortletRequest(request,
  441. getDeploymentConfiguration());
  442. }
  443. WrappedPortletResponse wrappedResponse = new WrappedPortletResponse(
  444. response, getDeploymentConfiguration());
  445. RequestType requestType = getRequestType(request);
  446. if (requestType == RequestType.UNKNOWN) {
  447. handleUnknownRequest(request, response);
  448. } else if (requestType == RequestType.DUMMY) {
  449. /*
  450. * This dummy page is used by action responses to redirect to, in
  451. * order to prevent the boot strap code from being rendered into
  452. * strange places such as iframes.
  453. */
  454. ((ResourceResponse) response).setContentType("text/html");
  455. final OutputStream out = ((ResourceResponse) response)
  456. .getPortletOutputStream();
  457. final PrintWriter outWriter = new PrintWriter(new BufferedWriter(
  458. new OutputStreamWriter(out, "UTF-8")));
  459. outWriter.print("<html><body>dummy page</body></html>");
  460. outWriter.close();
  461. } else if (requestType == RequestType.STATIC_FILE) {
  462. serveStaticResources((ResourceRequest) request,
  463. (ResourceResponse) response);
  464. } else {
  465. Application application = null;
  466. boolean transactionStarted = false;
  467. boolean requestStarted = false;
  468. try {
  469. // TODO What about PARAM_UNLOADBURST & redirectToApplication??
  470. /* Find out which application this request is related to */
  471. application = findApplicationInstance(wrappedRequest,
  472. requestType);
  473. if (application == null) {
  474. return;
  475. }
  476. Application.setCurrentApplication(application);
  477. /*
  478. * Get or create an application context and an application
  479. * manager for the session
  480. */
  481. PortletApplicationContext2 applicationContext = getApplicationContext(request
  482. .getPortletSession());
  483. applicationContext.setResponse(response);
  484. applicationContext.setPortletConfig(getPortletConfig());
  485. PortletCommunicationManager applicationManager = applicationContext
  486. .getApplicationManager(application);
  487. /* Update browser information from request */
  488. applicationContext.getBrowser().updateRequestDetails(
  489. wrappedRequest);
  490. /*
  491. * Call application requestStart before Application.init() is
  492. * called (bypasses the limitation in TransactionListener)
  493. */
  494. if (application instanceof PortletRequestListener) {
  495. ((PortletRequestListener) application).onRequestStart(
  496. request, response);
  497. requestStarted = true;
  498. }
  499. /* Start the newly created application */
  500. startApplication(request, application, applicationContext);
  501. /*
  502. * Transaction starts. Call transaction listeners. Transaction
  503. * end is called in the finally block below.
  504. */
  505. applicationContext.startTransaction(application, request);
  506. transactionStarted = true;
  507. /* Notify listeners */
  508. // Finds the window within the application
  509. Root root = null;
  510. synchronized (application) {
  511. if (application.isRunning()) {
  512. switch (requestType) {
  513. case RENDER:
  514. case ACTION:
  515. // Both action requests and render requests are ok
  516. // without a Root as they render the initial HTML
  517. // and then do a second request
  518. try {
  519. root = application
  520. .getRootForRequest(wrappedRequest);
  521. } catch (RootRequiresMoreInformationException e) {
  522. // Ignore problem and continue without root
  523. }
  524. break;
  525. case BROWSER_DETAILS:
  526. // Should not try to find a root here as the
  527. // combined request details might change the root
  528. break;
  529. case FILE_UPLOAD:
  530. // no window
  531. break;
  532. case APPLICATION_RESOURCE:
  533. // use main window - should not need any window
  534. // root = application.getRoot();
  535. break;
  536. default:
  537. root = application
  538. .getRootForRequest(wrappedRequest);
  539. }
  540. // if window not found, not a problem - use null
  541. }
  542. }
  543. // TODO Should this happen before or after the transaction
  544. // starts?
  545. if (request instanceof RenderRequest) {
  546. applicationContext.firePortletRenderRequest(application,
  547. root, (RenderRequest) request,
  548. (RenderResponse) response);
  549. } else if (request instanceof ActionRequest) {
  550. applicationContext.firePortletActionRequest(application,
  551. root, (ActionRequest) request,
  552. (ActionResponse) response);
  553. } else if (request instanceof EventRequest) {
  554. applicationContext.firePortletEventRequest(application,
  555. root, (EventRequest) request,
  556. (EventResponse) response);
  557. } else if (request instanceof ResourceRequest) {
  558. applicationContext.firePortletResourceRequest(application,
  559. root, (ResourceRequest) request,
  560. (ResourceResponse) response);
  561. }
  562. /* Handle the request */
  563. if (requestType == RequestType.FILE_UPLOAD) {
  564. applicationManager.handleFileUpload(wrappedRequest,
  565. wrappedResponse);
  566. return;
  567. } else if (requestType == RequestType.BROWSER_DETAILS) {
  568. applicationManager.handleBrowserDetailsRequest(
  569. wrappedRequest, wrappedResponse, application);
  570. return;
  571. } else if (requestType == RequestType.UIDL) {
  572. // Handles AJAX UIDL requests
  573. applicationManager.handleUidlRequest(wrappedRequest,
  574. wrappedResponse, portletWrapper, root);
  575. return;
  576. } else {
  577. /*
  578. * Removes the application if it has stopped
  579. */
  580. if (!application.isRunning()) {
  581. endApplication(request, response, application);
  582. return;
  583. }
  584. handleOtherRequest(wrappedRequest, wrappedResponse,
  585. requestType, application, applicationContext,
  586. applicationManager);
  587. }
  588. } catch (final SessionExpiredException e) {
  589. // TODO Figure out a better way to deal with
  590. // SessionExpiredExceptions
  591. logger.finest("A user session has expired");
  592. } catch (final GeneralSecurityException e) {
  593. // TODO Figure out a better way to deal with
  594. // GeneralSecurityExceptions
  595. logger.fine("General security exception, the security key was probably incorrect.");
  596. } catch (final Throwable e) {
  597. handleServiceException(request, response, application, e);
  598. } finally {
  599. // Notifies transaction end
  600. try {
  601. if (transactionStarted) {
  602. ((PortletApplicationContext2) application.getContext())
  603. .endTransaction(application, request);
  604. }
  605. } finally {
  606. try {
  607. if (requestStarted) {
  608. ((PortletRequestListener) application)
  609. .onRequestEnd(request, response);
  610. }
  611. } finally {
  612. Root.setCurrentRoot(null);
  613. Application.setCurrentApplication(null);
  614. requestTimer
  615. .stop((AbstractWebApplicationContext) application
  616. .getContext());
  617. }
  618. }
  619. }
  620. }
  621. }
  622. private DeploymentConfiguration getDeploymentConfiguration() {
  623. return deploymentConfiguration;
  624. }
  625. private void handleUnknownRequest(PortletRequest request,
  626. PortletResponse response) {
  627. logger.warning("Unknown request type");
  628. }
  629. /**
  630. * Handle a portlet request that is not for static files, UIDL or upload.
  631. * Also render requests are handled here.
  632. *
  633. * This method is called after starting the application and calling portlet
  634. * and transaction listeners.
  635. *
  636. * @param request
  637. * @param response
  638. * @param requestType
  639. * @param application
  640. * @param applicationContext
  641. * @param applicationManager
  642. * @throws PortletException
  643. * @throws IOException
  644. * @throws MalformedURLException
  645. */
  646. private void handleOtherRequest(WrappedPortletRequest request,
  647. WrappedResponse response, RequestType requestType,
  648. Application application,
  649. PortletApplicationContext2 applicationContext,
  650. PortletCommunicationManager applicationManager)
  651. throws PortletException, IOException, MalformedURLException {
  652. if (requestType == RequestType.APPLICATION_RESOURCE
  653. || requestType == RequestType.RENDER) {
  654. if (!applicationManager.handleApplicationRequest(request, response)) {
  655. response.sendError(HttpServletResponse.SC_NOT_FOUND,
  656. "Not found");
  657. }
  658. } else if (requestType == RequestType.EVENT) {
  659. // nothing to do, listeners do all the work
  660. } else if (requestType == RequestType.ACTION) {
  661. // nothing to do, listeners do all the work
  662. } else {
  663. throw new IllegalStateException(
  664. "handleRequest() without anything to do - should never happen!");
  665. }
  666. }
  667. @Override
  668. public void processEvent(EventRequest request, EventResponse response)
  669. throws PortletException, IOException {
  670. handleRequest(request, response);
  671. }
  672. private void serveStaticResources(ResourceRequest request,
  673. ResourceResponse response) throws IOException, PortletException {
  674. final String resourceID = request.getResourceID();
  675. final PortletContext pc = getPortletContext();
  676. InputStream is = pc.getResourceAsStream(resourceID);
  677. if (is != null) {
  678. final String mimetype = pc.getMimeType(resourceID);
  679. if (mimetype != null) {
  680. response.setContentType(mimetype);
  681. }
  682. final OutputStream os = response.getPortletOutputStream();
  683. final byte buffer[] = new byte[DEFAULT_BUFFER_SIZE];
  684. int bytes;
  685. while ((bytes = is.read(buffer)) >= 0) {
  686. os.write(buffer, 0, bytes);
  687. }
  688. } else {
  689. logger.info("Requested resource [" + resourceID
  690. + "] could not be found");
  691. response.setProperty(ResourceResponse.HTTP_STATUS_CODE,
  692. Integer.toString(HttpServletResponse.SC_NOT_FOUND));
  693. }
  694. }
  695. @Override
  696. public void processAction(ActionRequest request, ActionResponse response)
  697. throws PortletException, IOException {
  698. handleRequest(request, response);
  699. }
  700. @Override
  701. protected void doDispatch(RenderRequest request, RenderResponse response)
  702. throws PortletException, IOException {
  703. try {
  704. // try to let super handle - it'll call methods annotated for
  705. // handling, the default doXYZ(), or throw if a handler for the mode
  706. // is not found
  707. super.doDispatch(request, response);
  708. } catch (PortletException e) {
  709. if (e.getCause() == null) {
  710. // No cause interpreted as 'unknown mode' - pass that trough
  711. // so that the application can handle
  712. handleRequest(request, response);
  713. } else {
  714. // Something else failed, pass on
  715. throw e;
  716. }
  717. }
  718. }
  719. @Override
  720. public void serveResource(ResourceRequest request, ResourceResponse response)
  721. throws PortletException, IOException {
  722. handleRequest(request, response);
  723. }
  724. boolean requestCanCreateApplication(PortletRequest request,
  725. RequestType requestType) {
  726. if (requestType == RequestType.UIDL && isRepaintAll(request)) {
  727. return true;
  728. } else if (requestType == RequestType.RENDER) {
  729. // In most cases the first request is a render request that renders
  730. // the HTML fragment. This should create an application instance.
  731. return true;
  732. } else if (requestType == RequestType.EVENT) {
  733. // A portlet can also be sent an event even though it has not been
  734. // rendered, e.g. portlet on one page sends an event to a portlet on
  735. // another page and then moves the user to that page.
  736. return true;
  737. }
  738. return false;
  739. }
  740. private boolean isRepaintAll(PortletRequest request) {
  741. return (request.getParameter(URL_PARAMETER_REPAINT_ALL) != null)
  742. && (request.getParameter(URL_PARAMETER_REPAINT_ALL).equals("1"));
  743. }
  744. private void startApplication(PortletRequest request,
  745. Application application, PortletApplicationContext2 context)
  746. throws PortletException, MalformedURLException {
  747. if (!application.isRunning()) {
  748. Locale locale = request.getLocale();
  749. application.setLocale(locale);
  750. // No application URL when running inside a portlet
  751. application.start(new ApplicationStartEvent(null,
  752. applicationProperties, context, isProductionMode()));
  753. }
  754. }
  755. private void endApplication(PortletRequest request,
  756. PortletResponse response, Application application)
  757. throws IOException {
  758. final PortletSession session = request.getPortletSession();
  759. if (session != null) {
  760. getApplicationContext(session).removeApplication(application);
  761. }
  762. // Do not send any redirects when running inside a portlet.
  763. }
  764. private Application findApplicationInstance(
  765. WrappedPortletRequest wrappedRequest, RequestType requestType)
  766. throws PortletException, SessionExpiredException,
  767. MalformedURLException {
  768. PortletRequest request = wrappedRequest.getPortletRequest();
  769. boolean requestCanCreateApplication = requestCanCreateApplication(
  770. request, requestType);
  771. /* Find an existing application for this request. */
  772. Application application = getExistingApplication(request,
  773. requestCanCreateApplication);
  774. if (application != null) {
  775. /*
  776. * There is an existing application. We can use this as long as the
  777. * user not specifically requested to close or restart it.
  778. */
  779. final boolean restartApplication = (wrappedRequest
  780. .getParameter(URL_PARAMETER_RESTART_APPLICATION) != null);
  781. final boolean closeApplication = (wrappedRequest
  782. .getParameter(URL_PARAMETER_CLOSE_APPLICATION) != null);
  783. if (restartApplication) {
  784. closeApplication(application, request.getPortletSession(false));
  785. return createApplication(request);
  786. } else if (closeApplication) {
  787. closeApplication(application, request.getPortletSession(false));
  788. return null;
  789. } else {
  790. return application;
  791. }
  792. }
  793. // No existing application was found
  794. if (requestCanCreateApplication) {
  795. return createApplication(request);
  796. } else {
  797. throw new SessionExpiredException();
  798. }
  799. }
  800. private void closeApplication(Application application,
  801. PortletSession session) {
  802. if (application == null) {
  803. return;
  804. }
  805. application.close();
  806. if (session != null) {
  807. PortletApplicationContext2 context = getApplicationContext(session);
  808. context.removeApplication(application);
  809. }
  810. }
  811. private Application createApplication(PortletRequest request)
  812. throws PortletException, MalformedURLException {
  813. Application newApplication = getNewApplication(request);
  814. final PortletApplicationContext2 context = getApplicationContext(request
  815. .getPortletSession());
  816. context.addApplication(newApplication, request.getWindowID());
  817. return newApplication;
  818. }
  819. private Application getExistingApplication(PortletRequest request,
  820. boolean allowSessionCreation) throws MalformedURLException,
  821. SessionExpiredException {
  822. final PortletSession session = request
  823. .getPortletSession(allowSessionCreation);
  824. if (session == null) {
  825. throw new SessionExpiredException();
  826. }
  827. PortletApplicationContext2 context = getApplicationContext(session);
  828. Application application = context.getApplicationForWindowId(request
  829. .getWindowID());
  830. if (application == null) {
  831. return null;
  832. }
  833. if (application.isRunning()) {
  834. return application;
  835. }
  836. // application found but not running
  837. context.removeApplication(application);
  838. return null;
  839. }
  840. protected abstract Class<? extends Application> getApplicationClass()
  841. throws ClassNotFoundException;
  842. protected Application getNewApplication(PortletRequest request)
  843. throws PortletException {
  844. try {
  845. final Application application = getApplicationClass().newInstance();
  846. application.setRootPreserved(true);
  847. return application;
  848. } catch (final IllegalAccessException e) {
  849. throw new PortletException("getNewApplication failed", e);
  850. } catch (final InstantiationException e) {
  851. throw new PortletException("getNewApplication failed", e);
  852. } catch (final ClassNotFoundException e) {
  853. throw new PortletException("getNewApplication failed", e);
  854. }
  855. }
  856. protected ClassLoader getClassLoader() throws PortletException {
  857. // TODO Add support for custom class loader
  858. return getClass().getClassLoader();
  859. }
  860. /**
  861. * Get system messages from the current application class
  862. *
  863. * @return
  864. */
  865. protected SystemMessages getSystemMessages() {
  866. try {
  867. Class<? extends Application> appCls = getApplicationClass();
  868. Method m = appCls.getMethod("getSystemMessages", (Class[]) null);
  869. return (Application.SystemMessages) m.invoke(null, (Object[]) null);
  870. } catch (ClassNotFoundException e) {
  871. // This should never happen
  872. throw new SystemMessageException(e);
  873. } catch (SecurityException e) {
  874. throw new SystemMessageException(
  875. "Application.getSystemMessage() should be static public", e);
  876. } catch (NoSuchMethodException e) {
  877. // This is completely ok and should be silently ignored
  878. } catch (IllegalArgumentException e) {
  879. // This should never happen
  880. throw new SystemMessageException(e);
  881. } catch (IllegalAccessException e) {
  882. throw new SystemMessageException(
  883. "Application.getSystemMessage() should be static public", e);
  884. } catch (InvocationTargetException e) {
  885. // This should never happen
  886. throw new SystemMessageException(e);
  887. }
  888. return Application.getSystemMessages();
  889. }
  890. private void handleServiceException(PortletRequest request,
  891. PortletResponse response, Application application, Throwable e)
  892. throws IOException, PortletException {
  893. // TODO Check that this error handler is working when running inside a
  894. // portlet
  895. // if this was an UIDL request, response UIDL back to client
  896. if (getRequestType(request) == RequestType.UIDL) {
  897. Application.SystemMessages ci = getSystemMessages();
  898. criticalNotification(request, (ResourceResponse) response,
  899. ci.getInternalErrorCaption(), ci.getInternalErrorMessage(),
  900. null, ci.getInternalErrorURL());
  901. if (application != null) {
  902. application.getErrorHandler()
  903. .terminalError(new RequestError(e));
  904. } else {
  905. throw new PortletException(e);
  906. }
  907. } else {
  908. // Re-throw other exceptions
  909. throw new PortletException(e);
  910. }
  911. }
  912. @SuppressWarnings("serial")
  913. public class RequestError implements Terminal.ErrorEvent, Serializable {
  914. private final Throwable throwable;
  915. public RequestError(Throwable throwable) {
  916. this.throwable = throwable;
  917. }
  918. public Throwable getThrowable() {
  919. return throwable;
  920. }
  921. }
  922. /**
  923. * Send notification to client's application. Used to notify client of
  924. * critical errors and session expiration due to long inactivity. Server has
  925. * no knowledge of what application client refers to.
  926. *
  927. * @param request
  928. * the Portlet request instance.
  929. * @param response
  930. * the Portlet response to write to.
  931. * @param caption
  932. * for the notification
  933. * @param message
  934. * for the notification
  935. * @param details
  936. * a detail message to show in addition to the passed message.
  937. * Currently shown directly but could be hidden behind a details
  938. * drop down.
  939. * @param url
  940. * url to load after message, null for current page
  941. * @throws IOException
  942. * if the writing failed due to input/output error.
  943. */
  944. void criticalNotification(PortletRequest request, MimeResponse response,
  945. String caption, String message, String details, String url)
  946. throws IOException {
  947. // clients JS app is still running, but server application either
  948. // no longer exists or it might fail to perform reasonably.
  949. // send a notification to client's application and link how
  950. // to "restart" application.
  951. if (caption != null) {
  952. caption = "\"" + caption + "\"";
  953. }
  954. if (details != null) {
  955. if (message == null) {
  956. message = details;
  957. } else {
  958. message += "<br/><br/>" + details;
  959. }
  960. }
  961. if (message != null) {
  962. message = "\"" + message + "\"";
  963. }
  964. if (url != null) {
  965. url = "\"" + url + "\"";
  966. }
  967. // Set the response type
  968. response.setContentType("application/json; charset=UTF-8");
  969. final OutputStream out = response.getPortletOutputStream();
  970. final PrintWriter outWriter = new PrintWriter(new BufferedWriter(
  971. new OutputStreamWriter(out, "UTF-8")));
  972. outWriter.print("for(;;);[{\"changes\":[], \"meta\" : {"
  973. + "\"appError\": {" + "\"caption\":" + caption + ","
  974. + "\"message\" : " + message + "," + "\"url\" : " + url
  975. + "}}, \"resources\": {}, \"locales\":[]}]");
  976. outWriter.close();
  977. }
  978. /**
  979. *
  980. * Gets the application context for a PortletSession. If no context is
  981. * currently stored in a session a new context is created and stored in the
  982. * session.
  983. *
  984. * @param portletSession
  985. * the portlet session.
  986. * @return the application context for the session.
  987. */
  988. protected PortletApplicationContext2 getApplicationContext(
  989. PortletSession portletSession) {
  990. return PortletApplicationContext2.getApplicationContext(portletSession);
  991. }
  992. }