Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changing certain private declarations to protected to allow for library ... #115

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@
*.bak
*~
*~
/build/
88 changes: 52 additions & 36 deletions src/main/java/com/turn/ttorrent/client/Client.java
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,14 @@ public class Client extends Observable implements Runnable,

/** Peers unchoking frequency, in seconds. Current BitTorrent specification
* recommends 10 seconds to avoid choking fibrilation. */
private static final int UNCHOKING_FREQUENCY = 3;
protected static final int UNCHOKING_FREQUENCY = 3;

/** Optimistic unchokes are done every 2 loop iterations, i.e. every
* 2*UNCHOKING_FREQUENCY seconds. */
private static final int OPTIMISTIC_UNCHOKE_ITERATIONS = 3;
protected static final int OPTIMISTIC_UNCHOKE_ITERATIONS = 3;

private static final int RATE_COMPUTATION_ITERATIONS = 2;
private static final int MAX_DOWNLOADERS_UNCHOKE = 4;
protected static final int RATE_COMPUTATION_ITERATIONS = 2;
protected static final int MAX_DOWNLOADERS_UNCHOKE = 4;

public enum ClientState {
WAITING,
Expand All @@ -96,22 +96,22 @@ public enum ClientState {
DONE;
};

private static final String BITTORRENT_ID_PREFIX = "-TO0042-";
protected static final String BITTORRENT_ID_PREFIX = "-TO0042-";

private SharedTorrent torrent;
private ClientState state;
private Peer self;
protected SharedTorrent torrent;
protected ClientState state;
protected Peer self;

private Thread thread;
private boolean stop;
private long seed;
protected Thread thread;
protected boolean stop;
protected long seed;

private ConnectionHandler service;
private Announce announce;
private ConcurrentMap<String, SharingPeer> peers;
private ConcurrentMap<String, SharingPeer> connected;
protected ConnectionHandler service;
protected Announce announce;
protected ConcurrentMap<String, SharingPeer> peers = new ConcurrentHashMap<String, SharingPeer>();
protected ConcurrentMap<String, SharingPeer> connected = new ConcurrentHashMap<String, SharingPeer>();

private Random random;
protected Random random = new Random(System.currentTimeMillis());

/**
* Initialize the BitTorrent client.
Expand All @@ -124,24 +124,18 @@ public Client(InetAddress address, SharedTorrent torrent)
this.torrent = torrent;
this.state = ClientState.WAITING;

String id = Client.BITTORRENT_ID_PREFIX + UUID.randomUUID()
.toString().split("-")[4];
String id = clientId();

// Initialize the incoming connection handler and register ourselves to
// it.
this.service = new ConnectionHandler(this.torrent, id, address);
this.service.register(this);
initializeConnectionHandler(address, id);

this.self = new Peer(
this.service.getSocketAddress()
.getAddress().getHostAddress(),
(short)this.service.getSocketAddress().getPort(),
ByteBuffer.wrap(id.getBytes(Torrent.BYTE_ENCODING)));

// Initialize the announce request thread, and register ourselves to it
// as well.
this.announce = new Announce(this.torrent, this.self);
this.announce.register(this);

initializeAnnounceRequest();

logger.info("BitTorrent client [{}] for {} started and " +
"listening at {}:{}...",
Expand All @@ -151,10 +145,32 @@ public Client(InetAddress address, SharedTorrent torrent)
this.self.getIp(),
this.self.getPort()
});
}

this.peers = new ConcurrentHashMap<String, SharingPeer>();
this.connected = new ConcurrentHashMap<String, SharingPeer>();
this.random = new Random(System.currentTimeMillis());
/**
* @return The Id of the peer. This default implementation is _random_ and will
* return a different Id on each invocation.
*/
protected String clientId() {
String id = Client.BITTORRENT_ID_PREFIX + UUID.randomUUID()
.toString().split("-")[4];
return id;
}

/**
* Initialize the incoming connection handler and register ourselves to it.
*/
protected void initializeConnectionHandler(InetAddress address, String id) throws IOException {
this.service = new ConnectionHandler(this.torrent, id, address);
this.service.register(this);
}

/**
* Initialize the announce request thread, and register ourselves to it as well.
*/
protected void initializeAnnounceRequest() {
this.announce = new Announce(this.torrent, this.self);
this.announce.register(this);
}

/**
Expand Down Expand Up @@ -207,7 +223,7 @@ public Set<SharingPeer> getPeers() {
*
* @param state The new client state.
*/
private synchronized void setState(ClientState state) {
protected synchronized void setState(ClientState state) {
if (this.state != state) {
this.setChanged();
}
Expand Down Expand Up @@ -417,7 +433,7 @@ public void run() {
/**
* Close torrent and set final client state before signing off.
*/
private void finish() {
protected void finish() {
this.torrent.close();

// Determine final state
Expand Down Expand Up @@ -483,7 +499,7 @@ public synchronized void info() {
* seconds).
* </p>
*/
private synchronized void resetPeerRates() {
protected synchronized void resetPeerRates() {
for (SharingPeer peer : this.connected.values()) {
peer.getDLRate().reset();
peer.getULRate().reset();
Expand All @@ -501,7 +517,7 @@ private synchronized void resetPeerRates() {
*
* @param search The {@link Peer} specification.
*/
private SharingPeer getOrCreatePeer(Peer search) {
protected SharingPeer getOrCreatePeer(Peer search) {
SharingPeer peer;

synchronized (this.peers) {
Expand Down Expand Up @@ -555,7 +571,7 @@ private SharingPeer getOrCreatePeer(Peer search) {
* @return A SharingPeer comparator that can be used to sort peers based on
* the download or upload rate we get from them.
*/
private Comparator<SharingPeer> getPeerRateComparator() {
protected Comparator<SharingPeer> getPeerRateComparator() {
if (ClientState.SHARING.equals(this.state)) {
return new SharingPeer.DLRateComparator();
} else if (ClientState.SEEDING.equals(this.state)) {
Expand Down Expand Up @@ -597,7 +613,7 @@ private Comparator<SharingPeer> getPeerRateComparator() {
*
* @param optimistic Whether to perform an optimistic unchoke as well.
*/
private synchronized void unchokePeers(boolean optimistic) {
protected synchronized void unchokePeers(boolean optimistic) {
// Build a set of all connected peers, we don't care about peers we're
// not connected to.
TreeSet<SharingPeer> bound = new TreeSet<SharingPeer>(
Expand Down Expand Up @@ -932,7 +948,7 @@ public void handleIOException(SharingPeer peer, IOException ioe) {
*
* @see ClientShutdown
*/
private synchronized void seed() {
protected synchronized void seed() {
// Silently ignore if we're already seeding.
if (ClientState.SEEDING.equals(this.getState())) {
return;
Expand Down
46 changes: 23 additions & 23 deletions src/main/java/com/turn/ttorrent/client/ConnectionHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -82,20 +82,20 @@ public class ConnectionHandler implements Runnable {
public static final int PORT_RANGE_START = 6881;
public static final int PORT_RANGE_END = 6889;

private static final int OUTBOUND_CONNECTIONS_POOL_SIZE = 20;
private static final int OUTBOUND_CONNECTIONS_THREAD_KEEP_ALIVE_SECS = 10;
protected static final int OUTBOUND_CONNECTIONS_POOL_SIZE = 20;
protected static final int OUTBOUND_CONNECTIONS_THREAD_KEEP_ALIVE_SECS = 10;

private static final int CLIENT_KEEP_ALIVE_MINUTES = 3;
protected static final int CLIENT_KEEP_ALIVE_MINUTES = 3;

private SharedTorrent torrent;
private String id;
private ServerSocketChannel channel;
private InetSocketAddress address;
protected SharedTorrent torrent;
protected String id;
protected ServerSocketChannel channel;
protected InetSocketAddress address;

private Set<IncomingConnectionListener> listeners;
private ExecutorService executor;
private Thread thread;
private boolean stop;
protected Set<IncomingConnectionListener> listeners;
protected ExecutorService executor;
protected Thread thread;
protected boolean stop;

/**
* Create and start a new listening service for out torrent, reporting
Expand Down Expand Up @@ -269,7 +269,7 @@ public void run() {
* @return A textual representation (<em>host:port</em>) of the given
* socket.
*/
private String socketRepr(SocketChannel channel) {
protected String socketRepr(SocketChannel channel) {
Socket s = channel.socket();
return String.format("%s:%d%s",
s.getInetAddress().getHostName(),
Expand All @@ -294,7 +294,7 @@ private String socketRepr(SocketChannel channel) {
*
* @param client The accepted client's socket channel.
*/
private void accept(SocketChannel client)
protected void accept(SocketChannel client)
throws IOException, SocketTimeoutException {
try {
logger.debug("New incoming connection, waiting for handshake...");
Expand Down Expand Up @@ -364,7 +364,7 @@ public void connect(SharingPeer peer) {
* any peer ID is accepted (this is the case for incoming connections).
* @return The validated handshake message object.
*/
private Handshake validateHandshake(SocketChannel channel, byte[] peerId)
protected Handshake validateHandshake(SocketChannel channel, byte[] peerId)
throws IOException, ParseException {
ByteBuffer len = ByteBuffer.allocate(1);
ByteBuffer data;
Expand Down Expand Up @@ -411,7 +411,7 @@ private Handshake validateHandshake(SocketChannel channel, byte[] peerId)
*
* @param channel The socket channel to the remote peer.
*/
private int sendHandshake(SocketChannel channel) throws IOException {
protected int sendHandshake(SocketChannel channel) throws IOException {
return channel.write(
Handshake.craft(
this.torrent.getInfoHash(),
Expand All @@ -424,13 +424,13 @@ private int sendHandshake(SocketChannel channel) throws IOException {
* @param channel The socket channel to the newly connected peer.
* @param peerId The peer ID of the connected peer.
*/
private void fireNewPeerConnection(SocketChannel channel, byte[] peerId) {
protected void fireNewPeerConnection(SocketChannel channel, byte[] peerId) {
for (IncomingConnectionListener listener : this.listeners) {
listener.handleNewPeerConnection(channel, peerId);
}
}

private void fireFailedConnection(SharingPeer peer, Throwable cause) {
protected void fireFailedConnection(SharingPeer peer, Throwable cause) {
for (IncomingConnectionListener listener : this.listeners) {
listener.handleFailedConnection(peer, cause);
}
Expand All @@ -443,9 +443,9 @@ private void fireFailedConnection(SharingPeer peer, Throwable cause) {
*
* @author mpetazzoni
*/
private static class ConnectorThreadFactory implements ThreadFactory {
protected static class ConnectorThreadFactory implements ThreadFactory {

private int number = 0;
protected int number = 0;

@Override
public Thread newThread(Runnable r) {
Expand All @@ -469,12 +469,12 @@ public Thread newThread(Runnable r) {
*
* @author mpetazzoni
*/
private static class ConnectorTask implements Runnable {
protected static class ConnectorTask implements Runnable {

private final ConnectionHandler handler;
private final SharingPeer peer;
protected final ConnectionHandler handler;
protected final SharingPeer peer;

private ConnectorTask(ConnectionHandler handler, SharingPeer peer) {
protected ConnectorTask(ConnectionHandler handler, SharingPeer peer) {
this.handler = handler;
this.peer = peer;
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/turn/ttorrent/client/Handshake.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public class Handshake {
ByteBuffer infoHash;
ByteBuffer peerId;

private Handshake(ByteBuffer data, ByteBuffer infoHash,
protected Handshake(ByteBuffer data, ByteBuffer infoHash,
ByteBuffer peerId) {
this.data = data;
this.data.rewind();
Expand Down
20 changes: 10 additions & 10 deletions src/main/java/com/turn/ttorrent/client/Piece.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,16 @@ public class Piece implements Comparable<Piece> {
private static final Logger logger =
LoggerFactory.getLogger(Piece.class);

private final TorrentByteStorage bucket;
private final int index;
private final long offset;
private final long length;
private final byte[] hash;
private final boolean seeder;
protected final TorrentByteStorage bucket;
protected final int index;
protected final long offset;
protected final long length;
protected final byte[] hash;
protected final boolean seeder;

private volatile boolean valid;
private int seen;
private ByteBuffer data;
protected volatile boolean valid;
protected int seen;
protected ByteBuffer data;

/**
* Initialize a new piece in the byte bucket.
Expand Down Expand Up @@ -183,7 +183,7 @@ public synchronized boolean validate() throws IOException {
* @throws IOException If the read can't be completed (I/O error, or EOF
* reached, which can happen if the piece is not complete).
*/
private ByteBuffer _read(long offset, long length) throws IOException {
protected ByteBuffer _read(long offset, long length) throws IOException {
if (offset + length > this.length) {
throw new IllegalArgumentException("Piece#" + this.index +
" overrun (" + offset + " + " + length + " > " +
Expand Down
Loading