Check if the current node is part of routing request based on cluster.xml
or throw an exception.

@param key The key we are checking
@param routingStrategy The routing strategy
@param currentNode Current node
425757
public static void assertValidMetadata(ByteArray key,
                                           RoutingStrategy routingStrategy,
                                           Node currentNode) {
        List<Node> nodes = routingStrategy.routeRequest(key.get());
        for(Node node: nodes) {
            if(node.getId() == currentNode.getId()) {
                return;
            }
        }

        throw new InvalidMetadataException("Client accessing key belonging to partitions "
                                           + routingStrategy.getPartitionList(key.get())
                                           + " not present at " + currentNode);
    }
314116
boolean belongsToCluster(final MemcachedNode node) {
    for (MemcachedNode n : locator.getAll()) {
      if (n.getSocketAddress().equals(node.getSocketAddress())) {
        return true;
      }
    }
    return false;
  }
1053267
@Override
   public synchronized void updateCurrentTopology(List<Address> newMembers) {
      // The current topology might be null just after a joiner became the coordinator
      if (currentTopology == null) {
         createInitialCacheTopology();
      }
      ConsistentHashFactory<ConsistentHash> consistentHashFactory = getJoinInfo().getConsistentHashFactory();
      int topologyId = currentTopology.getTopologyId();
      int rebalanceId = currentTopology.getRebalanceId();
      ConsistentHash currentCH = currentTopology.getCurrentCH();
      ConsistentHash pendingCH = currentTopology.getPendingCH();
      if (!needConsistentHashUpdate()) {
         log.tracef("Cache %s members list was updated, but the cache topology doesn't need to change: %s",
               cacheName, currentTopology);
         return;
      }

      if (newMembers.isEmpty()) {
         log.tracef("Cache %s no longer has any members, removing topology", cacheName);
         setCurrentTopology(null);
         setStableTopology(null);
         rebalanceConfirmationCollector = null;
         status = ComponentStatus.INSTANTIATED;

         return;
      }


      List<Address> newCurrentMembers = pruneInvalidMembers(currentCH.getMembers());
      ConsistentHash newCurrentCH, newPendingCH = null;
      CacheTopology.Phase newPhase = CacheTopology.Phase.NO_REBALANCE;
      List<Address> actualMembers;
      if (newCurrentMembers.isEmpty()) {
         // All the current members left, try to replace them with the joiners
         log.tracef("All current members left, re-initializing status for cache %s", cacheName);
         rebalanceConfirmationCollector = null;

         newCurrentMembers = getExpectedMembers();
         actualMembers = newCurrentMembers;
         newCurrentCH = joinInfo.getConsistentHashFactory().create(
               joinInfo.getHashFunction(), joinInfo.getNumOwners(), joinInfo.getNumSegments(),
               newCurrentMembers, getCapacityFactors());
      } else {
         // ReplicatedConsistentHashFactory allocates segments to all its members, so we can't add any members here
         newCurrentCH = consistentHashFactory.updateMembers(currentCH, newCurrentMembers, getCapacityFactors());
         actualMembers = newCurrentMembers;
         if (pendingCH != null) {
            newPhase = currentTopology.getPhase();
            List<Address> newPendingMembers = pruneInvalidMembers(pendingCH.getMembers());
            newPendingCH = consistentHashFactory.updateMembers(pendingCH, newPendingMembers, getCapacityFactors());
            actualMembers = pruneInvalidMembers(newPendingMembers);
         }
      }
      // Losing members during state transfer could lead to a state where we have more than two topologies
      // concurrently in the cluster. We need to make sure that all the topologies are compatible (properties set
      // in CacheTopology docs hold) - we just remove lost members.
      CacheTopology newTopology = new CacheTopology(topologyId + 1, rebalanceId, newCurrentCH, newPendingCH,
            newPhase, actualMembers, persistentUUIDManager.mapAddresses(actualMembers));
      setCurrentTopology(newTopology);

      if (rebalanceConfirmationCollector != null) {
         // The node that will cancel the state transfer because of another topology update won't send topology confirm
         log.debugf("Cancelling topology confirmation %s because of another topology update", rebalanceConfirmationCollector);
         rebalanceConfirmationCollector = null;
      }

      CLUSTER.updatingTopology(cacheName, newTopology, availabilityMode);
      eventLogger.info(EventLogCategory.CLUSTER, MESSAGES.cacheMembersUpdated(
         actualMembers, newTopology.getTopologyId()));
      clusterTopologyManager.broadcastTopologyUpdate(cacheName, newTopology, availabilityMode,
            isTotalOrder(), isDistributed());
   }
799307
public boolean heartbeat(ClusterNodeInfo clusterNodeInfo)
    throws DisallowedNode {
    ClusterNode node = nameToNode.get(clusterNodeInfo.name);
    if (!canAllowNode(clusterNodeInfo.getAddress().getHost())) {
      if (node != null) {
        node.heartbeat(clusterNodeInfo);
      } else {
        throw new DisallowedNode(clusterNodeInfo.getAddress().getHost());
      }
      return false;
    }
    boolean newNode = false;
    Map<ResourceType, String> currentResources =
        clusterNodeInfo.getResourceInfos();
    if (currentResources == null) {
      currentResources = new EnumMap<ResourceType, String>(ResourceType.class);
    }

    if (node == null) {
      LOG.info("Adding node with heartbeat: " + clusterNodeInfo.toString());
      node = new ClusterNode(clusterNodeInfo,
          topologyCache.getNode(clusterNodeInfo.address.host),
          cpuToResourcePartitioning);
      addNode(node, currentResources);
      newNode = true;
    }

    node.heartbeat(clusterNodeInfo);

    boolean appsChanged = false;
    Map<ResourceType, String> prevResources =
        nameToApps.get(clusterNodeInfo.name);
    Set<ResourceType> deletedApps = null;
    for (Map.Entry<ResourceType, String> entry : prevResources.entrySet()) {
      String newAppInfo = currentResources.get(entry.getKey());
      String oldAppInfo = entry.getValue();
      if (newAppInfo == null || !newAppInfo.equals(oldAppInfo)) {
        if (deletedApps == null) {
          deletedApps = EnumSet.noneOf(ResourceType.class);
        }
        deletedApps.add(entry.getKey());
        appsChanged = true;
      }
    }
    Map<ResourceType, String> addedApps = null;
    for (Map.Entry<ResourceType, String> entry : currentResources.entrySet()) {
      String newAppInfo = entry.getValue();
      String oldAppInfo = prevResources.get(entry.getKey());
      if (oldAppInfo == null || !oldAppInfo.equals(newAppInfo)) {
        if (addedApps == null) {
          addedApps = new EnumMap<ResourceType, String>(ResourceType.class);
        }
        addedApps.put(entry.getKey(), entry.getValue());
        appsChanged = true;
      }
    }
    if (deletedApps != null) {
      for (ResourceType deleted : deletedApps) {
        clusterManager.nodeAppRemoved(clusterNodeInfo.name, deleted);
      }
    }
    if (addedApps != null) {
      for (Map.Entry<ResourceType, String> added: addedApps.entrySet()) {
        addAppToNode(node, added.getKey(), added.getValue());
      }
    }

    updateRunnability(node);
    return newNode || appsChanged;
  }
602394
protected boolean processNode2(Node current)
	{
		return processEdges(current, current.getDownstream()) ||
			processEdges(current, current.getUpstream());
	}
44378
public static void validateCurrentFinalCluster(final Cluster currentCluster,
                                                   final Cluster finalCluster) {
        validateClusterPartitionCounts(currentCluster, finalCluster);
        validateClusterNodeState(currentCluster, finalCluster);

        return;
    }
989869
public boolean containsKey(Object key) {
	if (key == null) {
	    throw new NullPointerException("key cannot be null");
	}
	else if (key instanceof String) {
	    Node<V> n = lookup((String)key);
	    return n != null && n.isTerminal();
	}
	else {
	    throw new ClassCastException("The provided key does not implement" +
					 " String: " + key);
	}
    }
561776
private int synchroizeTaskIDToHierarchy(Task parentTask, int currentID)
   {
      for (Task task : parentTask.getChildTasks())
      {
         task.setID(Integer.valueOf(currentID++));
         add(task);
         currentID = synchroizeTaskIDToHierarchy(task, currentID);
      }
      return currentID;
   }
1310846
public void execute(@Param("nodeId") Long nodeId, @Param("pageIndex") int pageIndex,
                        @Param("searchKey") String searchKey, Context context, Navigator nav) throws Exception {
        Node node = nodeService.findById(nodeId);
        if (node.getStatus().isStart()) {
            nav.redirectTo(WebConstant.ERROR_FORBIDDEN_Link);
            return;
        }

        List<AutoKeeperCluster> zkClusters = autoKeeperClusterService.listAutoKeeperClusters();
        context.put("zkClusters", zkClusters);
        context.put("node", node);
        context.put("pageIndex", pageIndex);
        context.put("searchKey", searchKey);
    }
848838
public static boolean checkPartitionBelongsToNode(int partition,
                                                      int nodeId,
                                                      Cluster cluster,
                                                      StoreDefinition storeDef) {
        List<Integer> nodePartitions = cluster.getNodeById(nodeId).getPartitionIds();
        List<Integer> replicatingPartitions = new RoutingStrategyFactory().updateRoutingStrategy(storeDef,
                                                                                                 cluster)
                                                                          .getReplicatingPartitionList(partition);
        replicatingPartitions.retainAll(nodePartitions);
        return replicatingPartitions.size() > 0;
    }
836398
protected void nodeCompleted(Object parent, Object node) {
        getProxyBuilder().getCurrentFactory().onNodeCompleted(getProxyBuilder().getChildBuilder(), parent, node);
    }
1350154
protected void checkNode(@Nullable Node node, Token type) throws MalformedException {
    if (node == null) {
      throw new MalformedException(
          "Expected node type " + type + "; found: null", node);
    }
    if (node.getToken() != type) {
      throw new MalformedException(
          "Expected node type " + type + "; found: " + node.getToken(), node);
    }
  }
984216
private void analyse(StructuralNode node) throws Exception {
	// if analysed already, return;
        // move to host part
        if (node.getHistoryReference() == null) {
            return;
        }

        if (!parent.nodeInScope(node.getName())) {
            return;
        }

        // ZAP: Removed unnecessary cast.
        HttpMessage baseMsg = node.getHistoryReference().getHttpMessage();
        URI baseUri = (URI) baseMsg.getRequestHeader().getURI().clone();

        baseUri.setQuery(null);
        //System.out.println("analysing: " + baseUri.toString());

        // already exist one.  no need to test
        if (mapVisited.get(baseUri.toString()) != null) {
            return;
        }

        String path = getRandomPathSuffix(node, baseUri);
        HttpMessage msg = baseMsg.cloneRequest();

        URI uri = (URI) baseUri.clone();
        uri.setPath(path);
        msg.getRequestHeader().setURI(uri);
        //System.out.println("analysing 2: " + uri);

        sendAndReceive(msg);

	// standard RFC response, no further check is needed
        if (msg.getResponseHeader().getStatusCode() == HttpStatusCode.NOT_FOUND) {
            addAnalysedHost(baseUri, msg, SampleResponse.ERROR_PAGE_RFC);
            return;
        }

        if (HttpStatusCode.isRedirection(msg.getResponseHeader().getStatusCode())) {
            addAnalysedHost(baseUri, msg, SampleResponse.ERROR_PAGE_REDIRECT);
            return;
        }

        if (msg.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
            addAnalysedHost(baseUri, msg, SampleResponse.ERROR_PAGE_NON_RFC);
            return;
        }

        HttpMessage msg2 = baseMsg.cloneRequest();
        URI uri2 = msg2.getRequestHeader().getURI();
        String path2 = getRandomPathSuffix(node, uri2);
        uri2 = (URI) baseUri.clone();
        uri2.setPath(path2);
        msg2.getRequestHeader().setURI(uri2);
        sendAndReceive(msg2);

        // remove HTML HEAD as this may contain expiry time which dynamic changes		
        String resBody1 = msg.getResponseBody().toString().replaceAll(p_REMOVE_HEADER, "");
        String resBody2 = msg2.getResponseBody().toString().replaceAll(p_REMOVE_HEADER, "");

        // check if page is static.  If so, remember this static page
        if (resBody1.equals(resBody2)) {
            msg.getResponseBody().setBody(resBody1);
            addAnalysedHost(baseUri, msg, SampleResponse.ERROR_PAGE_STATIC);
            return;
        }

        // else check if page is dynamic but deterministic
        resBody1 = resBody1.replaceAll(getPathRegex(uri), "").replaceAll("\\s[012]\\d:[0-5]\\d:[0-5]\\d\\s", "");
        resBody2 = resBody2.replaceAll(getPathRegex(uri2), "").replaceAll("\\s[012]\\d:[0-5]\\d:[0-5]\\d\\s", "");
        if (resBody1.equals(resBody2)) {
            msg.getResponseBody().setBody(resBody1);
            addAnalysedHost(baseUri, msg, SampleResponse.ERROR_PAGE_DYNAMIC_BUT_DETERMINISTIC);
            return;
        }

        // else mark app "undeterministic".
        addAnalysedHost(baseUri, msg, SampleResponse.ERROR_PAGE_UNDETERMINISTIC);

    }
577358
private int findPartnerNodeId( Tree<Row> current, Type type ){
        switch( type ) {
            case JOIN_FIRST:
            case JOIN_ALL:
            case WHILE_DO_END:
                // The partner is the previous sibling which is the SPLIT or WHILE_DO_BEGIN
                return current.getPrevious().getContent().getId();
            case DO_WHILE_BEGIN:
                // The partner is the next sibling which is the DO_WHILE_END
                return current.getNext().getContent().getMainElement().getId();
            case END_IF:
                // The partner is the first previous IF (there may be ELSE_IF and ELSE siblings between IF and this END_IF)
                Tree<Row> if_ = current;
                while( !Type.IF.equals( if_.getContent().getType() ) ){
                    if_ = if_.getPrevious();
                }
                return if_.getContent().getId();
            default :
                throw new IllegalStateException();
        }
    }
529898
private void handleRequestNodeInfoResponse(SerialMessage incomingMessage) {
		logger.trace("Handle RequestNodeInfo Response");
		if(incomingMessage.getMessageBuffer()[2] != 0x00)
			logger.debug("Request node info successfully placed on stack.");
		else
			logger.error("Request node info not placed on stack due to error.");
	}
27414
public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        InstanceInfo myInfo = ApplicationInfoManager.getInstance().getInfo();
        InstanceStatus status = myInfo.getStatus();
        if (status != InstanceStatus.UP && response instanceof HttpServletResponse) {
            HttpServletResponse httpRespone = (HttpServletResponse) response;
            httpRespone.sendError(SC_TEMPORARY_REDIRECT,
                    "Current node is currently not ready to serve requests -- current status: "
                            + status + " - try another DS node: ");
        }
        chain.doFilter(request, response);
    }
454595
private void connectNodesIfNecessary(AbstractPlanNode node) {
        NodeSchema outputSchema = node.getOutputSchema();
        if (outputSchema != null) {
            for (SchemaColumn col : outputSchema) {
                connectPredicateStmt(col.getExpression());
            }
        }
        if (node instanceof AbstractScanPlanNode) {
            AbstractScanPlanNode scanNode = (AbstractScanPlanNode)node;
            connectPredicateStmt(scanNode.getPredicate());
            // If this is common table scan, we connect the scan node to the
            // plan nodes for the base and recursive query.
            if (scanNode instanceof SeqScanPlanNode) {
                SeqScanPlanNode seqScanNode = (SeqScanPlanNode)scanNode;
                connectCTENodesIfAny(seqScanNode);
            }
        } else if (node instanceof AbstractJoinPlanNode) {
            AbstractJoinPlanNode joinNode = (AbstractJoinPlanNode)node;
            connectPredicateStmt(joinNode.getPreJoinPredicate());
            connectPredicateStmt(joinNode.getJoinPredicate());
            connectPredicateStmt(joinNode.getWherePredicate());
        } else if (node instanceof AggregatePlanNode) {
            AggregatePlanNode aggNode = (AggregatePlanNode)node;
            connectPredicateStmt(aggNode.getPostPredicate());
        }

        for (AbstractPlanNode inlineNode: node.getInlinePlanNodes().values()) {
            connectNodesIfNecessary(inlineNode);
        }
    }