javax.jmdns.ServiceInfo Java Examples

The following examples show how to use javax.jmdns.ServiceInfo. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ZeroConf.java    From cordova-plugin-zeroconf with MIT License 7 votes vote down vote up
public void sendCallback(String action, ServiceInfo service) {
    CallbackContext callbackContext = callbacks.get(service.getType());
    if (callbackContext == null) {
        return;
    }

    JSONObject status = new JSONObject();
    try {
        status.put("action", action);
        status.put("service", jsonifyService(service));

        Log.d(TAG, "Sending result: " + status.toString());

        PluginResult result = new PluginResult(PluginResult.Status.OK, status);
        result.setKeepCallback(true);
        callbackContext.sendPluginResult(result);

    } catch (JSONException e) {
        Log.e(TAG, e.getMessage(), e);
        callbackContext.error("Error: " + e.getMessage());
    }
}
 
Example #2
Source File: JmDNSImpl.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * A service has been added.
 *
 * @param event
 *            service event
 */
@Override
public void serviceAdded(ServiceEvent event) {
    synchronized (this) {
        ServiceInfo info = event.getInfo();
        if ((info != null) && (info.hasData())) {
            _infos.put(event.getName(), info);
        } else {
            String subtype = (info != null ? info.getSubtype() : "");
            info = ((JmDNSImpl) event.getDNS()).resolveServiceInfo(event.getType(), event.getName(), subtype, true);
            if (info != null) {
                _infos.put(event.getName(), info);
            } else {
                _events.put(event.getName(), event);
            }
        }
    }
}
 
Example #3
Source File: JmDNSImpl.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Returns an array of all service infos which have been collected by this ServiceCollector.
 *
 * @param timeout
 *            timeout if the info list is empty.
 * @return Service Info array
 */
public ServiceInfo[] list(long timeout) {
    if (_infos.isEmpty() || !_events.isEmpty() || _needToWaitForInfos) {
        long loops = (timeout / 200L);
        if (loops < 1) {
            loops = 1;
        }
        for (int i = 0; i < loops; i++) {
            try {
                Thread.sleep(200);
            } catch (final InterruptedException e) {
                /* Stub */
            }
            if (_events.isEmpty() && !_infos.isEmpty() && !_needToWaitForInfos) {
                break;
            }
        }
    }
    _needToWaitForInfos = false;
    return _infos.values().toArray(new ServiceInfo[_infos.size()]);
}
 
Example #4
Source File: SoundTouchDiscoveryParticipant.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ThingUID getThingUID(ServiceInfo info) {
    logger.trace("ServiceInfo: {}", info);
    ThingTypeUID typeUID = getThingTypeUID(info);
    if (typeUID != null) {
        if (info.getType() != null) {
            if (info.getType().equals(getServiceType())) {
                logger.trace("Discovered a Bose SoundTouch thing with name '{}'", info.getName());
                byte[] mac = getMacAddress(info);
                if (mac != null) {
                    return new ThingUID(typeUID, new String(mac, StandardCharsets.UTF_8));
                } else {
                    return null;
                }
            }
        }
    }
    return null;
}
 
Example #5
Source File: SoundTouchDiscoveryParticipant.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private byte[] getMacAddress(ServiceInfo info) {
    if (info != null) {
        // sometimes we see empty messages - ignore them
        if (!info.hasData()) {
            return null;
        }
        byte[] mac = info.getPropertyBytes("MAC");
        if (mac == null) {
            logger.warn("SoundTouch Device {} delivered no MAC address!", info.getName());
            return null;
        }
        if (mac.length != 12) {
            BigInteger bi = new BigInteger(1, mac);
            logger.warn("SoundTouch Device {} delivered an invalid MAC address: 0x{}", info.getName(),
                    String.format("%0" + (mac.length << 1) + "X", bi));
            return null;
        }
        return mac;
    }
    return null;
}
 
Example #6
Source File: ConnectDialog.java    From DroidPlay with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Initialize the dialog.
 * 
 * @param context The application context
 * @param callback The callback
 * @param services The current list of available services
 */
public ConnectDialog(Context context, DialogCallback callback, Collection<ServiceInfo> services) {
	super(context);
	setTitle("Select AirPlay Service");
	this.callback = callback;
	setContentView(R.layout.connect);

	adapter = new ConnectListAdapter(getContext(), new ArrayList<ServiceInfo>());
	for (ServiceInfo si : services) {
		adapter.add(si);
	}
	
	ListView list = (ListView) findViewById(R.id.list);
	list.setEmptyView(findViewById(R.id.empty));
	list.setAdapter(adapter);
	list.setOnItemClickListener(this);
	
	Button cancel = (Button) findViewById(R.id.cancel);
	cancel.setTag("cancel");
	cancel.setOnClickListener(this);
}
 
Example #7
Source File: ZeroConf.java    From cordova-plugin-zeroconf with MIT License 6 votes vote down vote up
public ServiceInfo register(String type, String domain, String name, int port, JSONObject props) throws JSONException, IOException {

            HashMap<String, String> txtRecord = new HashMap<String, String>();
            if (props != null) {
                Iterator<String> iter = props.keys();
                while (iter.hasNext()) {
                    String key = iter.next();
                    txtRecord.put(key, props.getString(key));
                }
            }

            ServiceInfo aService = null;
            for (JmDNS publisher : publishers) {
                ServiceInfo service = ServiceInfo.create(type + domain, name, port, 0, 0, txtRecord);
                try {
                    publisher.registerService(service);
                    aService = service;
                } catch (IOException e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }
            // returns only one of the ServiceInfo instances!
            return aService;
        }
 
Example #8
Source File: JmmDNSImpl.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
@Override
public ServiceInfo[] getServiceInfos(final String type, final String name, final boolean persistent, 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()));
    ExecutorService executor = Executors.newCachedThreadPool();
    for (final JmDNS mDNS : _knownMDNS.values()) {
        executor.submit(new Runnable() {
            /**
             * {@inheritDoc}
             */
            @Override
            public void run() {
                result.add(mDNS.getServiceInfo(type, name, persistent, 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()]);
}
 
Example #9
Source File: TradfriDiscoveryParticipant.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public DiscoveryResult createResult(ServiceInfo service) {
    ThingUID thingUID = getThingUID(service);
    if (thingUID != null) {
        if (service.getHostAddresses() != null && service.getHostAddresses().length > 0
                && !service.getHostAddresses()[0].isEmpty()) {
            logger.debug("Discovered Tradfri gateway: {}", service);
            Map<String, Object> properties = new HashMap<>(4);
            properties.put(PROPERTY_VENDOR, "IKEA of Sweden");
            properties.put(GATEWAY_CONFIG_HOST, service.getHostAddresses()[0]);
            properties.put(GATEWAY_CONFIG_PORT, service.getPort());
            properties.put(PROPERTY_SERIAL_NUMBER, service.getName());
            String fwVersion = service.getPropertyString("version");
            if (fwVersion != null) {
                properties.put(PROPERTY_FIRMWARE_VERSION, fwVersion);
            }
            return DiscoveryResultBuilder.create(thingUID).withProperties(properties).withLabel("TRÅDFRI Gateway")
                    .withRepresentationProperty(GATEWAY_CONFIG_HOST).build();
        } else {
            logger.warn("Discovered Tradfri gateway doesn't have an IP address: {}", service);
        }
    }
    return null;
}
 
Example #10
Source File: JmDNSImpl.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
private void waitForInfoData(ServiceInfo info, long timeout) {
    synchronized (info) {
        long loops = (timeout / 200L);
        if (loops < 1) {
            loops = 1;
        }
        for (int i = 0; i < loops; i++) {
            if (info.hasData()) {
                break;
            }
            try {
                info.wait(200);
            } catch (final InterruptedException e) {
                /* Stub */
            }
        }
    }
}
 
Example #11
Source File: DNSRecord.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
@Override
public ServiceEvent getServiceEvent(JmDNSImpl dns) {
    ServiceInfo info = this.getServiceInfo(false);
    ((ServiceInfoImpl) info).setDns(dns);
    // String domainName = "";
    // String serviceName = this.getServer();
    // int index = serviceName.indexOf('.');
    // if (index > 0)
    // {
    // serviceName = this.getServer().substring(0, index);
    // if (index + 1 < this.getServer().length())
    // domainName = this.getServer().substring(index + 1);
    // }
    // return new ServiceEventImpl(dns, domainName, serviceName, info);
    return new ServiceEventImpl(dns, info.getType(), info.getName(), info);

}
 
Example #12
Source File: MDNSDiscoveryService.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Scan has 2 different behaviours. background/ foreground. Background scans can
 * have much higher timeout. Foreground scans have only a short timeout as human
 * users may become impatient. The underlying reason is that the jmDNS
 * implementation {@code MDNSClient#list(String)} has a default timeout of 6
 * seconds when no ServiceInfo is found. When there are many participants,
 * waiting 6 seconds for each non-existent type is too long.
 *
 * @param isBackground true if it is background scan, false otherwise.
 */
private void scan(boolean isBackground) {
    for (MDNSDiscoveryParticipant participant : participants) {
        long start = System.currentTimeMillis();
        ServiceInfo[] services;
        if (isBackground) {
            services = mdnsClient.list(participant.getServiceType());
        } else {
            services = mdnsClient.list(participant.getServiceType(), FOREGROUND_SCAN_TIMEOUT);
        }
        logger.debug("{} services found for {}; duration: {}ms", services.length, participant.getServiceType(),
                System.currentTimeMillis() - start);
        for (ServiceInfo service : services) {
            DiscoveryResult result = participant.createResult(service);
            if (result != null) {
                thingDiscovered(result);
            }
        }
    }
}
 
Example #13
Source File: ListenerStatus.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * A service has been resolved. Its details are now available in the ServiceInfo record.<br/>
 * <b>Note:</b>This call back will never be called if the service does not resolve.<br/>
 * 
 * @param event
 *            The ServiceEvent providing the name, the fully qualified type of the service, and the service info record.
 */
synchronized void serviceResolved(ServiceEvent event) {
    ServiceInfo info = event.getInfo();
    if ((info != null) && (info.hasData())) {
        String qualifiedName = event.getName() + "." + event.getType();
        ServiceInfo previousServiceInfo = _addedServices.get(qualifiedName);
        if (!_sameInfo(info, previousServiceInfo)) {
            if (null == previousServiceInfo) {
                if (null == _addedServices.putIfAbsent(qualifiedName, info.clone())) {
                    this.getListener().serviceResolved(event);
                }
            } else {
                if (_addedServices.replace(qualifiedName, previousServiceInfo, info.clone())) {
                    this.getListener().serviceResolved(event);
                }
            }
        } else {
            logger.finer("Service Resolved called for a service already resolved: " + event);
        }
    } else {
        logger.warning("Service Resolved called for an unresolved event: " + event);

    }
}
 
Example #14
Source File: JmDNSImpl.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public ServiceInfo[] list(String type, long timeout) {
    this.cleanCache();
    // Implementation note: The first time a list for a given type is
    // requested, a ServiceCollector is created which collects service
    // infos. This greatly speeds up the performance of subsequent calls
    // to this method. The caveats are, that 1) the first call to this
    // method for a given type is slow, and 2) we spawn a ServiceCollector
    // instance for each service type which increases network traffic a
    // little.

    String loType = type.toLowerCase();

    boolean newCollectorCreated = false;
    if (this.isCanceling() || this.isCanceled()) {
        return new ServiceInfo[0];
    }

    ServiceCollector collector = _serviceCollectors.get(loType);
    if (collector == null) {
        newCollectorCreated = _serviceCollectors.putIfAbsent(loType, new ServiceCollector(type)) == null;
        collector = _serviceCollectors.get(loType);
        if (newCollectorCreated) {
            this.addServiceListener(type, collector, ListenerStatus.SYNCHONEOUS);
        }
    }
    if (logger.isLoggable(Level.FINER)) {
        logger.finer(this.getName() + ".collector: " + collector);
    }
    // At this stage the collector should never be null but it keeps findbugs happy.
    return (collector != null ? collector.list(timeout) : new ServiceInfo[0]);
}
 
Example #15
Source File: JmDNSImpl.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
public ServiceCollector(String type) {
    super();
    _infos = new ConcurrentHashMap<String, ServiceInfo>();
    _events = new ConcurrentHashMap<String, ServiceEvent>();
    _type = type;
    _needToWaitForInfos = true;
}
 
Example #16
Source File: AirPlayClientService.java    From DroidPlay with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Send a request to stop playing the current video.
 * 
 * @param serviceInfo The service to use
 * @throws Exception If there are any problems with the parameters
 */
public void stopVideo(ServiceInfo serviceInfo) throws Exception {
	if (serviceInfo == null) {
		throw new Exception("Not connected to AirPlay service");
	}
	es.submit(new StopVideoTask(serviceInfo));
}
 
Example #17
Source File: BonjourPeer.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Return a instance if the {@link ServiceInfo} is fully resolved and does
 * not represent this device, but something else on the network.
 */
@Nullable
public static BonjourPeer getInstance(ServiceInfo serviceInfo) {
    String type = serviceInfo.getPropertyString(TYPE);
    String fingerprint = serviceInfo.getPropertyString(FINGERPRINT);
    if (type == null || !type.startsWith("fdroidrepo")
            || TextUtils.equals(FDroidApp.repo.fingerprint, fingerprint)) {
        return null;
    }
    return new BonjourPeer(serviceInfo);
}
 
Example #18
Source File: MDNSClientImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Concatenate two arrays of ServiceInfo
 *
 * @param a: the first array
 * @param b: the second array
 * @return an array of ServiceInfo
 */
private ServiceInfo[] concatenate(ServiceInfo[] a, ServiceInfo[] b) {
    int aLen = a.length;
    int bLen = b.length;

    ServiceInfo[] c = new ServiceInfo[aLen + bLen];
    System.arraycopy(a, 0, c, 0, aLen);
    System.arraycopy(b, 0, c, aLen, bLen);

    return c;
}
 
Example #19
Source File: ZeroConf.java    From cordova-plugin-zeroconf with MIT License 5 votes vote down vote up
public void unregister(String type, String domain, String name) {

            for (JmDNS publisher : publishers) {
                ServiceInfo serviceInfo = publisher.getServiceInfo(type + domain, name, 5000);
                if (serviceInfo != null) {
                    publisher.unregisterService(serviceInfo);
                }
            }

        }
 
Example #20
Source File: MDNSClientImpl.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ServiceInfo[] list(String type) {
    ServiceInfo[] services = new ServiceInfo[0];
    for (JmDNS instance : jmdnsInstances.values()) {
        services = concatenate(services, instance.list(type));
    }
    return services;
}
 
Example #21
Source File: DNSRecord.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
@Override
public ServiceEvent getServiceEvent(JmDNSImpl dns) {
    ServiceInfo info = this.getServiceInfo(false);
    ((ServiceInfoImpl) info).setDns(dns);
    String domainName = info.getType();
    String serviceName = JmDNSImpl.toUnqualifiedName(domainName, this.getAlias());
    return new ServiceEventImpl(dns, domainName, serviceName, info);
}
 
Example #22
Source File: JmDNSImpl.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * Generate a possibly unique name for a service using the information we have in the cache.
 *
 * @return returns true, if the name of the service info had to be changed.
 */
private boolean makeServiceNameUnique(ServiceInfoImpl info) {
    final String originalQualifiedName = info.getKey();
    final long now = System.currentTimeMillis();

    boolean collision;
    do {
        collision = false;

        // Check for collision in cache
        for (DNSEntry dnsEntry : this.getCache().getDNSEntryList(info.getKey())) {
            if (DNSRecordType.TYPE_SRV.equals(dnsEntry.getRecordType()) && !dnsEntry.isExpired(now)) {
                final DNSRecord.Service s = (DNSRecord.Service) dnsEntry;
                if (s.getPort() != info.getPort() || !s.getServer().equals(_localHost.getName())) {
                    if (logger.isLoggable(Level.FINER)) {
                        logger.finer("makeServiceNameUnique() JmDNS.makeServiceNameUnique srv collision:" + dnsEntry + " s.server=" + s.getServer() + " " + _localHost.getName() + " equals:" + (s.getServer().equals(_localHost.getName())));
                    }
                    info.setName(incrementName(info.getName()));
                    collision = true;
                    break;
                }
            }
        }

        // Check for collision with other service infos published by JmDNS
        final ServiceInfo selfService = _services.get(info.getKey());
        if (selfService != null && selfService != info) {
            info.setName(incrementName(info.getName()));
            collision = true;
        }
    }
    while (collision);

    return !(originalQualifiedName.equals(info.getKey()));
}
 
Example #23
Source File: ListenerStatus.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
private static final boolean _sameInfo(ServiceInfo info, ServiceInfo lastInfo) {
    if (info == null) return false;
    if (lastInfo == null) return false;
    if (!info.equals(lastInfo)) return false;
    byte[] text = info.getTextBytes();
    byte[] lastText = lastInfo.getTextBytes();
    if (text.length != lastText.length) return false;
    for (int i = 0; i < text.length; i++) {
        if (text[i] != lastText[i]) return false;
    }
    return true;
}
 
Example #24
Source File: JmmDNSImpl.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 *
 */
public JmmDNSImpl() {
    super();
    _networkListeners = Collections.synchronizedSet(new HashSet<NetworkTopologyListener>());
    _knownMDNS = new ConcurrentHashMap<InetAddress, JmDNS>();
    _services = new ConcurrentHashMap<String, ServiceInfo>(20);
    _ListenerExecutor = Executors.newSingleThreadExecutor();
    _jmDNSExecutor = Executors.newCachedThreadPool();
    _timer = new Timer("Multihommed mDNS.Timer", true);
    (new NetworkChecker(this, NetworkTopologyDiscovery.Factory.getInstance())).start(_timer);
}
 
Example #25
Source File: MDNSClientImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void registerServiceInternal(ServiceDescription description) throws IOException {
    for (JmDNS instance : jmdnsInstances.values()) {
        logger.debug("Registering new service {} at {}:{} ({})", description.serviceType,
                instance.getInetAddress().getHostAddress(), description.servicePort, instance.getName());
        // Create one ServiceInfo object for each JmDNS instance
        ServiceInfo serviceInfo = ServiceInfo.create(description.serviceType, description.serviceName,
                description.servicePort, 0, 0, description.serviceProperties);
        instance.registerService(serviceInfo);
    }
}
 
Example #26
Source File: JmmDNSImpl.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
@Override
public void textValueUpdated(ServiceInfo target, byte[] value) {
    synchronized (_services) {
        for (JmDNS mDNS : _knownMDNS.values()) {
            ServiceInfo info = ((JmDNSImpl) mDNS).getServices().get(target.getQualifiedName());
            if (info != null) {
                info.setText(value);
            } else {
                logger.warning("We have a mDNS that does not know about the service info being updated.");
            }
        }
    }
}
 
Example #27
Source File: DNSRecord.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * Does the necessary actions, when this as a query.
 */
@Override
boolean handleQuery(JmDNSImpl dns, long expirationTime) {
    if (dns.getLocalHost().conflictWithRecord(this)) {
        DNSRecord.Address localAddress = dns.getLocalHost().getDNSAddressRecord(this.getRecordType(), this.isUnique(), DNSConstants.DNS_TTL);
        int comparison = this.compareTo(localAddress);

        if (comparison == 0) {
            // the 2 records are identical this probably means we are seeing our own record.
            // With multiple interfaces on a single computer it is possible to see our
            // own records come in on different interfaces than the ones they were sent on.
            // see section "10. Conflict Resolution" of mdns draft spec.
            logger1.finer("handleQuery() Ignoring an identical address query");
            return false;
        }

        logger1.finer("handleQuery() Conflicting query detected.");
        // Tie breaker test
        if (dns.isProbing() && comparison > 0) {
            // We lost the tie-break. We have to choose a different name.
            dns.getLocalHost().incrementHostName();
            dns.getCache().clear();
            for (ServiceInfo serviceInfo : dns.getServices().values()) {
                ServiceInfoImpl info = (ServiceInfoImpl) serviceInfo;
                info.revertState();
            }
        }
        dns.revertState();
        return true;
    }
    return false;
}
 
Example #28
Source File: JmmDNSImpl.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
@Override
public void unregisterService(ServiceInfo info) {
    synchronized (_services) {
        for (JmDNS mDNS : _knownMDNS.values()) {
            mDNS.unregisterService(info);
        }
        ((ServiceInfoImpl) info).setDelegate(null);
        _services.remove(info.getQualifiedName());
    }
}
 
Example #29
Source File: ServiceInfoAdapter.java    From Android-Remote with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    final ServiceInfo current = mData.get(position);
    holder.textViewHost.setText(current.getName());
    holder.textViewIp.setText(
            current.getInet4Addresses()[0].toString().split("/")[1] + ":" + current.getPort());
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mListener != null) {
                mListener.onItemClick(current);
            }
        }
    });
}
 
Example #30
Source File: DNSRecord.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
@Override
public ServiceInfo getServiceInfo(boolean persistent) {

    ServiceInfoImpl info = (ServiceInfoImpl) super.getServiceInfo(persistent);
    info.addAddress((Inet4Address) _addr);
    return info;
}