public void resetTotalBytesSentReceived(long new_sent, long new_received) {
    boolean running = download_manager.getPeerManager() != null;

    if (running) {

      download_manager.stopIt(DownloadManager.STATE_STOPPED, false, false);
    }

    if (new_sent >= 0) {

      saved_data_bytes_uploaded = new_sent;
      session_start_data_bytes_uploaded = new_sent;
      saved_protocol_bytes_uploaded = 0;
    }

    if (new_received >= 0) {

      saved_data_bytes_downloaded = new_received;
      session_start_data_bytes_downloaded = new_received;
      saved_protocol_bytes_downloaded = 0;
    }

    saved_discarded = 0;
    saved_hashfails = 0;

    if (running) {

      download_manager.setStateWaiting();
    }
  }
    @Override
    public void setUp() throws Exception {
        networkManagerStub = new NetworkManagerStub();
        networkManagerStub.setPort(PORT);
        Injector injector = LimeTestUtils.createInjector(MyActivityCallback.class, new LimeTestUtils.NetworkManagerStubModule(networkManagerStub));
        super.setUp(injector);

        DownloadManagerImpl downloadManager = (DownloadManagerImpl)injector.getInstance(DownloadManager.class);
        callback = (MyActivityCallback) injector.getInstance(ActivityCallback.class);
        
        downloadManager.clearAllDownloads();
        
        //      Turn off by default, explicitly test elsewhere.
        networkManagerStub.setIncomingTLSEnabled(false);
        networkManagerStub.setOutgoingTLSEnabled(false);
        // duplicate queries are sent out each time, so avoid the DuplicateFilter
        Thread.sleep(2000);        

        // send a MessagesSupportedMessage
        testUP[0].send(injector.getInstance(MessagesSupportedVendorMessage.class));
        testUP[0].flush();
        
        // we expect to get a PushProxy request
        Message m;
        do {
            m = testUP[0].receive(TIMEOUT);
        } while (!(m instanceof PushProxyRequest));

        // we should answer the push proxy request
        PushProxyAcknowledgement ack = new PushProxyAcknowledgement(InetAddress
                .getLocalHost(), 6355, new GUID(m.getGUID()));
        testUP[0].send(ack);
        testUP[0].flush();
    }
  public long getAvailWentBadTime() {
    PEPeerManager pm = download_manager.getPeerManager();

    if (pm != null) {

      long bad_time = pm.getAvailWentBadTime();

      if (bad_time > 0) {

        // valid last bad time

        return (bad_time);
      }

      if (pm.getMinAvailability() >= 1.0) {

        // we can believe the fact that it isn't bad (we want to ignore 0 results from
        // downloads that never get to a 1.0 availbility)

        return (0);
      }
    }

    DownloadManagerState state = download_manager.getDownloadState();

    return (state.getLongAttribute(DownloadManagerState.AT_AVAIL_BAD_TIME));
  }
  public long getSizeExcludingDND() {
    DiskManager dm = download_manager.getDiskManager();

    if (dm != null) {
      return dm.getSizeExcludingDND();
    }

    long totalLength = download_manager.getSize();
    return totalLength - saved_skipped_file_set_size;
  }
  public long getTotalAveragePerPeer() {
    int div =
        download_manager.getNbPeers()
            + (download_manager.isDownloadComplete(false)
                ? 0
                : 1); // since total speed includes our own speed
    // when downloading

    long average = div < 1 ? 0 : getTotalAverage() / div;

    return (average);
  }
  public long getRemaining() {
    DiskManager disk_manager = download_manager.getDiskManager();

    if (disk_manager == null) {

      return download_manager.getSize()
          - ((long) getDownloadCompleted(false) * download_manager.getSize() / 1000L);

    } else {

      return disk_manager.getRemainingExcludingDND();
    }
  }
  public void setShareRatio(int ratio) {
    if (ratio < 0) {
      ratio = 0;
    }

    if (ratio > 1000000) {
      ratio = 1000000;
    }

    DiskManagerFileInfo[] files = download_manager.getDiskManagerFileInfoSet().getFiles();

    long total_size = 0;

    for (DiskManagerFileInfo file : files) {

      if (!file.isSkipped()) {

        total_size += file.getLength();
      }
    }

    if (total_size == 0) {

      // can't do much if they have no files selected (which would be stupid anyway)

      return;
    }

    saved_hashfails = 0;
    saved_discarded = 0;
    saved_data_bytes_downloaded = 0;
    saved_data_bytes_uploaded = 0;

    long downloaded = getTotalGoodDataBytesReceived();
    long uploaded = getTotalDataBytesSent();

    // manipulate by updating downloaded to be one full copy and then uploaded as required

    long target_downloaded = total_size;
    long target_uploaded = (ratio * total_size) / 1000;

    saved_data_bytes_downloaded = target_downloaded - downloaded;
    saved_data_bytes_uploaded = target_uploaded - uploaded;

    if (download_manager.getPeerManager() == null) {

      saveSessionTotals();
    }
  }
  protected void saveSessionTotals() {
    // re-base the totals from current totals and session totals

    saved_data_bytes_downloaded = getTotalDataBytesReceived();
    saved_data_bytes_uploaded = getTotalDataBytesSent();

    saved_protocol_bytes_downloaded = getTotalProtocolBytesReceived();
    saved_protocol_bytes_uploaded = getTotalProtocolBytesSent();

    saved_discarded = getDiscarded();
    saved_hashfails = getHashFailBytes();

    saved_SecondsDownloading = getSecondsDownloading();
    saved_SecondsOnlySeeding = getSecondsOnlySeeding();

    saved_SecondsSinceDownload = getTimeSinceLastDataReceivedInSeconds();
    saved_SecondsSinceUpload = getTimeSinceLastDataSentInSeconds();

    saved_peak_receive_rate = getPeakDataReceiveRate();
    saved_peak_send_rate = getPeakDataSendRate();

    DownloadManagerState state = download_manager.getDownloadState();

    state.setIntAttribute(DownloadManagerState.AT_TIME_SINCE_DOWNLOAD, saved_SecondsSinceDownload);
    state.setIntAttribute(DownloadManagerState.AT_TIME_SINCE_UPLOAD, saved_SecondsSinceUpload);

    state.setLongAttribute(DownloadManagerState.AT_AVAIL_BAD_TIME, getAvailWentBadTime());

    state.setLongAttribute(DownloadManagerState.AT_PEAK_RECEIVE_RATE, saved_peak_receive_rate);
    state.setLongAttribute(DownloadManagerState.AT_PEAK_SEND_RATE, saved_peak_send_rate);
  }
  public void restoreSessionTotals(
      long _saved_data_bytes_downloaded,
      long _saved_data_bytes_uploaded,
      long _saved_discarded,
      long _saved_hashfails,
      long _saved_SecondsDownloading,
      long _saved_SecondsOnlySeeding) {
    saved_data_bytes_downloaded = _saved_data_bytes_downloaded;
    saved_data_bytes_uploaded = _saved_data_bytes_uploaded;
    saved_discarded = _saved_discarded;
    saved_hashfails = _saved_hashfails;
    saved_SecondsDownloading = _saved_SecondsDownloading;
    saved_SecondsOnlySeeding = _saved_SecondsOnlySeeding;

    session_start_data_bytes_downloaded = saved_data_bytes_downloaded;
    session_start_data_bytes_uploaded = _saved_data_bytes_uploaded;

    DownloadManagerState state = download_manager.getDownloadState();

    saved_SecondsSinceDownload = state.getIntAttribute(DownloadManagerState.AT_TIME_SINCE_DOWNLOAD);
    saved_SecondsSinceUpload = state.getIntAttribute(DownloadManagerState.AT_TIME_SINCE_UPLOAD);

    saved_peak_receive_rate = state.getLongAttribute(DownloadManagerState.AT_PEAK_RECEIVE_RATE);
    saved_peak_send_rate = state.getLongAttribute(DownloadManagerState.AT_PEAK_SEND_RATE);
  }
  public long getTotalDataBytesReceived() {
    PEPeerManager pm = download_manager.getPeerManager();

    if (pm != null) {
      return saved_data_bytes_downloaded + pm.getStats().getTotalDataBytesReceived();
    }
    return (saved_data_bytes_downloaded);
  }
  /*
   * (non-Javadoc)
   * @see org.gudy.azureus2.core3.download.DownloadManagerStats#getCompleted()
   */
  public int getCompleted() {
    DiskManager dm = download_manager.getDiskManager();

    if (dm == null) {
      int state = download_manager.getState();
      if (state == DownloadManager.STATE_ALLOCATING
          || state == DownloadManager.STATE_CHECKING
          || state == DownloadManager.STATE_INITIALIZING) return completed;
      else return downloadCompleted;
    }
    if (dm.getState() == DiskManager.ALLOCATING
        || dm.getState() == DiskManager.CHECKING
        || dm.getState() == DiskManager.INITIALIZING) return dm.getPercentDone();
    else {
      long total = dm.getTotalLength();
      return total == 0 ? 0 : (int) ((1000 * (total - dm.getRemaining())) / total);
    }
  }
  public String getElapsedTime() {
    PEPeerManager pm = download_manager.getPeerManager();

    if (pm != null) {
      return pm.getElapsedTime();
    }

    return "";
  }
  public long getSmoothedDataSendRate() {
    PEPeerManager pm = download_manager.getPeerManager();

    if (pm != null) {

      return (pm.getStats().getSmoothedDataSendRate());
    }

    return (0);
  }
  public long getTotalAverage() {
    PEPeerManager pm = download_manager.getPeerManager();

    if (pm != null) {

      return pm.getStats().getTotalAverage();
    }

    return (0);
  }
  public long getHashFailBytes() {
    PEPeerManager pm = download_manager.getPeerManager();

    if (pm != null) {

      return saved_hashfails + pm.getStats().getTotalHashFailBytes();
    }

    return (saved_hashfails);
  }
  public long getDiscarded() {
    PEPeerManager pm = download_manager.getPeerManager();

    if (pm != null) {

      return saved_discarded + pm.getStats().getTotalDiscarded();
    }

    return (saved_discarded);
  }
  public long getSmoothedETA() {
    PEPeerManager pm = download_manager.getPeerManager();

    if (pm != null) {

      return pm.getETA(true);
    }

    return -1; // return exactly -1 if ETA is unknown
  }
  public float getAvailability() {
    PEPeerManager pm = download_manager.getPeerManager();

    if (pm == null) {

      return (-1);
    }

    return (pm.getMinAvailability());
  }
  private long getTimeStartedSeeding(boolean mono) {
    PEPeerManager pm = download_manager.getPeerManager();

    if (pm != null) {

      return (pm.getTimeStartedSeeding(mono));
    }

    return -1;
  }
  public long getBytesUnavailable() {
    PEPeerManager pm = download_manager.getPeerManager();

    if (pm == null) {

      return (-1);
    }

    return (pm.getBytesUnavailable());
  }
  public long getTotalProtocolBytesSent() {
    PEPeerManager pm = download_manager.getPeerManager();

    if (pm != null) {

      return saved_protocol_bytes_uploaded + pm.getStats().getTotalProtocolBytesSent();
    }

    return (saved_protocol_bytes_uploaded);
  }
  public long getProtocolSendRate() {
    PEPeerManager pm = download_manager.getPeerManager();

    if (pm != null) {

      return pm.getStats().getProtocolSendRate();
    }

    return 0;
  }
  public long getDataReceiveRate() {
    PEPeerManager pm = download_manager.getPeerManager();

    if (pm != null) {

      return pm.getStats().getDataReceiveRate();
    }

    return 0;
  }
  public long getPeakDataSendRate() {
    PEPeerManager pm = download_manager.getPeerManager();

    long result = saved_peak_send_rate;

    if (pm != null) {

      result = Math.max(result, pm.getStats().getPeakDataSendRate());
    }

    return (result);
  }
  public long getRemainingExcludingDND() {
    DiskManager dm = download_manager.getDiskManager();

    if (dm != null) {
      return dm.getRemainingExcludingDND();
    }

    long remaining = getRemaining();
    long rem = (remaining - (saved_skipped_file_set_size - saved_skipped_but_downloaded));

    if (rem < 0) {

      rem = 0;
    }

    return (rem);
  }
  public long getHashFailCount() {
    TOTorrent t = download_manager.getTorrent();

    if (t == null) {

      return (0);
    }

    long total = getHashFailBytes();

    long res = total / t.getPieceLength();

    if (res == 0 && total > 0) {

      res = 1;
    }

    return (res);
  }
  public int getDownloadCompleted(boolean bLive) {
    DiskManager dm = download_manager.getDiskManager();

    // no disk manager -> not running -> use stored value

    if (dm == null) {

      return downloadCompleted;
    }

    int state = dm.getState();

    boolean transient_state =
        state == DiskManager.INITIALIZING
            || state == DiskManager.ALLOCATING
            || state == DiskManager.CHECKING;

    long total = dm.getTotalLength();

    int computed_completion =
        (total == 0) ? 0 : (int) ((1000 * (total - dm.getRemaining())) / total);

    // use non-transient values to update the record of download completion

    if (!transient_state) {

      downloadCompleted = computed_completion;
    }

    if (bLive) {

      // return the transient completion level

      return computed_completion;

    } else {

      // return the non-transient one

      return (downloadCompleted);
    }
  }
  public int getTimeSinceLastDataSentInSeconds() {
    PEPeerManager pm = download_manager.getPeerManager();

    int res = saved_SecondsSinceUpload;

    if (pm != null) {

      int current = pm.getStats().getTimeSinceLastDataSentInSeconds();

      if (current >= 0) {

        // activity this session, use this value

        res = current;

      } else {

        // no activity this session. If ever has been activity add in session
        // time

        if (res >= 0) {

          long now = SystemTime.getCurrentTime();

          long elapsed = now - pm.getTimeStarted(false);

          if (elapsed < 0) {

            elapsed = 0;
          }

          res += elapsed / 1000;
        }
      }
    }

    return (res);
  }
  protected void timerTick(int tick_count) {
    if (tick_count % 15 == 0) {

      if (last_sr_progress == -1) {

        long temp =
            download_manager
                .getDownloadState()
                .getLongAttribute(DownloadManagerState.AT_SHARE_RATIO_PROGRESS);

        last_sr_progress = (int) temp;
      }

      if (share_ratio_progress_interval <= 0) {

        // reset

        if (last_sr_progress != 0) {

          last_sr_progress = 0;

          download_manager
              .getDownloadState()
              .setLongAttribute(DownloadManagerState.AT_SHARE_RATIO_PROGRESS, 0);
        }
      } else {

        int current_sr = getShareRatio();

        current_sr = (current_sr / share_ratio_progress_interval) * share_ratio_progress_interval;

        if (current_sr != last_sr_progress) {

          last_sr_progress = current_sr;

          long data = ((SystemTime.getCurrentTime() / 1000) << 32) + last_sr_progress;

          download_manager
              .getDownloadState()
              .setLongAttribute(DownloadManagerState.AT_SHARE_RATIO_PROGRESS, data);
        }
      }
    }

    if (!history_retention_required) {

      return;
    }

    PEPeerManager pm = download_manager.getPeerManager();

    if (pm == null) {

      return;
    }

    PEPeerManagerStats stats = pm.getStats();

    long send_rate = stats.getDataSendRate() + stats.getProtocolSendRate();
    long receive_rate = stats.getDataReceiveRate() + stats.getProtocolReceiveRate();
    long peer_swarm_average = getTotalAveragePerPeer();

    long entry =
        ((((send_rate - 1 + HISTORY_DIV / 2) / HISTORY_DIV) << 42) & 0x7ffffc0000000000L)
            | ((((receive_rate - 1 + HISTORY_DIV / 2) / HISTORY_DIV) << 21) & 0x000003ffffe00000L)
            | ((((peer_swarm_average - 1 + HISTORY_DIV / 2) / HISTORY_DIV)) & 0x00000000001fffffL);

    synchronized (this) {
      if (history != null) {

        history[history_pos++] = entry;

        if (history_pos == HISTORY_MAX_SECS) {

          history_pos = 0;
          history_wrapped = true;
        }
      }
    }
  }