Package bandwidth.network

Source Code of bandwidth.network.ControlledInputStream

package bandwidth.network;


import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

import bandwidth.AbstractBandwidthController;
import bandwidth.DownloadBandwidthController;

import main.settings.Settings;


public class ControlledInputStream extends FilterInputStream
{
  private static DownloadBandwidthController controller;

  public static void initialize()
  {
    controller = new DownloadBandwidthController(
        Settings.connection.bandwidth.download);
  }

  public static AbstractBandwidthController getController()
  {
    return controller;
  }

  public ControlledInputStream(InputStream in)
  {
    super(in);
  }

  public int read() throws IOException
  {
    controller.produce();
    int result = in.read();
    controller.notifyConsumed(1);
    return result;
  }

  public int read(byte buffer[]) throws IOException
  {
    return read(buffer, 0, buffer.length);
  }

  public int read(byte buffer[], int offset, int length) throws IOException
  {
    final int produced = controller.produce(length);

    boolean success = doRead(buffer, offset, produced);
    controller.notifyConsumed(produced);

    if (!success)
    {
      return -1;
    }
    return produced;
  }

  private boolean doRead(byte buffer[], int offset, int toBeRead) throws IOException
  {
    int read = 0;
    while (read < toBeRead)
    {
      int lastRead = in.read(buffer, offset + read, toBeRead - read);
      if (lastRead == -1)
      {
        return false;
      }

      read += lastRead;
    }

    return true;
  }

  public long skip(long count) throws IOException
  {
    int request;
    if (count > Integer.MAX_VALUE)
    {
      request = Integer.MAX_VALUE;
    }
    else
    {
      request = (int) count;
    }

    int produced = controller.produce(request);
    return doSkip(produced);
  }

  private int doSkip(int count) throws IOException
  {
    int actuallySkipped = 0;
    while (actuallySkipped < count)
    {
      int skipped = (int) in.skip(count - actuallySkipped);
      controller.notifyConsumed(skipped);

      actuallySkipped += skipped;
    }

    return actuallySkipped;
  }

}
TOP

Related Classes of bandwidth.network.ControlledInputStream

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.