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.

AbstractClientConnector.java 36KB

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