DS-Lab / src / main / java / dslab / rmi / serialize / Serializer.java
Serializer.java
Raw
package dslab.rmi.serialize;

import dslab.protocol.ProtocolException;
import dslab.routing.Address;
import dslab.routing.Domain;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import static java.lang.Integer.valueOf;
import static java.lang.String.join;

/**
 * Serializer classes translate objects into their string representations that are fit to be sent over
 * TCP/UDP ("serialization"), and translate those strings back into their object representation at the
 * other end of the TCP/UDP channel ("deserialization").
 */
public class Serializer {

    protected StringTokenizer tokenizer;

    //UTILITY METHODS

    protected String arg(String name) throws ParseException {
        if (!tokenizer.hasMoreTokens())
            throw new MissingArgumentException(name);
        return tokenizer.nextToken();
    }

    protected Integer intArg(String name) throws ParseException {
        var value = arg(name);
        try {
            return valueOf(value);
        } catch (NumberFormatException e) {
            throw new ParseException("expected " + name + "to be integer, but got '" + value + "'");
        }
    }

    protected List<String> varArg(String name) throws ParseException {

        var list = new ArrayList<String>();

        if (!tokenizer.hasMoreTokens()) //if the arg is empty, that's an error.
            throw new MissingArgumentException(name);
        else
            list.add(tokenizer.nextToken(", "));

        while (tokenizer.hasMoreTokens())
            list.add(tokenizer.nextToken());

        return list;
    }

    /**
     * @throws ParseException if there are tokens left in the response
     */
    protected void assertEndOfLine() throws ParseException {
        if (tokenizer.hasMoreTokens())
            throw new ParseException("expected EOL but found " +
                    "additional token '" + tokenizer.nextToken() + "'");
    }

    protected String oneOrMoreRemainingAsString(String name) throws ProtocolException {

        var result = zeroOrMoreRemainingAsString(name);

        if (result.isEmpty())
            throw new MissingArgumentException(name);

        return result;
    }

    protected String zeroOrMoreRemainingAsString(String name) {

        var list = new ArrayList<String>();
        while (tokenizer.hasMoreTokens())
            list.add(tokenizer.nextToken());

        return join(" ", list);
    }

    public Address parseAddress(String address) throws ParseException {

        int atIndex = address.lastIndexOf("@");

        var ex = new ParseException("invalid email address");

        if (atIndex == -1) throw ex;

        String user = address.substring(0, atIndex);
        String domain = address.substring(atIndex + 1);

        if (user.isEmpty() || domain.isEmpty()) throw ex;

        return new Address(user, new Domain(domain));
    }
}