+ return new DistributedEntityOwnershipCandidateRegistration(entity, this);
+ }
+
+ void unregisterCandidate(final DOMEntity entity) {
+ LOG.debug("Unregistering candidate for {}", entity);
+
+ executeLocalEntityOwnershipShardOperation(new UnregisterCandidateLocal(entity));
+ registeredEntities.remove(entity);
+ }
+
+ @Override
+ public DOMEntityOwnershipListenerRegistration registerListener(final String entityType,
+ final DOMEntityOwnershipListener listener) {
+ 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(final DOMEntity forEntity) {
+ requireNonNull(forEntity, "forEntity cannot be null");
+
+ DataTree dataTree = getLocalEntityOwnershipShardDataTree();
+ if (dataTree == null) {
+ return Optional.empty();
+ }
+
+ Optional<NormalizedNode<?, ?>> entityNode = dataTree.takeSnapshot().readNode(
+ entityPath(forEntity.getType(), forEntity.getIdentifier()));
+ if (!entityNode.isPresent()) {
+ return Optional.empty();
+ }
+
+ // Check if there are any candidates, if there are none we do not really have ownership state
+ final MapEntryNode entity = (MapEntryNode) entityNode.get();
+ final Optional<DataContainerChild<? extends PathArgument, ?>> optionalCandidates =
+ entity.getChild(CANDIDATE_NODE_ID);
+ final boolean hasCandidates = optionalCandidates.isPresent()
+ && ((MapNode) optionalCandidates.get()).getValue().size() > 0;
+ if (!hasCandidates) {
+ return Optional.empty();
+ }
+
+ MemberName localMemberName = context.getCurrentMemberName();
+ Optional<DataContainerChild<? extends PathArgument, ?>> ownerLeaf = entity.getChild(ENTITY_OWNER_NODE_ID);
+ String owner = ownerLeaf.isPresent() ? ownerLeaf.get().getValue().toString() : null;
+ boolean hasOwner = !Strings.isNullOrEmpty(owner);
+ boolean isOwner = hasOwner && localMemberName.getName().equals(owner);
+
+ return Optional.of(EntityOwnershipState.from(isOwner, hasOwner));