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.

UIInitHandler.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /*
  2. * Copyright 2000-2014 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.server.communication;
  17. import java.io.IOException;
  18. import java.io.OutputStream;
  19. import java.io.StringWriter;
  20. import java.util.List;
  21. import java.util.logging.Level;
  22. import java.util.logging.Logger;
  23. import com.vaadin.annotations.PreserveOnRefresh;
  24. import com.vaadin.server.LegacyApplicationUIProvider;
  25. import com.vaadin.server.SynchronizedRequestHandler;
  26. import com.vaadin.server.UIClassSelectionEvent;
  27. import com.vaadin.server.UICreateEvent;
  28. import com.vaadin.server.UIProvider;
  29. import com.vaadin.server.VaadinRequest;
  30. import com.vaadin.server.VaadinResponse;
  31. import com.vaadin.server.VaadinService;
  32. import com.vaadin.server.VaadinSession;
  33. import com.vaadin.shared.ApplicationConstants;
  34. import com.vaadin.shared.JsonConstants;
  35. import com.vaadin.shared.communication.PushMode;
  36. import com.vaadin.shared.ui.ui.Transport;
  37. import com.vaadin.shared.ui.ui.UIConstants;
  38. import com.vaadin.ui.UI;
  39. import elemental.json.Json;
  40. import elemental.json.JsonException;
  41. import elemental.json.JsonObject;
  42. import elemental.json.impl.JsonUtil;
  43. /**
  44. * Handles an initial request from the client to initialize a {@link UI}.
  45. *
  46. * @author Vaadin Ltd
  47. * @since 7.1
  48. */
  49. public abstract class UIInitHandler extends SynchronizedRequestHandler {
  50. public static final String BROWSER_DETAILS_PARAMETER = "v-browserDetails";
  51. protected abstract boolean isInitRequest(VaadinRequest request);
  52. @Override
  53. protected boolean canHandleRequest(VaadinRequest request) {
  54. return isInitRequest(request);
  55. }
  56. @Override
  57. public boolean synchronizedHandleRequest(VaadinSession session,
  58. VaadinRequest request, VaadinResponse response) throws IOException {
  59. try {
  60. assert UI.getCurrent() == null;
  61. // Update browser information from the request
  62. session.getBrowser().updateRequestDetails(request);
  63. UI uI = getBrowserDetailsUI(request, session);
  64. session.getCommunicationManager().repaintAll(uI);
  65. JsonObject params = Json.createObject();
  66. params.put(UIConstants.UI_ID_PARAMETER, uI.getUIId());
  67. String initialUIDL = getInitialUidl(request, uI);
  68. params.put("uidl", initialUIDL);
  69. return commitJsonResponse(request, response,
  70. JsonUtil.stringify(params));
  71. } catch (JsonException e) {
  72. throw new IOException("Error producing initial UIDL", e);
  73. }
  74. }
  75. /**
  76. * Commit the JSON response. We can't write immediately to the output stream
  77. * as we want to write only a critical notification if something goes wrong
  78. * during the response handling.
  79. *
  80. * @param request
  81. * The request that resulted in this response
  82. * @param response
  83. * The response to write to
  84. * @param json
  85. * The JSON to write
  86. * @return true if the JSON was written successfully, false otherwise
  87. * @throws IOException
  88. * If there was an exception while writing to the output
  89. */
  90. static boolean commitJsonResponse(VaadinRequest request,
  91. VaadinResponse response, String json) throws IOException {
  92. // The response was produced without errors so write it to the client
  93. response.setContentType(JsonConstants.JSON_CONTENT_TYPE);
  94. // Ensure that the browser does not cache UIDL responses.
  95. // iOS 6 Safari requires this (#9732)
  96. response.setHeader("Cache-Control", "no-cache");
  97. byte[] b = json.getBytes("UTF-8");
  98. response.setContentLength(b.length);
  99. OutputStream outputStream = response.getOutputStream();
  100. outputStream.write(b);
  101. // NOTE GateIn requires the buffers to be flushed to work
  102. outputStream.flush();
  103. return true;
  104. }
  105. private UI getBrowserDetailsUI(VaadinRequest request, VaadinSession session) {
  106. VaadinService vaadinService = request.getService();
  107. List<UIProvider> uiProviders = session.getUIProviders();
  108. UIClassSelectionEvent classSelectionEvent = new UIClassSelectionEvent(
  109. request);
  110. UIProvider provider = null;
  111. Class<? extends UI> uiClass = null;
  112. for (UIProvider p : uiProviders) {
  113. // Check for existing LegacyWindow
  114. if (p instanceof LegacyApplicationUIProvider) {
  115. LegacyApplicationUIProvider legacyProvider = (LegacyApplicationUIProvider) p;
  116. UI existingUi = legacyProvider
  117. .getExistingUI(classSelectionEvent);
  118. if (existingUi != null) {
  119. reinitUI(existingUi, request);
  120. return existingUi;
  121. }
  122. }
  123. uiClass = p.getUIClass(classSelectionEvent);
  124. if (uiClass != null) {
  125. provider = p;
  126. break;
  127. }
  128. }
  129. if (provider == null || uiClass == null) {
  130. return null;
  131. }
  132. // Check for an existing UI based on embed id
  133. String embedId = getEmbedId(request);
  134. UI retainedUI = session.getUIByEmbedId(embedId);
  135. if (retainedUI != null) {
  136. if (vaadinService.preserveUIOnRefresh(provider, new UICreateEvent(
  137. request, uiClass))) {
  138. if (uiClass.isInstance(retainedUI)) {
  139. reinitUI(retainedUI, request);
  140. return retainedUI;
  141. } else {
  142. getLogger().info(
  143. "Not using the preserved UI " + embedId
  144. + " because it is of type "
  145. + retainedUI.getClass() + " but " + uiClass
  146. + " is expected for the request.");
  147. }
  148. }
  149. /*
  150. * Previous UI without preserve on refresh will be closed when the
  151. * new UI gets added to the session.
  152. */
  153. }
  154. // No existing UI found - go on by creating and initializing one
  155. Integer uiId = Integer.valueOf(session.getNextUIid());
  156. // Explicit Class.cast to detect if the UIProvider does something
  157. // unexpected
  158. UICreateEvent event = new UICreateEvent(request, uiClass, uiId);
  159. UI ui = uiClass.cast(provider.createInstance(event));
  160. // Initialize some fields for a newly created UI
  161. if (ui.getSession() != session) {
  162. // Session already set for LegacyWindow
  163. ui.setSession(session);
  164. }
  165. PushMode pushMode = provider.getPushMode(event);
  166. if (pushMode == null) {
  167. pushMode = session.getService().getDeploymentConfiguration()
  168. .getPushMode();
  169. }
  170. ui.getPushConfiguration().setPushMode(pushMode);
  171. Transport transport = provider.getPushTransport(event);
  172. if (transport != null) {
  173. ui.getPushConfiguration().setTransport(transport);
  174. }
  175. // Set thread local here so it is available in init
  176. UI.setCurrent(ui);
  177. ui.doInit(request, uiId.intValue(), embedId);
  178. session.addUI(ui);
  179. // Warn if the window can't be preserved
  180. if (embedId == null
  181. && vaadinService.preserveUIOnRefresh(provider, event)) {
  182. getLogger().warning(
  183. "There is no embed id available for UI " + uiClass
  184. + " that should be preserved.");
  185. }
  186. return ui;
  187. }
  188. /**
  189. * Constructs an embed id based on information in the request.
  190. *
  191. * @since 7.2
  192. *
  193. * @param request
  194. * the request to get embed information from
  195. * @return the embed id, or <code>null</code> if id is not available.
  196. *
  197. * @see UI#getEmbedId()
  198. */
  199. protected String getEmbedId(VaadinRequest request) {
  200. // Parameters sent by vaadinBootstrap.js
  201. String windowName = request.getParameter("v-wn");
  202. String appId = request.getParameter("v-appId");
  203. if (windowName != null && appId != null) {
  204. return windowName + '.' + appId;
  205. } else {
  206. return null;
  207. }
  208. }
  209. /**
  210. * Updates a UI that has already been initialized but is now loaded again,
  211. * e.g. because of {@link PreserveOnRefresh}.
  212. *
  213. * @param ui
  214. * @param request
  215. */
  216. private void reinitUI(UI ui, VaadinRequest request) {
  217. UI.setCurrent(ui);
  218. ui.doRefresh(request);
  219. }
  220. /**
  221. * Generates the initial UIDL message that can e.g. be included in a html
  222. * page to avoid a separate round trip just for getting the UIDL.
  223. *
  224. * @param request
  225. * the request that caused the initialization
  226. * @param uI
  227. * the UI for which the UIDL should be generated
  228. * @return a string with the initial UIDL message
  229. * @throws IOException
  230. */
  231. protected String getInitialUidl(VaadinRequest request, UI uI)
  232. throws IOException {
  233. StringWriter writer = new StringWriter();
  234. try {
  235. writer.write("{");
  236. VaadinSession session = uI.getSession();
  237. if (session.getConfiguration().isXsrfProtectionEnabled()) {
  238. writer.write(getSecurityKeyUIDL(session));
  239. }
  240. new UidlWriter().write(uI, writer, false);
  241. writer.write("}");
  242. String initialUIDL = writer.toString();
  243. getLogger().log(Level.FINE, "Initial UIDL:" + initialUIDL);
  244. return initialUIDL;
  245. } finally {
  246. writer.close();
  247. }
  248. }
  249. /**
  250. * Gets the security key (and generates one if needed) as UIDL.
  251. *
  252. * @param session
  253. * the vaadin session to which the security key belongs
  254. * @return the security key UIDL or "" if the feature is turned off
  255. */
  256. private static String getSecurityKeyUIDL(VaadinSession session) {
  257. String seckey = session.getCsrfToken();
  258. return "\"" + ApplicationConstants.UIDL_SECURITY_TOKEN_ID + "\":\""
  259. + seckey + "\",";
  260. }
  261. private static final Logger getLogger() {
  262. return Logger.getLogger(UIInitHandler.class.getName());
  263. }
  264. }