1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.limmen.crs.client.locator;
17
18 import java.io.IOException;
19 import java.net.InetAddress;
20 import java.net.NetworkInterface;
21 import java.net.UnknownHostException;
22 import java.util.Enumeration;
23
24 import javax.jmdns.JmDNS;
25 import javax.jmdns.ServiceInfo;
26
27 import org.limmen.crs.Constants;
28
29 public class MDNSServiceLocator implements ServiceLocator {
30
31 public MDNSServiceLocator() {
32
33 super();
34 }
35
36 @Override
37 public Service locate() throws ServiceLocatorException {
38
39 JmDNS jmdns = null;
40 String hostname = null;
41 int port = 0;
42 String contextPath = null;
43
44 try {
45
46 Enumeration<NetworkInterface> addressesEnum =
47 NetworkInterface.getNetworkInterfaces();
48
49 InetAddress inetAddress = addressesEnum.nextElement().getInetAddresses().nextElement();
50
51 while (addressesEnum.hasMoreElements()
52 && inetAddress.isLoopbackAddress()) {
53
54 inetAddress = addressesEnum.nextElement().getInetAddresses().nextElement();
55
56 }
57
58 jmdns = new JmDNS(inetAddress);
59
60 ServiceInfo serviceInfo = jmdns.getServiceInfo(
61 Constants.ZERO_CONF_SERVICE_TYPE,
62 Constants.ZERO_CONF_SERVICE_NAME,
63 10000);
64
65 if (serviceInfo != null) {
66
67 hostname = serviceInfo.getHostAddress();
68
69 port = serviceInfo.getPort();
70
71 contextPath = new String(
72 serviceInfo.getPropertyBytes(
73 Constants.SERVICE_CONTEXTPATH_PROPERTY));
74 }
75 else {
76
77 throw new ServiceLocatorException(
78 "CRS Service could not be located.");
79 }
80 }
81 catch (UnknownHostException uhe) {
82
83 throw new ServiceLocatorException(uhe);
84 }
85 catch (IOException ioe) {
86
87 throw new ServiceLocatorException(ioe);
88 }
89 finally {
90
91 jmdns.close();
92 }
93
94 return new Service(hostname, port, contextPath);
95 }
96 }