/*
Process the event generated when the node for a user snapshot request
is created.
424794
private void processUserSnapshotRequestEvent(final WatchedEvent event) throws Exception {
        if (event.getType() == EventType.NodeCreated) {
            byte data[] = m_zk.getData(event.getPath(), false, null);
            String jsonString = new String(data, "UTF-8");
            final JSONObject jsObj = new JSONObject(jsonString);
            final String requestId = jsObj.getString("requestId");
            final boolean blocking = jsObj.getBoolean(SnapshotUtil.JSON_BLOCK);
            /*
             * Going to reuse the request object, remove the requestId
             * field now that it is consumed
             */
            jsObj.remove("requestId");
            jsObj.put("perPartitionTxnIds", retrievePerPartitionTransactionIds());
            String nonce = jsObj.getString(SnapshotUtil.JSON_NONCE);
            final long handle = m_nextCallbackHandle++;
            m_procedureCallbacks.put(handle, new ProcedureCallback() {

                @Override
                public void clientCallback(ClientResponse clientResponse) {
                    m_lastInitiationTs = null;
                    try {
                        /*
                         * If there is an error then we are done.
                         */
                        if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
                            ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
                            saveResponseToZKAndReset(requestId, rimpl);
                            return;
                        }

                        /*
                         * Now analyze the response. If a snapshot was in progress
                         * we have to reattempt it later, and send a response to the client
                         * saying it was queued. Otherwise, forward the response
                         * failure/success to the client.
                         */
                        if (isSnapshotInProgressResponse(clientResponse)) {
                            loggingLog.info("Deferring user snapshot with nonce " + nonce + " until after in-progress snapshot completes");
                            scheduleSnapshotForLater(jsObj.toString(4), requestId, true);
                        } else {
                            ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
                            saveResponseToZKAndReset(requestId, rimpl);
                            return;
                        }
                    } catch (Exception e) {
                        SNAP_LOG.error("Error processing user snapshot request", e);
                        try {
                            userSnapshotRequestExistenceCheck(true);
                        } catch (Exception e2) {
                            VoltDB.crashLocalVoltDB("Error resetting watch for user snapshots", true, e2);
                        }
                    }
                }
            });
            loggingLog.info("Initiating user snapshot with nonce " + nonce);
            initiateSnapshotSave(handle, new Object[]{jsObj.toString(4)}, blocking);
            return;
        }
    }
235928
private void handleDeadNode(String nodeName, Set<String> sessions) {
    LOG.info("Notify sessions: " + sessions + " about dead node " + nodeName);
    for (String session : sessions) {
      sessionNotifier.notifyDeadNode(session, nodeName);
    }
  }
159502
void truncationRequestExistenceCheck() throws KeeperException, InterruptedException {
        loggingLog.info("Checking for existence of snapshot truncation request");
        m_currentTruncationWatcher.cancel();
        m_currentTruncationWatcher = new TruncationRequestExistenceWatcher();
        // TRAIL [TruncSnap:2] checking for zk node existence
        List<String> requests = m_zk.getChildren(VoltZK.request_truncation_snapshot, m_currentTruncationWatcher);
        if (!requests.isEmpty()) {
            loggingLog.info("A truncation request node already existed, processing truncation request event");
            m_currentTruncationWatcher.cancel();
            // TRAIL [TruncSnap:3] fake a node created event (req ZK node already there)
            processTruncationRequestEvent(new WatchedEvent(
                    EventType.NodeChildrenChanged,
                    KeeperState.SyncConnected,
                    VoltZK.request_truncation_snapshot));
        }
    }
1138128
private void processPartitionWatchEvent() throws KeeperException, InterruptedException {
        try {
            m_zk.create(m_rootNode, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            m_zk.getData(m_rootNode, m_childWatch, null);
        } catch (KeeperException.NodeExistsException e) {
            m_zk.getData(m_rootNode, m_childWatch, null);
        }
    }
334082
public void processEvent(EventObject event) // for asynchronous
  // (nonblocking) response
  // handling
  {
    synchronized (this) {
    } // wail til message sending has finished (transaction attribute set)

    if (event instanceof ResponseEvent) {
      processResponse((ResponseEvent) event);
    } else if (event instanceof TimeoutEvent) {
      processTimeout((TimeoutEvent) event);
    }

    // note, requests don't come through here, they are handled via the
    // listen/waitFor methods.
  }
796292
void processEvent(Event e) {
    assert !_processed;
    // Event e = _events[idx];
    if (e.isSend()) {
      _sends.put(e, new ArrayList<TimelineSnapshot.Event>());
      for (Event otherE : _events) {
        if ((otherE != null) && (otherE != e) && (!otherE.equals(e)) && otherE._blocked
          && otherE.match(e)) {
          _edges.put(otherE, e);
          _sends.get(e).add(otherE);
          otherE._blocked = false;
        }
      }
    } else { // look for matching send, otherwise set _blocked
      assert !_edges.containsKey(e);
      int senderIdx = e.packH2O().index();
      if (senderIdx < 0) { // binary search did not find member, should not happen?
        // no possible sender - return and do not block
        Log.warn("no sender found! port = " + e.portPack() + ", ip = " + e.addrPack().toString());
        return;
      }
      Event senderCnd = _events[senderIdx];
      if (senderCnd != null) {
        if (isSenderRecvPair(senderCnd, e)) {
          _edges.put(e, senderCnd.clone());
          _sends.get(senderCnd).add(e);
          return;
        }
        senderCnd = senderCnd.clone();
        while (senderCnd.prev()) {
          if (isSenderRecvPair(senderCnd, e)) {
            _edges.put(e, senderCnd);
            _sends.get(senderCnd).add(e);
            return;
          }
        }
      }
      e._blocked = true;
    }
    assert (e == null) || (e._eventIdx < TimeLine.MAX_EVENTS);
  }
109294
public void createAndWatchRequestNode(final long clientHandle,
                                          final Connection c,
                                          SnapshotInitiationInfo snapInfo,
                                          boolean notifyChanges) throws ForwardClientException {
        boolean requestExists = false;
        final String requestId = createRequestNode(snapInfo);
        if (requestId == null) {
            requestExists = true;
        } else {
            if (!snapInfo.isTruncationRequest()) {
                try {
                    registerUserSnapshotResponseWatch(requestId, clientHandle, c, notifyChanges);
                } catch (Exception e) {
                    VoltDB.crashLocalVoltDB("Failed to register ZK watch on snapshot response", true, e);
                }
            }
            else {
                // need to construct a success response of some sort here to indicate the truncation attempt
                // was successfully attempted
                VoltTable result = SnapshotUtil.constructNodeResultsTable();
                result.addRow(-1,
                        CoreUtils.getHostnameOrAddress(),
                        "",
                        "SUCCESS",
                        "SNAPSHOT REQUEST QUEUED");
                final ClientResponseImpl resp =
                    new ClientResponseImpl(ClientResponseImpl.SUCCESS,
                            new VoltTable[] {result},
                            "User-requested truncation snapshot successfully queued for execution.",
                            clientHandle);
                ByteBuffer buf = ByteBuffer.allocate(resp.getSerializedSize() + 4);
                buf.putInt(buf.capacity() - 4);
                resp.flattenToBuffer(buf).flip();
                c.writeStream().enqueue(buf);
            }
        }

        if (requestExists) {
            VoltTable result = SnapshotUtil.constructNodeResultsTable();
            result.addRow(-1,
                    CoreUtils.getHostnameOrAddress(),
                    "",
                    "FAILURE",
                    "SNAPSHOT IN PROGRESS");
            throw new ForwardClientException("A request to perform a user snapshot already exists", result);
        }
    }
85690
@Override
	protected void onNode(String name, String currentPath) throws SAXException
    {
        if (currentPath.equals("security") ||
            currentPath.equals("security/users"))
        {
            // Nothing to do
        }
        else if (currentPath.equals("security/users/user"))
        {
            descriptor.addUser(currentUser);
            currentUser = null;
        }
        else if (currentPath.equals("security/users/user/privilege"))
        {
            currentUser.addPrivilege(currentPrivilege);
            currentPrivilege = null;
        }
        else
            throw new SAXException("Unexpected node : " + name + " (" + currentPath + ")");
    }
955604
function firePopState() {
    var o = document.createEvent ? document.createEvent('Event') : document.createEventObject();
    if (o.initEvent) {
      o.initEvent('popstate', false, false);
    } else {
      o.type = 'popstate';
    }
    o.state = historyObject.state;
    // send a newly created events to be processed
    dispatchEvent(o);
  }
708352
@Override
    public void process(Object event) throws Exception {
        int secOffset = TimeUtils.secOffset();
        if (secOffset < UPLOAD_TIME_OFFSET_SEC) {
            JStormUtils.sleepMs((UPLOAD_TIME_OFFSET_SEC - secOffset) * 1000);
        } else if (secOffset == UPLOAD_TIME_OFFSET_SEC) {
            // do nothing
        } else {
            JStormUtils.sleepMs((60 - secOffset + UPLOAD_TIME_OFFSET_SEC) * 1000);
        }
        if (topologyMetricContext.getUploadedWorkerNum() > 0) {
            metricLogger.info("force upload metrics.");
            mergeAndUploadMetrics();
        }
    }
536000
protected void processParentEvent() throws Exception {
        // get current children snapshot and reset this watch.
        Set<String> children = new TreeSet<String>(m_zk.getChildren(m_rootNode, m_parentWatch));
        // intersect to get newChildren and update m_lastChildren to the current set.
        Set<String> newChildren = new HashSet<String>(children);
        newChildren.removeAll(m_lastChildren);
        m_lastChildren = children;

        List<ByteArrayCallback> callbacks = new ArrayList<ByteArrayCallback>();
        for (String child : children) {
            ByteArrayCallback cb = new ByteArrayCallback();
            // set watches on new children.
            if(newChildren.contains(child)) {
                m_zk.getData(ZKUtil.joinZKPath(m_rootNode, child), m_childWatch, cb, null);
            } else {
                m_zk.getData(ZKUtil.joinZKPath(m_rootNode, child), false, cb, null);
            }

            callbacks.add(cb);
        }

        HashMap<Integer, LeaderCallBackInfo> cache = new HashMap<Integer, LeaderCallBackInfo>();
        for (ByteArrayCallback callback : callbacks) {
            try {
                byte payload[] = callback.get();
                // During initialization children node may contain no data.
                if (payload == null) {
                    continue;
                }
                String data = new String(payload, "UTF-8");
                LeaderCallBackInfo info = LeaderCache.buildLeaderCallbackFromString(data);
                Integer partitionId = getPartitionIdFromZKPath(callback.getPath());
                cache.put(partitionId, info);
            } catch (KeeperException.NoNodeException e) {
                // child may have been deleted between the parent trigger and getData.
            }
        }

        m_publicCache = ImmutableMap.copyOf(cache);
        if (m_cb != null) {
            m_cb.run(m_publicCache);
        }
    }
12965
private void handleLeaveEvent(Node node) {
    SwimMember member = members.get(MemberId.from(node.id().id()));
    if (member != null && !member.isActive()) {
      members.remove(member.id());
    }
  }
1059664
private void processChildEvent(WatchedEvent event) throws Exception {
        HashMap<String, JSONObject> cacheCopy = new HashMap<String, JSONObject>(m_publicCache.get());
        ByteArrayCallback cb = new ByteArrayCallback();
        m_zk.getData(event.getPath(), m_childWatch, cb, null);
        try {
            byte payload[] = cb.get();
            JSONObject jsObj = new JSONObject(new String(payload, "UTF-8"));
            cacheCopy.put(cb.getPath(), jsObj);
        } catch (KeeperException.NoNodeException e) {
            cacheCopy.remove(event.getPath());
        }
        m_publicCache.set(ImmutableMap.copyOf(cacheCopy));
        if (m_cb != null) {
            m_cb.run(m_publicCache.get());
        }
    }
41681
@Override
  public void process(WatchedEvent event) {
    if (LOG.isDebugEnabled()) {
      LOG.info("Received ZooKeeper Event, " + "type=" + event.getType() + ", " + "state="
          + event.getState() + ", " + "path=" + event.getPath());
    }

    switch (event.getType()) {
    case None: {
      switch (event.getState()) {
      case SyncConnected: {
        try {
          waitToInitZooKeeper(2000); // init zookeeper in another thread, wait for a while
        } catch (Exception e) {
          LOG.error("Error to init ZooKeeper object after sleeping 2000 ms, reconnect ZooKeeper");
          try {
            reconnectZooKeeper();
          } catch (Exception e1) {
            LOG.error("Error to reconnect with ZooKeeper", e1);
          }
        } 
        break;
      }
      default:
        break;
      }
      break;
    }
    default:
      break;
    }
  }
474209
void process_record(InputRecord r, boolean expectingFinished)
            throws IOException {

        checkThrown();

        /*
         * Store the incoming handshake data, then see if we can
         * now process any completed handshake messages
         */
        input.incomingRecord(r);

        /*
         * We don't need to create a separate delegatable task
         * for finished messages.
         */
        if ((conn != null) || expectingFinished) {
            processLoop();
        } else {
            delegateTask(new PrivilegedExceptionAction<Void>() {
                public Void run() throws Exception {
                    processLoop();
                    return null;
                }
            });
        }
    }
593192
@Override
    public <P> void pojoDaoCreated(PojoDaoFactoryEvent<P> event) {
        String tableName = event.getTableName();
        Schema schema = new Schema();
        event.getPojoBinding().describe(schema.createTable(tableName), schema);

        schema.items().forEach(schemaItem -> {
            final String key = schemaItem.getKey();
            final String claimId = UUID.randomUUID().toString();
            session.execute(insertStatement.bind(key, claimId));
            Row row = session.execute(selectStatement.bind(key)).one();
            if (StringUtils.equals(claimId, row.getString(0))) {
                final SchemaStatement statement = schemaItem.createStatement();
                LOGGER.info("Creating table(s) to support \"{}\":\n\t{}\n", event.getPojoBinding().getPojoType().getSimpleName(), statement);
                session.execute(statement);
            }
        });
    }
804670
private void processNodeStateEvent(NodeStateEvent event) {
    switch (stateRef.get()) {
      case BEFORE_INIT:
      case DURING_INIT:
        throw new AssertionError("Filter should not be marked ready until LBP init");
      case CLOSING:
        return; // ignore
      case RUNNING:
        for (LoadBalancingPolicy policy : policies) {
          if (event.newState == NodeState.UP) {
            policy.onUp(event.node);
          } else if (event.newState == NodeState.DOWN || event.newState == NodeState.FORCED_DOWN) {
            policy.onDown(event.node);
          } else if (event.newState == NodeState.UNKNOWN) {
            policy.onAdd(event.node);
          } else if (event.newState == null) {
            policy.onRemove(event.node);
          } else {
            LOG.warn("[{}] Unsupported event: {}", logPrefix, event);
          }
        }
        break;
    }
  }