package protocolP2P; import protocolP2P.Payload; import protocolP2P.RequestResponseCode; import exception.TransmissionError; import exception.ProtocolError; import exception.InternalError; import exception.SizeError; import java.io.UnsupportedEncodingException; /** Representation of payload for load request. * @author Louis Royer * @author Flavien Haas * @author JS Auge * @version 1.0 */ public class LoadRequest extends Payload { private String filename; /** Constructor (typically used by the server) with a filename parameter. * @param filename name of the file to download. Must not be empty. * @throws InternalError */ public LoadRequest(String filename) throws InternalError { super(RequestResponseCode.LOAD_REQUEST); /* assert to help debugging */ assert filename.length() != 0 : "Payload size of LoadRequest must not be empty"; if (filename.length() == 0) { throw new InternalError(); } this.filename = filename; } /** Constructor (typically used by client) with a byte[] parameter containing the datagram received. * @param datagram the full datagram received * @throws SizeError * @throws InternalError * @throws ProtocolError * @throws TransmissionError */ protected LoadRequest(byte[] datagram) throws TransmissionError, SizeError, ProtocolError, InternalError { super(datagram); /* assert to help debugging */ assert requestResponseCode == RequestResponseCode.LOAD_REQUEST : "LoadRequest subclass is incompatible with this datagram, request/response code must be checked before using this constructor"; /* InternalErrorException */ if (requestResponseCode!= RequestResponseCode.LOAD_REQUEST) { throw new InternalError(); } int size = getPayloadSize(datagram); try { filename = new String(datagram, 8, size, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new InternalError(); } } /** Returns a byte[] containing datagram with padding. * This datagram is still incomplete and should not be send directly. * ProtocolP2PDatagram will use this method to generate the complete datagram. * @return datagram with padding * @throws InternalError */ protected byte[] toDatagram() throws InternalError { // compute size int size = 8 + filename.length(); byte[] datagram = new byte[size]; // java initialize all to zero // set request/response code datagram[RequestResponseCode.RRCODE_POSITION] = requestResponseCode.codeValue; // bits 16-31 are reserved for future use setPayloadSize(size - 8, datagram); // Write filename int bCount = 8; try { byte[] sb = filename.getBytes("UTF-8"); for(byte b : sb) { datagram[bCount] = b; bCount += 1; } } catch (UnsupportedEncodingException e) { throw new InternalError(); } return datagram; } /** filename getter. * @return filename */ public String getFilename() { return filename; } }