If the peer group has not been set for MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET seconds, then
the programmer probably forgot to set it and we should throw exception.
340213
private TransactionBroadcaster getAnnouncePeerGroup() {
        try {
            return announcePeerGroupFuture.get(MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            String err = "Transaction broadcaster not set";
            log.error(err);
            throw new RuntimeException(err, e);
        }
    }
1185474
@Override
    public void onError(ChannelHandlerContext ctx, boolean outbound, Throwable cause) {
        Http2Exception embedded = getEmbeddedHttp2Exception(cause);
        if (isStreamError(embedded)) {
            onStreamError(ctx, outbound, cause, (StreamException) embedded);
        } else if (embedded instanceof CompositeStreamException) {
            CompositeStreamException compositException = (CompositeStreamException) embedded;
            for (StreamException streamException : compositException) {
                onStreamError(ctx, outbound, cause, streamException);
            }
        } else {
            onConnectionError(ctx, outbound, cause, embedded);
        }
        ctx.flush();
    }
690418
def exception(self, url, exception):
        ''''''
        return (time.time() + self.ttl, self.factory(url))
433702
void waitProposedEpochFromQuorum()
      throws InterruptedException, TimeoutException, IOException {
    ClusterConfiguration currentConfig = persistence.getLastSeenConfig();
    long acknowledgedEpoch = persistence.getAckEpoch();
    // Waits PROPOED_EPOCH from a quorum of peers in current configuraion.
    while (this.quorumMap.size() < getQuorumSize() - 1) {
      MessageTuple tuple = filter.getExpectedMessage(MessageType.PROPOSED_EPOCH,
                                                     null,
                                                     config.getTimeoutMs());
      Message msg = tuple.getMessage();
      String source = tuple.getServerId();
      ZabMessage.ProposedEpoch epoch = msg.getProposedEpoch();
      ClusterConfiguration peerConfig =
        ClusterConfiguration.fromProto(epoch.getConfig(), source);
      long peerProposedEpoch = epoch.getProposedEpoch();
      long peerAckedEpoch = epoch.getCurrentEpoch();
      int syncTimeoutMs = epoch.getSyncTimeout();
      Zxid peerVersion = peerConfig.getVersion();
      Zxid selfVersion = currentConfig.getVersion();
      // If the peer's config version doesn't match leader's config version,
      // we'll check if the peer has the more likely "correct" configuration.
      if (!peerVersion.equals(selfVersion)) {
        LOG.debug("{}'s config version {} is different with leader's {}",
                  peerVersion, selfVersion);
        if (peerAckedEpoch > acknowledgedEpoch ||
            (peerAckedEpoch == acknowledgedEpoch &&
             peerVersion.compareTo(selfVersion) > 0)) {
          LOG.debug("{} probably has right configuration, go back to "
              + "leader election.",
              source);
          // TODO : current we just go back to leader election, probably we want
          // to select the peer as leader.
          throw new BackToElectionException();
        }
      }
      // Rejects peer who is not in the current configuration.
      if (!currentConfig.contains(source)) {
        LOG.debug("Current configuration doesn't contain {}, ignores it.",
                  source);
        continue;
      }
      if (this.quorumMap.containsKey(source)) {
        throw new RuntimeException("Quorum set has already contained "
            + source + ", probably a bug?");
      }
      LOG.debug("Got PROPOSED_EPOCH from {}", source);
      PeerHandler ph = new PeerHandler(source, transport,
                                       config.getTimeoutMs()/3);
      ph.setLastProposedEpoch(peerProposedEpoch);
      ph.setSyncTimeoutMs(syncTimeoutMs);
      this.quorumMap.put(source, ph);
    }
    LOG.debug("Got proposed epoch from a quorum.");
  }
547233
private void checkFailFast()
   {
      final long initializationTimeout = config.getInitializationFailTimeout();
      if (initializationTimeout < 0) {
         return;
      }

      final long startTime = currentTime();
      do {
         final PoolEntry poolEntry = createPoolEntry();
         if (poolEntry != null) {
            if (config.getMinimumIdle() > 0) {
               connectionBag.add(poolEntry);
               logger.debug("{} - Added connection {}", poolName, poolEntry.connection);
            }
            else {
               quietlyCloseConnection(poolEntry.close(), "(initialization check complete and minimumIdle is zero)");
            }

            return;
         }

         if (getLastConnectionFailure() instanceof ConnectionSetupException) {
            throwPoolInitializationException(getLastConnectionFailure().getCause());
         }

         quietlySleep(SECONDS.toMillis(1));
      } while (elapsedMillis(startTime) < initializationTimeout);

      if (initializationTimeout > 0) {
         throwPoolInitializationException(getLastConnectionFailure());
      }
   }
1260070
private void processParentEvent(WatchedEvent event) 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<String, JSONObject> cache = new HashMap<String, JSONObject>();
        for (ByteArrayCallback callback : callbacks) {
            try {
                byte payload[] = callback.get();
                JSONObject jsObj = new JSONObject(new String(payload, "UTF-8"));
                cache.put(callback.getPath(), jsObj);
            } catch (KeeperException.NoNodeException e) {
                // child may have been deleted between the parent trigger and getData.
            }
        }

        m_publicCache.set(ImmutableMap.copyOf(cache));
        if (m_cb != null) {
            m_cb.run(m_publicCache.get());
        }
    }
549919
public boolean socketError(Throwable throwable) {
    if (throwable instanceof SocketException || throwable instanceof SocketTimeoutException) {
      return true;
    }
    Throwable cause = throwable.getCause();
    // Subset of SSL exceptions that are caused by IO errors (e.g. SSLHandshakeException due to
    // unexpected connection closure) is also a socket error.
    if (throwable instanceof SSLException && cause != null && ioError(cause)) {
      return true;
    }
    return cause != null && socketError(cause);
  }
254269
def set_exception(self, exception, traceback=None):
        
        if not isinstance(exception, BaseException):
            raise RuntimeError("Exception must be of BaseException type")
        self._exception = exception
        self._traceback = traceback
        self._event.set()
        self._invoke_callbacks()
1256260
@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (getEmbeddedHttp2Exception(cause) != null) {
            // Some exception in the causality chain is an Http2Exception - handle it.
            onError(ctx, false, cause);
        } else {
            super.exceptionCaught(ctx, cause);
        }
    }
654424
@Override
  public void join(String peer) throws Exception {
    LOG.debug("Follower joins in.");
    try {
      LOG.debug("Query leader from {}", peer);
      Message query = MessageBuilder.buildQueryLeader();
      MessageTuple tuple = null;
      while (true) {
        // The joiner might gets started before the cluster gets started.
        // Instead of reporting failure immediately, the follower will retry
        // joining the cluster until joining the cluster successfully.
        try {
          sendMessage(peer, query);
          tuple = filter.getExpectedMessage(MessageType.QUERY_LEADER_REPLY,
                                            peer, config.getTimeoutMs());
          break;
        } catch (TimeoutException ex) {
          long retryInterval = 1;
          LOG.warn("Timeout while contacting leader, going to retry after {} "
              + "second.", retryInterval);
          // Waits for 1 second.
          Thread.sleep(retryInterval * 1000);
        }
      }
      this.electedLeader = tuple.getMessage().getReply().getLeader();
      LOG.debug("Got current leader {}", this.electedLeader);

      /* -- Synchronizing phase -- */
      while (true) {
        try {
          joinSynchronization();
          break;
        } catch (TimeoutException | BackToElectionException ex) {
          LOG.debug("Timeout({} ms) in synchronizing, retrying. Last zxid : {}",
                    getSyncTimeoutMs(),
                    persistence.getLatestZxid());
          transport.clear(electedLeader);
          clearMessageQueue();
        }
      }
      // See if it can be restored from the snapshot file.
      restoreFromSnapshot();
      // Delivers all transactions in log before entering broadcasting phase.
      deliverUndeliveredTxns();

      /* -- Broadcasting phase -- */
      // Initialize the vote for leader election.
      this.election.specifyLeader(this.electedLeader);
      changePhase(Phase.BROADCASTING);
      accepting();
    } catch (InterruptedException e) {
      LOG.debug("Participant is canceled by user.");
      throw e;
    } catch (TimeoutException e) {
      LOG.debug("Didn't hear message from {} for {} milliseconds. Going"
                + " back to leader election.",
                this.electedLeader,
                this.config.getTimeoutMs());
      if (persistence.getLastSeenConfig() == null) {
        throw new JoinFailure("Fails to join cluster.");
      }
    } catch (BackToElectionException e) {
      LOG.debug("Got GO_BACK message from queue, going back to electing.");
      if (persistence.getLastSeenConfig() == null) {
        throw new JoinFailure("Fails to join cluster.");
      }
    } catch (LeftCluster e) {
      LOG.debug("Exit running : {}", e.getMessage());
      throw e;
    } catch (Exception e) {
      LOG.error("Caught exception", e);
      throw e;
    } finally {
      changePhase(Phase.FINALIZING);
    }
  }
1068174
@Override
    protected void postInit() throws Exception {
        if (controlTree == null) {
            throw new RuntimeException("controlTree not set");
        }

        controlTree.create(NODES, false);
        controlTree.create(LEADERS, false);

        if (controlTree.exists(myNodeInfo.treeNodePath)) {
            LOG.error("A node with the name " + myNodeInfo.getName() + " already exists!");
            throw new RuntimeException("Initialization failure");
        }

        LOG.info("Required peer node properties: {}", requiredPeerNodeProperties);
        LOG.info("Required server properties: {}", requiredServerProperties);

        final Set<String> requiredProperties = (myId == 0 ? requiredServerProperties : requiredPeerNodeProperties);
        for (String property : requiredProperties) {
            if (!property.equals("id") && myNodeInfo.get(property) == null) {
                LOG.error("Required property {} not set!", property);
                throw new RuntimeException("Initialization failure");
            }
        }

        /// the calls in the demarcated section need to be in this specific order to avoid a possible race between nodes and leaders
        // `>>>> BEGIN CAREFULLY ORDERED SECTION
        branch = new DistributedBranchHelper(controlTree, NODES, false) {
            @Override
            protected boolean isNodeComplete(String node, Set<String> properties) {
                if (!properties.contains("id")) {
                    return false;
                }
                final short id = Short.parseShort(new String(controlTree.get(node + "/id"), Charsets.UTF_8));
                final Set<String> requiredProperties = (id == 0 ? requiredServerProperties : requiredPeerNodeProperties);
                final boolean success = properties.containsAll(requiredProperties);
                return success;
            }
        };

        branch.addListener(new DistributedTree.ListenerAdapter() {
            @Override
            public void nodeChildAdded(String parentPath, String childName) {
                AbstractCluster.this.nodeAdded(childName);
            }

            @Override
            public void nodeChildDeleted(String parentPath, String childName) {
                AbstractCluster.this.nodeRemoved(childName);
            }
        });
        // This read and handles the nodes.
        branch.init();

        controlTree.addListener(LEADERS, new DistributedTree.ListenerAdapter() {
            @Override
            public void nodeChildAdded(String parentPath, String childName) {
                AbstractCluster.this.leaderAdded(childName);
            }

            @Override
            public void nodeChildDeleted(String parentPath, String childName) {
                AbstractCluster.this.leaderRemoved(childName);
            }
        });

        myNodeInfo.writeToTree();

        setReady(true);

        super.postInit();

        joined = true;
        fireJoinedCluster();
        for (short id : masters.keySet()) {
            if (id != myId)
                fireNodeAdded(id);
        }
    }
533184
void setChannel(Channel channel) throws InvalidArgumentException {

        if (null != this.channel) {
            throw new InvalidArgumentException(format("Can not add peer %s to channel %s because it already belongs to channel %s.",
                    name, channel.getName(), this.channel.getName()));
        }
        logger.debug(format("%s setting channel to %s, from %s", toString(), "" + channel, "" + this.channel));

        this.channel = channel;
        this.channelName = channel.getName();

    }
427605
public synchronized void inactivityTimeout() {
        final boolean traceOn = TraceComponent.isAnyTracingEnabled();

        if (traceOn && tc.isEntryEnabled())
            Tr.entry(tc, "inactivityTimeout", this);

        _inactivityTimerActive = false;

        if (_inactivityTimer != null) {
            try {
                // important that this runs as part of synchronized block
                // to prevent context being re-imported while processing.
                _inactivityTimer.alarm();
            } catch (Throwable exc) {
                FFDCFilter.processException(exc, "com.ibm.ws.tx.jta.TransactionImpl.inactivityTimeout", "2796", this);
                if (traceOn && tc.isEventEnabled())
                    Tr.event(tc, "exception caught in inactivityTimeout", exc);
                // swallow
            } finally {
                _inactivityTimer = null;
            }

        } else {
            if (_activeAssociations <= 0) // off server ... do the rollback
            {
                final EmbeddableTranManagerSet tranManager = (EmbeddableTranManagerSet) TransactionManagerFactory.getTransactionManager();

                try {
                    // resume this onto the current thread and roll it back
                    tranManager.resume(this);
                    // PK15024
                    // If there is a superior server involved in this transaction, make sure it is told about this inactivity timeout.
                    try {
                        tranManager.setRollbackOnly();
                    } catch (Exception e) {
                        FFDCFilter.processException(e, "com.ibm.ws.Transaction.JTA.TransactionImpl.inactivityTimeout", "4353", this);
                        if (traceOn && tc.isDebugEnabled())
                            Tr.debug(tc, "inactivityTimeout setRollbackOnly threw exception", e);
                    }
                    // Mark it so that a bean on the superior server can test its status on return.
                    // PK15024
                    tranManager.rollback();
                } catch (Exception ex) {
                    if (traceOn && tc.isDebugEnabled())
                        Tr.debug(tc, "inactivityTimeout resume/rollback threw exception", ex);
                    // swallow this exception
                    // main timeout may have already rolled back!
                }
            }
        }

        if (traceOn && tc.isEntryEnabled())
            Tr.exit(tc, "inactivityTimeout");
    }
548606
private void waitForChannelResubscription(final Map<Integer, ChannelCallbackHandler> oldChannelIdSymbolMap)
			throws BitfinexClientException, InterruptedException {
		
		final Stopwatch stopwatch = Stopwatch.createStarted();
		final long MAX_WAIT_TIME_IN_MS = TimeUnit.MINUTES.toMillis(3);
		logger.info("Waiting for streams to resubscribe (max wait time {} msec)", MAX_WAIT_TIME_IN_MS);

		synchronized (channelIdToHandlerMap) {
			
			while(channelIdToHandlerMap.size() != oldChannelIdSymbolMap.size()) {
				
				if(stopwatch.elapsed(TimeUnit.MILLISECONDS) > MAX_WAIT_TIME_IN_MS) {
					// Raise BitfinexClientException
					handleResubscribeFailed(oldChannelIdSymbolMap);
				}
				
				channelIdToHandlerMap.wait(500);
			}
			
		}
	}
941113
public static boolean shouldNotIgnoreException(Throwable cause) {
        String message = String.valueOf(cause.getMessage()).toLowerCase();

        // is ssl exception
        if (cause.getCause() instanceof SSLException || cause instanceof DecoderException | cause instanceof NotSslRecordException) {
            return false;
        }

        // first try to match connection reset / broke peer based on the regex.
        // This is the fastest way but may fail on different jdk impls or OS's
        if (IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) {
            return false;
        }

        // Inspect the StackTraceElements to see if it was a connection reset / broken pipe or not
        StackTraceElement[] elements = cause.getStackTrace();
        for (StackTraceElement element : elements) {
            String classname = element.getClassName();
            String methodname = element.getMethodName();

            // skip all classes that belong to the io.netty package
            if (classname.startsWith("io.netty.")) {
                continue;
            }

            // check if the method name is read if not skip it
            if (!"read".equals(methodname)) {
                continue;
            }

            // This will also match against SocketInputStream which is used by openjdk 7 and maybe
            // also others
            if (IGNORABLE_CLASS_IN_STACK.matcher(classname).matches()) {
                return false;
            }

            try {
                // No match by now.. Try to load the class via classloader and inspect it.
                // This is mainly done as other JDK implementations may differ in name of
                // the impl.
                Class<?> clazz = PlatformDependent.getClassLoader(ExceptionHandler.class).loadClass(classname);

                if (SocketChannel.class.isAssignableFrom(clazz)
                    || DatagramChannel.class.isAssignableFrom(clazz)) {
                    return false;
                }

                // also match against SctpChannel via String matching as it may not present.
                if (PlatformDependent.javaVersion() >= 7
                    && "com.sun.nio.sctp.SctpChannel".equals(clazz.getSuperclass().getName())) {
                    return false;
                }
            } catch (ClassNotFoundException e) {
                // This should not happen just ignore
            }
        }
        return true;
    }
999182
private TransactionBroadcaster getBroadcaster() {
        try {
            return broadcasterFuture.get(MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            String err = "Transaction broadcaster not set";
            log.error(err);
            throw new RuntimeException(err,e);
        }
    }
125432
@Override
	public void on(String name, Tree payload, Groups groups, boolean broadcast) throws Exception {
		FastBuildTree msg = new FastBuildTree(6);
		msg.putUnsafe("ver", ServiceBroker.PROTOCOL_VERSION);
		msg.putUnsafe("sender", currentNodeID);
		msg.putUnsafe("event", name);
		msg.putUnsafe("broadcast", broadcast);
		if (groups != null) {
			String[] array = groups.groups();
			if (array != null && array.length > 0) {
				msg.putUnsafe("groups", array);
			}
		}
		if (payload != null) {
			msg.putUnsafe("data", payload);
		}
		transporter.publish(PACKET_EVENT, nodeID, msg);
	}