You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Projet_JAVA_P2P_STRI2A/src/protocolP2P/SizeResponse.java

87 lines
2.8 KiB
Java

package protocolP2P;
import protocolP2P.Payload;
import protocolP2P.RequestResponseCode;
import localException.ProtocolError;
import localException.InternalError;
import localException.SizeError;
import localException.TransmissionError;
import tools.BytesArrayTools;
/** Representation of payload for size response.
* @author Louis Royer
* @author Flavien Haas
* @author JS Auge
* @version 1.0
*/
public class SizeResponse extends Payload {
private String filename;
private long totalSize;
static final private int TOTAL_SIZE_POSITION = PAYLOAD_START_POSITION;
static final private int FILENAME_POSITION = TOTAL_SIZE_POSITION + 8;
/** Constructor (typically used by server) with informations about file part to send as parameters.
* @param filename name of the file
* @param totalSize size of the file
* @throws InternalError
*/
public SizeResponse(String filename, long totalSize) throws InternalError {
super(RequestResponseCode.SIZE_RESPONSE);
/* asserts to help debugging */
assert totalSize >= 0 : "offset cannot be negative";
assert filename != null : "filename is required";
if (filename == null || totalSize < 0) {
throw new InternalError();
}
this.filename = filename;
this.totalSize = totalSize;
}
/** Constructor (typically used by client) with Packet received as parameter.
* @param packet the full Packet received
* @throws SizeError
* @throws InternalError
* @throws TransmissionError
*/
protected SizeResponse(byte[] packet) throws TransmissionError, SizeError, ProtocolError, InternalError {
super(packet);
int filenameSize = getPayloadSize(packet) - FILENAME_POSITION + PAYLOAD_START_POSITION;
totalSize = BytesArrayTools.readLong(packet, TOTAL_SIZE_POSITION);
filename = BytesArrayTools.readString(packet, FILENAME_POSITION, filenameSize);
}
/** Returns a byte[] containing Packet with padding.
* This Packet is still incomplete and should not be send directly.
* ProtocolP2PPacket will use this method to generate the complete Packet.
* @return Packet with padding
* @throws InternalError
*/
protected byte[] toPacket() throws InternalError {
// compute total size
int size = FILENAME_POSITION + filename.length();
byte[] packet = new byte[size]; // java initialize all to zero
// set request/response code
packet[RequestResponseCode.RRCODE_POSITION] = requestResponseCode.codeValue;
// set Payload size
setPayloadSize(size - PAYLOAD_START_POSITION, packet);
// write totalSize to Packet
BytesArrayTools.write(packet, TOTAL_SIZE_POSITION, totalSize);
// write filename to Packet
BytesArrayTools.write(packet, filename, FILENAME_POSITION);
return packet;
}
/** filename getter.
* @return String
*/
public String getFilename() {
return filename;
}
/** totalSize getter.
* @return totalSize
*/
public long getTotalSize() {
return totalSize;
}
}