private void listenMembershipEvents() throws IOException {
    final SerializationService serializationService = clusterService.getSerializationService();
    while (!Thread.currentThread().isInterrupted()) {
      final Data clientResponseData = conn.read();
      final ClientResponse clientResponse = serializationService.toObject(clientResponseData);
      final Object eventObject = serializationService.toObject(clientResponse.getResponse());
      final ClientMembershipEvent event = (ClientMembershipEvent) eventObject;
      final MemberImpl member = (MemberImpl) event.getMember();
      boolean membersUpdated = false;
      if (event.getEventType() == MembershipEvent.MEMBER_ADDED) {
        members.add(member);
        membersUpdated = true;
      } else if (event.getEventType() == ClientMembershipEvent.MEMBER_REMOVED) {
        members.remove(member);
        membersUpdated = true;
        //                    getConnectionManager().removeConnectionPool(member.getAddress());
        // //TODO
      } else if (event.getEventType() == ClientMembershipEvent.MEMBER_ATTRIBUTE_CHANGED) {
        MemberAttributeChange memberAttributeChange = event.getMemberAttributeChange();
        Map<Address, MemberImpl> memberMap = clusterService.getMembersRef();
        if (memberMap != null) {
          for (MemberImpl target : memberMap.values()) {
            if (target.getUuid().equals(memberAttributeChange.getUuid())) {
              final MemberAttributeOperationType operationType =
                  memberAttributeChange.getOperationType();
              final String key = memberAttributeChange.getKey();
              final Object value = memberAttributeChange.getValue();
              target.updateAttribute(operationType, key, value);
              MemberAttributeEvent memberAttributeEvent =
                  new MemberAttributeEvent(client.getCluster(), target, operationType, key, value);
              clusterService.fireMemberAttributeEvent(memberAttributeEvent);
              break;
            }
          }
        }
      }

      if (membersUpdated) {
        ((ClientPartitionServiceImpl) client.getClientPartitionService()).refreshPartitions();
        updateMembersRef();
        LOGGER.info(clusterService.membersString());
        clusterService.fireMembershipEvent(
            new MembershipEvent(
                client.getCluster(),
                member,
                event.getEventType(),
                Collections.unmodifiableSet(new LinkedHashSet<Member>(members))));
      }
    }
  }
 private void updateMembersRef() {
   final Map<Address, MemberImpl> map = new LinkedHashMap<Address, MemberImpl>(members.size());
   for (MemberImpl member : members) {
     map.put(member.getAddress(), member);
   }
   clusterService.setMembersRef(Collections.unmodifiableMap(map));
 }
 private List<MembershipEvent> detectMembershipEvents(Map<String, MemberImpl> prevMembers) {
   final List<MembershipEvent> events = new LinkedList<MembershipEvent>();
   final Set<Member> eventMembers =
       Collections.unmodifiableSet(new LinkedHashSet<Member>(members));
   for (MemberImpl member : members) {
     final MemberImpl former = prevMembers.remove(member.getUuid());
     if (former == null) {
       events.add(
           new MembershipEvent(
               client.getCluster(), member, MembershipEvent.MEMBER_ADDED, eventMembers));
     }
   }
   for (MemberImpl member : prevMembers.values()) {
     events.add(
         new MembershipEvent(
             client.getCluster(), member, MembershipEvent.MEMBER_REMOVED, eventMembers));
     if (clusterService.getMember(member.getAddress()) == null) {
       final Connection connection = connectionManager.getConnection(member.getAddress());
       if (connection != null) {
         connectionManager.destroyConnection(connection);
       }
     }
   }
   return events;
 }
 @Override
 public void handle(String uuid, String key, int opType, String value) {
   Map<Address, Member> memberMap = clusterService.getMembersRef();
   if (memberMap == null) {
     return;
   }
   for (Member target : memberMap.values()) {
     if (target.getUuid().equals(uuid)) {
       final MemberAttributeOperationType operationType =
           MemberAttributeOperationType.getValue(opType);
       ((AbstractMember) target).updateAttribute(operationType, key, value);
       MemberAttributeEvent memberAttributeEvent =
           new MemberAttributeEvent(client.getCluster(), target, operationType, key, value);
       clusterService.fireMemberAttributeEvent(memberAttributeEvent);
       break;
     }
   }
 }
 void doShutdown() {
   CLIENTS.remove(id);
   executionService.shutdown();
   partitionService.stop();
   clusterService.stop();
   transactionManager.shutdown();
   connectionManager.shutdown();
   proxyManager.destroy();
   serializationService.destroy();
 }
 private void memberAdded(MemberImpl member) {
   members.add(member);
   applyMemberListChanges();
   MembershipEvent event =
       new MembershipEvent(
           client.getCluster(),
           member,
           ClientInitialMembershipEvent.MEMBER_ADDED,
           Collections.unmodifiableSet(new LinkedHashSet<Member>(members)));
   clusterService.fireMembershipEvent(event);
 }
 private void memberAttributeChanged(MemberAttributeChange memberAttributeChange) {
   Map<Address, MemberImpl> memberMap = clusterService.getMembersRef();
   if (memberMap == null) {
     return;
   }
   if (memberAttributeChange == null) {
     return;
   }
   for (MemberImpl target : memberMap.values()) {
     if (target.getUuid().equals(memberAttributeChange.getUuid())) {
       final MemberAttributeOperationType operationType = memberAttributeChange.getOperationType();
       final String key = memberAttributeChange.getKey();
       final Object value = memberAttributeChange.getValue();
       target.updateAttribute(operationType, key, value);
       MemberAttributeEvent memberAttributeEvent =
           new MemberAttributeEvent(client.getCluster(), target, operationType, key, value);
       clusterService.fireMemberAttributeEvent(memberAttributeEvent);
       break;
     }
   }
 }
  private void loadInitialMemberList() throws Exception {
    final SerializationService serializationService = clusterService.getSerializationService();
    final AddMembershipListenerRequest request = new AddMembershipListenerRequest();
    final SerializableCollection coll =
        (SerializableCollection) connectionManager.sendAndReceive(request, conn);

    Map<String, MemberImpl> prevMembers = Collections.emptyMap();
    if (!members.isEmpty()) {
      prevMembers = new HashMap<String, MemberImpl>(members.size());
      for (MemberImpl member : members) {
        prevMembers.put(member.getUuid(), member);
      }
      members.clear();
    }
    for (Data data : coll) {
      members.add((MemberImpl) serializationService.toObject(data));
    }
    updateMembersRef();
    LOGGER.info(clusterService.membersString());
    final List<MembershipEvent> events = new LinkedList<MembershipEvent>();
    final Set<Member> eventMembers =
        Collections.unmodifiableSet(new LinkedHashSet<Member>(members));
    for (MemberImpl member : members) {
      final MemberImpl former = prevMembers.remove(member.getUuid());
      if (former == null) {
        events.add(
            new MembershipEvent(
                client.getCluster(), member, MembershipEvent.MEMBER_ADDED, eventMembers));
      }
    }
    for (MemberImpl member : prevMembers.values()) {
      events.add(
          new MembershipEvent(
              client.getCluster(), member, MembershipEvent.MEMBER_REMOVED, eventMembers));
    }
    for (MembershipEvent event : events) {
      clusterService.fireMembershipEvent(event);
    }
    latch.countDown();
  }
 private void start() {
   lifecycleService.setStarted();
   connectionManager.start();
   try {
     clusterService.start();
   } catch (IllegalStateException e) {
     // there was an authentication failure (todo: perhaps use an AuthenticationException
     // ??)
     lifecycleService.shutdown();
     throw e;
   }
   loadBalancer.init(getCluster(), config);
   partitionService.start();
 }
 private void memberRemoved(MemberImpl member) {
   members.remove(member);
   final Connection connection = connectionManager.getConnection(member.getAddress());
   if (connection != null) {
     connectionManager.destroyConnection(connection);
   }
   applyMemberListChanges();
   MembershipEvent event =
       new MembershipEvent(
           client.getCluster(),
           member,
           ClientInitialMembershipEvent.MEMBER_REMOVED,
           Collections.unmodifiableSet(new LinkedHashSet<Member>(members)));
   clusterService.fireMembershipEvent(event);
 }
  private ClientConnection connectToOne() throws Exception {
    final ClientNetworkConfig networkConfig = client.getClientConfig().getNetworkConfig();
    final int connectionAttemptLimit = networkConfig.getConnectionAttemptLimit();
    final int connectionAttemptPeriod = networkConfig.getConnectionAttemptPeriod();
    int attempt = 0;
    Throwable lastError = null;
    while (true) {
      final long nextTry = Clock.currentTimeMillis() + connectionAttemptPeriod;
      final Collection<InetSocketAddress> socketAddresses = getSocketAddresses();
      for (InetSocketAddress isa : socketAddresses) {
        Address address = new Address(isa);
        try {
          final ClientConnection connection = connectionManager.ownerConnection(address);
          clusterService.fireConnectionEvent(false);
          return connection;
        } catch (IOException e) {
          lastError = e;
          LOGGER.finest("IO error during initial connection...", e);
        } catch (AuthenticationException e) {
          lastError = e;
          LOGGER.warning("Authentication error on " + address, e);
        }
      }
      if (attempt++ >= connectionAttemptLimit) {
        break;
      }
      final long remainingTime = nextTry - Clock.currentTimeMillis();
      LOGGER.warning(
          String.format(
              "Unable to get alive cluster connection," + " try in %d ms later, attempt %d of %d.",
              Math.max(0, remainingTime), attempt, connectionAttemptLimit));

      if (remainingTime > 0) {
        try {
          Thread.sleep(remainingTime);
        } catch (InterruptedException e) {
          break;
        }
      }
    }
    throw new IllegalStateException("Unable to connect to any address in the config!", lastError);
  }
  public void run() {
    while (!Thread.currentThread().isInterrupted()) {
      try {
        if (conn == null) {
          try {
            conn = connectToOne();
          } catch (Exception e) {
            LOGGER.severe("Error while connecting to cluster!", e);
            client.getLifecycleService().shutdown();
            latch.countDown();
            return;
          }
        }
        getInvocationService().triggerFailedListeners();
        loadInitialMemberList();
        listenMembershipEvents();
      } catch (Exception e) {
        if (client.getLifecycleService().isRunning()) {
          if (LOGGER.isFinestEnabled()) {
            LOGGER.warning("Error while listening cluster events! -> " + conn, e);
          } else {
            LOGGER.warning(
                "Error while listening cluster events! -> " + conn + ", Error: " + e.toString());
          }
        }

        connectionManager.markOwnerConnectionAsClosed();
        IOUtil.closeResource(conn);
        conn = null;
        clusterService.fireConnectionEvent(true);
      }
      try {
        Thread.sleep(SLEEP_TIME);
      } catch (InterruptedException e) {
        latch.countDown();
        break;
      }
    }
  }
  private void fireMembershipEvent(List<MembershipEvent> events) {

    for (MembershipEvent event : events) {
      clusterService.fireMembershipEvent(event);
    }
  }
 private void applyMemberListChanges() {
   updateMembersRef();
   LOGGER.info(clusterService.membersString());
 }
 @Override
 public Client getLocalEndpoint() {
   return clusterService.getLocalClient();
 }