Java 类io.netty.util.Timeout 实例源码

项目:JRediClients    文件:ScheduledTasksService.java   
@Override
protected void awaitResultAsync(final RemoteInvocationOptions optionsCopy, final RemotePromise<Object> result,
        final RemoteServiceRequest request, final String responseName) {
    if (!optionsCopy.isResultExpected()) {
        return;
    }

    Long startTime = 0L;
    if (request != null && request.getArgs() != null && request.getArgs().length > 3) {
        startTime = (Long)request.getArgs()[3];
    }
    long delay = startTime - System.currentTimeMillis();
    if (delay > 0) {
        commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                ScheduledTasksService.super.awaitResultAsync(optionsCopy, result, request, responseName);
            }
        }, delay, TimeUnit.MILLISECONDS);
    } else {
        super.awaitResultAsync(optionsCopy, result, request, responseName);
    }
}
项目:yajsw    文件:ReconnectHandler.java   
private synchronized void scheduleReconnect()
{
    if (_stop)
        return;
    if (_timeout != null)
        return;
    Constants.ahessianLogger.warn("channel closed wait to reconnect ...");
    _retryCounter++;
    long retryIntervall = Math.min(RECONNECT_DELAY * _retryCounter,
            MAX_RECONNECT_DELAY);
    _timeout = _timer.newTimeout(new TimerTask()
    {
        public void run(Timeout timeout) throws Exception
        {
            _timeout = null;
            connect(_bootstrap.getBootstrap());

        }
    }, retryIntervall, TimeUnit.MILLISECONDS);
}
项目:yajsw    文件:HeartbeatHandlerInbound.java   
public HeartbeatHandlerInbound(final String name, final Timer timer,
        final long timeout)
{
    _name = name;
    final TimerTask task = new TimerTask()
    {
        public void run(Timeout nTimeout) throws Exception
        {
            if (((getLastCalled() + timeout) <= System.currentTimeMillis())
                    && isConnected())
                try
                {
                    _action.timedOut(_ctx);
                }
                catch (Exception e)
                {
                    Constants.ahessianLogger.warn("", e);
                }
        }

    };
    _intervalTimer = new IntervalTimer(timer, task, timeout);
}
项目:yajsw    文件:TimedBlockingPriorityQueue.java   
public T poll(int group)
{
    LinkedList<T> q = _queues[group];
    T result = null;
    if (q != null)
    {
        result = q.poll();
        if (result != null)
        {
            Timeout timer = _timers.remove(result);
            if (timer != null)
                timer.cancel();
        }
    }
    return result;
}
项目:mpush    文件:ServerConnectionManager.java   
@Override
public void run(Timeout timeout) throws Exception {
    Connection connection = this.connection;

    if (connection == null || !connection.isConnected()) {
        Logs.HB.info("heartbeat timeout times={}, connection disconnected, conn={}", timeoutTimes, connection);
        return;
    }

    if (connection.isReadTimeout()) {
        if (++timeoutTimes > CC.mp.core.max_hb_timeout_times) {
            connection.close();
            Logs.HB.warn("client heartbeat timeout times={}, do close conn={}", timeoutTimes, connection);
            return;
        } else {
            Logs.HB.info("client heartbeat timeout times={}, connection={}", timeoutTimes, connection);
        }
    } else {
        timeoutTimes = 0;
    }
    startTimeout();
}
项目:incubator-pulsar    文件:ProducerImpl.java   
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }
    if (log.isDebugEnabled()) {
        log.debug("[{}] [{}] Batching the messages from the batch container from timer thread", topic,
                producerName);
    }
    // semaphore acquired when message was enqueued to container
    synchronized (ProducerImpl.this) {
        batchMessageAndSend();
    }
    // schedule the next batch message task
    client.timer().newTimeout(this, conf.getBatchingMaxPublishDelayMs(), TimeUnit.MILLISECONDS);
}
项目:incubator-pulsar    文件:UnAckedMessageTracker.java   
public void start(PulsarClientImpl client, ConsumerBase consumerBase, long ackTimeoutMillis) {
    this.stop();
    timeout = client.timer().newTimeout(new TimerTask() {
        @Override
        public void run(Timeout t) throws Exception {
            if (isAckTimeout()) {
                log.warn("[{}] {} messages have timed-out", consumerBase, oldOpenSet.size());
                Set<MessageIdImpl> messageIds = new HashSet<>();
                oldOpenSet.forEach(messageIds::add);
                oldOpenSet.clear();
                consumerBase.redeliverUnacknowledgedMessages(messageIds);
            }
            toggle();
            timeout = client.timer().newTimeout(this, ackTimeoutMillis, TimeUnit.MILLISECONDS);
        }
    }, ackTimeoutMillis, TimeUnit.MILLISECONDS);
}
项目:HeliosStreams    文件:TimeoutService.java   
/**
 * {@inheritDoc}
 * @see io.netty.util.Timer#newTimeout(io.netty.util.TimerTask, long, java.util.concurrent.TimeUnit)
 */
@Override
public Timeout newTimeout(final TimerTask task, final long delay, final TimeUnit unit) {
    final WrappedTimeout[] t = new WrappedTimeout[1];
    t[0] = new WrappedTimeout(timer.newTimeout(new TimerTask(){
        @Override
        public void run(final Timeout timeout) throws Exception {
            try {
                task.run(t[0]);
            } finally {
                pendingTimeouts.decrementAndGet();
                timeouts.increment();
            }               
        }           
    }, delay, unit));
    return t[0];
}
项目:milo    文件:UaTcpStackClient.java   
private void scheduleRequestTimeout(RequestHeader requestHeader) {
    UInteger requestHandle = requestHeader.getRequestHandle();

    long timeoutHint = requestHeader.getTimeoutHint() != null ?
        requestHeader.getTimeoutHint().longValue() : DEFAULT_TIMEOUT_MS;

    Timeout timeout = wheelTimer.newTimeout(t -> {
        if (timeouts.remove(requestHandle) != null && !t.isCancelled()) {
            CompletableFuture<UaResponseMessage> f = pending.remove(requestHandle);
            if (f != null) {
                String message = "request timed out after " + timeoutHint + "ms";
                f.completeExceptionally(new UaException(StatusCodes.Bad_Timeout, message));
            }
        }
    }, timeoutHint, TimeUnit.MILLISECONDS);

    timeouts.put(requestHandle, timeout);
}
项目:async-gamequery-lib    文件:ReadRequestTimeoutTimerTask.java   
@Override
public void run(Timeout timeout) throws Exception {
    log.debug("Timeout occured for Session {}", id);
    //Notify the listener that timeout has occured
    final SessionValue session = sessionManager.getSession(id);

    //Do not proceed if the session is null
    if (session == null) {
        log.error("could not find session value for id {}. Registry Size : {}", id, sessionManager.getSessionEntries().size());
        return;
    }

    //Check first if the promise has been completed
    if (session.getClientPromise() != null && !session.getClientPromise().isDone() && !session.getClientPromise().isCancelled() && !timeout.isCancelled()) {
        //Send a ReadTimeoutException to the client
        session.getClientPromise().completeExceptionally(new ReadTimeoutException(id, String.format("Timeout occured for '%s' Started: %f seconds ago", id, ((double) Duration.ofMillis(System.currentTimeMillis() - session.getTimeRegistered()).toMillis() / 1000.0))));
    }
}
项目:jannel    文件:TimedDeferredRequest.java   
/**
 * Intentional private local constructor
 * @param key the request key
 * @param request the request object
 * @param window the window
 * @param timeoutMillis the time after which this future will be cancelled
 * @param timer the timer used to implement the timeout functionality
 */
private TimedDeferredRequest(final K key,
                             final R request,
                             final Window<K, R, D> window,
                             final Timer timer,
                             final long timeoutMillis) {
    super(key, request, window);
    this.timeout = checkNotNull(timer).newTimeout(new TimerTask() {
                                                      @Override
                                                      public void run(Timeout timerTask) throws Exception {
                                                          window.fail(checkNotNull(key),
                                                                      new TimeoutException("The operation timed out (Window full)"));
                                                      }
                                                  },
                                                  timeoutMillis,
                                                  TimeUnit.MILLISECONDS);
}
项目:redisson    文件:RedissonLock.java   
private void newRefreshTask() {
    if (refreshTaskMap.containsKey(getName())) {
        return;
    }

    Timeout task = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            expire(internalLockLeaseTime, TimeUnit.MILLISECONDS);
            refreshTaskMap.remove(getName());
            newRefreshTask(); // reschedule itself
        }
    }, internalLockLeaseTime / 3, TimeUnit.MILLISECONDS);

    if (refreshTaskMap.putIfAbsent(getName(), task) != null) {
        task.cancel();
    }
}
项目:ethernet-ip    文件:CipClient.java   
@Override
public void itemsReceived(CpfItem[] items) {
    int connectionId = ((ConnectedAddressItem) items[0]).getConnectionId();
    ByteBuf buffer = ((ConnectedDataItemResponse) items[1]).getData();

    int sequenceNumber = buffer.readShort();
    ByteBuf data = buffer.readSlice(buffer.readableBytes()).retain();

    Timeout timeout = timeouts.remove(sequenceNumber);
    if (timeout != null) timeout.cancel();

    CompletableFuture<ByteBuf> future = pending.remove(sequenceNumber);

    if (future != null) {
        future.complete(data);
    } else {
        ReferenceCountUtil.release(data);
    }

    ReferenceCountUtil.release(buffer);
}
项目:ethernet-ip    文件:EtherNetIpClient.java   
@SuppressWarnings("unchecked")
private PendingRequest(CompletableFuture<T> future, Timeout timeout) {
    this.timeout = timeout;

    promise.whenComplete((r, ex) -> {
        if (r != null) {
            try {
                future.complete((T) r);
            } catch (ClassCastException e) {
                future.completeExceptionally(e);
            }
        } else {
            future.completeExceptionally(ex);
        }
    });
}
项目:imflux    文件:AbstractRtpSession.java   
/**
     * {@inheritDoc}
     * <br/>
     * Sends for each remote participant a report containing the status
     * of this session participant. 
     */
    @Override
    public void run(Timeout timeout) throws Exception {
        if (!this.running.get()) {
            return;
        }
        // send status update per remote participant
        final long currentSsrc = this.localParticipant.getSsrc();
        final SourceDescriptionPacket sdesPacket = buildSdesPacket(currentSsrc);
        this.participantDatabase.doWithReceivers(new ParticipantOperation() {
            @Override
            public void doWithParticipant(RtpParticipant participant) throws Exception {
                AbstractReportPacket report = buildReportPacket(currentSsrc, participant);
                // TODO: really to all other participants?
                // i would use:
//                writeToControl(new CompoundControlPacket(report, sdesPacket), participant.getControlDestination());
                internalSendControl(new CompoundControlPacket(report, sdesPacket));
            }
        });

        if (!this.running.get()) {
            return;
        }
        this.timer.newTimeout(this, this.updatePeriodicRtcpSendInterval(), TimeUnit.SECONDS);
    }
项目:modbus    文件:ModbusTcpMaster.java   
@SuppressWarnings("unchecked")
private PendingRequest(CompletableFuture<T> future, Timeout timeout, Timer.Context context) {
    this.timeout = timeout;
    this.context = context;

    promise.whenComplete((r, ex) -> {
        if (r != null) {
            try {
                future.complete((T) r);
            } catch (ClassCastException e) {
                future.completeExceptionally(e);
            }
        } else {
            future.completeExceptionally(ex);
        }
    });
}
项目:bgpcep    文件:PCCTunnelManagerImpl.java   
private void startRedelegationTimer(final PCCTunnel tunnel, final PlspId plspId, final PCCSession session) {
    final Timeout newRedelegationTimeout = this.timer.newTimeout(timeout -> {
        //remove delegation
        PCCTunnelManagerImpl.this.setDelegation(plspId, null);
        //delegate to another PCE
        int index = session.getId();
        for (int i = 1; i < PCCTunnelManagerImpl.this.sessions.size(); i++) {
            index++;
            if (index == PCCTunnelManagerImpl.this.sessions.size()) {
                index = 0;
            }
            final PCCSession nextSession = PCCTunnelManagerImpl.this.sessions.get(index);
            if (nextSession != null) {
                tunnel.cancelTimeouts();
                final Tlvs tlvs = buildTlvs(tunnel, plspId.getValue(), Optional.absent());

                nextSession.sendReport(createPcRtpMessage(
                    createLsp(plspId.getValue(), true, Optional.fromNullable(tlvs), true, false), NO_SRP,
                    tunnel.getLspState()));
                tunnel.setDelegationHolder(nextSession.getId());
                break;
            }
        }
    }, this.redelegationTimeout, TimeUnit.SECONDS);
    tunnel.setRedelegationTimeout(newRedelegationTimeout);
}
项目:flazr-fork    文件:RtmpPublisher.java   
public void fireNext(final ChannelHandlerContext ctx, final long delay) {
    final Event readyForNext = new Event(currentConversationId);
    if(delay > timerTickSize) {
        timer.newTimeout(new TimerTask() {
            @Override public void run(Timeout timeout) {
                if(logger.isDebugEnabled()) {
                    logger.debug("running after delay: {}", delay);
                }
                if(readyForNext.conversationId != currentConversationId) {
                    logger.debug("pending 'next' event found obsolete, aborting");
                    return;
                }
                ctx.pipeline().fireChannelRead(readyForNext);
            }
        }, delay, TimeUnit.MILLISECONDS);
    } else {
        ctx.pipeline().fireChannelRead(readyForNext);
    }
}
项目:onos    文件:MeterStatsCollector.java   
@Override
public void run(Timeout timeout) throws Exception {
    if (!sw.isConnected()) {
        log.debug("Switch {} disconnected. Aborting meter stats collection", sw.getStringId());
        return;
    }

    log.trace("Collecting stats for {}", sw.getStringId());

    sendMeterStatisticRequest();

    if (!this.stopTimer) {
        log.trace("Scheduling stats collection in {} seconds for {}",
                this.refreshInterval, this.sw.getStringId());
        timeout.timer().newTimeout(this, refreshInterval,
                TimeUnit.SECONDS);
    }
}
项目:onos    文件:LinkDiscovery.java   
/**
 * Execute this method every t milliseconds. Loops over all ports
 * labeled as fast and sends out an LLDP. Send out an LLDP on a single slow
 * port.
 *
 * @param t timeout
 */
@Override
public void run(Timeout t) {
    if (isStopped()) {
        return;
    }

    if (context.mastershipService().isLocalMaster(device.id())) {
        log.trace("Sending probes from {}", device.id());
        ports.forEach(this::sendProbes);
    }

    if (!isStopped()) {
        timeout = t.timer().newTimeout(this, context.probeRate(), MILLISECONDS);
    }
}
项目:opc-ua-stack    文件:UaTcpStackClient.java   
private void scheduleRequestTimeout(RequestHeader requestHeader) {
    UInteger requestHandle = requestHeader.getRequestHandle();

    long timeoutHint = requestHeader.getTimeoutHint() != null ?
            requestHeader.getTimeoutHint().longValue() : DEFAULT_TIMEOUT_MS;

    Timeout timeout = wheelTimer.newTimeout(t -> {
        timeouts.remove(requestHandle);
        if (!t.isCancelled()) {
            CompletableFuture<UaResponseMessage> f = pending.remove(requestHandle);
            if (f != null) {
                String message = "request timed out after " + timeoutHint + "ms";
                f.completeExceptionally(new UaException(StatusCodes.Bad_Timeout, message));
            }
        }
    }, timeoutHint, TimeUnit.MILLISECONDS);

    timeouts.put(requestHandle, timeout);
}
项目:JRediClients    文件:MasterSlaveConnectionManager.java   
@Override
public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) {
    try {
        return timer.newTimeout(task, delay, unit);
    } catch (IllegalStateException e) {
        // timer is shutdown
        return dummyTimeout;
    }
}
项目:NioSmtpClient    文件:ResponseHandler.java   
private void applyResponseTimeout(CompletableFuture<List<SmtpResponse>> responseFuture, Optional<Duration> responseTimeout, Supplier<String> debugStringSupplier) {
  responseTimeout = responseTimeout.isPresent() ? responseTimeout : defaultResponseTimeout;

  responseTimeout.ifPresent(timeout -> {
    Timeout hwtTimeout = TIMER.newTimeout(ignored -> {
      String message = String.format("[%s] Timed out waiting for a response to [%s]",
          connectionId, debugStringSupplier.get());

      responseFuture.completeExceptionally(new TimeoutException(message));
    }, timeout.toMillis(), TimeUnit.MILLISECONDS);

    responseFuture.whenComplete((ignored1, ignored2) -> hwtTimeout.cancel());
  });
}
项目:fresco_floodlight    文件:HandshakeTimeoutHandler.java   
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }

    if (!ctx.channel().isOpen()) {
        return;
    }
    if (!handler.isClientConnection && 
        ((handler.remoteNode == null ||
         !handler.rpcService.isConnected(handler.remoteNode.
                                         getNodeId()))))
        ctx.fireExceptionCaught(EXCEPTION);
}
项目:fresco_floodlight    文件:BootstrapTimeoutHandler.java   
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }

    if (!ctx.channel().isOpen()) {
        return;
    }
    ctx.channel().disconnect();
}
项目:fresco_floodlight    文件:RSHandshakeTimeoutHandler.java   
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }

    if (!ctx.channel().isOpen()) {
        return;
    }
    if (channelHandler.syncManager.ready == false)
        ctx.channel().disconnect();
}
项目:fresco_floodlight    文件:OFSwitchAppHandshakePlugin.java   
@Override
public void run(Timeout timeout) throws Exception {
    if (!timeout.isCancelled()) {
        log.warn("App handshake plugin for {} timed out. Returning result {}.",
                 sw, defaultResult);
        exitPlugin(defaultResult);
    }
}
项目:fresco_floodlight    文件:OFConnection.java   
@Override
public void run(Timeout timeout) throws Exception {
    Deliverable<?> removed = xidDeliverableMap.remove(xid);
    if (removed != null && !removed.isDone()) {
        removed.deliverError(new TimeoutException(
                "timeout - did not receive answer for xid " + xid));
    }

}
项目:fresco_floodlight    文件:HandshakeTimeoutHandler.java   
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }

    if (!ctx.channel().isOpen()) {
        return;
    }
    if (!handshakeHandler.isSwitchHandshakeComplete())
        ctx.fireExceptionCaught(EXCEPTION);
}
项目:fresco_floodlight    文件:OFSwitchHandlerTestBase.java   
@Before
public void setUp() throws Exception {
    /*
     * This needs to be called explicitly to ensure the featuresReply is not null.
     * Otherwise, there is no guarantee @Before will for setUpFeaturesReply() will
     * call that function before our @Before setUp() here.
     */
    setUpFeaturesReply(); 
    switchManager = createMock(IOFSwitchManager.class);
    roleManager = createMock(RoleManager.class);
    sw = createMock(IOFSwitchBackend.class);
    timer = createMock(Timer.class);
    expect(timer.newTimeout(anyObject(TimerTask.class), anyLong(), anyObject(TimeUnit.class))).andReturn(EasyMock.createNiceMock(Timeout.class));
    replay(timer);
    seenXids = null;

    // TODO: should mock IDebugCounterService and make sure
    // the expected counters are updated.
    debugCounterService = new DebugCounterServiceImpl();
    SwitchManagerCounters counters =
            new SwitchManagerCounters(debugCounterService);
    expect(switchManager.getCounters()).andReturn(counters).anyTimes();
    replay(switchManager);
    connection = new MockOFConnection(featuresReply.getDatapathId(), OFAuxId.MAIN);
    switchHandler = new OFSwitchHandshakeHandler(connection, featuresReply, switchManager, roleManager, timer);

    // replay sw. Reset it if you need more specific behavior
    replay(sw);
}
项目:ditb    文件:AsyncRpcChannel.java   
/**
 * Get SASL handler
 * @param bootstrap to reconnect to
 * @return new SASL handler
 * @throws java.io.IOException if handler failed to create
 */
private SaslClientHandler getSaslHandler(final UserGroupInformation realTicket,
    final Bootstrap bootstrap) throws IOException {
  return new SaslClientHandler(realTicket, authMethod, token, serverPrincipal,
      client.fallbackAllowed, client.conf.get("hbase.rpc.protection",
        SaslUtil.QualityOfProtection.AUTHENTICATION.name().toLowerCase()),
      new SaslClientHandler.SaslExceptionHandler() {
        @Override
        public void handle(int retryCount, Random random, Throwable cause) {
          try {
            // Handle Sasl failure. Try to potentially get new credentials
            handleSaslConnectionFailure(retryCount, cause, realTicket);

            // Try to reconnect
            client.newTimeout(new TimerTask() {
              @Override
              public void run(Timeout timeout) throws Exception {
                connect(bootstrap);
              }
            }, random.nextInt(reloginMaxBackoff) + 1, TimeUnit.MILLISECONDS);
          } catch (IOException | InterruptedException e) {
            close(e);
          }
        }
      }, new SaslClientHandler.SaslSuccessfulConnectHandler() {
        @Override
        public void onSuccess(Channel channel) {
          startHBaseConnection(channel);
        }
      });
}
项目:ditb    文件:AsyncRpcChannel.java   
/**
 * Retry to connect or close
 *
 * @param bootstrap      to connect with
 * @param connectCounter amount of tries
 * @param e              exception of fail
 */
private void retryOrClose(final Bootstrap bootstrap, int connectCounter, Throwable e) {
  if (connectCounter < client.maxRetries) {
    client.newTimeout(new TimerTask() {
      @Override public void run(Timeout timeout) throws Exception {
        connect(bootstrap);
      }
    }, client.failureSleep, TimeUnit.MILLISECONDS);
  } else {
    client.failedServers.addToFailedServers(address);
    close(e);
  }
}
项目:SDN-Multicast    文件:HandshakeTimeoutHandler.java   
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }

    if (!ctx.channel().isOpen()) {
        return;
    }
    if (!handler.isClientConnection && 
        ((handler.remoteNode == null ||
         !handler.rpcService.isConnected(handler.remoteNode.
                                         getNodeId()))))
        ctx.fireExceptionCaught(EXCEPTION);
}
项目:SDN-Multicast    文件:BootstrapTimeoutHandler.java   
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }

    if (!ctx.channel().isOpen()) {
        return;
    }
    ctx.channel().disconnect();
}
项目:SDN-Multicast    文件:RSHandshakeTimeoutHandler.java   
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }

    if (!ctx.channel().isOpen()) {
        return;
    }
    if (channelHandler.syncManager.ready == false)
        ctx.channel().disconnect();
}
项目:SDN-Multicast    文件:OFSwitchAppHandshakePlugin.java   
@Override
public void run(Timeout timeout) throws Exception {
    if (!timeout.isCancelled()) {
        log.warn("App handshake plugin for {} timed out. Returning result {}.",
                 sw, defaultResult);
        exitPlugin(defaultResult);
    }
}
项目:SDN-Multicast    文件:OFConnection.java   
@Override
public void run(Timeout timeout) throws Exception {
    Deliverable<?> removed = xidDeliverableMap.remove(xid);
    if (removed != null && !removed.isDone()) {
        removed.deliverError(new TimeoutException(
                "timeout - did not receive answer for xid " + xid));
    }

}
项目:SDN-Multicast    文件:HandshakeTimeoutHandler.java   
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }

    if (!ctx.channel().isOpen()) {
        return;
    }
    if (!handshakeHandler.isSwitchHandshakeComplete())
        ctx.fireExceptionCaught(EXCEPTION);
}
项目:SDN-Multicast    文件:OFSwitchHandlerTestBase.java   
@Before
public void setUp() throws Exception {
    /*
     * This needs to be called explicitly to ensure the featuresReply is not null.
     * Otherwise, there is no guarantee @Before will for setUpFeaturesReply() will
     * call that function before our @Before setUp() here.
     */
    setUpFeaturesReply(); 
    switchManager = createMock(IOFSwitchManager.class);
    roleManager = createMock(RoleManager.class);
    sw = createMock(IOFSwitchBackend.class);
    timer = createMock(Timer.class);
    expect(timer.newTimeout(anyObject(TimerTask.class), anyLong(), anyObject(TimeUnit.class))).andReturn(EasyMock.createNiceMock(Timeout.class));
    replay(timer);
    seenXids = null;

    // TODO: should mock IDebugCounterService and make sure
    // the expected counters are updated.
    debugCounterService = new DebugCounterServiceImpl();
    SwitchManagerCounters counters =
            new SwitchManagerCounters(debugCounterService);
    expect(switchManager.getCounters()).andReturn(counters).anyTimes();
    replay(switchManager);
    connection = new MockOFConnection(featuresReply.getDatapathId(), OFAuxId.MAIN);
    switchHandler = new OFSwitchHandshakeHandler(connection, featuresReply, switchManager, roleManager, timer);

    // replay sw. Reset it if you need more specific behavior
    replay(sw);
}
项目:yajsw    文件:ReconnectHandler.java   
public void stop()
{
    _stop = true;
    Timeout timeout = _timeout;
    _timeout = null;
    timeout.cancel();
}