File D:\maven-qcr-plugin-testsunitaires\qcr4java\jenkins-master\target\site\qc\test\src\test\java\hudson\UDPBroadcastThreadTest.java.html

1 package hudson;
2
3 import org.jvnet.hudson.test.HudsonTestCase;
4 import org.xml.sax.InputSource;
5 import org.xml.sax.SAXException;
6 import org.xml.sax.helpers.DefaultHandler;
7
8 import javax.xml.parsers.SAXParserFactory;
9 import javax.xml.parsers.ParserConfigurationException;
10 import java.net.DatagramSocket;
11 import java.net.DatagramPacket;
12 import java.net.InetAddress;
13 import java.io.StringReader;
14 import java.io.IOException;
15
16 /**
17 * @author Kohsuke Kawaguchi
18 */
19 public class UDPBroadcastThreadTest extends HudsonTestCase {
20 /**
21 * Old unicast based clients should still be able to receive some reply,
22 * as we haven't changed the port.
23 */
24 public void testLegacy() throws Exception {
25 DatagramSocket s = new DatagramSocket();
26 sendQueryTo(s, InetAddress.getLocalHost());
27 s.setSoTimeout(15000); // to prevent test hang
28 receiveAndVerify(s);
29 }
30
31 /**
32 * Multicast based clients should be able to receive multiple replies.
33 */
34 public void testMulticast() throws Exception {
35 UDPBroadcastThread second = new UDPBroadcastThread(jenkins);
36 second.start();
37
38 UDPBroadcastThread third = new UDPBroadcastThread(jenkins);
39 third.start();
40
41 second.ready.block();
42 third.ready.block();
43
44 try {
45 DatagramSocket s = new DatagramSocket();
46 sendQueryTo(s, UDPBroadcastThread.MULTICAST);
47 s.setSoTimeout(15000); // to prevent test hang
48
49 // we should at least get two replies since we run two broadcasts
50 receiveAndVerify(s);
51 receiveAndVerify(s);
52 } finally {
53 third.interrupt();
54 second.interrupt();
55 }
56 }
57
58 private void sendQueryTo(DatagramSocket s, InetAddress dest) throws IOException {
59 DatagramPacket p = new DatagramPacket(new byte[1024],1024);
60 p.setAddress(dest);
61 p.setPort(UDPBroadcastThread.PORT);
62 s.send(p);
63 }
64
65 /**
66 * Reads a reply from the socket and makes sure its shape is in order.
67 */
68 private void receiveAndVerify(DatagramSocket s) throws IOException, SAXException, ParserConfigurationException {
69 DatagramPacket p = new DatagramPacket(new byte[1024],1024);
70 s.receive(p);
71 String xml = new String(p.getData(), 0, p.getLength(), "UTF-8");
72 System.out.println(xml);
73
74 // make sure at least this XML parses
75 SAXParserFactory spf = SAXParserFactory.newInstance();
76 spf.setNamespaceAware(true);
77 spf.newSAXParser().parse(new InputSource(new StringReader(xml)),new DefaultHandler());
78 }
79 }
80