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.InetSocketAddress;
008import java.util.Map;
009import javax.annotation.CheckForNull;
010import javax.annotation.Nonnull;
011
012/**
013 *
014 * @author shevek
015 */
016public class UdpCharDevice extends AbstractCharDevice {
017
018    private final InetSocketAddress remoteAddress;
019    private final InetSocketAddress localAddress;
020
021    public UdpCharDevice(@Nonnull InetSocketAddress remoteAddress, @CheckForNull InetSocketAddress localAddress) {
022        super("udp");
023        this.remoteAddress = remoteAddress;
024        this.localAddress = localAddress;
025    }
026
027    public UdpCharDevice(@Nonnull InetSocketAddress remoteAddress) {
028        this(remoteAddress, null);
029    }
030
031    @Override
032    protected void addProperties(Map<String, Object> m) {
033        super.addProperties(m);
034        String remoteHost = remoteAddress.getHostString();
035        if (remoteHost != null)
036            m.put("host", remoteHost);
037        m.put("port", remoteAddress.getPort());
038        if (localAddress != null) {
039            String localHost = localAddress.getHostString();
040            if (localHost != null)
041                m.put("localaddr", localHost);
042            m.put("localport", localAddress.getPort());
043        }
044    }
045
046    @Nonnull
047    public static String toHostString(@Nonnull InetSocketAddress address) {
048        String text = address.getHostString();
049        if (text != null)
050            return text;
051        return "";
052    }
053
054    @Override
055    public String toString() {
056        StringBuilder buf = new StringBuilder("udp:");
057        buf.append(toHostString(remoteAddress))
058                .append(':').append(String.valueOf(remoteAddress.getPort()));
059        if (localAddress != null) {
060            buf.append('@').append(toHostString(localAddress))
061                    .append(':').append(String.valueOf(localAddress.getPort()));
062        }
063        return buf.toString();
064    }
065}