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

import java.io.*;

/**
 * This is a wireformat used by the messaging nodes to exit the overlay with the exit-overlay command.
 * 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 hostname and port number 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 Deregister implements Event {
    private int type;
    private String ipAddress;
    private int portNum;

    public Deregister(String ipAddress, int portNum) {
        this.type = Protocol.DEREGISTER_REQUEST;
        this.ipAddress = ipAddress;
        this.portNum = portNum;
    }

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

        this.type = din.readInt();//for type

        //for ipaddress
        int size = din.readInt();
        byte[] ipAddressBytes = new byte[size];
        din.readFully(ipAddressBytes, 0, size);
        this.ipAddress = new String(ipAddressBytes);

        //for port
        this.portNum = din.readInt();

        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);//write type

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

        //write port
        dout.writeInt(portNum);

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

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

    //returns the name of the messaging node like ip:port
    @Override
    public String toString() {
        return (this.ipAddress + ":" + Integer.toString(this.portNum));
    }
    
}