/**
   * If we receive an ACK or RST, we mark the outgoing request or response as acknowledged or
   * rejected respectively and cancel its retransmission.
   */
  @Override
  public void receiveEmptyMessage(Exchange exchange, EmptyMessage message) {
    exchange.setFailedTransmissionCount(0);
    // TODO: If this is an observe relation, the current response might not
    // be the one that is being acknowledged. The current response might
    // already be the next NON notification.

    if (message.getType() == Type.ACK) {
      if (exchange.getOrigin() == Origin.LOCAL) {
        exchange.getCurrentRequest().setAcknowledged(true);
      } else {
        exchange.getCurrentResponse().setAcknowledged(true);
      }
    } else if (message.getType() == Type.RST) {
      if (exchange.getOrigin() == Origin.LOCAL) {
        exchange.getCurrentRequest().setRejected(true);
      } else {
        exchange.getCurrentResponse().setRejected(true);
      }
    } else {
      LOGGER.warning("Empty messgae was not ACK nor RST: " + message);
    }

    LOGGER.finer("Cancel retransmission");
    exchange.setRetransmissionHandle(null);

    super.receiveEmptyMessage(exchange, message);
  }
  /**
   * Computes the back-off timer and schedules the specified retransmission task.
   *
   * @param exchange the exchange
   * @param task the retransmission task
   */
  protected void prepareRetransmission(Exchange exchange, RetransmissionTask task) {
    /*
     * For a new confirmable message, the initial timeout is set to a
     * random number between ACK_TIMEOUT and (ACK_TIMEOUT *
     * ACK_RANDOM_FACTOR)
     */
    int timeout;
    if (exchange.getFailedTransmissionCount() == 0) {
      timeout = getRandomTimeout(ack_timeout, (int) (ack_timeout * ack_random_factor));
    } else {
      timeout = (int) (ack_timeout_scale * exchange.getCurrentTimeout());
    }
    exchange.setCurrentTimeout(timeout);

    ScheduledFuture<?> f = executor.schedule(task, timeout, TimeUnit.MILLISECONDS);
    exchange.setRetransmissionHandle(f);
  }
  /**
   * When we receive a Confirmable response, we acknowledge it and it also counts as acknowledgment
   * for the request. If the response is a duplicate, we stop it here and do not forward it to the
   * upper layer.
   */
  @Override
  public void receiveResponse(Exchange exchange, Response response) {
    exchange.setFailedTransmissionCount(0);

    exchange.getCurrentRequest().setAcknowledged(true);
    LOGGER.finest("Cancel any retransmission");
    exchange.setRetransmissionHandle(null);

    if (response.getType() == Type.CON && !exchange.getRequest().isCanceled()) {
      LOGGER.finer("Response is confirmable, send ACK");
      EmptyMessage ack = EmptyMessage.newACK(response);
      sendEmptyMessage(exchange, ack);
    }

    if (response.isDuplicate()) {
      LOGGER.fine("Response is duplicate, ignore it");
    } else {
      super.receiveResponse(exchange, response);
    }
  }