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

import java.io.*;

/**
 * This is a wireformat used by the registry to tell all messaging nodes to start passing messages to peers.
 * It follows the same format as all of the other wireformats and is built using the provided example
 * in the slides. This wireformat accepts just the number of rounds 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 TaskInitiate implements Event {
    private int type;
    private int numRounds;

    public TaskInitiate(int numRounds) {
        this.type = Protocol.TASK_INITIATE;
        this.numRounds = numRounds;
    }

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

        this.type = din.readInt();
        this.numRounds = din.readInt();

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


    @Override
    public int getType() {
        return this.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.writeInt(numRounds);

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

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

    //returns the number of rounds the messages are passed; specified with start command
    public int getNumRounds() {
        return this.numRounds;
    }
    
}