+ public EntityOwnershipListenerRegistration registerListener(String entityType, EntityOwnershipListener listener) {
+ Preconditions.checkNotNull(entityType, "entityType cannot be null");
+ Preconditions.checkNotNull(listener, "listener cannot be null");
+
+ RegisterListenerLocal registerListener = new RegisterListenerLocal(listener, entityType);
+
+ LOG.debug("Registering listener with message: {}", registerListener);
+
+ executeLocalEntityOwnershipShardOperation(registerListener);
+ return new DistributedEntityOwnershipListenerRegistration(listener, entityType, this);
+ }
+
+ @Override
+ public Optional<EntityOwnershipState> getOwnershipState(Entity forEntity) {
+ Preconditions.checkNotNull(forEntity, "forEntity cannot be null");
+
+ DataTree dataTree = getLocalEntityOwnershipShardDataTree();
+ if(dataTree == null) {
+ return Optional.absent();
+ }
+
+ Optional<NormalizedNode<?, ?>> entityNode = dataTree.takeSnapshot().readNode(
+ entityPath(forEntity.getType(), forEntity.getId()));
+ if(!entityNode.isPresent()) {
+ return Optional.absent();
+ }
+
+ String localMemberName = datastore.getActorContext().getCurrentMemberName();
+ Optional<DataContainerChild<? extends PathArgument, ?>> ownerLeaf = ((MapEntryNode)entityNode.get()).
+ getChild(ENTITY_OWNER_NODE_ID);
+ String owner = ownerLeaf.isPresent() ? ownerLeaf.get().getValue().toString() : null;
+ boolean hasOwner = !Strings.isNullOrEmpty(owner);
+ boolean isOwner = hasOwner && localMemberName.equals(owner);
+
+ return Optional.of(new EntityOwnershipState(isOwner, hasOwner));
+ }
+
+ private DataTree getLocalEntityOwnershipShardDataTree() {
+ if(localEntityOwnershipShardDataTree == null) {
+ try {
+ if(localEntityOwnershipShard == null) {
+ localEntityOwnershipShard = Await.result(datastore.getActorContext().findLocalShardAsync(
+ ENTITY_OWNERSHIP_SHARD_NAME), Duration.Inf());
+ }
+
+ localEntityOwnershipShardDataTree = (DataTree) Await.result(Patterns.ask(localEntityOwnershipShard,
+ GetShardDataTree.INSTANCE, MESSAGE_TIMEOUT), Duration.Inf());
+ } catch (Exception e) {
+ LOG.error("Failed to find local {} shard", ENTITY_OWNERSHIP_SHARD_NAME, e);
+ }
+ }
+
+ return localEntityOwnershipShardDataTree;
+ }
+
+ void unregisterListener(String entityType, EntityOwnershipListener listener) {
+ LOG.debug("Unregistering listener {} for entity type {}", listener, entityType);
+
+ executeLocalEntityOwnershipShardOperation(new UnregisterListenerLocal(listener, entityType));