+ Preconditions.checkNotNull(entity, "entity cannot be null");
+
+ if (registeredEntities.putIfAbsent(entity, entity) != null) {
+ throw new CandidateAlreadyRegisteredException(entity);
+ }
+
+ RegisterCandidateLocal registerCandidate = new RegisterCandidateLocal(entity);
+
+ LOG.debug("Registering candidate with message: {}", registerCandidate);
+
+ executeLocalEntityOwnershipShardOperation(registerCandidate);
+ 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) {
+ 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(final DOMEntity 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.getIdentifier()));
+ if (!entityNode.isPresent()) {
+ return Optional.absent();
+ }
+
+ // 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.absent();
+ }
+
+ 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));