Routing-Packets-In-A-Network-Overlay / src / main / java / csx55 / overlay / wireformats / RegisterResponse.java
RegisterResponse.java
Raw
package csx55.overlay.wireformats;

import java.io.*;

/**
 * This is a wireformat used by the registry to respond to the messaging node after the node sends a 
 * registration request. Messaging nodes will be added to a list of connections if everything is correct.
 * It follows the same format as all of the other wireformats and is built using the provided example
 * in the slides. This wireformat accepts the status (Success or Failure) and addInfo regarding the registration request
 * as one constructor and intializes the instance variables. Another constructor takes in the byte stream and 
 * unmarshalls the information sent by the node. It also implemnts the getBytes() method from the Event interface, 
 * which marshalls the variables for this wireformat. The first constructor is used when creating an instance of the class
 * and the second is used by the event factory to create a new instance and return a class that the bytes
 * unmarshalled. The getBytes() is used before the data is sent using the sender thread.
 */
public class RegisterResponse implements Event {
    private int type;
    private byte status;
    private String addInfo;

    public RegisterResponse(byte status, String addInfo) {
        this.type = Protocol.REGISTER_RESPONSE;
        this.status = status;
        this.addInfo = addInfo;
    }

    public RegisterResponse(byte[] marshalledByte) throws IOException {
        ByteArrayInputStream baInputStream = new ByteArrayInputStream(marshalledByte);
        DataInputStream din = new DataInputStream(new BufferedInputStream(baInputStream));

        this.type = din.readInt();
        this.status = din.readByte();

        int addInfoSize = din.readInt();
        byte[] addInfoArray = new byte[addInfoSize];
        din.readFully(addInfoArray, 0, addInfoSize);
        this.addInfo = new String(addInfoArray);

        baInputStream.close();
        din.close();
    }

    @Override
    public int getType() {
        return type;
    }

    @Override
    public byte[] getBytes() throws IOException {
        byte[] marshalledBytes = null;
        ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(new BufferedOutputStream(baOutputStream));

        dout.writeInt(type);
        dout.writeByte(status);

        byte[] identifierBytes = addInfo.getBytes();
        int elementLength = identifierBytes.length;
        dout.writeInt(elementLength);
        dout.write(identifierBytes);

        dout.flush();
        marshalledBytes = baOutputStream.toByteArray();

        baOutputStream.close();
        dout.close();
        return marshalledBytes;
    }

    //returns the addInfo
    @Override
    public String toString() {
        return this.addInfo;
    }
}