use of javax.jmdns.ServiceInfo in project JAirPort by froks.
the class JmmDNSImpl method list.
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#list(java.lang.String, long)
*/
@Override
public ServiceInfo[] list(final String type, final long timeout) {
// We need to run this in parallel to respect the timeout.
final Set<ServiceInfo> result = Collections.synchronizedSet(new HashSet<ServiceInfo>(_knownMDNS.size() * 5));
ExecutorService executor = Executors.newCachedThreadPool();
for (final JmDNS mDNS : _knownMDNS.values()) {
executor.submit(new Runnable() {
/**
* {@inheritDoc}
*/
@Override
public void run() {
result.addAll(Arrays.asList(mDNS.list(type, timeout)));
}
});
}
executor.shutdown();
try {
executor.awaitTermination(timeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException exception) {
logger.log(Level.WARNING, "Exception ", exception);
}
return result.toArray(new ServiceInfo[result.size()]);
}
use of javax.jmdns.ServiceInfo in project cordova-plugin-zeroconf by becvert.
the class ZeroConf method execute.
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) {
if (ACTION_GET_HOSTNAME.equals(action)) {
if (hostname != null) {
Log.d(TAG, "Hostname: " + hostname);
callbackContext.success(hostname);
} else {
callbackContext.error("Error: undefined hostname");
return false;
}
} else if (ACTION_REGISTER.equals(action)) {
final String type = args.optString(0);
final String domain = args.optString(1);
final String name = args.optString(2);
final int port = args.optInt(3);
final JSONObject props = args.optJSONObject(4);
final String addressFamily = args.optString(5);
Log.d(TAG, "Register " + type + domain);
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
if (registrationManager == null) {
List<InetAddress> selectedAddresses = addresses;
if ("ipv6".equalsIgnoreCase(addressFamily)) {
selectedAddresses = ipv6Addresses;
} else if ("ipv4".equalsIgnoreCase(addressFamily)) {
selectedAddresses = ipv4Addresses;
}
registrationManager = new RegistrationManager(selectedAddresses, hostname);
}
ServiceInfo service = registrationManager.register(type, domain, name, port, props);
if (service == null) {
callbackContext.error("Failed to register");
return;
}
JSONObject status = new JSONObject();
status.put("action", "registered");
status.put("service", jsonifyService(service));
Log.d(TAG, "Sending result: " + status.toString());
PluginResult result = new PluginResult(PluginResult.Status.OK, status);
callbackContext.sendPluginResult(result);
} catch (JSONException e) {
Log.e(TAG, e.getMessage(), e);
callbackContext.error("Error: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
callbackContext.error("Error: " + e.getMessage());
} catch (RuntimeException e) {
Log.e(TAG, e.getMessage(), e);
callbackContext.error("Error: " + e.getMessage());
}
}
});
} else if (ACTION_UNREGISTER.equals(action)) {
final String type = args.optString(0);
final String domain = args.optString(1);
final String name = args.optString(2);
Log.d(TAG, "Unregister " + type + domain);
if (registrationManager != null) {
final RegistrationManager rm = registrationManager;
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
rm.unregister(type, domain, name);
callbackContext.success();
}
});
} else {
callbackContext.success();
}
} else if (ACTION_STOP.equals(action)) {
Log.d(TAG, "Stop");
if (registrationManager != null) {
final RegistrationManager rm = registrationManager;
registrationManager = null;
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
rm.stop();
callbackContext.success();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
callbackContext.error("Error: " + e.getMessage());
}
}
});
} else {
callbackContext.success();
}
} else if (ACTION_WATCH.equals(action)) {
final String type = args.optString(0);
final String domain = args.optString(1);
final String addressFamily = args.optString(2);
Log.d(TAG, "Watch " + type + domain);
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
if (browserManager == null) {
List<InetAddress> selectedAddresses = addresses;
if ("ipv6".equalsIgnoreCase(addressFamily)) {
selectedAddresses = ipv6Addresses;
} else if ("ipv4".equalsIgnoreCase(addressFamily)) {
selectedAddresses = ipv4Addresses;
}
browserManager = new BrowserManager(selectedAddresses, hostname);
}
browserManager.watch(type, domain, callbackContext);
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
callbackContext.error("Error: " + e.getMessage());
} catch (RuntimeException e) {
Log.e(TAG, e.getMessage(), e);
callbackContext.error("Error: " + e.getMessage());
}
}
});
PluginResult result = new PluginResult(Status.NO_RESULT);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
} else if (ACTION_UNWATCH.equals(action)) {
final String type = args.optString(0);
final String domain = args.optString(1);
Log.d(TAG, "Unwatch " + type + domain);
if (browserManager != null) {
final BrowserManager bm = browserManager;
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
bm.unwatch(type, domain);
callbackContext.success();
}
});
} else {
callbackContext.success();
}
} else if (ACTION_CLOSE.equals(action)) {
Log.d(TAG, "Close");
if (browserManager != null) {
final BrowserManager bm = browserManager;
browserManager = null;
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
bm.close();
callbackContext.success();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
callbackContext.error("Error: " + e.getMessage());
}
}
});
} else {
callbackContext.success();
}
} else if (ACTION_REINIT.equals(action)) {
Log.e(TAG, "Re-Initializing");
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
onDestroy();
initialize(cordova, webView);
callbackContext.success();
Log.e(TAG, "Re-Initialization complete");
}
});
} else {
Log.e(TAG, "Invalid action: " + action);
callbackContext.error("Invalid action: " + action);
return false;
}
return true;
}
use of javax.jmdns.ServiceInfo in project leshan by eclipse.
the class LeshanServerDemo method createAndStartServer.
public static void createAndStartServer(int webPort, String localAddress, int localPort, String secureLocalAddress, int secureLocalPort, String modelsFolderPath, String redisUrl, String keyStorePath, String keyStoreType, String keyStorePass, String keyStoreAlias, String keyStoreAliasPass, Boolean publishDNSSdServices) throws Exception {
// Prepare LWM2M server
LeshanServerBuilder builder = new LeshanServerBuilder();
builder.setLocalAddress(localAddress, localPort);
builder.setLocalSecureAddress(secureLocalAddress, secureLocalPort);
builder.setEncoder(new DefaultLwM2mNodeEncoder());
LwM2mNodeDecoder decoder = new DefaultLwM2mNodeDecoder();
builder.setDecoder(decoder);
// Create CoAP Config
NetworkConfig coapConfig;
File configFile = new File(NetworkConfig.DEFAULT_FILE_NAME);
if (configFile.isFile()) {
coapConfig = new NetworkConfig();
coapConfig.load(configFile);
} else {
coapConfig = LeshanServerBuilder.createDefaultNetworkConfig();
coapConfig.store(configFile);
}
builder.setCoapConfig(coapConfig);
// connect to redis if needed
Pool<Jedis> jedis = null;
if (redisUrl != null) {
// TODO: support sentinel pool and make pool configurable
jedis = new JedisPool(new URI(redisUrl));
}
PublicKey publicKey = null;
// Set up X.509 mode
if (keyStorePath != null) {
try {
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
try (FileInputStream fis = new FileInputStream(keyStorePath)) {
keyStore.load(fis, keyStorePass == null ? null : keyStorePass.toCharArray());
List<Certificate> trustedCertificates = new ArrayList<>();
for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements(); ) {
String alias = aliases.nextElement();
if (keyStore.isCertificateEntry(alias)) {
trustedCertificates.add(keyStore.getCertificate(alias));
} else if (keyStore.isKeyEntry(alias) && alias.equals(keyStoreAlias)) {
List<X509Certificate> x509CertificateChain = new ArrayList<>();
Certificate[] certificateChain = keyStore.getCertificateChain(alias);
if (certificateChain == null || certificateChain.length == 0) {
LOG.error("Keystore alias must have a non-empty chain of X509Certificates.");
System.exit(-1);
}
for (Certificate certificate : certificateChain) {
if (!(certificate instanceof X509Certificate)) {
LOG.error("Non-X.509 certificate in alias chain is not supported: {}", certificate);
System.exit(-1);
}
x509CertificateChain.add((X509Certificate) certificate);
}
Key key = keyStore.getKey(alias, keyStoreAliasPass == null ? new char[0] : keyStoreAliasPass.toCharArray());
if (!(key instanceof PrivateKey)) {
LOG.error("Keystore alias must have a PrivateKey entry, was {}", key == null ? null : key.getClass().getName());
System.exit(-1);
}
builder.setPrivateKey((PrivateKey) key);
publicKey = keyStore.getCertificate(alias).getPublicKey();
builder.setCertificateChain(x509CertificateChain.toArray(new X509Certificate[x509CertificateChain.size()]));
}
}
builder.setTrustedCertificates(trustedCertificates.toArray(new Certificate[trustedCertificates.size()]));
}
} catch (KeyStoreException | IOException e) {
LOG.error("Unable to initialize X.509.", e);
System.exit(-1);
}
} else // Otherwise, set up RPK mode
{
try {
// Get point values
byte[] publicX = Hex.decodeHex("fcc28728c123b155be410fc1c0651da374fc6ebe7f96606e90d927d188894a73".toCharArray());
byte[] publicY = Hex.decodeHex("d2ffaa73957d76984633fc1cc54d0b763ca0559a9dff9706e9f4557dacc3f52a".toCharArray());
byte[] privateS = Hex.decodeHex("1dae121ba406802ef07c193c1ee4df91115aabd79c1ed7f4c0ef7ef6a5449400".toCharArray());
// Get Elliptic Curve Parameter spec for secp256r1
AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
algoParameters.init(new ECGenParameterSpec("secp256r1"));
ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);
// Create key specs
KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), parameterSpec);
KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec);
// Get keys
publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec);
PrivateKey privateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec);
builder.setPublicKey(publicKey);
builder.setPrivateKey(privateKey);
} catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidParameterSpecException e) {
LOG.error("Unable to initialize RPK.", e);
System.exit(-1);
}
}
// Define model provider
List<ObjectModel> models = ObjectLoader.loadDefault();
models.addAll(ObjectLoader.loadDdfResources("/models/", modelPaths));
if (modelsFolderPath != null) {
models.addAll(ObjectLoader.loadObjectsFromDir(new File(modelsFolderPath)));
}
LwM2mModelProvider modelProvider = new StaticModelProvider(models);
builder.setObjectModelProvider(modelProvider);
// Set securityStore & registrationStore
EditableSecurityStore securityStore;
if (jedis == null) {
// use file persistence
securityStore = new FileSecurityStore();
} else {
// use Redis Store
securityStore = new RedisSecurityStore(jedis);
builder.setRegistrationStore(new RedisRegistrationStore(jedis));
}
builder.setSecurityStore(securityStore);
// Create and start LWM2M server
LeshanServer lwServer = builder.build();
// Now prepare Jetty
Server server = new Server(webPort);
WebAppContext root = new WebAppContext();
root.setContextPath("/");
root.setResourceBase(LeshanServerDemo.class.getClassLoader().getResource("webapp").toExternalForm());
root.setParentLoaderPriority(true);
server.setHandler(root);
// Create Servlet
EventServlet eventServlet = new EventServlet(lwServer, lwServer.getSecuredAddress().getPort());
ServletHolder eventServletHolder = new ServletHolder(eventServlet);
root.addServlet(eventServletHolder, "/event/*");
ServletHolder clientServletHolder = new ServletHolder(new ClientServlet(lwServer, lwServer.getSecuredAddress().getPort()));
root.addServlet(clientServletHolder, "/api/clients/*");
ServletHolder securityServletHolder = new ServletHolder(new SecurityServlet(securityStore, publicKey));
root.addServlet(securityServletHolder, "/api/security/*");
ServletHolder objectSpecServletHolder = new ServletHolder(new ObjectSpecServlet(lwServer.getModelProvider()));
root.addServlet(objectSpecServletHolder, "/api/objectspecs/*");
// Register a service to DNS-SD
if (publishDNSSdServices) {
// Create a JmDNS instance
JmDNS jmdns = JmDNS.create(InetAddress.getLocalHost());
// Publish Leshan HTTP Service
ServiceInfo httpServiceInfo = ServiceInfo.create("_http._tcp.local.", "leshan", webPort, "");
jmdns.registerService(httpServiceInfo);
// Publish Leshan CoAP Service
ServiceInfo coapServiceInfo = ServiceInfo.create("_coap._udp.local.", "leshan", localPort, "");
jmdns.registerService(coapServiceInfo);
// Publish Leshan Secure CoAP Service
ServiceInfo coapSecureServiceInfo = ServiceInfo.create("_coaps._udp.local.", "leshan", secureLocalPort, "");
jmdns.registerService(coapSecureServiceInfo);
}
// Start Jetty & Leshan
lwServer.start();
server.start();
LOG.info("Web server started at {}.", server.getURI());
}
use of javax.jmdns.ServiceInfo in project ecf by eclipse.
the class JMDNSDiscoveryContainer method registerService.
/* (non-Javadoc)
* @see org.eclipse.ecf.discovery.IDiscoveryContainerAdapter#registerService(org.eclipse.ecf.discovery.IServiceInfo)
*/
public void registerService(final IServiceInfo serviceInfo) {
Assert.isNotNull(serviceInfo);
final ServiceInfo svcInfo = createServiceInfoFromIServiceInfo(serviceInfo);
checkServiceInfo(svcInfo);
try {
jmdns.registerService(svcInfo);
} catch (final IOException e) {
// $NON-NLS-1$
throw new ECFRuntimeException("Exception registering service", e);
}
}
use of javax.jmdns.ServiceInfo in project ha-bridge by bwssytems.
the class UpnpListener method startListening.
public boolean startListening() {
if (bridgeControl.isReinit() || bridgeControl.isStop()) {
log.warn("UPNP Listener exiting as reinit or stop requested....");
return false;
}
log.info("UPNP Discovery Listener starting....");
Enumeration<NetworkInterface> ifs = null;
InetSocketAddress socketAddress = new InetSocketAddress(Configuration.UPNP_MULTICAST_ADDRESS, Configuration.UPNP_DISCOVERY_PORT);
try {
ifs = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
log.error("Could not get network interfaces for this machine: " + e.getMessage());
return false;
}
InetAddress theUpnpAddress = null;
while (ifs.hasMoreElements()) {
NetworkInterface xface = ifs.nextElement();
Enumeration<InetAddress> addrs = xface.getInetAddresses();
String name = xface.getName();
int IPsPerNic = 0;
while (addrs.hasMoreElements()) {
InetAddress addr = addrs.nextElement();
log.debug(name + " ... has addr " + addr);
if (InetAddressUtils.isIPv4Address(addr.getHostAddress())) {
if (!useUpnpIface) {
if (traceupnp)
log.info("Traceupnp: Interface: " + name + " valid usable IP address: " + addr);
IPsPerNic++;
} else if (useUpnpIface && (addr.getHostAddress().equals(upnpConfigIP) || name.equals("lo"))) {
if (traceupnp)
log.info("Traceupnp: Interface: " + name + " matches upnp config address of IP address: " + addr);
IPsPerNic++;
}
if (addr.getHostAddress().equals(upnpConfigIP)) {
theUpnpAddress = addr;
}
}
}
log.debug("Checking " + name + " to our interface set");
if (IPsPerNic > 0) {
try {
upnpMulticastSocket.joinGroup(socketAddress, xface);
if (traceupnp)
log.info("Traceupnp: Adding " + name + " to our upnp join interface set.");
else
log.debug("Adding " + name + " to our interface set");
} catch (IOException e) {
log.warn("Multicast join failed for: " + socketAddress.getHostName() + " to interface: " + xface.getName() + " with message: " + e.getMessage());
}
}
}
JmDNS jmdns = null;
if (theUpnpAddress != null) {
log.info("Create and run mDNS service.");
try {
// Create a JmDNS instance
jmdns = JmDNS.create(theUpnpAddress, "Philips-hue");
// Register a service - Defined TXT keys: bridgeid, modelid
final HashMap<String, String> values = new HashMap<String, String>();
values.put("modelid", HueConstants.MODEL_ID);
values.put("bridgeid", bridgeId);
ServiceInfo serviceInfo = ServiceInfo.create("_hue._tcp.local.", "Philips Hue - " + bridgeId.substring(bridgeId.length() - 6), httpServerPort, 0, 0, values);
jmdns.registerService(serviceInfo);
} catch (IOException e) {
log.warn("Could not start mDNS service for hue api. {}", e.getMessage());
}
}
if (bridgeControl.isReinit() || bridgeControl.isStop()) {
log.warn("UPNP Listener exiting as reinit or stop requested....");
return false;
}
log.info("UPNP Discovery Listener running and ready....");
boolean loopControl = true;
boolean error = false;
if (upnpAdvanced) {
try {
upnpMulticastSocket.setSoTimeout((int) Configuration.UPNP_NOTIFY_TIMEOUT);
} catch (SocketException e1) {
log.warn("Could not sent soTimeout on multi-cast socket");
}
}
// previous = Instant.now();
while (loopControl) {
// trigger shutdown here
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
try {
upnpMulticastSocket.receive(packet);
if (isSSDPDiscovery(packet)) {
try {
sendUpnpResponse(packet);
} catch (Exception e) {
log.warn("UpnpListener encountered an error sending upnp response packet. IP: " + packet.getAddress().getHostAddress() + " with message: " + e.getMessage());
log.debug("UpnpListener send upnp exception: ", e);
}
}
/*
* current = Instant.now(); if (ChronoUnit.MILLIS.between(previous, current) >
* Configuration.UPNP_NOTIFY_TIMEOUT) { try {
* sendUpnpNotify(socketAddress.getAddress()); } catch (IOException e) { log.
* warn("UpnpListener encountered an error sending upnp notify packets. IP: " +
* packet.getAddress().getHostAddress() + " with message: " + e.getMessage());
* log.debug("UpnpListener send upnp notify exception: ", e); } previous =
* Instant.now();
*
* }
*/
} catch (SocketTimeoutException e) {
try {
sendUpnpNotify(socketAddress.getAddress());
} catch (IOException en) {
log.warn("UpnpListener encountered an error sending upnp notify packets. IP: " + packet.getAddress().getHostAddress() + " with message: " + en.getMessage());
log.debug("UpnpListener send upnp notify exception: ", en);
}
} catch (IOException e) {
log.error("UpnpListener encountered an error reading socket. Shutting down", e);
error = true;
}
if (error || bridgeControl.isReinit() || bridgeControl.isStop()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// noop
}
loopControl = false;
}
}
upnpMulticastSocket.close();
if (jmdns != null) {
// Unregister all services
jmdns.unregisterAllServices();
}
if (bridgeControl.isReinit())
log.info("UPNP Discovery Listener - ended, restart found");
if (bridgeControl.isStop())
log.info("UPNP Discovery Listener - ended, stop found");
if (!bridgeControl.isStop() && !bridgeControl.isReinit()) {
log.info("UPNP Discovery Listener - ended, error found");
return false;
}
return bridgeControl.isReinit();
}
Aggregations