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 41KB

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