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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /*
  2. * Copyright 2000-2016 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,
  106. VaadinSession session) {
  107. VaadinService vaadinService = request.getService();
  108. List<UIProvider> uiProviders = session.getUIProviders();
  109. UIClassSelectionEvent classSelectionEvent = new UIClassSelectionEvent(
  110. request);
  111. UIProvider provider = null;
  112. Class<? extends UI> uiClass = null;
  113. for (UIProvider p : uiProviders) {
  114. // Check for existing LegacyWindow
  115. if (p instanceof LegacyApplicationUIProvider) {
  116. LegacyApplicationUIProvider legacyProvider = (LegacyApplicationUIProvider) p;
  117. UI existingUi = legacyProvider
  118. .getExistingUI(classSelectionEvent);
  119. if (existingUi != null) {
  120. reinitUI(existingUi, request);
  121. return existingUi;
  122. }
  123. }
  124. uiClass = p.getUIClass(classSelectionEvent);
  125. if (uiClass != null) {
  126. provider = p;
  127. break;
  128. }
  129. }
  130. if (provider == null || uiClass == null) {
  131. return null;
  132. }
  133. // Check for an existing UI based on embed id
  134. String embedId = getEmbedId(request);
  135. UI retainedUI = session.getUIByEmbedId(embedId);
  136. if (retainedUI != null) {
  137. if (vaadinService.preserveUIOnRefresh(provider,
  138. new UICreateEvent(request, uiClass))) {
  139. if (uiClass.isInstance(retainedUI)) {
  140. reinitUI(retainedUI, request);
  141. return retainedUI;
  142. } else {
  143. getLogger().info("Not using the preserved UI " + embedId
  144. + " because it is of type " + retainedUI.getClass()
  145. + " 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. Exception initException = null;
  178. try {
  179. ui.doInit(request, uiId.intValue(), embedId);
  180. } catch (Exception e) {
  181. initException = e;
  182. }
  183. session.addUI(ui);
  184. if (initException != null) {
  185. ui.getSession().getCommunicationManager()
  186. .handleConnectorRelatedException(ui, initException);
  187. }
  188. // Warn if the window can't be preserved
  189. if (embedId == null
  190. && vaadinService.preserveUIOnRefresh(provider, event)) {
  191. getLogger().warning("There is no embed id available for UI "
  192. + uiClass + " that should be preserved.");
  193. }
  194. return ui;
  195. }
  196. /**
  197. * Constructs an embed id based on information in the request.
  198. *
  199. * @since 7.2
  200. *
  201. * @param request
  202. * the request to get embed information from
  203. * @return the embed id, or <code>null</code> if id is not available.
  204. *
  205. * @see UI#getEmbedId()
  206. */
  207. protected String getEmbedId(VaadinRequest request) {
  208. // Parameters sent by vaadinBootstrap.js
  209. String windowName = request.getParameter("v-wn");
  210. String appId = request.getParameter("v-appId");
  211. if (windowName != null && appId != null) {
  212. return windowName + '.' + appId;
  213. } else {
  214. return null;
  215. }
  216. }
  217. /**
  218. * Updates a UI that has already been initialized but is now loaded again,
  219. * e.g. because of {@link PreserveOnRefresh}.
  220. *
  221. * @param ui
  222. * @param request
  223. */
  224. private void reinitUI(UI ui, VaadinRequest request) {
  225. UI.setCurrent(ui);
  226. ui.doRefresh(request);
  227. }
  228. /**
  229. * Generates the initial UIDL message that can e.g. be included in a html
  230. * page to avoid a separate round trip just for getting the UIDL.
  231. *
  232. * @param request
  233. * the request that caused the initialization
  234. * @param uI
  235. * the UI for which the UIDL should be generated
  236. * @return a string with the initial UIDL message
  237. * @throws IOException
  238. */
  239. protected String getInitialUidl(VaadinRequest request, UI uI)
  240. throws IOException {
  241. try (StringWriter writer = new StringWriter()) {
  242. writer.write("{");
  243. VaadinSession session = uI.getSession();
  244. if (session.getConfiguration().isXsrfProtectionEnabled()) {
  245. writer.write(getSecurityKeyUIDL(session));
  246. }
  247. if (uI.getPushConfiguration().getPushMode().isEnabled()) {
  248. writer.write(getPushIdUIDL(session));
  249. }
  250. new UidlWriter().write(uI, writer, false);
  251. writer.write("}");
  252. String initialUIDL = writer.toString();
  253. getLogger().log(Level.FINE, "Initial UIDL:" + initialUIDL);
  254. return initialUIDL;
  255. }
  256. }
  257. /**
  258. * Gets the security key (and generates one if needed) as UIDL.
  259. *
  260. * @param session
  261. * the vaadin session to which the security key belongs
  262. * @return the security key UIDL or "" if the feature is turned off
  263. */
  264. private static String getSecurityKeyUIDL(VaadinSession session) {
  265. String seckey = session.getCsrfToken();
  266. return "\"" + ApplicationConstants.UIDL_SECURITY_TOKEN_ID + "\":\""
  267. + seckey + "\",";
  268. }
  269. /**
  270. * Gets the push connection identifier as UIDL.
  271. *
  272. * @param session
  273. * the vaadin session to which the security key belongs
  274. * @return the push identifier UIDL
  275. */
  276. private static String getPushIdUIDL(VaadinSession session) {
  277. return "\"" + ApplicationConstants.UIDL_PUSH_ID + "\":\""
  278. + session.getPushId() + "\",";
  279. }
  280. private static final Logger getLogger() {
  281. return Logger.getLogger(UIInitHandler.class.getName());
  282. }
  283. }