View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.transport.udp.functional;
8   
9   import org.mule.tck.junit4.FunctionalTestCase;
10  import org.mule.tck.junit4.rule.DynamicPort;
11  
12  import java.io.ByteArrayInputStream;
13  import java.io.ByteArrayOutputStream;
14  import java.io.DataInputStream;
15  import java.io.DataOutputStream;
16  import java.io.IOException;
17  import java.net.DatagramPacket;
18  import java.net.DatagramSocket;
19  import java.net.InetAddress;
20  
21  import edu.emory.mathcs.backport.java.util.Arrays;
22  import org.junit.Rule;
23  import org.junit.Test;
24  
25  import static org.junit.Assert.assertEquals;
26  
27  public class UdpRoundTripTestCase extends FunctionalTestCase
28  {
29  
30      @Rule
31      public DynamicPort outPort = new DynamicPort("outPort");
32  
33      @Rule
34      public DynamicPort inPort = new DynamicPort("inPort");
35  
36      @Override
37      protected String getConfigResources()
38      {
39          return "udp-roundtrip-test-config.xml";
40      }
41  
42      @Test
43      public void testSendAndReceiveUDP() throws IOException
44      {
45          // the socket we talk to
46          DatagramSocket socket = new DatagramSocket(inPort.getNumber(), InetAddress.getLocalHost());
47  
48          // prepare outgoing packet
49          ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
50          DataOutputStream dataOut = new DataOutputStream(bytesOut);
51          dataOut.writeFloat(1.0f);
52          dataOut.writeFloat(2.0f);
53          byte[] bytesToSend = bytesOut.toByteArray();
54  
55          DatagramPacket outboundPacket = new DatagramPacket(bytesToSend, bytesToSend.length,
56              InetAddress.getLocalHost(), outPort.getNumber());
57          socket.send(outboundPacket);
58  
59          // receive whatever came back
60          byte[] receiveBuffer = new byte[bytesToSend.length];
61          DatagramPacket inboundPacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
62          socket.receive(inboundPacket);
63  
64          // compare byte buffers as strings so we get to see the diff
65          assertEquals(Arrays.toString(outboundPacket.getData()), Arrays.toString(inboundPacket.getData()));
66  
67          // make sure the contents are really the same
68          ByteArrayInputStream bytesIn = new ByteArrayInputStream(inboundPacket.getData());
69          DataInputStream dataIn = new DataInputStream(bytesIn);
70          // the delta is only here to make JUnit happy
71          assertEquals(1.0f, dataIn.readFloat(), 0.1f);
72          assertEquals(2.0f, dataIn.readFloat(), 0.1f);
73      }
74  
75  }