package transfer.download;
import handlers.AbstractContextualHandler;
import handlers.sets.FileDownloadHandlerSet;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import main.PeerProtocol;
import transfer.download.logic.DownloadAttempter;
import common.connection.AbstractCommunicationSet;
import common.connection.ConnectionWriterInterface;
import common.handlers.AbstractHandlerSet;
import connection.peer.GenericPeerConnection;
public class FileDownloadConnection extends GenericPeerConnection
{
private static final FileDownloadHandlerSet HANDLER_SET = new FileDownloadHandlerSet();
private DownloadAttempter attempter;
private FileDownload download;
public FileDownloadConnection(AbstractCommunicationSet source, FileDownload download,
DownloadAttempter attempter) throws IOException
{
super(source);
this.attempter = attempter;
this.download = download;
}
public void initializeConnection() throws IOException
{
attempter.notifyConnected(this);
}
public void finalizeConnection()
{
if (!download.isFinished() && !download.isInterrupted())
{
download.notifySourceDown();
}
}
protected AbstractHandlerSet getHandlerSet()
{
return HANDLER_SET;
}
public AbstractContextualHandler getContextualHandler(int protocolId, int opcode)
throws IOException, ClassNotFoundException
{
return FileDownloadHandlerSet.HANDLERS[protocolId][opcode]
.createContext(this, is);
}
public DownloadAttempter getAttempter()
{
return attempter;
}
public void requestFile()
{
int protocolId = PeerProtocol.PROTOCOL_TRANSFER;
int opcode = PeerProtocol.Transfer.OP_REQUEST_FILE;
send(protocolId, opcode, new ConnectionWriterInterface()
{
public void run(ObjectOutputStream os) throws IOException
{
os.writeObject(download.getFile());
os.writeLong(download.getCompletedSize());
}
});
}
public void download() throws IOException
{
OutputStream output = download.openTarget();
download.transfer(is, output);
output.close();
download.notifyFinished();
}
}