Projet_JAVA_P2P_STRI2A/src/protocolP2P/RequestResponseCode.java

63 lines
1.7 KiB
Java
Raw Normal View History

package protocolP2P;
import protocolP2P.CodeType;
import exception.ProtocolError;
import java.util.HashMap;
import java.util.Map;
import java.lang.Byte;
/** Request/Response code enum.
* @author Louis Royer
* @author Flavien Haas
* @author JS Auge
* @version 1.0
*/
public enum RequestResponseCode {
LIST_REQUEST(CodeType.REQUEST, (byte)0x00),
LOAD_REQUEST(CodeType.REQUEST, (byte)0x01),
LIST_RESPONSE(CodeType.RESPONSE, (byte)0x80),
LOAD_RESPONSE(CodeType.RESPONSE, (byte)0x81),
NOT_FOUND(CodeType.RESPONSE, (byte)0x82),
PROTOCOL_ERROR(CodeType.RESPONSE, (byte)0x83),
INTERNAL_ERROR(CodeType.RESPONSE, (byte)0x84);
public final CodeType codeType;
public final byte codeValue;
protected final static int RRCODE_POSITION = 1;
/* To be able to convert code to enum */
private static final Map<Byte, RequestResponseCode> BY_CODE = new HashMap<>();
/* Initialization of HashMap */
static {
for (RequestResponseCode r: values()) {
assert !BY_CODE.containsKey(Byte.valueOf(r.codeValue)) : "Duplicate in " + RequestResponseCode.class.getCanonicalName();
BY_CODE.put(Byte.valueOf(r.codeValue), r);
}
}
/** Private constructor
* @param codeType type of code (request or response)
* @param codeValue value of the element in datagram
* @return enum element
*/
private RequestResponseCode(CodeType codeType, byte codeValue) {
this.codeType = codeType;
this.codeValue = codeValue;
}
/** Gives enum from datagram code.
* @param code value of the element in datagram
* @return enum element
*/
public static RequestResponseCode fromCode(byte code) throws ProtocolError {
byte code = BY_CODE.get(Byte.valueOf(code));
if (code == null) {
throw new ProtocolError();
}
return code;
}
}