Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

AbstractClientConnector.java 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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.IOException;
  18. import java.io.Serializable;
  19. import java.lang.reflect.Constructor;
  20. import java.lang.reflect.InvocationHandler;
  21. import java.lang.reflect.Method;
  22. import java.lang.reflect.Proxy;
  23. import java.util.ArrayList;
  24. import java.util.Collection;
  25. import java.util.Collections;
  26. import java.util.EventObject;
  27. import java.util.HashMap;
  28. import java.util.Iterator;
  29. import java.util.List;
  30. import java.util.Map;
  31. import java.util.NoSuchElementException;
  32. import java.util.concurrent.ConcurrentHashMap;
  33. import java.util.logging.Logger;
  34. import com.vaadin.event.EventRouter;
  35. import com.vaadin.shared.Registration;
  36. import com.vaadin.shared.communication.ClientRpc;
  37. import com.vaadin.shared.communication.ServerRpc;
  38. import com.vaadin.shared.communication.SharedState;
  39. import com.vaadin.shared.ui.ComponentStateUtil;
  40. import com.vaadin.ui.Component;
  41. import com.vaadin.ui.Component.Event;
  42. import com.vaadin.ui.HasComponents;
  43. import com.vaadin.ui.LegacyComponent;
  44. import com.vaadin.ui.UI;
  45. import elemental.json.JsonObject;
  46. import elemental.json.JsonValue;
  47. /**
  48. * An abstract base class for ClientConnector implementations. This class
  49. * provides all the basic functionality required for connectors.
  50. *
  51. * @author Vaadin Ltd
  52. * @since 7.0.0
  53. */
  54. public abstract class AbstractClientConnector implements ClientConnector {
  55. /**
  56. * A map from client to server RPC interface class name to the RPC call
  57. * manager that handles incoming RPC calls for that interface.
  58. */
  59. private final Map<String, ServerRpcManager<?>> rpcManagerMap = new HashMap<>();
  60. /**
  61. * A map from server to client RPC interface class to the RPC proxy that
  62. * sends ourgoing RPC calls for that interface.
  63. */
  64. private final Map<Class<?>, ClientRpc> rpcProxyMap = new HashMap<>();
  65. /**
  66. * Shared state object to be communicated from the server to the client when
  67. * modified.
  68. */
  69. private SharedState sharedState;
  70. private Class<? extends SharedState> stateType;
  71. /**
  72. * Pending RPC method invocations to be sent.
  73. */
  74. private ArrayList<ClientMethodInvocation> pendingInvocations = new ArrayList<>();
  75. private String connectorId;
  76. private final ArrayList<Extension> extensions = new ArrayList<>();
  77. /**
  78. * The EventRouter used for the event model.
  79. */
  80. private EventRouter eventRouter = null;
  81. private ErrorHandler errorHandler = null;
  82. private static final ConcurrentHashMap<Class<? extends AbstractClientConnector>, Class<? extends SharedState>> stateTypeCache = new ConcurrentHashMap<>();
  83. @Override
  84. public Registration addAttachListener(AttachListener listener) {
  85. return addListener(AttachEvent.ATTACH_EVENT_IDENTIFIER,
  86. AttachEvent.class, listener, AttachListener.attachMethod);
  87. }
  88. @Override
  89. @Deprecated
  90. public void removeAttachListener(AttachListener listener) {
  91. removeListener(AttachEvent.ATTACH_EVENT_IDENTIFIER, AttachEvent.class,
  92. listener);
  93. }
  94. @Override
  95. public Registration addDetachListener(DetachListener listener) {
  96. return addListener(DetachEvent.DETACH_EVENT_IDENTIFIER,
  97. DetachEvent.class, listener, DetachListener.detachMethod);
  98. }
  99. @Override
  100. @Deprecated
  101. public void removeDetachListener(DetachListener listener) {
  102. removeListener(DetachEvent.DETACH_EVENT_IDENTIFIER, DetachEvent.class,
  103. listener);
  104. }
  105. /**
  106. * @deprecated As of 7.0, use {@link #markAsDirty()} instead. Note that you
  107. * typically do not need to call {@link #markAsDirty()} as
  108. * {@link #getState()} will mark the connector dirty and the
  109. * framework will then check what, if anything, needs to be sent
  110. * to the client. {@link LegacyComponent}s which rely on paint
  111. * might still need to call this or {@link #markAsDirty()} .
  112. */
  113. @Deprecated
  114. @Override
  115. public void requestRepaint() {
  116. markAsDirty();
  117. }
  118. /* Documentation copied from interface */
  119. @Override
  120. public void markAsDirty() {
  121. assert getSession() == null
  122. || getSession().hasLock() : buildLockAssertMessage(
  123. "markAsDirty()");
  124. UI uI = getUI();
  125. if (uI != null) {
  126. uI.getConnectorTracker().markDirty(this);
  127. }
  128. }
  129. private String buildLockAssertMessage(String method) {
  130. if (VaadinService.isOtherSessionLocked(getSession())) {
  131. return "The session of this connecor is not locked, but there is another session that is locked. "
  132. + "This might be caused by accidentally using a connector that belongs to another session.";
  133. } else {
  134. return "Session must be locked when " + method + " is called";
  135. }
  136. }
  137. /**
  138. * Registers an RPC interface implementation for this component.
  139. *
  140. * A component can listen to multiple RPC interfaces, and subclasses can
  141. * register additional implementations.
  142. *
  143. * @since 7.0
  144. *
  145. * @param implementation
  146. * RPC interface implementation
  147. * @param rpcInterfaceType
  148. * RPC interface class for which the implementation should be
  149. * registered
  150. */
  151. protected <T extends ServerRpc> void registerRpc(T implementation,
  152. Class<T> rpcInterfaceType) {
  153. rpcManagerMap.put(rpcInterfaceType.getName(),
  154. new ServerRpcManager<>(implementation, rpcInterfaceType));
  155. }
  156. /**
  157. * Registers an RPC interface implementation for this component.
  158. *
  159. * A component can listen to multiple RPC interfaces, and subclasses can
  160. * register additional implementations.
  161. *
  162. * @since 7.0
  163. *
  164. * @param implementation
  165. * RPC interface implementation. Also used to deduce the type.
  166. */
  167. protected <T extends ServerRpc> void registerRpc(T implementation) {
  168. // Search upwards until an interface is found. It must be found as T
  169. // extends ServerRpc
  170. Class<?> cls = implementation.getClass();
  171. Class<ServerRpc> serverRpcClass = getServerRpcInterface(cls);
  172. while (cls != null && serverRpcClass == null) {
  173. cls = cls.getSuperclass();
  174. serverRpcClass = getServerRpcInterface(cls);
  175. }
  176. if (serverRpcClass == null) {
  177. throw new RuntimeException(
  178. "No interface T extends ServerRpc found in the class hierarchy.");
  179. }
  180. registerRpc(implementation, serverRpcClass);
  181. }
  182. @SuppressWarnings("unchecked")
  183. private Class<ServerRpc> getServerRpcInterface(
  184. Class<?> implementationClass) {
  185. Class<ServerRpc> serverRpcClass = null;
  186. if (implementationClass != null) {
  187. for (Class<?> candidateInterface : implementationClass
  188. .getInterfaces()) {
  189. if (ServerRpc.class.isAssignableFrom(candidateInterface)) {
  190. if (serverRpcClass != null) {
  191. throw new RuntimeException(
  192. "Use registerRpc(T implementation, Class<T> rpcInterfaceType) if the Rpc implementation implements more than one interface");
  193. }
  194. serverRpcClass = (Class<ServerRpc>) candidateInterface;
  195. }
  196. }
  197. }
  198. return serverRpcClass;
  199. }
  200. /**
  201. * Returns the shared state for this connector. The shared state object is
  202. * shared between the server connector and the client connector. Changes are
  203. * only communicated from the server to the client and not in the other
  204. * direction.
  205. * <p>
  206. * As a side effect, marks the connector dirty so any changes done to the
  207. * state will be sent to the client. Use {@code getState(false)} to avoid
  208. * marking the connector as dirty.
  209. * </p>
  210. *
  211. * @return The shared state for this connector. Never null.
  212. */
  213. protected SharedState getState() {
  214. return getState(true);
  215. }
  216. /**
  217. * Returns the shared state for this connector.
  218. *
  219. * @param markAsDirty
  220. * true if the connector should automatically be marked dirty,
  221. * false otherwise
  222. *
  223. * @return The shared state for this connector. Never null.
  224. * @see #getState()
  225. */
  226. protected SharedState getState(boolean markAsDirty) {
  227. assert getSession() == null
  228. || getSession().hasLock() : buildLockAssertMessage(
  229. "getState()");
  230. if (null == sharedState) {
  231. sharedState = createState();
  232. }
  233. if (markAsDirty) {
  234. UI ui = getUI();
  235. if (ui != null && !ui.getConnectorTracker().isDirty(this)
  236. && !ui.getConnectorTracker().isWritingResponse()) {
  237. ui.getConnectorTracker().markDirty(this);
  238. }
  239. }
  240. return sharedState;
  241. }
  242. @Override
  243. public JsonObject encodeState() {
  244. return LegacyCommunicationManager.encodeState(this, getState(false));
  245. }
  246. /**
  247. * Creates the shared state bean to be used in server to client
  248. * communication.
  249. * <p>
  250. * By default a state object of the defined return type of
  251. * {@link #getState()} is created. Subclasses can override this method and
  252. * return a new instance of the correct state class but this should rarely
  253. * be necessary.
  254. * </p>
  255. * <p>
  256. * No configuration of the values of the state should be performed in
  257. * {@link #createState()}.
  258. *
  259. * @since 7.0
  260. *
  261. * @return new shared state object
  262. */
  263. protected SharedState createState() {
  264. try {
  265. return getStateType().newInstance();
  266. } catch (Exception e) {
  267. throw new RuntimeException("Error creating state of type "
  268. + getStateType().getName() + " for " + getClass().getName(),
  269. e);
  270. }
  271. }
  272. @Override
  273. public Class<? extends SharedState> getStateType() {
  274. // Lazy load because finding type can be expensive because of the
  275. // exceptions flying around
  276. if (stateType == null) {
  277. // Cache because we don't need to do this once per instance
  278. stateType = stateTypeCache.get(this.getClass());
  279. if (stateType == null) {
  280. stateType = findStateType();
  281. stateTypeCache.put(this.getClass(), stateType);
  282. }
  283. }
  284. return stateType;
  285. }
  286. private Class<? extends SharedState> findStateType() {
  287. try {
  288. Class<?> class1 = getClass();
  289. while (class1 != null) {
  290. try {
  291. Method m = class1.getDeclaredMethod("getState",
  292. (Class[]) null);
  293. Class<?> type = m.getReturnType();
  294. if (!m.isSynthetic()) {
  295. return type.asSubclass(SharedState.class);
  296. }
  297. } catch (NoSuchMethodException nsme) {
  298. }
  299. // Try in superclass instead
  300. class1 = class1.getSuperclass();
  301. }
  302. throw new NoSuchMethodException(
  303. getClass().getCanonicalName() + ".getState()");
  304. } catch (Exception e) {
  305. throw new RuntimeException(
  306. "Error finding state type for " + getClass().getName(), e);
  307. }
  308. }
  309. /**
  310. * Returns an RPC proxy for a given server to client RPC interface for this
  311. * component.
  312. *
  313. * TODO more javadoc, subclasses, ...
  314. *
  315. * @param rpcInterface
  316. * RPC interface type
  317. *
  318. * @since 7.0
  319. */
  320. protected <T extends ClientRpc> T getRpcProxy(final Class<T> rpcInterface) {
  321. // create, initialize and return a dynamic proxy for RPC
  322. try {
  323. if (!rpcProxyMap.containsKey(rpcInterface)) {
  324. Class<?> proxyClass = Proxy.getProxyClass(
  325. rpcInterface.getClassLoader(), rpcInterface);
  326. Constructor<?> constructor = proxyClass
  327. .getConstructor(InvocationHandler.class);
  328. T rpcProxy = rpcInterface.cast(constructor
  329. .newInstance(new RpcInvocationHandler(rpcInterface)));
  330. // cache the proxy
  331. rpcProxyMap.put(rpcInterface, rpcProxy);
  332. }
  333. return (T) rpcProxyMap.get(rpcInterface);
  334. } catch (Exception e) {
  335. // TODO exception handling?
  336. throw new RuntimeException(e);
  337. }
  338. }
  339. private class RpcInvocationHandler
  340. implements InvocationHandler, Serializable {
  341. private final String rpcInterfaceName;
  342. public RpcInvocationHandler(Class<?> rpcInterface) {
  343. rpcInterfaceName = rpcInterface.getName().replaceAll("\\$", ".");
  344. }
  345. @Override
  346. public Object invoke(Object proxy, Method method, Object[] args)
  347. throws Throwable {
  348. if (method.getDeclaringClass() == Object.class) {
  349. // Don't add Object methods such as toString and hashCode as
  350. // invocations
  351. return method.invoke(this, args);
  352. }
  353. addMethodInvocationToQueue(rpcInterfaceName, method, args);
  354. return null;
  355. }
  356. }
  357. /**
  358. * For internal use: adds a method invocation to the pending RPC call queue.
  359. *
  360. * @param interfaceName
  361. * RPC interface name
  362. * @param method
  363. * RPC method
  364. * @param parameters
  365. * RPC all parameters
  366. *
  367. * @since 7.0
  368. */
  369. protected void addMethodInvocationToQueue(String interfaceName,
  370. Method method, Object[] parameters) {
  371. // add to queue
  372. pendingInvocations.add(new ClientMethodInvocation(this, interfaceName,
  373. method, parameters));
  374. // TODO no need to do full repaint if only RPC calls
  375. requestRepaint();
  376. }
  377. @Override
  378. public ServerRpcManager<?> getRpcManager(String rpcInterfaceName) {
  379. return rpcManagerMap.get(rpcInterfaceName);
  380. }
  381. @Override
  382. public List<ClientMethodInvocation> retrievePendingRpcCalls() {
  383. if (pendingInvocations.isEmpty()) {
  384. return Collections.emptyList();
  385. } else {
  386. List<ClientMethodInvocation> result = pendingInvocations;
  387. pendingInvocations = new ArrayList<>();
  388. return Collections.unmodifiableList(result);
  389. }
  390. }
  391. @Override
  392. public String getConnectorId() {
  393. if (connectorId == null) {
  394. if (getSession() == null) {
  395. throw new RuntimeException(
  396. "Component must be attached to a session when getConnectorId() is called for the first time");
  397. }
  398. connectorId = getSession().createConnectorId(this);
  399. }
  400. return connectorId;
  401. }
  402. /**
  403. * Finds the {@link VaadinSession} to which this connector belongs. If the
  404. * connector has not been attached, <code>null</code> is returned.
  405. *
  406. * @return The connector's session, or <code>null</code> if not attached
  407. */
  408. protected VaadinSession getSession() {
  409. UI uI = getUI();
  410. if (uI == null) {
  411. return null;
  412. } else {
  413. return uI.getSession();
  414. }
  415. }
  416. /**
  417. * Finds a UI ancestor of this connector. <code>null</code> is returned if
  418. * no UI ancestor is found (typically because the connector is not attached
  419. * to a proper hierarchy).
  420. *
  421. * @return the UI ancestor of this connector, or <code>null</code> if none
  422. * is found.
  423. */
  424. @Override
  425. public UI getUI() {
  426. ClientConnector connector = this;
  427. while (connector != null) {
  428. if (connector instanceof UI) {
  429. return (UI) connector;
  430. }
  431. connector = connector.getParent();
  432. }
  433. return null;
  434. }
  435. private static Logger getLogger() {
  436. return Logger.getLogger(AbstractClientConnector.class.getName());
  437. }
  438. /**
  439. * @deprecated As of 7.0, use {@link #markAsDirtyRecursive()} instead
  440. */
  441. @Override
  442. @Deprecated
  443. public void requestRepaintAll() {
  444. markAsDirtyRecursive();
  445. }
  446. @Override
  447. public void markAsDirtyRecursive() {
  448. markAsDirty();
  449. for (ClientConnector connector : getAllChildrenIterable(this)) {
  450. connector.markAsDirtyRecursive();
  451. }
  452. }
  453. /**
  454. * Get an Iterable for iterating over all child connectors, including both
  455. * extensions and child components.
  456. *
  457. * @param connector
  458. * the connector to get children for
  459. * @return an Iterable giving all child connectors.
  460. */
  461. public static Iterable<? extends ClientConnector> getAllChildrenIterable(
  462. final ClientConnector connector) {
  463. Collection<Extension> extensions = connector.getExtensions();
  464. boolean hasComponents = connector instanceof HasComponents;
  465. boolean hasExtensions = extensions.size() > 0;
  466. if (!hasComponents && !hasExtensions) {
  467. // If has neither component nor extensions, return immutable empty
  468. // list as iterable.
  469. return Collections.emptyList();
  470. }
  471. if (hasComponents && !hasExtensions) {
  472. // only components
  473. return (HasComponents) connector;
  474. }
  475. if (!hasComponents && hasExtensions) {
  476. // only extensions
  477. return extensions;
  478. }
  479. // combine the iterators of extensions and components to a new iterable.
  480. final Iterator<Component> componentsIterator = ((HasComponents) connector)
  481. .iterator();
  482. final Iterator<Extension> extensionsIterator = extensions.iterator();
  483. Iterable<? extends ClientConnector> combinedIterable = () -> new Iterator<ClientConnector>() {
  484. @Override
  485. public boolean hasNext() {
  486. return componentsIterator.hasNext()
  487. || extensionsIterator.hasNext();
  488. }
  489. @Override
  490. public ClientConnector next() {
  491. if (componentsIterator.hasNext()) {
  492. return componentsIterator.next();
  493. }
  494. if (extensionsIterator.hasNext()) {
  495. return extensionsIterator.next();
  496. }
  497. throw new NoSuchElementException();
  498. }
  499. @Override
  500. public void remove() {
  501. throw new UnsupportedOperationException();
  502. }
  503. };
  504. return combinedIterable;
  505. }
  506. @Override
  507. public Collection<Extension> getExtensions() {
  508. return Collections.unmodifiableCollection(extensions);
  509. }
  510. /**
  511. * Add an extension to this connector. This method is protected to allow
  512. * extensions to select which targets they can extend.
  513. *
  514. * @param extension
  515. * the extension to add
  516. */
  517. protected void addExtension(Extension extension) {
  518. ClientConnector previousParent = extension.getParent();
  519. if (equals(previousParent)) {
  520. // Nothing to do, already attached
  521. return;
  522. } else if (previousParent != null) {
  523. throw new IllegalStateException(
  524. "Moving an extension from one parent to another is not supported");
  525. }
  526. extensions.add(extension);
  527. extension.setParent(this);
  528. markAsDirty();
  529. }
  530. @Override
  531. public void removeExtension(Extension extension) {
  532. if (extension.getParent() != this) {
  533. throw new IllegalArgumentException(
  534. "This connector is not the parent for given extension");
  535. }
  536. extension.setParent(null);
  537. extensions.remove(extension);
  538. markAsDirty();
  539. }
  540. /*
  541. * (non-Javadoc)
  542. *
  543. * @see com.vaadin.server.ClientConnector#isAttached()
  544. */
  545. @Override
  546. public boolean isAttached() {
  547. return getSession() != null;
  548. }
  549. @Override
  550. public void attach() {
  551. markAsDirty();
  552. getUI().getConnectorTracker().registerConnector(this);
  553. for (ClientConnector connector : getAllChildrenIterable(this)) {
  554. connector.attach();
  555. }
  556. fireEvent(new AttachEvent(this));
  557. }
  558. /**
  559. * {@inheritDoc}
  560. *
  561. * <p>
  562. * The {@link #getSession()} and {@link #getUI()} methods might return
  563. * <code>null</code> after this method is called.
  564. * </p>
  565. */
  566. @Override
  567. public void detach() {
  568. for (ClientConnector connector : getAllChildrenIterable(this)) {
  569. connector.detach();
  570. }
  571. fireEvent(new DetachEvent(this));
  572. getUI().getConnectorTracker().unregisterConnector(this);
  573. }
  574. @Override
  575. public boolean isConnectorEnabled() {
  576. if (getParent() == null) {
  577. // No parent -> the component cannot receive updates from the client
  578. return false;
  579. } else {
  580. return getParent().isConnectorEnabled();
  581. }
  582. }
  583. @Override
  584. public void beforeClientResponse(boolean initial) {
  585. // Do nothing by default
  586. }
  587. @Override
  588. public boolean handleConnectorRequest(VaadinRequest request,
  589. VaadinResponse response, String path) throws IOException {
  590. DownloadStream stream = null;
  591. String[] parts = path.split("/", 2);
  592. String key = parts[0];
  593. VaadinSession session = getSession();
  594. session.lock();
  595. try {
  596. ConnectorResource resource = (ConnectorResource) getResource(key);
  597. if (resource == null) {
  598. return false;
  599. }
  600. stream = resource.getStream();
  601. } finally {
  602. session.unlock();
  603. }
  604. stream.writeResponse(request, response);
  605. return true;
  606. }
  607. /**
  608. * Gets a resource defined using {@link #setResource(String, Resource)} with
  609. * the corresponding key.
  610. *
  611. * @param key
  612. * the string identifier of the resource
  613. * @return a resource, or <code>null</code> if there's no resource
  614. * associated with the given key
  615. *
  616. * @see #setResource(String, Resource)
  617. */
  618. protected Resource getResource(String key) {
  619. return ResourceReference
  620. .getResource(getState(false).resources.get(key));
  621. }
  622. /**
  623. * Registers a resource with this connector using the given key. This will
  624. * make the URL for retrieving the resource available to the client-side
  625. * connector using
  626. * {@link com.vaadin.terminal.gwt.client.ui.AbstractConnector#getResourceUrl(String)}
  627. * with the same key.
  628. *
  629. * @param key
  630. * the string key to associate the resource with
  631. * @param resource
  632. * the resource to set, or <code>null</code> to clear a previous
  633. * association.
  634. */
  635. protected void setResource(String key, Resource resource) {
  636. ResourceReference resourceReference = ResourceReference.create(resource,
  637. this, key);
  638. if (resourceReference == null) {
  639. getState().resources.remove(key);
  640. } else {
  641. getState().resources.put(key, resourceReference);
  642. }
  643. }
  644. /* Listener code starts. Should be refactored. */
  645. /**
  646. * <p>
  647. * Registers a new listener with the specified activation method to listen
  648. * events generated by this component. If the activation method does not
  649. * have any arguments the event object will not be passed to it when it's
  650. * called.
  651. * </p>
  652. *
  653. * <p>
  654. * This method additionally informs the event-api to route events with the
  655. * given eventIdentifier to the components handleEvent function call.
  656. * </p>
  657. *
  658. * <p>
  659. * For more information on the inheritable event mechanism see the
  660. * {@link com.vaadin.event com.vaadin.event package documentation}.
  661. * </p>
  662. *
  663. * @param eventIdentifier
  664. * the identifier of the event to listen for
  665. * @param eventType
  666. * the type of the listened event. Events of this type or its
  667. * subclasses activate the listener.
  668. * @param target
  669. * the object instance who owns the activation method.
  670. * @param method
  671. * the activation method.
  672. * @return a registration object for removing the listener
  673. * @since 6.2
  674. */
  675. protected Registration addListener(String eventIdentifier,
  676. Class<?> eventType, Object target, Method method) {
  677. if (eventRouter == null) {
  678. eventRouter = new EventRouter();
  679. }
  680. boolean needRepaint = !eventRouter.hasListeners(eventType);
  681. Registration registration = eventRouter.addListener(eventType, target,
  682. method);
  683. if (needRepaint) {
  684. ComponentStateUtil.addRegisteredEventListener(getState(),
  685. eventIdentifier);
  686. }
  687. return registration;
  688. }
  689. /**
  690. * Checks if the given {@link Event} type is listened for this component.
  691. *
  692. * @param eventType
  693. * the event type to be checked
  694. * @return true if a listener is registered for the given event type
  695. */
  696. protected boolean hasListeners(Class<?> eventType) {
  697. return eventRouter != null && eventRouter.hasListeners(eventType);
  698. }
  699. /**
  700. * Removes all registered listeners matching the given parameters. Since
  701. * this method receives the event type and the listener object as
  702. * parameters, it will unregister all <code>object</code>'s methods that are
  703. * registered to listen to events of type <code>eventType</code> generated
  704. * by this component.
  705. *
  706. * <p>
  707. * This method additionally informs the event-api to stop routing events
  708. * with the given eventIdentifier to the components handleEvent function
  709. * call.
  710. * </p>
  711. *
  712. * <p>
  713. * For more information on the inheritable event mechanism see the
  714. * {@link com.vaadin.event com.vaadin.event package documentation}.
  715. * </p>
  716. *
  717. * @param eventIdentifier
  718. * the identifier of the event to stop listening for
  719. * @param eventType
  720. * the exact event type the <code>object</code> listens to.
  721. * @param target
  722. * the target object that has registered to listen to events of
  723. * type <code>eventType</code> with one or more methods.
  724. *
  725. * @since 6.2
  726. */
  727. protected void removeListener(String eventIdentifier, Class<?> eventType,
  728. Object target) {
  729. if (eventRouter != null) {
  730. eventRouter.removeListener(eventType, target);
  731. if (!eventRouter.hasListeners(eventType)) {
  732. ComponentStateUtil.removeRegisteredEventListener(getState(),
  733. eventIdentifier);
  734. }
  735. }
  736. }
  737. /**
  738. * <p>
  739. * Registers a new listener with the specified activation method to listen
  740. * events generated by this component. If the activation method does not
  741. * have any arguments the event object will not be passed to it when it's
  742. * called.
  743. * </p>
  744. *
  745. * <p>
  746. * For more information on the inheritable event mechanism see the
  747. * {@link com.vaadin.event com.vaadin.event package documentation}.
  748. * </p>
  749. *
  750. * @param eventType
  751. * the type of the listened event. Events of this type or its
  752. * subclasses activate the listener.
  753. * @param target
  754. * the object instance who owns the activation method.
  755. * @param method
  756. * the activation method.
  757. * @return a registration object for removing the listener
  758. */
  759. public Registration addListener(Class<?> eventType, Object target,
  760. Method method) {
  761. if (eventRouter == null) {
  762. eventRouter = new EventRouter();
  763. }
  764. return eventRouter.addListener(eventType, target, method);
  765. }
  766. /**
  767. * Removes all registered listeners matching the given parameters. Since
  768. * this method receives the event type and the listener object as
  769. * parameters, it will unregister all <code>object</code>'s methods that are
  770. * registered to listen to events of type <code>eventType</code> generated
  771. * by this component.
  772. *
  773. * <p>
  774. * For more information on the inheritable event mechanism see the
  775. * {@link com.vaadin.event com.vaadin.event package documentation}.
  776. * </p>
  777. *
  778. * @param eventType
  779. * the exact event type the <code>object</code> listens to.
  780. * @param target
  781. * the target object that has registered to listen to events of
  782. * type <code>eventType</code> with one or more methods.
  783. */
  784. public void removeListener(Class<?> eventType, Object target) {
  785. if (eventRouter != null) {
  786. eventRouter.removeListener(eventType, target);
  787. }
  788. }
  789. /**
  790. * Removes one registered listener method. The given method owned by the
  791. * given object will no longer be called when the specified events are
  792. * generated by this component.
  793. *
  794. * <p>
  795. * For more information on the inheritable event mechanism see the
  796. * {@link com.vaadin.event com.vaadin.event package documentation}.
  797. * </p>
  798. *
  799. * @param eventType
  800. * the exact event type the <code>object</code> listens to.
  801. * @param target
  802. * target object that has registered to listen to events of type
  803. * <code>eventType</code> with one or more methods.
  804. * @param method
  805. * the method owned by <code>target</code> that's registered to
  806. * listen to events of type <code>eventType</code>.
  807. * @deprecated use a {@link Registration} from
  808. * {@link #addListener(Class, Object, Method)} to remove a
  809. * listener
  810. */
  811. @Deprecated
  812. public void removeListener(Class<?> eventType, Object target,
  813. Method method) {
  814. if (eventRouter != null) {
  815. eventRouter.removeListener(eventType, target, method);
  816. }
  817. }
  818. /**
  819. * Returns all listeners that are registered for the given event type or one
  820. * of its subclasses.
  821. *
  822. * @param eventType
  823. * The type of event to return listeners for.
  824. * @return A collection with all registered listeners. Empty if no listeners
  825. * are found.
  826. */
  827. public Collection<?> getListeners(Class<?> eventType) {
  828. if (eventRouter == null) {
  829. return Collections.emptyList();
  830. }
  831. return eventRouter.getListeners(eventType);
  832. }
  833. /**
  834. * Sends the event to all listeners.
  835. *
  836. * @param event
  837. * the Event to be sent to all listeners.
  838. */
  839. protected void fireEvent(EventObject event) {
  840. if (eventRouter != null) {
  841. eventRouter.fireEvent(event);
  842. }
  843. }
  844. /*
  845. * (non-Javadoc)
  846. *
  847. * @see com.vaadin.server.ClientConnector#getErrorHandler()
  848. */
  849. @Override
  850. public ErrorHandler getErrorHandler() {
  851. return errorHandler;
  852. }
  853. /*
  854. * (non-Javadoc)
  855. *
  856. * @see com.vaadin.server.ClientConnector#setErrorHandler(com.vaadin.server.
  857. * ErrorHandler)
  858. */
  859. @Override
  860. public void setErrorHandler(ErrorHandler errorHandler) {
  861. this.errorHandler = errorHandler;
  862. }
  863. /*
  864. * (non-Javadoc)
  865. *
  866. * @see java.lang.Object#equals(java.lang.Object)
  867. */
  868. @Override
  869. public boolean equals(Object obj) {
  870. if (this == obj) {
  871. return true;
  872. }
  873. /*
  874. * This equals method must return true when we're comparing an object to
  875. * its proxy. This happens a lot with CDI (and possibly Spring) when
  876. * we're injecting Components. See #14639
  877. */
  878. if (obj instanceof AbstractClientConnector) {
  879. AbstractClientConnector connector = (AbstractClientConnector) obj;
  880. return connector.isThis(this);
  881. }
  882. return false;
  883. }
  884. /**
  885. * For internal use only, may be changed or removed in future versions.
  886. * <p>
  887. * This method must be protected, because otherwise it will not be redefined
  888. * by the proxy to actually be called on the underlying instance.
  889. * <p>
  890. * See #14639
  891. *
  892. * @deprecated only defined for framework hacks, do not use.
  893. */
  894. @Deprecated
  895. protected boolean isThis(Object that) {
  896. return this == that;
  897. }
  898. /*
  899. * (non-Javadoc)
  900. *
  901. * @see java.lang.Object#hashCode()
  902. */
  903. @Override
  904. public int hashCode() {
  905. return super.hashCode();
  906. }
  907. /**
  908. * Sets the expected value of a state property so that changes can be
  909. * properly sent to the client. This needs to be done in cases where a state
  910. * change originates from the client, since otherwise the server-side would
  911. * fail to recognize if the value is changed back to its previous value.
  912. *
  913. * @param propertyName
  914. * the name of the shared state property to update
  915. * @param newValue
  916. * the new diffstate reference value
  917. */
  918. protected void updateDiffstate(String propertyName, JsonValue newValue) {
  919. if (!isAttached()) {
  920. return;
  921. }
  922. JsonObject diffState = getUI().getConnectorTracker().getDiffState(this);
  923. if (diffState == null) {
  924. return;
  925. }
  926. assert diffState.hasKey(propertyName) : "Diffstate for "
  927. + getClass().getName() + " has no property named "
  928. + propertyName;
  929. diffState.put(propertyName, newValue);
  930. }
  931. }