Example usage for java.net SocketAddress toString

List of usage examples for java.net SocketAddress toString

Introduction

In this page you can find the example usage for java.net SocketAddress toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:com.navercorp.pinpoint.plugin.thrift.ThriftUtils.java

private static String getSocketAddress(SocketAddress socketAddress) {
    String address = socketAddress.toString();
    int addressLength = address.length();

    if (addressLength > 0) {
        if (address.startsWith("/")) {
            return address.substring(1);
        } else {// w ww .j a v a2s .  c om
            int delimeterIndex = address.indexOf("/");
            if (delimeterIndex != -1 && delimeterIndex < addressLength) {
                return address.substring(address.indexOf("/") + 1);
            }
        }
    }
    return address;
}

From source file:com.couchbase.spring.monitor.ClientInfo.java

@ManagedAttribute(description = "Hostnames of connected nodes")
public String getHostNames() {
    StringBuilder result = new StringBuilder();
    for (SocketAddress node : getStats().keySet()) {
        result.append(node.toString()).append(",");
    }/*from   ww  w .j  a  va  2s . com*/
    return result.toString();
}

From source file:io.github.gsteckman.rpi_rest.SsdpHandler.java

private void sendResponse(final SocketAddress addr) {
    if (!(addr instanceof InetSocketAddress)) {
        LOG.warn("Don't know how to handle non Internet addresses");
        return;/* w  w  w .j  ava  2  s.c o m*/
    }
    DatagramSocket sock = null;
    LOG.debug("Responding to " + addr.toString());

    try {
        sock = new DatagramSocket();
        sock.connect(addr);
        byte[] ba = generateSearchResponse().getBytes();
        sock.send(new DatagramPacket(ba, ba.length));
    } catch (IOException e) {
        LOG.error(e.getMessage());
    } finally {
        if (sock != null) {
            sock.close();
        }
    }
}

From source file:org.apache.axis2.transport.nhttp.HttpCoreNIOSSLSender.java

protected SSLIOSessionHandler getSSLIOSessionHandler(TransportOutDescription transportOut) throws AxisFault {

    final Parameter hostnameVerifier = transportOut.getParameter("HostnameVerifier");

    return new SSLIOSessionHandler() {

        public void initalize(SSLEngine sslengine, HttpParams params) {
        }//from  ww  w.  j av a 2  s  .co m

        public void verify(SocketAddress remoteAddress, SSLSession session) throws SSLException {

            String address = null;
            if (remoteAddress instanceof InetSocketAddress) {
                address = ((InetSocketAddress) remoteAddress).getHostName();
            } else {
                address = remoteAddress.toString();
            }

            boolean valid = false;
            if (hostnameVerifier != null) {
                if ("Strict".equals(hostnameVerifier.getValue())) {
                    valid = HostnameVerifier.STRICT.verify(address, session);
                } else if ("AllowAll".equals(hostnameVerifier.getValue())) {
                    valid = HostnameVerifier.ALLOW_ALL.verify(address, session);
                } else if ("DefaultAndLocalhost".equals(hostnameVerifier.getValue())) {
                    valid = HostnameVerifier.DEFAULT_AND_LOCALHOST.verify(address, session);
                }
            } else {
                valid = HostnameVerifier.DEFAULT.verify(address, session);
            }

            if (!valid) {
                throw new SSLException("Host name verification failed for host : " + address);
            }
        }
    };
}

From source file:com.alibaba.dragoon.client.DragoonClient.java

public String getAgentAddress() {
    SocketAddress address = this.connectorFilter.getServerAddress();

    if (address != null) {
        return address.toString();
    }//from w  w  w .ja v a2s .c  o  m

    return null;
}

From source file:com.twitter.distributedlog.client.proxy.TestProxyClientManager.java

@Test(timeout = 60000)
public void testHandshake() throws Exception {
    final int numHosts = 3;
    final int numStreamsPerHost = 3;
    final int initialPort = 4000;

    MockProxyClientBuilder builder = new MockProxyClientBuilder();
    Map<SocketAddress, ServerInfo> serverInfoMap = new HashMap<SocketAddress, ServerInfo>();
    for (int i = 0; i < numHosts; i++) {
        SocketAddress address = createSocketAddress(initialPort + i);
        ServerInfo serverInfo = new ServerInfo();
        for (int j = 0; j < numStreamsPerHost; j++) {
            serverInfo.putToOwnerships(runtime.getMethodName() + "_stream_" + j, address.toString());
        }/*ww  w .j a  v  a  2s.  co  m*/
        Pair<MockProxyClient, MockServerInfoService> mockProxyClient = createMockProxyClient(address,
                serverInfo);
        builder.provideProxyClient(address, mockProxyClient.getLeft());
        serverInfoMap.put(address, serverInfo);
    }

    final Map<SocketAddress, ServerInfo> results = new HashMap<SocketAddress, ServerInfo>();
    final CountDownLatch doneLatch = new CountDownLatch(2 * numHosts);
    ProxyListener listener = new ProxyListener() {
        @Override
        public void onHandshakeSuccess(SocketAddress address, ProxyClient client, ServerInfo serverInfo) {
            synchronized (results) {
                results.put(address, serverInfo);
            }
            doneLatch.countDown();
        }

        @Override
        public void onHandshakeFailure(SocketAddress address, ProxyClient client, Throwable cause) {
        }
    };

    TestHostProvider rs = new TestHostProvider();
    ProxyClientManager clientManager = createProxyClientManager(builder, rs, 0L);
    clientManager.registerProxyListener(listener);
    assertEquals("There should be no clients in the manager", 0, clientManager.getNumProxies());
    for (int i = 0; i < numHosts; i++) {
        rs.addHost(createSocketAddress(initialPort + i));
    }
    // handshake would handshake with 3 hosts again
    clientManager.handshake();
    doneLatch.await();
    assertEquals("Handshake should return server info", numHosts, results.size());
    assertTrue("Handshake should get all server infos", Maps.difference(serverInfoMap, results).areEqual());
}

From source file:com.twitter.distributedlog.client.proxy.TestProxyClientManager.java

@Test(timeout = 60000)
public void testPeriodicHandshake() throws Exception {
    final int numHosts = 3;
    final int numStreamsPerHost = 3;
    final int initialPort = 5000;

    MockProxyClientBuilder builder = new MockProxyClientBuilder();
    Map<SocketAddress, ServerInfo> serverInfoMap = new HashMap<SocketAddress, ServerInfo>();
    Map<SocketAddress, MockServerInfoService> mockServiceMap = new HashMap<SocketAddress, MockServerInfoService>();
    final Map<SocketAddress, CountDownLatch> hostDoneLatches = new HashMap<SocketAddress, CountDownLatch>();
    for (int i = 0; i < numHosts; i++) {
        SocketAddress address = createSocketAddress(initialPort + i);
        ServerInfo serverInfo = new ServerInfo();
        for (int j = 0; j < numStreamsPerHost; j++) {
            serverInfo.putToOwnerships(runtime.getMethodName() + "_stream_" + j, address.toString());
        }// ww w.  j  a v  a  2s.c  om
        Pair<MockProxyClient, MockServerInfoService> mockProxyClient = createMockProxyClient(address,
                serverInfo);
        builder.provideProxyClient(address, mockProxyClient.getLeft());
        serverInfoMap.put(address, serverInfo);
        mockServiceMap.put(address, mockProxyClient.getRight());
        hostDoneLatches.put(address, new CountDownLatch(2));
    }

    final Map<SocketAddress, ServerInfo> results = new HashMap<SocketAddress, ServerInfo>();
    final CountDownLatch doneLatch = new CountDownLatch(numHosts);
    ProxyListener listener = new ProxyListener() {
        @Override
        public void onHandshakeSuccess(SocketAddress address, ProxyClient client, ServerInfo serverInfo) {
            synchronized (results) {
                results.put(address, serverInfo);
                CountDownLatch latch = hostDoneLatches.get(address);
                if (null != latch) {
                    latch.countDown();
                }
            }
            doneLatch.countDown();
        }

        @Override
        public void onHandshakeFailure(SocketAddress address, ProxyClient client, Throwable cause) {
        }
    };

    TestHostProvider rs = new TestHostProvider();
    ProxyClientManager clientManager = createProxyClientManager(builder, rs, 50L);
    clientManager.setPeriodicHandshakeEnabled(false);
    clientManager.registerProxyListener(listener);

    assertEquals("There should be no clients in the manager", 0, clientManager.getNumProxies());
    for (int i = 0; i < numHosts; i++) {
        SocketAddress address = createSocketAddress(initialPort + i);
        rs.addHost(address);
        clientManager.createClient(address);
    }

    // make sure the first 3 handshakes going through
    doneLatch.await();

    assertEquals("Handshake should return server info", numHosts, results.size());
    assertTrue("Handshake should get all server infos", Maps.difference(serverInfoMap, results).areEqual());

    // update server info
    for (int i = 0; i < numHosts; i++) {
        SocketAddress address = createSocketAddress(initialPort + i);
        ServerInfo serverInfo = new ServerInfo();
        for (int j = 0; j < numStreamsPerHost; j++) {
            serverInfo.putToOwnerships(runtime.getMethodName() + "_new_stream_" + j, address.toString());
        }
        MockServerInfoService service = mockServiceMap.get(address);
        serverInfoMap.put(address, serverInfo);
        service.updateServerInfo(serverInfo);
    }

    clientManager.setPeriodicHandshakeEnabled(true);
    for (int i = 0; i < numHosts; i++) {
        SocketAddress address = createSocketAddress(initialPort + i);
        CountDownLatch latch = hostDoneLatches.get(address);
        latch.await();
    }

    assertTrue("Periodic handshake should update all server infos",
            Maps.difference(serverInfoMap, results).areEqual());
}

From source file:gridool.util.xfer.TransferUtils.java

public static void send(@Nonnull final FastByteArrayOutputStream data, @Nonnull final String fileName,
        @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort,
        final boolean append, final boolean sync, @Nullable final TransferClientHandler handler)
        throws IOException {
    final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort);
    SocketChannel channel = null;
    Socket socket = null;//from www  . j  ava  2 s  . c om
    final OutputStream out;
    try {
        channel = SocketChannel.open();
        socket = channel.socket();
        socket.connect(dstSockAddr);
        out = socket.getOutputStream();
    } catch (IOException e) {
        LOG.error("failed to connect: " + dstSockAddr, e);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
        throw e;
    }

    DataInputStream din = null;
    if (sync) {
        InputStream in = socket.getInputStream();
        din = new DataInputStream(in);
    }
    final DataOutputStream dos = new DataOutputStream(out);
    final StopWatch sw = new StopWatch();
    try {
        IOUtils.writeString(fileName, dos);
        IOUtils.writeString(writeDirPath, dos);
        long nbytes = data.size();
        dos.writeLong(nbytes);
        dos.writeBoolean(append);
        dos.writeBoolean(sync);
        if (handler == null) {
            dos.writeBoolean(false);
        } else {
            dos.writeBoolean(true);
            handler.writeAdditionalHeader(dos);
        }

        // send file using zero-copy send
        data.writeTo(out);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Sent a file data '" + fileName + "' of " + nbytes + " bytes to " + dstSockAddr.toString()
                    + " in " + sw.toString());
        }

        if (sync) {// receive ack in sync mode
            long remoteRecieved = din.readLong();
            if (remoteRecieved != nbytes) {
                throw new IllegalStateException(
                        "Sent " + nbytes + " bytes, but remote node received " + remoteRecieved + " bytes");
            }
        }
    } catch (FileNotFoundException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } finally {
        IOUtils.closeQuietly(din, dos);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
    }
}

From source file:gridool.util.xfer.TransferUtils.java

public static void sendfile(@Nonnull final File file, final long fromPos, final long count,
        @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort,
        final boolean append, final boolean sync, @Nonnull final TransferClientHandler handler)
        throws IOException {
    if (!file.exists()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " does not exist");
    }/* ww  w .  j  a  va 2  s .  c o m*/
    if (!file.isFile()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " is not file");
    }
    if (!file.canRead()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " cannot read");
    }

    final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort);
    SocketChannel channel = null;
    Socket socket = null;
    final OutputStream out;
    try {
        channel = SocketChannel.open();
        socket = channel.socket();
        socket.connect(dstSockAddr);
        out = socket.getOutputStream();
    } catch (IOException e) {
        LOG.error("failed to connect: " + dstSockAddr, e);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
        throw e;
    }

    DataInputStream din = null;
    if (sync) {
        InputStream in = socket.getInputStream();
        din = new DataInputStream(in);
    }
    final DataOutputStream dos = new DataOutputStream(out);
    final StopWatch sw = new StopWatch();
    FileInputStream src = null;
    final long nbytes;
    try {
        src = new FileInputStream(file);
        FileChannel fc = src.getChannel();

        String fileName = file.getName();
        IOUtils.writeString(fileName, dos);
        IOUtils.writeString(writeDirPath, dos);
        long xferBytes = (count == -1L) ? fc.size() : count;
        dos.writeLong(xferBytes);
        dos.writeBoolean(append); // append=false
        dos.writeBoolean(sync);
        if (handler == null) {
            dos.writeBoolean(false);
        } else {
            dos.writeBoolean(true);
            handler.writeAdditionalHeader(dos);
        }

        // send file using zero-copy send
        nbytes = fc.transferTo(fromPos, xferBytes, channel);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sent a file '" + file.getAbsolutePath() + "' of " + nbytes + " bytes to "
                    + dstSockAddr.toString() + " in " + sw.toString());
        }

        if (sync) {// receive ack in sync mode
            long remoteRecieved = din.readLong();
            if (remoteRecieved != xferBytes) {
                throw new IllegalStateException(
                        "Sent " + xferBytes + " bytes, but remote node received " + remoteRecieved + " bytes");
            }
        }

    } catch (FileNotFoundException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } finally {
        IOUtils.closeQuietly(src);
        IOUtils.closeQuietly(din, dos);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
    }
}