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.

BootstrapHandler.java 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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;
  17. import java.io.BufferedWriter;
  18. import java.io.IOException;
  19. import java.io.OutputStreamWriter;
  20. import java.io.Serializable;
  21. import java.io.UnsupportedEncodingException;
  22. import java.net.URLEncoder;
  23. import java.util.ArrayList;
  24. import java.util.Collection;
  25. import java.util.Collections;
  26. import java.util.LinkedHashMap;
  27. import java.util.List;
  28. import java.util.Locale;
  29. import java.util.Map;
  30. import java.util.Map.Entry;
  31. import java.util.Set;
  32. import java.util.logging.Logger;
  33. import javax.servlet.http.HttpServletResponse;
  34. import org.jsoup.nodes.DataNode;
  35. import org.jsoup.nodes.Document;
  36. import org.jsoup.nodes.DocumentType;
  37. import org.jsoup.nodes.Element;
  38. import org.jsoup.nodes.Node;
  39. import org.jsoup.parser.Tag;
  40. import com.vaadin.annotations.Viewport;
  41. import com.vaadin.annotations.ViewportGeneratorClass;
  42. import com.vaadin.server.DependencyFilter.FilterContext;
  43. import com.vaadin.server.communication.AtmospherePushConnection;
  44. import com.vaadin.shared.ApplicationConstants;
  45. import com.vaadin.shared.VaadinUriResolver;
  46. import com.vaadin.shared.Version;
  47. import com.vaadin.shared.communication.PushMode;
  48. import com.vaadin.ui.Dependency;
  49. import com.vaadin.ui.Dependency.Type;
  50. import com.vaadin.ui.UI;
  51. import com.vaadin.util.ReflectTools;
  52. import elemental.json.Json;
  53. import elemental.json.JsonException;
  54. import elemental.json.JsonObject;
  55. import elemental.json.impl.JsonUtil;
  56. /**
  57. * Handles the initial request to start the application.
  58. *
  59. * @author Vaadin Ltd
  60. * @since 7.0.0
  61. *
  62. * @deprecated As of 7.0. Will likely change or be removed in a future version
  63. */
  64. @Deprecated
  65. public abstract class BootstrapHandler extends SynchronizedRequestHandler {
  66. /**
  67. * Parameter that is added to the UI init request if the session has already
  68. * been restarted when generating the bootstrap HTML and ?restartApplication
  69. * should thus be ignored when handling the UI init request.
  70. */
  71. public static final String IGNORE_RESTART_PARAM = "ignoreRestart";
  72. /**
  73. * Provides context information for the bootstrap process.
  74. */
  75. protected class BootstrapContext implements Serializable {
  76. private final VaadinResponse response;
  77. private final BootstrapFragmentResponse bootstrapResponse;
  78. private String themeName;
  79. private String appId;
  80. private PushMode pushMode;
  81. private JsonObject applicationParameters;
  82. private BootstrapUriResolver uriResolver;
  83. private WidgetsetInfo widgetsetInfo;
  84. /**
  85. * Creates a new context instance using the given Vaadin/HTTP response
  86. * and bootstrap response.
  87. *
  88. * @param response
  89. * the response object
  90. * @param bootstrapResponse
  91. * the bootstrap response object
  92. */
  93. public BootstrapContext(VaadinResponse response,
  94. BootstrapFragmentResponse bootstrapResponse) {
  95. this.response = response;
  96. this.bootstrapResponse = bootstrapResponse;
  97. }
  98. /**
  99. * Gets the Vaadin/HTTP response.
  100. *
  101. * @return the Vaadin/HTTP response
  102. */
  103. public VaadinResponse getResponse() {
  104. return response;
  105. }
  106. /**
  107. * Gets the Vaadin/HTTP request.
  108. *
  109. * @return the Vaadin/HTTP request
  110. */
  111. public VaadinRequest getRequest() {
  112. return bootstrapResponse.getRequest();
  113. }
  114. /**
  115. * Gets the Vaadin session.
  116. *
  117. * @return the Vaadin session
  118. */
  119. public VaadinSession getSession() {
  120. return bootstrapResponse.getSession();
  121. }
  122. /**
  123. * Gets the UI class which will be used.
  124. *
  125. * @return the UI class
  126. */
  127. public Class<? extends UI> getUIClass() {
  128. return bootstrapResponse.getUiClass();
  129. }
  130. /**
  131. * Gets information about the widgetset to use.
  132. *
  133. * @return the widgetset which will be loaded
  134. */
  135. public WidgetsetInfo getWidgetsetInfo() {
  136. if (widgetsetInfo == null) {
  137. widgetsetInfo = getWidgetsetForUI(this);
  138. }
  139. return widgetsetInfo;
  140. }
  141. /**
  142. * @return returns the name of the widgetset to use
  143. * @deprecated use {@link #getWidgetsetInfo()} instead
  144. */
  145. @Deprecated
  146. public String getWidgetsetName() {
  147. return getWidgetsetInfo().getWidgetsetName();
  148. }
  149. /**
  150. * Gets the name of the theme to use.
  151. *
  152. * @return the name of the theme, with special characters escaped or
  153. * removed
  154. */
  155. public String getThemeName() {
  156. if (themeName == null) {
  157. themeName = findAndEscapeThemeName(this);
  158. }
  159. return themeName;
  160. }
  161. /**
  162. * Gets the push mode to use.
  163. *
  164. * @return the desired push mode
  165. */
  166. public PushMode getPushMode() {
  167. if (pushMode == null) {
  168. UICreateEvent event = new UICreateEvent(getRequest(),
  169. getUIClass());
  170. pushMode = getBootstrapResponse().getUIProvider()
  171. .getPushMode(event);
  172. if (pushMode == null) {
  173. pushMode = getRequest().getService()
  174. .getDeploymentConfiguration().getPushMode();
  175. }
  176. if (pushMode.isEnabled()
  177. && !getRequest().getService().ensurePushAvailable()) {
  178. /*
  179. * Fall back if not supported (ensurePushAvailable will log
  180. * information to the developer the first time this happens)
  181. */
  182. pushMode = PushMode.DISABLED;
  183. }
  184. }
  185. return pushMode;
  186. }
  187. /**
  188. * Gets the application id.
  189. *
  190. * The application id is defined by
  191. * {@link VaadinService#getMainDivId(VaadinSession, VaadinRequest, Class)}
  192. *
  193. * @return the application id
  194. */
  195. public String getAppId() {
  196. if (appId == null) {
  197. appId = getRequest().getService().getMainDivId(getSession(),
  198. getRequest(), getUIClass());
  199. }
  200. return appId;
  201. }
  202. /**
  203. * Gets the bootstrap response object.
  204. *
  205. * @return the bootstrap response object
  206. */
  207. public BootstrapFragmentResponse getBootstrapResponse() {
  208. return bootstrapResponse;
  209. }
  210. /**
  211. * Gets the application parameters specified by the BootstrapHandler.
  212. *
  213. * @return the application parameters which will be written on the page
  214. */
  215. public JsonObject getApplicationParameters() {
  216. if (applicationParameters == null) {
  217. applicationParameters = BootstrapHandler.this
  218. .getApplicationParameters(this);
  219. }
  220. return applicationParameters;
  221. }
  222. /**
  223. * Gets the URI resolver to use for bootstrap resources.
  224. *
  225. * @return the URI resolver
  226. * @since 8.1
  227. */
  228. public BootstrapUriResolver getUriResolver() {
  229. if (uriResolver == null) {
  230. uriResolver = new BootstrapUriResolver(this);
  231. }
  232. return uriResolver;
  233. }
  234. }
  235. /**
  236. * The URI resolver used in the bootstrap process.
  237. *
  238. * @since 8.1
  239. */
  240. protected static class BootstrapUriResolver extends VaadinUriResolver {
  241. private final BootstrapContext context;
  242. private String frontendUrl;
  243. /**
  244. * Creates a new bootstrap resolver based on the given bootstrap
  245. * context.
  246. *
  247. * @param bootstrapContext
  248. * the bootstrap context
  249. */
  250. public BootstrapUriResolver(BootstrapContext bootstrapContext) {
  251. context = bootstrapContext;
  252. }
  253. @Override
  254. protected String getVaadinDirUrl() {
  255. return context.getApplicationParameters()
  256. .getString(ApplicationConstants.VAADIN_DIR_URL);
  257. }
  258. @Override
  259. protected String getThemeUri() {
  260. return getVaadinDirUrl() + "themes/" + context.getThemeName();
  261. }
  262. @Override
  263. protected String getServiceUrlParameterName() {
  264. return getConfigOrNull(
  265. ApplicationConstants.SERVICE_URL_PARAMETER_NAME);
  266. }
  267. @Override
  268. protected String getServiceUrl() {
  269. String serviceUrl = getConfigOrNull(
  270. ApplicationConstants.SERVICE_URL);
  271. if (serviceUrl == null) {
  272. return "./";
  273. } else if (!serviceUrl.endsWith("/")) {
  274. serviceUrl += "/";
  275. }
  276. return serviceUrl;
  277. }
  278. private String getConfigOrNull(String name) {
  279. JsonObject parameters = context.getApplicationParameters();
  280. if (parameters.hasKey(name)) {
  281. return parameters.getString(name);
  282. } else {
  283. return null;
  284. }
  285. }
  286. @Override
  287. protected String encodeQueryStringParameterValue(String queryString) {
  288. String encodedString = null;
  289. try {
  290. encodedString = URLEncoder.encode(queryString, "UTF-8");
  291. } catch (UnsupportedEncodingException e) {
  292. // should never happen
  293. throw new RuntimeException("Could not find UTF-8", e);
  294. }
  295. return encodedString;
  296. }
  297. @Override
  298. protected String getContextRootUrl() {
  299. String root = context.getApplicationParameters()
  300. .getString(ApplicationConstants.CONTEXT_ROOT_URL);
  301. assert root.endsWith("/");
  302. return root;
  303. }
  304. @Override
  305. protected String getFrontendUrl() {
  306. if (frontendUrl == null) {
  307. frontendUrl = resolveFrontendUrl(context.getSession());
  308. }
  309. return frontendUrl;
  310. }
  311. }
  312. /**
  313. * Resolves the URL to use for the {@literal frontend://} protocol.
  314. *
  315. * @param session
  316. * the session of the user to resolve the protocol for
  317. * @return the URL that frontend:// resolves to, possibly using another
  318. * internal protocol
  319. * @since 8.1
  320. */
  321. public static String resolveFrontendUrl(VaadinSession session) {
  322. DeploymentConfiguration configuration = session.getConfiguration();
  323. String frontendUrl;
  324. if (session.getBrowser().isEs6Supported()) {
  325. frontendUrl = configuration.getApplicationOrSystemProperty(
  326. ApplicationConstants.FRONTEND_URL_ES6,
  327. ApplicationConstants.FRONTEND_URL_ES6_DEFAULT_VALUE);
  328. } else {
  329. frontendUrl = configuration.getApplicationOrSystemProperty(
  330. ApplicationConstants.FRONTEND_URL_ES5,
  331. ApplicationConstants.FRONTEND_URL_ES5_DEFAULT_VALUE);
  332. }
  333. if (!frontendUrl.endsWith("/")) {
  334. frontendUrl += "/";
  335. }
  336. return frontendUrl;
  337. }
  338. @Override
  339. protected boolean canHandleRequest(VaadinRequest request) {
  340. // We do not want to handle /APP requests here, instead let it fall
  341. // through and produce a 404
  342. return !ServletPortletHelper.isAppRequest(request);
  343. }
  344. @Override
  345. public boolean synchronizedHandleRequest(VaadinSession session,
  346. VaadinRequest request, VaadinResponse response) throws IOException {
  347. try {
  348. List<UIProvider> uiProviders = session.getUIProviders();
  349. UIClassSelectionEvent classSelectionEvent = new UIClassSelectionEvent(
  350. request);
  351. // Find UI provider and UI class
  352. Class<? extends UI> uiClass = null;
  353. UIProvider provider = null;
  354. for (UIProvider p : uiProviders) {
  355. uiClass = p.getUIClass(classSelectionEvent);
  356. // If we found something
  357. if (uiClass != null) {
  358. provider = p;
  359. break;
  360. }
  361. }
  362. if (provider == null) {
  363. // Can't generate bootstrap if no UI provider matches
  364. return false;
  365. }
  366. BootstrapFragmentResponse bootstrapResponse = new BootstrapFragmentResponse(
  367. this, request, session, uiClass, new ArrayList<>(),
  368. provider);
  369. BootstrapContext context = new BootstrapContext(response,
  370. bootstrapResponse);
  371. bootstrapResponse.setUriResolver(context.getUriResolver());
  372. setupMainDiv(context);
  373. BootstrapFragmentResponse fragmentResponse = context
  374. .getBootstrapResponse();
  375. session.modifyBootstrapResponse(fragmentResponse);
  376. String html = getBootstrapHtml(context);
  377. writeBootstrapPage(response, html);
  378. } catch (JsonException e) {
  379. writeError(response, e);
  380. }
  381. return true;
  382. }
  383. private String getBootstrapHtml(BootstrapContext context) {
  384. VaadinRequest request = context.getRequest();
  385. VaadinResponse response = context.getResponse();
  386. VaadinService vaadinService = request.getService();
  387. BootstrapFragmentResponse fragmentResponse = context
  388. .getBootstrapResponse();
  389. if (vaadinService.isStandalone(request)) {
  390. Map<String, Object> headers = new LinkedHashMap<>();
  391. Document document = Document.createShell("");
  392. BootstrapPageResponse pageResponse = new BootstrapPageResponse(this,
  393. request, context.getSession(), context.getUIClass(),
  394. document, headers, fragmentResponse.getUIProvider());
  395. pageResponse.setUriResolver(context.getUriResolver());
  396. List<Node> fragmentNodes = fragmentResponse.getFragmentNodes();
  397. Element body = document.body();
  398. for (Node node : fragmentNodes) {
  399. body.appendChild(node);
  400. }
  401. setupStandaloneDocument(context, pageResponse);
  402. context.getSession().modifyBootstrapResponse(pageResponse);
  403. sendBootstrapHeaders(response, headers);
  404. return document.outerHtml();
  405. } else {
  406. StringBuilder sb = new StringBuilder();
  407. for (Node node : fragmentResponse.getFragmentNodes()) {
  408. if (sb.length() != 0) {
  409. sb.append('\n');
  410. }
  411. sb.append(node.outerHtml());
  412. }
  413. return sb.toString();
  414. }
  415. }
  416. private void sendBootstrapHeaders(VaadinResponse response,
  417. Map<String, Object> headers) {
  418. Set<Entry<String, Object>> entrySet = headers.entrySet();
  419. for (Entry<String, Object> header : entrySet) {
  420. Object value = header.getValue();
  421. if (value instanceof String) {
  422. response.setHeader(header.getKey(), (String) value);
  423. } else if (value instanceof Long) {
  424. response.setDateHeader(header.getKey(),
  425. ((Long) value).longValue());
  426. } else {
  427. throw new RuntimeException(
  428. "Unsupported header value: " + value);
  429. }
  430. }
  431. }
  432. private void writeBootstrapPage(VaadinResponse response, String html)
  433. throws IOException {
  434. response.setContentType(
  435. ApplicationConstants.CONTENT_TYPE_TEXT_HTML_UTF_8);
  436. try (BufferedWriter writer = new BufferedWriter(
  437. new OutputStreamWriter(response.getOutputStream(), "UTF-8"))) {
  438. writer.append(html);
  439. }
  440. }
  441. private void setupStandaloneDocument(BootstrapContext context,
  442. BootstrapPageResponse response) {
  443. response.setHeader("Cache-Control", "no-cache");
  444. response.setHeader("Pragma", "no-cache");
  445. response.setDateHeader("Expires", 0);
  446. Document document = response.getDocument();
  447. DocumentType doctype = new DocumentType("html", "", "",
  448. document.baseUri());
  449. document.child(0).before(doctype);
  450. Element head = document.head();
  451. head.appendElement("meta").attr("http-equiv", "Content-Type").attr(
  452. "content", ApplicationConstants.CONTENT_TYPE_TEXT_HTML_UTF_8);
  453. // Force IE 11 to use IE 11 mode.
  454. head.appendElement("meta").attr("http-equiv", "X-UA-Compatible").attr("content", "IE=11");
  455. Class<? extends UI> uiClass = context.getUIClass();
  456. String viewportContent = null;
  457. Viewport viewportAnnotation = uiClass.getAnnotation(Viewport.class);
  458. ViewportGeneratorClass viewportGeneratorClassAnnotation = uiClass
  459. .getAnnotation(ViewportGeneratorClass.class);
  460. if (viewportAnnotation != null
  461. && viewportGeneratorClassAnnotation != null) {
  462. throw new IllegalStateException(uiClass.getCanonicalName()
  463. + " cannot be annotated with both @"
  464. + Viewport.class.getSimpleName() + " and @"
  465. + ViewportGeneratorClass.class.getSimpleName());
  466. }
  467. if (viewportAnnotation != null) {
  468. viewportContent = viewportAnnotation.value();
  469. } else if (viewportGeneratorClassAnnotation != null) {
  470. Class<? extends ViewportGenerator> viewportGeneratorClass = viewportGeneratorClassAnnotation
  471. .value();
  472. try {
  473. viewportContent = ReflectTools
  474. .createInstance(viewportGeneratorClass)
  475. .getViewport(context.getRequest());
  476. } catch (Exception e) {
  477. throw new RuntimeException(
  478. "Error processing viewport generator "
  479. + viewportGeneratorClass.getCanonicalName(),
  480. e);
  481. }
  482. }
  483. if (viewportContent != null) {
  484. head.appendElement("meta").attr("name", "viewport").attr("content",
  485. viewportContent);
  486. }
  487. String title = response.getUIProvider().getPageTitle(
  488. new UICreateEvent(context.getRequest(), context.getUIClass()));
  489. if (title != null) {
  490. head.appendElement("title").appendText(title);
  491. }
  492. head.appendElement("style").attr("type", "text/css")
  493. .appendText("html, body {height:100%;margin:0;}");
  494. // Add favicon links
  495. String themeName = context.getThemeName();
  496. if (themeName != null) {
  497. String themeUri = getThemeUri(context, themeName);
  498. head.appendElement("link").attr("rel", "shortcut icon")
  499. .attr("type", "image/vnd.microsoft.icon")
  500. .attr("href", themeUri + "/favicon.ico");
  501. head.appendElement("link").attr("rel", "icon")
  502. .attr("type", "image/vnd.microsoft.icon")
  503. .attr("href", themeUri + "/favicon.ico");
  504. }
  505. Collection<? extends Dependency> deps = Dependency.findDependencies(
  506. Collections.singletonList(uiClass),
  507. context.getSession().getCommunicationManager(),
  508. new FilterContext(context.getSession()));
  509. for (Dependency dependency : deps) {
  510. Type type = dependency.getType();
  511. String url = context.getUriResolver()
  512. .resolveVaadinUri(dependency.getUrl());
  513. if (type == Type.HTMLIMPORT) {
  514. head.appendElement("link").attr("rel", "import").attr("href",
  515. url);
  516. } else if (type == Type.JAVASCRIPT) {
  517. head.appendElement("script").attr("type", "text/javascript")
  518. .attr("src", url);
  519. } else if (type == Type.STYLESHEET) {
  520. head.appendElement("link").attr("rel", "stylesheet")
  521. .attr("type", "text/css").attr("href", url);
  522. } else {
  523. getLogger().severe("Ignoring unknown dependency type "
  524. + dependency.getType());
  525. }
  526. }
  527. Element body = document.body();
  528. body.attr("scroll", "auto");
  529. body.addClass(ApplicationConstants.GENERATED_BODY_CLASSNAME);
  530. }
  531. private static Logger getLogger() {
  532. return Logger.getLogger(BootstrapHandler.class.getName());
  533. }
  534. protected String getMainDivStyle(BootstrapContext context) {
  535. return null;
  536. }
  537. public WidgetsetInfo getWidgetsetForUI(BootstrapContext context) {
  538. VaadinRequest request = context.getRequest();
  539. UICreateEvent event = new UICreateEvent(context.getRequest(),
  540. context.getUIClass());
  541. WidgetsetInfo widgetset = context.getBootstrapResponse().getUIProvider()
  542. .getWidgetsetInfo(event);
  543. if (widgetset == null) {
  544. // TODO do we want to move WidgetsetInfoImpl elsewhere?
  545. widgetset = new WidgetsetInfoImpl(
  546. request.getService().getConfiguredWidgetset(request));
  547. }
  548. return widgetset;
  549. }
  550. /**
  551. * Method to write the div element into which that actual Vaadin application
  552. * is rendered.
  553. * <p>
  554. * Override this method if you want to add some custom html around around
  555. * the div element into which the actual Vaadin application will be
  556. * rendered.
  557. *
  558. * @param context
  559. *
  560. * @throws IOException
  561. */
  562. private void setupMainDiv(BootstrapContext context) throws IOException {
  563. String style = getMainDivStyle(context);
  564. /*- Add classnames;
  565. * .v-app
  566. * .v-app-loading
  567. *- Additionally added from javascript:
  568. * <themeName, remove non-alphanum>
  569. */
  570. List<Node> fragmentNodes = context.getBootstrapResponse()
  571. .getFragmentNodes();
  572. Element mainDiv = new Element(Tag.valueOf("div"), "");
  573. mainDiv.attr("id", context.getAppId());
  574. mainDiv.addClass("v-app");
  575. mainDiv.addClass(context.getThemeName());
  576. mainDiv.addClass(context.getUIClass().getSimpleName()
  577. .toLowerCase(Locale.ENGLISH));
  578. if (style != null && !style.isEmpty()) {
  579. mainDiv.attr("style", style);
  580. }
  581. mainDiv.appendElement("div").addClass("v-app-loading");
  582. mainDiv.appendElement("noscript").append(
  583. "You have to enable javascript in your browser to use an application built with Vaadin.");
  584. fragmentNodes.add(mainDiv);
  585. VaadinRequest request = context.getRequest();
  586. VaadinService vaadinService = request.getService();
  587. String vaadinLocation = vaadinService.getStaticFileLocation(request)
  588. + "/VAADIN/";
  589. // Parameter appended to JS to bypass caches after version upgrade.
  590. String versionQueryParam = "?v=" + Version.getFullVersion();
  591. if (context.getPushMode().isEnabled()) {
  592. // Load client-side dependencies for push support
  593. String pushJS = vaadinLocation;
  594. if (context.getRequest().getService().getDeploymentConfiguration()
  595. .isProductionMode()) {
  596. pushJS += ApplicationConstants.VAADIN_PUSH_JS;
  597. } else {
  598. pushJS += ApplicationConstants.VAADIN_PUSH_DEBUG_JS;
  599. }
  600. pushJS += versionQueryParam;
  601. fragmentNodes.add(new Element(Tag.valueOf("script"), "")
  602. .attr("type", "text/javascript").attr("src", pushJS));
  603. }
  604. String bootstrapLocation = vaadinLocation
  605. + ApplicationConstants.VAADIN_BOOTSTRAP_JS + versionQueryParam;
  606. fragmentNodes.add(new Element(Tag.valueOf("script"), "")
  607. .attr("type", "text/javascript")
  608. .attr("src", bootstrapLocation));
  609. Element mainScriptTag = new Element(Tag.valueOf("script"), "")
  610. .attr("type", "text/javascript");
  611. StringBuilder builder = new StringBuilder();
  612. builder.append("//<![CDATA[\n");
  613. builder.append("if (!window.vaadin) alert(" + JsonUtil.quote(
  614. "Failed to load the bootstrap javascript: " + bootstrapLocation)
  615. + ");\n");
  616. appendMainScriptTagContents(context, builder);
  617. builder.append("//]]>");
  618. mainScriptTag.appendChild(
  619. new DataNode(builder.toString(), mainScriptTag.baseUri()));
  620. fragmentNodes.add(mainScriptTag);
  621. }
  622. protected void appendMainScriptTagContents(BootstrapContext context,
  623. StringBuilder builder) throws IOException {
  624. JsonObject appConfig = context.getApplicationParameters();
  625. boolean isDebug = !context.getSession().getConfiguration()
  626. .isProductionMode();
  627. if (isDebug) {
  628. /*
  629. * Add tracking needed for getting bootstrap metrics to the client
  630. * side Profiler if another implementation hasn't already been
  631. * added.
  632. */
  633. builder.append(
  634. "if (typeof window.__gwtStatsEvent != 'function') {\n");
  635. builder.append("vaadin.gwtStatsEvents = [];\n");
  636. builder.append(
  637. "window.__gwtStatsEvent = function(event) {vaadin.gwtStatsEvents.push(event); return true;};\n");
  638. builder.append("}\n");
  639. }
  640. builder.append("vaadin.initApplication(\"");
  641. builder.append(context.getAppId());
  642. builder.append("\",");
  643. appendJsonObject(builder, appConfig, isDebug);
  644. builder.append(");\n");
  645. }
  646. private static void appendJsonObject(StringBuilder builder,
  647. JsonObject jsonObject, boolean isDebug) {
  648. if (isDebug) {
  649. builder.append(JsonUtil.stringify(jsonObject, 4));
  650. } else {
  651. builder.append(JsonUtil.stringify(jsonObject));
  652. }
  653. }
  654. protected JsonObject getApplicationParameters(BootstrapContext context) {
  655. VaadinRequest request = context.getRequest();
  656. VaadinSession session = context.getSession();
  657. VaadinService vaadinService = request.getService();
  658. JsonObject appConfig = Json.createObject();
  659. String themeName = context.getThemeName();
  660. if (themeName != null) {
  661. appConfig.put("theme", themeName);
  662. }
  663. // Ignore restartApplication that might be passed to UI init
  664. if (request.getParameter(
  665. VaadinService.URL_PARAMETER_RESTART_APPLICATION) != null) {
  666. appConfig.put("extraParams", "&" + IGNORE_RESTART_PARAM + "=1");
  667. }
  668. JsonObject versionInfo = Json.createObject();
  669. versionInfo.put("vaadinVersion", Version.getFullVersion());
  670. String atmosphereVersion = AtmospherePushConnection
  671. .getAtmosphereVersion();
  672. if (atmosphereVersion != null) {
  673. versionInfo.put("atmosphereVersion", atmosphereVersion);
  674. }
  675. appConfig.put("versionInfo", versionInfo);
  676. WidgetsetInfo widgetsetInfo = context.getWidgetsetInfo();
  677. appConfig.put("widgetset", VaadinServlet
  678. .stripSpecialChars(widgetsetInfo.getWidgetsetName()));
  679. // add widgetset url if not null
  680. if (widgetsetInfo.getWidgetsetUrl() != null) {
  681. appConfig.put("widgetsetUrl", widgetsetInfo.getWidgetsetUrl());
  682. }
  683. appConfig.put("widgetsetReady", !widgetsetInfo.isCdn());
  684. // Use locale from session if set, else from the request
  685. Locale locale = ServletPortletHelper.findLocale(null,
  686. context.getSession(), context.getRequest());
  687. // Get system messages
  688. SystemMessages systemMessages = vaadinService.getSystemMessages(locale,
  689. request);
  690. if (systemMessages != null) {
  691. // Write the CommunicationError -message to client
  692. JsonObject comErrMsg = Json.createObject();
  693. putValueOrNull(comErrMsg, "caption",
  694. systemMessages.getCommunicationErrorCaption());
  695. putValueOrNull(comErrMsg, "message",
  696. systemMessages.getCommunicationErrorMessage());
  697. putValueOrNull(comErrMsg, "url",
  698. systemMessages.getCommunicationErrorURL());
  699. appConfig.put("comErrMsg", comErrMsg);
  700. JsonObject authErrMsg = Json.createObject();
  701. putValueOrNull(authErrMsg, "caption",
  702. systemMessages.getAuthenticationErrorCaption());
  703. putValueOrNull(authErrMsg, "message",
  704. systemMessages.getAuthenticationErrorMessage());
  705. putValueOrNull(authErrMsg, "url",
  706. systemMessages.getAuthenticationErrorURL());
  707. appConfig.put("authErrMsg", authErrMsg);
  708. JsonObject sessExpMsg = Json.createObject();
  709. putValueOrNull(sessExpMsg, "caption",
  710. systemMessages.getSessionExpiredCaption());
  711. putValueOrNull(sessExpMsg, "message",
  712. systemMessages.getSessionExpiredMessage());
  713. putValueOrNull(sessExpMsg, "url",
  714. systemMessages.getSessionExpiredURL());
  715. appConfig.put("sessExpMsg", sessExpMsg);
  716. }
  717. appConfig.put(ApplicationConstants.CONTEXT_ROOT_URL,
  718. getContextRootPath(context));
  719. // getStaticFileLocation documented to never end with a slash
  720. // vaadinDir should always end with a slash
  721. String vaadinDir = vaadinService.getStaticFileLocation(request)
  722. + "/VAADIN/";
  723. appConfig.put(ApplicationConstants.VAADIN_DIR_URL, vaadinDir);
  724. appConfig.put(ApplicationConstants.FRONTEND_URL,
  725. context.getUriResolver().getFrontendUrl());
  726. if (!session.getConfiguration().isProductionMode()) {
  727. appConfig.put("debug", true);
  728. }
  729. if (vaadinService.isStandalone(request)) {
  730. appConfig.put("standalone", true);
  731. }
  732. appConfig.put("heartbeatInterval", vaadinService
  733. .getDeploymentConfiguration().getHeartbeatInterval());
  734. String serviceUrl = getServiceUrl(context);
  735. if (serviceUrl != null) {
  736. appConfig.put(ApplicationConstants.SERVICE_URL, serviceUrl);
  737. }
  738. boolean sendUrlsAsParameters = vaadinService
  739. .getDeploymentConfiguration().isSendUrlsAsParameters();
  740. if (!sendUrlsAsParameters) {
  741. appConfig.put("sendUrlsAsParameters", false);
  742. }
  743. return appConfig;
  744. }
  745. /**
  746. * @since 8.0.3
  747. */
  748. protected abstract String getContextRootPath(BootstrapContext context);
  749. protected abstract String getServiceUrl(BootstrapContext context);
  750. /**
  751. * Get the URI for the application theme.
  752. *
  753. * A portal-wide default theme is fetched from the portal shared resource
  754. * directory (if any), other themes from the portlet.
  755. *
  756. * @param context
  757. * @param themeName
  758. *
  759. * @return
  760. */
  761. public String getThemeUri(BootstrapContext context, String themeName) {
  762. VaadinRequest request = context.getRequest();
  763. final String staticFilePath = request.getService()
  764. .getStaticFileLocation(request);
  765. return staticFilePath + "/" + VaadinServlet.THEME_DIR_PATH + '/'
  766. + themeName;
  767. }
  768. /**
  769. * Override if required
  770. *
  771. * @param context
  772. * @return
  773. */
  774. public String getThemeName(BootstrapContext context) {
  775. UICreateEvent event = new UICreateEvent(context.getRequest(),
  776. context.getUIClass());
  777. return context.getBootstrapResponse().getUIProvider().getTheme(event);
  778. }
  779. /**
  780. * Do not override.
  781. *
  782. * @param context
  783. * @return
  784. */
  785. public String findAndEscapeThemeName(BootstrapContext context) {
  786. String themeName = getThemeName(context);
  787. if (themeName == null) {
  788. VaadinRequest request = context.getRequest();
  789. themeName = request.getService().getConfiguredTheme(request);
  790. }
  791. // XSS preventation, theme names shouldn't contain special chars anyway.
  792. // The servlet denies them via url parameter.
  793. themeName = VaadinServlet.stripSpecialChars(themeName);
  794. return themeName;
  795. }
  796. protected void writeError(VaadinResponse response, Throwable e)
  797. throws IOException {
  798. response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
  799. e.getLocalizedMessage());
  800. }
  801. private void putValueOrNull(JsonObject object, String key, String value) {
  802. assert object != null;
  803. assert key != null;
  804. if (value == null) {
  805. object.put(key, Json.createNull());
  806. } else {
  807. object.put(key, value);
  808. }
  809. }
  810. }