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

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