Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

LegacyCommunicationManager.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /*
  2. * Copyright 2000-2018 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.Serializable;
  18. import java.net.URI;
  19. import java.net.URISyntaxException;
  20. import java.security.GeneralSecurityException;
  21. import java.util.HashMap;
  22. import java.util.HashSet;
  23. import java.util.Map;
  24. import java.util.Set;
  25. import java.util.concurrent.ConcurrentHashMap;
  26. import java.util.logging.Level;
  27. import java.util.logging.Logger;
  28. import com.vaadin.server.ClientConnector.ConnectorErrorEvent;
  29. import com.vaadin.shared.ApplicationConstants;
  30. import com.vaadin.shared.JavaScriptConnectorState;
  31. import com.vaadin.shared.JavaScriptExtensionState;
  32. import com.vaadin.shared.communication.SharedState;
  33. import com.vaadin.shared.ui.JavaScriptComponentState;
  34. import com.vaadin.ui.Component;
  35. import com.vaadin.ui.ConnectorTracker;
  36. import com.vaadin.ui.HasComponents;
  37. import com.vaadin.ui.SelectiveRenderer;
  38. import com.vaadin.ui.UI;
  39. import com.vaadin.util.ReflectTools;
  40. import elemental.json.JsonObject;
  41. import elemental.json.JsonValue;
  42. /**
  43. * This is a common base class for the server-side implementations of the
  44. * communication system between the client code (compiled with GWT into
  45. * JavaScript) and the server side components. Its client side counterpart is
  46. * {@link com.vaadin.client.ApplicationConnection}.
  47. * <p>
  48. * TODO Document better!
  49. *
  50. * @deprecated As of 7.0. Will likely change or be removed in a future version
  51. */
  52. @Deprecated
  53. @SuppressWarnings("serial")
  54. public class LegacyCommunicationManager implements Serializable {
  55. // TODO Refactor (#11410)
  56. private final Map<Integer, ClientCache> uiToClientCache = new HashMap<>();
  57. /**
  58. * The session this communication manager is used for
  59. */
  60. private final VaadinSession session;
  61. // TODO Refactor (#11413)
  62. private final Map<String, Class<?>> publishedFileContexts = new HashMap<>();
  63. /**
  64. * TODO New constructor - document me!
  65. *
  66. * @param session
  67. */
  68. public LegacyCommunicationManager(VaadinSession session) {
  69. this.session = session;
  70. }
  71. protected VaadinSession getSession() {
  72. return session;
  73. }
  74. private static final ConcurrentHashMap<Class<? extends SharedState>, JsonValue> REFERENCE_DIFF_STATES = new ConcurrentHashMap<>();
  75. /**
  76. * @deprecated As of 7.1. See #11411.
  77. */
  78. @Deprecated
  79. public static JsonObject encodeState(ClientConnector connector,
  80. SharedState state) {
  81. UI uI = connector.getUI();
  82. ConnectorTracker connectorTracker = uI.getConnectorTracker();
  83. Class<? extends SharedState> stateType = connector.getStateType();
  84. JsonValue diffState = connectorTracker.getDiffState(connector);
  85. if (diffState == null) {
  86. // Use an empty state object as reference for full
  87. // repaints
  88. diffState = REFERENCE_DIFF_STATES.get(stateType);
  89. if (diffState == null) {
  90. diffState = createReferenceDiffStateState(stateType);
  91. REFERENCE_DIFF_STATES.put(stateType, diffState);
  92. }
  93. }
  94. EncodeResult encodeResult = JsonCodec.encode(state, diffState,
  95. stateType, uI.getConnectorTracker());
  96. connectorTracker.setDiffState(connector,
  97. (JsonObject) encodeResult.getEncodedValue());
  98. return (JsonObject) encodeResult.getDiff();
  99. }
  100. private static JsonValue createReferenceDiffStateState(
  101. Class<? extends SharedState> stateType) {
  102. if (JavaScriptConnectorState.class.isAssignableFrom(stateType)) {
  103. /*
  104. * For JS state types, we should only include the framework-provided
  105. * state fields in the reference diffstate since other fields are
  106. * not know by the client and would therefore not get the right
  107. * initial value if it would be recorded in the diffstate.
  108. */
  109. stateType = findJsStateReferenceType(stateType);
  110. }
  111. try {
  112. SharedState referenceState = ReflectTools.createInstance(stateType);
  113. EncodeResult encodeResult = JsonCodec.encode(referenceState, null,
  114. stateType, null);
  115. return encodeResult.getEncodedValue();
  116. } catch (Exception e) {
  117. getLogger().log(Level.WARNING,
  118. "Error creating reference object for state of type {0}",
  119. stateType.getName());
  120. return null;
  121. }
  122. }
  123. /**
  124. * Finds the highest super class which implements
  125. * {@link JavaScriptConnectorState}. In practice, this finds either
  126. * {@link JavaScriptComponentState} or {@link JavaScriptExtensionState}.
  127. * This is used to find which state properties the client side knows
  128. * something about.
  129. *
  130. * @param stateType
  131. * the state type for which the reference type should be found
  132. * @return the found reference type
  133. */
  134. private static Class<? extends SharedState> findJsStateReferenceType(
  135. Class<? extends SharedState> stateType) {
  136. assert JavaScriptConnectorState.class.isAssignableFrom(stateType);
  137. Class<?> type = stateType;
  138. while (type != null) {
  139. Class<?> superclass = type.getSuperclass();
  140. if (!JavaScriptConnectorState.class.isAssignableFrom(superclass)) {
  141. break;
  142. }
  143. type = superclass;
  144. }
  145. return type.asSubclass(SharedState.class);
  146. }
  147. /**
  148. * Resolves a dependency URI, registering the URI with this
  149. * {@code LegacyCommunicationManager} if needed and returns a fully
  150. * qualified URI.
  151. *
  152. * @deprecated As of 7.1. See #11413.
  153. */
  154. @Deprecated
  155. public String registerDependency(String resourceUri, Class<?> context) {
  156. try {
  157. URI uri = new URI(resourceUri);
  158. String protocol = uri.getScheme();
  159. if (ApplicationConstants.PUBLISHED_PROTOCOL_NAME.equals(protocol)) {
  160. // Strip initial slash
  161. String resourceName = uri.getPath().substring(1);
  162. return registerPublishedFile(resourceName, context);
  163. }
  164. if (protocol != null || uri.getHost() != null) {
  165. return resourceUri;
  166. }
  167. // Bare path interpreted as published file
  168. return registerPublishedFile(resourceUri, context);
  169. } catch (URISyntaxException e) {
  170. getLogger().log(Level.WARNING,
  171. "Could not parse resource url " + resourceUri, e);
  172. return resourceUri;
  173. }
  174. }
  175. /**
  176. * @deprecated As of 7.1. See #11413.
  177. */
  178. @Deprecated
  179. public Map<String, Class<?>> getDependencies() {
  180. return publishedFileContexts;
  181. }
  182. private String registerPublishedFile(String name, Class<?> context) {
  183. // Add to map of names accepted by servePublishedFile
  184. if (publishedFileContexts.containsKey(name)) {
  185. Class<?> oldContext = publishedFileContexts.get(name);
  186. if (oldContext != context) {
  187. getLogger().log(Level.WARNING,
  188. "{0} published by both {1} and {2}. File from {2} will be used.",
  189. new Object[] { name, context, oldContext });
  190. }
  191. } else {
  192. publishedFileContexts.put(name, context);
  193. }
  194. return ApplicationConstants.PUBLISHED_PROTOCOL_PREFIX + "/" + name;
  195. }
  196. /**
  197. * @deprecated As of 7.1. See #11410.
  198. */
  199. @Deprecated
  200. public ClientCache getClientCache(UI uI) {
  201. Integer uiId = Integer.valueOf(uI.getUIId());
  202. ClientCache cache = uiToClientCache.get(uiId);
  203. if (cache == null) {
  204. cache = new ClientCache();
  205. uiToClientCache.put(uiId, cache);
  206. }
  207. return cache;
  208. }
  209. /**
  210. * Checks if the connector is visible in context. For Components,
  211. * {@link #isComponentVisibleToClient(Component)} is used. For other types
  212. * of connectors, the contextual visibility of its first Component ancestor
  213. * is used. If no Component ancestor is found, the connector is not visible.
  214. *
  215. * @deprecated As of 7.1. See #11411.
  216. *
  217. * @param connector
  218. * The connector to check
  219. * @return <code>true</code> if the connector is visible to the client,
  220. * <code>false</code> otherwise
  221. */
  222. @Deprecated
  223. public static boolean isConnectorVisibleToClient(
  224. ClientConnector connector) {
  225. if (connector instanceof Component) {
  226. return isComponentVisibleToClient((Component) connector);
  227. } else {
  228. ClientConnector parent = connector.getParent();
  229. if (parent == null) {
  230. return false;
  231. } else {
  232. return isConnectorVisibleToClient(parent);
  233. }
  234. }
  235. }
  236. /**
  237. * Checks if the component should be visible to the client. Returns false if
  238. * the child should not be sent to the client, true otherwise.
  239. *
  240. * @deprecated As of 7.1. See #11411.
  241. *
  242. * @param child
  243. * The child to check
  244. * @return true if the child is visible to the client, false otherwise
  245. */
  246. @Deprecated
  247. public static boolean isComponentVisibleToClient(Component child) {
  248. if (!child.isVisible()) {
  249. return false;
  250. }
  251. HasComponents parent = child.getParent();
  252. if (parent instanceof SelectiveRenderer) {
  253. if (!((SelectiveRenderer) parent).isRendered(child)) {
  254. return false;
  255. }
  256. }
  257. if (parent != null) {
  258. return isComponentVisibleToClient(parent);
  259. } else {
  260. if (child instanceof UI) {
  261. // UI has no parent and visibility was checked above
  262. return true;
  263. } else {
  264. // Component which is not attached to any UI
  265. return false;
  266. }
  267. }
  268. }
  269. /**
  270. * @deprecated As of 7.1. In 7.2 and later, use
  271. * {@link ConnectorTracker#getConnector(String)
  272. * uI.getConnectorTracker().getConnector(connectorId)} instead.
  273. * See ticket #11411.
  274. */
  275. @Deprecated
  276. public ClientConnector getConnector(UI uI, String connectorId) {
  277. return uI.getConnectorTracker().getConnector(connectorId);
  278. }
  279. /**
  280. * @deprecated As of 7.1. Will be removed in the future.
  281. */
  282. @Deprecated
  283. public static class InvalidUIDLSecurityKeyException
  284. extends GeneralSecurityException {
  285. public InvalidUIDLSecurityKeyException(String message) {
  286. super(message);
  287. }
  288. }
  289. private final Map<Class<? extends ClientConnector>, Integer> typeToKey = new HashMap<>();
  290. private int nextTypeKey = 0;
  291. /**
  292. * @deprecated As of 7.1. Will be removed in the future.
  293. */
  294. @Deprecated
  295. public String getTagForType(Class<? extends ClientConnector> class1) {
  296. Integer id = typeToKey.get(class1);
  297. if (id == null) {
  298. id = nextTypeKey++;
  299. typeToKey.put(class1, id);
  300. if (getLogger().isLoggable(Level.FINE)) {
  301. getLogger().log(Level.FINE, "Mapping {0} to {1}",
  302. new Object[] { class1.getName(), id });
  303. }
  304. }
  305. return id.toString();
  306. }
  307. /**
  308. * Helper class for terminal to keep track of data that client is expected
  309. * to know.
  310. *
  311. * TODO make customlayout templates (from theme) to be cached here.
  312. *
  313. * @deprecated As of 7.1. See #11410.
  314. */
  315. @Deprecated
  316. public class ClientCache implements Serializable {
  317. private final Set<Object> res = new HashSet<>();
  318. /**
  319. *
  320. * @param object
  321. * @return true if the given class was added to cache
  322. */
  323. public boolean cache(Object object) {
  324. return res.add(object);
  325. }
  326. public void clear() {
  327. res.clear();
  328. }
  329. public boolean isEmpty() {
  330. return res.isEmpty();
  331. }
  332. }
  333. /**
  334. * @deprecated As of 7.1. See #11411.
  335. */
  336. @Deprecated
  337. public String getStreamVariableTargetUrl(ClientConnector owner, String name,
  338. StreamVariable value) {
  339. /*
  340. * We will use the same APP/* URI space as ApplicationResources but
  341. * prefix url with UPLOAD
  342. *
  343. * e.g. APP/UPLOAD/[UIID]/[PID]/[NAME]/[SECKEY]
  344. *
  345. * SECKEY is created on each paint to make URL's unpredictable (to
  346. * prevent CSRF attacks).
  347. *
  348. * NAME and PID from URI forms a key to fetch StreamVariable when
  349. * handling post
  350. */
  351. String paintableId = owner.getConnectorId();
  352. UI ui = owner.getUI();
  353. int uiId = ui.getUIId();
  354. String key = uiId + "/" + paintableId + "/" + name;
  355. ConnectorTracker connectorTracker = ui.getConnectorTracker();
  356. connectorTracker.addStreamVariable(paintableId, name, value);
  357. String seckey = connectorTracker.getSeckey(value);
  358. return ApplicationConstants.APP_PROTOCOL_PREFIX
  359. + ServletPortletHelper.UPLOAD_URL_PREFIX + key + "/" + seckey;
  360. }
  361. /**
  362. * Handles an exception related to a connector by invoking the appropriate
  363. * error handler.
  364. *
  365. * @deprecated As of 7.1. See #11411.
  366. *
  367. * @param throwable
  368. * the exception to handle
  369. * @param connector
  370. * the connector that the exception is related to
  371. */
  372. @Deprecated
  373. public void handleConnectorRelatedException(ClientConnector connector,
  374. Throwable throwable) {
  375. ErrorEvent errorEvent = new ConnectorErrorEvent(connector, throwable);
  376. ErrorHandler handler = ErrorEvent.findErrorHandler(connector);
  377. handler.error(errorEvent);
  378. }
  379. /**
  380. * Requests that the given UI should be fully re-rendered on the client
  381. * side.
  382. *
  383. * @since 7.1 @deprecated. As of 7.1. Should be refactored once locales are
  384. * fixed (#11378)
  385. */
  386. @Deprecated
  387. public void repaintAll(UI ui) {
  388. getClientCache(ui).clear();
  389. ui.getConnectorTracker().markAllConnectorsDirty();
  390. ui.getConnectorTracker().markAllClientSidesUninitialized();
  391. }
  392. private static final Logger getLogger() {
  393. return Logger.getLogger(LegacyCommunicationManager.class.getName());
  394. }
  395. }