Search in sources :

Example 26 with DatagramSocket

use of java.net.DatagramSocket in project hadoop by apache.

the class TestStatsDMetrics method testPutMetrics2.

@Test(timeout = 3000)
public void testPutMetrics2() throws IOException {
    StatsDSink sink = new StatsDSink();
    List<MetricsTag> tags = new ArrayList<MetricsTag>();
    tags.add(new MetricsTag(MsInfo.Hostname, null));
    tags.add(new MetricsTag(MsInfo.Context, "jvm"));
    tags.add(new MetricsTag(MsInfo.ProcessName, "process"));
    Set<AbstractMetric> metrics = new HashSet<AbstractMetric>();
    metrics.add(makeMetric("foo1", 1, MetricType.COUNTER));
    metrics.add(makeMetric("foo2", 2, MetricType.GAUGE));
    MetricsRecord record = new MetricsRecordImpl(MsInfo.Context, (long) 10000, tags, metrics);
    try (DatagramSocket sock = new DatagramSocket()) {
        sock.setReceiveBufferSize(8192);
        final StatsDSink.StatsD mockStatsD = new StatsD(sock.getLocalAddress().getHostName(), sock.getLocalPort());
        Whitebox.setInternalState(sink, "statsd", mockStatsD);
        final DatagramPacket p = new DatagramPacket(new byte[8192], 8192);
        sink.putMetrics(record);
        sock.receive(p);
        String result = new String(p.getData(), 0, p.getLength(), Charset.forName("UTF-8"));
        assertTrue("Received data did not match data sent", result.equals("process.jvm.Context.foo1:1|c") || result.equals("process.jvm.Context.foo2:2|g"));
    } finally {
        sink.close();
    }
}
Also used : StatsDSink(org.apache.hadoop.metrics2.sink.StatsDSink) MetricsRecord(org.apache.hadoop.metrics2.MetricsRecord) ArrayList(java.util.ArrayList) AbstractMetric(org.apache.hadoop.metrics2.AbstractMetric) MetricsTag(org.apache.hadoop.metrics2.MetricsTag) StatsD(org.apache.hadoop.metrics2.sink.StatsDSink.StatsD) DatagramSocket(java.net.DatagramSocket) StatsD(org.apache.hadoop.metrics2.sink.StatsDSink.StatsD) DatagramPacket(java.net.DatagramPacket) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 27 with DatagramSocket

use of java.net.DatagramSocket in project hadoop by apache.

the class TestGangliaSink method testShouldCreateDatagramSocketByDefault.

@Test
public void testShouldCreateDatagramSocketByDefault() throws Exception {
    SubsetConfiguration conf = new ConfigBuilder().subset("test.sink.ganglia");
    GangliaSink30 gangliaSink = new GangliaSink30();
    gangliaSink.init(conf);
    DatagramSocket socket = gangliaSink.getDatagramSocket();
    assertFalse("Did not create DatagramSocket", socket == null || socket instanceof MulticastSocket);
}
Also used : MulticastSocket(java.net.MulticastSocket) DatagramSocket(java.net.DatagramSocket) ConfigBuilder(org.apache.hadoop.metrics2.impl.ConfigBuilder) SubsetConfiguration(org.apache.commons.configuration2.SubsetConfiguration) Test(org.junit.Test)

Example 28 with DatagramSocket

use of java.net.DatagramSocket in project hadoop by apache.

the class TestGangliaSink method testShouldCreateDatagramSocketIfMulticastIsDisabled.

@Test
public void testShouldCreateDatagramSocketIfMulticastIsDisabled() throws Exception {
    SubsetConfiguration conf = new ConfigBuilder().add("test.sink.ganglia.multicast", false).subset("test.sink.ganglia");
    GangliaSink30 gangliaSink = new GangliaSink30();
    gangliaSink.init(conf);
    DatagramSocket socket = gangliaSink.getDatagramSocket();
    assertFalse("Did not create DatagramSocket", socket == null || socket instanceof MulticastSocket);
}
Also used : MulticastSocket(java.net.MulticastSocket) DatagramSocket(java.net.DatagramSocket) ConfigBuilder(org.apache.hadoop.metrics2.impl.ConfigBuilder) SubsetConfiguration(org.apache.commons.configuration2.SubsetConfiguration) Test(org.junit.Test)

Example 29 with DatagramSocket

use of java.net.DatagramSocket in project hadoop by apache.

the class SimpleUdpClient method run.

public void run() throws IOException {
    InetAddress IPAddress = InetAddress.getByName(host);
    byte[] sendData = request.getBytes();
    byte[] receiveData = new byte[65535];
    // Use the provided socket if there is one, else just make a new one.
    DatagramSocket socket = this.clientSocket == null ? new DatagramSocket() : this.clientSocket;
    try {
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
        socket.send(sendPacket);
        socket.setSoTimeout(udpTimeoutMillis);
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        socket.receive(receivePacket);
        // Check reply status
        XDR xdr = new XDR(Arrays.copyOfRange(receiveData, 0, receivePacket.getLength()));
        RpcReply reply = RpcReply.read(xdr);
        if (reply.getState() != RpcReply.ReplyState.MSG_ACCEPTED) {
            throw new IOException("Request failed: " + reply.getState());
        }
    } finally {
        // caller of this UDP client to close that socket.
        if (this.clientSocket == null) {
            socket.close();
        }
    }
}
Also used : DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) IOException(java.io.IOException) InetAddress(java.net.InetAddress)

Example 30 with DatagramSocket

use of java.net.DatagramSocket in project Genius-Android by qiujuer.

the class DnsResolve method resolve.

/**
     * This resolve domain to ips
     *
     * @param domain    Domain Name
     * @param dnsServer DNS Server
     * @return IPs
     */
private ArrayList<String> resolve(String domain, InetAddress dnsServer) {
    // Pointer
    int pos = 12;
    // Cmd buffer
    byte[] sendBuffer = new byte[100];
    // Message head
    sendBuffer[0] = ID[0];
    sendBuffer[1] = ID[1];
    sendBuffer[2] = 0x01;
    sendBuffer[3] = 0x00;
    sendBuffer[4] = 0x00;
    sendBuffer[5] = 0x01;
    sendBuffer[6] = 0x00;
    sendBuffer[7] = 0x00;
    sendBuffer[8] = 0x00;
    sendBuffer[9] = 0x00;
    sendBuffer[10] = 0x00;
    sendBuffer[11] = 0x00;
    // Add domain
    String[] part = domain.split("\\.");
    for (String s : part) {
        if (s == null || s.length() <= 0)
            continue;
        int sLength = s.length();
        sendBuffer[pos++] = (byte) sLength;
        int i = 0;
        char[] val = s.toCharArray();
        while (i < sLength) {
            sendBuffer[pos++] = (byte) val[i++];
        }
    }
    // 0 end
    sendBuffer[pos++] = 0x00;
    sendBuffer[pos++] = 0x00;
    // 1 A record query
    sendBuffer[pos++] = 0x01;
    sendBuffer[pos++] = 0x00;
    // Internet record query
    sendBuffer[pos++] = 0x01;
    /**
         * UDP Send
         */
    DatagramSocket ds = null;
    byte[] receiveBuffer = null;
    try {
        ds = new DatagramSocket();
        ds.setSoTimeout(TIME_OUT);
        // Send
        DatagramPacket dp = new DatagramPacket(sendBuffer, pos, dnsServer, 53);
        ds.send(dp);
        // Receive
        dp = new DatagramPacket(new byte[512], 512);
        ds.receive(dp);
        // Copy
        int len = dp.getLength();
        receiveBuffer = new byte[len];
        System.arraycopy(dp.getData(), 0, receiveBuffer, 0, len);
    } catch (UnknownHostException e) {
        mError = Cmd.UNKNOWN_HOST_ERROR;
    } catch (SocketException e) {
        mError = Cmd.NETWORK_SOCKET_ERROR;
        e.printStackTrace();
    } catch (IOException e) {
        mError = Cmd.NETWORK_IO_ERROR;
        e.printStackTrace();
    } finally {
        if (ds != null) {
            try {
                ds.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    // Check is return
    if (mError != Cmd.SUCCEED || receiveBuffer == null)
        return null;
    // ID
    if (receiveBuffer[0] != ID[0] || receiveBuffer[1] != ID[1] || (receiveBuffer[2] & 0x80) != 0x80)
        return null;
    // Count
    int queryCount = (receiveBuffer[4] << 8) | receiveBuffer[5];
    if (queryCount == 0)
        return null;
    int answerCount = (receiveBuffer[6] << 8) | receiveBuffer[7];
    if (answerCount == 0)
        return null;
    // Pointer restore
    pos = 12;
    // Skip the query part head
    for (int i = 0; i < queryCount; i++) {
        while (receiveBuffer[pos] != 0x00) {
            pos += receiveBuffer[pos] + 1;
        }
        pos += 5;
    }
    // Get ip form data
    ArrayList<String> iPs = new ArrayList<>();
    for (int i = 0; i < answerCount; i++) {
        if (receiveBuffer[pos] == (byte) 0xC0) {
            pos += 2;
        } else {
            while (receiveBuffer[pos] != (byte) 0x00) {
                pos += receiveBuffer[pos] + 1;
            }
            pos++;
        }
        byte queryType = (byte) (receiveBuffer[pos] << 8 | receiveBuffer[pos + 1]);
        pos += 8;
        int dataLength = (receiveBuffer[pos] << 8 | receiveBuffer[pos + 1]);
        pos += 2;
        // Add ip
        if (queryType == (byte) 0x01) {
            int[] address = new int[4];
            for (int n = 0; n < 4; n++) {
                address[n] = receiveBuffer[pos + n];
                if (address[n] < 0)
                    address[n] += 256;
            }
            iPs.add(String.format("%s.%s.%s.%S", address[0], address[1], address[2], address[3]));
        }
        pos += dataLength;
    }
    return iPs;
}
Also used : SocketException(java.net.SocketException) UnknownHostException(java.net.UnknownHostException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) SocketException(java.net.SocketException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket)

Aggregations

DatagramSocket (java.net.DatagramSocket)294 DatagramPacket (java.net.DatagramPacket)137 IOException (java.io.IOException)112 SocketException (java.net.SocketException)74 InetAddress (java.net.InetAddress)63 InetSocketAddress (java.net.InetSocketAddress)46 UnknownHostException (java.net.UnknownHostException)33 Test (org.junit.Test)27 SocketTimeoutException (java.net.SocketTimeoutException)24 InterruptedIOException (java.io.InterruptedIOException)18 PortUnreachableException (java.net.PortUnreachableException)18 ServerSocket (java.net.ServerSocket)18 BindException (java.net.BindException)16 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)16 DatagramChannel (java.nio.channels.DatagramChannel)14 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)11 MulticastSocket (java.net.MulticastSocket)10 SocketAddress (java.net.SocketAddress)9 ByteBuffer (java.nio.ByteBuffer)8 ArrayList (java.util.ArrayList)6