All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cocaine.msgpack.SocketAddressTemplate Maven / Gradle / Ivy

There is a newer version: 0.11.1.0
Show newest version
package cocaine.msgpack;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.msgpack.packer.Packer;
import org.msgpack.template.AbstractTemplate;
import org.msgpack.template.Template;
import org.msgpack.unpacker.Unpacker;

/**
 * @author Anton Bobukh 
 */
public final class SocketAddressTemplate extends AbstractTemplate {

    private static final Template instance = new SocketAddressTemplate();

    private SocketAddressTemplate() { }

    public static Template getInstance() {
        return instance;
    }

    @Override
    public void write(Packer packer, SocketAddress endpoint, boolean required) throws IOException {
        if (!InetSocketAddress.class.isAssignableFrom(endpoint.getClass())) {
            throw new IllegalArgumentException(endpoint.getClass().getSimpleName()
                    + " can not be encoded by " + SocketAddressTemplate.class.getSimpleName());
        }

        InetSocketAddress inetEndpoint = (InetSocketAddress) endpoint;
        packer.writeArrayBegin(2);
        packer.write(inetEndpoint.getHostName());
        packer.write(inetEndpoint.getPort());
        packer.writeArrayEnd();
    }

    @Override
    public SocketAddress read(Unpacker unpacker, SocketAddress endpoint, boolean required) throws IOException {
        unpacker.readArrayBegin();
        String host = unpacker.readString();
        int port = unpacker.readInt();
        unpacker.readArrayEnd();

        return new InetSocketAddress(host, port);
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy