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

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