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 18KB

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