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.

AbstractConnector.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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.client.ui;
  17. import java.util.ArrayList;
  18. import java.util.Collection;
  19. import java.util.Collections;
  20. import java.util.HashSet;
  21. import java.util.List;
  22. import java.util.Set;
  23. import com.google.gwt.core.client.JsArrayString;
  24. import com.google.gwt.dom.client.Element;
  25. import com.google.gwt.event.shared.GwtEvent;
  26. import com.google.gwt.event.shared.HandlerManager;
  27. import com.google.gwt.event.shared.HandlerRegistration;
  28. import com.vaadin.client.ApplicationConnection;
  29. import com.vaadin.client.ComponentConnector;
  30. import com.vaadin.client.FastStringMap;
  31. import com.vaadin.client.FastStringSet;
  32. import com.vaadin.client.JsArrayObject;
  33. import com.vaadin.client.Profiler;
  34. import com.vaadin.client.ServerConnector;
  35. import com.vaadin.client.Util;
  36. import com.vaadin.client.VConsole;
  37. import com.vaadin.client.communication.RpcProxy;
  38. import com.vaadin.client.communication.StateChangeEvent;
  39. import com.vaadin.client.communication.StateChangeEvent.StateChangeHandler;
  40. import com.vaadin.client.metadata.NoDataException;
  41. import com.vaadin.client.metadata.OnStateChangeMethod;
  42. import com.vaadin.client.metadata.Type;
  43. import com.vaadin.client.metadata.TypeData;
  44. import com.vaadin.client.metadata.TypeDataStore;
  45. import com.vaadin.shared.communication.ClientRpc;
  46. import com.vaadin.shared.communication.ServerRpc;
  47. import com.vaadin.shared.communication.SharedState;
  48. import com.vaadin.shared.communication.URLReference;
  49. /**
  50. * An abstract implementation of Connector.
  51. *
  52. * @author Vaadin Ltd
  53. * @since 7.0.0
  54. *
  55. */
  56. public abstract class AbstractConnector
  57. implements ServerConnector, StateChangeHandler {
  58. private ApplicationConnection connection;
  59. private String id;
  60. private HandlerManager handlerManager;
  61. private FastStringMap<HandlerManager> statePropertyHandlerManagers;
  62. private FastStringMap<Collection<ClientRpc>> rpcImplementations;
  63. private final boolean debugLogging = false;
  64. private SharedState state;
  65. private ServerConnector parent;
  66. /**
  67. * A map from client-to-server RPC interface class to the RPC proxy that
  68. * sends outgoing RPC calls for that interface.
  69. */
  70. private FastStringMap<ServerRpc> rpcProxyMap = FastStringMap.create();
  71. /**
  72. * Temporary storage for last enabled state to be able to see if it has
  73. * changed. Can be removed once we are able to listen specifically for
  74. * enabled changes in the state. Widget.isEnabled() cannot be used as all
  75. * Widgets do not implement HasEnabled
  76. */
  77. private boolean lastEnabledState = true;
  78. private List<ServerConnector> children;
  79. /*
  80. * (non-Javadoc)
  81. *
  82. * @see com.vaadin.client.VPaintable#getConnection()
  83. */
  84. @Override
  85. public final ApplicationConnection getConnection() {
  86. return connection;
  87. }
  88. /*
  89. * (non-Javadoc)
  90. *
  91. * @see com.vaadin.client.Connector#getId()
  92. */
  93. @Override
  94. public String getConnectorId() {
  95. return id;
  96. }
  97. /**
  98. * Called once by the framework to initialize the connector.
  99. * <p>
  100. * Note that the shared state is not yet available when this method is
  101. * called.
  102. * <p>
  103. * Connector classes should override {@link #init()} instead of this method.
  104. */
  105. @Override
  106. public final void doInit(String connectorId,
  107. ApplicationConnection connection) {
  108. Profiler.enter("AbstractConnector.doInit");
  109. this.connection = connection;
  110. id = connectorId;
  111. // Doing this here because we want to run it after connection and id has
  112. // been set but before init() is called to enable e.g.
  113. // JavaScriptConnector to use connection when determining the tag name
  114. if (this instanceof ComponentConnector) {
  115. setConnectorId(((ComponentConnector) this).getWidget().getElement(),
  116. connectorId);
  117. }
  118. addStateChangeHandler(this);
  119. if (Profiler.isEnabled()) {
  120. Profiler.enter(
  121. "AbstractConnector.init " + getClass().getSimpleName());
  122. }
  123. init();
  124. if (Profiler.isEnabled()) {
  125. Profiler.leave(
  126. "AbstractConnector.init " + getClass().getSimpleName());
  127. }
  128. Profiler.leave("AbstractConnector.doInit");
  129. }
  130. private static native void setConnectorId(Element el, String id)
  131. /*-{
  132. el.tkPid = id;
  133. }-*/;
  134. /**
  135. * Called when the connector has been initialized. Override this method to
  136. * perform initialization of the connector.
  137. */
  138. // FIXME: It might make sense to make this abstract to force users to
  139. // use init instead of constructor, where connection and id has not yet been
  140. // set.
  141. protected void init() {
  142. }
  143. /**
  144. * Registers an implementation for a server to client RPC interface.
  145. *
  146. * Multiple registrations can be made for a single interface, in which case
  147. * all of them receive corresponding RPC calls.
  148. *
  149. * @param rpcInterface
  150. * RPC interface
  151. * @param implementation
  152. * implementation that should receive RPC calls
  153. * @param <T>
  154. * The type of the RPC interface that is being registered
  155. */
  156. protected <T extends ClientRpc> void registerRpc(Class<T> rpcInterface,
  157. T implementation) {
  158. String rpcInterfaceId = rpcInterface.getName().replaceAll("\\$", ".");
  159. if (null == rpcImplementations) {
  160. rpcImplementations = FastStringMap.create();
  161. }
  162. if (null == rpcImplementations.get(rpcInterfaceId)) {
  163. rpcImplementations.put(rpcInterfaceId, new ArrayList<ClientRpc>());
  164. }
  165. rpcImplementations.get(rpcInterfaceId).add(implementation);
  166. }
  167. /**
  168. * Unregisters an implementation for a server to client RPC interface.
  169. *
  170. * @param rpcInterface
  171. * RPC interface
  172. * @param implementation
  173. * implementation to unregister
  174. */
  175. protected <T extends ClientRpc> void unregisterRpc(Class<T> rpcInterface,
  176. T implementation) {
  177. String rpcInterfaceId = rpcInterface.getName().replaceAll("\\$", ".");
  178. if (null != rpcImplementations
  179. && null != rpcImplementations.get(rpcInterfaceId)) {
  180. rpcImplementations.get(rpcInterfaceId).remove(implementation);
  181. }
  182. }
  183. /**
  184. * Returns an RPC proxy object which can be used to invoke the RPC method on
  185. * the server.
  186. *
  187. * @param <T>
  188. * The type of the ServerRpc interface
  189. * @param rpcInterface
  190. * The ServerRpc interface to retrieve a proxy object for
  191. * @return A proxy object which can be used to invoke the RPC method on the
  192. * server.
  193. */
  194. protected <T extends ServerRpc> T getRpcProxy(Class<T> rpcInterface) {
  195. String name = rpcInterface.getName();
  196. if (!rpcProxyMap.containsKey(name)) {
  197. rpcProxyMap.put(name, RpcProxy.create(rpcInterface, this));
  198. }
  199. return (T) rpcProxyMap.get(name);
  200. }
  201. @Override
  202. public <T extends ClientRpc> Collection<T> getRpcImplementations(
  203. String rpcInterfaceId) {
  204. if (null == rpcImplementations) {
  205. return Collections.emptyList();
  206. }
  207. return (Collection<T>) rpcImplementations.get(rpcInterfaceId);
  208. }
  209. @Override
  210. public void fireEvent(GwtEvent<?> event) {
  211. String profilerKey = null;
  212. if (Profiler.isEnabled()) {
  213. profilerKey = "Fire " + event.getClass().getSimpleName() + " for "
  214. + getClass().getSimpleName();
  215. Profiler.enter(profilerKey);
  216. }
  217. if (handlerManager != null) {
  218. handlerManager.fireEvent(event);
  219. }
  220. if (statePropertyHandlerManagers != null
  221. && event instanceof StateChangeEvent) {
  222. Profiler.enter(
  223. "AbstractConnector.fireEvent statePropertyHandlerManagers");
  224. StateChangeEvent stateChangeEvent = (StateChangeEvent) event;
  225. JsArrayString keys = statePropertyHandlerManagers.getKeys();
  226. for (int i = 0; i < keys.length(); i++) {
  227. String property = keys.get(i);
  228. if (stateChangeEvent.hasPropertyChanged(property)) {
  229. statePropertyHandlerManagers.get(property).fireEvent(event);
  230. }
  231. }
  232. Profiler.leave(
  233. "AbstractConnector.fireEvent statePropertyHandlerManagers");
  234. }
  235. if (Profiler.isEnabled()) {
  236. Profiler.leave(profilerKey);
  237. }
  238. }
  239. protected HandlerManager ensureHandlerManager() {
  240. if (handlerManager == null) {
  241. handlerManager = new HandlerManager(this);
  242. }
  243. return handlerManager;
  244. }
  245. @Override
  246. public HandlerRegistration addStateChangeHandler(
  247. StateChangeHandler handler) {
  248. return ensureHandlerManager().addHandler(StateChangeEvent.TYPE,
  249. handler);
  250. }
  251. @Override
  252. public void removeStateChangeHandler(StateChangeHandler handler) {
  253. ensureHandlerManager().removeHandler(StateChangeEvent.TYPE, handler);
  254. }
  255. @Override
  256. public HandlerRegistration addStateChangeHandler(String propertyName,
  257. StateChangeHandler handler) {
  258. return ensureHandlerManager(propertyName)
  259. .addHandler(StateChangeEvent.TYPE, handler);
  260. }
  261. @Override
  262. public void removeStateChangeHandler(String propertyName,
  263. StateChangeHandler handler) {
  264. ensureHandlerManager(propertyName).removeHandler(StateChangeEvent.TYPE,
  265. handler);
  266. }
  267. private HandlerManager ensureHandlerManager(String propertyName) {
  268. if (statePropertyHandlerManagers == null) {
  269. statePropertyHandlerManagers = FastStringMap.create();
  270. }
  271. HandlerManager manager = statePropertyHandlerManagers.get(propertyName);
  272. if (manager == null) {
  273. manager = new HandlerManager(this);
  274. statePropertyHandlerManagers.put(propertyName, manager);
  275. }
  276. return manager;
  277. }
  278. @Override
  279. public void onStateChanged(StateChangeEvent stateChangeEvent) {
  280. Profiler.enter("AbstractConnector.onStateChanged");
  281. if (debugLogging) {
  282. VConsole.log("State change event for "
  283. + Util.getConnectorString(stateChangeEvent.getConnector())
  284. + " received by " + Util.getConnectorString(this));
  285. }
  286. updateEnabledState(isEnabled());
  287. FastStringMap<JsArrayObject<OnStateChangeMethod>> handlers = TypeDataStore
  288. .getOnStateChangeMethods(getClass());
  289. if (handlers != null) {
  290. Profiler.enter("AbstractConnector.onStateChanged @OnStateChange");
  291. HashSet<OnStateChangeMethod> invokedMethods = new HashSet<>();
  292. JsArrayString propertyNames = handlers.getKeys();
  293. for (int i = 0; i < propertyNames.length(); i++) {
  294. String propertyName = propertyNames.get(i);
  295. if (stateChangeEvent.hasPropertyChanged(propertyName)) {
  296. JsArrayObject<OnStateChangeMethod> propertyMethods = handlers
  297. .get(propertyName);
  298. for (int j = 0; j < propertyMethods.size(); j++) {
  299. OnStateChangeMethod method = propertyMethods.get(j);
  300. if (invokedMethods.add(method)) {
  301. method.invoke(stateChangeEvent);
  302. }
  303. }
  304. }
  305. }
  306. Profiler.leave("AbstractConnector.onStateChanged @OnStateChange");
  307. }
  308. Profiler.leave("AbstractConnector.onStateChanged");
  309. }
  310. /*
  311. * (non-Javadoc)
  312. *
  313. * @see com.vaadin.client.ServerConnector#onUnregister()
  314. */
  315. @Override
  316. public void onUnregister() {
  317. if (debugLogging) {
  318. VConsole.log(
  319. "Unregistered connector " + Util.getConnectorString(this));
  320. }
  321. }
  322. /**
  323. * Returns the shared state object for this connector.
  324. *
  325. * Override this method to define the shared state type for your connector.
  326. *
  327. * @return the current shared state (never null)
  328. */
  329. @Override
  330. public SharedState getState() {
  331. if (state == null) {
  332. Profiler.enter("AbstractConnector.createState()");
  333. state = createState();
  334. Profiler.leave("AbstractConnector.createState()");
  335. }
  336. return state;
  337. }
  338. /**
  339. * Creates a state object with default values for this connector. The
  340. * created state object must be compatible with the return type of
  341. * {@link #getState()}. The default implementation creates a state object
  342. * using GWT.create() using the defined return type of {@link #getState()}.
  343. *
  344. * @return A new state object
  345. */
  346. protected SharedState createState() {
  347. try {
  348. Type stateType = getStateType(this);
  349. Object stateInstance = stateType.createInstance();
  350. return (SharedState) stateInstance;
  351. } catch (NoDataException e) {
  352. throw new IllegalStateException(
  353. "There is no information about the state for "
  354. + getClass().getSimpleName()
  355. + ". Did you remember to compile the right widgetset?",
  356. e);
  357. }
  358. }
  359. public static Type getStateType(ServerConnector connector) {
  360. try {
  361. return TypeData.getType(connector.getClass()).getMethod("getState")
  362. .getReturnType();
  363. } catch (NoDataException e) {
  364. throw new IllegalStateException(
  365. "There is no information about the state for "
  366. + connector.getClass().getSimpleName()
  367. + ". Did you remember to compile the right widgetset?",
  368. e);
  369. }
  370. }
  371. @Override
  372. public ServerConnector getParent() {
  373. return parent;
  374. }
  375. @Override
  376. public void setParent(ServerConnector parent) {
  377. this.parent = parent;
  378. }
  379. @Override
  380. public List<ServerConnector> getChildren() {
  381. if (children == null) {
  382. return Collections.emptyList();
  383. }
  384. return children;
  385. }
  386. @Override
  387. public void setChildren(List<ServerConnector> children) {
  388. this.children = children;
  389. }
  390. @Override
  391. public boolean isEnabled() {
  392. if (!getState().enabled) {
  393. return false;
  394. }
  395. if (getParent() == null) {
  396. return true;
  397. } else {
  398. return getParent().isEnabled();
  399. }
  400. }
  401. @Override
  402. public void updateEnabledState(boolean enabledState) {
  403. if (lastEnabledState == enabledState) {
  404. return;
  405. }
  406. Profiler.enter("AbstractConnector.updateEnabledState");
  407. lastEnabledState = enabledState;
  408. for (ServerConnector c : getChildren()) {
  409. // Update children as they might be affected by the enabled state of
  410. // their parent
  411. c.updateEnabledState(c.isEnabled());
  412. }
  413. Profiler.leave("AbstractConnector.updateEnabledState");
  414. }
  415. /**
  416. * Gets the URL for a resource that has been added by the server-side
  417. * connector using
  418. * {@link com.vaadin.terminal.AbstractClientConnector#setResource(String, com.vaadin.terminal.Resource)}
  419. * with the same key. <code>null</code> is returned if no corresponding
  420. * resource is found.
  421. *
  422. * @param key
  423. * a string identifying the resource.
  424. * @return the resource URL as a string, or <code>null</code> if no
  425. * corresponding resource is found.
  426. */
  427. public String getResourceUrl(String key) {
  428. URLReference urlReference = getState().resources.get(key);
  429. if (urlReference == null) {
  430. return null;
  431. } else {
  432. return urlReference.getURL();
  433. }
  434. }
  435. /*
  436. * (non-Javadoc)
  437. *
  438. * @see com.vaadin.client.ServerConnector#hasEventListener(java.lang.String)
  439. */
  440. @Override
  441. public boolean hasEventListener(String eventIdentifier) {
  442. Set<String> reg = getState().registeredEventListeners;
  443. return (reg != null && reg.contains(eventIdentifier));
  444. }
  445. /**
  446. * Force the connector to recheck its state variables as the variables or
  447. * their meaning might have changed.
  448. *
  449. * @since 7.3
  450. */
  451. public void forceStateChange() {
  452. StateChangeEvent event = new FullStateChangeEvent(this);
  453. fireEvent(event);
  454. }
  455. private static class FullStateChangeEvent extends StateChangeEvent {
  456. public FullStateChangeEvent(ServerConnector connector) {
  457. super(connector, FastStringSet.create());
  458. }
  459. @Override
  460. public boolean hasPropertyChanged(String property) {
  461. return true;
  462. }
  463. }
  464. }