001/*
002 * To change this template, choose Tools | Templates
003 * and open the template in the editor.
004 */
005package org.anarres.qemu.exec.host.chardev;
006
007import java.net.InetAddress;
008import java.net.InetSocketAddress;
009import java.util.Map;
010import javax.annotation.Nonnull;
011
012/**
013 *
014 * @author shevek
015 */
016public class TcpCharDevice extends AbstractSocketCharDevice {
017
018    private static boolean isAnyLocalAddress(@Nonnull InetSocketAddress address) {
019        if (address.getHostString() == null)
020            return true;
021        InetAddress addr = address.getAddress();
022        if (addr == null)
023            return true;
024        if (addr.isAnyLocalAddress())
025            return true;
026        return false;
027    }
028    private final InetSocketAddress address;
029    public int to = -1;
030    public boolean nodelay;
031
032    public TcpCharDevice(@Nonnull InetSocketAddress address, boolean server, boolean nowait) {
033        super("socket", server, nowait);
034        this.address = address;
035        if (address.getHostString() == null && !server)
036            throw new IllegalArgumentException("A client tcp chardev requires a hostname.");
037    }
038
039    public TcpCharDevice(InetSocketAddress address) {
040        this(address, isAnyLocalAddress(address), false);
041    }
042
043    public TcpCharDevice(int port) {
044        this(new InetSocketAddress(port));
045    }
046
047    @Nonnull
048    public InetSocketAddress getAddress() {
049        return address;
050    }
051
052    @Override
053    protected void addProperties(Map<String, Object> m) {
054        super.addProperties(m);
055        m.put("host", address.getHostString());
056        m.put("port", address.getPort());
057        if (to >= 0)
058            m.put("to", to);
059        if (nodelay)
060            m.put("nodelay", null);
061    }
062
063    @Override
064    public String toString() {
065        StringBuilder buf = new StringBuilder("tcp:");
066        buf.append(UdpCharDevice.toHostString(address))
067                .append(':').append(String.valueOf(address.getPort()));
068        if (server)
069            buf.append(",server");
070        if (nowait)
071            buf.append(",nowait");
072        if (nodelay)
073            buf.append(",nodelay");
074        return buf.toString();
075    }
076}