rtlduino rtl8710af gcc base version
1
tools/wigadget/Android/WiGadget/app/.gitignore
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
/build
|
||||
102
tools/wigadget/Android/WiGadget/app/app.iml
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="WiGadget" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
|
||||
<component name="FacetManager">
|
||||
<facet type="android-gradle" name="Android-Gradle">
|
||||
<configuration>
|
||||
<option name="GRADLE_PROJECT_PATH" value=":app" />
|
||||
</configuration>
|
||||
</facet>
|
||||
<facet type="android" name="Android">
|
||||
<configuration>
|
||||
<option name="SELECTED_BUILD_VARIANT" value="debug" />
|
||||
<option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
|
||||
<option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
|
||||
<option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
|
||||
<option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
|
||||
<option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
|
||||
<afterSyncTasks>
|
||||
<task>generateDebugAndroidTestSources</task>
|
||||
<task>generateDebugSources</task>
|
||||
</afterSyncTasks>
|
||||
<option name="ALLOW_USER_CONFIGURATION" value="false" />
|
||||
<option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
|
||||
<option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
|
||||
<option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
|
||||
<option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
|
||||
</configuration>
|
||||
</facet>
|
||||
</component>
|
||||
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
|
||||
<output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
|
||||
<output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/androidTest/debug" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.3/jars" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/support-v4/21.0.3/jars" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/outputs" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/tmp" />
|
||||
</content>
|
||||
<orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="library" exported="" name="appcompat-v7-21.0.3" level="project" />
|
||||
<orderEntry type="library" exported="" name="firebase-client-android-2.2.4" level="project" />
|
||||
<orderEntry type="library" exported="" name="support-annotations-21.0.3" level="project" />
|
||||
<orderEntry type="library" exported="" name="jmdns-3.4.1" level="project" />
|
||||
<orderEntry type="library" exported="" name="support-v4-21.0.3" level="project" />
|
||||
<orderEntry type="library" exported="" name="androidplot-core-0.6.1" level="project" />
|
||||
<orderEntry type="library" exported="" name="commons-codec-1.6-repack" level="project" />
|
||||
<orderEntry type="library" exported="" name="jmdns" level="project" />
|
||||
</component>
|
||||
</module>
|
||||
34
tools/wigadget/Android/WiGadget/app/build.gradle
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
apply plugin: 'com.android.application'
|
||||
|
||||
android {
|
||||
compileSdkVersion 21
|
||||
buildToolsVersion "21.1.2"
|
||||
|
||||
defaultConfig {
|
||||
applicationId "com.realtek.amebazeroconf"
|
||||
minSdkVersion 16
|
||||
targetSdkVersion 21
|
||||
versionCode 1
|
||||
versionName "1.0"
|
||||
}
|
||||
buildTypes {
|
||||
release {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
packagingOptions {
|
||||
exclude 'META-INF/LICENSE.txt'
|
||||
exclude 'META-INF/NOTICE.txt'
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile fileTree(include: ['*.jar'], dir: 'libs')
|
||||
compile 'com.android.support:appcompat-v7:21.0.3'
|
||||
compile files('libs/commons-codec-1.6-repack.jar')
|
||||
compile files('libs/jmdns-3.4.1.jar')
|
||||
compile files('libs/jmdns.jar')
|
||||
compile files('libs/firebase-client-android-2.2.4.jar')
|
||||
compile files('libs/androidplot-core-0.6.1.jar')
|
||||
}
|
||||
17
tools/wigadget/Android/WiGadget/app/proguard-rules.pro
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
# Add project specific ProGuard rules here.
|
||||
# By default, the flags in this file are appended to flags specified
|
||||
# in C:\Users\Wu Jinzhou\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt
|
||||
# You can edit the include path and order by changing the proguardFiles
|
||||
# directive in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# Add any project specific keep options here:
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.app.Application;
|
||||
import android.test.ApplicationTestCase;
|
||||
|
||||
/**
|
||||
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
|
||||
*/
|
||||
public class ApplicationTest extends ApplicationTestCase<Application> {
|
||||
public ApplicationTest() {
|
||||
super(Application.class);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.realtek.wigadget" >
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/AppTheme" >
|
||||
|
||||
<activity
|
||||
android:name="com.realtek.wigadget.MainActivity"
|
||||
android:label="@string/app_name"
|
||||
android:configChanges="screenSize|orientation">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="com.realtek.wigadget.HTSensorActivity"
|
||||
android:label="H&T Sensor Readings"/>
|
||||
|
||||
<activity
|
||||
android:name="com.realtek.wigadget.RegisterFirebaseAccountActivity"
|
||||
android:label="Register Firebase"/>
|
||||
|
||||
<activity
|
||||
android:name="com.realtek.wigadget.SettingsActivity"
|
||||
android:label="Settings"/>
|
||||
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
/**
|
||||
* Created by Wu Jinzhou on 5/6/2015.
|
||||
*/
|
||||
public class AES128 {
|
||||
|
||||
private static final String IV = "AAAAAAAAAAAAAAAA";
|
||||
private static final int byteUnit =16;
|
||||
|
||||
private synchronized byte[] encrypt(String plainText, byte[] encryptionKey) throws Exception {
|
||||
//padding
|
||||
int boz=plainText.length()%byteUnit;
|
||||
if(boz!=0){
|
||||
for (int i=0 ; i<(byteUnit-boz); i++){
|
||||
plainText+='\0';
|
||||
}
|
||||
}
|
||||
//Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
|
||||
SecretKeySpec key = new SecretKeySpec(encryptionKey, "AES");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
|
||||
return cipher.doFinal(plainText.getBytes("UTF-8"));
|
||||
}
|
||||
|
||||
private synchronized String decrypt(byte[] cipherText, byte[] encryptionKey) throws Exception{
|
||||
//Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
|
||||
SecretKeySpec key = new SecretKeySpec(encryptionKey, "AES");
|
||||
cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
|
||||
return new String(cipher.doFinal(cipherText),"UTF-8");
|
||||
}
|
||||
|
||||
private synchronized byte[] parseByteArrayFromString(String stringOfByteArray){
|
||||
|
||||
//parse format: "[ -1, 2, -3, 4, -5]"
|
||||
|
||||
String[] items = stringOfByteArray.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\ ","").split(",");
|
||||
|
||||
int[] resultsInInt = new int[items.length];
|
||||
|
||||
byte[] resultsInByte = new byte[items.length];
|
||||
|
||||
for (int i = 0; i < items.length; i++) {
|
||||
resultsInInt[i] = Integer.parseInt(items[i]);
|
||||
}
|
||||
|
||||
for (int i =0;i<resultsInInt.length;i++){
|
||||
resultsInByte[i]=(byte)resultsInInt[i];
|
||||
}
|
||||
|
||||
return resultsInByte;
|
||||
}
|
||||
|
||||
public synchronized String encryptToStringOfShortArray(String plainText,String keyArrayInString)throws Exception{
|
||||
byte [] key = parseByteArrayFromString(keyArrayInString);
|
||||
byte[] encryptedDataInByte = encrypt(plainText, key);
|
||||
short[] encryptedDataInShort = new short[encryptedDataInByte.length];
|
||||
for (int i=0; i<encryptedDataInByte.length;i++){
|
||||
encryptedDataInShort[i]=(short)(encryptedDataInByte[i]&0xff);
|
||||
}
|
||||
return Arrays.toString(encryptedDataInShort);
|
||||
}
|
||||
|
||||
public synchronized String decryptFromStringOfShortArray(String cipherTextArrayInString, String keyArrayInString)throws Exception{
|
||||
byte[] cipherText = parseByteArrayFromString(cipherTextArrayInString);
|
||||
byte[] key = parseByteArrayFromString(keyArrayInString);
|
||||
return decrypt(cipherText,key);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.app.Fragment;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.TextView;
|
||||
|
||||
public class AboutFragment extends Fragment {
|
||||
static Constants c = Constants.getInstance();
|
||||
final String tag= c.tag_about_fragment;
|
||||
|
||||
public AboutFragment(){}
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
getActivity().setTitle(R.string.about_fragment_title);
|
||||
}
|
||||
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
|
||||
View rootView = inflater.inflate(R.layout.fragment_about, container, false);
|
||||
TextView tv = (TextView)rootView.findViewById(R.id.txtLabel);
|
||||
String tvText = "Build on 08/06/2015";
|
||||
|
||||
tv.setText(tvText);
|
||||
return rootView;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.InetAddress;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* Created by Wu Jinzhou on 5/15/2015.
|
||||
*/
|
||||
public class ConnectionChecker {
|
||||
|
||||
private static final Constants c = Constants.getInstance();
|
||||
|
||||
public synchronized boolean testConnection(String ip, int baseTimeOut, int maxTry){
|
||||
try {
|
||||
InetAddress serverAddr = InetAddress.getByName(ip);
|
||||
for(int i = 1; i< maxTry+1 ; i++){
|
||||
Log.v(c.tag_connection_checker,"testConnection() checking ip "+ip+" with timeout "+(baseTimeOut*i));
|
||||
if(serverAddr.isReachable(baseTimeOut*i)){
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IOException e){Log.e(c.tag_connection_checker,"testConnection() IOException e "+e);}
|
||||
return false;
|
||||
}
|
||||
|
||||
public synchronized boolean testConnection(String firebaseAppId){
|
||||
|
||||
int responseCode = 404;
|
||||
String firebaseURL;
|
||||
|
||||
if(firebaseAppId.endsWith(".firebaseio.com")){
|
||||
firebaseURL = "https://"+firebaseAppId;
|
||||
}
|
||||
else{
|
||||
firebaseURL = "https://"+firebaseAppId+".firebaseio.com";
|
||||
}
|
||||
|
||||
try{
|
||||
Log.v(c.tag_connection_checker,"testConnection() checking FirebaseAppId "+firebaseAppId);
|
||||
URL url = new URL(firebaseURL);
|
||||
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
connection.connect();
|
||||
responseCode = connection.getResponseCode();
|
||||
}
|
||||
catch (MalformedURLException e){
|
||||
Log.e(c.tag_connection_checker,"testConnection() for cloud -- MalformedURLException e"+e);
|
||||
}
|
||||
catch (IOException e){
|
||||
Log.e(c.tag_connection_checker,"testConnection() for cloud -- IOException e"+e);
|
||||
}
|
||||
|
||||
if(responseCode == 200){
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,121 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
/**
|
||||
* Created by Wu Jinzhou on 4/21/2015.
|
||||
*/
|
||||
public final class Constants {
|
||||
private static Constants thisConstants;
|
||||
public static synchronized Constants getInstance(){
|
||||
if (thisConstants==null){
|
||||
thisConstants = new Constants();
|
||||
}
|
||||
return thisConstants;
|
||||
}
|
||||
private Constants(){
|
||||
}
|
||||
|
||||
///////////////////////////////////////device list///////////////////////////////////////
|
||||
String key_mac = "MAC_ADDR";
|
||||
String key_date_format = "yyyy-MM-dd HH:mm:ss";
|
||||
String key_ip = "IP";
|
||||
String key_port = "PORT";
|
||||
String key_service_name = "SERVICE_NAME";
|
||||
String key_control_type = "CONTROL_TYPE";
|
||||
String key_shared_key = "SHARED_KEY";
|
||||
String key_device_description = "DESCRIPTION";
|
||||
String key_date = "DATE";
|
||||
String key_firebase_app_id = "FIREBASE_APP_ID";
|
||||
String key_pair_state = "PAIR_STATE";
|
||||
String val_file_name = "PairedDevices.json";
|
||||
String val_local_control = "0";
|
||||
String val_cloud_control = "1";
|
||||
String val_not_paired = "0";
|
||||
String val_paired = "1";
|
||||
String val_empty = "";
|
||||
int val_device_not_found = -1;
|
||||
///////////////////////////////////////device list///////////////////////////////////////
|
||||
|
||||
///////////////////////////////////////nsd///////////////////////////////////////
|
||||
String nsd_service_type = "_Ameba._tcp.local.";
|
||||
String nsd_service_ht = "ht_sensor";
|
||||
String nsd_service_unknown = "unknown";
|
||||
///////////////////////////////////////nsd///////////////////////////////////////
|
||||
|
||||
///////////////////////////////////////tags///////////////////////////////////////
|
||||
String tag_about_fragment = "@AboutFragment ";
|
||||
String tag_nsd_helper = "@NsdHelper ";
|
||||
String tag_device_list = "@DeviceList ";
|
||||
String tag_find_device_fragment = "@FindDeviceFragment ";
|
||||
String tag_main_activity = "@MainActivity ";
|
||||
String tag_tcp_client = "@TcpClient ";
|
||||
String tag_key_gen = "@KeyGen ";
|
||||
String tag_my_device_fragment = "@MyDeviceFragment ";
|
||||
String tag_ht_sensor_activity = "@HTSensorActivity ";
|
||||
String tag_connection_checker ="@ConnectionChecker ";
|
||||
///////////////////////////////////////tags///////////////////////////////////////
|
||||
|
||||
////////////////////////////////////////tcp///////////////////////////////////////
|
||||
String tcp_tx_pair = "PAIR";
|
||||
String tcp_tx_cmd_unpairing = "remove";
|
||||
String tcp_rx_unpairing_ok = "Remove OK";
|
||||
String tcp_rx_error = "ERROR";
|
||||
String tcp_rx_firebase_app_url = "FIREBASE URL";
|
||||
String tcp_rx_pair_ok = "PAIR OK";
|
||||
int val_tcp_next_cmd_waiting_ms = 500; //ameba side delay: 250ms
|
||||
///////////////////////////////////////tcp////////////////////////////////////////
|
||||
|
||||
///////////////////////////////////////pairing///////////////////////////////////////
|
||||
int val_pairing_succeed = 0;
|
||||
int err_pairing_failed_to_start = -1;
|
||||
int err_server_no_response = -2;
|
||||
int err_pair_cmd_rejected = -3;
|
||||
int err_public_key_rejected = -4;
|
||||
int err_firebase_app_url_rejected = -5;
|
||||
int err_unknown_host_exception = -6;
|
||||
int err_interrupted_exception = -7;
|
||||
int err_io_exception = -8;
|
||||
int err_firebase_app_url_cannot_be_verified = -9;
|
||||
int err_unknown_error = -10;
|
||||
///////////////////////////////////////pairing///////////////////////////////////////
|
||||
|
||||
///////////////////////////////////////unpairing///////////////////////////////////////
|
||||
int val_unpairing_succeed = 0;
|
||||
int err_unpairing_device_not_found = -1;
|
||||
int err_unpairing_server_ping_timeout = -2;
|
||||
int err_unpairing_with_server_failed = -3;
|
||||
///////////////////////////////////////unpairing///////////////////////////////////////
|
||||
|
||||
///////////////////////////////////////firebase///////////////////////////////////////
|
||||
String val_firebase_register_url = "https://www.firebase.com/signup/";
|
||||
String key_humidity = "HUM";
|
||||
String key_temperature = "TEM";
|
||||
///////////////////////////////////////firebase///////////////////////////////////////
|
||||
|
||||
//////////////////////////////////ht sensor activity//////////////////////////////////
|
||||
String key_ht_sensor_data_update_frequency = "data_update_frequency";
|
||||
String key_ht_sensor_alarm_options = "ht_alarm_options";
|
||||
String key_ht_sensor_temperature_threshold = "temperature_threshold";
|
||||
String key_ht_sensor_humidity_threshold = "humidity_threshold";
|
||||
String key_ht_sensor_alarm_sound = "alarm_sound";
|
||||
int val_ht_sensor_default_data_update_frequency = 2000;
|
||||
boolean val_ht_sensor_default_alarm_options = false;
|
||||
double val_ht_sensor_default_temperature_threshold = 100.0;
|
||||
double val_ht_sensor_default_humidity_threshold = 100.0;
|
||||
String val_ht_sensor_default_alarm_sound = "sound_ding";
|
||||
String val_ht_sensor_alarm_sound_altair = "sound_altair";
|
||||
String val_ht_sensor_alarm_sound_ariel = "sound_ariel";
|
||||
String val_ht_sensor_alarm_sound_fomalhaut = "sound_fomalhaut";
|
||||
String val_ht_sensor_alarm_sound_tinkerbell = "sound_tinkerbell";
|
||||
//////////////////////////////////ht sensor activity//////////////////////////////////
|
||||
|
||||
///////////////////////////////////////ping///////////////////////////////////////
|
||||
int val_ping_base_time_out = 500;
|
||||
int val_ping_max_try = 4;
|
||||
///////////////////////////////////////ping///////////////////////////////////////
|
||||
|
||||
///////////////////////////////////////ui///////////////////////////////////////
|
||||
int val_ui_update_period_ms = 1000;
|
||||
int val_ui_double_click_interval = 500;
|
||||
///////////////////////////////////////ui///////////////////////////////////////
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.graphics.Bitmap;
|
||||
|
||||
public class DeviceIcon {
|
||||
private Bitmap deviceIcon;
|
||||
private String deviceMac;
|
||||
private String deviceDescription;
|
||||
|
||||
public DeviceIcon(Bitmap icon, String description, String mac) {
|
||||
super();
|
||||
this.deviceIcon = icon;
|
||||
this.deviceDescription=description;
|
||||
this.deviceMac = mac;
|
||||
}
|
||||
|
||||
public Bitmap getDeviceIcon() {
|
||||
return deviceIcon;
|
||||
}
|
||||
|
||||
public String getDeviceDescription() {
|
||||
return deviceDescription;
|
||||
}
|
||||
|
||||
public void setDeviceDescription(String description) {
|
||||
this.deviceDescription = description;
|
||||
}
|
||||
|
||||
public String getDeviceMac(){
|
||||
return deviceMac;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,502 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.res.TypedArray;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.util.Log;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Vector;
|
||||
|
||||
import javax.jmdns.ServiceEvent;
|
||||
|
||||
/**
|
||||
* Created by Wu Jinzhou on 4/15/2015.
|
||||
*/
|
||||
public class DeviceList {
|
||||
static final Constants c =Constants.getInstance();
|
||||
|
||||
private final String tag = c.tag_device_list;
|
||||
|
||||
private static DeviceList thisDeviceList;
|
||||
private static Vector<ServiceEvent> tempList = new Vector<>();
|
||||
private static Vector<ServiceEvent> trackingList = new Vector<>();
|
||||
private static Vector<ServiceEvent> transientList = new Vector<>();
|
||||
private static Vector<String> downList = new Vector<>();
|
||||
private static JSONArray jArray;
|
||||
|
||||
private static Context mContext;
|
||||
|
||||
private DeviceList(Context ctx){
|
||||
mContext=ctx;
|
||||
}
|
||||
|
||||
public synchronized boolean addDevice (String mac, String serviceName, String controlType, String firebaseAppId, String sharedKey, String description) throws JSONException,IOException {
|
||||
if (deviceLookup(mac)==c.val_device_not_found){
|
||||
|
||||
JSONObject jObject =new JSONObject();
|
||||
String currentDateTime = new SimpleDateFormat(c.key_date_format).format(new Date());
|
||||
|
||||
jObject.put(c.key_mac,mac);
|
||||
jObject.put(c.key_service_name,serviceName);
|
||||
jObject.put(c.key_control_type,controlType);
|
||||
jObject.put(c.key_firebase_app_id,firebaseAppId);
|
||||
jObject.put(c.key_shared_key,sharedKey);
|
||||
jObject.put(c.key_device_description,description);
|
||||
jObject.put(c.key_date,currentDateTime);
|
||||
jArray.put(jObject);
|
||||
|
||||
//save change to file
|
||||
saveChange();
|
||||
Log.v(tag,"added device :"+mac);
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
Log.v(tag,"device "+mac+" already in list");
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public synchronized boolean removeDevice(String mac)throws JSONException,IOException{
|
||||
|
||||
int idxToBeRemoved = deviceLookup(mac);
|
||||
|
||||
if(idxToBeRemoved!=c.val_device_not_found){
|
||||
|
||||
Vector jVector = new Vector<JSONObject>();
|
||||
|
||||
for (int i=0;i<jArray.length();i++){
|
||||
if(i!=idxToBeRemoved){
|
||||
jVector.add(jArray.getJSONObject(i));
|
||||
}
|
||||
}
|
||||
|
||||
jArray = new JSONArray();
|
||||
|
||||
for (int i=0;i<jVector.size();i++){
|
||||
jArray.put(jVector.elementAt(i));
|
||||
}
|
||||
|
||||
//also remove device it its in trackingList, transientList and downList
|
||||
if(trackingListDeviceLookup(mac)!=c.val_device_not_found){
|
||||
trackingListRemoveDevice(mac);
|
||||
Log.v(tag,"trackingListRemoveDevice() "+mac);
|
||||
}
|
||||
|
||||
if(transientListLookup(mac)!=c.val_device_not_found){
|
||||
transientListRemoveDevice(mac);
|
||||
Log.v(tag, "transientListRemoveDevice() " + mac);
|
||||
}
|
||||
|
||||
if(downListLookup(mac)!=c.val_device_not_found){
|
||||
downListRemoveDevice(mac);
|
||||
Log.v(tag, "downListRemoveDevice() " + mac);
|
||||
}
|
||||
|
||||
//save change to file
|
||||
saveChange();
|
||||
Log.v(tag,"removed device :"+mac);
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
Log.v(tag,"device "+mac+" not found");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public synchronized int deviceLookup(String mac) throws JSONException{
|
||||
for (int i=0;i<jArray.length();i++)
|
||||
{
|
||||
if (jArray.getJSONObject(i).getString(c.key_mac).equals(mac)){
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return c.val_device_not_found;
|
||||
}
|
||||
|
||||
private static synchronized void load() throws JSONException,IOException{
|
||||
|
||||
String filePath = mContext.getFilesDir().getPath()+"/"+c.val_file_name;
|
||||
File f = new File(filePath);
|
||||
|
||||
if (!f.exists()){
|
||||
f.createNewFile();
|
||||
}
|
||||
|
||||
FileInputStream fis=mContext.openFileInput(c.val_file_name);
|
||||
BufferedInputStream bis=new BufferedInputStream(fis);
|
||||
StringBuffer sb=new StringBuffer();
|
||||
while (bis.available()!=0){
|
||||
char c=(char)bis.read();
|
||||
sb.append(c);
|
||||
}
|
||||
bis.close();
|
||||
fis.close();
|
||||
|
||||
if(sb.toString().equals("")){
|
||||
jArray=new JSONArray();
|
||||
}
|
||||
else {
|
||||
jArray=new JSONArray(sb.toString());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private synchronized void saveChange() throws IOException,JSONException{
|
||||
FileOutputStream fos;
|
||||
fos = mContext.openFileOutput(c.val_file_name, Context.MODE_PRIVATE);
|
||||
fos.write(jArray.toString(4).getBytes());
|
||||
fos.close();
|
||||
}
|
||||
|
||||
public synchronized Bitmap getDeviceIcon(String serviceName, String controlType, boolean online)throws JSONException{
|
||||
|
||||
TypedArray imgArray;
|
||||
Bitmap bitmap;
|
||||
|
||||
if(serviceName.equals(c.nsd_service_ht)){
|
||||
imgArray=mContext.getResources().obtainTypedArray(R.array.device_ht);
|
||||
if((online)&&(controlType.equals(c.val_local_control))) {
|
||||
//local online
|
||||
bitmap = BitmapFactory.decodeResource(mContext.getResources(), imgArray.getResourceId(0, -1));
|
||||
}
|
||||
else if((!online)&&(controlType.equals(c.val_local_control))) {
|
||||
//local offline
|
||||
bitmap = BitmapFactory.decodeResource(mContext.getResources(), imgArray.getResourceId(1, -1));
|
||||
}
|
||||
else if((online)&&(controlType.equals(c.val_cloud_control))){
|
||||
//cloud online
|
||||
bitmap = BitmapFactory.decodeResource(mContext.getResources(), imgArray.getResourceId(2, -1));
|
||||
}
|
||||
else {
|
||||
//cloud offline
|
||||
bitmap = BitmapFactory.decodeResource(mContext.getResources(), imgArray.getResourceId(3, -1));
|
||||
}
|
||||
}
|
||||
|
||||
//else if(serviceName.equals(xxxx_xxxxx)....)
|
||||
// {..
|
||||
//
|
||||
// ..}
|
||||
|
||||
else{
|
||||
imgArray=mContext.getResources().obtainTypedArray(R.array.device_unknown);
|
||||
|
||||
if((online)&&(controlType.equals(c.val_local_control))) {
|
||||
//local online
|
||||
bitmap = BitmapFactory.decodeResource(mContext.getResources(), imgArray.getResourceId(0, -1));
|
||||
}
|
||||
else if((!online)&&(controlType.equals(c.val_local_control))) {
|
||||
//local offline
|
||||
bitmap = BitmapFactory.decodeResource(mContext.getResources(), imgArray.getResourceId(1, -1));
|
||||
}
|
||||
else if((online)&&(controlType.equals(c.val_cloud_control))){
|
||||
//cloud online
|
||||
bitmap = BitmapFactory.decodeResource(mContext.getResources(), imgArray.getResourceId(2, -1));
|
||||
}
|
||||
else {
|
||||
//cloud offline
|
||||
bitmap = BitmapFactory.decodeResource(mContext.getResources(), imgArray.getResourceId(3, -1));
|
||||
}
|
||||
}
|
||||
imgArray.recycle();
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
public synchronized String getDeviceMac(int idx)throws JSONException{
|
||||
if((idx<0)||(idx>jArray.length())){
|
||||
return null;
|
||||
}
|
||||
return jArray.getJSONObject(idx).getString(c.key_mac);
|
||||
}
|
||||
|
||||
public synchronized String getDeviceServiceName(String mac)throws JSONException{
|
||||
int idx=deviceLookup(mac);
|
||||
if(idx==c.val_device_not_found){
|
||||
return null;
|
||||
}
|
||||
return jArray.getJSONObject(idx).getString(c.key_service_name);
|
||||
}
|
||||
|
||||
|
||||
public synchronized String getDeviceControlType(String mac)throws JSONException{
|
||||
int idx=deviceLookup(mac);
|
||||
if (idx==c.val_device_not_found){
|
||||
return null;
|
||||
}
|
||||
return jArray.getJSONObject(idx).getString(c.key_control_type);
|
||||
}
|
||||
|
||||
|
||||
public synchronized String getDeviceSharedKey(String mac) throws JSONException{
|
||||
int idx=deviceLookup(mac);
|
||||
if(idx==c.val_device_not_found){
|
||||
return null;
|
||||
}
|
||||
return jArray.getJSONObject(idx).getString(c.key_shared_key);
|
||||
}
|
||||
|
||||
public synchronized String getDeviceDescription(String mac)throws JSONException{
|
||||
int idx=deviceLookup(mac);
|
||||
if(idx==c.val_device_not_found){
|
||||
return null;
|
||||
}
|
||||
else {
|
||||
return jArray.getJSONObject(idx).getString(c.key_device_description);
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized boolean setDeviceDescription(String mac, String description)throws JSONException,IOException{
|
||||
int idx=deviceLookup(mac);
|
||||
if(idx==c.val_device_not_found){
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
jArray.getJSONObject(idx).put(c.key_device_description,description);
|
||||
saveChange();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized String getDeviceFirebaseAppId(String mac)throws JSONException{
|
||||
int idx =deviceLookup(mac);
|
||||
if(idx==c.val_device_not_found){
|
||||
return null;
|
||||
}
|
||||
else if(jArray.getJSONObject(idx).getString(c.key_control_type).equals(c.val_local_control)){
|
||||
return null;
|
||||
}
|
||||
else {
|
||||
return jArray.getJSONObject(idx).getString(c.key_firebase_app_id);
|
||||
}
|
||||
}
|
||||
public synchronized int size(){
|
||||
return jArray.length();
|
||||
}
|
||||
|
||||
public synchronized String tempListGetMac(int idx){
|
||||
if((idx<0)||(idx>tempList.size())){
|
||||
return null;
|
||||
}
|
||||
return tempList.elementAt(idx).getInfo().getPropertyString(c.key_mac);
|
||||
}
|
||||
|
||||
public synchronized ServiceEvent tempListGetDeviceServiceEvent(String mac){
|
||||
for (int i=0;i<tempList.size();i++){
|
||||
if (mac.equals(tempListGetMac(i))) {
|
||||
return tempList.elementAt(i);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public synchronized void tempListUpdate(ServiceEvent serviceEvent)throws JSONException,IOException{
|
||||
String mac = serviceEvent.getInfo().getPropertyString(c.key_mac);
|
||||
String pairState = serviceEvent.getInfo().getPropertyString(c.key_pair_state);
|
||||
if((pairState.equals(c.val_not_paired))&&(tempListDeviceLookup(mac)==c.val_device_not_found)){
|
||||
tempList.add(serviceEvent);
|
||||
Log.v(c.tag_device_list,"tempListUpdate(): tempList.add("+mac+")"+"with pair state "+pairState);
|
||||
if((deviceLookup(mac)!=c.val_device_not_found)&&(transientListLookup(mac)==c.val_device_not_found)){
|
||||
removeDevice(mac);
|
||||
Log.v(c.tag_device_list, "tempListUpdate(): removeDevice(" + mac + ")"+"with pair state "+pairState);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if(transientListLookup(mac)!=c.val_device_not_found){
|
||||
tempListRemoveDevice(mac);
|
||||
Log.v(c.tag_device_list, "tempListUpdate(): tempListRemoveDevice(" + mac + ")"+"with pair state "+pairState);
|
||||
transientListRemoveDevice(mac);
|
||||
Log.v(c.tag_device_list, "tempListUpdate(): transientListRemoveDevice(" + mac + ")"+"with pair state "+pairState);
|
||||
}
|
||||
else {
|
||||
if((tempListDeviceLookup(mac)==c.val_device_not_found)&&(deviceLookup(mac)==c.val_device_not_found)){
|
||||
tempList.add(serviceEvent);
|
||||
Log.v(c.tag_device_list, "tempListUpdate(): tempList.add(" + mac + ")"+"with pair state "+pairState);
|
||||
}
|
||||
}
|
||||
trackingListUpdate(serviceEvent);
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized boolean tempListRemoveDevice(String mac){
|
||||
int idx=tempListDeviceLookup(mac);
|
||||
if(idx==c.val_device_not_found){
|
||||
return false;
|
||||
}
|
||||
tempList.remove(idx);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public synchronized int tempListDeviceLookup(String mac){
|
||||
for (int i=0;i<tempList.size();i++)
|
||||
{
|
||||
if (mac.equals(tempListGetMac(i))){
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return c.val_device_not_found;
|
||||
}
|
||||
|
||||
public synchronized int tempListSize(){
|
||||
return tempList.size();
|
||||
}
|
||||
|
||||
public synchronized String trackingListGetMac(int idx){
|
||||
if((idx<0)||(idx>trackingList.size())){
|
||||
return null;
|
||||
}
|
||||
return trackingList.elementAt(idx).getInfo().getPropertyString(c.key_mac);
|
||||
}
|
||||
|
||||
public synchronized int trackingListDeviceLookup(String mac){
|
||||
for (int i=0;i<trackingList.size();i++)
|
||||
{
|
||||
if (mac.equals(trackingListGetMac(i))){
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return c.val_device_not_found;
|
||||
}
|
||||
|
||||
public synchronized boolean trackingListFindDeviceOnline(String mac){
|
||||
int idx = trackingListDeviceLookup(mac);
|
||||
|
||||
if(idx==c.val_device_not_found){
|
||||
return false;
|
||||
}
|
||||
|
||||
ServiceEvent event = trackingListGetDeviceServiceEvent(mac);
|
||||
String mPairState = event.getInfo().getPropertyString(c.key_pair_state);
|
||||
|
||||
if(mPairState.equals(c.val_not_paired)){
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public synchronized String trackingListGetDeviceIp(String mac){
|
||||
int idx = trackingListDeviceLookup(mac);
|
||||
if(idx!=c.val_device_not_found){
|
||||
return trackingListGetDeviceServiceEvent(mac).getInfo().getPropertyString(c.key_ip);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public synchronized int trackingListGetDevicePort(String mac){
|
||||
int idx = trackingListDeviceLookup(mac);
|
||||
if(idx!=c.val_device_not_found){
|
||||
return Integer.parseInt(trackingListGetDeviceServiceEvent(mac).getInfo().getPropertyString(c.key_port));
|
||||
}
|
||||
return c.val_device_not_found;
|
||||
}
|
||||
|
||||
public synchronized ServiceEvent trackingListGetDeviceServiceEvent(String mac){
|
||||
for (int i=0;i<trackingList.size();i++){
|
||||
if (mac.equals(trackingListGetMac(i))) {
|
||||
return trackingList.elementAt(i);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public synchronized void trackingListUpdate(ServiceEvent serviceEvent)throws JSONException{
|
||||
String mac = serviceEvent.getInfo().getPropertyString(c.key_mac);
|
||||
String pairState = serviceEvent.getInfo().getPropertyString(c.key_pair_state);
|
||||
if(trackingListDeviceLookup(mac)!=c.val_device_not_found){
|
||||
trackingListRemoveDevice(mac);
|
||||
Log.v(c.tag_device_list, "trackingListUpdate(): trackingListRemoveDevice(" + mac + ") with pair state " + pairState);
|
||||
}
|
||||
trackingList.add(serviceEvent);
|
||||
downListRemoveDevice(mac);
|
||||
Log.v(c.tag_device_list, "trackingListUpdate(): trackingList.add(" + mac + ") with pair state "+pairState);
|
||||
}
|
||||
|
||||
public synchronized boolean trackingListRemoveDevice(String mac){
|
||||
int idx = trackingListDeviceLookup(mac);
|
||||
if(idx!=c.val_device_not_found){
|
||||
trackingList.remove(idx);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public synchronized int transientListLookup(String mac){
|
||||
for(int i= 0; i<transientList.size();i++){
|
||||
if(mac.equals(transientList.get(i).getInfo().getPropertyString(c.key_mac))){
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return c.val_device_not_found;
|
||||
}
|
||||
|
||||
public synchronized boolean transientListRemoveDevice(String mac){
|
||||
int idx = transientListLookup(mac);
|
||||
if(idx!=c.val_device_not_found){
|
||||
transientList.remove(idx);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public synchronized boolean transientListAddDevice(ServiceEvent serviceEvent){
|
||||
String mac = serviceEvent.getInfo().getPropertyString(c.key_mac);
|
||||
int idx = transientListLookup(mac);
|
||||
if (idx ==c.val_device_not_found){
|
||||
transientList.add(serviceEvent);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public synchronized int downListLookup(String mac){
|
||||
for (int i=0;i<downList.size();i++){
|
||||
if(downList.elementAt(i).equals(mac)){
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return c.val_device_not_found;
|
||||
}
|
||||
|
||||
public synchronized boolean downListRemoveDevice(String mac){
|
||||
int idx=downListLookup(mac);
|
||||
if(idx!=c.val_device_not_found){
|
||||
downList.remove(idx);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public synchronized boolean downListAddDevice(String mac){
|
||||
int idx=downListLookup(mac);
|
||||
if(idx==c.val_device_not_found){
|
||||
downList.addElement(mac);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static synchronized DeviceList getInstance(Context mContext)throws JSONException,IOException{
|
||||
if(thisDeviceList ==null){
|
||||
thisDeviceList = new DeviceList(mContext);
|
||||
load();
|
||||
}
|
||||
return thisDeviceList;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,461 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.app.AlertDialog;
|
||||
import android.app.Fragment;
|
||||
import android.app.FragmentManager;
|
||||
import android.app.ProgressDialog;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.drawable.AnimationDrawable;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.util.Log;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.EditText;
|
||||
import android.widget.GridView;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.json.JSONException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import javax.jmdns.ServiceEvent;
|
||||
|
||||
public class FindDeviceFragment extends Fragment {
|
||||
static final Constants c = Constants.getInstance();
|
||||
private AES128 mAES = new AES128();
|
||||
private GridView gridView;
|
||||
private GridViewAdapter gridAdapter;
|
||||
private DeviceList mDeviceList;
|
||||
private ConnectionChecker connectionChecker;
|
||||
|
||||
private Handler mHandler;
|
||||
|
||||
public FindDeviceFragment() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
getActivity().setTitle(R.string.find_device_fragment_title);
|
||||
}
|
||||
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
|
||||
|
||||
View rootView = inflater.inflate(R.layout.fragment_find_device, container, false);
|
||||
|
||||
try {
|
||||
mDeviceList = DeviceList.getInstance(getActivity().getApplicationContext());
|
||||
} catch (JSONException e) {
|
||||
Log.e(c.tag_find_device_fragment, "init mDeviceList JSONException e --" + e);
|
||||
} catch (IOException e) {
|
||||
Log.e(c.tag_find_device_fragment, "init mDeviceList IOException e --" + e);
|
||||
}
|
||||
|
||||
///////////////////////////////////show animation///////////////////////////////////
|
||||
ImageView iv = (ImageView) rootView.findViewById(R.id.animation);
|
||||
iv.setBackgroundResource(R.drawable.animation);
|
||||
final AnimationDrawable anim = (AnimationDrawable) iv.getBackground();
|
||||
|
||||
rootView.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
anim.start();
|
||||
}
|
||||
});
|
||||
///////////////////////////////////show animation///////////////////////////////////
|
||||
|
||||
|
||||
/////////////////////////////////set gridview/////////////////////////////////////////
|
||||
|
||||
gridView = (GridView) rootView.findViewById(R.id.find_device_gridView);
|
||||
try {
|
||||
gridAdapter = new GridViewAdapter(getActivity(), R.layout.layout_grid_view_item, getDeviceIcons());
|
||||
} catch (JSONException e) {
|
||||
Log.e(c.tag_find_device_fragment, "JSONException e --" + e);
|
||||
}
|
||||
|
||||
gridView.setAdapter(gridAdapter);
|
||||
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
|
||||
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
|
||||
|
||||
//get mac addr from position:
|
||||
String mac = gridAdapter.getDeviceIconAt(position).getDeviceMac();
|
||||
Log.v(c.tag_find_device_fragment, "clicked on device :" + mac);
|
||||
//pair device
|
||||
popupOptions(id);
|
||||
}
|
||||
});
|
||||
/////////////////////////////////set gridview/////////////////////////////////////////
|
||||
|
||||
|
||||
/////////////////////////////////update ui thread/////////////////////////////////////
|
||||
mHandler=new Handler();
|
||||
startUpdateUi();
|
||||
/////////////////////////////////update ui thread/////////////////////////////////////
|
||||
|
||||
|
||||
return rootView;
|
||||
}
|
||||
|
||||
|
||||
private void popupOptions(final long id) {
|
||||
|
||||
final boolean alreadyPaired;
|
||||
|
||||
//test if the device is paired
|
||||
String mMAC = gridAdapter.getDeviceIconAt((int) id).getDeviceMac();
|
||||
ServiceEvent serviceEvent = mDeviceList.tempListGetDeviceServiceEvent(mMAC);
|
||||
if (serviceEvent.getInfo().getPropertyString(c.key_pair_state).equals(c.val_paired)) {
|
||||
alreadyPaired = true;
|
||||
} else {
|
||||
alreadyPaired = false;
|
||||
}
|
||||
|
||||
//setup popup
|
||||
final ImageListAdapter adapter;
|
||||
if (alreadyPaired) {
|
||||
adapter = new ImageListAdapter(getView().getContext(), getResources().getStringArray(R.array.find_device_popup_share));
|
||||
} else {
|
||||
adapter = new ImageListAdapter(getView().getContext(), getResources().getStringArray(R.array.find_device_popup_pair));
|
||||
}
|
||||
|
||||
final AlertDialog.Builder builder = new AlertDialog.Builder(getView().getContext());
|
||||
|
||||
|
||||
builder.setTitle(R.string.popup_dialog_title_options);
|
||||
builder.setCancelable(true);
|
||||
|
||||
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
|
||||
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int index) {
|
||||
|
||||
///////////////switch controls/////////////////
|
||||
if (index == 0) {
|
||||
if (alreadyPaired) {
|
||||
/*share device*/
|
||||
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "Device Sharing\nWill be supported in the future release", Toast.LENGTH_SHORT);
|
||||
toast.show();
|
||||
} else {
|
||||
final String mac = gridAdapter.getDeviceIconAt((int) id).getDeviceMac();
|
||||
final String controlType = mDeviceList.tempListGetDeviceServiceEvent(mac).getInfo().getPropertyString(c.key_control_type);
|
||||
final String[] firebaseAppId = {c.val_empty};
|
||||
|
||||
final String description = gridAdapter.getDeviceIconAt((int) id).getDeviceDescription();
|
||||
final int[] result = {c.err_pairing_failed_to_start};
|
||||
|
||||
////////////////////////////////////////pairing blocks////////////////////////////////////////
|
||||
if (controlType.equals(c.val_cloud_control)) {
|
||||
//cloud pairing process: 1. get firebase app id 2. pairing
|
||||
LayoutInflater inflater;
|
||||
View promptsView;
|
||||
AlertDialog.Builder dialogBuilder;
|
||||
final EditText etUserInput;
|
||||
|
||||
inflater = LayoutInflater.from(getActivity());
|
||||
promptsView = inflater.inflate(R.layout.layout_popup_dialog_prompts_firebase_app_id, null);
|
||||
|
||||
dialogBuilder = new AlertDialog.Builder(getActivity());
|
||||
dialogBuilder.setView(promptsView);
|
||||
etUserInput = (EditText) promptsView.findViewById(R.id.editText_firebase_app_id);
|
||||
|
||||
dialogBuilder.setCancelable(true);
|
||||
|
||||
dialogBuilder.setPositiveButton("OK",
|
||||
new DialogInterface.OnClickListener() {
|
||||
public void onClick(DialogInterface dialog, int id) {
|
||||
firebaseAppId[0] = etUserInput.getText().toString();
|
||||
if (firebaseAppId[0].equals(c.val_empty)) {
|
||||
Toast.makeText(getActivity().getApplicationContext(), "Firebase app id is empty, pairing canceled", Toast.LENGTH_LONG).show();
|
||||
} else {
|
||||
/////////////////////////////cloud pairing///////////////////////////////
|
||||
final ProgressDialog progress = ProgressDialog.show(getActivity(), "Device Pairing", "Adding new device: " + description, true);
|
||||
new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
connectionChecker = new ConnectionChecker();
|
||||
|
||||
getActivity().runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
Toast.makeText(getActivity().getApplicationContext(), "Verifying Firebase App Id: " + firebaseAppId[0], Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
|
||||
if (connectionChecker.testConnection(firebaseAppId[0])) {
|
||||
result[0] = pairing(mac, firebaseAppId[0]);
|
||||
}
|
||||
else {
|
||||
|
||||
getActivity().runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
Toast.makeText(getActivity().getApplicationContext(), "Verify Firebase App Id Failed", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
|
||||
result[0] = c.err_firebase_app_url_cannot_be_verified;
|
||||
}
|
||||
|
||||
getActivity().runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
progress.dismiss();
|
||||
if (result[0] == c.val_pairing_succeed) {
|
||||
Toast.makeText(getActivity().getApplicationContext(), "Pairing succeed, device saved !", Toast.LENGTH_SHORT).show();
|
||||
////////////////////////switch fragment////////////////////////
|
||||
Fragment fragment = new MyDeviceFragment();
|
||||
FragmentManager fragmentManager = getFragmentManager();
|
||||
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
|
||||
////////////////////////switch fragment////////////////////////
|
||||
} else {
|
||||
Toast.makeText(getActivity().getApplicationContext(), "Pairing failed, err code: " + result[0], Toast.LENGTH_LONG).show();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}).start();
|
||||
////////////////////////////cloud pairing////////////////////////////////
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
dialogBuilder.setNeutralButton("Register Firebase",
|
||||
new DialogInterface.OnClickListener() {
|
||||
public void onClick(DialogInterface dialog, int id) {
|
||||
|
||||
Intent intent = new Intent(getActivity(), RegisterFirebaseAccountActivity.class);
|
||||
startActivity(intent);
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
AlertDialog alertDialog = dialogBuilder.create();
|
||||
alertDialog.show();
|
||||
|
||||
} else {
|
||||
//local pairing process
|
||||
/////////////////////////////local pairing///////////////////////////////
|
||||
final ProgressDialog progress = ProgressDialog.show(getActivity(), "Device Pairing", "Adding new device: " + description, true);
|
||||
|
||||
new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
result[0] = pairing(mac, firebaseAppId[0]);
|
||||
|
||||
getActivity().runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
progress.dismiss();
|
||||
if (result[0] == c.val_pairing_succeed) {
|
||||
Toast.makeText(getActivity().getApplicationContext(), "Pairing succeed, device saved !", Toast.LENGTH_SHORT).show();
|
||||
////////////////////////switch fragment////////////////////////
|
||||
Fragment fragment = new MyDeviceFragment();
|
||||
FragmentManager fragmentManager = getFragmentManager();
|
||||
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
|
||||
////////////////////////switch fragment////////////////////////
|
||||
} else {
|
||||
Toast.makeText(getActivity().getApplicationContext(), "Pairing failed, err code: " + result[0], Toast.LENGTH_LONG).show();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}).start();
|
||||
|
||||
}
|
||||
/////////////////////////////local pairing///////////////////////////////
|
||||
|
||||
////////////////////////////////////////pairing blocks////////////////////////////////////////
|
||||
|
||||
}
|
||||
} else {
|
||||
//nothing, only one item in the list
|
||||
}
|
||||
}
|
||||
});
|
||||
builder.show();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Prepare data for gridview
|
||||
*/
|
||||
private synchronized ArrayList<DeviceIcon> getDeviceIcons() throws JSONException {
|
||||
final ArrayList<DeviceIcon> deviceIcons = new ArrayList<>();
|
||||
for (int i = 0; i < mDeviceList.tempListSize(); i++) {
|
||||
String mac = mDeviceList.tempListGetMac(i);
|
||||
|
||||
String name = mDeviceList.tempListGetDeviceServiceEvent(mac).getInfo().getPropertyString(c.key_service_name);
|
||||
String controlType = mDeviceList.tempListGetDeviceServiceEvent(mac).getInfo().getPropertyString(c.key_control_type);
|
||||
String append = mac;
|
||||
if(mac.length()<5){
|
||||
append=mac+"WU:JZ";
|
||||
}
|
||||
if (mDeviceList.tempListGetDeviceServiceEvent(mac).getInfo().getPropertyString(c.key_pair_state).equals(c.val_paired)) {
|
||||
name += " "+append.substring((append.length()-5),(append.length()))+" (Paired)";
|
||||
} else {
|
||||
name += " "+append.substring((append.length()-5),(append.length()))+" (Unpaired)";
|
||||
}
|
||||
|
||||
Bitmap icon;
|
||||
if (mDeviceList.tempListGetDeviceServiceEvent(mac).getInfo().getPropertyString(c.key_service_name).equals(c.nsd_service_ht)) {
|
||||
icon = mDeviceList.getDeviceIcon(c.nsd_service_ht, controlType, true);
|
||||
} else {
|
||||
icon = mDeviceList.getDeviceIcon(c.nsd_service_unknown, controlType, true);
|
||||
}
|
||||
|
||||
deviceIcons.add(new DeviceIcon(icon, name, mac));
|
||||
}
|
||||
return deviceIcons;
|
||||
}
|
||||
|
||||
|
||||
private int pairing (String mac, String firebaseAppId){
|
||||
|
||||
final String ip = mDeviceList.tempListGetDeviceServiceEvent(mac).getInfo().getHostAddresses()[0];
|
||||
final int port = mDeviceList.tempListGetDeviceServiceEvent(mac).getInfo().getPort();
|
||||
|
||||
try {
|
||||
|
||||
KeyGen keyGen = KeyGen.getInstance();
|
||||
|
||||
TcpClient tcpClient = new TcpClient();
|
||||
|
||||
String rx = tcpClient.echo(InetAddress.getByName(ip),port,c.tcp_tx_pair);
|
||||
|
||||
if(rx==null){
|
||||
return c.err_server_no_response;
|
||||
}
|
||||
|
||||
if(rx.equals(c.tcp_rx_error)){
|
||||
return c.err_pair_cmd_rejected;
|
||||
}
|
||||
|
||||
keyGen.makeKeys(rx);
|
||||
|
||||
rx = tcpClient.echo(InetAddress.getByName(ip), port, keyGen.getPublicKeyString());
|
||||
|
||||
if(rx==null){
|
||||
return c.err_server_no_response;
|
||||
}
|
||||
|
||||
if (rx.equals(c.tcp_rx_error)){
|
||||
return c.err_public_key_rejected;
|
||||
}
|
||||
|
||||
String serviceName = mDeviceList.tempListGetDeviceServiceEvent(mac).getInfo().getPropertyString(c.key_service_name);
|
||||
String controlType = mDeviceList.tempListGetDeviceServiceEvent(mac).getInfo().getPropertyString(c.key_control_type);
|
||||
String aes128Key = keyGen.getAES128KeyString();
|
||||
|
||||
String append =mac;
|
||||
if(mac.length()<5){
|
||||
append=mac+"WU:JZ";
|
||||
}
|
||||
|
||||
String description = "[New] "+serviceName +" "+append.substring((append.length()-5),(append.length()));
|
||||
|
||||
if(rx.equals(c.tcp_rx_pair_ok)){
|
||||
try {
|
||||
//if device with same mac is already in the list, remove it first
|
||||
int idx = mDeviceList.deviceLookup(mac);
|
||||
if(idx!=c.val_device_not_found){
|
||||
mDeviceList.removeDevice(mac);
|
||||
}
|
||||
mDeviceList.transientListAddDevice(mDeviceList.tempListGetDeviceServiceEvent(mac));
|
||||
mDeviceList.addDevice(mac,serviceName,controlType,firebaseAppId,aes128Key,description);
|
||||
}
|
||||
catch (JSONException e){Log.e(c.tag_find_device_fragment,"pairing() JSONException e "+e);}
|
||||
|
||||
return c.val_pairing_succeed;
|
||||
}
|
||||
|
||||
if(rx.equals(c.tcp_rx_firebase_app_url)){
|
||||
String firebaseAppUrl = "https://"+firebaseAppId+".firebaseio.com";
|
||||
String txEnc=null;
|
||||
|
||||
try {
|
||||
txEnc= mAES.encryptToStringOfShortArray(firebaseAppUrl,aes128Key);
|
||||
}
|
||||
catch (Exception e){Log.e(c.tag_find_device_fragment,"pairing() Exception e"+e);}
|
||||
|
||||
rx = tcpClient.echo(InetAddress.getByName(ip), port, txEnc);
|
||||
|
||||
if(rx==null){
|
||||
return c.err_server_no_response;
|
||||
}
|
||||
|
||||
if(rx.equals(c.tcp_rx_error)){
|
||||
return c.err_firebase_app_url_rejected;
|
||||
}
|
||||
|
||||
if(rx.equals(c.tcp_rx_pair_ok)){
|
||||
try {
|
||||
//if device with same mac is already in the list, remove it first
|
||||
int idx = mDeviceList.deviceLookup(mac);
|
||||
if(idx!=c.val_device_not_found){
|
||||
mDeviceList.removeDevice(mac);
|
||||
}
|
||||
mDeviceList.transientListAddDevice(mDeviceList.tempListGetDeviceServiceEvent(mac));
|
||||
mDeviceList.addDevice(mac,serviceName,controlType,firebaseAppId,aes128Key,description);
|
||||
}
|
||||
catch (JSONException e){Log.e(c.tag_find_device_fragment,"pairing() JSONException e "+e);}
|
||||
return c.val_pairing_succeed;
|
||||
}
|
||||
}
|
||||
return c.err_unknown_error;
|
||||
}
|
||||
catch (UnknownHostException e){
|
||||
Log.e(c.tag_find_device_fragment, "pairing() UnknownHostException e " + e);
|
||||
return c.err_unknown_host_exception;
|
||||
}
|
||||
catch (InterruptedException e){
|
||||
Log.e(c.tag_find_device_fragment,"InterruptedException e"+e);
|
||||
return c.err_interrupted_exception;
|
||||
}
|
||||
catch (IOException e){
|
||||
Log.e(c.tag_find_device_fragment,"IOException e"+e);
|
||||
return c.err_io_exception;
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////update ui////////////////////////////
|
||||
|
||||
Runnable updateUiCallback = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
////////////////////update ui////////////////////
|
||||
if(getActivity() != null) {
|
||||
try {
|
||||
gridAdapter = new GridViewAdapter(getActivity(), R.layout.layout_grid_view_item, getDeviceIcons());
|
||||
gridView.setAdapter(gridAdapter);
|
||||
} catch (JSONException e) {
|
||||
Log.e(c.tag_find_device_fragment, "updateUiCallback JSONException e " + e);
|
||||
}
|
||||
}
|
||||
////////////////////update ui////////////////////
|
||||
mHandler.postDelayed(updateUiCallback, c.val_ui_update_period_ms);
|
||||
}
|
||||
};
|
||||
|
||||
void startUpdateUi() {
|
||||
updateUiCallback.run();
|
||||
}
|
||||
|
||||
void stopUpdateUi() {
|
||||
mHandler.removeCallbacks(updateUiCallback);
|
||||
}
|
||||
|
||||
///////////////////////////update ui////////////////////////////
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class GridViewAdapter extends ArrayAdapter<DeviceIcon> {
|
||||
|
||||
private Context context;
|
||||
private int layoutResourceId;
|
||||
private ArrayList<DeviceIcon> iconArrayList = new ArrayList<DeviceIcon>();
|
||||
|
||||
public GridViewAdapter(Context context, int layoutResourceId, ArrayList<DeviceIcon> iconArrayList) {
|
||||
super(context, layoutResourceId, iconArrayList);
|
||||
this.layoutResourceId = layoutResourceId;
|
||||
this.context = context;
|
||||
this.iconArrayList = iconArrayList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public View getView(int position, View convertView, ViewGroup parent) {
|
||||
View row = convertView;
|
||||
ViewHolder holder;
|
||||
|
||||
if (row == null) {
|
||||
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
|
||||
row = inflater.inflate(layoutResourceId, parent, false);
|
||||
holder = new ViewHolder();
|
||||
holder.deviceDescription = (TextView) row.findViewById(R.id.text);
|
||||
holder.deviceIcon = (ImageView) row.findViewById(R.id.image);
|
||||
row.setTag(holder);
|
||||
} else {
|
||||
holder = (ViewHolder) row.getTag();
|
||||
}
|
||||
|
||||
|
||||
DeviceIcon item = iconArrayList.get(position);
|
||||
holder.deviceDescription.setText(item.getDeviceDescription());
|
||||
holder.deviceIcon.setImageBitmap(item.getDeviceIcon());
|
||||
return row;
|
||||
}
|
||||
|
||||
static class ViewHolder {
|
||||
TextView deviceDescription;
|
||||
ImageView deviceIcon;
|
||||
}
|
||||
|
||||
public DeviceIcon getDeviceIconAt(int idx){
|
||||
return iconArrayList.get(idx);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,387 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.SharedPreferences;
|
||||
import android.graphics.Color;
|
||||
import android.media.MediaPlayer;
|
||||
import android.os.Bundle;
|
||||
import android.preference.PreferenceManager;
|
||||
import android.util.Log;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.androidplot.ui.SizeLayoutType;
|
||||
import com.androidplot.ui.SizeMetrics;
|
||||
import com.androidplot.xy.BoundaryMode;
|
||||
import com.androidplot.xy.LineAndPointFormatter;
|
||||
import com.androidplot.xy.PointLabelFormatter;
|
||||
import com.androidplot.xy.SimpleXYSeries;
|
||||
import com.androidplot.xy.XYPlot;
|
||||
import com.androidplot.xy.XYSeries;
|
||||
import com.androidplot.xy.XYStepMode;
|
||||
import com.firebase.client.DataSnapshot;
|
||||
import com.firebase.client.Firebase;
|
||||
import com.firebase.client.FirebaseError;
|
||||
import com.firebase.client.ValueEventListener;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.text.DecimalFormat;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Vector;
|
||||
|
||||
public class HTSensorActivity extends Activity {
|
||||
|
||||
private static final Constants c = Constants.getInstance();
|
||||
private AES128 mAES = new AES128();
|
||||
private String mIp;
|
||||
private int mPort;
|
||||
private String mAESKey;
|
||||
private String mFirebaseAppId;
|
||||
private String mMac;
|
||||
private String mDescription;
|
||||
private TextView textViewTemp;
|
||||
private TextView textViewHumi;
|
||||
|
||||
private boolean runLocalLink = true;
|
||||
private boolean runCloudLink = true;
|
||||
|
||||
private XYPlot plot;
|
||||
private List<Double> timeList= new Vector<>();
|
||||
private List<Double> temperatureList=new Vector<>();
|
||||
private List<Double> humidityList=new Vector<>();
|
||||
private int maxListSize = 6;
|
||||
private long timeCounter = 0;
|
||||
private boolean receivedNewData =false;
|
||||
private SharedPreferences sp;
|
||||
private int dataUpdateDelay = c.val_ht_sensor_default_data_update_frequency;
|
||||
private boolean alarmOptions = c.val_ht_sensor_default_alarm_options;
|
||||
private double tempTresh = c.val_ht_sensor_default_temperature_threshold;
|
||||
private double humiTresh = c.val_ht_sensor_default_humidity_threshold;
|
||||
private String alarmSound = c.val_ht_sensor_default_alarm_sound;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_device_ht);
|
||||
|
||||
mIp=getIntent().getStringExtra(c.key_ip);
|
||||
mPort=getIntent().getIntExtra(c.key_port, c.val_device_not_found);
|
||||
mMac=getIntent().getStringExtra(c.key_mac);
|
||||
mAESKey=getIntent().getStringExtra(c.key_shared_key);
|
||||
mFirebaseAppId=getIntent().getStringExtra(c.key_firebase_app_id);
|
||||
mDescription=getIntent().getStringExtra(c.key_device_description);
|
||||
|
||||
setTitle(mDescription);
|
||||
|
||||
textViewTemp = (TextView)findViewById(R.id.textViewTemperature);
|
||||
textViewHumi = (TextView)findViewById(R.id.textViewHumidity);
|
||||
|
||||
loadSharedPreference();
|
||||
|
||||
if((!mIp.equals(c.val_empty))&&(mPort!=c.val_device_not_found)){
|
||||
try {
|
||||
amebaLocalLink(mIp, mPort);
|
||||
}
|
||||
catch (Exception e){
|
||||
Log.e(c.tag_ht_sensor_activity,"connectToAmeba() Exception e "+e);
|
||||
}
|
||||
}
|
||||
else {
|
||||
amebaCloudLink(mFirebaseAppId);
|
||||
}
|
||||
|
||||
plotChart();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
runLocalLink = false;
|
||||
runCloudLink = false;
|
||||
Log.v(c.tag_ht_sensor_activity, "onDestroy()");
|
||||
}
|
||||
|
||||
|
||||
private void loadSharedPreference(){
|
||||
sp = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
|
||||
dataUpdateDelay = Integer.parseInt(sp.getString(c.key_ht_sensor_data_update_frequency, Integer.toString(dataUpdateDelay)));
|
||||
alarmOptions = sp.getBoolean(c.key_ht_sensor_alarm_options,false);
|
||||
tempTresh = Double.parseDouble(sp.getString(c.key_ht_sensor_temperature_threshold, Double.toString(tempTresh)));
|
||||
humiTresh=Double.parseDouble(sp.getString(c.key_ht_sensor_humidity_threshold,Double.toString(humiTresh)));
|
||||
alarmSound=sp.getString(c.key_ht_sensor_alarm_sound, alarmSound);
|
||||
}
|
||||
|
||||
private void playAlarm(double temp, double humi){
|
||||
if((alarmOptions)&&((temp>tempTresh)||(humi>humiTresh))){
|
||||
String sound = alarmSound;
|
||||
MediaPlayer mediaPlayer;
|
||||
|
||||
if(sound.equals(c.val_ht_sensor_alarm_sound_altair)){
|
||||
mediaPlayer = MediaPlayer.create(this, R.raw.sound_altair);
|
||||
}
|
||||
else if(sound.equals(c.val_ht_sensor_alarm_sound_ariel)){
|
||||
mediaPlayer = MediaPlayer.create(this,R.raw.sound_ariel);
|
||||
}
|
||||
else if(sound.equals(c.val_ht_sensor_alarm_sound_fomalhaut)){
|
||||
mediaPlayer = MediaPlayer.create(this,R.raw.sound_fomalhaut);
|
||||
}
|
||||
else if(sound.equals(c.val_ht_sensor_alarm_sound_tinkerbell)){
|
||||
mediaPlayer = MediaPlayer.create(this,R.raw.sound_tinkerbell);
|
||||
}
|
||||
else {
|
||||
mediaPlayer = MediaPlayer.create(this,R.raw.sound_ding);
|
||||
}
|
||||
|
||||
mediaPlayer.start();
|
||||
}
|
||||
}
|
||||
|
||||
private void amebaLocalLink(String ip, int port)throws Exception{
|
||||
|
||||
final TcpClient tcpClient = new TcpClient();
|
||||
Log.v(c.tag_ht_sensor_activity, "amebaLocalLink() ip/port: " + ip + "/" + port);
|
||||
Log.v(c.tag_ht_sensor_activity, "amebaLocalLink() AES key: " + mAESKey);
|
||||
|
||||
final String mIp=ip;
|
||||
final int mPort=port;
|
||||
|
||||
class AmebaLocalLinkGetDataThread extends Thread{
|
||||
@Override
|
||||
public void run() {
|
||||
while (runLocalLink){
|
||||
try {
|
||||
Thread.sleep(dataUpdateDelay);
|
||||
Log.v(c.tag_ht_sensor_activity,"amebaLocalLink() get data frequency: Every "+dataUpdateDelay+"ms");
|
||||
}
|
||||
catch (InterruptedException e){Log.e(c.tag_ht_sensor_activity,"AmebaLocalLinkGetDataThread InterruptedException e"+e);}
|
||||
|
||||
try {
|
||||
String txEnc = mAES.encryptToStringOfShortArray("request", mAESKey);
|
||||
Log.v(c.tag_ht_sensor_activity, "amebaLocalLink() txEnc: " + txEnc);
|
||||
|
||||
String rxEnc = tcpClient.echo(InetAddress.getByName(mIp), mPort, txEnc);
|
||||
Log.v(c.tag_ht_sensor_activity,"amebaLocalLink() rxEnc: "+rxEnc);
|
||||
|
||||
String rx = mAES.decryptFromStringOfShortArray(rxEnc,mAESKey);
|
||||
Log.v(c.tag_ht_sensor_activity, "amebaLocalLink() rx: " + rx);
|
||||
|
||||
|
||||
////////////////////////parse json data////////////////////////
|
||||
JSONObject jObject = new JSONObject(rx);
|
||||
final double hum = jObject.getDouble(c.key_humidity);
|
||||
final double tem = jObject.getDouble(c.key_temperature);
|
||||
////////////////////////parse json data////////////////////////
|
||||
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
textViewTemp.setText("" +tem);
|
||||
textViewHumi.setText(""+hum);
|
||||
updateDataList(tem,hum);
|
||||
playAlarm(tem,hum);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
catch (Exception e){Log.e(c.tag_ht_sensor_activity,"AmebaLocalLinkGetDataThread Exception e"+e);}
|
||||
|
||||
}//while(true)
|
||||
}
|
||||
}
|
||||
|
||||
new AmebaLocalLinkGetDataThread().start();
|
||||
}
|
||||
|
||||
|
||||
private void amebaCloudLink(String firebaseAppId){
|
||||
|
||||
String firebaseURL = "https://"+firebaseAppId+".firebaseio.com";
|
||||
Firebase.setAndroidContext(this);
|
||||
|
||||
final Firebase firebaseRef = new Firebase(firebaseURL);
|
||||
|
||||
Log.v(c.tag_ht_sensor_activity, "amebaCloudLink() connect to firebase: " + firebaseURL);
|
||||
|
||||
firebaseRef.child(c.nsd_service_ht).child(mMac).addValueEventListener(new ValueEventListener() {
|
||||
|
||||
@Override
|
||||
public void onDataChange(DataSnapshot snapshot) {
|
||||
if (runCloudLink) {
|
||||
|
||||
Map<String, Object> newData = (Map<String, Object>) snapshot.getValue();
|
||||
|
||||
try {
|
||||
double hum = Double.parseDouble((String) newData.get(c.key_humidity));
|
||||
double tem = Double.parseDouble((String) newData.get(c.key_temperature));
|
||||
textViewTemp.setText("" + tem);
|
||||
textViewHumi.setText("" + hum);
|
||||
updateDataList(tem, hum);
|
||||
playAlarm(tem, hum);
|
||||
Log.v(c.tag_ht_sensor_activity, snapshot.getValue().toString());
|
||||
} catch (Exception e) {
|
||||
Log.e(c.tag_ht_sensor_activity, "onDataChange() Exception e " + e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCancelled(FirebaseError error) {
|
||||
Log.e(c.tag_ht_sensor_activity, "onCancelled() FirebaseError error" + error);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////////////////////plot//////////////////////////////////////////////
|
||||
|
||||
private void plotChart(){
|
||||
|
||||
//init lists
|
||||
timeList.add((double)0);
|
||||
temperatureList.add((double)0);
|
||||
humidityList.add((double)0);
|
||||
|
||||
new Thread() {
|
||||
public void run() {
|
||||
while (runLocalLink) {
|
||||
try {
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
//update plot data
|
||||
timeCounter++;
|
||||
timeList.add((double)timeCounter);
|
||||
while (timeList.size()>maxListSize){
|
||||
timeList.remove(0);
|
||||
}
|
||||
|
||||
//sync data with time:
|
||||
if(!receivedNewData){
|
||||
//push data manually
|
||||
updateDataList(temperatureList.get(temperatureList.size()-1),humidityList.get(humidityList.size()-1));
|
||||
}
|
||||
|
||||
//sync list length
|
||||
//consider 1.when series size < timelist size 2.when series size > timelist size
|
||||
while (temperatureList.size()<timeList.size()){
|
||||
temperatureList.add(temperatureList.get(temperatureList.size()-1));
|
||||
}
|
||||
while (humidityList.size()<timeList.size()){
|
||||
humidityList.add(humidityList.get(humidityList.size()-1));
|
||||
}
|
||||
while (temperatureList.size()>timeList.size()){
|
||||
temperatureList.remove(0);
|
||||
}
|
||||
while (humidityList.size()>timeList.size()){
|
||||
humidityList.remove(0);
|
||||
}
|
||||
|
||||
try{
|
||||
plot.clear();
|
||||
}
|
||||
catch (Exception e){
|
||||
Log.e(c.tag_ht_sensor_activity,"Exception e"+e);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////plot setup//////////////////////////////////////////////////
|
||||
// initialize our XYPlot reference:
|
||||
plot = (XYPlot) findViewById(R.id.mySimpleXYPlot);
|
||||
plot.setBorderStyle(XYPlot.BorderStyle.NONE, null, null);
|
||||
plot.setGridPadding(5, 25, 25, 5);
|
||||
plot.getGraphWidget().setSize(new SizeMetrics(0, SizeLayoutType.FILL, 0, SizeLayoutType.FILL));
|
||||
plot.getGraphWidget().getBackgroundPaint().setColor(Color.argb(0, 0, 0, 0));
|
||||
plot.getGraphWidget().getGridBackgroundPaint().setColor(Color.argb(0, 0, 0, 0));
|
||||
|
||||
//domain -- x
|
||||
plot.getGraphWidget().getDomainLabelPaint().setColor(Color.BLACK);
|
||||
plot.getGraphWidget().getDomainOriginLabelPaint().setColor(Color.BLACK);
|
||||
plot.getGraphWidget().getDomainOriginLinePaint().setColor(Color.BLACK);
|
||||
plot.setDomainValueFormat(new DecimalFormat("0"));
|
||||
plot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 1);
|
||||
plot.setDomainStepValue(1);
|
||||
|
||||
//range -- y
|
||||
plot.getGraphWidget().getRangeLabelPaint().setColor(Color.BLACK);
|
||||
plot.getGraphWidget().getRangeOriginLabelPaint().setColor(Color.BLACK);
|
||||
plot.getGraphWidget().getRangeOriginLinePaint().setColor(Color.BLACK);
|
||||
plot.setRangeValueFormat(new DecimalFormat("0"));
|
||||
plot.setRangeStep(XYStepMode.INCREMENT_BY_VAL, 1);
|
||||
plot.setRangeStepValue(5);
|
||||
|
||||
//label
|
||||
plot.getDomainLabelWidget().getLabelPaint().setColor(Color.BLACK);
|
||||
plot.getRangeLabelWidget().getLabelPaint().setColor(Color.BLACK);
|
||||
|
||||
|
||||
// Create a formatter to use for drawing a series using LineAndPointRenderer
|
||||
// and configure it from xml:
|
||||
LineAndPointFormatter seriesHumiFormat = new LineAndPointFormatter();
|
||||
seriesHumiFormat.setPointLabelFormatter(new PointLabelFormatter());
|
||||
seriesHumiFormat.configure(getApplicationContext(), R.xml.line_point_formatter_with_plf1);
|
||||
|
||||
// same as above:
|
||||
LineAndPointFormatter seriesTempFormat = new LineAndPointFormatter();
|
||||
seriesTempFormat.setPointLabelFormatter(new PointLabelFormatter());
|
||||
seriesTempFormat.configure(getApplicationContext(), R.xml.line_point_formatter_with_plf2);
|
||||
|
||||
|
||||
// reduce the number of range labels
|
||||
plot.setTicksPerRangeLabel(3);
|
||||
plot.getGraphWidget().setDomainLabelOrientation(-45);
|
||||
|
||||
XYSeries seriesHumi = new SimpleXYSeries(timeList, humidityList, "Humidity");
|
||||
XYSeries seriesTemp = new SimpleXYSeries(timeList, temperatureList, "Temperature");
|
||||
plot.addSeries(seriesHumi, seriesHumiFormat);
|
||||
plot.addSeries(seriesTemp, seriesTempFormat);
|
||||
|
||||
// handle the boundary bug -> define a boundary, DO NOT USE DEFAULT SETTINGS
|
||||
List<Double> readings =new Vector<>();
|
||||
for (double r : temperatureList){
|
||||
readings.add(r);
|
||||
}
|
||||
for (double r : humidityList){
|
||||
readings.add(r);
|
||||
}
|
||||
Collections.sort(readings);
|
||||
double min=readings.get(0);
|
||||
double max=readings.get(readings.size()-1);
|
||||
plot.setRangeBoundaries(min,max, BoundaryMode.FIXED);
|
||||
Log.v(c.tag_ht_sensor_activity,"plotChart() set range boundaries ("+min+","+max+")");
|
||||
//////////////////////////////////////////////////plot setup//////////////////////////////////////////////////
|
||||
plot.redraw();
|
||||
receivedNewData=false;
|
||||
Log.v(c.tag_ht_sensor_activity,"plotChart(): List.size:" + timeList.size());
|
||||
Log.v(c.tag_ht_sensor_activity, "plotChart(): temperatureList.end: " + temperatureList.get(temperatureList.size() - 1));
|
||||
Log.v(c.tag_ht_sensor_activity,"plotChart(): humidityList.end: "+humidityList.get(humidityList.size()-1));
|
||||
}
|
||||
});
|
||||
Thread.sleep(c.val_ui_update_period_ms);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}//while()
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
|
||||
private void updateDataList(double temperature, double humidity){
|
||||
|
||||
temperatureList.add(temperature);
|
||||
humidityList.add(humidity);
|
||||
|
||||
while(temperatureList.size()>maxListSize){
|
||||
temperatureList.remove(0);
|
||||
}
|
||||
|
||||
while(humidityList.size()>maxListSize){
|
||||
humidityList.remove(0);
|
||||
}
|
||||
|
||||
receivedNewData =true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.content.Context;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
/**
|
||||
* Created by Wu Jinzhou on 3/24/2015.
|
||||
*/
|
||||
public class ImageListAdapter extends ArrayAdapter<String> {
|
||||
private final Context context;
|
||||
private final String[] values;
|
||||
|
||||
public ImageListAdapter(Context context, String[] values) {
|
||||
super(context, R.layout.layout_popup_dialog_row_cell, values);
|
||||
this.context = context;
|
||||
this.values = values;
|
||||
}
|
||||
|
||||
@Override
|
||||
public View getView(int position, View convertView, ViewGroup parent) {
|
||||
|
||||
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
|
||||
|
||||
View rowView = inflater.inflate(R.layout.layout_popup_dialog_row_cell, parent, false);
|
||||
|
||||
TextView textView = (TextView) rowView.findViewById(R.id.label);
|
||||
|
||||
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
|
||||
|
||||
textView.setText(values[position]);
|
||||
|
||||
// Change the icon for different control options
|
||||
String s = values[position];
|
||||
if (s.equals(getContext().getResources().getString(R.string.option_rename))) {
|
||||
imageView.setImageResource(R.drawable.ic_edit);
|
||||
}
|
||||
if(s.equals(getContext().getResources().getString(R.string.option_remove)))
|
||||
{
|
||||
imageView.setImageResource(R.drawable.ic_delete);
|
||||
}
|
||||
if(s.equals(getContext().getResources().getString(R.string.option_request_share))){
|
||||
imageView.setImageResource(R.drawable.ic_share);
|
||||
}
|
||||
if(s.equals(getContext().getResources().getString(R.string.option_pair_device))){
|
||||
imageView.setImageResource(R.drawable.ic_pair);
|
||||
}
|
||||
|
||||
return rowView;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import org.apaches.commons.codec.digest.DigestUtils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
|
||||
import djb.Curve25519;
|
||||
|
||||
/**
|
||||
* Created by Wu Jinzhou on 4/27/2015.
|
||||
*/
|
||||
public class KeyGen {
|
||||
private static KeyGen thisKeyGen;
|
||||
private KeyGen(){}
|
||||
public static synchronized KeyGen getInstance(){
|
||||
if(thisKeyGen==null){
|
||||
thisKeyGen = new KeyGen();
|
||||
}
|
||||
return thisKeyGen;
|
||||
}
|
||||
|
||||
private static final Constants c = Constants.getInstance();
|
||||
private byte[] a_private_key_byte = new byte[32];
|
||||
private byte[] a_public_key_byte =new byte[32];
|
||||
private byte[] b_public_key_byte =new byte[32];
|
||||
private byte[] shared_key_byte = new byte[32];
|
||||
private byte[] aes_128_key = new byte[16]; //AES 128 bit encryption
|
||||
private short[] a_public_key_short = new short[32];
|
||||
|
||||
public synchronized void makeKeys (String keyB){
|
||||
|
||||
String seed= ((Double)(new Random(System.currentTimeMillis())).nextDouble()).toString();
|
||||
a_private_key_byte = DigestUtils.md5Hex(seed).getBytes();
|
||||
|
||||
a_public_key_byte =new byte[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
|
||||
|
||||
Curve25519.keygen(a_public_key_byte,null, a_private_key_byte);
|
||||
|
||||
String[] items = keyB.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\ ", "").split(",");
|
||||
//String[] items = keyB.split(",");
|
||||
|
||||
int[] results = new int[items.length];
|
||||
|
||||
for (int i = 0; i < items.length; i++) {
|
||||
try {
|
||||
results[i] = Integer.parseInt(items[i]);
|
||||
} catch (NumberFormatException e) {
|
||||
Log.e(c.tag_key_gen,"makeKeys() (NumberFormatException e "+e);
|
||||
}
|
||||
}
|
||||
|
||||
for (int i =0;i<results.length;i++){
|
||||
b_public_key_byte[i]=(byte)results[i];
|
||||
}
|
||||
|
||||
Curve25519.curve(shared_key_byte, a_private_key_byte, b_public_key_byte);
|
||||
|
||||
a_public_key_short=toShort(a_public_key_byte);
|
||||
|
||||
aes_128_key=Arrays.copyOf(shared_key_byte,16);
|
||||
|
||||
Log.v(c.tag_key_gen,"makeKeys() final AES key: "+getAES128KeyString());
|
||||
}
|
||||
|
||||
public synchronized String getPublicKeyString(){
|
||||
return Arrays.toString(a_public_key_short);
|
||||
}
|
||||
|
||||
public synchronized String getAES128KeyString(){
|
||||
return Arrays.toString(aes_128_key);
|
||||
}
|
||||
|
||||
private synchronized short[] toShort (byte[] b){
|
||||
short s [] = new short[b.length];
|
||||
for (int i=0;i<b.length;i++){
|
||||
s[i]=(short)(b[i]&0xff);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,347 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.Fragment;
|
||||
import android.app.FragmentManager;
|
||||
import android.content.Intent;
|
||||
import android.content.res.Configuration;
|
||||
import android.content.res.TypedArray;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.support.v4.app.ActionBarDrawerToggle;
|
||||
import android.support.v4.widget.DrawerLayout;
|
||||
import android.util.Log;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.ListView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.json.JSONException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
|
||||
|
||||
|
||||
public class MainActivity extends Activity {
|
||||
private DrawerLayout mDrawerLayout;
|
||||
private ListView mDrawerList;
|
||||
private ActionBarDrawerToggle mDrawerToggle;
|
||||
|
||||
// nav drawer title
|
||||
private CharSequence mDrawerTitle;
|
||||
|
||||
// used to store app title
|
||||
private CharSequence mTitle;
|
||||
|
||||
// slide menu items
|
||||
private String[] navMenuTitles;
|
||||
private TypedArray navMenuIcons;
|
||||
|
||||
private ArrayList<NavDrawerItem> navDrawerItems;
|
||||
private NavDrawerListAdapter adapter;
|
||||
|
||||
private static final Constants c = Constants.getInstance();
|
||||
private DeviceList mDeviceList;
|
||||
private int tempListSize;
|
||||
private int savedListSize;
|
||||
private Handler mHandler;
|
||||
|
||||
private boolean exitActivity =false;
|
||||
private boolean showToast = true;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_main);
|
||||
|
||||
try {
|
||||
mDeviceList = DeviceList.getInstance(getApplicationContext());
|
||||
tempListSize=0;
|
||||
savedListSize=0;
|
||||
} catch (JSONException e) {
|
||||
Log.e(c.tag_main_activity, "init mDeviceList JSONException e --" + e);
|
||||
} catch (IOException e) {
|
||||
Log.e(c.tag_main_activity, "init mDeviceList IOException e --" + e);
|
||||
}
|
||||
|
||||
mTitle = mDrawerTitle = getTitle();
|
||||
|
||||
// load slide menu items
|
||||
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
|
||||
|
||||
// nav drawer icons from resources
|
||||
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
|
||||
|
||||
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
|
||||
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
|
||||
|
||||
navDrawerItems = new ArrayList<>();
|
||||
|
||||
// adding nav drawer items to array
|
||||
savedListSize=mDeviceList.size();
|
||||
tempListSize=mDeviceList.tempListSize();
|
||||
|
||||
// my device
|
||||
if(savedListSize!=0){
|
||||
String number=""+savedListSize;
|
||||
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1),true,number));
|
||||
}
|
||||
else {
|
||||
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
|
||||
}
|
||||
|
||||
// find device
|
||||
if(tempListSize!=0){
|
||||
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1),true,"NEW"));
|
||||
}
|
||||
else {
|
||||
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
|
||||
}
|
||||
|
||||
// about
|
||||
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
|
||||
|
||||
// Recycle the typed array
|
||||
//navMenuIcons.recycle();
|
||||
|
||||
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
|
||||
|
||||
// setting the nav drawer list adapter
|
||||
adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
|
||||
mDrawerList.setAdapter(adapter);
|
||||
|
||||
// enabling action bar app icon and behaving it as toggle button
|
||||
getActionBar().setDisplayHomeAsUpEnabled(true);
|
||||
getActionBar().setHomeButtonEnabled(true);
|
||||
|
||||
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
|
||||
R.drawable.ic_drawer, //nav menu toggle icon
|
||||
R.string.app_name, // nav drawer open - description for accessibility
|
||||
R.string.app_name // nav drawer close - description for accessibility
|
||||
) {
|
||||
public void onDrawerClosed(View view) {
|
||||
getActionBar().setTitle(mTitle);
|
||||
// calling onPrepareOptionsMenu() to show action bar icons
|
||||
invalidateOptionsMenu();
|
||||
}
|
||||
|
||||
public void onDrawerOpened(View drawerView) {
|
||||
getActionBar().setTitle(mDrawerTitle);
|
||||
// calling onPrepareOptionsMenu() to hide action bar icons
|
||||
invalidateOptionsMenu();
|
||||
}
|
||||
};
|
||||
mDrawerLayout.setDrawerListener(mDrawerToggle);
|
||||
|
||||
if (savedInstanceState == null) {
|
||||
// on first time display view for first nav item
|
||||
displayView(0);
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////////start nsd///////////////////////////////////////////
|
||||
try {
|
||||
NsdHelper nsdHelper = new NsdHelper(getApplicationContext());
|
||||
nsdHelper.execute();
|
||||
} catch (IOException e) {
|
||||
Log.e(c.tag_main_activity, "init NsdHelper IOException e --" + e);
|
||||
} catch (JSONException e) {
|
||||
Log.e(c.tag_main_activity, "init NsdHelper JSONException e --" + e);
|
||||
}
|
||||
//////////////////////////////////start nsd///////////////////////////////////////////
|
||||
|
||||
/////////////////////////////////update ui thread/////////////////////////////////////
|
||||
mHandler=new Handler();
|
||||
startUpdateUi();
|
||||
/////////////////////////////////update ui thread/////////////////////////////////////
|
||||
}
|
||||
|
||||
/**
|
||||
* Slide menu item click listener
|
||||
* */
|
||||
private class SlideMenuClickListener implements
|
||||
ListView.OnItemClickListener {
|
||||
@Override
|
||||
public void onItemClick(AdapterView<?> parent, View view, int position,
|
||||
long id) {
|
||||
// display view for selected nav drawer item
|
||||
displayView(position);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCreateOptionsMenu(Menu menu) {
|
||||
getMenuInflater().inflate(R.menu.main, menu);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
// toggle nav drawer on selecting action bar app icon/title
|
||||
if (mDrawerToggle.onOptionsItemSelected(item)) {
|
||||
return true;
|
||||
}
|
||||
// Handle action bar actions click
|
||||
switch (item.getItemId()) {
|
||||
case R.id.action_settings:
|
||||
Log.v(c.tag_main_activity,"onOptionsItemSelected() : open SettingsActivity");
|
||||
startActivity(new Intent(this,SettingsActivity.class));
|
||||
return true;
|
||||
default:
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
}
|
||||
|
||||
/* *
|
||||
* Called when invalidateOptionsMenu() is triggered
|
||||
*/
|
||||
@Override
|
||||
public boolean onPrepareOptionsMenu(Menu menu) {
|
||||
// if nav drawer is opened, hide the action items
|
||||
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
|
||||
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
|
||||
return super.onPrepareOptionsMenu(menu);
|
||||
}
|
||||
|
||||
/**
|
||||
* Diplaying fragment view for selected nav drawer list item
|
||||
* */
|
||||
private void displayView(int position) {
|
||||
// update the main content by replacing fragments
|
||||
Fragment fragment = null;
|
||||
switch (position) {
|
||||
case 0:
|
||||
fragment = new MyDeviceFragment();
|
||||
break;
|
||||
case 1:
|
||||
fragment = new FindDeviceFragment();
|
||||
break;
|
||||
case 2:
|
||||
fragment = new AboutFragment();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (fragment != null) {
|
||||
FragmentManager fragmentManager = getFragmentManager();
|
||||
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
|
||||
|
||||
// update selected item and title, then close the drawer
|
||||
mDrawerList.setItemChecked(position, true);
|
||||
mDrawerList.setSelection(position);
|
||||
setTitle(navMenuTitles[position]);
|
||||
mDrawerLayout.closeDrawer(mDrawerList);
|
||||
} else {
|
||||
// error in creating fragment
|
||||
Log.e(c.tag_main_activity, "displayView() Error in creating fragment");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTitle(CharSequence title) {
|
||||
mTitle = title;
|
||||
getActionBar().setTitle(mTitle);
|
||||
}
|
||||
|
||||
/**
|
||||
* When using the ActionBarDrawerToggle, you must call it during
|
||||
* onPostCreate() and onConfigurationChanged()...
|
||||
*/
|
||||
|
||||
@Override
|
||||
protected void onPostCreate(Bundle savedInstanceState) {
|
||||
super.onPostCreate(savedInstanceState);
|
||||
// Sync the toggle state after onRestoreInstanceState has occurred.
|
||||
mDrawerToggle.syncState();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConfigurationChanged(Configuration newConfig) {
|
||||
super.onConfigurationChanged(newConfig);
|
||||
// Pass any configuration change to the drawer toggls
|
||||
mDrawerToggle.onConfigurationChanged(newConfig);
|
||||
}
|
||||
|
||||
|
||||
|
||||
///////////////////////////update ui////////////////////////////
|
||||
|
||||
Runnable updateUiCallback = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
////////////////////update ui////////////////////
|
||||
navDrawerItems = new ArrayList<NavDrawerItem>();
|
||||
|
||||
// adding nav drawer items to array
|
||||
savedListSize=mDeviceList.size();
|
||||
tempListSize=mDeviceList.tempListSize();
|
||||
|
||||
// my device
|
||||
if(savedListSize!=0){
|
||||
String number=""+savedListSize;
|
||||
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1),true,number));
|
||||
}
|
||||
else {
|
||||
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
|
||||
}
|
||||
|
||||
// find device
|
||||
if(tempListSize!=0){
|
||||
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1),true,"NEW"));
|
||||
}
|
||||
else {
|
||||
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
|
||||
}
|
||||
|
||||
// about
|
||||
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
|
||||
|
||||
// setting the nav drawer list adapter
|
||||
adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
|
||||
mDrawerList.setAdapter(adapter);
|
||||
////////////////////update ui////////////////////
|
||||
|
||||
mHandler.postDelayed(updateUiCallback, c.val_ui_update_period_ms);
|
||||
}
|
||||
};
|
||||
|
||||
void startUpdateUi() {
|
||||
updateUiCallback.run();
|
||||
}
|
||||
|
||||
void stopUpdateUi() {
|
||||
mHandler.removeCallbacks(updateUiCallback);
|
||||
}
|
||||
|
||||
///////////////////////////update ui////////////////////////////
|
||||
|
||||
|
||||
//////////////////////////double click to quit//////////////////////////
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
|
||||
if(showToast){
|
||||
Toast.makeText(this, "Double-Click to Quit", Toast.LENGTH_LONG).show();
|
||||
showToast =false;
|
||||
}
|
||||
|
||||
if (exitActivity) {
|
||||
super.onBackPressed();
|
||||
}
|
||||
|
||||
exitActivity = true;
|
||||
new Handler().postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
exitActivity =false;
|
||||
}
|
||||
}, c.val_ui_double_click_interval);
|
||||
}
|
||||
//////////////////////////double click to quit//////////////////////////
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,452 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.app.AlertDialog;
|
||||
import android.app.Fragment;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Bitmap;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.util.Log;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.EditText;
|
||||
import android.widget.GridView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.json.JSONException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class MyDeviceFragment extends Fragment {
|
||||
|
||||
public MyDeviceFragment(){}
|
||||
|
||||
private GridView gridView;
|
||||
private GridViewAdapter gridAdapter;
|
||||
|
||||
private DeviceList mDeviceList;
|
||||
|
||||
private static final Constants c = Constants.getInstance();
|
||||
|
||||
private Handler mHandler;
|
||||
|
||||
private ConnectionChecker connectionChecker;
|
||||
|
||||
private AES128 mAES = new AES128();
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
getActivity().setTitle(R.string.my_device_fragment_title);
|
||||
}
|
||||
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
|
||||
final View rootView = inflater.inflate(R.layout.fragment_my_device, container, false);
|
||||
|
||||
try{
|
||||
mDeviceList = DeviceList.getInstance(getActivity().getApplicationContext());
|
||||
}
|
||||
catch (JSONException e){
|
||||
Log.e(c.tag_my_device_fragment,"JSONException e --"+e);
|
||||
}
|
||||
catch (IOException e){
|
||||
Log.e(c.tag_my_device_fragment,"IOException e --"+e);
|
||||
}
|
||||
|
||||
/////////////////////////////////set gridview/////////////////////////////////////////
|
||||
|
||||
gridView = (GridView) rootView.findViewById(R.id.my_device_gridView);
|
||||
try {
|
||||
gridAdapter = new GridViewAdapter(getActivity(), R.layout.layout_grid_view_item, getDeviceIcons());
|
||||
}
|
||||
catch (JSONException e){
|
||||
Log.e(c.tag_my_device_fragment,"JSONException e --"+e);
|
||||
}
|
||||
|
||||
gridView.setAdapter(gridAdapter);
|
||||
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
|
||||
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
|
||||
|
||||
//get mac addr from position:
|
||||
String mac = gridAdapter.getDeviceIconAt(position).getDeviceMac();
|
||||
Log.v(c.tag_my_device_fragment,"clicked on device :"+mac);
|
||||
|
||||
try {
|
||||
startAmebaActivity(mac);
|
||||
}
|
||||
catch (JSONException e){
|
||||
Log.e(c.tag_my_device_fragment,"startAmebaActivity() JSONException e "+e);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
|
||||
@Override
|
||||
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
|
||||
|
||||
popupOptions(id);
|
||||
|
||||
return true;
|
||||
}
|
||||
});
|
||||
/////////////////////////////////set gridview/////////////////////////////////////////
|
||||
|
||||
/////////////////////////////////update ui thread/////////////////////////////////////
|
||||
mHandler=new Handler();
|
||||
startUpdateUi();
|
||||
/////////////////////////////////update ui thread/////////////////////////////////////
|
||||
|
||||
return rootView;
|
||||
}
|
||||
|
||||
|
||||
private void popupOptions(long id){
|
||||
|
||||
final long idx = id;
|
||||
final ImageListAdapter adapter = new ImageListAdapter (getView().getContext(),getResources().getStringArray(R.array.my_device_popup_dialog_options));
|
||||
|
||||
final AlertDialog.Builder builder = new AlertDialog.Builder(getView().getContext());
|
||||
|
||||
builder.setTitle(R.string.popup_dialog_title_options);
|
||||
builder.setCancelable(true);
|
||||
|
||||
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
|
||||
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int index) {
|
||||
|
||||
///////////////switch controls/////////////////
|
||||
if (index == 0) {
|
||||
|
||||
LayoutInflater inflater;
|
||||
View promptsView;
|
||||
AlertDialog.Builder dialogBuilder;
|
||||
final EditText etUserInput;
|
||||
final String[] newDescription = {""};
|
||||
|
||||
inflater = LayoutInflater.from(getActivity());
|
||||
promptsView = inflater.inflate(R.layout.layout_popup_dialog_prompts_rename, null);
|
||||
dialogBuilder = new AlertDialog.Builder(getActivity());
|
||||
dialogBuilder.setView(promptsView);
|
||||
etUserInput = (EditText) promptsView.findViewById(R.id.editText_rename_device);
|
||||
|
||||
//get current name
|
||||
etUserInput.setText(gridAdapter.getDeviceIconAt((int) idx).getDeviceDescription());
|
||||
|
||||
dialogBuilder.setCancelable(true);
|
||||
dialogBuilder.setPositiveButton("OK",
|
||||
new DialogInterface.OnClickListener() {
|
||||
public void onClick(DialogInterface dialog, int id) {
|
||||
newDescription[0] = etUserInput.getText().toString(); //what a smart way to modify "final" :)
|
||||
Log.v(c.tag_my_device_fragment, "rename device: GridView id=" + idx + " new name: " + newDescription[0]);
|
||||
|
||||
//up date the device description: update device list first, then UI
|
||||
String mac = gridAdapter.getDeviceIconAt((int) idx).getDeviceMac();
|
||||
try {
|
||||
mDeviceList.setDeviceDescription(mac, newDescription[0]);
|
||||
} catch (JSONException e) {
|
||||
Log.e(c.tag_my_device_fragment, "gridAdapter->change device description JSONException e " + e);
|
||||
} catch (IOException e) {
|
||||
Log.e(c.tag_my_device_fragment, "gridAdapter->change device description IOException e " + e);
|
||||
}
|
||||
|
||||
gridAdapter.getDeviceIconAt((int) idx).setDeviceDescription(newDescription[0]);
|
||||
|
||||
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "New name: " + newDescription[0], Toast.LENGTH_SHORT);
|
||||
toast.show();
|
||||
|
||||
}
|
||||
});
|
||||
dialogBuilder.setNegativeButton("Cancel",
|
||||
new DialogInterface.OnClickListener() {
|
||||
public void onClick(DialogInterface dialog, int id) {
|
||||
dialog.cancel();
|
||||
}
|
||||
});
|
||||
|
||||
AlertDialog alertDialog = dialogBuilder.create();
|
||||
alertDialog.show();
|
||||
|
||||
} else {
|
||||
//remove device: remove it form list first, then UI
|
||||
final String mac = gridAdapter.getDeviceIconAt((int) idx).getDeviceMac();
|
||||
new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Log.v("unpair-result:","before call \n");
|
||||
final int result = unpairing(mac);
|
||||
Log.v("unpair-result:","after call result ="+result+"\n");
|
||||
final String deviceDescription = gridAdapter.getDeviceIconAt((int) idx).getDeviceDescription();
|
||||
if(result==c.val_unpairing_succeed){
|
||||
getActivity().runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
gridAdapter.remove(gridAdapter.getDeviceIconAt((int) idx));
|
||||
mDeviceList.removeDevice(mac);
|
||||
Toast.makeText(getActivity().getApplicationContext(), deviceDescription + " removed", Toast.LENGTH_SHORT).show();
|
||||
} catch (Exception e) {
|
||||
Log.e(c.tag_my_device_fragment, "gridAdapter->remove device Exception e " + e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
else {
|
||||
getActivity().runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Toast.makeText(getActivity().getApplicationContext(), "Failed to unpair "+deviceDescription + ", Error code: "+result, Toast.LENGTH_LONG).show();
|
||||
//////////force remove prompt//////////
|
||||
AlertDialog.Builder dialogBuilder;
|
||||
dialogBuilder = new AlertDialog.Builder(getActivity());
|
||||
dialogBuilder.setTitle("Force to Remove Device ?");
|
||||
dialogBuilder.setCancelable(true);
|
||||
dialogBuilder.setPositiveButton("OK",
|
||||
new DialogInterface.OnClickListener() {
|
||||
public void onClick(DialogInterface dialog, int id) {
|
||||
|
||||
try {
|
||||
gridAdapter.remove(gridAdapter.getDeviceIconAt((int) idx));
|
||||
mDeviceList.removeDevice(mac);
|
||||
Toast.makeText(getActivity().getApplicationContext(), deviceDescription + " removed", Toast.LENGTH_SHORT).show();
|
||||
} catch (Exception e) {
|
||||
Log.e(c.tag_my_device_fragment, "gridAdapter->Force to Remove device Exception e " + e);
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
dialogBuilder.setNegativeButton("Cancel",
|
||||
new DialogInterface.OnClickListener() {
|
||||
public void onClick(DialogInterface dialog, int id) {
|
||||
dialog.cancel();
|
||||
}
|
||||
});
|
||||
|
||||
AlertDialog alertDialog = dialogBuilder.create();
|
||||
alertDialog.show();
|
||||
//////////force remove prompt//////////
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (Exception e){}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
}
|
||||
});
|
||||
builder.show();
|
||||
}
|
||||
|
||||
private synchronized int unpairing(String mac)throws Exception{
|
||||
if(mDeviceList.trackingListDeviceLookup(mac)==c.val_device_not_found)
|
||||
{
|
||||
return c.err_unpairing_device_not_found;
|
||||
}
|
||||
else {
|
||||
String ip = mDeviceList.trackingListGetDeviceIp(mac);
|
||||
connectionChecker = new ConnectionChecker();
|
||||
boolean deviceIsOnline = connectionChecker.testConnection(ip, c.val_ping_base_time_out,c.val_ping_max_try);
|
||||
if(!deviceIsOnline){
|
||||
mDeviceList.downListAddDevice(mac);
|
||||
return c.err_unpairing_server_ping_timeout;
|
||||
}
|
||||
else {
|
||||
int port = mDeviceList.trackingListGetDevicePort(mac);
|
||||
String key = mDeviceList.getDeviceSharedKey(mac);
|
||||
String txEnc = mAES.encryptToStringOfShortArray(c.tcp_tx_cmd_unpairing, key);
|
||||
TcpClient tcpClient = new TcpClient();
|
||||
String rx = tcpClient.echo(InetAddress.getByName(ip),port,txEnc);
|
||||
if (!rx.equals(c.tcp_rx_unpairing_ok)){
|
||||
return c.err_unpairing_with_server_failed;
|
||||
}
|
||||
return c.val_unpairing_succeed;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private synchronized void startAmebaActivity(final String mac) throws JSONException{
|
||||
connectionChecker = new ConnectionChecker();
|
||||
String deviceDescription = mDeviceList.getDeviceDescription(mac);
|
||||
String controlType = mDeviceList.getDeviceControlType(mac);
|
||||
final String firebaseAppId = mDeviceList.getDeviceFirebaseAppId(mac);
|
||||
String key = mDeviceList.getDeviceSharedKey(mac);
|
||||
final String ip;
|
||||
final int port;
|
||||
final Intent intent;
|
||||
|
||||
//test if ip and port is available, if not available, assign proper value to ip and port
|
||||
if(mDeviceList.trackingListDeviceLookup(mac)==c.val_device_not_found){
|
||||
ip = c.val_empty;
|
||||
port = c.val_device_not_found;
|
||||
}
|
||||
else {
|
||||
ip = mDeviceList.trackingListGetDeviceIp(mac);
|
||||
port = mDeviceList.trackingListGetDevicePort(mac);
|
||||
}
|
||||
|
||||
//for ht sensor
|
||||
//if(serviceName.equals(c.nsd_service_ht)){
|
||||
intent = new Intent(getActivity(), HTSensorActivity.class);
|
||||
intent.putExtra(c.key_ip,ip);
|
||||
intent.putExtra(c.key_port,port);
|
||||
intent.putExtra(c.key_mac,mac);
|
||||
intent.putExtra(c.key_control_type,controlType);
|
||||
intent.putExtra(c.key_firebase_app_id,firebaseAppId);
|
||||
intent.putExtra(c.key_shared_key, key);
|
||||
intent.putExtra(c.key_device_description,deviceDescription);
|
||||
//}
|
||||
|
||||
/*//for XXX sensor:
|
||||
else if (serviceName.equals(c.nsd_service_XXX)){
|
||||
....
|
||||
}*/
|
||||
|
||||
|
||||
new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
////////////////////////////////toast on ui////////////////////////////////
|
||||
getActivity().runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
Toast.makeText(getActivity(), "Checking device status...", Toast.LENGTH_LONG).show();
|
||||
}
|
||||
});
|
||||
////////////////////////////////toast on ui////////////////////////////////
|
||||
|
||||
//check if the device is online
|
||||
boolean deviceIsOnline;
|
||||
String controlType=c.val_empty;
|
||||
try {
|
||||
controlType=mDeviceList.getDeviceControlType(mac);
|
||||
}catch (JSONException e){Log.e(c.tag_my_device_fragment,"startAmebaActivity() JSONException e"+e);}
|
||||
|
||||
if(controlType.equals(c.val_local_control)){
|
||||
if(ip.equals(c.val_empty)){
|
||||
deviceIsOnline=false;
|
||||
Log.v(c.tag_my_device_fragment,"startAmebaActivity() ping local device "+mac+" with ip "+ip+" -- device is not found in tracking list");
|
||||
}
|
||||
else {
|
||||
Log.v(c.tag_my_device_fragment,"startAmebaActivity() ping local device "+mac+" with ip "+ip);
|
||||
deviceIsOnline= connectionChecker.testConnection(ip, c.val_ping_base_time_out,c.val_ping_max_try);
|
||||
}
|
||||
}
|
||||
else {
|
||||
//cloud device, if its in tracking list, it must be validate by local ping
|
||||
if(!ip.equals(c.val_empty)){
|
||||
Log.v(c.tag_my_device_fragment,"startAmebaActivity() ping cloud device "+mac+" locally with ip "+ip);
|
||||
deviceIsOnline= connectionChecker.testConnection(ip, c.val_ping_base_time_out,c.val_ping_max_try);
|
||||
}
|
||||
else {
|
||||
Log.v(c.tag_my_device_fragment,"startAmebaActivity() check cloud device "+mac+" with firebase app Id "+firebaseAppId);
|
||||
deviceIsOnline=connectionChecker.testConnection(firebaseAppId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if(deviceIsOnline){
|
||||
mDeviceList.downListRemoveDevice(mac);
|
||||
////////////////////////////////toast on ui////////////////////////////////
|
||||
getActivity().runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
Toast.makeText(getActivity(), "Connect to Ameba...", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
////////////////////////////////toast on ui////////////////////////////////
|
||||
startActivity(intent);
|
||||
}
|
||||
else {
|
||||
mDeviceList.downListAddDevice(mac);
|
||||
////////////////////////////////toast on ui////////////////////////////////
|
||||
getActivity().runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
Toast.makeText(getActivity(), "Device is offline", Toast.LENGTH_LONG).show();
|
||||
}
|
||||
});
|
||||
////////////////////////////////toast on ui////////////////////////////////
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare data for gridview
|
||||
*/
|
||||
private synchronized ArrayList<DeviceIcon> getDeviceIcons() throws JSONException{
|
||||
final ArrayList<DeviceIcon> deviceIcons = new ArrayList<>();
|
||||
for (int i = 0; i < mDeviceList.size(); i++) {
|
||||
String mac = mDeviceList.getDeviceMac(i);
|
||||
String serviceName = mDeviceList.getDeviceServiceName(mac);
|
||||
String controlType = mDeviceList.getDeviceControlType(mac);
|
||||
Bitmap icon;
|
||||
|
||||
/////////////////////////////icon/////////////////////////////
|
||||
if(controlType.equals(c.val_local_control)){
|
||||
if(mDeviceList.trackingListDeviceLookup(mac)==c.val_device_not_found){
|
||||
icon = mDeviceList.getDeviceIcon(serviceName,controlType,false);
|
||||
}
|
||||
else if(mDeviceList.downListLookup(mac)!=c.val_device_not_found){
|
||||
icon = mDeviceList.getDeviceIcon(serviceName,controlType,false);
|
||||
}
|
||||
else {
|
||||
icon = mDeviceList.getDeviceIcon(serviceName,controlType,true);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if(mDeviceList.downListLookup(mac)!=c.val_device_not_found){
|
||||
icon = mDeviceList.getDeviceIcon(serviceName,controlType,false);
|
||||
}
|
||||
else {
|
||||
icon = mDeviceList.getDeviceIcon(serviceName,controlType,true);
|
||||
}
|
||||
}
|
||||
/////////////////////////////icon/////////////////////////////
|
||||
|
||||
String description = mDeviceList.getDeviceDescription(mac);
|
||||
|
||||
deviceIcons.add(new DeviceIcon(icon,description,mac));
|
||||
}
|
||||
return deviceIcons;
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////update ui////////////////////////////
|
||||
|
||||
Runnable updateUiCallback = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
////////////////////update ui////////////////////
|
||||
if(getActivity() != null) {
|
||||
try {
|
||||
gridAdapter = new GridViewAdapter(getActivity(), R.layout.layout_grid_view_item, getDeviceIcons());
|
||||
gridView.setAdapter(gridAdapter);
|
||||
} catch (JSONException e) {
|
||||
Log.e(c.tag_my_device_fragment, "updateUiCallback JSONException e " + e);
|
||||
}
|
||||
}
|
||||
////////////////////update ui////////////////////
|
||||
mHandler.postDelayed(updateUiCallback, c.val_ui_update_period_ms);
|
||||
}
|
||||
};
|
||||
|
||||
void startUpdateUi() {
|
||||
updateUiCallback.run();
|
||||
}
|
||||
|
||||
void stopUpdateUi() {
|
||||
mHandler.removeCallbacks(updateUiCallback);
|
||||
}
|
||||
|
||||
///////////////////////////update ui////////////////////////////
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
public class NavDrawerItem {
|
||||
|
||||
private String title;
|
||||
private int icon;
|
||||
private String count = "0";
|
||||
// boolean to set visiblity of the counter
|
||||
private boolean isCounterVisible = false;
|
||||
|
||||
public NavDrawerItem(){}
|
||||
|
||||
public NavDrawerItem(String title, int icon){
|
||||
this.title = title;
|
||||
this.icon = icon;
|
||||
}
|
||||
|
||||
public NavDrawerItem(String title, int icon, boolean isCounterVisible, String count){
|
||||
this.title = title;
|
||||
this.icon = icon;
|
||||
this.isCounterVisible = isCounterVisible;
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public String getTitle(){
|
||||
return this.title;
|
||||
}
|
||||
|
||||
public int getIcon(){
|
||||
return this.icon;
|
||||
}
|
||||
|
||||
public String getCount(){
|
||||
return this.count;
|
||||
}
|
||||
|
||||
public boolean getCounterVisibility(){
|
||||
return this.isCounterVisible;
|
||||
}
|
||||
|
||||
public void setTitle(String title){
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public void setIcon(int icon){
|
||||
this.icon = icon;
|
||||
}
|
||||
|
||||
public void setCount(String count){
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public void setCounterVisibility(boolean isCounterVisible){
|
||||
this.isCounterVisible = isCounterVisible;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.BaseAdapter;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class NavDrawerListAdapter extends BaseAdapter {
|
||||
|
||||
private Context context;
|
||||
private ArrayList<NavDrawerItem> navDrawerItems;
|
||||
|
||||
public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
|
||||
this.context = context;
|
||||
this.navDrawerItems = navDrawerItems;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getCount() {
|
||||
return navDrawerItems.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getItem(int position) {
|
||||
return navDrawerItems.get(position);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getItemId(int position) {
|
||||
return position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public View getView(int position, View convertView, ViewGroup parent) {
|
||||
if (convertView == null) {
|
||||
LayoutInflater mInflater = (LayoutInflater)
|
||||
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
|
||||
convertView = mInflater.inflate(R.layout.layout_drawer_list_item, null);
|
||||
}
|
||||
|
||||
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
|
||||
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
|
||||
TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
|
||||
|
||||
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
|
||||
txtTitle.setText(navDrawerItems.get(position).getTitle());
|
||||
|
||||
// displaying count
|
||||
// check whether it set visible or not
|
||||
if(navDrawerItems.get(position).getCounterVisibility()){
|
||||
txtCount.setText(navDrawerItems.get(position).getCount());
|
||||
}else{
|
||||
// hide the counter view
|
||||
txtCount.setVisibility(View.GONE);
|
||||
}
|
||||
|
||||
return convertView;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,126 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.content.Context;
|
||||
import android.net.wifi.WifiManager;
|
||||
import android.os.AsyncTask;
|
||||
import android.text.format.Formatter;
|
||||
import android.util.Log;
|
||||
|
||||
import org.json.JSONException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
|
||||
import javax.jmdns.JmDNS;
|
||||
import javax.jmdns.ServiceEvent;
|
||||
import javax.jmdns.ServiceListener;
|
||||
|
||||
/**
|
||||
* Created by WUJINZHOU on 5/2/15.
|
||||
*/
|
||||
public class NsdHelper extends AsyncTask<Void, Void, Void> {
|
||||
static final Constants c = Constants.getInstance();
|
||||
|
||||
private final String mServiceType = c.nsd_service_type;
|
||||
private final String tag = c.tag_nsd_helper;
|
||||
private DeviceList mDeviceList;
|
||||
|
||||
private JmDNS jmdns = null;
|
||||
private ServiceListener listener = null;
|
||||
|
||||
private WifiManager wifi = null;
|
||||
private WifiManager.MulticastLock multicastLock = null;
|
||||
private Context mContext =null;
|
||||
|
||||
public NsdHelper(Context context)throws JSONException,IOException{
|
||||
mContext=context;
|
||||
mDeviceList=DeviceList.getInstance(mContext);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Void doInBackground(Void... params) {
|
||||
startNSD();
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCancelled() {
|
||||
super.onCancelled();
|
||||
stopNSD();
|
||||
}
|
||||
|
||||
private void startNSD() {
|
||||
Log.v(tag, "startNSD() ");
|
||||
|
||||
try {
|
||||
|
||||
wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
|
||||
|
||||
String ip = Formatter.formatIpAddress(wifi.getConnectionInfo().getIpAddress());
|
||||
String hostname = InetAddress.getByName(InetAddress.getByName(ip).getHostName()).toString();
|
||||
|
||||
multicastLock = wifi.createMulticastLock(getClass().getName());
|
||||
multicastLock.setReferenceCounted(true);
|
||||
multicastLock.acquire();
|
||||
|
||||
jmdns = JmDNS.create(InetAddress.getByName(ip),hostname);
|
||||
|
||||
jmdns.addServiceListener(mServiceType, listener = new ServiceListener() {
|
||||
|
||||
@Override
|
||||
public void serviceAdded(ServiceEvent event) {
|
||||
jmdns.requestServiceInfo(event.getType(), event.getName(), true);
|
||||
Log.v(tag, "serviceAdded() " + event.getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serviceRemoved(ServiceEvent event) {
|
||||
Log.v(tag, "serviceRemoved() " + event.getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serviceResolved(ServiceEvent event) {
|
||||
|
||||
try {
|
||||
mDeviceList.tempListUpdate(event);
|
||||
String mac = event.getInfo().getPropertyString(c.key_mac);
|
||||
String pairState = event.getInfo().getPropertyString(c.key_pair_state);
|
||||
Log.v(tag, "serviceResolved() " + "mac: " + mac + " pair state: " + pairState);
|
||||
} catch (JSONException e) {
|
||||
Log.e(tag, "serviceResolved() JSONException e" + e);
|
||||
} catch (IOException e) {
|
||||
Log.e(tag, "serviceResolved() IOException e" + e);
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
} catch (IOException e) {
|
||||
Log.e(tag,"startNSD() IOException e:"+e);
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private void stopNSD() {
|
||||
Log.v(tag,"stopNSD() ");
|
||||
if (jmdns != null) {
|
||||
if (listener != null) {
|
||||
jmdns.removeServiceListener(mServiceType, listener);
|
||||
listener = null;
|
||||
}
|
||||
jmdns.unregisterAllServices();
|
||||
try {
|
||||
jmdns.close();
|
||||
} catch (IOException e) {
|
||||
Log.e(tag,"stopNSD() IOException e:"+e);
|
||||
e.printStackTrace();
|
||||
}
|
||||
jmdns = null;
|
||||
}
|
||||
if (multicastLock != null) {
|
||||
multicastLock.release();
|
||||
multicastLock = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.graphics.Bitmap;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.webkit.WebView;
|
||||
import android.webkit.WebViewClient;
|
||||
import android.widget.Toast;
|
||||
|
||||
/**
|
||||
* Created by Wu Jinzhou on 5/11/2015.
|
||||
*/
|
||||
public class RegisterFirebaseAccountActivity extends Activity {
|
||||
private static final Constants c = Constants.getInstance();
|
||||
WebView web;
|
||||
boolean exitActivity =false;
|
||||
boolean showToast = true;
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_register_firebase_account);
|
||||
|
||||
web = (WebView) findViewById(R.id.webView_register_firebase_account);
|
||||
web.setWebViewClient(new myWebClient());
|
||||
web.getSettings().setJavaScriptEnabled(true);
|
||||
web.loadUrl(c.val_firebase_register_url);
|
||||
}
|
||||
|
||||
public class myWebClient extends WebViewClient
|
||||
{
|
||||
@Override
|
||||
public void onPageStarted(WebView view, String url, Bitmap favicon) {
|
||||
|
||||
super.onPageStarted(view, url, favicon);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldOverrideUrlLoading(WebView view, String url) {
|
||||
|
||||
view.loadUrl(url);
|
||||
return true;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// To handle "Back" key press event for WebView to go back to previous screen.
|
||||
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
|
||||
if(showToast){
|
||||
Toast.makeText(this, "Nav Options:\nSingle-click: Back\nDouble-Click: Quit", Toast.LENGTH_LONG).show();
|
||||
showToast =false;
|
||||
}
|
||||
if (exitActivity) {
|
||||
super.onBackPressed();
|
||||
}
|
||||
else{
|
||||
if(web.canGoBack()){
|
||||
web.goBack();
|
||||
}
|
||||
}
|
||||
|
||||
exitActivity = true;
|
||||
new Handler().postDelayed(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
exitActivity =false;
|
||||
}
|
||||
}, c.val_ui_double_click_interval);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.media.MediaPlayer;
|
||||
import android.os.Bundle;
|
||||
import android.preference.ListPreference;
|
||||
import android.preference.Preference;
|
||||
import android.preference.PreferenceActivity;
|
||||
import android.preference.PreferenceManager;
|
||||
|
||||
/**
|
||||
* Created by Wu Jinzhou on 6/8/2015.
|
||||
*/
|
||||
public class SettingsActivity extends PreferenceActivity{
|
||||
static private boolean canPlayHtAlarmSound = false;
|
||||
static private Constants c = Constants.getInstance();
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
addPreferencesFromResource(R.xml.app_settings);
|
||||
|
||||
// bind preference summary for H&T
|
||||
canPlayHtAlarmSound = false;
|
||||
bindPreferenceSummaryToValue(findPreference(c.key_ht_sensor_data_update_frequency));
|
||||
bindPreferenceSummaryToValue(findPreference(c.key_ht_sensor_temperature_threshold));
|
||||
bindPreferenceSummaryToValue(findPreference(c.key_ht_sensor_humidity_threshold));
|
||||
bindPreferenceSummaryToValue(findPreference(c.key_ht_sensor_alarm_sound));
|
||||
canPlayHtAlarmSound =true;
|
||||
|
||||
}
|
||||
|
||||
private static void bindPreferenceSummaryToValue(Preference preference) {
|
||||
// Set the listener to watch for value changes.
|
||||
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
|
||||
|
||||
// Trigger the listener immediately with the preference's
|
||||
// current value
|
||||
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(preference.getKey(), ""));
|
||||
}
|
||||
|
||||
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
|
||||
@Override
|
||||
public boolean onPreferenceChange(Preference preference, Object newValue) {
|
||||
String newValueStr = newValue.toString();
|
||||
|
||||
if (preference instanceof ListPreference) {
|
||||
// For list preferences, look up the correct display newValue in
|
||||
// the preference's 'entries' list.
|
||||
ListPreference listPreference = (ListPreference) preference;
|
||||
int index = listPreference.findIndexOfValue(newValueStr);
|
||||
|
||||
// Set the summary to reflect the new newValue.
|
||||
preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null);
|
||||
|
||||
} else {
|
||||
// For all other preferences, set the summary to the newValue's
|
||||
// simple string representation.
|
||||
preference.setSummary(newValueStr);
|
||||
}
|
||||
|
||||
//for H&T : play selected alarm sound
|
||||
if(preference.getKey().equals(c.key_ht_sensor_alarm_sound) && canPlayHtAlarmSound){
|
||||
String sound = newValueStr;
|
||||
MediaPlayer mediaPlayer;
|
||||
|
||||
if(sound.equals(c.val_ht_sensor_alarm_sound_altair)){
|
||||
mediaPlayer = MediaPlayer.create(preference.getContext(), R.raw.sound_altair);
|
||||
}
|
||||
else if(sound.equals(c.val_ht_sensor_alarm_sound_ariel)){
|
||||
mediaPlayer = MediaPlayer.create(preference.getContext(),R.raw.sound_ariel);
|
||||
}
|
||||
else if(sound.equals(c.val_ht_sensor_alarm_sound_fomalhaut)){
|
||||
mediaPlayer = MediaPlayer.create(preference.getContext(),R.raw.sound_fomalhaut);
|
||||
}
|
||||
else if(sound.equals(c.val_ht_sensor_alarm_sound_tinkerbell)){
|
||||
mediaPlayer = MediaPlayer.create(preference.getContext(),R.raw.sound_tinkerbell);
|
||||
}
|
||||
else {
|
||||
mediaPlayer = MediaPlayer.create(preference.getContext(),R.raw.sound_ding);
|
||||
}
|
||||
|
||||
mediaPlayer.start();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
package com.realtek.wigadget;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.PrintWriter;
|
||||
import java.net.InetAddress;
|
||||
import java.net.Socket;
|
||||
|
||||
/**
|
||||
* Created by Wu Jinzhou on 4/28/2015.
|
||||
*/
|
||||
public class TcpClient {
|
||||
|
||||
private static final Constants c = Constants.getInstance();
|
||||
|
||||
public synchronized String echo(InetAddress serverAddress, int serverPort,String command)throws InterruptedException,IOException{
|
||||
|
||||
Thread.sleep(c.val_tcp_next_cmd_waiting_ms);
|
||||
|
||||
Log.v(c.tag_tcp_client,"echo("+serverAddress+","+serverPort+")"+" with command :"+command);
|
||||
|
||||
Socket s = new Socket(serverAddress,serverPort);
|
||||
|
||||
BufferedReader rx = new BufferedReader(new InputStreamReader(s.getInputStream()));
|
||||
|
||||
PrintWriter tx = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true);
|
||||
|
||||
tx.println(command);
|
||||
|
||||
Log.v(c.tag_tcp_client, "Tx :" + command);
|
||||
|
||||
String response = rx.readLine();
|
||||
|
||||
Log.v(c.tag_tcp_client,"Rx :"+response);
|
||||
|
||||
s.close();
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,903 @@
|
|||
/* Ported from C to Java by Dmitry Skiba [sahn0], 23/02/08.
|
||||
* Original: http://cds.xs4all.nl:8081/ecdh/
|
||||
*/
|
||||
/* Generic 64-bit integer implementation of Curve25519 ECDH
|
||||
* Written by Matthijs van Duin, 200608242056
|
||||
* Public domain.
|
||||
*
|
||||
* Based on work by Daniel J Bernstein, http://cr.yp.to/ecdh.html
|
||||
*/
|
||||
package djb;
|
||||
|
||||
public class Curve25519 {
|
||||
|
||||
/* key size */
|
||||
public static final int KEY_SIZE = 32;
|
||||
|
||||
/* 0 */
|
||||
public static final byte[] ZERO = {
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
|
||||
};
|
||||
|
||||
/* the prime 2^255-19 */
|
||||
public static final byte[] PRIME = {
|
||||
(byte)237, (byte)255, (byte)255, (byte)255,
|
||||
(byte)255, (byte)255, (byte)255, (byte)255,
|
||||
(byte)255, (byte)255, (byte)255, (byte)255,
|
||||
(byte)255, (byte)255, (byte)255, (byte)255,
|
||||
(byte)255, (byte)255, (byte)255, (byte)255,
|
||||
(byte)255, (byte)255, (byte)255, (byte)255,
|
||||
(byte)255, (byte)255, (byte)255, (byte)255,
|
||||
(byte)255, (byte)255, (byte)255, (byte)127
|
||||
};
|
||||
|
||||
/* group order (a prime near 2^252+2^124) */
|
||||
public static final byte[] ORDER = {
|
||||
(byte)237, (byte)211, (byte)245, (byte)92,
|
||||
(byte)26, (byte)99, (byte)18, (byte)88,
|
||||
(byte)214, (byte)156, (byte)247, (byte)162,
|
||||
(byte)222, (byte)249, (byte)222, (byte)20,
|
||||
(byte)0, (byte)0, (byte)0, (byte)0,
|
||||
(byte)0, (byte)0, (byte)0, (byte)0,
|
||||
(byte)0, (byte)0, (byte)0, (byte)0,
|
||||
(byte)0, (byte)0, (byte)0, (byte)16
|
||||
};
|
||||
|
||||
/********* KEY AGREEMENT *********/
|
||||
|
||||
/* Private key clamping
|
||||
* k [out] your private key for key agreement
|
||||
* k [in] 32 random bytes
|
||||
*/
|
||||
public static final void clamp(byte[] k) {
|
||||
k[31] &= 0x7F;
|
||||
k[31] |= 0x40;
|
||||
k[ 0] &= 0xF8;
|
||||
}
|
||||
|
||||
/* Key-pair generation
|
||||
* P [out] your public key
|
||||
* s [out] your private key for signing
|
||||
* k [out] your private key for key agreement
|
||||
* k [in] 32 random bytes
|
||||
* s may be NULL if you don't care
|
||||
*
|
||||
* WARNING: if s is not NULL, this function has data-dependent timing */
|
||||
public static final void keygen(byte[] P, byte[] s, byte[] k) {
|
||||
clamp(k);
|
||||
core(P, s, k, null);
|
||||
}
|
||||
|
||||
/* Key agreement
|
||||
* Z [out] shared secret (needs hashing before use)
|
||||
* k [in] your private key for key agreement
|
||||
* P [in] peer's public key
|
||||
*/
|
||||
public static final void curve(byte[] Z, byte[] k, byte[] P) {
|
||||
core(Z, null, k, P);
|
||||
}
|
||||
|
||||
/********* DIGITAL SIGNATURES *********/
|
||||
|
||||
/* deterministic EC-KCDSA
|
||||
*
|
||||
* s is the private key for signing
|
||||
* P is the corresponding public key
|
||||
* Z is the context data (signer public key or certificate, etc)
|
||||
*
|
||||
* signing:
|
||||
*
|
||||
* m = hash(Z, message)
|
||||
* x = hash(m, s)
|
||||
* keygen25519(Y, NULL, x);
|
||||
* r = hash(Y);
|
||||
* h = m XOR r
|
||||
* sign25519(v, h, x, s);
|
||||
*
|
||||
* output (v,r) as the signature
|
||||
*
|
||||
* verification:
|
||||
*
|
||||
* m = hash(Z, message);
|
||||
* h = m XOR r
|
||||
* verify25519(Y, v, h, P)
|
||||
*
|
||||
* confirm r == hash(Y)
|
||||
*
|
||||
* It would seem to me that it would be simpler to have the signer directly do
|
||||
* h = hash(m, Y) and send that to the recipient instead of r, who can verify
|
||||
* the signature by checking h == hash(m, Y). If there are any problems with
|
||||
* such a scheme, please let me know.
|
||||
*
|
||||
* Also, EC-KCDSA (like most DS algorithms) picks x random, which is a waste of
|
||||
* perfectly good entropy, but does allow Y to be calculated in advance of (or
|
||||
* parallel to) hashing the message.
|
||||
*/
|
||||
|
||||
/* Signature generation primitive, calculates (x-h)s mod q
|
||||
* v [out] signature value
|
||||
* h [in] signature hash (of message, signature pub key, and context data)
|
||||
* x [in] signature private key
|
||||
* s [in] private key for signing
|
||||
* returns true on success, false on failure (use different x or h)
|
||||
*/
|
||||
public static final boolean sign(byte[] v, byte[] h, byte[] x, byte[] s) {
|
||||
/* v = (x - h) s mod q */
|
||||
byte[] tmp1=new byte[65];
|
||||
byte[] tmp2=new byte[33];
|
||||
int w;
|
||||
int i;
|
||||
for (i = 0; i < 32; i++)
|
||||
v[i] = 0;
|
||||
i = mula_small(v, x, 0, h, 32, -1);
|
||||
mula_small(v, v, 0, ORDER, 32, (15-v[31])/16);
|
||||
mula32(tmp1, v, s, 32, 1);
|
||||
divmod(tmp2, tmp1, 64, ORDER, 32);
|
||||
for (w = 0, i = 0; i < 32; i++)
|
||||
w |= v[i] = tmp1[i];
|
||||
return w != 0;
|
||||
}
|
||||
|
||||
/* Signature verification primitive, calculates Y = vP + hG
|
||||
* Y [out] signature public key
|
||||
* v [in] signature value
|
||||
* h [in] signature hash
|
||||
* P [in] public key
|
||||
*/
|
||||
public static final void verify(byte[] Y, byte[] v, byte[] h, byte[] P) {
|
||||
/* Y = v abs(P) + h G */
|
||||
byte[] d=new byte[32];
|
||||
long10[]
|
||||
p=new long10[]{new long10(),new long10()},
|
||||
s=new long10[]{new long10(),new long10()},
|
||||
yx=new long10[]{new long10(),new long10(),new long10()},
|
||||
yz=new long10[]{new long10(),new long10(),new long10()},
|
||||
t1=new long10[]{new long10(),new long10(),new long10()},
|
||||
t2=new long10[]{new long10(),new long10(),new long10()};
|
||||
|
||||
int vi = 0, hi = 0, di = 0, nvh=0, i, j, k;
|
||||
|
||||
/* set p[0] to G and p[1] to P */
|
||||
|
||||
set(p[0], 9);
|
||||
unpack(p[1], P);
|
||||
|
||||
/* set s[0] to P+G and s[1] to P-G */
|
||||
|
||||
/* s[0] = (Py^2 + Gy^2 - 2 Py Gy)/(Px - Gx)^2 - Px - Gx - 486662 */
|
||||
/* s[1] = (Py^2 + Gy^2 + 2 Py Gy)/(Px - Gx)^2 - Px - Gx - 486662 */
|
||||
|
||||
x_to_y2(t1[0], t2[0], p[1]); /* t2[0] = Py^2 */
|
||||
sqrt(t1[0], t2[0]); /* t1[0] = Py or -Py */
|
||||
j = is_negative(t1[0]); /* ... check which */
|
||||
t2[0]._0 += 39420360; /* t2[0] = Py^2 + Gy^2 */
|
||||
mul(t2[1], BASE_2Y, t1[0]);/* t2[1] = 2 Py Gy or -2 Py Gy */
|
||||
sub(t1[j], t2[0], t2[1]); /* t1[0] = Py^2 + Gy^2 - 2 Py Gy */
|
||||
add(t1[1-j], t2[0], t2[1]);/* t1[1] = Py^2 + Gy^2 + 2 Py Gy */
|
||||
cpy(t2[0], p[1]); /* t2[0] = Px */
|
||||
t2[0]._0 -= 9; /* t2[0] = Px - Gx */
|
||||
sqr(t2[1], t2[0]); /* t2[1] = (Px - Gx)^2 */
|
||||
recip(t2[0], t2[1], 0); /* t2[0] = 1/(Px - Gx)^2 */
|
||||
mul(s[0], t1[0], t2[0]); /* s[0] = t1[0]/(Px - Gx)^2 */
|
||||
sub(s[0], s[0], p[1]); /* s[0] = t1[0]/(Px - Gx)^2 - Px */
|
||||
s[0]._0 -= 9 + 486662; /* s[0] = X(P+G) */
|
||||
mul(s[1], t1[1], t2[0]); /* s[1] = t1[1]/(Px - Gx)^2 */
|
||||
sub(s[1], s[1], p[1]); /* s[1] = t1[1]/(Px - Gx)^2 - Px */
|
||||
s[1]._0 -= 9 + 486662; /* s[1] = X(P-G) */
|
||||
mul_small(s[0], s[0], 1); /* reduce s[0] */
|
||||
mul_small(s[1], s[1], 1); /* reduce s[1] */
|
||||
|
||||
|
||||
/* prepare the chain */
|
||||
for (i = 0; i < 32; i++) {
|
||||
vi = (vi >> 8) ^ (v[i] & 0xFF) ^ ((v[i] & 0xFF) << 1);
|
||||
hi = (hi >> 8) ^ (h[i] & 0xFF) ^ ((h[i] & 0xFF) << 1);
|
||||
nvh = ~(vi ^ hi);
|
||||
di = (nvh & (di & 0x80) >> 7) ^ vi;
|
||||
di ^= nvh & (di & 0x01) << 1;
|
||||
di ^= nvh & (di & 0x02) << 1;
|
||||
di ^= nvh & (di & 0x04) << 1;
|
||||
di ^= nvh & (di & 0x08) << 1;
|
||||
di ^= nvh & (di & 0x10) << 1;
|
||||
di ^= nvh & (di & 0x20) << 1;
|
||||
di ^= nvh & (di & 0x40) << 1;
|
||||
d[i] = (byte)di;
|
||||
}
|
||||
|
||||
di = ((nvh & (di & 0x80) << 1) ^ vi) >> 8;
|
||||
|
||||
/* initialize state */
|
||||
set(yx[0], 1);
|
||||
cpy(yx[1], p[di]);
|
||||
cpy(yx[2], s[0]);
|
||||
set(yz[0], 0);
|
||||
set(yz[1], 1);
|
||||
set(yz[2], 1);
|
||||
|
||||
/* y[0] is (even)P + (even)G
|
||||
* y[1] is (even)P + (odd)G if current d-bit is 0
|
||||
* y[1] is (odd)P + (even)G if current d-bit is 1
|
||||
* y[2] is (odd)P + (odd)G
|
||||
*/
|
||||
|
||||
vi = 0;
|
||||
hi = 0;
|
||||
|
||||
/* and go for it! */
|
||||
for (i = 32; i--!=0; ) {
|
||||
vi = (vi << 8) | (v[i] & 0xFF);
|
||||
hi = (hi << 8) | (h[i] & 0xFF);
|
||||
di = (di << 8) | (d[i] & 0xFF);
|
||||
|
||||
for (j = 8; j--!=0; ) {
|
||||
mont_prep(t1[0], t2[0], yx[0], yz[0]);
|
||||
mont_prep(t1[1], t2[1], yx[1], yz[1]);
|
||||
mont_prep(t1[2], t2[2], yx[2], yz[2]);
|
||||
|
||||
k = ((vi ^ vi >> 1) >> j & 1)
|
||||
+ ((hi ^ hi >> 1) >> j & 1);
|
||||
mont_dbl(yx[2], yz[2], t1[k], t2[k], yx[0], yz[0]);
|
||||
|
||||
k = (di >> j & 2) ^ ((di >> j & 1) << 1);
|
||||
mont_add(t1[1], t2[1], t1[k], t2[k], yx[1], yz[1],
|
||||
p[di >> j & 1]);
|
||||
|
||||
mont_add(t1[2], t2[2], t1[0], t2[0], yx[2], yz[2],
|
||||
s[((vi ^ hi) >> j & 2) >> 1]);
|
||||
}
|
||||
}
|
||||
|
||||
k = (vi & 1) + (hi & 1);
|
||||
recip(t1[0], yz[k], 0);
|
||||
mul(t1[1], yx[k], t1[0]);
|
||||
|
||||
pack(t1[1], Y);
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/* sahn0:
|
||||
* Using this class instead of long[10] to avoid bounds checks. */
|
||||
private static final class long10 {
|
||||
public long10() {}
|
||||
public long10(
|
||||
long _0, long _1, long _2, long _3, long _4,
|
||||
long _5, long _6, long _7, long _8, long _9)
|
||||
{
|
||||
this._0=_0; this._1=_1; this._2=_2;
|
||||
this._3=_3; this._4=_4; this._5=_5;
|
||||
this._6=_6; this._7=_7; this._8=_8;
|
||||
this._9=_9;
|
||||
}
|
||||
public long _0,_1,_2,_3,_4,_5,_6,_7,_8,_9;
|
||||
}
|
||||
|
||||
/********************* radix 2^8 math *********************/
|
||||
|
||||
private static final void cpy32(byte[] d, byte[] s) {
|
||||
int i;
|
||||
for (i = 0; i < 32; i++)
|
||||
d[i] = s[i];
|
||||
}
|
||||
|
||||
/* p[m..n+m-1] = q[m..n+m-1] + z * x */
|
||||
/* n is the size of x */
|
||||
/* n+m is the size of p and q */
|
||||
private static final int mula_small(byte[] p,byte[] q,int m,byte[] x,int n,int z) {
|
||||
int v=0;
|
||||
for (int i=0;i<n;++i) {
|
||||
v+=(q[i+m] & 0xFF)+z*(x[i] & 0xFF);
|
||||
p[i+m]=(byte)v;
|
||||
v>>=8;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
/* p += x * y * z where z is a small integer
|
||||
* x is size 32, y is size t, p is size 32+t
|
||||
* y is allowed to overlap with p+32 if you don't care about the upper half */
|
||||
private static final int mula32(byte[] p, byte[] x, byte[] y, int t, int z) {
|
||||
final int n = 31;
|
||||
int w = 0;
|
||||
int i = 0;
|
||||
for (; i < t; i++) {
|
||||
int zy = z * (y[i] & 0xFF);
|
||||
w += mula_small(p, p, i, x, n, zy) +
|
||||
(p[i+n] & 0xFF) + zy * (x[n] & 0xFF);
|
||||
p[i+n] = (byte)w;
|
||||
w >>= 8;
|
||||
}
|
||||
p[i+n] = (byte)(w + (p[i+n] & 0xFF));
|
||||
return w >> 8;
|
||||
}
|
||||
|
||||
/* divide r (size n) by d (size t), returning quotient q and remainder r
|
||||
* quotient is size n-t+1, remainder is size t
|
||||
* requires t > 0 && d[t-1] != 0
|
||||
* requires that r[-1] and d[-1] are valid memory locations
|
||||
* q may overlap with r+t */
|
||||
private static final void divmod(byte[] q, byte[] r, int n, byte[] d, int t) {
|
||||
int rn = 0;
|
||||
int dt = ((d[t-1] & 0xFF) << 8);
|
||||
if (t>1) {
|
||||
dt |= (d[t-2] & 0xFF);
|
||||
}
|
||||
while (n-- >= t) {
|
||||
int z = (rn << 16) | ((r[n] & 0xFF) << 8);
|
||||
if (n>0) {
|
||||
z |= (r[n-1] & 0xFF);
|
||||
}
|
||||
z/=dt;
|
||||
rn += mula_small(r,r, n-t+1, d, t, -z);
|
||||
q[n-t+1] = (byte)((z + rn) & 0xFF); /* rn is 0 or -1 (underflow) */
|
||||
mula_small(r,r, n-t+1, d, t, -rn);
|
||||
rn = (r[n] & 0xFF);
|
||||
r[n] = 0;
|
||||
}
|
||||
r[t-1] = (byte)rn;
|
||||
}
|
||||
|
||||
private static final int numsize(byte[] x,int n) {
|
||||
while (n--!=0 && x[n]==0)
|
||||
;
|
||||
return n+1;
|
||||
}
|
||||
|
||||
/* Returns x if a contains the gcd, y if b.
|
||||
* Also, the returned buffer contains the inverse of a mod b,
|
||||
* as 32-byte signed.
|
||||
* x and y must have 64 bytes space for temporary use.
|
||||
* requires that a[-1] and b[-1] are valid memory locations */
|
||||
private static final byte[] egcd32(byte[] x,byte[] y,byte[] a,byte[] b) {
|
||||
int an, bn = 32, qn, i;
|
||||
for (i = 0; i < 32; i++)
|
||||
x[i] = y[i] = 0;
|
||||
x[0] = 1;
|
||||
an = numsize(a, 32);
|
||||
if (an==0)
|
||||
return y; /* division by zero */
|
||||
byte[] temp=new byte[32];
|
||||
while (true) {
|
||||
qn = bn - an + 1;
|
||||
divmod(temp, b, bn, a, an);
|
||||
bn = numsize(b, bn);
|
||||
if (bn==0)
|
||||
return x;
|
||||
mula32(y, x, temp, qn, -1);
|
||||
|
||||
qn = an - bn + 1;
|
||||
divmod(temp, a, an, b, bn);
|
||||
an = numsize(a, an);
|
||||
if (an==0)
|
||||
return y;
|
||||
mula32(x, y, temp, qn, -1);
|
||||
}
|
||||
}
|
||||
|
||||
/********************* radix 2^25.5 GF(2^255-19) math *********************/
|
||||
|
||||
private static final int P25=33554431; /* (1 << 25) - 1 */
|
||||
private static final int P26=67108863; /* (1 << 26) - 1 */
|
||||
|
||||
/* Convert to internal format from little-endian byte format */
|
||||
private static final void unpack(long10 x,byte[] m) {
|
||||
x._0 = ((m[0] & 0xFF)) | ((m[1] & 0xFF))<<8 |
|
||||
(m[2] & 0xFF)<<16 | ((m[3] & 0xFF)& 3)<<24;
|
||||
x._1 = ((m[3] & 0xFF)&~ 3)>>2 | (m[4] & 0xFF)<<6 |
|
||||
(m[5] & 0xFF)<<14 | ((m[6] & 0xFF)& 7)<<22;
|
||||
x._2 = ((m[6] & 0xFF)&~ 7)>>3 | (m[7] & 0xFF)<<5 |
|
||||
(m[8] & 0xFF)<<13 | ((m[9] & 0xFF)&31)<<21;
|
||||
x._3 = ((m[9] & 0xFF)&~31)>>5 | (m[10] & 0xFF)<<3 |
|
||||
(m[11] & 0xFF)<<11 | ((m[12] & 0xFF)&63)<<19;
|
||||
x._4 = ((m[12] & 0xFF)&~63)>>6 | (m[13] & 0xFF)<<2 |
|
||||
(m[14] & 0xFF)<<10 | (m[15] & 0xFF) <<18;
|
||||
x._5 = (m[16] & 0xFF) | (m[17] & 0xFF)<<8 |
|
||||
(m[18] & 0xFF)<<16 | ((m[19] & 0xFF)& 1)<<24;
|
||||
x._6 = ((m[19] & 0xFF)&~ 1)>>1 | (m[20] & 0xFF)<<7 |
|
||||
(m[21] & 0xFF)<<15 | ((m[22] & 0xFF)& 7)<<23;
|
||||
x._7 = ((m[22] & 0xFF)&~ 7)>>3 | (m[23] & 0xFF)<<5 |
|
||||
(m[24] & 0xFF)<<13 | ((m[25] & 0xFF)&15)<<21;
|
||||
x._8 = ((m[25] & 0xFF)&~15)>>4 | (m[26] & 0xFF)<<4 |
|
||||
(m[27] & 0xFF)<<12 | ((m[28] & 0xFF)&63)<<20;
|
||||
x._9 = ((m[28] & 0xFF)&~63)>>6 | (m[29] & 0xFF)<<2 |
|
||||
(m[30] & 0xFF)<<10 | (m[31] & 0xFF) <<18;
|
||||
}
|
||||
|
||||
/* Check if reduced-form input >= 2^255-19 */
|
||||
private static final boolean is_overflow(long10 x) {
|
||||
return (
|
||||
((x._0 > P26-19)) &&
|
||||
((x._1 & x._3 & x._5 & x._7 & x._9) == P25) &&
|
||||
((x._2 & x._4 & x._6 & x._8) == P26)
|
||||
) || (x._9 > P25);
|
||||
}
|
||||
|
||||
/* Convert from internal format to little-endian byte format. The
|
||||
* number must be in a reduced form which is output by the following ops:
|
||||
* unpack, mul, sqr
|
||||
* set -- if input in range 0 .. P25
|
||||
* If you're unsure if the number is reduced, first multiply it by 1. */
|
||||
private static final void pack(long10 x,byte[] m) {
|
||||
int ld = 0, ud = 0;
|
||||
long t;
|
||||
ld = (is_overflow(x)?1:0) - ((x._9 < 0)?1:0);
|
||||
ud = ld * -(P25+1);
|
||||
ld *= 19;
|
||||
t = ld + x._0 + (x._1 << 26);
|
||||
m[ 0] = (byte)t;
|
||||
m[ 1] = (byte)(t >> 8);
|
||||
m[ 2] = (byte)(t >> 16);
|
||||
m[ 3] = (byte)(t >> 24);
|
||||
t = (t >> 32) + (x._2 << 19);
|
||||
m[ 4] = (byte)t;
|
||||
m[ 5] = (byte)(t >> 8);
|
||||
m[ 6] = (byte)(t >> 16);
|
||||
m[ 7] = (byte)(t >> 24);
|
||||
t = (t >> 32) + (x._3 << 13);
|
||||
m[ 8] = (byte)t;
|
||||
m[ 9] = (byte)(t >> 8);
|
||||
m[10] = (byte)(t >> 16);
|
||||
m[11] = (byte)(t >> 24);
|
||||
t = (t >> 32) + (x._4 << 6);
|
||||
m[12] = (byte)t;
|
||||
m[13] = (byte)(t >> 8);
|
||||
m[14] = (byte)(t >> 16);
|
||||
m[15] = (byte)(t >> 24);
|
||||
t = (t >> 32) + x._5 + (x._6 << 25);
|
||||
m[16] = (byte)t;
|
||||
m[17] = (byte)(t >> 8);
|
||||
m[18] = (byte)(t >> 16);
|
||||
m[19] = (byte)(t >> 24);
|
||||
t = (t >> 32) + (x._7 << 19);
|
||||
m[20] = (byte)t;
|
||||
m[21] = (byte)(t >> 8);
|
||||
m[22] = (byte)(t >> 16);
|
||||
m[23] = (byte)(t >> 24);
|
||||
t = (t >> 32) + (x._8 << 12);
|
||||
m[24] = (byte)t;
|
||||
m[25] = (byte)(t >> 8);
|
||||
m[26] = (byte)(t >> 16);
|
||||
m[27] = (byte)(t >> 24);
|
||||
t = (t >> 32) + ((x._9 + ud) << 6);
|
||||
m[28] = (byte)t;
|
||||
m[29] = (byte)(t >> 8);
|
||||
m[30] = (byte)(t >> 16);
|
||||
m[31] = (byte)(t >> 24);
|
||||
}
|
||||
|
||||
/* Copy a number */
|
||||
private static final void cpy(long10 out, long10 in) {
|
||||
out._0=in._0; out._1=in._1;
|
||||
out._2=in._2; out._3=in._3;
|
||||
out._4=in._4; out._5=in._5;
|
||||
out._6=in._6; out._7=in._7;
|
||||
out._8=in._8; out._9=in._9;
|
||||
}
|
||||
|
||||
/* Set a number to value, which must be in range -185861411 .. 185861411 */
|
||||
private static final void set(long10 out, int in) {
|
||||
out._0=in; out._1=0;
|
||||
out._2=0; out._3=0;
|
||||
out._4=0; out._5=0;
|
||||
out._6=0; out._7=0;
|
||||
out._8=0; out._9=0;
|
||||
}
|
||||
|
||||
/* Add/subtract two numbers. The inputs must be in reduced form, and the
|
||||
* output isn't, so to do another addition or subtraction on the output,
|
||||
* first multiply it by one to reduce it. */
|
||||
private static final void add(long10 xy, long10 x, long10 y) {
|
||||
xy._0 = x._0 + y._0; xy._1 = x._1 + y._1;
|
||||
xy._2 = x._2 + y._2; xy._3 = x._3 + y._3;
|
||||
xy._4 = x._4 + y._4; xy._5 = x._5 + y._5;
|
||||
xy._6 = x._6 + y._6; xy._7 = x._7 + y._7;
|
||||
xy._8 = x._8 + y._8; xy._9 = x._9 + y._9;
|
||||
}
|
||||
private static final void sub(long10 xy, long10 x, long10 y) {
|
||||
xy._0 = x._0 - y._0; xy._1 = x._1 - y._1;
|
||||
xy._2 = x._2 - y._2; xy._3 = x._3 - y._3;
|
||||
xy._4 = x._4 - y._4; xy._5 = x._5 - y._5;
|
||||
xy._6 = x._6 - y._6; xy._7 = x._7 - y._7;
|
||||
xy._8 = x._8 - y._8; xy._9 = x._9 - y._9;
|
||||
}
|
||||
|
||||
/* Multiply a number by a small integer in range -185861411 .. 185861411.
|
||||
* The output is in reduced form, the input x need not be. x and xy may point
|
||||
* to the same buffer. */
|
||||
private static final long10 mul_small(long10 xy, long10 x, long y) {
|
||||
long t;
|
||||
t = (x._8*y);
|
||||
xy._8 = (t & ((1 << 26) - 1));
|
||||
t = (t >> 26) + (x._9*y);
|
||||
xy._9 = (t & ((1 << 25) - 1));
|
||||
t = 19 * (t >> 25) + (x._0*y);
|
||||
xy._0 = (t & ((1 << 26) - 1));
|
||||
t = (t >> 26) + (x._1*y);
|
||||
xy._1 = (t & ((1 << 25) - 1));
|
||||
t = (t >> 25) + (x._2*y);
|
||||
xy._2 = (t & ((1 << 26) - 1));
|
||||
t = (t >> 26) + (x._3*y);
|
||||
xy._3 = (t & ((1 << 25) - 1));
|
||||
t = (t >> 25) + (x._4*y);
|
||||
xy._4 = (t & ((1 << 26) - 1));
|
||||
t = (t >> 26) + (x._5*y);
|
||||
xy._5 = (t & ((1 << 25) - 1));
|
||||
t = (t >> 25) + (x._6*y);
|
||||
xy._6 = (t & ((1 << 26) - 1));
|
||||
t = (t >> 26) + (x._7*y);
|
||||
xy._7 = (t & ((1 << 25) - 1));
|
||||
t = (t >> 25) + xy._8;
|
||||
xy._8 = (t & ((1 << 26) - 1));
|
||||
xy._9 += (t >> 26);
|
||||
return xy;
|
||||
}
|
||||
|
||||
/* Multiply two numbers. The output is in reduced form, the inputs need not
|
||||
* be. */
|
||||
private static final long10 mul(long10 xy, long10 x, long10 y) {
|
||||
/* sahn0:
|
||||
* Using local variables to avoid class access.
|
||||
* This seem to improve performance a bit...
|
||||
*/
|
||||
long
|
||||
x_0=x._0,x_1=x._1,x_2=x._2,x_3=x._3,x_4=x._4,
|
||||
x_5=x._5,x_6=x._6,x_7=x._7,x_8=x._8,x_9=x._9;
|
||||
long
|
||||
y_0=y._0,y_1=y._1,y_2=y._2,y_3=y._3,y_4=y._4,
|
||||
y_5=y._5,y_6=y._6,y_7=y._7,y_8=y._8,y_9=y._9;
|
||||
long t;
|
||||
t = (x_0*y_8) + (x_2*y_6) + (x_4*y_4) + (x_6*y_2) +
|
||||
(x_8*y_0) + 2 * ((x_1*y_7) + (x_3*y_5) +
|
||||
(x_5*y_3) + (x_7*y_1)) + 38 *
|
||||
(x_9*y_9);
|
||||
xy._8 = (t & ((1 << 26) - 1));
|
||||
t = (t >> 26) + (x_0*y_9) + (x_1*y_8) + (x_2*y_7) +
|
||||
(x_3*y_6) + (x_4*y_5) + (x_5*y_4) +
|
||||
(x_6*y_3) + (x_7*y_2) + (x_8*y_1) +
|
||||
(x_9*y_0);
|
||||
xy._9 = (t & ((1 << 25) - 1));
|
||||
t = (x_0*y_0) + 19 * ((t >> 25) + (x_2*y_8) + (x_4*y_6)
|
||||
+ (x_6*y_4) + (x_8*y_2)) + 38 *
|
||||
((x_1*y_9) + (x_3*y_7) + (x_5*y_5) +
|
||||
(x_7*y_3) + (x_9*y_1));
|
||||
xy._0 = (t & ((1 << 26) - 1));
|
||||
t = (t >> 26) + (x_0*y_1) + (x_1*y_0) + 19 * ((x_2*y_9)
|
||||
+ (x_3*y_8) + (x_4*y_7) + (x_5*y_6) +
|
||||
(x_6*y_5) + (x_7*y_4) + (x_8*y_3) +
|
||||
(x_9*y_2));
|
||||
xy._1 = (t & ((1 << 25) - 1));
|
||||
t = (t >> 25) + (x_0*y_2) + (x_2*y_0) + 19 * ((x_4*y_8)
|
||||
+ (x_6*y_6) + (x_8*y_4)) + 2 * (x_1*y_1)
|
||||
+ 38 * ((x_3*y_9) + (x_5*y_7) +
|
||||
(x_7*y_5) + (x_9*y_3));
|
||||
xy._2 = (t & ((1 << 26) - 1));
|
||||
t = (t >> 26) + (x_0*y_3) + (x_1*y_2) + (x_2*y_1) +
|
||||
(x_3*y_0) + 19 * ((x_4*y_9) + (x_5*y_8) +
|
||||
(x_6*y_7) + (x_7*y_6) +
|
||||
(x_8*y_5) + (x_9*y_4));
|
||||
xy._3 = (t & ((1 << 25) - 1));
|
||||
t = (t >> 25) + (x_0*y_4) + (x_2*y_2) + (x_4*y_0) + 19 *
|
||||
((x_6*y_8) + (x_8*y_6)) + 2 * ((x_1*y_3) +
|
||||
(x_3*y_1)) + 38 *
|
||||
((x_5*y_9) + (x_7*y_7) + (x_9*y_5));
|
||||
xy._4 = (t & ((1 << 26) - 1));
|
||||
t = (t >> 26) + (x_0*y_5) + (x_1*y_4) + (x_2*y_3) +
|
||||
(x_3*y_2) + (x_4*y_1) + (x_5*y_0) + 19 *
|
||||
((x_6*y_9) + (x_7*y_8) + (x_8*y_7) +
|
||||
(x_9*y_6));
|
||||
xy._5 = (t & ((1 << 25) - 1));
|
||||
t = (t >> 25) + (x_0*y_6) + (x_2*y_4) + (x_4*y_2) +
|
||||
(x_6*y_0) + 19 * (x_8*y_8) + 2 * ((x_1*y_5) +
|
||||
(x_3*y_3) + (x_5*y_1)) + 38 *
|
||||
((x_7*y_9) + (x_9*y_7));
|
||||
xy._6 = (t & ((1 << 26) - 1));
|
||||
t = (t >> 26) + (x_0*y_7) + (x_1*y_6) + (x_2*y_5) +
|
||||
(x_3*y_4) + (x_4*y_3) + (x_5*y_2) +
|
||||
(x_6*y_1) + (x_7*y_0) + 19 * ((x_8*y_9) +
|
||||
(x_9*y_8));
|
||||
xy._7 = (t & ((1 << 25) - 1));
|
||||
t = (t >> 25) + xy._8;
|
||||
xy._8 = (t & ((1 << 26) - 1));
|
||||
xy._9 += (t >> 26);
|
||||
return xy;
|
||||
}
|
||||
|
||||
/* Square a number. Optimization of mul25519(x2, x, x) */
|
||||
private static final long10 sqr(long10 x2, long10 x) {
|
||||
long
|
||||
x_0=x._0,x_1=x._1,x_2=x._2,x_3=x._3,x_4=x._4,
|
||||
x_5=x._5,x_6=x._6,x_7=x._7,x_8=x._8,x_9=x._9;
|
||||
long t;
|
||||
t = (x_4*x_4) + 2 * ((x_0*x_8) + (x_2*x_6)) + 38 *
|
||||
(x_9*x_9) + 4 * ((x_1*x_7) + (x_3*x_5));
|
||||
x2._8 = (t & ((1 << 26) - 1));
|
||||
t = (t >> 26) + 2 * ((x_0*x_9) + (x_1*x_8) + (x_2*x_7) +
|
||||
(x_3*x_6) + (x_4*x_5));
|
||||
x2._9 = (t & ((1 << 25) - 1));
|
||||
t = 19 * (t >> 25) + (x_0*x_0) + 38 * ((x_2*x_8) +
|
||||
(x_4*x_6) + (x_5*x_5)) + 76 * ((x_1*x_9)
|
||||
+ (x_3*x_7));
|
||||
x2._0 = (t & ((1 << 26) - 1));
|
||||
t = (t >> 26) + 2 * (x_0*x_1) + 38 * ((x_2*x_9) +
|
||||
(x_3*x_8) + (x_4*x_7) + (x_5*x_6));
|
||||
x2._1 = (t & ((1 << 25) - 1));
|
||||
t = (t >> 25) + 19 * (x_6*x_6) + 2 * ((x_0*x_2) +
|
||||
(x_1*x_1)) + 38 * (x_4*x_8) + 76 *
|
||||
((x_3*x_9) + (x_5*x_7));
|
||||
x2._2 = (t & ((1 << 26) - 1));
|
||||
t = (t >> 26) + 2 * ((x_0*x_3) + (x_1*x_2)) + 38 *
|
||||
((x_4*x_9) + (x_5*x_8) + (x_6*x_7));
|
||||
x2._3 = (t & ((1 << 25) - 1));
|
||||
t = (t >> 25) + (x_2*x_2) + 2 * (x_0*x_4) + 38 *
|
||||
((x_6*x_8) + (x_7*x_7)) + 4 * (x_1*x_3) + 76 *
|
||||
(x_5*x_9);
|
||||
x2._4 = (t & ((1 << 26) - 1));
|
||||
t = (t >> 26) + 2 * ((x_0*x_5) + (x_1*x_4) + (x_2*x_3))
|
||||
+ 38 * ((x_6*x_9) + (x_7*x_8));
|
||||
x2._5 = (t & ((1 << 25) - 1));
|
||||
t = (t >> 25) + 19 * (x_8*x_8) + 2 * ((x_0*x_6) +
|
||||
(x_2*x_4) + (x_3*x_3)) + 4 * (x_1*x_5) +
|
||||
76 * (x_7*x_9);
|
||||
x2._6 = (t & ((1 << 26) - 1));
|
||||
t = (t >> 26) + 2 * ((x_0*x_7) + (x_1*x_6) + (x_2*x_5) +
|
||||
(x_3*x_4)) + 38 * (x_8*x_9);
|
||||
x2._7 = (t & ((1 << 25) - 1));
|
||||
t = (t >> 25) + x2._8;
|
||||
x2._8 = (t & ((1 << 26) - 1));
|
||||
x2._9 += (t >> 26);
|
||||
return x2;
|
||||
}
|
||||
|
||||
/* Calculates a reciprocal. The output is in reduced form, the inputs need not
|
||||
* be. Simply calculates y = x^(p-2) so it's not too fast. */
|
||||
/* When sqrtassist is true, it instead calculates y = x^((p-5)/8) */
|
||||
private static final void recip(long10 y, long10 x, int sqrtassist) {
|
||||
long10
|
||||
t0=new long10(),
|
||||
t1=new long10(),
|
||||
t2=new long10(),
|
||||
t3=new long10(),
|
||||
t4=new long10();
|
||||
int i;
|
||||
/* the chain for x^(2^255-21) is straight from djb's implementation */
|
||||
sqr(t1, x); /* 2 == 2 * 1 */
|
||||
sqr(t2, t1); /* 4 == 2 * 2 */
|
||||
sqr(t0, t2); /* 8 == 2 * 4 */
|
||||
mul(t2, t0, x); /* 9 == 8 + 1 */
|
||||
mul(t0, t2, t1); /* 11 == 9 + 2 */
|
||||
sqr(t1, t0); /* 22 == 2 * 11 */
|
||||
mul(t3, t1, t2); /* 31 == 22 + 9
|
||||
== 2^5 - 2^0 */
|
||||
sqr(t1, t3); /* 2^6 - 2^1 */
|
||||
sqr(t2, t1); /* 2^7 - 2^2 */
|
||||
sqr(t1, t2); /* 2^8 - 2^3 */
|
||||
sqr(t2, t1); /* 2^9 - 2^4 */
|
||||
sqr(t1, t2); /* 2^10 - 2^5 */
|
||||
mul(t2, t1, t3); /* 2^10 - 2^0 */
|
||||
sqr(t1, t2); /* 2^11 - 2^1 */
|
||||
sqr(t3, t1); /* 2^12 - 2^2 */
|
||||
for (i = 1; i < 5; i++) {
|
||||
sqr(t1, t3);
|
||||
sqr(t3, t1);
|
||||
} /* t3 */ /* 2^20 - 2^10 */
|
||||
mul(t1, t3, t2); /* 2^20 - 2^0 */
|
||||
sqr(t3, t1); /* 2^21 - 2^1 */
|
||||
sqr(t4, t3); /* 2^22 - 2^2 */
|
||||
for (i = 1; i < 10; i++) {
|
||||
sqr(t3, t4);
|
||||
sqr(t4, t3);
|
||||
} /* t4 */ /* 2^40 - 2^20 */
|
||||
mul(t3, t4, t1); /* 2^40 - 2^0 */
|
||||
for (i = 0; i < 5; i++) {
|
||||
sqr(t1, t3);
|
||||
sqr(t3, t1);
|
||||
} /* t3 */ /* 2^50 - 2^10 */
|
||||
mul(t1, t3, t2); /* 2^50 - 2^0 */
|
||||
sqr(t2, t1); /* 2^51 - 2^1 */
|
||||
sqr(t3, t2); /* 2^52 - 2^2 */
|
||||
for (i = 1; i < 25; i++) {
|
||||
sqr(t2, t3);
|
||||
sqr(t3, t2);
|
||||
} /* t3 */ /* 2^100 - 2^50 */
|
||||
mul(t2, t3, t1); /* 2^100 - 2^0 */
|
||||
sqr(t3, t2); /* 2^101 - 2^1 */
|
||||
sqr(t4, t3); /* 2^102 - 2^2 */
|
||||
for (i = 1; i < 50; i++) {
|
||||
sqr(t3, t4);
|
||||
sqr(t4, t3);
|
||||
} /* t4 */ /* 2^200 - 2^100 */
|
||||
mul(t3, t4, t2); /* 2^200 - 2^0 */
|
||||
for (i = 0; i < 25; i++) {
|
||||
sqr(t4, t3);
|
||||
sqr(t3, t4);
|
||||
} /* t3 */ /* 2^250 - 2^50 */
|
||||
mul(t2, t3, t1); /* 2^250 - 2^0 */
|
||||
sqr(t1, t2); /* 2^251 - 2^1 */
|
||||
sqr(t2, t1); /* 2^252 - 2^2 */
|
||||
if (sqrtassist!=0) {
|
||||
mul(y, x, t2); /* 2^252 - 3 */
|
||||
} else {
|
||||
sqr(t1, t2); /* 2^253 - 2^3 */
|
||||
sqr(t2, t1); /* 2^254 - 2^4 */
|
||||
sqr(t1, t2); /* 2^255 - 2^5 */
|
||||
mul(y, t1, t0); /* 2^255 - 21 */
|
||||
}
|
||||
}
|
||||
|
||||
/* checks if x is "negative", requires reduced input */
|
||||
private static final int is_negative(long10 x) {
|
||||
return (int)(((is_overflow(x) || (x._9 < 0))?1:0) ^ (x._0 & 1));
|
||||
}
|
||||
|
||||
/* a square root */
|
||||
private static final void sqrt(long10 x, long10 u) {
|
||||
long10 v=new long10(), t1=new long10(), t2=new long10();
|
||||
add(t1, u, u); /* t1 = 2u */
|
||||
recip(v, t1, 1); /* v = (2u)^((p-5)/8) */
|
||||
sqr(x, v); /* x = v^2 */
|
||||
mul(t2, t1, x); /* t2 = 2uv^2 */
|
||||
t2._0--; /* t2 = 2uv^2-1 */
|
||||
mul(t1, v, t2); /* t1 = v(2uv^2-1) */
|
||||
mul(x, u, t1); /* x = uv(2uv^2-1) */
|
||||
}
|
||||
|
||||
/********************* Elliptic curve *********************/
|
||||
|
||||
/* y^2 = x^3 + 486662 x^2 + x over GF(2^255-19) */
|
||||
|
||||
/* t1 = ax + az
|
||||
* t2 = ax - az */
|
||||
private static final void mont_prep(long10 t1, long10 t2, long10 ax, long10 az) {
|
||||
add(t1, ax, az);
|
||||
sub(t2, ax, az);
|
||||
}
|
||||
|
||||
/* A = P + Q where
|
||||
* X(A) = ax/az
|
||||
* X(P) = (t1+t2)/(t1-t2)
|
||||
* X(Q) = (t3+t4)/(t3-t4)
|
||||
* X(P-Q) = dx
|
||||
* clobbers t1 and t2, preserves t3 and t4 */
|
||||
private static final void mont_add(long10 t1, long10 t2, long10 t3, long10 t4,long10 ax, long10 az, long10 dx) {
|
||||
mul(ax, t2, t3);
|
||||
mul(az, t1, t4);
|
||||
add(t1, ax, az);
|
||||
sub(t2, ax, az);
|
||||
sqr(ax, t1);
|
||||
sqr(t1, t2);
|
||||
mul(az, t1, dx);
|
||||
}
|
||||
|
||||
/* B = 2 * Q where
|
||||
* X(B) = bx/bz
|
||||
* X(Q) = (t3+t4)/(t3-t4)
|
||||
* clobbers t1 and t2, preserves t3 and t4 */
|
||||
private static final void mont_dbl(long10 t1, long10 t2, long10 t3, long10 t4,long10 bx, long10 bz) {
|
||||
sqr(t1, t3);
|
||||
sqr(t2, t4);
|
||||
mul(bx, t1, t2);
|
||||
sub(t2, t1, t2);
|
||||
mul_small(bz, t2, 121665);
|
||||
add(t1, t1, bz);
|
||||
mul(bz, t1, t2);
|
||||
}
|
||||
|
||||
/* Y^2 = X^3 + 486662 X^2 + X
|
||||
* t is a temporary */
|
||||
private static final void x_to_y2(long10 t, long10 y2, long10 x) {
|
||||
sqr(t, x);
|
||||
mul_small(y2, x, 486662);
|
||||
add(t, t, y2);
|
||||
t._0++;
|
||||
mul(y2, t, x);
|
||||
}
|
||||
|
||||
/* P = kG and s = sign(P)/k */
|
||||
private static final void core(byte[] Px, byte[] s, byte[] k, byte[] Gx) {
|
||||
long10
|
||||
dx=new long10(),
|
||||
t1=new long10(),
|
||||
t2=new long10(),
|
||||
t3=new long10(),
|
||||
t4=new long10();
|
||||
long10[]
|
||||
x=new long10[]{new long10(),new long10()},
|
||||
z=new long10[]{new long10(),new long10()};
|
||||
int i, j;
|
||||
|
||||
/* unpack the base */
|
||||
if (Gx!=null)
|
||||
unpack(dx, Gx);
|
||||
else
|
||||
set(dx, 9);
|
||||
|
||||
/* 0G = point-at-infinity */
|
||||
set(x[0], 1);
|
||||
set(z[0], 0);
|
||||
|
||||
/* 1G = G */
|
||||
cpy(x[1], dx);
|
||||
set(z[1], 1);
|
||||
|
||||
for (i = 32; i--!=0; ) {
|
||||
if (i==0) {
|
||||
i=0;
|
||||
}
|
||||
for (j = 8; j--!=0; ) {
|
||||
/* swap arguments depending on bit */
|
||||
int bit1 = (k[i] & 0xFF) >> j & 1;
|
||||
int bit0 = ~(k[i] & 0xFF) >> j & 1;
|
||||
long10 ax = x[bit0];
|
||||
long10 az = z[bit0];
|
||||
long10 bx = x[bit1];
|
||||
long10 bz = z[bit1];
|
||||
|
||||
/* a' = a + b */
|
||||
/* b' = 2 b */
|
||||
mont_prep(t1, t2, ax, az);
|
||||
mont_prep(t3, t4, bx, bz);
|
||||
mont_add(t1, t2, t3, t4, ax, az, dx);
|
||||
mont_dbl(t1, t2, t3, t4, bx, bz);
|
||||
}
|
||||
}
|
||||
|
||||
recip(t1, z[0], 0);
|
||||
mul(dx, x[0], t1);
|
||||
pack(dx, Px);
|
||||
|
||||
/* calculate s such that s abs(P) = G .. assumes G is std base point */
|
||||
if (s!=null) {
|
||||
x_to_y2(t2, t1, dx); /* t1 = Py^2 */
|
||||
recip(t3, z[1], 0); /* where Q=P+G ... */
|
||||
mul(t2, x[1], t3); /* t2 = Qx */
|
||||
add(t2, t2, dx); /* t2 = Qx + Px */
|
||||
t2._0 += 9 + 486662; /* t2 = Qx + Px + Gx + 486662 */
|
||||
dx._0 -= 9; /* dx = Px - Gx */
|
||||
sqr(t3, dx); /* t3 = (Px - Gx)^2 */
|
||||
mul(dx, t2, t3); /* dx = t2 (Px - Gx)^2 */
|
||||
sub(dx, dx, t1); /* dx = t2 (Px - Gx)^2 - Py^2 */
|
||||
dx._0 -= 39420360; /* dx = t2 (Px - Gx)^2 - Py^2 - Gy^2 */
|
||||
mul(t1, dx, BASE_R2Y); /* t1 = -Py */
|
||||
if (is_negative(t1)!=0) /* sign is 1, so just copy */
|
||||
cpy32(s, k);
|
||||
else /* sign is -1, so negate */
|
||||
mula_small(s, ORDER_TIMES_8, 0, k, 32, -1);
|
||||
|
||||
/* reduce s mod q
|
||||
* (is this needed? do it just in case, it's fast anyway) */
|
||||
//divmod((dstptr) t1, s, 32, order25519, 32);
|
||||
|
||||
/* take reciprocal of s mod q */
|
||||
byte[] temp1=new byte[32];
|
||||
byte[] temp2=new byte[64];
|
||||
byte[] temp3=new byte[64];
|
||||
cpy32(temp1, ORDER);
|
||||
cpy32(s, egcd32(temp2, temp3, s, temp1));
|
||||
if ((s[31] & 0x80)!=0)
|
||||
mula_small(s, s, 0, ORDER, 32, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* smallest multiple of the order that's >= 2^255 */
|
||||
private static final byte[] ORDER_TIMES_8 = {
|
||||
(byte)104, (byte)159, (byte)174, (byte)231,
|
||||
(byte)210, (byte)24, (byte)147, (byte)192,
|
||||
(byte)178, (byte)230, (byte)188, (byte)23,
|
||||
(byte)245, (byte)206, (byte)247, (byte)166,
|
||||
(byte)0, (byte)0, (byte)0, (byte)0,
|
||||
(byte)0, (byte)0, (byte)0, (byte)0,
|
||||
(byte)0, (byte)0, (byte)0, (byte)0,
|
||||
(byte)0, (byte)0, (byte)0, (byte)128
|
||||
};
|
||||
|
||||
/* constants 2Gy and 1/(2Gy) */
|
||||
private static final long10 BASE_2Y = new long10(
|
||||
39999547, 18689728, 59995525, 1648697, 57546132,
|
||||
24010086, 19059592, 5425144, 63499247, 16420658
|
||||
);
|
||||
private static final long10 BASE_R2Y = new long10(
|
||||
5744, 8160848, 4790893, 13779497, 35730846,
|
||||
12541209, 49101323, 30047407, 40071253, 6226132
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,433 @@
|
|||
// /Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.jmdns.impl.JmDNSImpl;
|
||||
|
||||
/**
|
||||
* mDNS implementation in Java.
|
||||
*
|
||||
* @author Arthur van Hoff, Rick Blair, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Scott Lewis, Scott Cytacki
|
||||
*/
|
||||
public abstract class JmDNS implements Closeable {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public static interface Delegate {
|
||||
|
||||
/**
|
||||
* This method is called if JmDNS cannot recover from an I/O error.
|
||||
*
|
||||
* @param dns
|
||||
* target DNS
|
||||
* @param infos
|
||||
* service info registered with the DNS
|
||||
*/
|
||||
public void cannotRecoverFromIOError(JmDNS dns, Collection<ServiceInfo> infos);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The version of JmDNS.
|
||||
*/
|
||||
public static final String VERSION = "3.4.2";
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Create an instance of JmDNS.
|
||||
* </p>
|
||||
* <p>
|
||||
* <b>Note:</b> This is a convenience method. The preferred constructor is {@link #create(InetAddress, String)}.<br/>
|
||||
* Check that your platform correctly handle the default localhost IP address and the local hostname. In doubt use the explicit constructor.<br/>
|
||||
* This call is equivalent to <code>create(null, null)</code>.
|
||||
* </p>
|
||||
*
|
||||
* @see #create(InetAddress, String)
|
||||
* @return jmDNS instance
|
||||
* @exception IOException
|
||||
* if an exception occurs during the socket creation
|
||||
*/
|
||||
public static JmDNS create() throws IOException {
|
||||
return new JmDNSImpl(null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Create an instance of JmDNS and bind it to a specific network interface given its IP-address.
|
||||
* </p>
|
||||
* <p>
|
||||
* <b>Note:</b> This is a convenience method. The preferred constructor is {@link #create(InetAddress, String)}.<br/>
|
||||
* Check that your platform correctly handle the default localhost IP address and the local hostname. In doubt use the explicit constructor.<br/>
|
||||
* This call is equivalent to <code>create(addr, null)</code>.
|
||||
* </p>
|
||||
*
|
||||
* @see #create(InetAddress, String)
|
||||
* @param addr
|
||||
* IP address to bind to.
|
||||
* @return jmDNS instance
|
||||
* @exception IOException
|
||||
* if an exception occurs during the socket creation
|
||||
*/
|
||||
public static JmDNS create(final InetAddress addr) throws IOException {
|
||||
return new JmDNSImpl(addr, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Create an instance of JmDNS.
|
||||
* </p>
|
||||
* <p>
|
||||
* <b>Note:</b> This is a convenience method. The preferred constructor is {@link #create(InetAddress, String)}.<br/>
|
||||
* Check that your platform correctly handle the default localhost IP address and the local hostname. In doubt use the explicit constructor.<br/>
|
||||
* This call is equivalent to <code>create(null, name)</code>.
|
||||
* </p>
|
||||
*
|
||||
* @see #create(InetAddress, String)
|
||||
* @param name
|
||||
* name of the newly created JmDNS
|
||||
* @return jmDNS instance
|
||||
* @exception IOException
|
||||
* if an exception occurs during the socket creation
|
||||
*/
|
||||
public static JmDNS create(final String name) throws IOException {
|
||||
return new JmDNSImpl(null, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Create an instance of JmDNS and bind it to a specific network interface given its IP-address.
|
||||
* </p>
|
||||
* If <code>addr</code> parameter is null this method will try to resolve to a local IP address of the machine using a network discovery:
|
||||
* <ol>
|
||||
* <li>Check the system property <code>net.mdns.interface</code></li>
|
||||
* <li>Check the JVM local host</li>
|
||||
* <li>Use the {@link NetworkTopologyDiscovery} to find a valid network interface and IP.</li>
|
||||
* <li>In the last resort bind to the loopback address. This is non functional in most cases.</li>
|
||||
* </ol>
|
||||
* If <code>name</code> parameter is null will use the hostname. The hostname is determined by the following algorithm:
|
||||
* <ol>
|
||||
* <li>Get the hostname from the InetAdress obtained before.</li>
|
||||
* <li>If the hostname is a reverse lookup default to <code>JmDNS name</code> or <code>computer</code> if null.</li>
|
||||
* <li>If the name contains <code>'.'</code> replace them by <code>'-'</code></li>
|
||||
* <li>Add <code>.local.</code> at the end of the name.</li>
|
||||
* </ol>
|
||||
* <p>
|
||||
* <b>Note:</b> If you need to use a custom {@link NetworkTopologyDiscovery} it must be setup before any call to this method. This is done by setting up a {@link NetworkTopologyDiscovery.Factory.ClassDelegate} and installing it using
|
||||
* {@link NetworkTopologyDiscovery.Factory#setClassDelegate(NetworkTopologyDiscovery.Factory.ClassDelegate)}. This must be done before creating a {@link JmDNS} or {@link JmmDNS} instance.
|
||||
* </p>
|
||||
*
|
||||
* @param addr
|
||||
* IP address to bind to.
|
||||
* @param name
|
||||
* name of the newly created JmDNS
|
||||
* @return jmDNS instance
|
||||
* @exception IOException
|
||||
* if an exception occurs during the socket creation
|
||||
*/
|
||||
public static JmDNS create(final InetAddress addr, final String name) throws IOException {
|
||||
return new JmDNSImpl(addr, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the name of the JmDNS instance. This is an arbitrary string that is useful for distinguishing instances.
|
||||
*
|
||||
* @return name of the JmDNS
|
||||
*/
|
||||
public abstract String getName();
|
||||
|
||||
/**
|
||||
* Return the HostName associated with this JmDNS instance. Note: May not be the same as what started. The host name is subject to negotiation.
|
||||
*
|
||||
* @return Host name
|
||||
*/
|
||||
public abstract String getHostName();
|
||||
|
||||
/**
|
||||
* Return the address of the interface to which this instance of JmDNS is bound.
|
||||
*
|
||||
* @return Internet Address
|
||||
* @exception IOException
|
||||
* if there is an error in the underlying protocol, such as a TCP error.
|
||||
*/
|
||||
public abstract InetAddress getInetAddress() throws IOException;
|
||||
|
||||
/**
|
||||
* Return the address of the interface to which this instance of JmDNS is bound.
|
||||
*
|
||||
* @return Internet Address
|
||||
* @exception IOException
|
||||
* if there is an error in the underlying protocol, such as a TCP error.
|
||||
* @deprecated do not use this implementation yields unpredictable results use {@link #getInetAddress()}
|
||||
*/
|
||||
@Deprecated
|
||||
public abstract InetAddress getInterface() throws IOException;
|
||||
|
||||
/**
|
||||
* Get service information. If the information is not cached, the method will block until updated information is received.
|
||||
* <p/>
|
||||
* Usage note: Do not call this method from the AWT event dispatcher thread. You will make the user interface unresponsive.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
* @return null if the service information cannot be obtained
|
||||
*/
|
||||
public abstract ServiceInfo getServiceInfo(String type, String name);
|
||||
|
||||
/**
|
||||
* Get service information. If the information is not cached, the method will block for the given timeout until updated information is received.
|
||||
* <p/>
|
||||
* Usage note: If you call this method from the AWT event dispatcher thread, use a small timeout, or you will make the user interface unresponsive.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
* @param timeout
|
||||
* timeout in milliseconds. Typical timeout should be 5s.
|
||||
* @return null if the service information cannot be obtained
|
||||
*/
|
||||
public abstract ServiceInfo getServiceInfo(String type, String name, long timeout);
|
||||
|
||||
/**
|
||||
* Get service information. If the information is not cached, the method will block until updated information is received.
|
||||
* <p/>
|
||||
* Usage note: Do not call this method from the AWT event dispatcher thread. You will make the user interface unresponsive.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
* @param persistent
|
||||
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
|
||||
* @return null if the service information cannot be obtained
|
||||
*/
|
||||
public abstract ServiceInfo getServiceInfo(String type, String name, boolean persistent);
|
||||
|
||||
/**
|
||||
* Get service information. If the information is not cached, the method will block for the given timeout until updated information is received.
|
||||
* <p/>
|
||||
* Usage note: If you call this method from the AWT event dispatcher thread, use a small timeout, or you will make the user interface unresponsive.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
* @param timeout
|
||||
* timeout in milliseconds. Typical timeout should be 5s.
|
||||
* @param persistent
|
||||
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
|
||||
* @return null if the service information cannot be obtained
|
||||
*/
|
||||
public abstract ServiceInfo getServiceInfo(String type, String name, boolean persistent, long timeout);
|
||||
|
||||
/**
|
||||
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
|
||||
* <p/>
|
||||
* Usage note: Do not call this method from the AWT event dispatcher thread. You will make the user interface unresponsive.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
*/
|
||||
public abstract void requestServiceInfo(String type, String name);
|
||||
|
||||
/**
|
||||
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
|
||||
* <p/>
|
||||
* Usage note: Do not call this method from the AWT event dispatcher thread. You will make the user interface unresponsive.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
* @param persistent
|
||||
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
|
||||
*/
|
||||
public abstract void requestServiceInfo(String type, String name, boolean persistent);
|
||||
|
||||
/**
|
||||
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
* @param timeout
|
||||
* timeout in milliseconds
|
||||
*/
|
||||
public abstract void requestServiceInfo(String type, String name, long timeout);
|
||||
|
||||
/**
|
||||
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
* @param persistent
|
||||
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
|
||||
* @param timeout
|
||||
* timeout in milliseconds
|
||||
*/
|
||||
public abstract void requestServiceInfo(String type, String name, boolean persistent, long timeout);
|
||||
|
||||
/**
|
||||
* Listen for service types.
|
||||
*
|
||||
* @param listener
|
||||
* listener for service types
|
||||
* @exception IOException
|
||||
* if there is an error in the underlying protocol, such as a TCP error.
|
||||
*/
|
||||
public abstract void addServiceTypeListener(ServiceTypeListener listener) throws IOException;
|
||||
|
||||
/**
|
||||
* Remove listener for service types.
|
||||
*
|
||||
* @param listener
|
||||
* listener for service types
|
||||
*/
|
||||
public abstract void removeServiceTypeListener(ServiceTypeListener listener);
|
||||
|
||||
/**
|
||||
* Listen for services of a given type. The type has to be a fully qualified type name such as <code>_http._tcp.local.</code>.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code>.
|
||||
* @param listener
|
||||
* listener for service updates
|
||||
*/
|
||||
public abstract void addServiceListener(String type, ServiceListener listener);
|
||||
|
||||
/**
|
||||
* Remove listener for services of a given type.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code>.
|
||||
* @param listener
|
||||
* listener for service updates
|
||||
*/
|
||||
public abstract void removeServiceListener(String type, ServiceListener listener);
|
||||
|
||||
/**
|
||||
* Register a service. The service is registered for access by other jmdns clients. The name of the service may be changed to make it unique.<br>
|
||||
* Note that the given {@code ServiceInfo} is bound to this {@code JmDNS} instance, and should not be reused for any other {@linkplain #registerService(ServiceInfo)}.
|
||||
*
|
||||
* @param info
|
||||
* service info to register
|
||||
* @exception IOException
|
||||
* if there is an error in the underlying protocol, such as a TCP error.
|
||||
*/
|
||||
public abstract void registerService(ServiceInfo info) throws IOException;
|
||||
|
||||
/**
|
||||
* Unregister a service. The service should have been registered.
|
||||
* <p>
|
||||
* <b>Note:</b> Unregistered services will not disappear form the list of services immediately. According to the specification, when unregistering services we send goodbye packets and then wait <b>1s</b> before purging the cache.<br/>
|
||||
* This is support for shared records that can be rescued by some other cooperation DNS.
|
||||
*
|
||||
* <pre>
|
||||
* Clients receiving a Multicast DNS Response with a TTL of zero SHOULD NOT immediately delete the record from the cache, but instead record a TTL of 1 and then delete the record one second later.
|
||||
* </pre>
|
||||
*
|
||||
* </p>
|
||||
*
|
||||
* @param info
|
||||
* service info to remove
|
||||
*/
|
||||
public abstract void unregisterService(ServiceInfo info);
|
||||
|
||||
/**
|
||||
* Unregister all services.
|
||||
*/
|
||||
public abstract void unregisterAllServices();
|
||||
|
||||
/**
|
||||
* Register a service type. If this service type was not already known, all service listeners will be notified of the new service type.
|
||||
* <p>
|
||||
* Service types are automatically registered as they are discovered.
|
||||
* </p>
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code>.
|
||||
* @return <code>true</code> if the type or subtype was added, <code>false</code> if the type was already registered.
|
||||
*/
|
||||
public abstract boolean registerServiceType(String type);
|
||||
|
||||
/**
|
||||
* List Services and serviceTypes. Debugging Only
|
||||
*
|
||||
* @deprecated since 3.2.2
|
||||
*/
|
||||
@Deprecated
|
||||
public abstract void printServices();
|
||||
|
||||
/**
|
||||
* Returns a list of service infos of the specified type.
|
||||
*
|
||||
* @param type
|
||||
* Service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @return An array of service instance.
|
||||
*/
|
||||
public abstract ServiceInfo[] list(String type);
|
||||
|
||||
/**
|
||||
* Returns a list of service infos of the specified type.
|
||||
*
|
||||
* @param type
|
||||
* Service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param timeout
|
||||
* timeout in milliseconds. Typical timeout should be 6s.
|
||||
* @return An array of service instance.
|
||||
*/
|
||||
public abstract ServiceInfo[] list(String type, long timeout);
|
||||
|
||||
/**
|
||||
* Returns a list of service infos of the specified type sorted by subtype. Any service that do not register a subtype is listed in the empty subtype section.
|
||||
*
|
||||
* @param type
|
||||
* Service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @return A dictionary of service info by subtypes.
|
||||
*/
|
||||
public abstract Map<String, ServiceInfo[]> listBySubtype(String type);
|
||||
|
||||
/**
|
||||
* Returns a list of service infos of the specified type sorted by subtype. Any service that do not register a subtype is listed in the empty subtype section.
|
||||
*
|
||||
* @param type
|
||||
* Service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param timeout
|
||||
* timeout in milliseconds. Typical timeout should be 6s.
|
||||
* @return A dictionary of service info by subtypes.
|
||||
*/
|
||||
public abstract Map<String, ServiceInfo[]> listBySubtype(String type, long timeout);
|
||||
|
||||
/**
|
||||
* Returns the instance delegate
|
||||
*
|
||||
* @return instance delegate
|
||||
*/
|
||||
public abstract Delegate getDelegate();
|
||||
|
||||
/**
|
||||
* Sets the instance delegate
|
||||
*
|
||||
* @param value
|
||||
* new instance delegate
|
||||
* @return previous instance delegate
|
||||
*/
|
||||
public abstract Delegate setDelegate(Delegate value);
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,426 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import javax.jmdns.impl.JmmDNSImpl;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Java Multihomed Multicast DNS
|
||||
* </p>
|
||||
* Uses an underlying {@link JmDNS} instance for each {@link InetAddress} found on this computer.<br/>
|
||||
* This class will monitor network topology changes, and will create or destroy JmDNS instances as required. It is your responsibility to maintain services registration (hint: use a {@link NetworkTopologyListener}).<br/>
|
||||
* Most of this class methods have no notion of transaction: if an Exception is raised in the middle of execution, you may be in an incoherent state.
|
||||
* <p>
|
||||
* <b>Note:</b> This API is experimental and may change in the future please let us know what work and what does not work in your application.
|
||||
* </p>
|
||||
*
|
||||
* @author Cédrik Lime, Pierre Frisch
|
||||
*/
|
||||
public interface JmmDNS extends Closeable {
|
||||
|
||||
/**
|
||||
* JmmDNS.Factory enable the creation of new instance of JmmDNS.
|
||||
*/
|
||||
public static final class Factory {
|
||||
private static volatile JmmDNS _instance;
|
||||
|
||||
/**
|
||||
* This interface defines a delegate to the EOClassDescriptionRegister class to enable subclassing.
|
||||
*/
|
||||
public static interface ClassDelegate {
|
||||
|
||||
/**
|
||||
* Allows the delegate the opportunity to construct and return a different JmmDNS.
|
||||
*
|
||||
* @return Should return a new JmmDNS.
|
||||
* @see #classDelegate()
|
||||
* @see #setClassDelegate(ClassDelegate anObject)
|
||||
*/
|
||||
public JmmDNS newJmmDNS();
|
||||
|
||||
}
|
||||
|
||||
private static final AtomicReference<ClassDelegate> _databaseClassDelegate = new AtomicReference<ClassDelegate>();
|
||||
|
||||
private Factory() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns <code>delegate</code> as JmmDNS's class delegate. The class delegate is optional.
|
||||
*
|
||||
* @param delegate
|
||||
* The object to set as JmmDNS's class delegate.
|
||||
* @see #classDelegate()
|
||||
* @see JmmDNS.Factory.ClassDelegate
|
||||
*/
|
||||
public static void setClassDelegate(ClassDelegate delegate) {
|
||||
_databaseClassDelegate.set(delegate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns JmmDNS's class delegate.
|
||||
*
|
||||
* @return JmmDNS's class delegate.
|
||||
* @see #setClassDelegate(ClassDelegate anObject)
|
||||
* @see JmmDNS.Factory.ClassDelegate
|
||||
*/
|
||||
public static ClassDelegate classDelegate() {
|
||||
return _databaseClassDelegate.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new instance of JmmDNS using the class delegate if it exists.
|
||||
*
|
||||
* @return new instance of JmmDNS
|
||||
*/
|
||||
protected static JmmDNS newJmmDNS() {
|
||||
JmmDNS dns = null;
|
||||
ClassDelegate delegate = _databaseClassDelegate.get();
|
||||
if (delegate != null) {
|
||||
dns = delegate.newJmmDNS();
|
||||
}
|
||||
return (dns != null ? dns : new JmmDNSImpl());
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the instance of the Multihomed Multicast DNS.
|
||||
*
|
||||
* @return the JmmDNS
|
||||
*/
|
||||
public static JmmDNS getInstance() {
|
||||
if (_instance == null) {
|
||||
synchronized (Factory.class) {
|
||||
if (_instance == null) {
|
||||
_instance = JmmDNS.Factory.newJmmDNS();
|
||||
}
|
||||
}
|
||||
}
|
||||
return _instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the instance if still running and discard it.
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void close() throws IOException {
|
||||
synchronized (Factory.class) {
|
||||
_instance.close();
|
||||
_instance = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the names of the JmDNS instances.
|
||||
*
|
||||
* @return list of name of the JmDNS
|
||||
* @see javax.jmdns.JmDNS#getName()
|
||||
*/
|
||||
public abstract String[] getNames();
|
||||
|
||||
/**
|
||||
* Return the list HostName associated with this JmmDNS instance.
|
||||
*
|
||||
* @return list of host names
|
||||
* @see javax.jmdns.JmDNS#getHostName()
|
||||
*/
|
||||
public abstract String[] getHostNames();
|
||||
|
||||
/**
|
||||
* Return the list of addresses of the interface to which this instance of JmmDNS is bound.
|
||||
*
|
||||
* @return list of Internet Address
|
||||
* @exception IOException
|
||||
* @see javax.jmdns.JmDNS#getInetAddress()
|
||||
*/
|
||||
public abstract InetAddress[] getInetAddresses() throws IOException;
|
||||
|
||||
/**
|
||||
* Return the list of addresses of the interface to which this instance of JmmDNS is bound.
|
||||
*
|
||||
* @return list of Internet Address
|
||||
* @exception IOException
|
||||
* @see javax.jmdns.JmDNS#getInterface()
|
||||
* @deprecated do not use this implementation yields unpredictable results use {@link #getInetAddresses()}
|
||||
*/
|
||||
@Deprecated
|
||||
public abstract InetAddress[] getInterfaces() throws IOException;
|
||||
|
||||
/**
|
||||
* Return a list of all the registered JmDNS instances
|
||||
*
|
||||
* @return list of JmDNS instances
|
||||
*/
|
||||
public abstract JmDNS[] getDNS();
|
||||
|
||||
/**
|
||||
* Get service information. If the information is not cached, the method will block until updated information is received on all DNS.
|
||||
* <p/>
|
||||
* Usage note: Do not call this method from the AWT event dispatcher thread. You will make the user interface unresponsive.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
* @return list of service info. If no service info is found the list is empty.
|
||||
* @see javax.jmdns.JmDNS#getServiceInfo(java.lang.String, java.lang.String)
|
||||
*/
|
||||
public abstract ServiceInfo[] getServiceInfos(String type, String name);
|
||||
|
||||
/**
|
||||
* Get service information. If the information is not cached, the method will block until updated information is received on all DNS.
|
||||
* <p/>
|
||||
* Usage note: If you call this method from the AWT event dispatcher thread, use a small timeout, or you will make the user interface unresponsive.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
* @param timeout
|
||||
* timeout in milliseconds. Typical timeout should be 5s.
|
||||
* @return list of service info. If no service info is found the list is empty.
|
||||
* @see javax.jmdns.JmDNS#getServiceInfo(java.lang.String, java.lang.String, long)
|
||||
*/
|
||||
public abstract ServiceInfo[] getServiceInfos(String type, String name, long timeout);
|
||||
|
||||
/**
|
||||
* Get service information. If the information is not cached, the method will block until updated information is received on all DNS.
|
||||
* <p/>
|
||||
* Usage note: If you call this method from the AWT event dispatcher thread, use a small timeout, or you will make the user interface unresponsive.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
* @param persistent
|
||||
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
|
||||
* @return list of service info. If no service info is found the list is empty.
|
||||
* @see javax.jmdns.JmDNS#getServiceInfo(java.lang.String, java.lang.String, boolean)
|
||||
*/
|
||||
public abstract ServiceInfo[] getServiceInfos(String type, String name, boolean persistent);
|
||||
|
||||
/**
|
||||
* Get service information. If the information is not cached, the method will block until updated information is received on all DNS.
|
||||
* <p/>
|
||||
* Usage note: If you call this method from the AWT event dispatcher thread, use a small timeout, or you will make the user interface unresponsive.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
* @param timeout
|
||||
* timeout in milliseconds. Typical timeout should be 5s.
|
||||
* @param persistent
|
||||
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
|
||||
* @return list of service info. If no service info is found the list is empty.
|
||||
* @see javax.jmdns.JmDNS#getServiceInfo(java.lang.String, java.lang.String, boolean, long)
|
||||
*/
|
||||
public abstract ServiceInfo[] getServiceInfos(String type, String name, boolean persistent, long timeout);
|
||||
|
||||
/**
|
||||
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
* @see javax.jmdns.JmDNS#requestServiceInfo(java.lang.String, java.lang.String)
|
||||
*/
|
||||
public abstract void requestServiceInfo(String type, String name);
|
||||
|
||||
/**
|
||||
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
* @param persistent
|
||||
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
|
||||
* @see javax.jmdns.JmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean)
|
||||
*/
|
||||
public abstract void requestServiceInfo(String type, String name, boolean persistent);
|
||||
|
||||
/**
|
||||
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
* @param timeout
|
||||
* timeout in milliseconds
|
||||
* @see javax.jmdns.JmDNS#requestServiceInfo(java.lang.String, java.lang.String, long)
|
||||
*/
|
||||
public abstract void requestServiceInfo(String type, String name, long timeout);
|
||||
|
||||
/**
|
||||
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code> .
|
||||
* @param name
|
||||
* unqualified service name, such as <code>foobar</code> .
|
||||
* @param persistent
|
||||
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
|
||||
* @param timeout
|
||||
* timeout in milliseconds
|
||||
* @see javax.jmdns.JmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean, long)
|
||||
*/
|
||||
public abstract void requestServiceInfo(String type, String name, boolean persistent, long timeout);
|
||||
|
||||
/**
|
||||
* Listen for service types.
|
||||
*
|
||||
* @param listener
|
||||
* listener for service types
|
||||
* @exception IOException
|
||||
* @see javax.jmdns.JmDNS#addServiceTypeListener(javax.jmdns.ServiceTypeListener)
|
||||
*/
|
||||
public abstract void addServiceTypeListener(ServiceTypeListener listener) throws IOException;
|
||||
|
||||
/**
|
||||
* Remove listener for service types.
|
||||
*
|
||||
* @param listener
|
||||
* listener for service types
|
||||
* @see javax.jmdns.JmDNS#removeServiceTypeListener(javax.jmdns.ServiceTypeListener)
|
||||
*/
|
||||
public abstract void removeServiceTypeListener(ServiceTypeListener listener);
|
||||
|
||||
/**
|
||||
* Listen for services of a given type. The type has to be a fully qualified type name such as <code>_http._tcp.local.</code>.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code>.
|
||||
* @param listener
|
||||
* listener for service updates
|
||||
* @see javax.jmdns.JmDNS#addServiceListener(java.lang.String, javax.jmdns.ServiceListener)
|
||||
*/
|
||||
public abstract void addServiceListener(String type, ServiceListener listener);
|
||||
|
||||
/**
|
||||
* Remove listener for services of a given type.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code>.
|
||||
* @param listener
|
||||
* listener for service updates
|
||||
* @see javax.jmdns.JmDNS#removeServiceListener(java.lang.String, javax.jmdns.ServiceListener)
|
||||
*/
|
||||
public abstract void removeServiceListener(String type, ServiceListener listener);
|
||||
|
||||
/**
|
||||
* Register a service. The service is registered for access by other jmdns clients. The name of the service may be changed to make it unique.<br>
|
||||
* <b>Note</b> the Service info is cloned for each network interface.
|
||||
*
|
||||
* @param info
|
||||
* service info to register
|
||||
* @exception IOException
|
||||
* @see javax.jmdns.JmDNS#registerService(javax.jmdns.ServiceInfo)
|
||||
*/
|
||||
public abstract void registerService(ServiceInfo info) throws IOException;
|
||||
|
||||
/**
|
||||
* Unregister a service. The service should have been registered.
|
||||
*
|
||||
* @param info
|
||||
* service info to remove
|
||||
* @see javax.jmdns.JmDNS#unregisterService(javax.jmdns.ServiceInfo)
|
||||
*/
|
||||
public abstract void unregisterService(ServiceInfo info);
|
||||
|
||||
/**
|
||||
* Unregister all services.
|
||||
*
|
||||
* @see javax.jmdns.JmDNS#unregisterAllServices()
|
||||
*/
|
||||
public abstract void unregisterAllServices();
|
||||
|
||||
/**
|
||||
* Register a service type. If this service type was not already known, all service listeners will be notified of the new service type. Service types are automatically registered as they are discovered.
|
||||
*
|
||||
* @param type
|
||||
* full qualified service type, such as <code>_http._tcp.local.</code>.
|
||||
* @see javax.jmdns.JmDNS#registerServiceType(java.lang.String)
|
||||
*/
|
||||
public abstract void registerServiceType(String type);
|
||||
|
||||
/**
|
||||
* Returns a list of service infos of the specified type.
|
||||
*
|
||||
* @param type
|
||||
* Service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @return An array of service instance.
|
||||
* @see javax.jmdns.JmDNS#list(java.lang.String)
|
||||
*/
|
||||
public abstract ServiceInfo[] list(String type);
|
||||
|
||||
/**
|
||||
* Returns a list of service infos of the specified type.
|
||||
*
|
||||
* @param type
|
||||
* Service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param timeout
|
||||
* timeout in milliseconds. Typical timeout should be 6s.
|
||||
* @return An array of service instance.
|
||||
* @see javax.jmdns.JmDNS#list(java.lang.String, long)
|
||||
*/
|
||||
public abstract ServiceInfo[] list(String type, long timeout);
|
||||
|
||||
/**
|
||||
* Returns a list of service infos of the specified type sorted by subtype. Any service that do not register a subtype is listed in the empty subtype section.
|
||||
*
|
||||
* @param type
|
||||
* Service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @return A dictionary of service info by subtypes.
|
||||
* @see javax.jmdns.JmDNS#listBySubtype(java.lang.String)
|
||||
*/
|
||||
public abstract Map<String, ServiceInfo[]> listBySubtype(String type);
|
||||
|
||||
/**
|
||||
* Returns a list of service infos of the specified type sorted by subtype. Any service that do not register a subtype is listed in the empty subtype section.
|
||||
*
|
||||
* @param type
|
||||
* Service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param timeout
|
||||
* timeout in milliseconds. Typical timeout should be 6s.
|
||||
* @return A dictionary of service info by subtypes.
|
||||
* @see javax.jmdns.JmDNS#listBySubtype(java.lang.String, long)
|
||||
*/
|
||||
public abstract Map<String, ServiceInfo[]> listBySubtype(String type, long timeout);
|
||||
|
||||
/**
|
||||
* Listen to network changes.
|
||||
*
|
||||
* @param listener
|
||||
* listener for network changes
|
||||
*/
|
||||
public abstract void addNetworkTopologyListener(NetworkTopologyListener listener);
|
||||
|
||||
/**
|
||||
* Remove listener for network changes.
|
||||
*
|
||||
* @param listener
|
||||
* listener for network changes
|
||||
*/
|
||||
public abstract void removeNetworkTopologyListener(NetworkTopologyListener listener);
|
||||
|
||||
/**
|
||||
* Returns list of network change listeners
|
||||
*
|
||||
* @return list of network change listeners
|
||||
*/
|
||||
public abstract NetworkTopologyListener[] networkListeners();
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,164 @@
|
|||
package javax.jmdns;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import javax.jmdns.impl.NetworkTopologyDiscoveryImpl;
|
||||
|
||||
/**
|
||||
* This class is used to resolve the list of Internet address to use when attaching JmDNS to the network.
|
||||
* <p>
|
||||
* To create you own filtering class for Internet Addresses you will need to implement the class and the factory delegate. These must be called before any other call to JmDNS.
|
||||
*
|
||||
* <pre>
|
||||
* public static class MyNetworkTopologyDiscovery implements NetworkTopologyDiscovery {
|
||||
*
|
||||
* @Override
|
||||
* public InetAddress[] getInetAddresses() {
|
||||
* // TODO Auto-generated method stub
|
||||
* return null;
|
||||
* }
|
||||
*
|
||||
* @Override
|
||||
* public boolean useInetAddress(NetworkInterface networkInterface, InetAddress interfaceAddress) {
|
||||
* // TODO Auto-generated method stub
|
||||
* return false;
|
||||
* }
|
||||
*
|
||||
* }
|
||||
*
|
||||
* public static class MyClass implements NetworkTopologyDiscovery.Factory.ClassDelegate {
|
||||
* public MyClass() {
|
||||
* super();
|
||||
* NetworkTopologyDiscovery.Factory.setClassDelegate(this);
|
||||
*
|
||||
* // Access JmDNS or JmmDNS
|
||||
* }
|
||||
*
|
||||
* @Override
|
||||
* public NetworkTopologyDiscovery newNetworkTopologyDiscovery() {
|
||||
* return new MyNetworkTopologyDiscovery();
|
||||
* }
|
||||
*
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* </p>
|
||||
*
|
||||
* @author Pierre Frisch
|
||||
*/
|
||||
public interface NetworkTopologyDiscovery {
|
||||
|
||||
/**
|
||||
* NetworkTopologyDiscovery.Factory enable the creation of new instance of NetworkTopologyDiscovery.
|
||||
*/
|
||||
public static final class Factory {
|
||||
private static volatile NetworkTopologyDiscovery _instance;
|
||||
|
||||
/**
|
||||
* This interface defines a delegate to the NetworkTopologyDiscovery.Factory class to enable subclassing.
|
||||
*/
|
||||
public static interface ClassDelegate {
|
||||
|
||||
/**
|
||||
* Allows the delegate the opportunity to construct and return a different NetworkTopologyDiscovery.
|
||||
*
|
||||
* @return Should return a new NetworkTopologyDiscovery Object.
|
||||
* @see #classDelegate()
|
||||
* @see #setClassDelegate(ClassDelegate anObject)
|
||||
*/
|
||||
public NetworkTopologyDiscovery newNetworkTopologyDiscovery();
|
||||
}
|
||||
|
||||
private static final AtomicReference<Factory.ClassDelegate> _databaseClassDelegate = new AtomicReference<Factory.ClassDelegate>();
|
||||
|
||||
private Factory() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns <code>delegate</code> as NetworkTopologyDiscovery's class delegate. The class delegate is optional.
|
||||
*
|
||||
* @param delegate
|
||||
* The object to set as NetworkTopologyDiscovery's class delegate.
|
||||
* @see #classDelegate()
|
||||
* @see JmmDNS.Factory.ClassDelegate
|
||||
*/
|
||||
public static void setClassDelegate(Factory.ClassDelegate delegate) {
|
||||
_databaseClassDelegate.set(delegate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns NetworkTopologyDiscovery's class delegate.
|
||||
*
|
||||
* @return NetworkTopologyDiscovery's class delegate.
|
||||
* @see #setClassDelegate(ClassDelegate anObject)
|
||||
* @see JmmDNS.Factory.ClassDelegate
|
||||
*/
|
||||
public static Factory.ClassDelegate classDelegate() {
|
||||
return _databaseClassDelegate.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new instance of NetworkTopologyDiscovery using the class delegate if it exists.
|
||||
*
|
||||
* @return new instance of NetworkTopologyDiscovery
|
||||
*/
|
||||
protected static NetworkTopologyDiscovery newNetworkTopologyDiscovery() {
|
||||
NetworkTopologyDiscovery instance = null;
|
||||
Factory.ClassDelegate delegate = _databaseClassDelegate.get();
|
||||
if (delegate != null) {
|
||||
instance = delegate.newNetworkTopologyDiscovery();
|
||||
}
|
||||
return (instance != null ? instance : new NetworkTopologyDiscoveryImpl());
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the instance of the Multihomed Multicast DNS.
|
||||
*
|
||||
* @return the JmmDNS
|
||||
*/
|
||||
public static NetworkTopologyDiscovery getInstance() {
|
||||
if (_instance == null) {
|
||||
synchronized (NetworkTopologyDiscovery.Factory.class) {
|
||||
if (_instance == null) {
|
||||
_instance = NetworkTopologyDiscovery.Factory.newNetworkTopologyDiscovery();
|
||||
}
|
||||
}
|
||||
}
|
||||
return _instance;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all local Internet Addresses for the machine.
|
||||
*
|
||||
* @return Set of InetAddress
|
||||
*/
|
||||
public abstract InetAddress[] getInetAddresses();
|
||||
|
||||
/**
|
||||
* Check if a given InetAddress should be used for mDNS
|
||||
*
|
||||
* @param networkInterface
|
||||
* @param interfaceAddress
|
||||
* @return <code>true</code> is the address is to be used, <code>false</code> otherwise.
|
||||
*/
|
||||
public boolean useInetAddress(NetworkInterface networkInterface, InetAddress interfaceAddress);
|
||||
|
||||
/**
|
||||
* Locks the given InetAddress if the device requires it.
|
||||
*
|
||||
* @param interfaceAddress
|
||||
*/
|
||||
public void lockInetAddress(InetAddress interfaceAddress);
|
||||
|
||||
/**
|
||||
* Locks the given InetAddress if the device requires it.
|
||||
*
|
||||
* @param interfaceAddress
|
||||
*/
|
||||
public void unlockInetAddress(InetAddress interfaceAddress);
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.EventObject;
|
||||
|
||||
/**
|
||||
* @author Cédrik Lime, Pierre Frisch
|
||||
*/
|
||||
public abstract class NetworkTopologyEvent extends EventObject {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = -8630033521752540987L;
|
||||
|
||||
/**
|
||||
* Constructs a Service Event.
|
||||
*
|
||||
* @param eventSource
|
||||
* The DNS on which the Event initially occurred.
|
||||
* @exception IllegalArgumentException
|
||||
* if source is null.
|
||||
*/
|
||||
protected NetworkTopologyEvent(final Object eventSource) {
|
||||
super(eventSource);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the JmDNS instance associated with the event or null if it is a generic event.
|
||||
*
|
||||
* @return JmDNS instance
|
||||
*/
|
||||
public abstract JmDNS getDNS();
|
||||
|
||||
/**
|
||||
* The Internet address affected by this event.
|
||||
*
|
||||
* @return InetAddress
|
||||
*/
|
||||
public abstract InetAddress getInetAddress();
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns;
|
||||
|
||||
import java.util.EventListener;
|
||||
|
||||
/**
|
||||
* Listener for network topology updates.
|
||||
*
|
||||
* @author Cédrik Lime, Pierre Frisch
|
||||
*/
|
||||
public interface NetworkTopologyListener extends EventListener {
|
||||
/**
|
||||
* A network address has been added.<br/>
|
||||
*
|
||||
* @param event
|
||||
* The NetworkTopologyEvent providing the name and fully qualified type of the service.
|
||||
*/
|
||||
void inetAddressAdded(NetworkTopologyEvent event);
|
||||
|
||||
/**
|
||||
* A network address has been removed.
|
||||
*
|
||||
* @param event
|
||||
* The NetworkTopologyEvent providing the name and fully qualified type of the service.
|
||||
*/
|
||||
void inetAddressRemoved(NetworkTopologyEvent event);
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns;
|
||||
|
||||
import java.util.EventObject;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public abstract class ServiceEvent extends EventObject implements Cloneable {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = -8558445644541006271L;
|
||||
|
||||
/**
|
||||
* Constructs a Service Event.
|
||||
*
|
||||
* @param eventSource
|
||||
* The object on which the Event initially occurred.
|
||||
* @exception IllegalArgumentException
|
||||
* if source is null.
|
||||
*/
|
||||
public ServiceEvent(final Object eventSource) {
|
||||
super(eventSource);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the JmDNS instance which originated the event.
|
||||
*
|
||||
* @return JmDNS instance
|
||||
*/
|
||||
public abstract JmDNS getDNS();
|
||||
|
||||
/**
|
||||
* Returns the fully qualified type of the service.
|
||||
*
|
||||
* @return type of the service.
|
||||
*/
|
||||
public abstract String getType();
|
||||
|
||||
/**
|
||||
* Returns the instance name of the service. Always returns null, if the event is sent to a service type listener.
|
||||
*
|
||||
* @return name of the service
|
||||
*/
|
||||
public abstract String getName();
|
||||
|
||||
/**
|
||||
* Returns the service info record, or null if the service could not be resolved. Always returns null, if the event is sent to a service type listener.
|
||||
*
|
||||
* @return service info record
|
||||
* @see javax.jmdns.ServiceEvent#getInfo()
|
||||
*/
|
||||
public abstract ServiceInfo getInfo();
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#clone()
|
||||
*/
|
||||
@Override
|
||||
public ServiceEvent clone() {
|
||||
try {
|
||||
return (ServiceEvent) super.clone();
|
||||
} catch (CloneNotSupportedException exception) {
|
||||
// clone is supported
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,727 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
package javax.jmdns;
|
||||
|
||||
import java.net.Inet4Address;
|
||||
import java.net.Inet6Address;
|
||||
import java.net.InetAddress;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.jmdns.impl.ServiceInfoImpl;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* The fully qualified service name is build using up to 5 components with the following structure:
|
||||
*
|
||||
* <pre>
|
||||
* <app>.<protocol>.<servicedomain>.<parentdomain>.<br/>
|
||||
* <Instance>.<app>.<protocol>.<servicedomain>.<parentdomain>.<br/>
|
||||
* <sub>._sub.<app>.<protocol>.<servicedomain>.<parentdomain>.
|
||||
* </pre>
|
||||
*
|
||||
* <ol>
|
||||
* <li><servicedomain>.<parentdomain>: This is the domain scope of the service typically "local.", but this can also be something similar to "in-addr.arpa." or "ip6.arpa."</li>
|
||||
* <li><protocol>: This is either "_tcp" or "_udp"</li>
|
||||
* <li><app>: This define the application protocol. Typical example are "_http", "_ftp", etc.</li>
|
||||
* <li><Instance>: This is the service name</li>
|
||||
* <li><sub>: This is the subtype for the application protocol</li>
|
||||
* </ol>
|
||||
* </p>
|
||||
*/
|
||||
public abstract class ServiceInfo implements Cloneable {
|
||||
|
||||
/**
|
||||
* This is the no value text byte. According top the specification it is one byte with 0 value.
|
||||
*/
|
||||
public static final byte[] NO_VALUE = new byte[0];
|
||||
|
||||
/**
|
||||
* Fields for the fully qualified map.
|
||||
*/
|
||||
public enum Fields {
|
||||
/**
|
||||
* Domain Field.
|
||||
*/
|
||||
Domain,
|
||||
/**
|
||||
* Protocol Field.
|
||||
*/
|
||||
Protocol,
|
||||
/**
|
||||
* Application Field.
|
||||
*/
|
||||
Application,
|
||||
/**
|
||||
* Instance Field.
|
||||
*/
|
||||
Instance,
|
||||
/**
|
||||
* Subtype Field.
|
||||
*/
|
||||
Subtype
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a service description for registering with JmDNS.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param name
|
||||
* unqualified service instance name, such as <code>foobar</code>
|
||||
* @param port
|
||||
* the local port on which the service runs
|
||||
* @param text
|
||||
* string describing the service
|
||||
* @return new service info
|
||||
*/
|
||||
public static ServiceInfo create(final String type, final String name, final int port, final String text) {
|
||||
return new ServiceInfoImpl(type, name, "", port, 0, 0, false, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a service description for registering with JmDNS.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param name
|
||||
* unqualified service instance name, such as <code>foobar</code>
|
||||
* @param subtype
|
||||
* service subtype see draft-cheshire-dnsext-dns-sd-06.txt chapter 7.1 Selective Instance Enumeration
|
||||
* @param port
|
||||
* the local port on which the service runs
|
||||
* @param text
|
||||
* string describing the service
|
||||
* @return new service info
|
||||
*/
|
||||
public static ServiceInfo create(final String type, final String name, final String subtype, final int port, final String text) {
|
||||
return new ServiceInfoImpl(type, name, subtype, port, 0, 0, false, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a service description for registering with JmDNS.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param name
|
||||
* unqualified service instance name, such as <code>foobar</code>
|
||||
* @param port
|
||||
* the local port on which the service runs
|
||||
* @param weight
|
||||
* weight of the service
|
||||
* @param priority
|
||||
* priority of the service
|
||||
* @param text
|
||||
* string describing the service
|
||||
* @return new service info
|
||||
*/
|
||||
public static ServiceInfo create(final String type, final String name, final int port, final int weight, final int priority, final String text) {
|
||||
return new ServiceInfoImpl(type, name, "", port, weight, priority, false, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a service description for registering with JmDNS.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param name
|
||||
* unqualified service instance name, such as <code>foobar</code>
|
||||
* @param subtype
|
||||
* service subtype see draft-cheshire-dnsext-dns-sd-06.txt chapter 7.1 Selective Instance Enumeration
|
||||
* @param port
|
||||
* the local port on which the service runs
|
||||
* @param weight
|
||||
* weight of the service
|
||||
* @param priority
|
||||
* priority of the service
|
||||
* @param text
|
||||
* string describing the service
|
||||
* @return new service info
|
||||
*/
|
||||
public static ServiceInfo create(final String type, final String name, final String subtype, final int port, final int weight, final int priority, final String text) {
|
||||
return new ServiceInfoImpl(type, name, subtype, port, weight, priority, false, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a service description for registering with JmDNS. The properties hashtable must map property names to either Strings or byte arrays describing the property values.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param name
|
||||
* unqualified service instance name, such as <code>foobar</code>
|
||||
* @param port
|
||||
* the local port on which the service runs
|
||||
* @param weight
|
||||
* weight of the service
|
||||
* @param priority
|
||||
* priority of the service
|
||||
* @param props
|
||||
* properties describing the service
|
||||
* @return new service info
|
||||
*/
|
||||
public static ServiceInfo create(final String type, final String name, final int port, final int weight, final int priority, final Map<String, ?> props) {
|
||||
return new ServiceInfoImpl(type, name, "", port, weight, priority, false, props);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a service description for registering with JmDNS. The properties hashtable must map property names to either Strings or byte arrays describing the property values.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param name
|
||||
* unqualified service instance name, such as <code>foobar</code>
|
||||
* @param subtype
|
||||
* service subtype see draft-cheshire-dnsext-dns-sd-06.txt chapter 7.1 Selective Instance Enumeration
|
||||
* @param port
|
||||
* the local port on which the service runs
|
||||
* @param weight
|
||||
* weight of the service
|
||||
* @param priority
|
||||
* priority of the service
|
||||
* @param props
|
||||
* properties describing the service
|
||||
* @return new service info
|
||||
*/
|
||||
public static ServiceInfo create(final String type, final String name, final String subtype, final int port, final int weight, final int priority, final Map<String, ?> props) {
|
||||
return new ServiceInfoImpl(type, name, subtype, port, weight, priority, false, props);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a service description for registering with JmDNS.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param name
|
||||
* unqualified service instance name, such as <code>foobar</code>
|
||||
* @param port
|
||||
* the local port on which the service runs
|
||||
* @param weight
|
||||
* weight of the service
|
||||
* @param priority
|
||||
* priority of the service
|
||||
* @param text
|
||||
* bytes describing the service
|
||||
* @return new service info
|
||||
*/
|
||||
public static ServiceInfo create(final String type, final String name, final int port, final int weight, final int priority, final byte[] text) {
|
||||
return new ServiceInfoImpl(type, name, "", port, weight, priority, false, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a service description for registering with JmDNS.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param name
|
||||
* unqualified service instance name, such as <code>foobar</code>
|
||||
* @param subtype
|
||||
* service subtype see draft-cheshire-dnsext-dns-sd-06.txt chapter 7.1 Selective Instance Enumeration
|
||||
* @param port
|
||||
* the local port on which the service runs
|
||||
* @param weight
|
||||
* weight of the service
|
||||
* @param priority
|
||||
* priority of the service
|
||||
* @param text
|
||||
* bytes describing the service
|
||||
* @return new service info
|
||||
*/
|
||||
public static ServiceInfo create(final String type, final String name, final String subtype, final int port, final int weight, final int priority, final byte[] text) {
|
||||
return new ServiceInfoImpl(type, name, subtype, port, weight, priority, false, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a service description for registering with JmDNS.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param name
|
||||
* unqualified service instance name, such as <code>foobar</code>
|
||||
* @param port
|
||||
* the local port on which the service runs
|
||||
* @param weight
|
||||
* weight of the service
|
||||
* @param priority
|
||||
* priority of the service
|
||||
* @param persistent
|
||||
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
|
||||
* @param text
|
||||
* string describing the service
|
||||
* @return new service info
|
||||
*/
|
||||
public static ServiceInfo create(final String type, final String name, final int port, final int weight, final int priority, final boolean persistent, final String text) {
|
||||
return new ServiceInfoImpl(type, name, "", port, weight, priority, persistent, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a service description for registering with JmDNS.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param name
|
||||
* unqualified service instance name, such as <code>foobar</code>
|
||||
* @param subtype
|
||||
* service subtype see draft-cheshire-dnsext-dns-sd-06.txt chapter 7.1 Selective Instance Enumeration
|
||||
* @param port
|
||||
* the local port on which the service runs
|
||||
* @param weight
|
||||
* weight of the service
|
||||
* @param priority
|
||||
* priority of the service
|
||||
* @param persistent
|
||||
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
|
||||
* @param text
|
||||
* string describing the service
|
||||
* @return new service info
|
||||
*/
|
||||
public static ServiceInfo create(final String type, final String name, final String subtype, final int port, final int weight, final int priority, final boolean persistent, final String text) {
|
||||
return new ServiceInfoImpl(type, name, subtype, port, weight, priority, persistent, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a service description for registering with JmDNS. The properties hashtable must map property names to either Strings or byte arrays describing the property values.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param name
|
||||
* unqualified service instance name, such as <code>foobar</code>
|
||||
* @param port
|
||||
* the local port on which the service runs
|
||||
* @param weight
|
||||
* weight of the service
|
||||
* @param priority
|
||||
* priority of the service
|
||||
* @param persistent
|
||||
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
|
||||
* @param props
|
||||
* properties describing the service
|
||||
* @return new service info
|
||||
*/
|
||||
public static ServiceInfo create(final String type, final String name, final int port, final int weight, final int priority, final boolean persistent, final Map<String, ?> props) {
|
||||
return new ServiceInfoImpl(type, name, "", port, weight, priority, persistent, props);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a service description for registering with JmDNS. The properties hashtable must map property names to either Strings or byte arrays describing the property values.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param name
|
||||
* unqualified service instance name, such as <code>foobar</code>
|
||||
* @param subtype
|
||||
* service subtype see draft-cheshire-dnsext-dns-sd-06.txt chapter 7.1 Selective Instance Enumeration
|
||||
* @param port
|
||||
* the local port on which the service runs
|
||||
* @param weight
|
||||
* weight of the service
|
||||
* @param priority
|
||||
* priority of the service
|
||||
* @param persistent
|
||||
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
|
||||
* @param props
|
||||
* properties describing the service
|
||||
* @return new service info
|
||||
*/
|
||||
public static ServiceInfo create(final String type, final String name, final String subtype, final int port, final int weight, final int priority, final boolean persistent, final Map<String, ?> props) {
|
||||
return new ServiceInfoImpl(type, name, subtype, port, weight, priority, persistent, props);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a service description for registering with JmDNS.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param name
|
||||
* unqualified service instance name, such as <code>foobar</code>
|
||||
* @param port
|
||||
* the local port on which the service runs
|
||||
* @param weight
|
||||
* weight of the service
|
||||
* @param priority
|
||||
* priority of the service
|
||||
* @param persistent
|
||||
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
|
||||
* @param text
|
||||
* bytes describing the service
|
||||
* @return new service info
|
||||
*/
|
||||
public static ServiceInfo create(final String type, final String name, final int port, final int weight, final int priority, final boolean persistent, final byte[] text) {
|
||||
return new ServiceInfoImpl(type, name, "", port, weight, priority, persistent, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a service description for registering with JmDNS.
|
||||
*
|
||||
* @param type
|
||||
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
|
||||
* @param name
|
||||
* unqualified service instance name, such as <code>foobar</code>
|
||||
* @param subtype
|
||||
* service subtype see draft-cheshire-dnsext-dns-sd-06.txt chapter 7.1 Selective Instance Enumeration
|
||||
* @param port
|
||||
* the local port on which the service runs
|
||||
* @param weight
|
||||
* weight of the service
|
||||
* @param priority
|
||||
* priority of the service
|
||||
* @param persistent
|
||||
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
|
||||
* @param text
|
||||
* bytes describing the service
|
||||
* @return new service info
|
||||
*/
|
||||
public static ServiceInfo create(final String type, final String name, final String subtype, final int port, final int weight, final int priority, final boolean persistent, final byte[] text) {
|
||||
return new ServiceInfoImpl(type, name, subtype, port, weight, priority, persistent, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a service description for registering with JmDNS. The properties hashtable must map property names to either Strings or byte arrays describing the property values.
|
||||
*
|
||||
* @param qualifiedNameMap
|
||||
* dictionary of values to build the fully qualified service name. Mandatory keys are Application and Instance. The Domain default is local, the Protocol default is tcp and the subtype default is none.
|
||||
* @param port
|
||||
* the local port on which the service runs
|
||||
* @param weight
|
||||
* weight of the service
|
||||
* @param priority
|
||||
* priority of the service
|
||||
* @param persistent
|
||||
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
|
||||
* @param props
|
||||
* properties describing the service
|
||||
* @return new service info
|
||||
*/
|
||||
public static ServiceInfo create(final Map<Fields, String> qualifiedNameMap, final int port, final int weight, final int priority, final boolean persistent, final Map<String, ?> props) {
|
||||
return new ServiceInfoImpl(qualifiedNameMap, port, weight, priority, persistent, props);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the service info is filled with data.
|
||||
*
|
||||
* @return <code>true</code> if the service info has data, <code>false</code> otherwise.
|
||||
*/
|
||||
public abstract boolean hasData();
|
||||
|
||||
/**
|
||||
* Fully qualified service type name, such as <code>_http._tcp.local.</code>
|
||||
*
|
||||
* @return service type name
|
||||
*/
|
||||
public abstract String getType();
|
||||
|
||||
/**
|
||||
* Fully qualified service type name with the subtype if appropriate, such as <code>_printer._sub._http._tcp.local.</code>
|
||||
*
|
||||
* @return service type name
|
||||
*/
|
||||
public abstract String getTypeWithSubtype();
|
||||
|
||||
/**
|
||||
* Unqualified service instance name, such as <code>foobar</code> .
|
||||
*
|
||||
* @return service name
|
||||
*/
|
||||
public abstract String getName();
|
||||
|
||||
/**
|
||||
* The key is used to retrieve service info in hash tables.<br/>
|
||||
* The key is the lower case qualified name.
|
||||
*
|
||||
* @return the key
|
||||
*/
|
||||
public abstract String getKey();
|
||||
|
||||
/**
|
||||
* Fully qualified service name, such as <code>foobar._http._tcp.local.</code> .
|
||||
*
|
||||
* @return qualified service name
|
||||
*/
|
||||
public abstract String getQualifiedName();
|
||||
|
||||
/**
|
||||
* Get the name of the server.
|
||||
*
|
||||
* @return server name
|
||||
*/
|
||||
public abstract String getServer();
|
||||
|
||||
/**
|
||||
* Returns the host IP address string in textual presentation.<br/>
|
||||
* <b>Note:</b> This can be either an IPv4 or an IPv6 representation.
|
||||
*
|
||||
* @return the host raw IP address in a string format.
|
||||
* @deprecated since 3.2.3
|
||||
* @see #getHostAddresses()
|
||||
*/
|
||||
@Deprecated
|
||||
public abstract String getHostAddress();
|
||||
|
||||
/**
|
||||
* Returns the host IP addresses string in textual presentation.
|
||||
*
|
||||
* @return list of host raw IP address in a string format.
|
||||
*/
|
||||
public abstract String[] getHostAddresses();
|
||||
|
||||
/**
|
||||
* Get the host address of the service.<br/>
|
||||
*
|
||||
* @return host Internet address
|
||||
* @deprecated since 3.1.8
|
||||
* @see #getInetAddresses()
|
||||
*/
|
||||
@Deprecated
|
||||
public abstract InetAddress getAddress();
|
||||
|
||||
/**
|
||||
* Get the InetAddress of the service. This will return the IPv4 if it exist, otherwise it return the IPv6 if set.<br/>
|
||||
* <b>Note:</b> This return null if the service IP address cannot be resolved.
|
||||
*
|
||||
* @return Internet address
|
||||
* @deprecated since 3.2.3
|
||||
* @see #getInetAddresses()
|
||||
*/
|
||||
@Deprecated
|
||||
public abstract InetAddress getInetAddress();
|
||||
|
||||
/**
|
||||
* Get the IPv4 InetAddress of the service.<br/>
|
||||
* <b>Note:</b> This return null if the service IPv4 address cannot be resolved.
|
||||
*
|
||||
* @return Internet address
|
||||
* @deprecated since 3.2.3
|
||||
* @see #getInet4Addresses()
|
||||
*/
|
||||
@Deprecated
|
||||
public abstract Inet4Address getInet4Address();
|
||||
|
||||
/**
|
||||
* Get the IPv6 InetAddress of the service.<br/>
|
||||
* <b>Note:</b> This return null if the service IPv6 address cannot be resolved.
|
||||
*
|
||||
* @return Internet address
|
||||
* @deprecated since 3.2.3
|
||||
* @see #getInet6Addresses()
|
||||
*/
|
||||
@Deprecated
|
||||
public abstract Inet6Address getInet6Address();
|
||||
|
||||
/**
|
||||
* Returns a list of all InetAddresses that can be used for this service.
|
||||
* <p>
|
||||
* In a multi-homed environment service info can be associated with more than one address.
|
||||
* </p>
|
||||
*
|
||||
* @return list of InetAddress objects
|
||||
*/
|
||||
public abstract InetAddress[] getInetAddresses();
|
||||
|
||||
/**
|
||||
* Returns a list of all IPv4 InetAddresses that can be used for this service.
|
||||
* <p>
|
||||
* In a multi-homed environment service info can be associated with more than one address.
|
||||
* </p>
|
||||
*
|
||||
* @return list of InetAddress objects
|
||||
*/
|
||||
public abstract Inet4Address[] getInet4Addresses();
|
||||
|
||||
/**
|
||||
* Returns a list of all IPv6 InetAddresses that can be used for this service.
|
||||
* <p>
|
||||
* In a multi-homed environment service info can be associated with more than one address.
|
||||
* </p>
|
||||
*
|
||||
* @return list of InetAddress objects
|
||||
*/
|
||||
public abstract Inet6Address[] getInet6Addresses();
|
||||
|
||||
/**
|
||||
* Get the port for the service.
|
||||
*
|
||||
* @return service port
|
||||
*/
|
||||
public abstract int getPort();
|
||||
|
||||
/**
|
||||
* Get the priority of the service.
|
||||
*
|
||||
* @return service priority
|
||||
*/
|
||||
public abstract int getPriority();
|
||||
|
||||
/**
|
||||
* Get the weight of the service.
|
||||
*
|
||||
* @return service weight
|
||||
*/
|
||||
public abstract int getWeight();
|
||||
|
||||
/**
|
||||
* Get the text for the service as raw bytes.
|
||||
*
|
||||
* @return raw service text
|
||||
*/
|
||||
public abstract byte[] getTextBytes();
|
||||
|
||||
/**
|
||||
* Get the text for the service. This will interpret the text bytes as a UTF8 encoded string. Will return null if the bytes are not a valid UTF8 encoded string.<br/>
|
||||
* <b>Note:</b> Do not use. This method make the assumption that the TXT record is one string. This is false. The TXT record is a series of key value pairs.
|
||||
*
|
||||
* @return service text
|
||||
* @see #getPropertyNames()
|
||||
* @see #getPropertyBytes(String)
|
||||
* @see #getPropertyString(String)
|
||||
* @deprecated since 3.1.7
|
||||
*/
|
||||
@Deprecated
|
||||
public abstract String getTextString();
|
||||
|
||||
/**
|
||||
* Get the URL for this service. An http URL is created by combining the address, port, and path properties.
|
||||
*
|
||||
* @return service URL
|
||||
* @deprecated since 3.2.3
|
||||
* @see #getURLs()
|
||||
*/
|
||||
@Deprecated
|
||||
public abstract String getURL();
|
||||
|
||||
/**
|
||||
* Get the list of URL for this service. An http URL is created by combining the address, port, and path properties.
|
||||
*
|
||||
* @return list of service URL
|
||||
*/
|
||||
public abstract String[] getURLs();
|
||||
|
||||
/**
|
||||
* Get the URL for this service. An URL is created by combining the protocol, address, port, and path properties.
|
||||
*
|
||||
* @param protocol
|
||||
* requested protocol
|
||||
* @return service URL
|
||||
* @deprecated since 3.2.3
|
||||
* @see #getURLs()
|
||||
*/
|
||||
@Deprecated
|
||||
public abstract String getURL(String protocol);
|
||||
|
||||
/**
|
||||
* Get the list of URL for this service. An URL is created by combining the protocol, address, port, and path properties.
|
||||
*
|
||||
* @param protocol
|
||||
* requested protocol
|
||||
* @return list of service URL
|
||||
*/
|
||||
public abstract String[] getURLs(String protocol);
|
||||
|
||||
/**
|
||||
* Get a property of the service. This involves decoding the text bytes into a property list. Returns null if the property is not found or the text data could not be decoded correctly.
|
||||
*
|
||||
* @param name
|
||||
* property name
|
||||
* @return raw property text
|
||||
*/
|
||||
public abstract byte[] getPropertyBytes(final String name);
|
||||
|
||||
/**
|
||||
* Get a property of the service. This involves decoding the text bytes into a property list. Returns null if the property is not found, the text data could not be decoded correctly, or the resulting bytes are not a valid UTF8 string.
|
||||
*
|
||||
* @param name
|
||||
* property name
|
||||
* @return property text
|
||||
*/
|
||||
public abstract String getPropertyString(final String name);
|
||||
|
||||
/**
|
||||
* Enumeration of the property names.
|
||||
*
|
||||
* @return property name enumeration
|
||||
*/
|
||||
public abstract Enumeration<String> getPropertyNames();
|
||||
|
||||
/**
|
||||
* Returns a description of the service info suitable for printing.
|
||||
*
|
||||
* @return service info description
|
||||
*/
|
||||
public abstract String getNiceTextString();
|
||||
|
||||
/**
|
||||
* Set the text for the service. Setting the text will fore a re-announce of the service.
|
||||
*
|
||||
* @param text
|
||||
* the raw byte representation of the text field.
|
||||
* @exception IllegalStateException
|
||||
* if attempting to set the text for a non persistent service info.
|
||||
*/
|
||||
public abstract void setText(final byte[] text) throws IllegalStateException;
|
||||
|
||||
/**
|
||||
* Set the text for the service. Setting the text will fore a re-announce of the service.
|
||||
*
|
||||
* @param props
|
||||
* a key=value map that will be encoded into raw bytes.
|
||||
* @exception IllegalStateException
|
||||
* if attempting to set the text for a non persistent service info.
|
||||
*/
|
||||
public abstract void setText(final Map<String, ?> props) throws IllegalStateException;
|
||||
|
||||
/**
|
||||
* Returns <code>true</code> if ServiceListener.resolveService will be called whenever new new information is received.
|
||||
*
|
||||
* @return the persistent
|
||||
*/
|
||||
public abstract boolean isPersistent();
|
||||
|
||||
/**
|
||||
* Returns the domain of the service info suitable for printing.
|
||||
*
|
||||
* @return service domain
|
||||
*/
|
||||
public abstract String getDomain();
|
||||
|
||||
/**
|
||||
* Returns the protocol of the service info suitable for printing.
|
||||
*
|
||||
* @return service protocol
|
||||
*/
|
||||
public abstract String getProtocol();
|
||||
|
||||
/**
|
||||
* Returns the application of the service info suitable for printing.
|
||||
*
|
||||
* @return service application
|
||||
*/
|
||||
public abstract String getApplication();
|
||||
|
||||
/**
|
||||
* Returns the sub type of the service info suitable for printing.
|
||||
*
|
||||
* @return service sub type
|
||||
*/
|
||||
public abstract String getSubtype();
|
||||
|
||||
/**
|
||||
* Returns a dictionary of the fully qualified name component of this service.
|
||||
*
|
||||
* @return dictionary of the fully qualified name components
|
||||
*/
|
||||
public abstract Map<Fields, String> getQualifiedNameMap();
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#clone()
|
||||
*/
|
||||
@Override
|
||||
public ServiceInfo clone() {
|
||||
try {
|
||||
return (ServiceInfo) super.clone();
|
||||
} catch (CloneNotSupportedException exception) {
|
||||
// clone is supported
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns;
|
||||
|
||||
import java.util.EventListener;
|
||||
|
||||
/**
|
||||
* Listener for service updates.
|
||||
*
|
||||
* @author Arthur van Hoff, Werner Randelshofer, Pierre Frisch
|
||||
*/
|
||||
public interface ServiceListener extends EventListener {
|
||||
/**
|
||||
* A service has been added.<br/>
|
||||
* <b>Note:</b>This event is only the service added event. The service info associated with this event does not include resolution information.<br/>
|
||||
* To get the full resolved information you need to listen to {@link #serviceResolved(ServiceEvent)} or call {@link JmDNS#getServiceInfo(String, String, long)}
|
||||
*
|
||||
* <pre>
|
||||
* ServiceInfo info = event.getDNS().getServiceInfo(event.getType(), event.getName())
|
||||
* </pre>
|
||||
* <p>
|
||||
* Please note that service resolution may take a few second to resolve.
|
||||
* </p>
|
||||
*
|
||||
* @param event
|
||||
* The ServiceEvent providing the name and fully qualified type of the service.
|
||||
*/
|
||||
void serviceAdded(ServiceEvent event);
|
||||
|
||||
/**
|
||||
* A service has been removed.
|
||||
*
|
||||
* @param event
|
||||
* The ServiceEvent providing the name and fully qualified type of the service.
|
||||
*/
|
||||
void serviceRemoved(ServiceEvent event);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
void serviceResolved(ServiceEvent event);
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns;
|
||||
|
||||
import java.util.EventListener;
|
||||
|
||||
/**
|
||||
* Listener for service types.
|
||||
*
|
||||
* @author Arthur van Hoff, Werner Randelshofer
|
||||
*/
|
||||
public interface ServiceTypeListener extends EventListener {
|
||||
/**
|
||||
* A new service type was discovered.
|
||||
*
|
||||
* @param event
|
||||
* The service event providing the fully qualified type of the service.
|
||||
*/
|
||||
void serviceTypeAdded(ServiceEvent event);
|
||||
|
||||
/**
|
||||
* A new subtype for the service type was discovered.
|
||||
*
|
||||
* <pre>
|
||||
* <sub>._sub.<app>.<protocol>.<servicedomain>.<parentdomain>.
|
||||
* </pre>
|
||||
*
|
||||
* @param event
|
||||
* The service event providing the fully qualified type of the service with subtype.
|
||||
* @since 3.2.0
|
||||
*/
|
||||
void subTypeForServiceTypeAdded(ServiceEvent event);
|
||||
}
|
||||
|
|
@ -0,0 +1,293 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import javax.jmdns.impl.constants.DNSRecordClass;
|
||||
import javax.jmdns.impl.constants.DNSRecordType;
|
||||
|
||||
/**
|
||||
* A table of DNS entries. This is a map table which can handle multiple entries with the same name.
|
||||
* <p/>
|
||||
* Storing multiple entries with the same name is implemented using a linked list. This is hidden from the user and can change in later implementation.
|
||||
* <p/>
|
||||
* Here's how to iterate over all entries:
|
||||
*
|
||||
* <pre>
|
||||
* for (Iterator i=dnscache.allValues().iterator(); i.hasNext(); ) {
|
||||
* DNSEntry entry = i.next();
|
||||
* ...do something with entry...
|
||||
* }
|
||||
* </pre>
|
||||
* <p/>
|
||||
* And here's how to iterate over all entries having a given name:
|
||||
*
|
||||
* <pre>
|
||||
* for (Iterator i=dnscache.getDNSEntryList(name).iterator(); i.hasNext(); ) {
|
||||
* DNSEntry entry = i.next();
|
||||
* ...do something with entry...
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @author Arthur van Hoff, Werner Randelshofer, Rick Blair, Pierre Frisch
|
||||
*/
|
||||
public class DNSCache extends ConcurrentHashMap<String, List<DNSEntry>> {
|
||||
|
||||
// private static Logger logger = Logger.getLogger(DNSCache.class.getName());
|
||||
|
||||
private static final long serialVersionUID = 3024739453186759259L;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public DNSCache() {
|
||||
this(1024);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param map
|
||||
*/
|
||||
public DNSCache(DNSCache map) {
|
||||
this(map != null ? map.size() : 1024);
|
||||
if (map != null) {
|
||||
this.putAll(map);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a table with a given initial size.
|
||||
*
|
||||
* @param initialCapacity
|
||||
*/
|
||||
public DNSCache(int initialCapacity) {
|
||||
super(initialCapacity);
|
||||
}
|
||||
|
||||
// ====================================================================
|
||||
// Map
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
return new DNSCache(this);
|
||||
}
|
||||
|
||||
// ====================================================================
|
||||
|
||||
/**
|
||||
* Returns all entries in the cache
|
||||
*
|
||||
* @return all entries in the cache
|
||||
*/
|
||||
public Collection<DNSEntry> allValues() {
|
||||
List<DNSEntry> allValues = new ArrayList<DNSEntry>();
|
||||
for (List<? extends DNSEntry> entry : this.values()) {
|
||||
if (entry != null) {
|
||||
allValues.addAll(entry);
|
||||
}
|
||||
}
|
||||
return allValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate only over items with matching name. Returns an list of DNSEntry or null. To retrieve all entries, one must iterate over this linked list.
|
||||
*
|
||||
* @param name
|
||||
* @return list of DNSEntries
|
||||
*/
|
||||
public Collection<? extends DNSEntry> getDNSEntryList(String name) {
|
||||
Collection<? extends DNSEntry> entryList = this._getDNSEntryList(name);
|
||||
if (entryList != null) {
|
||||
synchronized (entryList) {
|
||||
entryList = new ArrayList<DNSEntry>(entryList);
|
||||
}
|
||||
} else {
|
||||
entryList = Collections.emptyList();
|
||||
}
|
||||
return entryList;
|
||||
}
|
||||
|
||||
private Collection<? extends DNSEntry> _getDNSEntryList(String name) {
|
||||
return this.get(name != null ? name.toLowerCase() : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a matching DNS entry from the table (using isSameEntry). Returns the entry that was found.
|
||||
*
|
||||
* @param dnsEntry
|
||||
* @return DNSEntry
|
||||
*/
|
||||
public DNSEntry getDNSEntry(DNSEntry dnsEntry) {
|
||||
DNSEntry result = null;
|
||||
if (dnsEntry != null) {
|
||||
Collection<? extends DNSEntry> entryList = this._getDNSEntryList(dnsEntry.getKey());
|
||||
if (entryList != null) {
|
||||
synchronized (entryList) {
|
||||
for (DNSEntry testDNSEntry : entryList) {
|
||||
if (testDNSEntry.isSameEntry(dnsEntry)) {
|
||||
result = testDNSEntry;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a matching DNS entry from the table.
|
||||
*
|
||||
* @param name
|
||||
* @param type
|
||||
* @param recordClass
|
||||
* @return DNSEntry
|
||||
*/
|
||||
public DNSEntry getDNSEntry(String name, DNSRecordType type, DNSRecordClass recordClass) {
|
||||
DNSEntry result = null;
|
||||
Collection<? extends DNSEntry> entryList = this._getDNSEntryList(name);
|
||||
if (entryList != null) {
|
||||
synchronized (entryList) {
|
||||
for (DNSEntry testDNSEntry : entryList) {
|
||||
if (testDNSEntry.matchRecordType(type) && testDNSEntry.matchRecordClass(recordClass)) {
|
||||
result = testDNSEntry;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all matching DNS entries from the table.
|
||||
*
|
||||
* @param name
|
||||
* @param type
|
||||
* @param recordClass
|
||||
* @return list of entries
|
||||
*/
|
||||
public Collection<? extends DNSEntry> getDNSEntryList(String name, DNSRecordType type, DNSRecordClass recordClass) {
|
||||
Collection<? extends DNSEntry> entryList = this._getDNSEntryList(name);
|
||||
if (entryList != null) {
|
||||
synchronized (entryList) {
|
||||
entryList = new ArrayList<DNSEntry>(entryList);
|
||||
for (Iterator<? extends DNSEntry> i = entryList.iterator(); i.hasNext();) {
|
||||
DNSEntry testDNSEntry = i.next();
|
||||
if (!testDNSEntry.matchRecordType(type) || (!testDNSEntry.matchRecordClass(recordClass))) {
|
||||
i.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
entryList = Collections.emptyList();
|
||||
}
|
||||
return entryList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an entry to the table.
|
||||
*
|
||||
* @param dnsEntry
|
||||
* @return true if the entry was added
|
||||
*/
|
||||
public boolean addDNSEntry(final DNSEntry dnsEntry) {
|
||||
boolean result = false;
|
||||
if (dnsEntry != null) {
|
||||
List<DNSEntry> entryList = this.get(dnsEntry.getKey());
|
||||
if (entryList == null) {
|
||||
this.putIfAbsent(dnsEntry.getKey(), new ArrayList<DNSEntry>());
|
||||
entryList = this.get(dnsEntry.getKey());
|
||||
}
|
||||
synchronized (entryList) {
|
||||
entryList.add(dnsEntry);
|
||||
}
|
||||
// This is probably not very informative
|
||||
result = true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a specific entry from the table. Returns true if the entry was found.
|
||||
*
|
||||
* @param dnsEntry
|
||||
* @return true if the entry was removed
|
||||
*/
|
||||
public boolean removeDNSEntry(DNSEntry dnsEntry) {
|
||||
boolean result = false;
|
||||
if (dnsEntry != null) {
|
||||
List<DNSEntry> entryList = this.get(dnsEntry.getKey());
|
||||
if (entryList != null) {
|
||||
synchronized (entryList) {
|
||||
entryList.remove(dnsEntry);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace an existing entry by a new one.<br/>
|
||||
* <b>Note:</b> the 2 entries must have the same key.
|
||||
*
|
||||
* @param newDNSEntry
|
||||
* @param existingDNSEntry
|
||||
* @return <code>true</code> if the entry has been replace, <code>false</code> otherwise.
|
||||
*/
|
||||
public boolean replaceDNSEntry(DNSEntry newDNSEntry, DNSEntry existingDNSEntry) {
|
||||
boolean result = false;
|
||||
if ((newDNSEntry != null) && (existingDNSEntry != null) && (newDNSEntry.getKey().equals(existingDNSEntry.getKey()))) {
|
||||
List<DNSEntry> entryList = this.get(newDNSEntry.getKey());
|
||||
if (entryList == null) {
|
||||
this.putIfAbsent(newDNSEntry.getKey(), new ArrayList<DNSEntry>());
|
||||
entryList = this.get(newDNSEntry.getKey());
|
||||
}
|
||||
synchronized (entryList) {
|
||||
entryList.remove(existingDNSEntry);
|
||||
entryList.add(newDNSEntry);
|
||||
}
|
||||
// This is probably not very informative
|
||||
result = true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public synchronized String toString() {
|
||||
StringBuffer aLog = new StringBuffer(2000);
|
||||
aLog.append("\t---- cache ----");
|
||||
for (String key : this.keySet()) {
|
||||
aLog.append("\n\t\t");
|
||||
aLog.append("\n\t\tname '");
|
||||
aLog.append(key);
|
||||
aLog.append("' ");
|
||||
List<? extends DNSEntry> entryList = this.get(key);
|
||||
if ((entryList != null) && (!entryList.isEmpty())) {
|
||||
synchronized (entryList) {
|
||||
for (DNSEntry entry : entryList) {
|
||||
aLog.append("\n\t\t\t");
|
||||
aLog.append(entry.toString());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
aLog.append(" no entries");
|
||||
}
|
||||
}
|
||||
return aLog.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,316 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.jmdns.ServiceInfo.Fields;
|
||||
import javax.jmdns.impl.constants.DNSRecordClass;
|
||||
import javax.jmdns.impl.constants.DNSRecordType;
|
||||
|
||||
/**
|
||||
* DNS entry with a name, type, and class. This is the base class for questions and records.
|
||||
*
|
||||
* @author Arthur van Hoff, Pierre Frisch, Rick Blair
|
||||
*/
|
||||
public abstract class DNSEntry {
|
||||
// private static Logger logger = Logger.getLogger(DNSEntry.class.getName());
|
||||
private final String _key;
|
||||
|
||||
private final String _name;
|
||||
|
||||
private final String _type;
|
||||
|
||||
private final DNSRecordType _recordType;
|
||||
|
||||
private final DNSRecordClass _dnsClass;
|
||||
|
||||
private final boolean _unique;
|
||||
|
||||
final Map<Fields, String> _qualifiedNameMap;
|
||||
|
||||
/**
|
||||
* Create an entry.
|
||||
*/
|
||||
DNSEntry(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
|
||||
_name = name;
|
||||
// _key = (name != null ? name.trim().toLowerCase() : null);
|
||||
_recordType = type;
|
||||
_dnsClass = recordClass;
|
||||
_unique = unique;
|
||||
_qualifiedNameMap = ServiceInfoImpl.decodeQualifiedNameMapForType(this.getName());
|
||||
String domain = _qualifiedNameMap.get(Fields.Domain);
|
||||
String protocol = _qualifiedNameMap.get(Fields.Protocol);
|
||||
String application = _qualifiedNameMap.get(Fields.Application);
|
||||
String instance = _qualifiedNameMap.get(Fields.Instance).toLowerCase();
|
||||
_type = (application.length() > 0 ? "_" + application + "." : "") + (protocol.length() > 0 ? "_" + protocol + "." : "") + domain + ".";
|
||||
_key = ((instance.length() > 0 ? instance + "." : "") + _type).toLowerCase();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#equals(java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
boolean result = false;
|
||||
if (obj instanceof DNSEntry) {
|
||||
DNSEntry other = (DNSEntry) obj;
|
||||
result = this.getKey().equals(other.getKey()) && this.getRecordType().equals(other.getRecordType()) && this.getRecordClass() == other.getRecordClass();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if two entries have exactly the same name, type, and class.
|
||||
*
|
||||
* @param entry
|
||||
* @return <code>true</code> if the two entries have are for the same record, <code>false</code> otherwise
|
||||
*/
|
||||
public boolean isSameEntry(DNSEntry entry) {
|
||||
return this.getKey().equals(entry.getKey()) && this.matchRecordType(entry.getRecordType()) && this.matchRecordClass(entry.getRecordClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if two entries have the same subtype.
|
||||
*
|
||||
* @param other
|
||||
* @return <code>true</code> if the two entries have are for the same subtype, <code>false</code> otherwise
|
||||
*/
|
||||
public boolean sameSubtype(DNSEntry other) {
|
||||
return this.getSubtype().equals(other.getSubtype());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the requested record class match the current record class
|
||||
*
|
||||
* @param recordClass
|
||||
* @return <code>true</code> if the two entries have compatible class, <code>false</code> otherwise
|
||||
*/
|
||||
public boolean matchRecordClass(DNSRecordClass recordClass) {
|
||||
return (DNSRecordClass.CLASS_ANY == recordClass) || (DNSRecordClass.CLASS_ANY == this.getRecordClass()) || this.getRecordClass().equals(recordClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the requested record tyep match the current record type
|
||||
*
|
||||
* @param recordType
|
||||
* @return <code>true</code> if the two entries have compatible type, <code>false</code> otherwise
|
||||
*/
|
||||
public boolean matchRecordType(DNSRecordType recordType) {
|
||||
return this.getRecordType().equals(recordType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the subtype of this entry
|
||||
*
|
||||
* @return subtype of this entry
|
||||
*/
|
||||
public String getSubtype() {
|
||||
String subtype = this.getQualifiedNameMap().get(Fields.Subtype);
|
||||
return (subtype != null ? subtype : "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of this entry
|
||||
*
|
||||
* @return name of this entry
|
||||
*/
|
||||
public String getName() {
|
||||
return (_name != null ? _name : "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the type
|
||||
*/
|
||||
public String getType() {
|
||||
return (_type != null ? _type : "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the key for this entry. The key is the lower case name.
|
||||
*
|
||||
* @return key for this entry
|
||||
*/
|
||||
public String getKey() {
|
||||
return (_key != null ? _key : "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @return record type
|
||||
*/
|
||||
public DNSRecordType getRecordType() {
|
||||
return (_recordType != null ? _recordType : DNSRecordType.TYPE_IGNORE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return record class
|
||||
*/
|
||||
public DNSRecordClass getRecordClass() {
|
||||
return (_dnsClass != null ? _dnsClass : DNSRecordClass.CLASS_UNKNOWN);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if unique
|
||||
*/
|
||||
public boolean isUnique() {
|
||||
return _unique;
|
||||
}
|
||||
|
||||
public Map<Fields, String> getQualifiedNameMap() {
|
||||
return Collections.unmodifiableMap(_qualifiedNameMap);
|
||||
}
|
||||
|
||||
public boolean isServicesDiscoveryMetaQuery() {
|
||||
return _qualifiedNameMap.get(Fields.Application).equals("dns-sd") && _qualifiedNameMap.get(Fields.Instance).equals("_services");
|
||||
}
|
||||
|
||||
public boolean isDomainDiscoveryQuery() {
|
||||
// b._dns-sd._udp.<domain>.
|
||||
// db._dns-sd._udp.<domain>.
|
||||
// r._dns-sd._udp.<domain>.
|
||||
// dr._dns-sd._udp.<domain>.
|
||||
// lb._dns-sd._udp.<domain>.
|
||||
|
||||
if (_qualifiedNameMap.get(Fields.Application).equals("dns-sd")) {
|
||||
String name = _qualifiedNameMap.get(Fields.Instance);
|
||||
return "b".equals(name) || "db".equals(name) || "r".equals(name) || "dr".equals(name) || "lb".equals(name);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isReverseLookup() {
|
||||
return this.isV4ReverseLookup() || this.isV6ReverseLookup();
|
||||
}
|
||||
|
||||
public boolean isV4ReverseLookup() {
|
||||
return _qualifiedNameMap.get(Fields.Domain).endsWith("in-addr.arpa");
|
||||
}
|
||||
|
||||
public boolean isV6ReverseLookup() {
|
||||
return _qualifiedNameMap.get(Fields.Domain).endsWith("ip6.arpa");
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the record is stale, i.e. it has outlived more than half of its TTL.
|
||||
*
|
||||
* @param now
|
||||
* update date
|
||||
* @return <code>true</code> is the record is stale, <code>false</code> otherwise.
|
||||
*/
|
||||
public abstract boolean isStale(long now);
|
||||
|
||||
/**
|
||||
* Check if the record is expired.
|
||||
*
|
||||
* @param now
|
||||
* update date
|
||||
* @return <code>true</code> is the record is expired, <code>false</code> otherwise.
|
||||
*/
|
||||
public abstract boolean isExpired(long now);
|
||||
|
||||
/**
|
||||
* Check that 2 entries are of the same class.
|
||||
*
|
||||
* @param entry
|
||||
* @return <code>true</code> is the two class are the same, <code>false</code> otherwise.
|
||||
*/
|
||||
public boolean isSameRecordClass(DNSEntry entry) {
|
||||
return (entry != null) && (entry.getRecordClass() == this.getRecordClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that 2 entries are of the same type.
|
||||
*
|
||||
* @param entry
|
||||
* @return <code>true</code> is the two type are the same, <code>false</code> otherwise.
|
||||
*/
|
||||
public boolean isSameType(DNSEntry entry) {
|
||||
return (entry != null) && (entry.getRecordType() == this.getRecordType());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param dout
|
||||
* @exception IOException
|
||||
*/
|
||||
protected void toByteArray(DataOutputStream dout) throws IOException {
|
||||
dout.write(this.getName().getBytes("UTF8"));
|
||||
dout.writeShort(this.getRecordType().indexValue());
|
||||
dout.writeShort(this.getRecordClass().indexValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a byte array representation of this record. This is needed for tie-break tests according to draft-cheshire-dnsext-multicastdns-04.txt chapter 9.2.
|
||||
*
|
||||
* @return byte array representation
|
||||
*/
|
||||
protected byte[] toByteArray() {
|
||||
try {
|
||||
ByteArrayOutputStream bout = new ByteArrayOutputStream();
|
||||
DataOutputStream dout = new DataOutputStream(bout);
|
||||
this.toByteArray(dout);
|
||||
dout.close();
|
||||
return bout.toByteArray();
|
||||
} catch (IOException e) {
|
||||
throw new InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Does a lexicographic comparison of the byte array representation of this record and that record. This is needed for tie-break tests according to draft-cheshire-dnsext-multicastdns-04.txt chapter 9.2.
|
||||
*
|
||||
* @param that
|
||||
* @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
|
||||
*/
|
||||
public int compareTo(DNSEntry that) {
|
||||
byte[] thisBytes = this.toByteArray();
|
||||
byte[] thatBytes = that.toByteArray();
|
||||
for (int i = 0, n = Math.min(thisBytes.length, thatBytes.length); i < n; i++) {
|
||||
if (thisBytes[i] > thatBytes[i]) {
|
||||
return 1;
|
||||
} else if (thisBytes[i] < thatBytes[i]) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return thisBytes.length - thatBytes.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overriden, to return a value which is consistent with the value returned by equals(Object).
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return this.getKey().hashCode() + this.getRecordType().indexValue() + this.getRecordClass().indexValue();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder aLog = new StringBuilder(200);
|
||||
aLog.append("[" + this.getClass().getSimpleName() + "@" + System.identityHashCode(this));
|
||||
aLog.append(" type: " + this.getRecordType());
|
||||
aLog.append(", class: " + this.getRecordClass());
|
||||
aLog.append((_unique ? "-unique," : ","));
|
||||
aLog.append(" name: " + _name);
|
||||
this.toString(aLog);
|
||||
aLog.append("]");
|
||||
return aLog.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param aLog
|
||||
*/
|
||||
protected void toString(StringBuilder aLog) {
|
||||
// Stub
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,604 @@
|
|||
// /Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.InetAddress;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
import javax.jmdns.impl.constants.DNSLabel;
|
||||
import javax.jmdns.impl.constants.DNSOptionCode;
|
||||
import javax.jmdns.impl.constants.DNSRecordClass;
|
||||
import javax.jmdns.impl.constants.DNSRecordType;
|
||||
import javax.jmdns.impl.constants.DNSResultCode;
|
||||
|
||||
/**
|
||||
* Parse an incoming DNS message into its components.
|
||||
*
|
||||
* @author Arthur van Hoff, Werner Randelshofer, Pierre Frisch, Daniel Bobbert
|
||||
*/
|
||||
public final class DNSIncoming extends DNSMessage {
|
||||
private static Logger logger = Logger.getLogger(DNSIncoming.class.getName());
|
||||
|
||||
// This is a hack to handle a bug in the BonjourConformanceTest
|
||||
// It is sending out target strings that don't follow the "domain name" format.
|
||||
public static boolean USE_DOMAIN_NAME_FORMAT_FOR_SRV_TARGET = true;
|
||||
|
||||
public static class MessageInputStream extends ByteArrayInputStream {
|
||||
private static Logger logger1 = Logger.getLogger(MessageInputStream.class.getName());
|
||||
|
||||
final Map<Integer, String> _names;
|
||||
|
||||
public MessageInputStream(byte[] buffer, int length) {
|
||||
this(buffer, 0, length);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param buffer
|
||||
* @param offset
|
||||
* @param length
|
||||
*/
|
||||
public MessageInputStream(byte[] buffer, int offset, int length) {
|
||||
super(buffer, offset, length);
|
||||
_names = new HashMap<Integer, String>();
|
||||
}
|
||||
|
||||
public int readByte() {
|
||||
return this.read();
|
||||
}
|
||||
|
||||
public int readUnsignedByte() {
|
||||
return (this.read() & 0xFF);
|
||||
}
|
||||
|
||||
public int readUnsignedShort() {
|
||||
return (this.readUnsignedByte() << 8) | this.readUnsignedByte();
|
||||
}
|
||||
|
||||
public int readInt() {
|
||||
return (this.readUnsignedShort() << 16) | this.readUnsignedShort();
|
||||
}
|
||||
|
||||
public byte[] readBytes(int len) {
|
||||
byte bytes[] = new byte[len];
|
||||
this.read(bytes, 0, len);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public String readUTF(int len) {
|
||||
StringBuilder buffer = new StringBuilder(len);
|
||||
for (int index = 0; index < len; index++) {
|
||||
int ch = this.readUnsignedByte();
|
||||
switch (ch >> 4) {
|
||||
case 0:
|
||||
case 1:
|
||||
case 2:
|
||||
case 3:
|
||||
case 4:
|
||||
case 5:
|
||||
case 6:
|
||||
case 7:
|
||||
// 0xxxxxxx
|
||||
break;
|
||||
case 12:
|
||||
case 13:
|
||||
// 110x xxxx 10xx xxxx
|
||||
ch = ((ch & 0x1F) << 6) | (this.readUnsignedByte() & 0x3F);
|
||||
index++;
|
||||
break;
|
||||
case 14:
|
||||
// 1110 xxxx 10xx xxxx 10xx xxxx
|
||||
ch = ((ch & 0x0f) << 12) | ((this.readUnsignedByte() & 0x3F) << 6) | (this.readUnsignedByte() & 0x3F);
|
||||
index++;
|
||||
index++;
|
||||
break;
|
||||
default:
|
||||
// 10xx xxxx, 1111 xxxx
|
||||
ch = ((ch & 0x3F) << 4) | (this.readUnsignedByte() & 0x0f);
|
||||
index++;
|
||||
break;
|
||||
}
|
||||
buffer.append((char) ch);
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
protected synchronized int peek() {
|
||||
return (pos < count) ? (buf[pos] & 0xff) : -1;
|
||||
}
|
||||
|
||||
public String readName() {
|
||||
Map<Integer, StringBuilder> names = new HashMap<Integer, StringBuilder>();
|
||||
StringBuilder buffer = new StringBuilder();
|
||||
boolean finished = false;
|
||||
while (!finished) {
|
||||
int len = this.readUnsignedByte();
|
||||
if (len == 0) {
|
||||
finished = true;
|
||||
break;
|
||||
}
|
||||
switch (DNSLabel.labelForByte(len)) {
|
||||
case Standard:
|
||||
int offset = pos - 1;
|
||||
String label = this.readUTF(len) + ".";
|
||||
buffer.append(label);
|
||||
for (StringBuilder previousLabel : names.values()) {
|
||||
previousLabel.append(label);
|
||||
}
|
||||
names.put(Integer.valueOf(offset), new StringBuilder(label));
|
||||
break;
|
||||
case Compressed:
|
||||
int index = (DNSLabel.labelValue(len) << 8) | this.readUnsignedByte();
|
||||
String compressedLabel = _names.get(Integer.valueOf(index));
|
||||
if (compressedLabel == null) {
|
||||
logger1.severe("bad domain name: possible circular name detected. Bad offset: 0x" + Integer.toHexString(index) + " at 0x" + Integer.toHexString(pos - 2));
|
||||
compressedLabel = "";
|
||||
}
|
||||
buffer.append(compressedLabel);
|
||||
for (StringBuilder previousLabel : names.values()) {
|
||||
previousLabel.append(compressedLabel);
|
||||
}
|
||||
finished = true;
|
||||
break;
|
||||
case Extended:
|
||||
// int extendedLabelClass = DNSLabel.labelValue(len);
|
||||
logger1.severe("Extended label are not currently supported.");
|
||||
break;
|
||||
case Unknown:
|
||||
default:
|
||||
logger1.severe("unsupported dns label type: '" + Integer.toHexString(len & 0xC0) + "'");
|
||||
}
|
||||
}
|
||||
for (Integer index : names.keySet()) {
|
||||
_names.put(index, names.get(index).toString());
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
public String readNonNameString() {
|
||||
int len = this.readUnsignedByte();
|
||||
return this.readUTF(len);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private final DatagramPacket _packet;
|
||||
|
||||
private final long _receivedTime;
|
||||
|
||||
private final MessageInputStream _messageInputStream;
|
||||
|
||||
private int _senderUDPPayload;
|
||||
|
||||
/**
|
||||
* Parse a message from a datagram packet.
|
||||
*
|
||||
* @param packet
|
||||
* @exception IOException
|
||||
*/
|
||||
public DNSIncoming(DatagramPacket packet) throws IOException {
|
||||
super(0, 0, packet.getPort() == DNSConstants.MDNS_PORT);
|
||||
this._packet = packet;
|
||||
InetAddress source = packet.getAddress();
|
||||
this._messageInputStream = new MessageInputStream(packet.getData(), packet.getLength());
|
||||
this._receivedTime = System.currentTimeMillis();
|
||||
this._senderUDPPayload = DNSConstants.MAX_MSG_TYPICAL;
|
||||
|
||||
try {
|
||||
this.setId(_messageInputStream.readUnsignedShort());
|
||||
this.setFlags(_messageInputStream.readUnsignedShort());
|
||||
if (this.getOperationCode() > 0) {
|
||||
throw new IOException("Received a message with a non standard operation code. Currently unsupported in the specification.");
|
||||
}
|
||||
int numQuestions = _messageInputStream.readUnsignedShort();
|
||||
int numAnswers = _messageInputStream.readUnsignedShort();
|
||||
int numAuthorities = _messageInputStream.readUnsignedShort();
|
||||
int numAdditionals = _messageInputStream.readUnsignedShort();
|
||||
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
logger.finer("DNSIncoming() questions:" + numQuestions + " answers:" + numAnswers + " authorities:" + numAuthorities + " additionals:" + numAdditionals);
|
||||
}
|
||||
|
||||
// We need some sanity checks
|
||||
// A question is at least 5 bytes and answer 11 so check what we have
|
||||
|
||||
if ((numQuestions * 5 + (numAnswers + numAuthorities + numAdditionals) * 11) > packet.getLength()) {
|
||||
throw new IOException("questions:" + numQuestions + " answers:" + numAnswers + " authorities:" + numAuthorities + " additionals:" + numAdditionals);
|
||||
}
|
||||
|
||||
// parse questions
|
||||
if (numQuestions > 0) {
|
||||
for (int i = 0; i < numQuestions; i++) {
|
||||
_questions.add(this.readQuestion());
|
||||
}
|
||||
}
|
||||
|
||||
// parse answers
|
||||
if (numAnswers > 0) {
|
||||
for (int i = 0; i < numAnswers; i++) {
|
||||
DNSRecord rec = this.readAnswer(source);
|
||||
if (rec != null) {
|
||||
// Add a record, if we were able to create one.
|
||||
_answers.add(rec);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (numAuthorities > 0) {
|
||||
for (int i = 0; i < numAuthorities; i++) {
|
||||
DNSRecord rec = this.readAnswer(source);
|
||||
if (rec != null) {
|
||||
// Add a record, if we were able to create one.
|
||||
_authoritativeAnswers.add(rec);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (numAdditionals > 0) {
|
||||
for (int i = 0; i < numAdditionals; i++) {
|
||||
DNSRecord rec = this.readAnswer(source);
|
||||
if (rec != null) {
|
||||
// Add a record, if we were able to create one.
|
||||
_additionals.add(rec);
|
||||
}
|
||||
}
|
||||
}
|
||||
// We should have drained the entire stream by now
|
||||
if (_messageInputStream.available() > 0) {
|
||||
throw new IOException("Received a message with the wrong length.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.log(Level.WARNING, "DNSIncoming() dump " + print(true) + "\n exception ", e);
|
||||
// This ugly but some JVM don't implement the cause on IOException
|
||||
IOException ioe = new IOException("DNSIncoming corrupted message");
|
||||
ioe.initCause(e);
|
||||
throw ioe;
|
||||
}
|
||||
}
|
||||
|
||||
private DNSIncoming(int flags, int id, boolean multicast, DatagramPacket packet, long receivedTime) {
|
||||
super(flags, id, multicast);
|
||||
this._packet = packet;
|
||||
this._messageInputStream = new MessageInputStream(packet.getData(), packet.getLength());
|
||||
this._receivedTime = receivedTime;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#clone()
|
||||
*/
|
||||
@Override
|
||||
public DNSIncoming clone() {
|
||||
DNSIncoming in = new DNSIncoming(this.getFlags(), this.getId(), this.isMulticast(), this._packet, this._receivedTime);
|
||||
in._senderUDPPayload = this._senderUDPPayload;
|
||||
in._questions.addAll(this._questions);
|
||||
in._answers.addAll(this._answers);
|
||||
in._authoritativeAnswers.addAll(this._authoritativeAnswers);
|
||||
in._additionals.addAll(this._additionals);
|
||||
return in;
|
||||
}
|
||||
|
||||
private DNSQuestion readQuestion() {
|
||||
String domain = _messageInputStream.readName();
|
||||
DNSRecordType type = DNSRecordType.typeForIndex(_messageInputStream.readUnsignedShort());
|
||||
if (type == DNSRecordType.TYPE_IGNORE) {
|
||||
logger.log(Level.SEVERE, "Could not find record type: " + this.print(true));
|
||||
}
|
||||
int recordClassIndex = _messageInputStream.readUnsignedShort();
|
||||
DNSRecordClass recordClass = DNSRecordClass.classForIndex(recordClassIndex);
|
||||
boolean unique = recordClass.isUnique(recordClassIndex);
|
||||
return DNSQuestion.newQuestion(domain, type, recordClass, unique);
|
||||
}
|
||||
|
||||
private DNSRecord readAnswer(InetAddress source) {
|
||||
String domain = _messageInputStream.readName();
|
||||
DNSRecordType type = DNSRecordType.typeForIndex(_messageInputStream.readUnsignedShort());
|
||||
if (type == DNSRecordType.TYPE_IGNORE) {
|
||||
logger.log(Level.SEVERE, "Could not find record type. domain: " + domain + "\n" + this.print(true));
|
||||
}
|
||||
int recordClassIndex = _messageInputStream.readUnsignedShort();
|
||||
DNSRecordClass recordClass = (type == DNSRecordType.TYPE_OPT ? DNSRecordClass.CLASS_UNKNOWN : DNSRecordClass.classForIndex(recordClassIndex));
|
||||
if ((recordClass == DNSRecordClass.CLASS_UNKNOWN) && (type != DNSRecordType.TYPE_OPT)) {
|
||||
logger.log(Level.SEVERE, "Could not find record class. domain: " + domain + " type: " + type + "\n" + this.print(true));
|
||||
}
|
||||
boolean unique = recordClass.isUnique(recordClassIndex);
|
||||
int ttl = _messageInputStream.readInt();
|
||||
int len = _messageInputStream.readUnsignedShort();
|
||||
DNSRecord rec = null;
|
||||
|
||||
switch (type) {
|
||||
case TYPE_A: // IPv4
|
||||
rec = new DNSRecord.IPv4Address(domain, recordClass, unique, ttl, _messageInputStream.readBytes(len));
|
||||
break;
|
||||
case TYPE_AAAA: // IPv6
|
||||
rec = new DNSRecord.IPv6Address(domain, recordClass, unique, ttl, _messageInputStream.readBytes(len));
|
||||
break;
|
||||
case TYPE_CNAME:
|
||||
case TYPE_PTR:
|
||||
String service = "";
|
||||
service = _messageInputStream.readName();
|
||||
if (service.length() > 0) {
|
||||
rec = new DNSRecord.Pointer(domain, recordClass, unique, ttl, service);
|
||||
} else {
|
||||
logger.log(Level.WARNING, "PTR record of class: " + recordClass + ", there was a problem reading the service name of the answer for domain:" + domain);
|
||||
}
|
||||
break;
|
||||
case TYPE_TXT:
|
||||
rec = new DNSRecord.Text(domain, recordClass, unique, ttl, _messageInputStream.readBytes(len));
|
||||
break;
|
||||
case TYPE_SRV:
|
||||
int priority = _messageInputStream.readUnsignedShort();
|
||||
int weight = _messageInputStream.readUnsignedShort();
|
||||
int port = _messageInputStream.readUnsignedShort();
|
||||
String target = "";
|
||||
// This is a hack to handle a bug in the BonjourConformanceTest
|
||||
// It is sending out target strings that don't follow the "domain name" format.
|
||||
if (USE_DOMAIN_NAME_FORMAT_FOR_SRV_TARGET) {
|
||||
target = _messageInputStream.readName();
|
||||
} else {
|
||||
// [PJYF Nov 13 2010] Do we still need this? This looks really bad. All label are supposed to start by a length.
|
||||
target = _messageInputStream.readNonNameString();
|
||||
}
|
||||
rec = new DNSRecord.Service(domain, recordClass, unique, ttl, priority, weight, port, target);
|
||||
break;
|
||||
case TYPE_HINFO:
|
||||
StringBuilder buf = new StringBuilder();
|
||||
buf.append(_messageInputStream.readUTF(len));
|
||||
int index = buf.indexOf(" ");
|
||||
String cpu = (index > 0 ? buf.substring(0, index) : buf.toString()).trim();
|
||||
String os = (index > 0 ? buf.substring(index + 1) : "").trim();
|
||||
rec = new DNSRecord.HostInformation(domain, recordClass, unique, ttl, cpu, os);
|
||||
break;
|
||||
case TYPE_OPT:
|
||||
DNSResultCode extendedResultCode = DNSResultCode.resultCodeForFlags(this.getFlags(), ttl);
|
||||
int version = (ttl & 0x00ff0000) >> 16;
|
||||
if (version == 0) {
|
||||
_senderUDPPayload = recordClassIndex;
|
||||
while (_messageInputStream.available() > 0) {
|
||||
// Read RDData
|
||||
int optionCodeInt = 0;
|
||||
DNSOptionCode optionCode = null;
|
||||
if (_messageInputStream.available() >= 2) {
|
||||
optionCodeInt = _messageInputStream.readUnsignedShort();
|
||||
optionCode = DNSOptionCode.resultCodeForFlags(optionCodeInt);
|
||||
} else {
|
||||
logger.log(Level.WARNING, "There was a problem reading the OPT record. Ignoring.");
|
||||
break;
|
||||
}
|
||||
int optionLength = 0;
|
||||
if (_messageInputStream.available() >= 2) {
|
||||
optionLength = _messageInputStream.readUnsignedShort();
|
||||
} else {
|
||||
logger.log(Level.WARNING, "There was a problem reading the OPT record. Ignoring.");
|
||||
break;
|
||||
}
|
||||
byte[] optiondata = new byte[0];
|
||||
if (_messageInputStream.available() >= optionLength) {
|
||||
optiondata = _messageInputStream.readBytes(optionLength);
|
||||
}
|
||||
//
|
||||
// We should really do something with those options.
|
||||
switch (optionCode) {
|
||||
case Owner:
|
||||
// Valid length values are 8, 14, 18 and 20
|
||||
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
// |Opt|Len|V|S|Primary MAC|Wakeup MAC | Password |
|
||||
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
//
|
||||
int ownerVersion = 0;
|
||||
int ownerSequence = 0;
|
||||
byte[] ownerPrimaryMacAddress = null;
|
||||
byte[] ownerWakeupMacAddress = null;
|
||||
byte[] ownerPassword = null;
|
||||
try {
|
||||
ownerVersion = optiondata[0];
|
||||
ownerSequence = optiondata[1];
|
||||
ownerPrimaryMacAddress = new byte[] { optiondata[2], optiondata[3], optiondata[4], optiondata[5], optiondata[6], optiondata[7] };
|
||||
ownerWakeupMacAddress = ownerPrimaryMacAddress;
|
||||
if (optiondata.length > 8) {
|
||||
// We have a wakeupMacAddress.
|
||||
ownerWakeupMacAddress = new byte[] { optiondata[8], optiondata[9], optiondata[10], optiondata[11], optiondata[12], optiondata[13] };
|
||||
}
|
||||
if (optiondata.length == 18) {
|
||||
// We have a short password.
|
||||
ownerPassword = new byte[] { optiondata[14], optiondata[15], optiondata[16], optiondata[17] };
|
||||
}
|
||||
if (optiondata.length == 22) {
|
||||
// We have a long password.
|
||||
ownerPassword = new byte[] { optiondata[14], optiondata[15], optiondata[16], optiondata[17], optiondata[18], optiondata[19], optiondata[20], optiondata[21] };
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
logger.warning("Malformed OPT answer. Option code: Owner data: " + this._hexString(optiondata));
|
||||
}
|
||||
if (logger.isLoggable(Level.FINE)) {
|
||||
logger.fine("Unhandled Owner OPT version: " + ownerVersion + " sequence: " + ownerSequence + " MAC address: " + this._hexString(ownerPrimaryMacAddress)
|
||||
+ (ownerWakeupMacAddress != ownerPrimaryMacAddress ? " wakeup MAC address: " + this._hexString(ownerWakeupMacAddress) : "") + (ownerPassword != null ? " password: " + this._hexString(ownerPassword) : ""));
|
||||
}
|
||||
break;
|
||||
case LLQ:
|
||||
case NSID:
|
||||
case UL:
|
||||
if (logger.isLoggable(Level.FINE)) {
|
||||
logger.log(Level.FINE, "There was an OPT answer. Option code: " + optionCode + " data: " + this._hexString(optiondata));
|
||||
}
|
||||
break;
|
||||
case Unknown:
|
||||
if (optionCodeInt >= 65001 && optionCodeInt <= 65534) {
|
||||
// RFC 6891 defines this range as used for experimental/local purposes.
|
||||
if (logger.isLoggable(Level.FINE)) {
|
||||
logger.log(Level.FINE, "There was an OPT answer using an experimental/local option code: " + optionCodeInt + " data: " + this._hexString(optiondata));
|
||||
}
|
||||
} else {
|
||||
logger.log(Level.WARNING, "There was an OPT answer. Not currently handled. Option code: " + optionCodeInt + " data: " + this._hexString(optiondata));
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// This is to keep the compiler happy.
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.log(Level.WARNING, "There was an OPT answer. Wrong version number: " + version + " result code: " + extendedResultCode);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
logger.finer("DNSIncoming() unknown type:" + type);
|
||||
}
|
||||
_messageInputStream.skip(len);
|
||||
break;
|
||||
}
|
||||
if (rec != null) {
|
||||
rec.setRecordSource(source);
|
||||
}
|
||||
return rec;
|
||||
}
|
||||
|
||||
/**
|
||||
* Debugging.
|
||||
*/
|
||||
String print(boolean dump) {
|
||||
StringBuilder buf = new StringBuilder();
|
||||
buf.append(this.print());
|
||||
if (dump) {
|
||||
byte[] data = new byte[_packet.getLength()];
|
||||
System.arraycopy(_packet.getData(), 0, data, 0, data.length);
|
||||
buf.append(this.print(data));
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder buf = new StringBuilder();
|
||||
buf.append(isQuery() ? "dns[query," : "dns[response,");
|
||||
if (_packet.getAddress() != null) {
|
||||
buf.append(_packet.getAddress().getHostAddress());
|
||||
}
|
||||
buf.append(':');
|
||||
buf.append(_packet.getPort());
|
||||
buf.append(", length=");
|
||||
buf.append(_packet.getLength());
|
||||
buf.append(", id=0x");
|
||||
buf.append(Integer.toHexString(this.getId()));
|
||||
if (this.getFlags() != 0) {
|
||||
buf.append(", flags=0x");
|
||||
buf.append(Integer.toHexString(this.getFlags()));
|
||||
if ((this.getFlags() & DNSConstants.FLAGS_QR_RESPONSE) != 0) {
|
||||
buf.append(":r");
|
||||
}
|
||||
if ((this.getFlags() & DNSConstants.FLAGS_AA) != 0) {
|
||||
buf.append(":aa");
|
||||
}
|
||||
if ((this.getFlags() & DNSConstants.FLAGS_TC) != 0) {
|
||||
buf.append(":tc");
|
||||
}
|
||||
}
|
||||
if (this.getNumberOfQuestions() > 0) {
|
||||
buf.append(", questions=");
|
||||
buf.append(this.getNumberOfQuestions());
|
||||
}
|
||||
if (this.getNumberOfAnswers() > 0) {
|
||||
buf.append(", answers=");
|
||||
buf.append(this.getNumberOfAnswers());
|
||||
}
|
||||
if (this.getNumberOfAuthorities() > 0) {
|
||||
buf.append(", authorities=");
|
||||
buf.append(this.getNumberOfAuthorities());
|
||||
}
|
||||
if (this.getNumberOfAdditionals() > 0) {
|
||||
buf.append(", additionals=");
|
||||
buf.append(this.getNumberOfAdditionals());
|
||||
}
|
||||
if (this.getNumberOfQuestions() > 0) {
|
||||
buf.append("\nquestions:");
|
||||
for (DNSQuestion question : _questions) {
|
||||
buf.append("\n\t");
|
||||
buf.append(question);
|
||||
}
|
||||
}
|
||||
if (this.getNumberOfAnswers() > 0) {
|
||||
buf.append("\nanswers:");
|
||||
for (DNSRecord record : _answers) {
|
||||
buf.append("\n\t");
|
||||
buf.append(record);
|
||||
}
|
||||
}
|
||||
if (this.getNumberOfAuthorities() > 0) {
|
||||
buf.append("\nauthorities:");
|
||||
for (DNSRecord record : _authoritativeAnswers) {
|
||||
buf.append("\n\t");
|
||||
buf.append(record);
|
||||
}
|
||||
}
|
||||
if (this.getNumberOfAdditionals() > 0) {
|
||||
buf.append("\nadditionals:");
|
||||
for (DNSRecord record : _additionals) {
|
||||
buf.append("\n\t");
|
||||
buf.append(record);
|
||||
}
|
||||
}
|
||||
buf.append("]");
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends answers to this Incoming.
|
||||
*
|
||||
* @exception IllegalArgumentException
|
||||
* If not a query or if Truncated.
|
||||
*/
|
||||
void append(DNSIncoming that) {
|
||||
if (this.isQuery() && this.isTruncated() && that.isQuery()) {
|
||||
this._questions.addAll(that.getQuestions());
|
||||
this._answers.addAll(that.getAnswers());
|
||||
this._authoritativeAnswers.addAll(that.getAuthorities());
|
||||
this._additionals.addAll(that.getAdditionals());
|
||||
} else {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
}
|
||||
|
||||
public int elapseSinceArrival() {
|
||||
return (int) (System.currentTimeMillis() - _receivedTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* This will return the default UDP payload except if an OPT record was found with a different size.
|
||||
*
|
||||
* @return the senderUDPPayload
|
||||
*/
|
||||
public int getSenderUDPPayload() {
|
||||
return this._senderUDPPayload;
|
||||
}
|
||||
|
||||
private static final char[] _nibbleToHex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
|
||||
|
||||
/**
|
||||
* Returns a hex-string for printing
|
||||
*
|
||||
* @param bytes
|
||||
* @return Returns a hex-string which can be used within a SQL expression
|
||||
*/
|
||||
private String _hexString(byte[] bytes) {
|
||||
|
||||
StringBuilder result = new StringBuilder(2 * bytes.length);
|
||||
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
int b = bytes[i] & 0xFF;
|
||||
result.append(_nibbleToHex[b / 16]);
|
||||
result.append(_nibbleToHex[b % 16]);
|
||||
}
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl;
|
||||
|
||||
// REMIND: Listener should follow Java idiom for listener or have a different
|
||||
// name.
|
||||
|
||||
/**
|
||||
* DNSListener. Listener for record updates.
|
||||
*
|
||||
* @author Werner Randelshofer, Rick Blair
|
||||
* @version 1.0 May 22, 2004 Created.
|
||||
*/
|
||||
interface DNSListener {
|
||||
/**
|
||||
* Update a DNS record.
|
||||
*
|
||||
* @param dnsCache
|
||||
* record cache
|
||||
* @param now
|
||||
* update date
|
||||
* @param record
|
||||
* DNS record
|
||||
*/
|
||||
void updateRecord(DNSCache dnsCache, long now, DNSEntry record);
|
||||
}
|
||||
|
|
@ -0,0 +1,335 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
|
||||
/**
|
||||
* DNSMessage define a DNS message either incoming or outgoing.
|
||||
*
|
||||
* @author Werner Randelshofer, Rick Blair, Pierre Frisch
|
||||
*/
|
||||
public abstract class DNSMessage {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public static final boolean MULTICAST = true;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public static final boolean UNICAST = false;
|
||||
|
||||
// protected DatagramPacket _packet;
|
||||
// protected int _off;
|
||||
// protected int _len;
|
||||
// protected byte[] _data;
|
||||
|
||||
private int _id;
|
||||
|
||||
boolean _multicast;
|
||||
|
||||
private int _flags;
|
||||
|
||||
protected final List<DNSQuestion> _questions;
|
||||
|
||||
protected final List<DNSRecord> _answers;
|
||||
|
||||
protected final List<DNSRecord> _authoritativeAnswers;
|
||||
|
||||
protected final List<DNSRecord> _additionals;
|
||||
|
||||
/**
|
||||
* @param flags
|
||||
* @param id
|
||||
* @param multicast
|
||||
*/
|
||||
protected DNSMessage(int flags, int id, boolean multicast) {
|
||||
super();
|
||||
_flags = flags;
|
||||
_id = id;
|
||||
_multicast = multicast;
|
||||
_questions = Collections.synchronizedList(new LinkedList<DNSQuestion>());
|
||||
_answers = Collections.synchronizedList(new LinkedList<DNSRecord>());
|
||||
_authoritativeAnswers = Collections.synchronizedList(new LinkedList<DNSRecord>());
|
||||
_additionals = Collections.synchronizedList(new LinkedList<DNSRecord>());
|
||||
}
|
||||
|
||||
// public DatagramPacket getPacket() {
|
||||
// return _packet;
|
||||
// }
|
||||
//
|
||||
// public int getOffset() {
|
||||
// return _off;
|
||||
// }
|
||||
//
|
||||
// public int getLength() {
|
||||
// return _len;
|
||||
// }
|
||||
//
|
||||
// public byte[] getData() {
|
||||
// if ( _data == null ) _data = new byte[DNSConstants.MAX_MSG_TYPICAL];
|
||||
// return _data;
|
||||
// }
|
||||
|
||||
/**
|
||||
* @return message id
|
||||
*/
|
||||
public int getId() {
|
||||
return (_multicast ? 0 : _id);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param id
|
||||
* the id to set
|
||||
*/
|
||||
public void setId(int id) {
|
||||
this._id = id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return message flags
|
||||
*/
|
||||
public int getFlags() {
|
||||
return _flags;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param flags
|
||||
* the flags to set
|
||||
*/
|
||||
public void setFlags(int flags) {
|
||||
this._flags = flags;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if multicast
|
||||
*/
|
||||
public boolean isMulticast() {
|
||||
return _multicast;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list of questions
|
||||
*/
|
||||
public Collection<? extends DNSQuestion> getQuestions() {
|
||||
return _questions;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return number of questions in the message
|
||||
*/
|
||||
public int getNumberOfQuestions() {
|
||||
return this.getQuestions().size();
|
||||
}
|
||||
|
||||
public Collection<? extends DNSRecord> getAllAnswers() {
|
||||
List<DNSRecord> aList = new ArrayList<DNSRecord>(_answers.size() + _authoritativeAnswers.size() + _additionals.size());
|
||||
aList.addAll(_answers);
|
||||
aList.addAll(_authoritativeAnswers);
|
||||
aList.addAll(_additionals);
|
||||
return aList;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list of answers
|
||||
*/
|
||||
public Collection<? extends DNSRecord> getAnswers() {
|
||||
return _answers;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return number of answers in the message
|
||||
*/
|
||||
public int getNumberOfAnswers() {
|
||||
return this.getAnswers().size();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list of authorities
|
||||
*/
|
||||
public Collection<? extends DNSRecord> getAuthorities() {
|
||||
return _authoritativeAnswers;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return number of authorities in the message
|
||||
*/
|
||||
public int getNumberOfAuthorities() {
|
||||
return this.getAuthorities().size();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list of additional answers
|
||||
*/
|
||||
public Collection<? extends DNSRecord> getAdditionals() {
|
||||
return _additionals;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return number of additional in the message
|
||||
*/
|
||||
public int getNumberOfAdditionals() {
|
||||
return this.getAdditionals().size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check is the response code is valid<br/>
|
||||
* The only valid value is zero all other values signify an error and the message must be ignored.
|
||||
*
|
||||
* @return true if the message has a valid response code.
|
||||
*/
|
||||
public boolean isValidResponseCode() {
|
||||
return (_flags & DNSConstants.FLAGS_RCODE) == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the operation code value. Currently only standard query 0 is valid.
|
||||
*
|
||||
* @return The operation code value.
|
||||
*/
|
||||
public int getOperationCode() {
|
||||
return (_flags & DNSConstants.FLAGS_OPCODE) >> 11;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the message is truncated.
|
||||
*
|
||||
* @return true if the message was truncated
|
||||
*/
|
||||
public boolean isTruncated() {
|
||||
return (_flags & DNSConstants.FLAGS_TC) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the message is an authoritative answer.
|
||||
*
|
||||
* @return true if the message is an authoritative answer
|
||||
*/
|
||||
public boolean isAuthoritativeAnswer() {
|
||||
return (_flags & DNSConstants.FLAGS_AA) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the message is a query.
|
||||
*
|
||||
* @return true is the message is a query
|
||||
*/
|
||||
public boolean isQuery() {
|
||||
return (_flags & DNSConstants.FLAGS_QR_MASK) == DNSConstants.FLAGS_QR_QUERY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the message is a response.
|
||||
*
|
||||
* @return true is the message is a response
|
||||
*/
|
||||
public boolean isResponse() {
|
||||
return (_flags & DNSConstants.FLAGS_QR_MASK) == DNSConstants.FLAGS_QR_RESPONSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the message is empty
|
||||
*
|
||||
* @return true is the message is empty
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return (this.getNumberOfQuestions() + this.getNumberOfAnswers() + this.getNumberOfAuthorities() + this.getNumberOfAdditionals()) == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Debugging.
|
||||
*/
|
||||
String print() {
|
||||
StringBuffer buf = new StringBuffer(200);
|
||||
buf.append(this.toString());
|
||||
buf.append("\n");
|
||||
for (DNSQuestion question : _questions) {
|
||||
buf.append("\tquestion: ");
|
||||
buf.append(question);
|
||||
buf.append("\n");
|
||||
}
|
||||
for (DNSRecord answer : _answers) {
|
||||
buf.append("\tanswer: ");
|
||||
buf.append(answer);
|
||||
buf.append("\n");
|
||||
}
|
||||
for (DNSRecord answer : _authoritativeAnswers) {
|
||||
buf.append("\tauthoritative: ");
|
||||
buf.append(answer);
|
||||
buf.append("\n");
|
||||
}
|
||||
for (DNSRecord answer : _additionals) {
|
||||
buf.append("\tadditional: ");
|
||||
buf.append(answer);
|
||||
buf.append("\n");
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Debugging.
|
||||
*
|
||||
* @param data
|
||||
* @return data dump
|
||||
*/
|
||||
protected String print(byte[] data) {
|
||||
StringBuilder buf = new StringBuilder(4000);
|
||||
for (int off = 0, len = data.length; off < len; off += 32) {
|
||||
int n = Math.min(32, len - off);
|
||||
if (off < 0x10) {
|
||||
buf.append(' ');
|
||||
}
|
||||
if (off < 0x100) {
|
||||
buf.append(' ');
|
||||
}
|
||||
if (off < 0x1000) {
|
||||
buf.append(' ');
|
||||
}
|
||||
buf.append(Integer.toHexString(off));
|
||||
buf.append(':');
|
||||
int index = 0;
|
||||
for (index = 0; index < n; index++) {
|
||||
if ((index % 8) == 0) {
|
||||
buf.append(' ');
|
||||
}
|
||||
buf.append(Integer.toHexString((data[off + index] & 0xF0) >> 4));
|
||||
buf.append(Integer.toHexString((data[off + index] & 0x0F) >> 0));
|
||||
}
|
||||
// for incomplete lines
|
||||
if (index < 32) {
|
||||
for (int i = index; i < 32; i++) {
|
||||
if ((i % 8) == 0) {
|
||||
buf.append(' ');
|
||||
}
|
||||
buf.append(" ");
|
||||
}
|
||||
}
|
||||
buf.append(" ");
|
||||
for (index = 0; index < n; index++) {
|
||||
if ((index % 8) == 0) {
|
||||
buf.append(' ');
|
||||
}
|
||||
int ch = data[off + index] & 0xFF;
|
||||
buf.append(((ch > ' ') && (ch < 127)) ? (char) ch : '.');
|
||||
}
|
||||
buf.append("\n");
|
||||
|
||||
// limit message size
|
||||
if (off + 32 >= 2048) {
|
||||
buf.append("....\n");
|
||||
break;
|
||||
}
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,446 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
import javax.jmdns.impl.constants.DNSRecordClass;
|
||||
|
||||
/**
|
||||
* An outgoing DNS message.
|
||||
*
|
||||
* @author Arthur van Hoff, Rick Blair, Werner Randelshofer
|
||||
*/
|
||||
public final class DNSOutgoing extends DNSMessage {
|
||||
|
||||
public static class MessageOutputStream extends ByteArrayOutputStream {
|
||||
private final DNSOutgoing _out;
|
||||
|
||||
private final int _offset;
|
||||
|
||||
/**
|
||||
* Creates a new message stream, with a buffer capacity of the specified size, in bytes.
|
||||
*
|
||||
* @param size
|
||||
* the initial size.
|
||||
* @exception IllegalArgumentException
|
||||
* if size is negative.
|
||||
*/
|
||||
MessageOutputStream(int size, DNSOutgoing out) {
|
||||
this(size, out, 0);
|
||||
}
|
||||
|
||||
MessageOutputStream(int size, DNSOutgoing out, int offset) {
|
||||
super(size);
|
||||
_out = out;
|
||||
_offset = offset;
|
||||
}
|
||||
|
||||
void writeByte(int value) {
|
||||
this.write(value & 0xFF);
|
||||
}
|
||||
|
||||
void writeBytes(String str, int off, int len) {
|
||||
for (int i = 0; i < len; i++) {
|
||||
writeByte(str.charAt(off + i));
|
||||
}
|
||||
}
|
||||
|
||||
void writeBytes(byte data[]) {
|
||||
if (data != null) {
|
||||
writeBytes(data, 0, data.length);
|
||||
}
|
||||
}
|
||||
|
||||
void writeBytes(byte data[], int off, int len) {
|
||||
for (int i = 0; i < len; i++) {
|
||||
writeByte(data[off + i]);
|
||||
}
|
||||
}
|
||||
|
||||
void writeShort(int value) {
|
||||
writeByte(value >> 8);
|
||||
writeByte(value);
|
||||
}
|
||||
|
||||
void writeInt(int value) {
|
||||
writeShort(value >> 16);
|
||||
writeShort(value);
|
||||
}
|
||||
|
||||
void writeUTF(String str, int off, int len) {
|
||||
// compute utf length
|
||||
int utflen = 0;
|
||||
for (int i = 0; i < len; i++) {
|
||||
int ch = str.charAt(off + i);
|
||||
if ((ch >= 0x0001) && (ch <= 0x007F)) {
|
||||
utflen += 1;
|
||||
} else {
|
||||
if (ch > 0x07FF) {
|
||||
utflen += 3;
|
||||
} else {
|
||||
utflen += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
// write utf length
|
||||
writeByte(utflen);
|
||||
// write utf data
|
||||
for (int i = 0; i < len; i++) {
|
||||
int ch = str.charAt(off + i);
|
||||
if ((ch >= 0x0001) && (ch <= 0x007F)) {
|
||||
writeByte(ch);
|
||||
} else {
|
||||
if (ch > 0x07FF) {
|
||||
writeByte(0xE0 | ((ch >> 12) & 0x0F));
|
||||
writeByte(0x80 | ((ch >> 6) & 0x3F));
|
||||
writeByte(0x80 | ((ch >> 0) & 0x3F));
|
||||
} else {
|
||||
writeByte(0xC0 | ((ch >> 6) & 0x1F));
|
||||
writeByte(0x80 | ((ch >> 0) & 0x3F));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void writeName(String name) {
|
||||
writeName(name, true);
|
||||
}
|
||||
|
||||
void writeName(String name, boolean useCompression) {
|
||||
String aName = name;
|
||||
while (true) {
|
||||
int n = aName.indexOf('.');
|
||||
if (n < 0) {
|
||||
n = aName.length();
|
||||
}
|
||||
if (n <= 0) {
|
||||
writeByte(0);
|
||||
return;
|
||||
}
|
||||
String label = aName.substring(0, n);
|
||||
if (useCompression && USE_DOMAIN_NAME_COMPRESSION) {
|
||||
Integer offset = _out._names.get(aName);
|
||||
if (offset != null) {
|
||||
int val = offset.intValue();
|
||||
writeByte((val >> 8) | 0xC0);
|
||||
writeByte(val & 0xFF);
|
||||
return;
|
||||
}
|
||||
_out._names.put(aName, Integer.valueOf(this.size() + _offset));
|
||||
writeUTF(label, 0, label.length());
|
||||
} else {
|
||||
writeUTF(label, 0, label.length());
|
||||
}
|
||||
aName = aName.substring(n);
|
||||
if (aName.startsWith(".")) {
|
||||
aName = aName.substring(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void writeQuestion(DNSQuestion question) {
|
||||
writeName(question.getName());
|
||||
writeShort(question.getRecordType().indexValue());
|
||||
writeShort(question.getRecordClass().indexValue());
|
||||
}
|
||||
|
||||
void writeRecord(DNSRecord rec, long now) {
|
||||
writeName(rec.getName());
|
||||
writeShort(rec.getRecordType().indexValue());
|
||||
writeShort(rec.getRecordClass().indexValue() | ((rec.isUnique() && _out.isMulticast()) ? DNSRecordClass.CLASS_UNIQUE : 0));
|
||||
writeInt((now == 0) ? rec.getTTL() : rec.getRemainingTTL(now));
|
||||
|
||||
// We need to take into account the 2 size bytes
|
||||
MessageOutputStream record = new MessageOutputStream(512, _out, _offset + this.size() + 2);
|
||||
rec.write(record);
|
||||
byte[] byteArray = record.toByteArray();
|
||||
|
||||
writeShort(byteArray.length);
|
||||
write(byteArray, 0, byteArray.length);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* This can be used to turn off domain name compression. This was helpful for tracking problems interacting with other mdns implementations.
|
||||
*/
|
||||
public static boolean USE_DOMAIN_NAME_COMPRESSION = true;
|
||||
|
||||
Map<String, Integer> _names;
|
||||
|
||||
private int _maxUDPPayload;
|
||||
|
||||
private final MessageOutputStream _questionsBytes;
|
||||
|
||||
private final MessageOutputStream _answersBytes;
|
||||
|
||||
private final MessageOutputStream _authoritativeAnswersBytes;
|
||||
|
||||
private final MessageOutputStream _additionalsAnswersBytes;
|
||||
|
||||
private final static int HEADER_SIZE = 12;
|
||||
|
||||
/**
|
||||
* Create an outgoing multicast query or response.
|
||||
*
|
||||
* @param flags
|
||||
*/
|
||||
public DNSOutgoing(int flags) {
|
||||
this(flags, true, DNSConstants.MAX_MSG_TYPICAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an outgoing query or response.
|
||||
*
|
||||
* @param flags
|
||||
* @param multicast
|
||||
*/
|
||||
public DNSOutgoing(int flags, boolean multicast) {
|
||||
this(flags, multicast, DNSConstants.MAX_MSG_TYPICAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an outgoing query or response.
|
||||
*
|
||||
* @param flags
|
||||
* @param multicast
|
||||
* @param senderUDPPayload
|
||||
* The sender's UDP payload size is the number of bytes of the largest UDP payload that can be reassembled and delivered in the sender's network stack.
|
||||
*/
|
||||
public DNSOutgoing(int flags, boolean multicast, int senderUDPPayload) {
|
||||
super(flags, 0, multicast);
|
||||
_names = new HashMap<String, Integer>();
|
||||
_maxUDPPayload = (senderUDPPayload > 0 ? senderUDPPayload : DNSConstants.MAX_MSG_TYPICAL);
|
||||
_questionsBytes = new MessageOutputStream(senderUDPPayload, this);
|
||||
_answersBytes = new MessageOutputStream(senderUDPPayload, this);
|
||||
_authoritativeAnswersBytes = new MessageOutputStream(senderUDPPayload, this);
|
||||
_additionalsAnswersBytes = new MessageOutputStream(senderUDPPayload, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the number of byte available in the message.
|
||||
*
|
||||
* @return available space
|
||||
*/
|
||||
public int availableSpace() {
|
||||
return _maxUDPPayload - HEADER_SIZE - _questionsBytes.size() - _answersBytes.size() - _authoritativeAnswersBytes.size() - _additionalsAnswersBytes.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a question to the message.
|
||||
*
|
||||
* @param rec
|
||||
* @exception IOException
|
||||
*/
|
||||
public void addQuestion(DNSQuestion rec) throws IOException {
|
||||
MessageOutputStream record = new MessageOutputStream(512, this);
|
||||
record.writeQuestion(rec);
|
||||
byte[] byteArray = record.toByteArray();
|
||||
if (byteArray.length < this.availableSpace()) {
|
||||
_questions.add(rec);
|
||||
_questionsBytes.write(byteArray, 0, byteArray.length);
|
||||
} else {
|
||||
throw new IOException("message full");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an answer if it is not suppressed.
|
||||
*
|
||||
* @param in
|
||||
* @param rec
|
||||
* @exception IOException
|
||||
*/
|
||||
public void addAnswer(DNSIncoming in, DNSRecord rec) throws IOException {
|
||||
if ((in == null) || !rec.suppressedBy(in)) {
|
||||
this.addAnswer(rec, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an answer to the message.
|
||||
*
|
||||
* @param rec
|
||||
* @param now
|
||||
* @exception IOException
|
||||
*/
|
||||
public void addAnswer(DNSRecord rec, long now) throws IOException {
|
||||
if (rec != null) {
|
||||
if ((now == 0) || !rec.isExpired(now)) {
|
||||
MessageOutputStream record = new MessageOutputStream(512, this);
|
||||
record.writeRecord(rec, now);
|
||||
byte[] byteArray = record.toByteArray();
|
||||
if (byteArray.length < this.availableSpace()) {
|
||||
_answers.add(rec);
|
||||
_answersBytes.write(byteArray, 0, byteArray.length);
|
||||
} else {
|
||||
throw new IOException("message full");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an authoritative answer to the message.
|
||||
*
|
||||
* @param rec
|
||||
* @exception IOException
|
||||
*/
|
||||
public void addAuthorativeAnswer(DNSRecord rec) throws IOException {
|
||||
MessageOutputStream record = new MessageOutputStream(512, this);
|
||||
record.writeRecord(rec, 0);
|
||||
byte[] byteArray = record.toByteArray();
|
||||
if (byteArray.length < this.availableSpace()) {
|
||||
_authoritativeAnswers.add(rec);
|
||||
_authoritativeAnswersBytes.write(byteArray, 0, byteArray.length);
|
||||
} else {
|
||||
throw new IOException("message full");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an additional answer to the record. Omit if there is no room.
|
||||
*
|
||||
* @param in
|
||||
* @param rec
|
||||
* @exception IOException
|
||||
*/
|
||||
public void addAdditionalAnswer(DNSIncoming in, DNSRecord rec) throws IOException {
|
||||
MessageOutputStream record = new MessageOutputStream(512, this);
|
||||
record.writeRecord(rec, 0);
|
||||
byte[] byteArray = record.toByteArray();
|
||||
if (byteArray.length < this.availableSpace()) {
|
||||
_additionals.add(rec);
|
||||
_additionalsAnswersBytes.write(byteArray, 0, byteArray.length);
|
||||
} else {
|
||||
throw new IOException("message full");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the final message buffer to be send and returns it.
|
||||
*
|
||||
* @return bytes to send.
|
||||
*/
|
||||
public byte[] data() {
|
||||
long now = System.currentTimeMillis(); // System.currentTimeMillis()
|
||||
_names.clear();
|
||||
|
||||
MessageOutputStream message = new MessageOutputStream(_maxUDPPayload, this);
|
||||
message.writeShort(_multicast ? 0 : this.getId());
|
||||
message.writeShort(this.getFlags());
|
||||
message.writeShort(this.getNumberOfQuestions());
|
||||
message.writeShort(this.getNumberOfAnswers());
|
||||
message.writeShort(this.getNumberOfAuthorities());
|
||||
message.writeShort(this.getNumberOfAdditionals());
|
||||
for (DNSQuestion question : _questions) {
|
||||
message.writeQuestion(question);
|
||||
}
|
||||
for (DNSRecord record : _answers) {
|
||||
message.writeRecord(record, now);
|
||||
}
|
||||
for (DNSRecord record : _authoritativeAnswers) {
|
||||
message.writeRecord(record, now);
|
||||
}
|
||||
for (DNSRecord record : _additionals) {
|
||||
message.writeRecord(record, now);
|
||||
}
|
||||
return message.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Debugging.
|
||||
*/
|
||||
String print(boolean dump) {
|
||||
StringBuilder buf = new StringBuilder();
|
||||
buf.append(this.print());
|
||||
if (dump) {
|
||||
buf.append(this.print(this.data()));
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuffer buf = new StringBuffer();
|
||||
buf.append(isQuery() ? "dns[query:" : "dns[response:");
|
||||
buf.append(" id=0x");
|
||||
buf.append(Integer.toHexString(this.getId()));
|
||||
if (this.getFlags() != 0) {
|
||||
buf.append(", flags=0x");
|
||||
buf.append(Integer.toHexString(this.getFlags()));
|
||||
if (this.isResponse()) {
|
||||
buf.append(":r");
|
||||
}
|
||||
if (this.isAuthoritativeAnswer()) {
|
||||
buf.append(":aa");
|
||||
}
|
||||
if (this.isTruncated()) {
|
||||
buf.append(":tc");
|
||||
}
|
||||
}
|
||||
if (this.getNumberOfQuestions() > 0) {
|
||||
buf.append(", questions=");
|
||||
buf.append(this.getNumberOfQuestions());
|
||||
}
|
||||
if (this.getNumberOfAnswers() > 0) {
|
||||
buf.append(", answers=");
|
||||
buf.append(this.getNumberOfAnswers());
|
||||
}
|
||||
if (this.getNumberOfAuthorities() > 0) {
|
||||
buf.append(", authorities=");
|
||||
buf.append(this.getNumberOfAuthorities());
|
||||
}
|
||||
if (this.getNumberOfAdditionals() > 0) {
|
||||
buf.append(", additionals=");
|
||||
buf.append(this.getNumberOfAdditionals());
|
||||
}
|
||||
if (this.getNumberOfQuestions() > 0) {
|
||||
buf.append("\nquestions:");
|
||||
for (DNSQuestion question : _questions) {
|
||||
buf.append("\n\t");
|
||||
buf.append(question);
|
||||
}
|
||||
}
|
||||
if (this.getNumberOfAnswers() > 0) {
|
||||
buf.append("\nanswers:");
|
||||
for (DNSRecord record : _answers) {
|
||||
buf.append("\n\t");
|
||||
buf.append(record);
|
||||
}
|
||||
}
|
||||
if (this.getNumberOfAuthorities() > 0) {
|
||||
buf.append("\nauthorities:");
|
||||
for (DNSRecord record : _authoritativeAnswers) {
|
||||
buf.append("\n\t");
|
||||
buf.append(record);
|
||||
}
|
||||
}
|
||||
if (this.getNumberOfAdditionals() > 0) {
|
||||
buf.append("\nadditionals:");
|
||||
for (DNSRecord record : _additionals) {
|
||||
buf.append("\n\t");
|
||||
buf.append(record);
|
||||
}
|
||||
}
|
||||
buf.append("\nnames=");
|
||||
buf.append(_names);
|
||||
buf.append("]");
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the maxUDPPayload
|
||||
*/
|
||||
public int getMaxUDPPayload() {
|
||||
return this._maxUDPPayload;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,328 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.ServiceInfo;
|
||||
import javax.jmdns.ServiceInfo.Fields;
|
||||
import javax.jmdns.impl.JmDNSImpl.ServiceTypeEntry;
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
import javax.jmdns.impl.constants.DNSRecordClass;
|
||||
import javax.jmdns.impl.constants.DNSRecordType;
|
||||
|
||||
/**
|
||||
* A DNS question.
|
||||
*
|
||||
* @author Arthur van Hoff, Pierre Frisch
|
||||
*/
|
||||
public class DNSQuestion extends DNSEntry {
|
||||
private static Logger logger = Logger.getLogger(DNSQuestion.class.getName());
|
||||
|
||||
/**
|
||||
* Address question.
|
||||
*/
|
||||
private static class DNS4Address extends DNSQuestion {
|
||||
DNS4Address(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
|
||||
super(name, type, recordClass, unique);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addAnswers(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers) {
|
||||
DNSRecord answer = jmDNSImpl.getLocalHost().getDNSAddressRecord(this.getRecordType(), DNSRecordClass.UNIQUE, DNSConstants.DNS_TTL);
|
||||
if (answer != null) {
|
||||
answers.add(answer);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean iAmTheOnlyOne(JmDNSImpl jmDNSImpl) {
|
||||
String name = this.getName().toLowerCase();
|
||||
return jmDNSImpl.getLocalHost().getName().equals(name) || jmDNSImpl.getServices().keySet().contains(name);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Address question.
|
||||
*/
|
||||
private static class DNS6Address extends DNSQuestion {
|
||||
DNS6Address(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
|
||||
super(name, type, recordClass, unique);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addAnswers(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers) {
|
||||
DNSRecord answer = jmDNSImpl.getLocalHost().getDNSAddressRecord(this.getRecordType(), DNSRecordClass.UNIQUE, DNSConstants.DNS_TTL);
|
||||
if (answer != null) {
|
||||
answers.add(answer);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean iAmTheOnlyOne(JmDNSImpl jmDNSImpl) {
|
||||
String name = this.getName().toLowerCase();
|
||||
return jmDNSImpl.getLocalHost().getName().equals(name) || jmDNSImpl.getServices().keySet().contains(name);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Host Information question.
|
||||
*/
|
||||
private static class HostInformation extends DNSQuestion {
|
||||
HostInformation(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
|
||||
super(name, type, recordClass, unique);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pointer question.
|
||||
*/
|
||||
private static class Pointer extends DNSQuestion {
|
||||
Pointer(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
|
||||
super(name, type, recordClass, unique);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addAnswers(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers) {
|
||||
// find matching services
|
||||
for (ServiceInfo serviceInfo : jmDNSImpl.getServices().values()) {
|
||||
this.addAnswersForServiceInfo(jmDNSImpl, answers, (ServiceInfoImpl) serviceInfo);
|
||||
}
|
||||
if (this.isServicesDiscoveryMetaQuery()) {
|
||||
for (String serviceType : jmDNSImpl.getServiceTypes().keySet()) {
|
||||
ServiceTypeEntry typeEntry = jmDNSImpl.getServiceTypes().get(serviceType);
|
||||
answers.add(new DNSRecord.Pointer("_services._dns-sd._udp.local.", DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE, DNSConstants.DNS_TTL, typeEntry.getType()));
|
||||
}
|
||||
} else if (this.isReverseLookup()) {
|
||||
String ipValue = this.getQualifiedNameMap().get(Fields.Instance);
|
||||
if ((ipValue != null) && (ipValue.length() > 0)) {
|
||||
InetAddress address = jmDNSImpl.getLocalHost().getInetAddress();
|
||||
String hostIPAddress = (address != null ? address.getHostAddress() : "");
|
||||
if (ipValue.equalsIgnoreCase(hostIPAddress)) {
|
||||
if (this.isV4ReverseLookup()) {
|
||||
answers.add(jmDNSImpl.getLocalHost().getDNSReverseAddressRecord(DNSRecordType.TYPE_A, DNSRecordClass.NOT_UNIQUE, DNSConstants.DNS_TTL));
|
||||
}
|
||||
if (this.isV6ReverseLookup()) {
|
||||
answers.add(jmDNSImpl.getLocalHost().getDNSReverseAddressRecord(DNSRecordType.TYPE_AAAA, DNSRecordClass.NOT_UNIQUE, DNSConstants.DNS_TTL));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (this.isDomainDiscoveryQuery()) {
|
||||
// FIXME [PJYF Nov 16 2010] We do not currently support domain discovery
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Service question.
|
||||
*/
|
||||
private static class Service extends DNSQuestion {
|
||||
Service(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
|
||||
super(name, type, recordClass, unique);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addAnswers(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers) {
|
||||
String loname = this.getName().toLowerCase();
|
||||
if (jmDNSImpl.getLocalHost().getName().equalsIgnoreCase(loname)) {
|
||||
// type = DNSConstants.TYPE_A;
|
||||
answers.addAll(jmDNSImpl.getLocalHost().answers(this.getRecordClass(), this.isUnique(), DNSConstants.DNS_TTL));
|
||||
return;
|
||||
}
|
||||
// Service type request
|
||||
if (jmDNSImpl.getServiceTypes().containsKey(loname)) {
|
||||
DNSQuestion question = new Pointer(this.getName(), DNSRecordType.TYPE_PTR, this.getRecordClass(), this.isUnique());
|
||||
question.addAnswers(jmDNSImpl, answers);
|
||||
return;
|
||||
}
|
||||
|
||||
this.addAnswersForServiceInfo(jmDNSImpl, answers, (ServiceInfoImpl) jmDNSImpl.getServices().get(loname));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean iAmTheOnlyOne(JmDNSImpl jmDNSImpl) {
|
||||
String name = this.getName().toLowerCase();
|
||||
return jmDNSImpl.getLocalHost().getName().equals(name) || jmDNSImpl.getServices().keySet().contains(name);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Text question.
|
||||
*/
|
||||
private static class Text extends DNSQuestion {
|
||||
Text(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
|
||||
super(name, type, recordClass, unique);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addAnswers(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers) {
|
||||
this.addAnswersForServiceInfo(jmDNSImpl, answers, (ServiceInfoImpl) jmDNSImpl.getServices().get(this.getName().toLowerCase()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean iAmTheOnlyOne(JmDNSImpl jmDNSImpl) {
|
||||
String name = this.getName().toLowerCase();
|
||||
return jmDNSImpl.getLocalHost().getName().equals(name) || jmDNSImpl.getServices().keySet().contains(name);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* AllRecords question.
|
||||
*/
|
||||
private static class AllRecords extends DNSQuestion {
|
||||
AllRecords(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
|
||||
super(name, type, recordClass, unique);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSameType(DNSEntry entry) {
|
||||
// We match all non null entry
|
||||
return (entry != null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addAnswers(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers) {
|
||||
String loname = this.getName().toLowerCase();
|
||||
if (jmDNSImpl.getLocalHost().getName().equalsIgnoreCase(loname)) {
|
||||
// type = DNSConstants.TYPE_A;
|
||||
answers.addAll(jmDNSImpl.getLocalHost().answers(this.getRecordClass(), this.isUnique(), DNSConstants.DNS_TTL));
|
||||
return;
|
||||
}
|
||||
// Service type request
|
||||
if (jmDNSImpl.getServiceTypes().containsKey(loname)) {
|
||||
DNSQuestion question = new Pointer(this.getName(), DNSRecordType.TYPE_PTR, this.getRecordClass(), this.isUnique());
|
||||
question.addAnswers(jmDNSImpl, answers);
|
||||
return;
|
||||
}
|
||||
|
||||
this.addAnswersForServiceInfo(jmDNSImpl, answers, (ServiceInfoImpl) jmDNSImpl.getServices().get(loname));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean iAmTheOnlyOne(JmDNSImpl jmDNSImpl) {
|
||||
String name = this.getName().toLowerCase();
|
||||
return jmDNSImpl.getLocalHost().getName().equals(name) || jmDNSImpl.getServices().keySet().contains(name);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
DNSQuestion(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
|
||||
super(name, type, recordClass, unique);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a question.
|
||||
*
|
||||
* @param name
|
||||
* DNS name to be resolved
|
||||
* @param type
|
||||
* Record type to resolve
|
||||
* @param recordClass
|
||||
* Record class to resolve
|
||||
* @param unique
|
||||
* Request unicast response (Currently not supported in this implementation)
|
||||
* @return new question
|
||||
*/
|
||||
public static DNSQuestion newQuestion(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
|
||||
switch (type) {
|
||||
case TYPE_A:
|
||||
return new DNS4Address(name, type, recordClass, unique);
|
||||
case TYPE_A6:
|
||||
return new DNS6Address(name, type, recordClass, unique);
|
||||
case TYPE_AAAA:
|
||||
return new DNS6Address(name, type, recordClass, unique);
|
||||
case TYPE_ANY:
|
||||
return new AllRecords(name, type, recordClass, unique);
|
||||
case TYPE_HINFO:
|
||||
return new HostInformation(name, type, recordClass, unique);
|
||||
case TYPE_PTR:
|
||||
return new Pointer(name, type, recordClass, unique);
|
||||
case TYPE_SRV:
|
||||
return new Service(name, type, recordClass, unique);
|
||||
case TYPE_TXT:
|
||||
return new Text(name, type, recordClass, unique);
|
||||
default:
|
||||
return new DNSQuestion(name, type, recordClass, unique);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this question is answered by a given DNS record.
|
||||
*/
|
||||
boolean answeredBy(DNSEntry rec) {
|
||||
return this.isSameRecordClass(rec) && this.isSameType(rec) && this.getName().equals(rec.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds answers to the list for our question.
|
||||
*
|
||||
* @param jmDNSImpl
|
||||
* DNS holding the records
|
||||
* @param answers
|
||||
* List of previous answer to append.
|
||||
*/
|
||||
public void addAnswers(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers) {
|
||||
// By default we do nothing
|
||||
}
|
||||
|
||||
protected void addAnswersForServiceInfo(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers, ServiceInfoImpl info) {
|
||||
if ((info != null) && info.isAnnounced()) {
|
||||
if (this.getName().equalsIgnoreCase(info.getQualifiedName()) || this.getName().equalsIgnoreCase(info.getType()) || this.getName().equalsIgnoreCase(info.getTypeWithSubtype())) {
|
||||
answers.addAll(jmDNSImpl.getLocalHost().answers(this.getRecordClass(), DNSRecordClass.UNIQUE, DNSConstants.DNS_TTL));
|
||||
answers.addAll(info.answers(this.getRecordClass(), DNSRecordClass.UNIQUE, DNSConstants.DNS_TTL, jmDNSImpl.getLocalHost()));
|
||||
}
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
logger.finer(jmDNSImpl.getName() + " DNSQuestion(" + this.getName() + ").addAnswersForServiceInfo(): info: " + info + "\n" + answers);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSEntry#isStale(long)
|
||||
*/
|
||||
@Override
|
||||
public boolean isStale(long now) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSEntry#isExpired(long)
|
||||
*/
|
||||
@Override
|
||||
public boolean isExpired(long now) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if we are the only to be able to answer that question.
|
||||
*
|
||||
* @param jmDNSImpl
|
||||
* DNS holding the records
|
||||
* @return <code>true</code> if we are the only one with the answer to the question, <code>false</code> otherwise.
|
||||
*/
|
||||
public boolean iAmTheOnlyOne(JmDNSImpl jmDNSImpl) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSEntry#toString(java.lang.StringBuilder)
|
||||
*/
|
||||
@Override
|
||||
public void toString(StringBuilder aLog) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,572 @@
|
|||
// Licensed under Apache License version 2.0
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.impl.constants.DNSState;
|
||||
import javax.jmdns.impl.tasks.DNSTask;
|
||||
|
||||
/**
|
||||
* Sets of methods to manage the state machine.<br/>
|
||||
* <b>Implementation note:</b> This interface is accessed from multiple threads. The implementation must be thread safe.
|
||||
*
|
||||
* @author Pierre Frisch
|
||||
*/
|
||||
public interface DNSStatefulObject {
|
||||
|
||||
/**
|
||||
* This class define a semaphore. On this multiple threads can wait the arrival of one event. Thread wait for a maximum defined by the timeout.
|
||||
* <p>
|
||||
* Implementation note: this class is based on {@link java.util.concurrent.Semaphore} so that they can be released by the timeout timer.
|
||||
* </p>
|
||||
*
|
||||
* @author Pierre Frisch
|
||||
*/
|
||||
public static final class DNSStatefulObjectSemaphore {
|
||||
private static Logger logger = Logger.getLogger(DNSStatefulObjectSemaphore.class.getName());
|
||||
|
||||
private final String _name;
|
||||
|
||||
private final ConcurrentMap<Thread, Semaphore> _semaphores;
|
||||
|
||||
/**
|
||||
* @param name
|
||||
* Semaphore name for debugging purposes.
|
||||
*/
|
||||
public DNSStatefulObjectSemaphore(String name) {
|
||||
super();
|
||||
_name = name;
|
||||
_semaphores = new ConcurrentHashMap<Thread, Semaphore>(50);
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocks the current thread until the event arrives or the timeout expires.
|
||||
*
|
||||
* @param timeout
|
||||
* wait period for the event
|
||||
*/
|
||||
public void waitForEvent(long timeout) {
|
||||
Thread thread = Thread.currentThread();
|
||||
Semaphore semaphore = _semaphores.get(thread);
|
||||
if (semaphore == null) {
|
||||
semaphore = new Semaphore(1, true);
|
||||
semaphore.drainPermits();
|
||||
_semaphores.putIfAbsent(thread, semaphore);
|
||||
}
|
||||
semaphore = _semaphores.get(thread);
|
||||
try {
|
||||
semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException exception) {
|
||||
logger.log(Level.FINER, "Exception ", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Signals the semaphore when the event arrives.
|
||||
*/
|
||||
public void signalEvent() {
|
||||
Collection<Semaphore> semaphores = _semaphores.values();
|
||||
for (Semaphore semaphore : semaphores) {
|
||||
semaphore.release();
|
||||
semaphores.remove(semaphore);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder aLog = new StringBuilder(1000);
|
||||
aLog.append("Semaphore: ");
|
||||
aLog.append(this._name);
|
||||
if (_semaphores.size() == 0) {
|
||||
aLog.append(" no semaphores.");
|
||||
} else {
|
||||
aLog.append(" semaphores:\n");
|
||||
for (Thread thread : _semaphores.keySet()) {
|
||||
aLog.append("\tThread: ");
|
||||
aLog.append(thread.getName());
|
||||
aLog.append(' ');
|
||||
aLog.append(_semaphores.get(thread));
|
||||
aLog.append('\n');
|
||||
}
|
||||
}
|
||||
return aLog.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class DefaultImplementation extends ReentrantLock implements DNSStatefulObject {
|
||||
private static Logger logger = Logger.getLogger(DefaultImplementation.class.getName());
|
||||
|
||||
private static final long serialVersionUID = -3264781576883412227L;
|
||||
|
||||
private volatile JmDNSImpl _dns;
|
||||
|
||||
protected volatile DNSTask _task;
|
||||
|
||||
protected volatile DNSState _state;
|
||||
|
||||
private final DNSStatefulObjectSemaphore _announcing;
|
||||
|
||||
private final DNSStatefulObjectSemaphore _canceling;
|
||||
|
||||
public DefaultImplementation() {
|
||||
super();
|
||||
_dns = null;
|
||||
_task = null;
|
||||
_state = DNSState.PROBING_1;
|
||||
_announcing = new DNSStatefulObjectSemaphore("Announce");
|
||||
_canceling = new DNSStatefulObjectSemaphore("Cancel");
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public JmDNSImpl getDns() {
|
||||
return this._dns;
|
||||
}
|
||||
|
||||
protected void setDns(JmDNSImpl dns) {
|
||||
this._dns = dns;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void associateWithTask(DNSTask task, DNSState state) {
|
||||
if (this._task == null && this._state == state) {
|
||||
this.lock();
|
||||
try {
|
||||
if (this._task == null && this._state == state) {
|
||||
this.setTask(task);
|
||||
}
|
||||
} finally {
|
||||
this.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void removeAssociationWithTask(DNSTask task) {
|
||||
if (this._task == task) {
|
||||
this.lock();
|
||||
try {
|
||||
if (this._task == task) {
|
||||
this.setTask(null);
|
||||
}
|
||||
} finally {
|
||||
this.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isAssociatedWithTask(DNSTask task, DNSState state) {
|
||||
this.lock();
|
||||
try {
|
||||
return this._task == task && this._state == state;
|
||||
} finally {
|
||||
this.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
protected void setTask(DNSTask task) {
|
||||
this._task = task;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param state
|
||||
* the state to set
|
||||
*/
|
||||
protected void setState(DNSState state) {
|
||||
this.lock();
|
||||
try {
|
||||
this._state = state;
|
||||
if (this.isAnnounced()) {
|
||||
_announcing.signalEvent();
|
||||
}
|
||||
if (this.isCanceled()) {
|
||||
_canceling.signalEvent();
|
||||
// clear any waiting announcing
|
||||
_announcing.signalEvent();
|
||||
}
|
||||
} finally {
|
||||
this.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean advanceState(DNSTask task) {
|
||||
boolean result = true;
|
||||
if (this._task == task) {
|
||||
this.lock();
|
||||
try {
|
||||
if (this._task == task) {
|
||||
this.setState(this._state.advance());
|
||||
} else {
|
||||
logger.warning("Trying to advance state whhen not the owner. owner: " + this._task + " perpetrator: " + task);
|
||||
}
|
||||
} finally {
|
||||
this.unlock();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean revertState() {
|
||||
boolean result = true;
|
||||
if (!this.willCancel()) {
|
||||
this.lock();
|
||||
try {
|
||||
if (!this.willCancel()) {
|
||||
this.setState(this._state.revert());
|
||||
this.setTask(null);
|
||||
}
|
||||
} finally {
|
||||
this.unlock();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean cancelState() {
|
||||
boolean result = false;
|
||||
if (!this.willCancel()) {
|
||||
this.lock();
|
||||
try {
|
||||
if (!this.willCancel()) {
|
||||
this.setState(DNSState.CANCELING_1);
|
||||
this.setTask(null);
|
||||
result = true;
|
||||
}
|
||||
} finally {
|
||||
this.unlock();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean closeState() {
|
||||
boolean result = false;
|
||||
if (!this.willClose()) {
|
||||
this.lock();
|
||||
try {
|
||||
if (!this.willClose()) {
|
||||
this.setState(DNSState.CLOSING);
|
||||
this.setTask(null);
|
||||
result = true;
|
||||
}
|
||||
} finally {
|
||||
this.unlock();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean recoverState() {
|
||||
boolean result = false;
|
||||
this.lock();
|
||||
try {
|
||||
this.setState(DNSState.PROBING_1);
|
||||
this.setTask(null);
|
||||
} finally {
|
||||
this.unlock();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isProbing() {
|
||||
return this._state.isProbing();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isAnnouncing() {
|
||||
return this._state.isAnnouncing();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isAnnounced() {
|
||||
return this._state.isAnnounced();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isCanceling() {
|
||||
return this._state.isCanceling();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isCanceled() {
|
||||
return this._state.isCanceled();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isClosing() {
|
||||
return this._state.isClosing();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isClosed() {
|
||||
return this._state.isClosed();
|
||||
}
|
||||
|
||||
private boolean willCancel() {
|
||||
return this._state.isCanceled() || this._state.isCanceling();
|
||||
}
|
||||
|
||||
private boolean willClose() {
|
||||
return this._state.isClosed() || this._state.isClosing();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean waitForAnnounced(long timeout) {
|
||||
if (!this.isAnnounced() && !this.willCancel()) {
|
||||
_announcing.waitForEvent(timeout + 10);
|
||||
}
|
||||
if (!this.isAnnounced()) {
|
||||
// When we run multihomed we need to check twice
|
||||
_announcing.waitForEvent(10);
|
||||
if (!this.isAnnounced()) {
|
||||
if (this.willCancel() || this.willClose()) {
|
||||
logger.fine("Wait for announced cancelled: " + this);
|
||||
} else {
|
||||
logger.warning("Wait for announced timed out: " + this);
|
||||
}
|
||||
}
|
||||
}
|
||||
return this.isAnnounced();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean waitForCanceled(long timeout) {
|
||||
if (!this.isCanceled()) {
|
||||
_canceling.waitForEvent(timeout);
|
||||
}
|
||||
if (!this.isCanceled()) {
|
||||
// When we run multihomed we need to check twice
|
||||
_canceling.waitForEvent(10);
|
||||
if (!this.isCanceled() && !this.willClose()) {
|
||||
logger.warning("Wait for canceled timed out: " + this);
|
||||
}
|
||||
}
|
||||
return this.isCanceled();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
try {
|
||||
return (_dns != null ? "DNS: " + _dns.getName() + " [" + _dns.getInetAddress() + "]" : "NO DNS") + " state: " + _state + " task: " + _task;
|
||||
} catch (IOException exception) {
|
||||
return (_dns != null ? "DNS: " + _dns.getName() : "NO DNS") + " state: " + _state + " task: " + _task;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the DNS associated with this object.
|
||||
*
|
||||
* @return DNS resolver
|
||||
*/
|
||||
public JmDNSImpl getDns();
|
||||
|
||||
/**
|
||||
* Sets the task associated with this Object.
|
||||
*
|
||||
* @param task
|
||||
* associated task
|
||||
* @param state
|
||||
* state of the task
|
||||
*/
|
||||
public void associateWithTask(DNSTask task, DNSState state);
|
||||
|
||||
/**
|
||||
* Remove the association of the task with this Object.
|
||||
*
|
||||
* @param task
|
||||
* associated task
|
||||
*/
|
||||
public void removeAssociationWithTask(DNSTask task);
|
||||
|
||||
/**
|
||||
* Checks if this object is associated with the task and in the same state.
|
||||
*
|
||||
* @param task
|
||||
* associated task
|
||||
* @param state
|
||||
* state of the task
|
||||
* @return <code>true</code> is the task is associated with this object, <code>false</code> otherwise.
|
||||
*/
|
||||
public boolean isAssociatedWithTask(DNSTask task, DNSState state);
|
||||
|
||||
/**
|
||||
* Sets the state and notifies all objects that wait on the ServiceInfo.
|
||||
*
|
||||
* @param task
|
||||
* associated task
|
||||
* @return <code>true</code if the state was changed by this thread, <code>false</code> otherwise.
|
||||
* @see DNSState#advance()
|
||||
*/
|
||||
public boolean advanceState(DNSTask task);
|
||||
|
||||
/**
|
||||
* Sets the state and notifies all objects that wait on the ServiceInfo.
|
||||
*
|
||||
* @return <code>true</code if the state was changed by this thread, <code>false</code> otherwise.
|
||||
* @see DNSState#revert()
|
||||
*/
|
||||
public boolean revertState();
|
||||
|
||||
/**
|
||||
* Sets the state and notifies all objects that wait on the ServiceInfo.
|
||||
*
|
||||
* @return <code>true</code if the state was changed by this thread, <code>false</code> otherwise.
|
||||
*/
|
||||
public boolean cancelState();
|
||||
|
||||
/**
|
||||
* Sets the state and notifies all objects that wait on the ServiceInfo.
|
||||
*
|
||||
* @return <code>true</code if the state was changed by this thread, <code>false</code> otherwise.
|
||||
*/
|
||||
public boolean closeState();
|
||||
|
||||
/**
|
||||
* Sets the state and notifies all objects that wait on the ServiceInfo.
|
||||
*
|
||||
* @return <code>true</code if the state was changed by this thread, <code>false</code> otherwise.
|
||||
*/
|
||||
public boolean recoverState();
|
||||
|
||||
/**
|
||||
* Returns true, if this is a probing state.
|
||||
*
|
||||
* @return <code>true</code> if probing state, <code>false</code> otherwise
|
||||
*/
|
||||
public boolean isProbing();
|
||||
|
||||
/**
|
||||
* Returns true, if this is an announcing state.
|
||||
*
|
||||
* @return <code>true</code> if announcing state, <code>false</code> otherwise
|
||||
*/
|
||||
public boolean isAnnouncing();
|
||||
|
||||
/**
|
||||
* Returns true, if this is an announced state.
|
||||
*
|
||||
* @return <code>true</code> if announced state, <code>false</code> otherwise
|
||||
*/
|
||||
public boolean isAnnounced();
|
||||
|
||||
/**
|
||||
* Returns true, if this is a canceling state.
|
||||
*
|
||||
* @return <code>true</code> if canceling state, <code>false</code> otherwise
|
||||
*/
|
||||
public boolean isCanceling();
|
||||
|
||||
/**
|
||||
* Returns true, if this is a canceled state.
|
||||
*
|
||||
* @return <code>true</code> if canceled state, <code>false</code> otherwise
|
||||
*/
|
||||
public boolean isCanceled();
|
||||
|
||||
/**
|
||||
* Returns true, if this is a closing state.
|
||||
*
|
||||
* @return <code>true</code> if closing state, <code>false</code> otherwise
|
||||
*/
|
||||
public boolean isClosing();
|
||||
|
||||
/**
|
||||
* Returns true, if this is a closed state.
|
||||
*
|
||||
* @return <code>true</code> if closed state, <code>false</code> otherwise
|
||||
*/
|
||||
public boolean isClosed();
|
||||
|
||||
/**
|
||||
* Waits for the object to be announced.
|
||||
*
|
||||
* @param timeout
|
||||
* the maximum time to wait in milliseconds.
|
||||
* @return <code>true</code> if the object is announced, <code>false</code> otherwise
|
||||
*/
|
||||
public boolean waitForAnnounced(long timeout);
|
||||
|
||||
/**
|
||||
* Waits for the object to be canceled.
|
||||
*
|
||||
* @param timeout
|
||||
* the maximum time to wait in milliseconds.
|
||||
* @return <code>true</code> if the object is canceled, <code>false</code> otherwise
|
||||
*/
|
||||
public boolean waitForCanceled(long timeout);
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,474 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import javax.jmdns.impl.tasks.RecordReaper;
|
||||
import javax.jmdns.impl.tasks.Responder;
|
||||
import javax.jmdns.impl.tasks.resolver.ServiceInfoResolver;
|
||||
import javax.jmdns.impl.tasks.resolver.ServiceResolver;
|
||||
import javax.jmdns.impl.tasks.resolver.TypeResolver;
|
||||
import javax.jmdns.impl.tasks.state.Announcer;
|
||||
import javax.jmdns.impl.tasks.state.Canceler;
|
||||
import javax.jmdns.impl.tasks.state.Prober;
|
||||
import javax.jmdns.impl.tasks.state.Renewer;
|
||||
|
||||
/**
|
||||
* This class is used by JmDNS to start the various task required to run the DNS discovery. This interface is only there in order to support MANET modifications.
|
||||
* <p>
|
||||
* <b>Note: </b> This is not considered as part of the general public API of JmDNS.
|
||||
* </p>
|
||||
*
|
||||
* @author Pierre Frisch
|
||||
*/
|
||||
public interface DNSTaskStarter {
|
||||
|
||||
/**
|
||||
* DNSTaskStarter.Factory enable the creation of new instance of DNSTaskStarter.
|
||||
*/
|
||||
public static final class Factory {
|
||||
|
||||
private static volatile Factory _instance;
|
||||
private final ConcurrentMap<JmDNSImpl, DNSTaskStarter> _instances;
|
||||
|
||||
/**
|
||||
* This interface defines a delegate to the DNSTaskStarter class to enable subclassing.
|
||||
*/
|
||||
public static interface ClassDelegate {
|
||||
|
||||
/**
|
||||
* Allows the delegate the opportunity to construct and return a different DNSTaskStarter.
|
||||
*
|
||||
* @param jmDNSImpl
|
||||
* jmDNS instance
|
||||
* @return Should return a new DNSTaskStarter Object.
|
||||
* @see #classDelegate()
|
||||
* @see #setClassDelegate(ClassDelegate anObject)
|
||||
*/
|
||||
public DNSTaskStarter newDNSTaskStarter(JmDNSImpl jmDNSImpl);
|
||||
}
|
||||
|
||||
private static final AtomicReference<Factory.ClassDelegate> _databaseClassDelegate = new AtomicReference<Factory.ClassDelegate>();
|
||||
|
||||
private Factory() {
|
||||
super();
|
||||
_instances = new ConcurrentHashMap<JmDNSImpl, DNSTaskStarter>(20);
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns <code>delegate</code> as DNSTaskStarter's class delegate. The class delegate is optional.
|
||||
*
|
||||
* @param delegate
|
||||
* The object to set as DNSTaskStarter's class delegate.
|
||||
* @see #classDelegate()
|
||||
* @see DNSTaskStarter.Factory.ClassDelegate
|
||||
*/
|
||||
public static void setClassDelegate(Factory.ClassDelegate delegate) {
|
||||
_databaseClassDelegate.set(delegate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns DNSTaskStarter's class delegate.
|
||||
*
|
||||
* @return DNSTaskStarter's class delegate.
|
||||
* @see #setClassDelegate(ClassDelegate anObject)
|
||||
* @see DNSTaskStarter.Factory.ClassDelegate
|
||||
*/
|
||||
public static Factory.ClassDelegate classDelegate() {
|
||||
return _databaseClassDelegate.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new instance of DNSTaskStarter using the class delegate if it exists.
|
||||
*
|
||||
* @param jmDNSImpl
|
||||
* jmDNS instance
|
||||
* @return new instance of DNSTaskStarter
|
||||
*/
|
||||
protected static DNSTaskStarter newDNSTaskStarter(JmDNSImpl jmDNSImpl) {
|
||||
DNSTaskStarter instance = null;
|
||||
Factory.ClassDelegate delegate = _databaseClassDelegate.get();
|
||||
if (delegate != null) {
|
||||
instance = delegate.newDNSTaskStarter(jmDNSImpl);
|
||||
}
|
||||
return (instance != null ? instance : new DNSTaskStarterImpl(jmDNSImpl));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the instance of the DNSTaskStarter Factory.
|
||||
*
|
||||
* @return DNSTaskStarter Factory
|
||||
*/
|
||||
public static Factory getInstance() {
|
||||
if (_instance == null) {
|
||||
synchronized (DNSTaskStarter.Factory.class) {
|
||||
if (_instance == null) {
|
||||
_instance = new Factory();
|
||||
}
|
||||
}
|
||||
}
|
||||
return _instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the instance of the DNSTaskStarter for the JmDNS.
|
||||
*
|
||||
* @param jmDNSImpl
|
||||
* jmDNS instance
|
||||
* @return the DNSTaskStarter
|
||||
*/
|
||||
public DNSTaskStarter getStarter(JmDNSImpl jmDNSImpl) {
|
||||
DNSTaskStarter starter = _instances.get(jmDNSImpl);
|
||||
if (starter == null) {
|
||||
_instances.putIfAbsent(jmDNSImpl, newDNSTaskStarter(jmDNSImpl));
|
||||
starter = _instances.get(jmDNSImpl);
|
||||
}
|
||||
return starter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispose of the DNSTaskStarter instance associated with this JmDNS.
|
||||
*
|
||||
* @param jmDNSImpl
|
||||
* jmDNS instance
|
||||
*/
|
||||
public void disposeStarter(JmDNSImpl jmDNSImpl) {
|
||||
_instances.remove(jmDNSImpl);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static final class DNSTaskStarterImpl implements DNSTaskStarter {
|
||||
|
||||
private final JmDNSImpl _jmDNSImpl;
|
||||
|
||||
/**
|
||||
* The timer is used to dispatch all outgoing messages of JmDNS. It is also used to dispatch maintenance tasks for the DNS cache.
|
||||
*/
|
||||
private final Timer _timer;
|
||||
|
||||
/**
|
||||
* The timer is used to dispatch maintenance tasks for the DNS cache.
|
||||
*/
|
||||
private final Timer _stateTimer;
|
||||
|
||||
public static class StarterTimer extends Timer {
|
||||
|
||||
// This is needed because in some case we cancel the timers before all the task have finished running and in some case they will try to reschedule
|
||||
private volatile boolean _cancelled;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public StarterTimer() {
|
||||
super();
|
||||
_cancelled = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param isDaemon
|
||||
*/
|
||||
public StarterTimer(boolean isDaemon) {
|
||||
super(isDaemon);
|
||||
_cancelled = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param name
|
||||
* @param isDaemon
|
||||
*/
|
||||
public StarterTimer(String name, boolean isDaemon) {
|
||||
super(name, isDaemon);
|
||||
_cancelled = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param name
|
||||
*/
|
||||
public StarterTimer(String name) {
|
||||
super(name);
|
||||
_cancelled = false;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.util.Timer#cancel()
|
||||
*/
|
||||
@Override
|
||||
public synchronized void cancel() {
|
||||
if (_cancelled) return;
|
||||
_cancelled = true;
|
||||
super.cancel();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.util.Timer#schedule(java.util.TimerTask, long)
|
||||
*/
|
||||
@Override
|
||||
public synchronized void schedule(TimerTask task, long delay) {
|
||||
if (_cancelled) return;
|
||||
super.schedule(task, delay);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.util.Timer#schedule(java.util.TimerTask, java.util.Date)
|
||||
*/
|
||||
@Override
|
||||
public synchronized void schedule(TimerTask task, Date time) {
|
||||
if (_cancelled) return;
|
||||
super.schedule(task, time);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.util.Timer#schedule(java.util.TimerTask, long, long)
|
||||
*/
|
||||
@Override
|
||||
public synchronized void schedule(TimerTask task, long delay, long period) {
|
||||
if (_cancelled) return;
|
||||
super.schedule(task, delay, period);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.util.Timer#schedule(java.util.TimerTask, java.util.Date, long)
|
||||
*/
|
||||
@Override
|
||||
public synchronized void schedule(TimerTask task, Date firstTime, long period) {
|
||||
if (_cancelled) return;
|
||||
super.schedule(task, firstTime, period);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.util.Timer#scheduleAtFixedRate(java.util.TimerTask, long, long)
|
||||
*/
|
||||
@Override
|
||||
public synchronized void scheduleAtFixedRate(TimerTask task, long delay, long period) {
|
||||
if (_cancelled) return;
|
||||
super.scheduleAtFixedRate(task, delay, period);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.util.Timer#scheduleAtFixedRate(java.util.TimerTask, java.util.Date, long)
|
||||
*/
|
||||
@Override
|
||||
public synchronized void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) {
|
||||
if (_cancelled) return;
|
||||
super.scheduleAtFixedRate(task, firstTime, period);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public DNSTaskStarterImpl(JmDNSImpl jmDNSImpl) {
|
||||
super();
|
||||
_jmDNSImpl = jmDNSImpl;
|
||||
_timer = new StarterTimer("JmDNS(" + _jmDNSImpl.getName() + ").Timer", true);
|
||||
_stateTimer = new StarterTimer("JmDNS(" + _jmDNSImpl.getName() + ").State.Timer", true);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSTaskStarter#purgeTimer()
|
||||
*/
|
||||
@Override
|
||||
public void purgeTimer() {
|
||||
_timer.purge();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSTaskStarter#purgeStateTimer()
|
||||
*/
|
||||
@Override
|
||||
public void purgeStateTimer() {
|
||||
_stateTimer.purge();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSTaskStarter#cancelTimer()
|
||||
*/
|
||||
@Override
|
||||
public void cancelTimer() {
|
||||
_timer.cancel();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSTaskStarter#cancelStateTimer()
|
||||
*/
|
||||
@Override
|
||||
public void cancelStateTimer() {
|
||||
_stateTimer.cancel();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSTaskStarter#startProber()
|
||||
*/
|
||||
@Override
|
||||
public void startProber() {
|
||||
new Prober(_jmDNSImpl).start(_stateTimer);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSTaskStarter#startAnnouncer()
|
||||
*/
|
||||
@Override
|
||||
public void startAnnouncer() {
|
||||
new Announcer(_jmDNSImpl).start(_stateTimer);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSTaskStarter#startRenewer()
|
||||
*/
|
||||
@Override
|
||||
public void startRenewer() {
|
||||
new Renewer(_jmDNSImpl).start(_stateTimer);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSTaskStarter#startCanceler()
|
||||
*/
|
||||
@Override
|
||||
public void startCanceler() {
|
||||
new Canceler(_jmDNSImpl).start(_stateTimer);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSTaskStarter#startReaper()
|
||||
*/
|
||||
@Override
|
||||
public void startReaper() {
|
||||
new RecordReaper(_jmDNSImpl).start(_timer);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSTaskStarter#startServiceInfoResolver(javax.jmdns.impl.ServiceInfoImpl)
|
||||
*/
|
||||
@Override
|
||||
public void startServiceInfoResolver(ServiceInfoImpl info) {
|
||||
new ServiceInfoResolver(_jmDNSImpl, info).start(_timer);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSTaskStarter#startTypeResolver()
|
||||
*/
|
||||
@Override
|
||||
public void startTypeResolver() {
|
||||
new TypeResolver(_jmDNSImpl).start(_timer);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSTaskStarter#startServiceResolver(java.lang.String)
|
||||
*/
|
||||
@Override
|
||||
public void startServiceResolver(String type) {
|
||||
new ServiceResolver(_jmDNSImpl, type).start(_timer);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.DNSTaskStarter#startResponder(javax.jmdns.impl.DNSIncoming, int)
|
||||
*/
|
||||
@Override
|
||||
public void startResponder(DNSIncoming in, int port) {
|
||||
new Responder(_jmDNSImpl, in, port).start(_timer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge the general task timer
|
||||
*/
|
||||
public void purgeTimer();
|
||||
|
||||
/**
|
||||
* Purge the state task timer
|
||||
*/
|
||||
public void purgeStateTimer();
|
||||
|
||||
/**
|
||||
* Cancel the generals task timer
|
||||
*/
|
||||
public void cancelTimer();
|
||||
|
||||
/**
|
||||
* Cancel the state task timer
|
||||
*/
|
||||
public void cancelStateTimer();
|
||||
|
||||
/**
|
||||
* Start a new prober task
|
||||
*/
|
||||
public void startProber();
|
||||
|
||||
/**
|
||||
* Start a new announcer task
|
||||
*/
|
||||
public void startAnnouncer();
|
||||
|
||||
/**
|
||||
* Start a new renewer task
|
||||
*/
|
||||
public void startRenewer();
|
||||
|
||||
/**
|
||||
* Start a new canceler task
|
||||
*/
|
||||
public void startCanceler();
|
||||
|
||||
/**
|
||||
* Start a new reaper task. There is only supposed to be one reaper running at a time.
|
||||
*/
|
||||
public void startReaper();
|
||||
|
||||
/**
|
||||
* Start a new service info resolver task
|
||||
*
|
||||
* @param info
|
||||
* service info to resolve
|
||||
*/
|
||||
public void startServiceInfoResolver(ServiceInfoImpl info);
|
||||
|
||||
/**
|
||||
* Start a new service type resolver task
|
||||
*/
|
||||
public void startTypeResolver();
|
||||
|
||||
/**
|
||||
* Start a new service resolver task
|
||||
*
|
||||
* @param type
|
||||
* service type to resolve
|
||||
*/
|
||||
public void startServiceResolver(String type);
|
||||
|
||||
/**
|
||||
* Start a new responder task
|
||||
*
|
||||
* @param in
|
||||
* incoming message
|
||||
* @param port
|
||||
* incoming port
|
||||
*/
|
||||
public void startResponder(DNSIncoming in, int port);
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,434 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.Inet6Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.NetworkTopologyDiscovery;
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
import javax.jmdns.impl.constants.DNSRecordClass;
|
||||
import javax.jmdns.impl.constants.DNSRecordType;
|
||||
import javax.jmdns.impl.constants.DNSState;
|
||||
import javax.jmdns.impl.tasks.DNSTask;
|
||||
|
||||
/**
|
||||
* HostInfo information on the local host to be able to cope with change of addresses.
|
||||
*
|
||||
* @author Pierre Frisch, Werner Randelshofer
|
||||
*/
|
||||
public class HostInfo implements DNSStatefulObject {
|
||||
private static Logger logger = Logger.getLogger(HostInfo.class.getName());
|
||||
|
||||
protected String _name;
|
||||
|
||||
protected InetAddress _address;
|
||||
|
||||
protected NetworkInterface _interfaze;
|
||||
|
||||
private final HostInfoState _state;
|
||||
|
||||
private final static class HostInfoState extends DNSStatefulObject.DefaultImplementation {
|
||||
|
||||
private static final long serialVersionUID = -8191476803620402088L;
|
||||
|
||||
/**
|
||||
* @param dns
|
||||
*/
|
||||
public HostInfoState(JmDNSImpl dns) {
|
||||
super();
|
||||
this.setDns(dns);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param address
|
||||
* IP address to bind
|
||||
* @param dns
|
||||
* JmDNS instance
|
||||
* @param jmdnsName
|
||||
* JmDNS name
|
||||
* @return new HostInfo
|
||||
*/
|
||||
public static HostInfo newHostInfo(InetAddress address, JmDNSImpl dns, String jmdnsName) {
|
||||
HostInfo localhost = null;
|
||||
String aName = (jmdnsName != null ? jmdnsName : "");
|
||||
InetAddress addr = address;
|
||||
try {
|
||||
if (addr == null) {
|
||||
String ip = System.getProperty("net.mdns.interface");
|
||||
if (ip != null) {
|
||||
addr = InetAddress.getByName(ip);
|
||||
} else {
|
||||
addr = InetAddress.getLocalHost();
|
||||
if (addr.isLoopbackAddress()) {
|
||||
// Find local address that isn't a loopback address
|
||||
InetAddress[] addresses = NetworkTopologyDiscovery.Factory.getInstance().getInetAddresses();
|
||||
if (addresses.length > 0) {
|
||||
addr = addresses[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (addr.isLoopbackAddress()) {
|
||||
logger.warning("Could not find any address beside the loopback.");
|
||||
}
|
||||
}
|
||||
if (aName.length() == 0) {
|
||||
aName = addr.getHostName();
|
||||
}
|
||||
if (aName.contains("in-addr.arpa") || (aName.equals(addr.getHostAddress()))) {
|
||||
aName = ((jmdnsName != null) && (jmdnsName.length() > 0) ? jmdnsName : addr.getHostAddress());
|
||||
}
|
||||
} catch (final IOException e) {
|
||||
logger.log(Level.WARNING, "Could not intialize the host network interface on " + address + "because of an error: " + e.getMessage(), e);
|
||||
// This is only used for running unit test on Debian / Ubuntu
|
||||
addr = loopbackAddress();
|
||||
aName = ((jmdnsName != null) && (jmdnsName.length() > 0) ? jmdnsName : "computer");
|
||||
}
|
||||
// A host name with "." is illegal. so strip off everything and append .local.
|
||||
// We also need to be carefull that the .local may already be there
|
||||
int index = aName.indexOf(".local");
|
||||
if (index > 0) {
|
||||
aName = aName.substring(0, index);
|
||||
}
|
||||
aName = aName.replace('.', '-');
|
||||
aName += ".local.";
|
||||
localhost = new HostInfo(addr, aName, dns);
|
||||
return localhost;
|
||||
}
|
||||
|
||||
private static InetAddress loopbackAddress() {
|
||||
try {
|
||||
return InetAddress.getByName(null);
|
||||
} catch (UnknownHostException exception) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private HostInfo(final InetAddress address, final String name, final JmDNSImpl dns) {
|
||||
super();
|
||||
this._state = new HostInfoState(dns);
|
||||
this._address = address;
|
||||
this._name = name;
|
||||
if (address != null) {
|
||||
try {
|
||||
_interfaze = NetworkInterface.getByInetAddress(address);
|
||||
} catch (Exception exception) {
|
||||
logger.log(Level.SEVERE, "LocalHostInfo() exception ", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return _name;
|
||||
}
|
||||
|
||||
public InetAddress getInetAddress() {
|
||||
return _address;
|
||||
}
|
||||
|
||||
Inet4Address getInet4Address() {
|
||||
if (this.getInetAddress() instanceof Inet4Address) {
|
||||
return (Inet4Address) _address;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Inet6Address getInet6Address() {
|
||||
if (this.getInetAddress() instanceof Inet6Address) {
|
||||
return (Inet6Address) _address;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public NetworkInterface getInterface() {
|
||||
return _interfaze;
|
||||
}
|
||||
|
||||
public boolean conflictWithRecord(DNSRecord.Address record) {
|
||||
DNSRecord.Address hostAddress = this.getDNSAddressRecord(record.getRecordType(), record.isUnique(), DNSConstants.DNS_TTL);
|
||||
if (hostAddress != null) {
|
||||
return hostAddress.sameType(record) && hostAddress.sameName(record) && (!hostAddress.sameValue(record));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
synchronized String incrementHostName() {
|
||||
_name = NameRegister.Factory.getRegistry().incrementName(this.getInetAddress(), _name, NameRegister.NameType.HOST);
|
||||
return _name;
|
||||
}
|
||||
|
||||
boolean shouldIgnorePacket(DatagramPacket packet) {
|
||||
boolean result = false;
|
||||
if (this.getInetAddress() != null) {
|
||||
InetAddress from = packet.getAddress();
|
||||
if (from != null) {
|
||||
if ((this.getInetAddress().isLinkLocalAddress() || this.getInetAddress().isMCLinkLocal()) && (!from.isLinkLocalAddress())) {
|
||||
// A host sending Multicast DNS queries to a link-local destination
|
||||
// address (including the 224.0.0.251 and FF02::FB link-local multicast
|
||||
// addresses) MUST only accept responses to that query that originate
|
||||
// from the local link, and silently discard any other response packets.
|
||||
// Without this check, it could be possible for remote rogue hosts to
|
||||
// send spoof answer packets (perhaps unicast to the victim host) which
|
||||
// the receiving machine could misinterpret as having originated on the
|
||||
// local link.
|
||||
result = true;
|
||||
}
|
||||
// if (from.isLinkLocalAddress() && (!this.getInetAddress().isLinkLocalAddress())) {
|
||||
// // Ignore linklocal packets on regular interfaces, unless this is
|
||||
// // also a linklocal interface. This is to avoid duplicates. This is
|
||||
// // a terrible hack caused by the lack of an API to get the address
|
||||
// // of the interface on which the packet was received.
|
||||
// result = true;
|
||||
// }
|
||||
if (from.isLoopbackAddress() && (!this.getInetAddress().isLoopbackAddress())) {
|
||||
// Ignore loopback packets on a regular interface unless this is also a loopback interface.
|
||||
result = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
DNSRecord.Address getDNSAddressRecord(DNSRecordType type, boolean unique, int ttl) {
|
||||
switch (type) {
|
||||
case TYPE_A:
|
||||
return this.getDNS4AddressRecord(unique, ttl);
|
||||
case TYPE_A6:
|
||||
case TYPE_AAAA:
|
||||
return this.getDNS6AddressRecord(unique, ttl);
|
||||
default:
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private DNSRecord.Address getDNS4AddressRecord(boolean unique, int ttl) {
|
||||
if (this.getInetAddress() instanceof Inet4Address) {
|
||||
return new DNSRecord.IPv4Address(this.getName(), DNSRecordClass.CLASS_IN, unique, ttl, this.getInetAddress());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private DNSRecord.Address getDNS6AddressRecord(boolean unique, int ttl) {
|
||||
if (this.getInetAddress() instanceof Inet6Address) {
|
||||
return new DNSRecord.IPv6Address(this.getName(), DNSRecordClass.CLASS_IN, unique, ttl, this.getInetAddress());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
DNSRecord.Pointer getDNSReverseAddressRecord(DNSRecordType type, boolean unique, int ttl) {
|
||||
switch (type) {
|
||||
case TYPE_A:
|
||||
return this.getDNS4ReverseAddressRecord(unique, ttl);
|
||||
case TYPE_A6:
|
||||
case TYPE_AAAA:
|
||||
return this.getDNS6ReverseAddressRecord(unique, ttl);
|
||||
default:
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private DNSRecord.Pointer getDNS4ReverseAddressRecord(boolean unique, int ttl) {
|
||||
if (this.getInetAddress() instanceof Inet4Address) {
|
||||
return new DNSRecord.Pointer(this.getInetAddress().getHostAddress() + ".in-addr.arpa.", DNSRecordClass.CLASS_IN, unique, ttl, this.getName());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private DNSRecord.Pointer getDNS6ReverseAddressRecord(boolean unique, int ttl) {
|
||||
if (this.getInetAddress() instanceof Inet6Address) {
|
||||
return new DNSRecord.Pointer(this.getInetAddress().getHostAddress() + ".ip6.arpa.", DNSRecordClass.CLASS_IN, unique, ttl, this.getName());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder buf = new StringBuilder(1024);
|
||||
buf.append("local host info[");
|
||||
buf.append(getName() != null ? getName() : "no name");
|
||||
buf.append(", ");
|
||||
buf.append(getInterface() != null ? getInterface().getDisplayName() : "???");
|
||||
buf.append(":");
|
||||
buf.append(getInetAddress() != null ? getInetAddress().getHostAddress() : "no address");
|
||||
buf.append(", ");
|
||||
buf.append(_state);
|
||||
buf.append("]");
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public Collection<DNSRecord> answers(DNSRecordClass recordClass, boolean unique, int ttl) {
|
||||
List<DNSRecord> list = new ArrayList<DNSRecord>();
|
||||
DNSRecord answer = this.getDNS4AddressRecord(unique, ttl);
|
||||
if ((answer != null) && answer.matchRecordClass(recordClass)) {
|
||||
list.add(answer);
|
||||
}
|
||||
answer = this.getDNS6AddressRecord(unique, ttl);
|
||||
if ((answer != null) && answer.matchRecordClass(recordClass)) {
|
||||
list.add(answer);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public JmDNSImpl getDns() {
|
||||
return this._state.getDns();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean advanceState(DNSTask task) {
|
||||
return this._state.advanceState(task);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void removeAssociationWithTask(DNSTask task) {
|
||||
this._state.removeAssociationWithTask(task);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean revertState() {
|
||||
return this._state.revertState();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void associateWithTask(DNSTask task, DNSState state) {
|
||||
this._state.associateWithTask(task, state);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isAssociatedWithTask(DNSTask task, DNSState state) {
|
||||
return this._state.isAssociatedWithTask(task, state);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean cancelState() {
|
||||
return this._state.cancelState();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean closeState() {
|
||||
return this._state.closeState();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean recoverState() {
|
||||
return this._state.recoverState();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isProbing() {
|
||||
return this._state.isProbing();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isAnnouncing() {
|
||||
return this._state.isAnnouncing();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isAnnounced() {
|
||||
return this._state.isAnnounced();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isCanceling() {
|
||||
return this._state.isCanceling();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isCanceled() {
|
||||
return this._state.isCanceled();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isClosing() {
|
||||
return this._state.isClosing();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean isClosed() {
|
||||
return this._state.isClosed();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean waitForAnnounced(long timeout) {
|
||||
return _state.waitForAnnounced(timeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public boolean waitForCanceled(long timeout) {
|
||||
if (_address == null) {
|
||||
// No need to wait this was never announced.
|
||||
return true;
|
||||
}
|
||||
return _state.waitForCanceled(timeout);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,788 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.JmDNS;
|
||||
import javax.jmdns.JmmDNS;
|
||||
import javax.jmdns.NetworkTopologyDiscovery;
|
||||
import javax.jmdns.NetworkTopologyEvent;
|
||||
import javax.jmdns.NetworkTopologyListener;
|
||||
import javax.jmdns.ServiceInfo;
|
||||
import javax.jmdns.ServiceListener;
|
||||
import javax.jmdns.ServiceTypeListener;
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
import javax.jmdns.impl.util.NamedThreadFactory;
|
||||
|
||||
/**
|
||||
* This class enable multihoming mDNS. It will open a mDNS per IP address of the machine.
|
||||
*
|
||||
* @author Cédrik Lime, Pierre Frisch
|
||||
*/
|
||||
public class JmmDNSImpl implements JmmDNS, NetworkTopologyListener, ServiceInfoImpl.Delegate {
|
||||
private static Logger logger = Logger.getLogger(JmmDNSImpl.class.getName());
|
||||
|
||||
private final Set<NetworkTopologyListener> _networkListeners;
|
||||
|
||||
/**
|
||||
* Every JmDNS created.
|
||||
*/
|
||||
private final ConcurrentMap<InetAddress, JmDNS> _knownMDNS;
|
||||
|
||||
/**
|
||||
* This enable the service info text update.
|
||||
*/
|
||||
private final ConcurrentMap<String, ServiceInfo> _services;
|
||||
|
||||
/**
|
||||
* List of registered services
|
||||
*/
|
||||
private final Set<String> _serviceTypes;
|
||||
|
||||
/**
|
||||
* Holds instances of ServiceListener's. Keys are Strings holding a fully qualified service type. Values are LinkedList's of ServiceListener's.
|
||||
*/
|
||||
private final ConcurrentMap<String, List<ServiceListener>> _serviceListeners;
|
||||
|
||||
/**
|
||||
* Holds instances of ServiceTypeListener's.
|
||||
*/
|
||||
private final Set<ServiceTypeListener> _typeListeners;
|
||||
|
||||
private final ExecutorService _listenerExecutor;
|
||||
|
||||
private final ExecutorService _jmDNSExecutor;
|
||||
|
||||
private final Timer _timer;
|
||||
|
||||
private final AtomicBoolean _isClosing;
|
||||
|
||||
private final AtomicBoolean _closed;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public JmmDNSImpl() {
|
||||
super();
|
||||
_networkListeners = Collections.synchronizedSet(new HashSet<NetworkTopologyListener>());
|
||||
_knownMDNS = new ConcurrentHashMap<InetAddress, JmDNS>();
|
||||
_services = new ConcurrentHashMap<String, ServiceInfo>(20);
|
||||
_listenerExecutor = Executors.newSingleThreadExecutor(new NamedThreadFactory("JmmDNS Listeners"));
|
||||
_jmDNSExecutor = Executors.newCachedThreadPool(new NamedThreadFactory("JmmDNS"));
|
||||
_timer = new Timer("Multihomed mDNS.Timer", true);
|
||||
_serviceListeners = new ConcurrentHashMap<String, List<ServiceListener>>();
|
||||
_typeListeners = Collections.synchronizedSet(new HashSet<ServiceTypeListener>());
|
||||
_serviceTypes = Collections.synchronizedSet(new HashSet<String>());
|
||||
(new NetworkChecker(this, NetworkTopologyDiscovery.Factory.getInstance())).start(_timer);
|
||||
_isClosing = new AtomicBoolean(false);
|
||||
_closed = new AtomicBoolean(false);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.io.Closeable#close()
|
||||
*/
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
if (_isClosing.compareAndSet(false, true)) {
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
logger.finer("Cancelling JmmDNS: " + this);
|
||||
}
|
||||
_timer.cancel();
|
||||
_listenerExecutor.shutdown();
|
||||
_jmDNSExecutor.shutdown();
|
||||
// We need to cancel all the DNS
|
||||
ExecutorService executor = Executors.newCachedThreadPool(new NamedThreadFactory("JmmDNS.close"));
|
||||
try {
|
||||
for (final JmDNS mDNS : this.getDNS()) {
|
||||
executor.submit(new Runnable() {
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
mDNS.close();
|
||||
} catch (IOException exception) {
|
||||
// JmDNS never throws this is only because of the closeable interface
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
executor.shutdown();
|
||||
}
|
||||
try {
|
||||
executor.awaitTermination(DNSConstants.CLOSE_TIMEOUT, TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException exception) {
|
||||
logger.log(Level.WARNING, "Exception ", exception);
|
||||
}
|
||||
_knownMDNS.clear();
|
||||
_services.clear();
|
||||
_serviceListeners.clear();
|
||||
_typeListeners.clear();
|
||||
_serviceTypes.clear();
|
||||
_closed.set(true);
|
||||
JmmDNS.Factory.close();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#getNames()
|
||||
*/
|
||||
@Override
|
||||
public String[] getNames() {
|
||||
Set<String> result = new HashSet<String>();
|
||||
for (JmDNS mDNS : this.getDNS()) {
|
||||
result.add(mDNS.getName());
|
||||
}
|
||||
return result.toArray(new String[result.size()]);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#getHostNames()
|
||||
*/
|
||||
@Override
|
||||
public String[] getHostNames() {
|
||||
Set<String> result = new HashSet<String>();
|
||||
for (JmDNS mDNS : this.getDNS()) {
|
||||
result.add(mDNS.getHostName());
|
||||
}
|
||||
return result.toArray(new String[result.size()]);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#getInetAddresses()
|
||||
*/
|
||||
@Override
|
||||
public InetAddress[] getInetAddresses() throws IOException {
|
||||
Set<InetAddress> result = new HashSet<InetAddress>();
|
||||
for (JmDNS mDNS : this.getDNS()) {
|
||||
result.add(mDNS.getInetAddress());
|
||||
}
|
||||
return result.toArray(new InetAddress[result.size()]);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#getDNS()
|
||||
*/
|
||||
@Override
|
||||
public JmDNS[] getDNS() {
|
||||
synchronized (_knownMDNS) {
|
||||
return _knownMDNS.values().toArray(new JmDNS[_knownMDNS.size()]);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#getInterfaces()
|
||||
*/
|
||||
@Override
|
||||
@Deprecated
|
||||
public InetAddress[] getInterfaces() throws IOException {
|
||||
Set<InetAddress> result = new HashSet<InetAddress>();
|
||||
for (JmDNS mDNS : this.getDNS()) {
|
||||
result.add(mDNS.getInterface());
|
||||
}
|
||||
return result.toArray(new InetAddress[result.size()]);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String)
|
||||
*/
|
||||
@Override
|
||||
public ServiceInfo[] getServiceInfos(String type, String name) {
|
||||
return this.getServiceInfos(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String, long)
|
||||
*/
|
||||
@Override
|
||||
public ServiceInfo[] getServiceInfos(String type, String name, long timeout) {
|
||||
return this.getServiceInfos(type, name, false, timeout);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String, boolean)
|
||||
*/
|
||||
@Override
|
||||
public ServiceInfo[] getServiceInfos(String type, String name, boolean persistent) {
|
||||
return this.getServiceInfos(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String, boolean, long)
|
||||
*/
|
||||
@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 JmDNS[] dnsArray = this.getDNS();
|
||||
final Set<ServiceInfo> result = new HashSet<ServiceInfo>(dnsArray.length);
|
||||
if (dnsArray.length > 0) {
|
||||
List<Callable<ServiceInfo>> tasks = new ArrayList<Callable<ServiceInfo>>(dnsArray.length);
|
||||
for (final JmDNS mDNS : dnsArray) {
|
||||
tasks.add(new Callable<ServiceInfo>() {
|
||||
|
||||
@Override
|
||||
public ServiceInfo call() throws Exception {
|
||||
return mDNS.getServiceInfo(type, name, persistent, timeout);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
ExecutorService executor = Executors.newFixedThreadPool(tasks.size(), new NamedThreadFactory("JmmDNS.getServiceInfos"));
|
||||
try {
|
||||
List<Future<ServiceInfo>> results = Collections.emptyList();
|
||||
try {
|
||||
results = executor.invokeAll(tasks, timeout + 100, TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException exception) {
|
||||
logger.log(Level.FINE, "Interrupted ", exception);
|
||||
Thread.currentThread().interrupt();
|
||||
// Will terminate next loop early.
|
||||
}
|
||||
|
||||
for (Future<ServiceInfo> future : results) {
|
||||
if (future.isCancelled()) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
ServiceInfo info = future.get();
|
||||
if (info != null) {
|
||||
result.add(info);
|
||||
}
|
||||
} catch (InterruptedException exception) {
|
||||
logger.log(Level.FINE, "Interrupted ", exception);
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (ExecutionException exception) {
|
||||
logger.log(Level.WARNING, "Exception ", exception);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
executor.shutdown();
|
||||
}
|
||||
}
|
||||
return result.toArray(new ServiceInfo[result.size()]);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String)
|
||||
*/
|
||||
@Override
|
||||
public void requestServiceInfo(String type, String name) {
|
||||
this.requestServiceInfo(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean)
|
||||
*/
|
||||
@Override
|
||||
public void requestServiceInfo(String type, String name, boolean persistent) {
|
||||
this.requestServiceInfo(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String, long)
|
||||
*/
|
||||
@Override
|
||||
public void requestServiceInfo(String type, String name, long timeout) {
|
||||
this.requestServiceInfo(type, name, false, timeout);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean, long)
|
||||
*/
|
||||
@Override
|
||||
public void requestServiceInfo(final String type, final String name, final boolean persistent, final long timeout) {
|
||||
// We need to run this in parallel to respect the timeout.
|
||||
for (final JmDNS mDNS : this.getDNS()) {
|
||||
_jmDNSExecutor.submit(new Runnable() {
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void run() {
|
||||
mDNS.requestServiceInfo(type, name, persistent, timeout);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#addServiceTypeListener(javax.jmdns.ServiceTypeListener)
|
||||
*/
|
||||
@Override
|
||||
public void addServiceTypeListener(ServiceTypeListener listener) throws IOException {
|
||||
_typeListeners.add(listener);
|
||||
for (JmDNS mDNS : this.getDNS()) {
|
||||
mDNS.addServiceTypeListener(listener);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#removeServiceTypeListener(javax.jmdns.ServiceTypeListener)
|
||||
*/
|
||||
@Override
|
||||
public void removeServiceTypeListener(ServiceTypeListener listener) {
|
||||
_typeListeners.remove(listener);
|
||||
for (JmDNS mDNS : this.getDNS()) {
|
||||
mDNS.removeServiceTypeListener(listener);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#addServiceListener(java.lang.String, javax.jmdns.ServiceListener)
|
||||
*/
|
||||
@Override
|
||||
public void addServiceListener(String type, ServiceListener listener) {
|
||||
final String loType = type.toLowerCase();
|
||||
List<ServiceListener> list = _serviceListeners.get(loType);
|
||||
if (list == null) {
|
||||
_serviceListeners.putIfAbsent(loType, new LinkedList<ServiceListener>());
|
||||
list = _serviceListeners.get(loType);
|
||||
}
|
||||
if (list != null) {
|
||||
synchronized (list) {
|
||||
if (!list.contains(listener)) {
|
||||
list.add(listener);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (JmDNS mDNS : this.getDNS()) {
|
||||
mDNS.addServiceListener(type, listener);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#removeServiceListener(java.lang.String, javax.jmdns.ServiceListener)
|
||||
*/
|
||||
@Override
|
||||
public void removeServiceListener(String type, ServiceListener listener) {
|
||||
String loType = type.toLowerCase();
|
||||
List<ServiceListener> list = _serviceListeners.get(loType);
|
||||
if (list != null) {
|
||||
synchronized (list) {
|
||||
list.remove(listener);
|
||||
if (list.isEmpty()) {
|
||||
_serviceListeners.remove(loType, list);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (JmDNS mDNS : this.getDNS()) {
|
||||
mDNS.removeServiceListener(type, listener);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.ServiceInfoImpl.Delegate#textValueUpdated(javax.jmdns.ServiceInfo, byte[])
|
||||
*/
|
||||
@Override
|
||||
public void textValueUpdated(ServiceInfo target, byte[] value) {
|
||||
// We need to get the list out of the synchronized block to prevent dead locks
|
||||
final JmDNS[] dnsArray = this.getDNS();
|
||||
synchronized (_services) {
|
||||
for (JmDNS mDNS : dnsArray) {
|
||||
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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#registerService(javax.jmdns.ServiceInfo)
|
||||
*/
|
||||
@Override
|
||||
public void registerService(ServiceInfo info) throws IOException {
|
||||
// We need to get the list out of the synchronized block to prevent dead locks
|
||||
final JmDNS[] dnsArray = this.getDNS();
|
||||
// This is really complex. We need to clone the service info for each DNS but then we loose the ability to update it.
|
||||
synchronized (_services) {
|
||||
for (JmDNS mDNS : dnsArray) {
|
||||
mDNS.registerService(info.clone());
|
||||
}
|
||||
((ServiceInfoImpl) info).setDelegate(this);
|
||||
_services.put(info.getQualifiedName(), info);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#unregisterService(javax.jmdns.ServiceInfo)
|
||||
*/
|
||||
@Override
|
||||
public void unregisterService(ServiceInfo info) {
|
||||
// We need to get the list out of the synchronized block to prevent dead locks
|
||||
final JmDNS[] dnsArray = this.getDNS();
|
||||
synchronized (_services) {
|
||||
_services.remove(info.getQualifiedName());
|
||||
for (JmDNS mDNS : dnsArray) {
|
||||
mDNS.unregisterService(info);
|
||||
}
|
||||
((ServiceInfoImpl) info).setDelegate(null);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#unregisterAllServices()
|
||||
*/
|
||||
@Override
|
||||
public void unregisterAllServices() {
|
||||
// We need to get the list out of the synchronized block to prevent dead locks
|
||||
final JmDNS[] dnsArray = this.getDNS();
|
||||
synchronized (_services) {
|
||||
_services.clear();
|
||||
for (JmDNS mDNS : dnsArray) {
|
||||
mDNS.unregisterAllServices();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#registerServiceType(java.lang.String)
|
||||
*/
|
||||
@Override
|
||||
public void registerServiceType(String type) {
|
||||
_serviceTypes.add(type);
|
||||
for (JmDNS mDNS : this.getDNS()) {
|
||||
mDNS.registerServiceType(type);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#list(java.lang.String)
|
||||
*/
|
||||
@Override
|
||||
public ServiceInfo[] list(String type) {
|
||||
return this.list(type, DNSConstants.SERVICE_INFO_TIMEOUT);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#list(java.lang.String, long)
|
||||
*/
|
||||
@Override
|
||||
public ServiceInfo[] list(final String type, final long timeout) {
|
||||
final JmDNS[] dnsArray = this.getDNS();
|
||||
// We need to run this in parallel to respect the timeout.
|
||||
final Set<ServiceInfo> result = new HashSet<ServiceInfo>(dnsArray.length * 5);
|
||||
if (dnsArray.length > 0) {
|
||||
List<Callable<List<ServiceInfo>>> tasks = new ArrayList<Callable<List<ServiceInfo>>>(dnsArray.length);
|
||||
for (final JmDNS mDNS : dnsArray) {
|
||||
tasks.add(new Callable<List<ServiceInfo>>() {
|
||||
@Override
|
||||
public List<ServiceInfo> call() throws Exception {
|
||||
return Arrays.asList(mDNS.list(type, timeout));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ExecutorService executor = Executors.newFixedThreadPool(tasks.size(), new NamedThreadFactory("JmmDNS.list"));
|
||||
try {
|
||||
List<Future<List<ServiceInfo>>> results = Collections.emptyList();
|
||||
try {
|
||||
results = executor.invokeAll(tasks, timeout + 100, TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException exception) {
|
||||
logger.log(Level.FINE, "Interrupted ", exception);
|
||||
Thread.currentThread().interrupt();
|
||||
// Will terminate next loop early.
|
||||
}
|
||||
|
||||
for (Future<List<ServiceInfo>> future : results) {
|
||||
if (future.isCancelled()) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
result.addAll(future.get());
|
||||
} catch (InterruptedException exception) {
|
||||
logger.log(Level.FINE, "Interrupted ", exception);
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (ExecutionException exception) {
|
||||
logger.log(Level.WARNING, "Exception ", exception);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
executor.shutdown();
|
||||
}
|
||||
}
|
||||
return result.toArray(new ServiceInfo[result.size()]);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#listBySubtype(java.lang.String)
|
||||
*/
|
||||
@Override
|
||||
public Map<String, ServiceInfo[]> listBySubtype(String type) {
|
||||
return this.listBySubtype(type, DNSConstants.SERVICE_INFO_TIMEOUT);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#listBySubtype(java.lang.String, long)
|
||||
*/
|
||||
@Override
|
||||
public Map<String, ServiceInfo[]> listBySubtype(final String type, final long timeout) {
|
||||
Map<String, List<ServiceInfo>> map = new HashMap<String, List<ServiceInfo>>(5);
|
||||
for (ServiceInfo info : this.list(type, timeout)) {
|
||||
String subtype = info.getSubtype();
|
||||
if (!map.containsKey(subtype)) {
|
||||
map.put(subtype, new ArrayList<ServiceInfo>(10));
|
||||
}
|
||||
map.get(subtype).add(info);
|
||||
}
|
||||
|
||||
Map<String, ServiceInfo[]> result = new HashMap<String, ServiceInfo[]>(map.size());
|
||||
for (String subtype : map.keySet()) {
|
||||
List<ServiceInfo> infoForSubType = map.get(subtype);
|
||||
result.put(subtype, infoForSubType.toArray(new ServiceInfo[infoForSubType.size()]));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#addNetworkTopologyListener(javax.jmdns.NetworkTopologyListener)
|
||||
*/
|
||||
@Override
|
||||
public void addNetworkTopologyListener(NetworkTopologyListener listener) {
|
||||
_networkListeners.add(listener);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#removeNetworkTopologyListener(javax.jmdns.NetworkTopologyListener)
|
||||
*/
|
||||
@Override
|
||||
public void removeNetworkTopologyListener(NetworkTopologyListener listener) {
|
||||
_networkListeners.remove(listener);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS#networkListeners()
|
||||
*/
|
||||
@Override
|
||||
public NetworkTopologyListener[] networkListeners() {
|
||||
return _networkListeners.toArray(new NetworkTopologyListener[_networkListeners.size()]);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.NetworkTopologyListener#inetAddressAdded(javax.jmdns.NetworkTopologyEvent)
|
||||
*/
|
||||
@Override
|
||||
public void inetAddressAdded(NetworkTopologyEvent event) {
|
||||
InetAddress address = event.getInetAddress();
|
||||
try {
|
||||
if (!_knownMDNS.containsKey(address)) {
|
||||
synchronized (_knownMDNS) {
|
||||
if (!_knownMDNS.containsKey(address)) {
|
||||
final JmDNS dns = JmDNS.create(address);
|
||||
if (_knownMDNS.putIfAbsent(address, dns) == null) {
|
||||
// We need to register the services and listeners with the new JmDNS
|
||||
final Collection<String> types = _serviceTypes;
|
||||
final Collection<ServiceInfo> infos = _services.values();
|
||||
final Collection<ServiceTypeListener> typeListeners = _typeListeners;
|
||||
final Map<String, List<ServiceListener>> serviceListeners = _serviceListeners;
|
||||
_jmDNSExecutor.submit(new Runnable() {
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void run() {
|
||||
// Register Types
|
||||
for (String type : types) {
|
||||
dns.registerServiceType(type);
|
||||
}
|
||||
// Register services
|
||||
for (ServiceInfo info : infos) {
|
||||
try {
|
||||
dns.registerService(info.clone());
|
||||
} catch (IOException exception) {
|
||||
// logger.warning("Unexpected unhandled exception: " + exception);
|
||||
}
|
||||
}
|
||||
// Add ServiceType Listeners
|
||||
for (ServiceTypeListener listener : typeListeners) {
|
||||
try {
|
||||
dns.addServiceTypeListener(listener);
|
||||
} catch (IOException exception) {
|
||||
// logger.warning("Unexpected unhandled exception: " + exception);
|
||||
}
|
||||
}
|
||||
// Add Service Listeners
|
||||
for (String type : serviceListeners.keySet()) {
|
||||
List<ServiceListener> listeners = serviceListeners.get(type);
|
||||
synchronized (listeners) {
|
||||
for (ServiceListener listener : listeners) {
|
||||
dns.addServiceListener(type, listener);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
final NetworkTopologyEvent jmdnsEvent = new NetworkTopologyEventImpl(dns, address);
|
||||
for (final NetworkTopologyListener listener : this.networkListeners()) {
|
||||
_listenerExecutor.submit(new Runnable() {
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void run() {
|
||||
listener.inetAddressAdded(jmdnsEvent);
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
dns.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warning("Unexpected unhandled exception: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.NetworkTopologyListener#inetAddressRemoved(javax.jmdns.NetworkTopologyEvent)
|
||||
*/
|
||||
@Override
|
||||
public void inetAddressRemoved(NetworkTopologyEvent event) {
|
||||
InetAddress address = event.getInetAddress();
|
||||
try {
|
||||
if (_knownMDNS.containsKey(address)) {
|
||||
synchronized (_knownMDNS) {
|
||||
if (_knownMDNS.containsKey(address)) {
|
||||
JmDNS mDNS = _knownMDNS.remove(address);
|
||||
mDNS.close();
|
||||
final NetworkTopologyEvent jmdnsEvent = new NetworkTopologyEventImpl(mDNS, address);
|
||||
for (final NetworkTopologyListener listener : this.networkListeners()) {
|
||||
_listenerExecutor.submit(new Runnable() {
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void run() {
|
||||
listener.inetAddressRemoved(jmdnsEvent);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warning("Unexpected unhandled exception: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the network state.<br/>
|
||||
* If the network change, this class will reconfigure the list of DNS do adapt to the new configuration.
|
||||
*/
|
||||
static class NetworkChecker extends TimerTask {
|
||||
private static Logger logger1 = Logger.getLogger(NetworkChecker.class.getName());
|
||||
|
||||
private final NetworkTopologyListener _mmDNS;
|
||||
|
||||
private final NetworkTopologyDiscovery _topology;
|
||||
|
||||
private Set<InetAddress> _knownAddresses;
|
||||
|
||||
public NetworkChecker(NetworkTopologyListener mmDNS, NetworkTopologyDiscovery topology) {
|
||||
super();
|
||||
this._mmDNS = mmDNS;
|
||||
this._topology = topology;
|
||||
_knownAddresses = Collections.synchronizedSet(new HashSet<InetAddress>());
|
||||
}
|
||||
|
||||
public void start(Timer timer) {
|
||||
// Run once up-front otherwise the list of servers will only appear after a delay.
|
||||
run();
|
||||
timer.schedule(this, DNSConstants.NETWORK_CHECK_INTERVAL, DNSConstants.NETWORK_CHECK_INTERVAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
InetAddress[] curentAddresses = _topology.getInetAddresses();
|
||||
Set<InetAddress> current = new HashSet<InetAddress>(curentAddresses.length);
|
||||
for (InetAddress address : curentAddresses) {
|
||||
current.add(address);
|
||||
if (!_knownAddresses.contains(address)) {
|
||||
final NetworkTopologyEvent event = new NetworkTopologyEventImpl(_mmDNS, address);
|
||||
_mmDNS.inetAddressAdded(event);
|
||||
}
|
||||
}
|
||||
for (InetAddress address : _knownAddresses) {
|
||||
if (!current.contains(address)) {
|
||||
final NetworkTopologyEvent event = new NetworkTopologyEventImpl(_mmDNS, address);
|
||||
_mmDNS.inetAddressRemoved(event);
|
||||
}
|
||||
}
|
||||
_knownAddresses = current;
|
||||
} catch (Exception e) {
|
||||
logger1.warning("Unexpected unhandled exception: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,286 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import java.util.EventListener;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.JmDNS;
|
||||
import javax.jmdns.ServiceEvent;
|
||||
import javax.jmdns.ServiceInfo;
|
||||
import javax.jmdns.ServiceListener;
|
||||
import javax.jmdns.ServiceTypeListener;
|
||||
|
||||
/**
|
||||
* This class track the status of listener.<br/>
|
||||
* The main purpose of this class is to collapse consecutive events so that we can guarantee the correct call back sequence.
|
||||
*
|
||||
* @param <T>
|
||||
* listener type
|
||||
*/
|
||||
public class ListenerStatus<T extends EventListener> {
|
||||
|
||||
public static class ServiceListenerStatus extends ListenerStatus<ServiceListener> {
|
||||
private static Logger logger = Logger.getLogger(ServiceListenerStatus.class.getName());
|
||||
|
||||
private final ConcurrentMap<String, ServiceInfo> _addedServices;
|
||||
|
||||
/**
|
||||
* @param listener
|
||||
* listener being tracked.
|
||||
* @param synch
|
||||
* true if that listener can be called asynchronously
|
||||
*/
|
||||
public ServiceListenerStatus(ServiceListener listener, boolean synch) {
|
||||
super(listener, synch);
|
||||
_addedServices = new ConcurrentHashMap<String, ServiceInfo>(32);
|
||||
}
|
||||
|
||||
/**
|
||||
* A service has been added.<br/>
|
||||
* <b>Note:</b>This event is only the service added event. The service info associated with this event does not include resolution information.<br/>
|
||||
* To get the full resolved information you need to listen to {@link #serviceResolved(ServiceEvent)} or call {@link JmDNS#getServiceInfo(String, String, long)}
|
||||
*
|
||||
* <pre>
|
||||
* ServiceInfo info = event.getDNS().getServiceInfo(event.getType(), event.getName())
|
||||
* </pre>
|
||||
* <p>
|
||||
* Please note that service resolution may take a few second to resolve.
|
||||
* </p>
|
||||
*
|
||||
* @param event
|
||||
* The ServiceEvent providing the name and fully qualified type of the service.
|
||||
*/
|
||||
void serviceAdded(ServiceEvent event) {
|
||||
String qualifiedName = event.getName() + "." + event.getType();
|
||||
if (null == _addedServices.putIfAbsent(qualifiedName, event.getInfo().clone())) {
|
||||
this.getListener().serviceAdded(event);
|
||||
ServiceInfo info = event.getInfo();
|
||||
if ((info != null) && (info.hasData())) {
|
||||
this.getListener().serviceResolved(event);
|
||||
}
|
||||
} else {
|
||||
logger.finer("Service Added called for a service already added: " + event);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A service has been removed.
|
||||
*
|
||||
* @param event
|
||||
* The ServiceEvent providing the name and fully qualified type of the service.
|
||||
*/
|
||||
void serviceRemoved(ServiceEvent event) {
|
||||
String qualifiedName = event.getName() + "." + event.getType();
|
||||
if (_addedServices.remove(qualifiedName, _addedServices.get(qualifiedName))) {
|
||||
this.getListener().serviceRemoved(event);
|
||||
} else {
|
||||
logger.finer("Service Removed called for a service already removed: " + event);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder aLog = new StringBuilder(2048);
|
||||
aLog.append("[Status for ");
|
||||
aLog.append(this.getListener().toString());
|
||||
if (_addedServices.isEmpty()) {
|
||||
aLog.append(" no type event ");
|
||||
} else {
|
||||
aLog.append(" (");
|
||||
for (String service : _addedServices.keySet()) {
|
||||
aLog.append(service + ", ");
|
||||
}
|
||||
aLog.append(") ");
|
||||
}
|
||||
aLog.append("]");
|
||||
return aLog.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class ServiceTypeListenerStatus extends ListenerStatus<ServiceTypeListener> {
|
||||
private static Logger logger = Logger.getLogger(ServiceTypeListenerStatus.class.getName());
|
||||
|
||||
private final ConcurrentMap<String, String> _addedTypes;
|
||||
|
||||
/**
|
||||
* @param listener
|
||||
* listener being tracked.
|
||||
* @param synch
|
||||
* true if that listener can be called asynchronously
|
||||
*/
|
||||
public ServiceTypeListenerStatus(ServiceTypeListener listener, boolean synch) {
|
||||
super(listener, synch);
|
||||
_addedTypes = new ConcurrentHashMap<String, String>(32);
|
||||
}
|
||||
|
||||
/**
|
||||
* A new service type was discovered.
|
||||
*
|
||||
* @param event
|
||||
* The service event providing the fully qualified type of the service.
|
||||
*/
|
||||
void serviceTypeAdded(ServiceEvent event) {
|
||||
if (null == _addedTypes.putIfAbsent(event.getType(), event.getType())) {
|
||||
this.getListener().serviceTypeAdded(event);
|
||||
} else {
|
||||
logger.finest("Service Type Added called for a service type already added: " + event);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A new subtype for the service type was discovered.
|
||||
*
|
||||
* <pre>
|
||||
* <sub>._sub.<app>.<protocol>.<servicedomain>.<parentdomain>.
|
||||
* </pre>
|
||||
*
|
||||
* @param event
|
||||
* The service event providing the fully qualified type of the service with subtype.
|
||||
*/
|
||||
void subTypeForServiceTypeAdded(ServiceEvent event) {
|
||||
if (null == _addedTypes.putIfAbsent(event.getType(), event.getType())) {
|
||||
this.getListener().subTypeForServiceTypeAdded(event);
|
||||
} else {
|
||||
logger.finest("Service Sub Type Added called for a service sub type already added: " + event);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder aLog = new StringBuilder(2048);
|
||||
aLog.append("[Status for ");
|
||||
aLog.append(this.getListener().toString());
|
||||
if (_addedTypes.isEmpty()) {
|
||||
aLog.append(" no type event ");
|
||||
} else {
|
||||
aLog.append(" (");
|
||||
for (String type : _addedTypes.keySet()) {
|
||||
aLog.append(type + ", ");
|
||||
}
|
||||
aLog.append(") ");
|
||||
}
|
||||
aLog.append("]");
|
||||
return aLog.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public final static boolean SYNCHONEOUS = true;
|
||||
public final static boolean ASYNCHONEOUS = false;
|
||||
|
||||
private final T _listener;
|
||||
|
||||
private final boolean _synch;
|
||||
|
||||
/**
|
||||
* @param listener
|
||||
* listener being tracked.
|
||||
* @param synch
|
||||
* true if that listener can be called asynchronously
|
||||
*/
|
||||
public ListenerStatus(T listener, boolean synch) {
|
||||
super();
|
||||
_listener = listener;
|
||||
_synch = synch;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the listener
|
||||
*/
|
||||
public T getListener() {
|
||||
return _listener;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return <cod>true</code> if the listener must be called synchronously.
|
||||
*
|
||||
* @return the synch
|
||||
*/
|
||||
public boolean isSynchronous() {
|
||||
return _synch;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#hashCode()
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return this.getListener().hashCode();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#equals(java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return (obj instanceof ListenerStatus) && this.getListener().equals(((ListenerStatus<?>) obj).getListener());
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return "[Status for " + this.getListener().toString() + "]";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,274 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public interface NameRegister {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public enum NameType {
|
||||
/**
|
||||
* This name represents a host name
|
||||
*/
|
||||
HOST,
|
||||
/**
|
||||
* This name represents a service name
|
||||
*/
|
||||
SERVICE,
|
||||
}
|
||||
|
||||
public static abstract class BaseRegister implements NameRegister {
|
||||
|
||||
protected String incrementNameWithDash(String name) {
|
||||
StringBuilder givenName = new StringBuilder(name.length() + 5);
|
||||
int hostNameCount = 0;
|
||||
int plocal = name.indexOf(".local.");
|
||||
int punder = name.lastIndexOf('-');
|
||||
if (punder < 0) {
|
||||
// This is the first increment
|
||||
hostNameCount = 1;
|
||||
givenName.append(name.substring(0, plocal));
|
||||
} else {
|
||||
try {
|
||||
int value = Integer.parseInt(name.substring(punder + 1, plocal));
|
||||
hostNameCount = value + 1;
|
||||
givenName.append(name.substring(0, punder));
|
||||
} catch (Exception e) {
|
||||
// If we got an exception this means that we have a name with a "-"
|
||||
hostNameCount = 1;
|
||||
givenName.append(name.substring(0, plocal));
|
||||
}
|
||||
}
|
||||
givenName.append('-');
|
||||
givenName.append(hostNameCount);
|
||||
givenName.append(".local.");
|
||||
return givenName.toString();
|
||||
}
|
||||
|
||||
protected String incrementNameWithParentesis(String name) {
|
||||
StringBuilder givenName = new StringBuilder(name.length() + 5);
|
||||
final int l = name.lastIndexOf('(');
|
||||
final int r = name.lastIndexOf(')');
|
||||
if ((l >= 0) && (l < r)) {
|
||||
try {
|
||||
givenName.append(name.substring(0, l));
|
||||
givenName.append('(');
|
||||
givenName.append(Integer.parseInt(name.substring(l + 1, r)) + 1);
|
||||
givenName.append(')');
|
||||
} catch (final NumberFormatException e) {
|
||||
givenName.setLength(0);
|
||||
givenName.append(name);
|
||||
givenName.append(" (2)");
|
||||
}
|
||||
} else {
|
||||
givenName.append(name);
|
||||
givenName.append(" (2)");
|
||||
}
|
||||
return givenName.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class UniqueNamePerInterface extends BaseRegister {
|
||||
|
||||
private final ConcurrentMap<InetAddress, String> _hostNames;
|
||||
private final ConcurrentMap<InetAddress, Set<String>> _serviceNames;
|
||||
|
||||
public UniqueNamePerInterface() {
|
||||
super();
|
||||
_hostNames = new ConcurrentHashMap<InetAddress, String>();
|
||||
_serviceNames = new ConcurrentHashMap<InetAddress, Set<String>>();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.NameRegister#register(java.net.InetAddress, java.lang.String, javax.jmdns.impl.NameRegister.NameType)
|
||||
*/
|
||||
@Override
|
||||
public void register(InetAddress networkInterface, String name, NameType type) {
|
||||
switch (type) {
|
||||
case HOST:
|
||||
break;
|
||||
case SERVICE:
|
||||
break;
|
||||
default:
|
||||
// this is trash to keep the compiler happy
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.NameRegister#checkName(java.net.InetAddress, java.lang.String, javax.jmdns.impl.NameRegister.NameType)
|
||||
*/
|
||||
@Override
|
||||
public boolean checkName(InetAddress networkInterface, String name, NameType type) {
|
||||
switch (type) {
|
||||
case HOST:
|
||||
String hostname = _hostNames.get(networkInterface);
|
||||
return hostname != null && hostname.equals(name);
|
||||
case SERVICE:
|
||||
Set<String> names = _serviceNames.get(networkInterface);
|
||||
return names != null && names.contains(names);
|
||||
default:
|
||||
// this is trash to keep the compiler happy
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.NameRegister#incrementHostName(java.net.InetAddress, java.lang.String, javax.jmdns.impl.NameRegister.NameType)
|
||||
*/
|
||||
@Override
|
||||
public String incrementName(InetAddress networkInterface, String name, NameType type) {
|
||||
switch (type) {
|
||||
case HOST:
|
||||
return this.incrementNameWithDash(name);
|
||||
case SERVICE:
|
||||
return this.incrementNameWithParentesis(name);
|
||||
default:
|
||||
// this is trash to keep the compiler happy
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class UniqueNameAcrossInterface extends BaseRegister {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.NameRegister#register(java.net.InetAddress, java.lang.String, javax.jmdns.impl.NameRegister.NameType)
|
||||
*/
|
||||
@Override
|
||||
public void register(InetAddress networkInterface, String name, NameType type) {
|
||||
switch (type) {
|
||||
case HOST:
|
||||
break;
|
||||
case SERVICE:
|
||||
break;
|
||||
default:
|
||||
// this is trash to keep the compiler happy
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.NameRegister#checkName(java.net.InetAddress, java.lang.String, javax.jmdns.impl.NameRegister.NameType)
|
||||
*/
|
||||
@Override
|
||||
public boolean checkName(InetAddress networkInterface, String name, NameType type) {
|
||||
switch (type) {
|
||||
case HOST:
|
||||
return false;
|
||||
case SERVICE:
|
||||
return false;
|
||||
default:
|
||||
// this is trash to keep the compiler happy
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.NameRegister#incrementHostName(java.net.InetAddress, java.lang.String, javax.jmdns.impl.NameRegister.NameType)
|
||||
*/
|
||||
@Override
|
||||
public String incrementName(InetAddress networkInterface, String name, NameType type) {
|
||||
switch (type) {
|
||||
case HOST:
|
||||
return this.incrementNameWithDash(name);
|
||||
case SERVICE:
|
||||
return this.incrementNameWithParentesis(name);
|
||||
default:
|
||||
// this is trash to keep the compiler happy
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class Factory {
|
||||
|
||||
private static volatile NameRegister _register;
|
||||
|
||||
/**
|
||||
* Register a Name register.
|
||||
*
|
||||
* @param register
|
||||
* new register
|
||||
* @throws IllegalStateException
|
||||
* the register can only be set once
|
||||
*/
|
||||
public static void setRegistry(NameRegister register) throws IllegalStateException {
|
||||
if (_register != null) {
|
||||
throw new IllegalStateException("The register can only be set once.");
|
||||
}
|
||||
if (register != null) {
|
||||
_register = register;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name register.
|
||||
*
|
||||
* @return name register
|
||||
*/
|
||||
public static NameRegister getRegistry() {
|
||||
if (_register == null) {
|
||||
_register = new UniqueNamePerInterface();
|
||||
}
|
||||
return _register;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a name that is defended by this group of mDNS.
|
||||
*
|
||||
* @param networkInterface
|
||||
* IP address to handle
|
||||
* @param name
|
||||
* name to register
|
||||
* @param type
|
||||
* name type to register
|
||||
*/
|
||||
public abstract void register(InetAddress networkInterface, String name, NameType type);
|
||||
|
||||
/**
|
||||
* Checks a name that is defended by this group of mDNS.
|
||||
*
|
||||
* @param networkInterface
|
||||
* IP address to handle
|
||||
* @param name
|
||||
* name to check
|
||||
* @param type
|
||||
* name type to check
|
||||
* @return <code>true</code> if the name is not in conflict, <code>flase</code> otherwise.
|
||||
*/
|
||||
public abstract boolean checkName(InetAddress networkInterface, String name, NameType type);
|
||||
|
||||
/**
|
||||
* Increments a name that is defended by this group of mDNS after it has been found in conflict.
|
||||
*
|
||||
* @param networkInterface
|
||||
* IP address to handle
|
||||
* @param name
|
||||
* name to increment
|
||||
* @param type
|
||||
* name type to increments
|
||||
* @return new name
|
||||
*/
|
||||
public abstract String incrementName(InetAddress networkInterface, String name, NameType type);
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,129 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.NetworkTopologyDiscovery;
|
||||
|
||||
/**
|
||||
* This class implements NetworkTopologyDiscovery.
|
||||
*
|
||||
* @author Pierre Frisch
|
||||
*/
|
||||
public class NetworkTopologyDiscoveryImpl implements NetworkTopologyDiscovery {
|
||||
private final static Logger logger = Logger.getLogger(NetworkTopologyDiscoveryImpl.class.getName());
|
||||
|
||||
private final Method _isUp;
|
||||
|
||||
private final Method _supportsMulticast;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public NetworkTopologyDiscoveryImpl() {
|
||||
super();
|
||||
Method isUp;
|
||||
try {
|
||||
isUp = NetworkInterface.class.getMethod("isUp", (Class<?>[]) null);
|
||||
} catch (Exception exception) {
|
||||
// We do not want to throw anything if the method does not exist.
|
||||
isUp = null;
|
||||
}
|
||||
_isUp = isUp;
|
||||
Method supportsMulticast;
|
||||
try {
|
||||
supportsMulticast = NetworkInterface.class.getMethod("supportsMulticast", (Class<?>[]) null);
|
||||
} catch (Exception exception) {
|
||||
// We do not want to throw anything if the method does not exist.
|
||||
supportsMulticast = null;
|
||||
}
|
||||
_supportsMulticast = supportsMulticast;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS.NetworkTopologyDiscovery#getInetAddresses()
|
||||
*/
|
||||
@Override
|
||||
public InetAddress[] getInetAddresses() {
|
||||
Set<InetAddress> result = new HashSet<InetAddress>();
|
||||
try {
|
||||
|
||||
for (Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces(); nifs.hasMoreElements();) {
|
||||
NetworkInterface nif = nifs.nextElement();
|
||||
for (Enumeration<InetAddress> iaenum = nif.getInetAddresses(); iaenum.hasMoreElements();) {
|
||||
InetAddress interfaceAddress = iaenum.nextElement();
|
||||
if (logger.isLoggable(Level.FINEST)) {
|
||||
logger.finest("Found NetworkInterface/InetAddress: " + nif + " -- " + interfaceAddress);
|
||||
}
|
||||
if (this.useInetAddress(nif, interfaceAddress)) {
|
||||
result.add(interfaceAddress);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (SocketException se) {
|
||||
logger.warning("Error while fetching network interfaces addresses: " + se);
|
||||
}
|
||||
return result.toArray(new InetAddress[result.size()]);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.JmmDNS.NetworkTopologyDiscovery#useInetAddress(java.net.NetworkInterface, java.net.InetAddress)
|
||||
*/
|
||||
@Override
|
||||
public boolean useInetAddress(NetworkInterface networkInterface, InetAddress interfaceAddress) {
|
||||
try {
|
||||
if (_isUp != null) {
|
||||
try {
|
||||
if (!((Boolean) _isUp.invoke(networkInterface, (Object[]) null)).booleanValue()) {
|
||||
return false;
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
// We should hide that exception.
|
||||
}
|
||||
}
|
||||
if (_supportsMulticast != null) {
|
||||
try {
|
||||
if (!((Boolean) _supportsMulticast.invoke(networkInterface, (Object[]) null)).booleanValue()) {
|
||||
return false;
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
// We should hide that exception.
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (Exception exception) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.NetworkTopologyDiscovery#lockInetAddress(java.net.InetAddress)
|
||||
*/
|
||||
@Override
|
||||
public void lockInetAddress(InetAddress interfaceAddress) {
|
||||
// Default implementation does nothing.
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.NetworkTopologyDiscovery#unlockInetAddress(java.net.InetAddress)
|
||||
*/
|
||||
@Override
|
||||
public void unlockInetAddress(InetAddress interfaceAddress) {
|
||||
// Default implementation does nothing.
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import java.net.InetAddress;
|
||||
|
||||
import javax.jmdns.JmDNS;
|
||||
import javax.jmdns.NetworkTopologyEvent;
|
||||
import javax.jmdns.NetworkTopologyListener;
|
||||
|
||||
/**
|
||||
* @author Cédrik Lime, Pierre Frisch
|
||||
*/
|
||||
public class NetworkTopologyEventImpl extends NetworkTopologyEvent implements Cloneable {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1445606146153550463L;
|
||||
|
||||
private final InetAddress _inetAddress;
|
||||
|
||||
/**
|
||||
* Constructs a Network Topology Event.
|
||||
*
|
||||
* @param jmDNS
|
||||
* @param inetAddress
|
||||
* @exception IllegalArgumentException
|
||||
* if source is null.
|
||||
*/
|
||||
public NetworkTopologyEventImpl(JmDNS jmDNS, InetAddress inetAddress) {
|
||||
super(jmDNS);
|
||||
this._inetAddress = inetAddress;
|
||||
}
|
||||
|
||||
NetworkTopologyEventImpl(NetworkTopologyListener jmmDNS, InetAddress inetAddress) {
|
||||
super(jmmDNS);
|
||||
this._inetAddress = inetAddress;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.NetworkTopologyEvent#getDNS()
|
||||
*/
|
||||
@Override
|
||||
public JmDNS getDNS() {
|
||||
return (this.getSource() instanceof JmDNS ? (JmDNS) getSource() : null);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.NetworkTopologyEvent#getInetAddress()
|
||||
*/
|
||||
@Override
|
||||
public InetAddress getInetAddress() {
|
||||
return _inetAddress;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder buf = new StringBuilder();
|
||||
buf.append("[" + this.getClass().getSimpleName() + "@" + System.identityHashCode(this) + " ");
|
||||
buf.append("\n\tinetAddress: '");
|
||||
buf.append(this.getInetAddress());
|
||||
buf.append("']");
|
||||
// buf.append("' source: ");
|
||||
// buf.append("\n\t" + source + "");
|
||||
// buf.append("\n]");
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#clone()
|
||||
*/
|
||||
@Override
|
||||
public NetworkTopologyEventImpl clone() throws CloneNotSupportedException {
|
||||
return new NetworkTopologyEventImpl(getDNS(), getInetAddress());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,124 @@
|
|||
// /Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import javax.jmdns.JmDNS;
|
||||
import javax.jmdns.ServiceEvent;
|
||||
import javax.jmdns.ServiceInfo;
|
||||
|
||||
/**
|
||||
* ServiceEvent.
|
||||
*
|
||||
* @author Werner Randelshofer, Rick Blair
|
||||
*/
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public class ServiceEventImpl extends ServiceEvent {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 7107973622016897488L;
|
||||
// private static Logger logger = Logger.getLogger(ServiceEvent.class.getName());
|
||||
/**
|
||||
* The type name of the service.
|
||||
*/
|
||||
private final String _type;
|
||||
/**
|
||||
* The instance name of the service. Or null, if the event was fired to a service type listener.
|
||||
*/
|
||||
private final String _name;
|
||||
/**
|
||||
* The service info record, or null if the service could be be resolved. This is also null, if the event was fired to a service type listener.
|
||||
*/
|
||||
private final ServiceInfo _info;
|
||||
|
||||
/**
|
||||
* Creates a new instance.
|
||||
*
|
||||
* @param jmDNS
|
||||
* the JmDNS instance which originated the event.
|
||||
* @param type
|
||||
* the type name of the service.
|
||||
* @param name
|
||||
* the instance name of the service.
|
||||
* @param info
|
||||
* the service info record, or null if the service could be be resolved.
|
||||
*/
|
||||
public ServiceEventImpl(JmDNSImpl jmDNS, String type, String name, ServiceInfo info) {
|
||||
super(jmDNS);
|
||||
this._type = type;
|
||||
this._name = name;
|
||||
this._info = info;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.ServiceEvent#getDNS()
|
||||
*/
|
||||
@Override
|
||||
public JmDNS getDNS() {
|
||||
return (JmDNS) getSource();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.ServiceEvent#getType()
|
||||
*/
|
||||
@Override
|
||||
public String getType() {
|
||||
return _type;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.ServiceEvent#getName()
|
||||
*/
|
||||
@Override
|
||||
public String getName() {
|
||||
return _name;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.util.EventObject#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder buf = new StringBuilder();
|
||||
buf.append("[" + this.getClass().getSimpleName() + "@" + System.identityHashCode(this) + " ");
|
||||
buf.append("\n\tname: '");
|
||||
buf.append(this.getName());
|
||||
buf.append("' type: '");
|
||||
buf.append(this.getType());
|
||||
buf.append("' info: '");
|
||||
buf.append(this.getInfo());
|
||||
buf.append("']");
|
||||
// buf.append("' source: ");
|
||||
// buf.append("\n\t" + source + "");
|
||||
// buf.append("\n]");
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.ServiceEvent#getInfo()
|
||||
*/
|
||||
@Override
|
||||
public ServiceInfo getInfo() {
|
||||
return _info;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.ServiceEvent#clone()
|
||||
*/
|
||||
@Override
|
||||
public ServiceEventImpl clone() {
|
||||
ServiceInfoImpl newInfo = new ServiceInfoImpl(this.getInfo());
|
||||
return new ServiceEventImpl((JmDNSImpl) this.getDNS(), this.getType(), this.getName(), newInfo);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
|
||||
/**
|
||||
* Listen for multicast packets.
|
||||
*/
|
||||
class SocketListener extends Thread {
|
||||
static Logger logger = Logger.getLogger(SocketListener.class.getName());
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private final JmDNSImpl _jmDNSImpl;
|
||||
|
||||
/**
|
||||
* @param jmDNSImpl
|
||||
*/
|
||||
SocketListener(JmDNSImpl jmDNSImpl) {
|
||||
super("SocketListener(" + (jmDNSImpl != null ? jmDNSImpl.getName() : "") + ")");
|
||||
this.setDaemon(true);
|
||||
this._jmDNSImpl = jmDNSImpl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
byte buf[] = new byte[DNSConstants.MAX_MSG_ABSOLUTE];
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length);
|
||||
while (!this._jmDNSImpl.isCanceling() && !this._jmDNSImpl.isCanceled()) {
|
||||
packet.setLength(buf.length);
|
||||
this._jmDNSImpl.getSocket().receive(packet);
|
||||
if (this._jmDNSImpl.isCanceling() || this._jmDNSImpl.isCanceled() || this._jmDNSImpl.isClosing() || this._jmDNSImpl.isClosed()) {
|
||||
break;
|
||||
}
|
||||
try {
|
||||
if (this._jmDNSImpl.getLocalHost().shouldIgnorePacket(packet)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
DNSIncoming msg = new DNSIncoming(packet);
|
||||
if (msg.isValidResponseCode()) {
|
||||
if (logger.isLoggable(Level.FINEST)) {
|
||||
logger.finest(this.getName() + ".run() JmDNS in:" + msg.print(true));
|
||||
}
|
||||
if (msg.isQuery()) {
|
||||
if (packet.getPort() != DNSConstants.MDNS_PORT) {
|
||||
this._jmDNSImpl.handleQuery(msg, packet.getAddress(), packet.getPort());
|
||||
}
|
||||
this._jmDNSImpl.handleQuery(msg, this._jmDNSImpl.getGroup(), DNSConstants.MDNS_PORT);
|
||||
} else {
|
||||
this._jmDNSImpl.handleResponse(msg);
|
||||
}
|
||||
} else {
|
||||
if (logger.isLoggable(Level.FINE)) {
|
||||
logger.fine(this.getName() + ".run() JmDNS in message with error code:" + msg.print(true));
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
logger.log(Level.WARNING, this.getName() + ".run() exception ", e);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
if (!this._jmDNSImpl.isCanceling() && !this._jmDNSImpl.isCanceled() && !this._jmDNSImpl.isClosing() && !this._jmDNSImpl.isClosed()) {
|
||||
logger.log(Level.WARNING, this.getName() + ".run() exception ", e);
|
||||
this._jmDNSImpl.recover();
|
||||
}
|
||||
}
|
||||
if (logger.isLoggable(Level.FINEST)) {
|
||||
logger.finest(this.getName() + ".run() exiting.");
|
||||
}
|
||||
}
|
||||
|
||||
public JmDNSImpl getDns() {
|
||||
return _jmDNSImpl;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl.constants;
|
||||
|
||||
/**
|
||||
* DNS constants.
|
||||
*
|
||||
* @author Arthur van Hoff, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Rick Blair
|
||||
*/
|
||||
public final class DNSConstants {
|
||||
// http://www.iana.org/assignments/dns-parameters
|
||||
|
||||
// changed to final class - jeffs
|
||||
public static final String MDNS_GROUP = "224.0.0.251";
|
||||
public static final String MDNS_GROUP_IPV6 = "FF02::FB";
|
||||
public static final int MDNS_PORT = Integer.parseInt(System.getProperty("net.mdns.port", "5353"));
|
||||
public static final int DNS_PORT = 53;
|
||||
public static final int DNS_TTL = 60 * 60; // default one hour TTL
|
||||
// public static final int DNS_TTL = 120 * 60; // two hour TTL (draft-cheshire-dnsext-multicastdns.txt ch 13)
|
||||
|
||||
public static final int MAX_MSG_TYPICAL = 1460;
|
||||
public static final int MAX_MSG_ABSOLUTE = 8972;
|
||||
|
||||
public static final int FLAGS_QR_MASK = 0x8000; // Query response mask
|
||||
public static final int FLAGS_QR_QUERY = 0x0000; // Query
|
||||
public static final int FLAGS_QR_RESPONSE = 0x8000; // Response
|
||||
|
||||
public static final int FLAGS_OPCODE = 0x7800; // Operation code
|
||||
public static final int FLAGS_AA = 0x0400; // Authorative answer
|
||||
public static final int FLAGS_TC = 0x0200; // Truncated
|
||||
public static final int FLAGS_RD = 0x0100; // Recursion desired
|
||||
public static final int FLAGS_RA = 0x8000; // Recursion available
|
||||
|
||||
public static final int FLAGS_Z = 0x0040; // Zero
|
||||
public static final int FLAGS_AD = 0x0020; // Authentic data
|
||||
public static final int FLAGS_CD = 0x0010; // Checking disabled
|
||||
public static final int FLAGS_RCODE = 0x000F; // Response code
|
||||
|
||||
// Time Intervals for various functions
|
||||
|
||||
public static final int SHARED_QUERY_TIME = 20; // milliseconds before send shared query
|
||||
public static final int QUERY_WAIT_INTERVAL = 225; // milliseconds between query loops.
|
||||
public static final int PROBE_WAIT_INTERVAL = 250; // milliseconds between probe loops.
|
||||
public static final int RESPONSE_MIN_WAIT_INTERVAL = 20; // minimal wait interval for response.
|
||||
public static final int RESPONSE_MAX_WAIT_INTERVAL = 115; // maximal wait interval for response
|
||||
public static final int PROBE_CONFLICT_INTERVAL = 1000; // milliseconds to wait after conflict.
|
||||
public static final int PROBE_THROTTLE_COUNT = 10; // After x tries go 1 time a sec. on probes.
|
||||
public static final int PROBE_THROTTLE_COUNT_INTERVAL = 5000; // We only increment the throttle count, if the previous increment is inside this interval.
|
||||
public static final int ANNOUNCE_WAIT_INTERVAL = 1000; // milliseconds between Announce loops.
|
||||
public static final int RECORD_REAPER_INTERVAL = 10000; // milliseconds between cache cleanups.
|
||||
public static final int RECORD_EXPIRY_DELAY = 1; // This is 1s delay used in ttl and therefore in seconds
|
||||
public static final int KNOWN_ANSWER_TTL = 120;
|
||||
public static final int ANNOUNCED_RENEWAL_TTL_INTERVAL = DNS_TTL * 500; // 50% of the TTL in milliseconds
|
||||
|
||||
public static final long CLOSE_TIMEOUT = ANNOUNCE_WAIT_INTERVAL * 5L;
|
||||
public static final long SERVICE_INFO_TIMEOUT = ANNOUNCE_WAIT_INTERVAL * 6L;
|
||||
|
||||
public static final int NETWORK_CHECK_INTERVAL = 10 * 1000; // 10 secondes
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns.impl.constants;
|
||||
|
||||
/**
|
||||
* DNS label.
|
||||
*
|
||||
* @author Arthur van Hoff, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Rick Blair
|
||||
*/
|
||||
public enum DNSLabel {
|
||||
/**
|
||||
* This is unallocated.
|
||||
*/
|
||||
Unknown("", 0x80),
|
||||
/**
|
||||
* Standard label [RFC 1035]
|
||||
*/
|
||||
Standard("standard label", 0x00),
|
||||
/**
|
||||
* Compressed label [RFC 1035]
|
||||
*/
|
||||
Compressed("compressed label", 0xC0),
|
||||
/**
|
||||
* Extended label [RFC 2671]
|
||||
*/
|
||||
Extended("extended label", 0x40);
|
||||
|
||||
/**
|
||||
* DNS label types are encoded on the first 2 bits
|
||||
*/
|
||||
static final int LABEL_MASK = 0xC0;
|
||||
static final int LABEL_NOT_MASK = 0x3F;
|
||||
|
||||
private final String _externalName;
|
||||
|
||||
private final int _index;
|
||||
|
||||
DNSLabel(String name, int index) {
|
||||
_externalName = name;
|
||||
_index = index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the string representation of this type
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public String externalName() {
|
||||
return _externalName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the numeric value of this type
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public int indexValue() {
|
||||
return _index;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param index
|
||||
* @return label
|
||||
*/
|
||||
public static DNSLabel labelForByte(int index) {
|
||||
int maskedIndex = index & LABEL_MASK;
|
||||
for (DNSLabel aLabel : DNSLabel.values()) {
|
||||
if (aLabel._index == maskedIndex) return aLabel;
|
||||
}
|
||||
return Unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param index
|
||||
* @return masked value
|
||||
*/
|
||||
public static int labelValue(int index) {
|
||||
return index & LABEL_NOT_MASK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.name() + " index " + this.indexValue();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns.impl.constants;
|
||||
|
||||
/**
|
||||
* DNS operation code.
|
||||
*
|
||||
* @author Arthur van Hoff, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Rick Blair
|
||||
*/
|
||||
public enum DNSOperationCode {
|
||||
/**
|
||||
* Query [RFC1035]
|
||||
*/
|
||||
Query("Query", 0),
|
||||
/**
|
||||
* IQuery (Inverse Query, Obsolete) [RFC3425]
|
||||
*/
|
||||
IQuery("Inverse Query", 1),
|
||||
/**
|
||||
* Status [RFC1035]
|
||||
*/
|
||||
Status("Status", 2),
|
||||
/**
|
||||
* Unassigned
|
||||
*/
|
||||
Unassigned("Unassigned", 3),
|
||||
/**
|
||||
* Notify [RFC1996]
|
||||
*/
|
||||
Notify("Notify", 4),
|
||||
/**
|
||||
* Update [RFC2136]
|
||||
*/
|
||||
Update("Update", 5);
|
||||
|
||||
/**
|
||||
* DNS RCode types are encoded on the last 4 bits
|
||||
*/
|
||||
static final int OpCode_MASK = 0x7800;
|
||||
|
||||
private final String _externalName;
|
||||
|
||||
private final int _index;
|
||||
|
||||
DNSOperationCode(String name, int index) {
|
||||
_externalName = name;
|
||||
_index = index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the string representation of this type
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public String externalName() {
|
||||
return _externalName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the numeric value of this type
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public int indexValue() {
|
||||
return _index;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param flags
|
||||
* @return label
|
||||
*/
|
||||
public static DNSOperationCode operationCodeForFlags(int flags) {
|
||||
int maskedIndex = (flags & OpCode_MASK) >> 11;
|
||||
for (DNSOperationCode aCode : DNSOperationCode.values()) {
|
||||
if (aCode._index == maskedIndex) return aCode;
|
||||
}
|
||||
return Unassigned;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.name() + " index " + this.indexValue();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns.impl.constants;
|
||||
|
||||
/**
|
||||
* DNS option code.
|
||||
*
|
||||
* @author Arthur van Hoff, Pierre Frisch, Rick Blair
|
||||
*/
|
||||
public enum DNSOptionCode {
|
||||
|
||||
/**
|
||||
* Token
|
||||
*/
|
||||
Unknown("Unknown", 65535),
|
||||
/**
|
||||
* Long-Lived Queries Option [http://files.dns-sd.org/draft-sekar-dns-llq.txt]
|
||||
*/
|
||||
LLQ("LLQ", 1),
|
||||
/**
|
||||
* Update Leases Option [http://files.dns-sd.org/draft-sekar-dns-ul.txt]
|
||||
*/
|
||||
UL("UL", 2),
|
||||
/**
|
||||
* Name Server Identifier Option [RFC5001]
|
||||
*/
|
||||
NSID("NSID", 3),
|
||||
/**
|
||||
* Owner Option [draft-cheshire-edns0-owner-option]
|
||||
*/
|
||||
Owner("Owner", 4);
|
||||
|
||||
private final String _externalName;
|
||||
|
||||
private final int _index;
|
||||
|
||||
DNSOptionCode(String name, int index) {
|
||||
_externalName = name;
|
||||
_index = index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the string representation of this type
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public String externalName() {
|
||||
return _externalName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the numeric value of this type
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public int indexValue() {
|
||||
return _index;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param optioncode
|
||||
* @return label
|
||||
*/
|
||||
public static DNSOptionCode resultCodeForFlags(int optioncode) {
|
||||
int maskedIndex = optioncode;
|
||||
for (DNSOptionCode aCode : DNSOptionCode.values()) {
|
||||
if (aCode._index == maskedIndex) return aCode;
|
||||
}
|
||||
return Unknown;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.name() + " index " + this.indexValue();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,138 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns.impl.constants;
|
||||
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* DNS Record Class
|
||||
*
|
||||
* @author Arthur van Hoff, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Rick Blair
|
||||
*/
|
||||
public enum DNSRecordClass {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
CLASS_UNKNOWN("?", 0),
|
||||
/**
|
||||
* static final Internet
|
||||
*/
|
||||
CLASS_IN("in", 1),
|
||||
/**
|
||||
* CSNET
|
||||
*/
|
||||
CLASS_CS("cs", 2),
|
||||
/**
|
||||
* CHAOS
|
||||
*/
|
||||
CLASS_CH("ch", 3),
|
||||
/**
|
||||
* Hesiod
|
||||
*/
|
||||
CLASS_HS("hs", 4),
|
||||
/**
|
||||
* Used in DNS UPDATE [RFC 2136]
|
||||
*/
|
||||
CLASS_NONE("none", 254),
|
||||
/**
|
||||
* Not a DNS class, but a DNS query class, meaning "all classes"
|
||||
*/
|
||||
CLASS_ANY("any", 255);
|
||||
|
||||
private static Logger logger = Logger.getLogger(DNSRecordClass.class.getName());
|
||||
|
||||
/**
|
||||
* Multicast DNS uses the bottom 15 bits to identify the record class...<br/>
|
||||
* Except for pseudo records like OPT.
|
||||
*/
|
||||
public static final int CLASS_MASK = 0x7FFF;
|
||||
|
||||
/**
|
||||
* For answers the top bit indicates that all other cached records are now invalid.<br/>
|
||||
* For questions it indicates that we should send a unicast response.
|
||||
*/
|
||||
public static final int CLASS_UNIQUE = 0x8000;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public static final boolean UNIQUE = true;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public static final boolean NOT_UNIQUE = false;
|
||||
|
||||
private final String _externalName;
|
||||
|
||||
private final int _index;
|
||||
|
||||
DNSRecordClass(String name, int index) {
|
||||
_externalName = name;
|
||||
_index = index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the string representation of this type
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public String externalName() {
|
||||
return _externalName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the numeric value of this type
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public int indexValue() {
|
||||
return _index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the class is unique
|
||||
*
|
||||
* @param index
|
||||
* @return <code>true</code> is the class is unique, <code>false</code> otherwise.
|
||||
*/
|
||||
public boolean isUnique(int index) {
|
||||
return (this != CLASS_UNKNOWN) && ((index & CLASS_UNIQUE) != 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param name
|
||||
* @return class for name
|
||||
*/
|
||||
public static DNSRecordClass classForName(String name) {
|
||||
if (name != null) {
|
||||
String aName = name.toLowerCase();
|
||||
for (DNSRecordClass aClass : DNSRecordClass.values()) {
|
||||
if (aClass._externalName.equals(aName)) return aClass;
|
||||
}
|
||||
}
|
||||
logger.log(Level.WARNING, "Could not find record class for name: " + name);
|
||||
return CLASS_UNKNOWN;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param index
|
||||
* @return class for name
|
||||
*/
|
||||
public static DNSRecordClass classForIndex(int index) {
|
||||
int maskedIndex = index & CLASS_MASK;
|
||||
for (DNSRecordClass aClass : DNSRecordClass.values()) {
|
||||
if (aClass._index == maskedIndex) return aClass;
|
||||
}
|
||||
logger.log(Level.WARNING, "Could not find record class for index: " + index);
|
||||
return CLASS_UNKNOWN;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.name() + " index " + this.indexValue();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,312 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns.impl.constants;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* DNS Record Type
|
||||
*
|
||||
* @author Arthur van Hoff, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Rick Blair
|
||||
*/
|
||||
public enum DNSRecordType {
|
||||
/**
|
||||
* Address
|
||||
*/
|
||||
TYPE_IGNORE("ignore", 0),
|
||||
/**
|
||||
* Address
|
||||
*/
|
||||
TYPE_A("a", 1),
|
||||
/**
|
||||
* Name Server
|
||||
*/
|
||||
TYPE_NS("ns", 2),
|
||||
/**
|
||||
* Mail Destination
|
||||
*/
|
||||
TYPE_MD("md", 3),
|
||||
/**
|
||||
* Mail Forwarder
|
||||
*/
|
||||
TYPE_MF("mf", 4),
|
||||
/**
|
||||
* Canonical Name
|
||||
*/
|
||||
TYPE_CNAME("cname", 5),
|
||||
/**
|
||||
* Start of Authority
|
||||
*/
|
||||
TYPE_SOA("soa", 6),
|
||||
/**
|
||||
* Mailbox
|
||||
*/
|
||||
TYPE_MB("mb", 7),
|
||||
/**
|
||||
* Mail Group
|
||||
*/
|
||||
TYPE_MG("mg", 8),
|
||||
/**
|
||||
* Mail Rename
|
||||
*/
|
||||
TYPE_MR("mr", 9),
|
||||
/**
|
||||
* NULL RR
|
||||
*/
|
||||
TYPE_NULL("null", 10),
|
||||
/**
|
||||
* Well-known-service
|
||||
*/
|
||||
TYPE_WKS("wks", 11),
|
||||
/**
|
||||
* Domain Name pointer
|
||||
*/
|
||||
TYPE_PTR("ptr", 12),
|
||||
/**
|
||||
* Host information
|
||||
*/
|
||||
TYPE_HINFO("hinfo", 13),
|
||||
/**
|
||||
* Mailbox information
|
||||
*/
|
||||
TYPE_MINFO("minfo", 14),
|
||||
/**
|
||||
* Mail exchanger
|
||||
*/
|
||||
TYPE_MX("mx", 15),
|
||||
/**
|
||||
* Arbitrary text string
|
||||
*/
|
||||
TYPE_TXT("txt", 16),
|
||||
/**
|
||||
* for Responsible Person [RFC1183]
|
||||
*/
|
||||
TYPE_RP("rp", 17),
|
||||
/**
|
||||
* for AFS Data Base location [RFC1183]
|
||||
*/
|
||||
TYPE_AFSDB("afsdb", 18),
|
||||
/**
|
||||
* for X.25 PSDN address [RFC1183]
|
||||
*/
|
||||
TYPE_X25("x25", 19),
|
||||
/**
|
||||
* for ISDN address [RFC1183]
|
||||
*/
|
||||
TYPE_ISDN("isdn", 20),
|
||||
/**
|
||||
* for Route Through [RFC1183]
|
||||
*/
|
||||
TYPE_RT("rt", 21),
|
||||
/**
|
||||
* for NSAP address, NSAP style A record [RFC1706]
|
||||
*/
|
||||
TYPE_NSAP("nsap", 22),
|
||||
/**
|
||||
*
|
||||
*/
|
||||
TYPE_NSAP_PTR("nsap-otr", 23),
|
||||
/**
|
||||
* for security signature [RFC2931]
|
||||
*/
|
||||
TYPE_SIG("sig", 24),
|
||||
/**
|
||||
* for security key [RFC2535]
|
||||
*/
|
||||
TYPE_KEY("key", 25),
|
||||
/**
|
||||
* X.400 mail mapping information [RFC2163]
|
||||
*/
|
||||
TYPE_PX("px", 26),
|
||||
/**
|
||||
* Geographical Position [RFC1712]
|
||||
*/
|
||||
TYPE_GPOS("gpos", 27),
|
||||
/**
|
||||
* IP6 Address [Thomson]
|
||||
*/
|
||||
TYPE_AAAA("aaaa", 28),
|
||||
/**
|
||||
* Location Information [Vixie]
|
||||
*/
|
||||
TYPE_LOC("loc", 29),
|
||||
/**
|
||||
* Next Domain - OBSOLETE [RFC2535, RFC3755]
|
||||
*/
|
||||
TYPE_NXT("nxt", 30),
|
||||
/**
|
||||
* Endpoint Identifier [Patton]
|
||||
*/
|
||||
TYPE_EID("eid", 31),
|
||||
/**
|
||||
* Nimrod Locator [Patton]
|
||||
*/
|
||||
TYPE_NIMLOC("nimloc", 32),
|
||||
/**
|
||||
* Server Selection [RFC2782]
|
||||
*/
|
||||
TYPE_SRV("srv", 33),
|
||||
/**
|
||||
* ATM Address [Dobrowski]
|
||||
*/
|
||||
TYPE_ATMA("atma", 34),
|
||||
/**
|
||||
* Naming Authority Pointer [RFC2168, RFC2915]
|
||||
*/
|
||||
TYPE_NAPTR("naptr", 35),
|
||||
/**
|
||||
* Key Exchanger [RFC2230]
|
||||
*/
|
||||
TYPE_KX("kx", 36),
|
||||
/**
|
||||
* CERT [RFC2538]
|
||||
*/
|
||||
TYPE_CERT("cert", 37),
|
||||
/**
|
||||
* A6 [RFC2874]
|
||||
*/
|
||||
TYPE_A6("a6", 38),
|
||||
/**
|
||||
* DNAME [RFC2672]
|
||||
*/
|
||||
TYPE_DNAME("dname", 39),
|
||||
/**
|
||||
* SINK [Eastlake]
|
||||
*/
|
||||
TYPE_SINK("sink", 40),
|
||||
/**
|
||||
* OPT [RFC2671]
|
||||
*/
|
||||
TYPE_OPT("opt", 41),
|
||||
/**
|
||||
* APL [RFC3123]
|
||||
*/
|
||||
TYPE_APL("apl", 42),
|
||||
/**
|
||||
* Delegation Signer [RFC3658]
|
||||
*/
|
||||
TYPE_DS("ds", 43),
|
||||
/**
|
||||
* SSH Key Fingerprint [RFC-ietf-secsh-dns-05.txt]
|
||||
*/
|
||||
TYPE_SSHFP("sshfp", 44),
|
||||
/**
|
||||
* RRSIG [RFC3755]
|
||||
*/
|
||||
TYPE_RRSIG("rrsig", 46),
|
||||
/**
|
||||
* NSEC [RFC3755]
|
||||
*/
|
||||
TYPE_NSEC("nsec", 47),
|
||||
/**
|
||||
* DNSKEY [RFC3755]
|
||||
*/
|
||||
TYPE_DNSKEY("dnskey", 48),
|
||||
/**
|
||||
* [IANA-Reserved]
|
||||
*/
|
||||
TYPE_UINFO("uinfo", 100),
|
||||
/**
|
||||
* [IANA-Reserved]
|
||||
*/
|
||||
TYPE_UID("uid", 101),
|
||||
/**
|
||||
* [IANA-Reserved]
|
||||
*/
|
||||
TYPE_GID("gid", 102),
|
||||
/**
|
||||
* [IANA-Reserved]
|
||||
*/
|
||||
TYPE_UNSPEC("unspec", 103),
|
||||
/**
|
||||
* Transaction Key [RFC2930]
|
||||
*/
|
||||
TYPE_TKEY("tkey", 249),
|
||||
/**
|
||||
* Transaction Signature [RFC2845]
|
||||
*/
|
||||
TYPE_TSIG("tsig", 250),
|
||||
/**
|
||||
* Incremental transfer [RFC1995]
|
||||
*/
|
||||
TYPE_IXFR("ixfr", 251),
|
||||
/**
|
||||
* Transfer of an entire zone [RFC1035]
|
||||
*/
|
||||
TYPE_AXFR("axfr", 252),
|
||||
/**
|
||||
* Mailbox-related records (MB, MG or MR) [RFC1035]
|
||||
*/
|
||||
TYPE_MAILA("mails", 253),
|
||||
/**
|
||||
* Mail agent RRs (Obsolete - see MX) [RFC1035]
|
||||
*/
|
||||
TYPE_MAILB("mailb", 254),
|
||||
/**
|
||||
* Request for all records [RFC1035]
|
||||
*/
|
||||
TYPE_ANY("any", 255);
|
||||
|
||||
private static Logger logger = Logger.getLogger(DNSRecordType.class.getName());
|
||||
|
||||
private final String _externalName;
|
||||
|
||||
private final int _index;
|
||||
|
||||
DNSRecordType(String name, int index) {
|
||||
_externalName = name;
|
||||
_index = index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the string representation of this type
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public String externalName() {
|
||||
return _externalName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the numeric value of this type
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public int indexValue() {
|
||||
return _index;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param name
|
||||
* @return type for name
|
||||
*/
|
||||
public static DNSRecordType typeForName(String name) {
|
||||
if (name != null) {
|
||||
String aName = name.toLowerCase();
|
||||
for (DNSRecordType aType : DNSRecordType.values()) {
|
||||
if (aType._externalName.equals(aName)) return aType;
|
||||
}
|
||||
}
|
||||
logger.severe("Could not find record type for name: " + name);
|
||||
return TYPE_IGNORE;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param index
|
||||
* @return type for name
|
||||
*/
|
||||
public static DNSRecordType typeForIndex(int index) {
|
||||
for (DNSRecordType aType : DNSRecordType.values()) {
|
||||
if (aType._index == index) return aType;
|
||||
}
|
||||
logger.severe("Could not find record type for index: " + index);
|
||||
return TYPE_IGNORE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.name() + " index " + this.indexValue();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,149 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package javax.jmdns.impl.constants;
|
||||
|
||||
/**
|
||||
* DNS result code.
|
||||
*
|
||||
* @author Arthur van Hoff, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Rick Blair
|
||||
*/
|
||||
public enum DNSResultCode {
|
||||
/**
|
||||
* Token
|
||||
*/
|
||||
Unknown("Unknown", 65535),
|
||||
/**
|
||||
* No Error [RFC1035]
|
||||
*/
|
||||
NoError("No Error", 0),
|
||||
/**
|
||||
* Format Error [RFC1035]
|
||||
*/
|
||||
FormErr("Format Error", 1),
|
||||
/**
|
||||
* Server Failure [RFC1035]
|
||||
*/
|
||||
ServFail("Server Failure", 2),
|
||||
/**
|
||||
* Non-Existent Domain [RFC1035]
|
||||
*/
|
||||
NXDomain("Non-Existent Domain", 3),
|
||||
/**
|
||||
* Not Implemented [RFC1035]
|
||||
*/
|
||||
NotImp("Not Implemented", 4),
|
||||
/**
|
||||
* Query Refused [RFC1035]
|
||||
*/
|
||||
Refused("Query Refused", 5),
|
||||
/**
|
||||
* Name Exists when it should not [RFC2136]
|
||||
*/
|
||||
YXDomain("Name Exists when it should not", 6),
|
||||
/**
|
||||
* RR Set Exists when it should not [RFC2136]
|
||||
*/
|
||||
YXRRSet("RR Set Exists when it should not", 7),
|
||||
/**
|
||||
* RR Set that should exist does not [RFC2136]
|
||||
*/
|
||||
NXRRSet("RR Set that should exist does not", 8),
|
||||
/**
|
||||
* Server Not Authoritative for zone [RFC2136]]
|
||||
*/
|
||||
NotAuth("Server Not Authoritative for zone", 9),
|
||||
/**
|
||||
* Name not contained in zone [RFC2136]
|
||||
*/
|
||||
NotZone("NotZone Name not contained in zone", 10),
|
||||
|
||||
;
|
||||
|
||||
// 0 NoError No Error [RFC1035]
|
||||
// 1 FormErr Format Error [RFC1035]
|
||||
// 2 ServFail Server Failure [RFC1035]
|
||||
// 3 NXDomain Non-Existent Domain [RFC1035]
|
||||
// 4 NotImp Not Implemented [RFC1035]
|
||||
// 5 Refused Query Refused [RFC1035]
|
||||
// 6 YXDomain Name Exists when it should not [RFC2136]
|
||||
// 7 YXRRSet RR Set Exists when it should not [RFC2136]
|
||||
// 8 NXRRSet RR Set that should exist does not [RFC2136]
|
||||
// 9 NotAuth Server Not Authoritative for zone [RFC2136]
|
||||
// 10 NotZone Name not contained in zone [RFC2136]
|
||||
// 11-15 Unassigned
|
||||
// 16 BADVERS Bad OPT Version [RFC2671]
|
||||
// 16 BADSIG TSIG Signature Failure [RFC2845]
|
||||
// 17 BADKEY Key not recognized [RFC2845]
|
||||
// 18 BADTIME Signature out of time window [RFC2845]
|
||||
// 19 BADMODE Bad TKEY Mode [RFC2930]
|
||||
// 20 BADNAME Duplicate key name [RFC2930]
|
||||
// 21 BADALG Algorithm not supported [RFC2930]
|
||||
// 22 BADTRUNC Bad Truncation [RFC4635]
|
||||
// 23-3840 Unassigned
|
||||
// 3841-4095 Reserved for Private Use [RFC5395]
|
||||
// 4096-65534 Unassigned
|
||||
// 65535 Reserved, can be allocated by Standards Action [RFC5395]
|
||||
|
||||
/**
|
||||
* DNS Result Code types are encoded on the last 4 bits
|
||||
*/
|
||||
final static int RCode_MASK = 0x0F;
|
||||
/**
|
||||
* DNS Extended Result Code types are encoded on the first 8 bits
|
||||
*/
|
||||
final static int ExtendedRCode_MASK = 0xFF;
|
||||
|
||||
private final String _externalName;
|
||||
|
||||
private final int _index;
|
||||
|
||||
DNSResultCode(String name, int index) {
|
||||
_externalName = name;
|
||||
_index = index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the string representation of this type
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public String externalName() {
|
||||
return _externalName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the numeric value of this type
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public int indexValue() {
|
||||
return _index;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param flags
|
||||
* @return label
|
||||
*/
|
||||
public static DNSResultCode resultCodeForFlags(int flags) {
|
||||
int maskedIndex = flags & RCode_MASK;
|
||||
for (DNSResultCode aCode : DNSResultCode.values()) {
|
||||
if (aCode._index == maskedIndex) return aCode;
|
||||
}
|
||||
return Unknown;
|
||||
}
|
||||
|
||||
public static DNSResultCode resultCodeForFlags(int flags, int extendedRCode) {
|
||||
int maskedIndex = ((extendedRCode >> 28) & ExtendedRCode_MASK) | (flags & RCode_MASK);
|
||||
for (DNSResultCode aCode : DNSResultCode.values()) {
|
||||
if (aCode._index == maskedIndex) return aCode;
|
||||
}
|
||||
return Unknown;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.name() + " index " + this.indexValue();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,215 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl.constants;
|
||||
|
||||
/**
|
||||
* DNSState defines the possible states for services registered with JmDNS.
|
||||
*
|
||||
* @author Werner Randelshofer, Rick Blair, Pierre Frisch
|
||||
*/
|
||||
public enum DNSState {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
PROBING_1("probing 1", StateClass.probing),
|
||||
/**
|
||||
*
|
||||
*/
|
||||
PROBING_2("probing 2", StateClass.probing),
|
||||
/**
|
||||
*
|
||||
*/
|
||||
PROBING_3("probing 3", StateClass.probing),
|
||||
/**
|
||||
*
|
||||
*/
|
||||
ANNOUNCING_1("announcing 1", StateClass.announcing),
|
||||
/**
|
||||
*
|
||||
*/
|
||||
ANNOUNCING_2("announcing 2", StateClass.announcing),
|
||||
/**
|
||||
*
|
||||
*/
|
||||
ANNOUNCED("announced", StateClass.announced),
|
||||
/**
|
||||
*
|
||||
*/
|
||||
CANCELING_1("canceling 1", StateClass.canceling),
|
||||
/**
|
||||
*
|
||||
*/
|
||||
CANCELING_2("canceling 2", StateClass.canceling),
|
||||
/**
|
||||
*
|
||||
*/
|
||||
CANCELING_3("canceling 3", StateClass.canceling),
|
||||
/**
|
||||
*
|
||||
*/
|
||||
CANCELED("canceled", StateClass.canceled),
|
||||
/**
|
||||
*
|
||||
*/
|
||||
CLOSING("closing", StateClass.closing),
|
||||
/**
|
||||
*
|
||||
*/
|
||||
CLOSED("closed", StateClass.closed);
|
||||
|
||||
private enum StateClass {
|
||||
probing, announcing, announced, canceling, canceled, closing, closed
|
||||
}
|
||||
|
||||
// private static Logger logger = Logger.getLogger(DNSState.class.getName());
|
||||
|
||||
private final String _name;
|
||||
|
||||
private final StateClass _state;
|
||||
|
||||
private DNSState(String name, StateClass state) {
|
||||
_name = name;
|
||||
_state = state;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final String toString() {
|
||||
return _name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the next advanced state.<br/>
|
||||
* In general, this advances one step in the following sequence: PROBING_1, PROBING_2, PROBING_3, ANNOUNCING_1, ANNOUNCING_2, ANNOUNCED.<br/>
|
||||
* or CANCELING_1, CANCELING_2, CANCELING_3, CANCELED Does not advance for ANNOUNCED and CANCELED state.
|
||||
*
|
||||
* @return next state
|
||||
*/
|
||||
public final DNSState advance() {
|
||||
switch (this) {
|
||||
case PROBING_1:
|
||||
return PROBING_2;
|
||||
case PROBING_2:
|
||||
return PROBING_3;
|
||||
case PROBING_3:
|
||||
return ANNOUNCING_1;
|
||||
case ANNOUNCING_1:
|
||||
return ANNOUNCING_2;
|
||||
case ANNOUNCING_2:
|
||||
return ANNOUNCED;
|
||||
case ANNOUNCED:
|
||||
return ANNOUNCED;
|
||||
case CANCELING_1:
|
||||
return CANCELING_2;
|
||||
case CANCELING_2:
|
||||
return CANCELING_3;
|
||||
case CANCELING_3:
|
||||
return CANCELED;
|
||||
case CANCELED:
|
||||
return CANCELED;
|
||||
case CLOSING:
|
||||
return CLOSED;
|
||||
case CLOSED:
|
||||
return CLOSED;
|
||||
default:
|
||||
// This is just to keep the compiler happy as we have covered all cases before.
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns to the next reverted state. All states except CANCELED revert to PROBING_1. Status CANCELED does not revert.
|
||||
*
|
||||
* @return reverted state
|
||||
*/
|
||||
public final DNSState revert() {
|
||||
switch (this) {
|
||||
case PROBING_1:
|
||||
case PROBING_2:
|
||||
case PROBING_3:
|
||||
case ANNOUNCING_1:
|
||||
case ANNOUNCING_2:
|
||||
case ANNOUNCED:
|
||||
return PROBING_1;
|
||||
case CANCELING_1:
|
||||
case CANCELING_2:
|
||||
case CANCELING_3:
|
||||
return CANCELING_1;
|
||||
case CANCELED:
|
||||
return CANCELED;
|
||||
case CLOSING:
|
||||
return CLOSING;
|
||||
case CLOSED:
|
||||
return CLOSED;
|
||||
default:
|
||||
// This is just to keep the compiler happy as we have covered all cases before.
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true, if this is a probing state.
|
||||
*
|
||||
* @return <code>true</code> if probing state, <code>false</code> otherwise
|
||||
*/
|
||||
public final boolean isProbing() {
|
||||
return _state == StateClass.probing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true, if this is an announcing state.
|
||||
*
|
||||
* @return <code>true</code> if announcing state, <code>false</code> otherwise
|
||||
*/
|
||||
public final boolean isAnnouncing() {
|
||||
return _state == StateClass.announcing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true, if this is an announced state.
|
||||
*
|
||||
* @return <code>true</code> if announced state, <code>false</code> otherwise
|
||||
*/
|
||||
public final boolean isAnnounced() {
|
||||
return _state == StateClass.announced;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true, if this is a canceling state.
|
||||
*
|
||||
* @return <code>true</code> if canceling state, <code>false</code> otherwise
|
||||
*/
|
||||
public final boolean isCanceling() {
|
||||
return _state == StateClass.canceling;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true, if this is a canceled state.
|
||||
*
|
||||
* @return <code>true</code> if canceled state, <code>false</code> otherwise
|
||||
*/
|
||||
public final boolean isCanceled() {
|
||||
return _state == StateClass.canceled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true, if this is a closing state.
|
||||
*
|
||||
* @return <code>true</code> if closing state, <code>false</code> otherwise
|
||||
*/
|
||||
public final boolean isClosing() {
|
||||
return _state == StateClass.closing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true, if this is a closing state.
|
||||
*
|
||||
* @return <code>true</code> if closed state, <code>false</code> otherwise
|
||||
*/
|
||||
public final boolean isClosed() {
|
||||
return _state == StateClass.closed;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
package javax.jmdns.impl.constants;
|
||||
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
package javax.jmdns.impl;
|
||||
|
||||
|
|
@ -0,0 +1,223 @@
|
|||
// Licensed under Apache License version 2.0
|
||||
package javax.jmdns.impl.tasks;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
|
||||
import javax.jmdns.impl.DNSIncoming;
|
||||
import javax.jmdns.impl.DNSOutgoing;
|
||||
import javax.jmdns.impl.DNSQuestion;
|
||||
import javax.jmdns.impl.DNSRecord;
|
||||
import javax.jmdns.impl.JmDNSImpl;
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
|
||||
/**
|
||||
* This is the root class for all task scheduled by the timer in JmDNS.
|
||||
*
|
||||
* @author Pierre Frisch
|
||||
*/
|
||||
public abstract class DNSTask extends TimerTask {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private final JmDNSImpl _jmDNSImpl;
|
||||
|
||||
/**
|
||||
* @param jmDNSImpl
|
||||
*/
|
||||
protected DNSTask(JmDNSImpl jmDNSImpl) {
|
||||
super();
|
||||
this._jmDNSImpl = jmDNSImpl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the DNS associated with this task.
|
||||
*
|
||||
* @return associated DNS
|
||||
*/
|
||||
public JmDNSImpl getDns() {
|
||||
return _jmDNSImpl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start this task.
|
||||
*
|
||||
* @param timer
|
||||
* task timer.
|
||||
*/
|
||||
public abstract void start(Timer timer);
|
||||
|
||||
/**
|
||||
* Return this task name.
|
||||
*
|
||||
* @return task name
|
||||
*/
|
||||
public abstract String getName();
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.getName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a question to the message.
|
||||
*
|
||||
* @param out
|
||||
* outgoing message
|
||||
* @param rec
|
||||
* DNS question
|
||||
* @return outgoing message for the next question
|
||||
* @exception IOException
|
||||
*/
|
||||
public DNSOutgoing addQuestion(DNSOutgoing out, DNSQuestion rec) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
try {
|
||||
newOut.addQuestion(rec);
|
||||
} catch (final IOException e) {
|
||||
int flags = newOut.getFlags();
|
||||
boolean multicast = newOut.isMulticast();
|
||||
int maxUDPPayload = newOut.getMaxUDPPayload();
|
||||
int id = newOut.getId();
|
||||
|
||||
newOut.setFlags(flags | DNSConstants.FLAGS_TC);
|
||||
newOut.setId(id);
|
||||
this._jmDNSImpl.send(newOut);
|
||||
|
||||
newOut = new DNSOutgoing(flags, multicast, maxUDPPayload);
|
||||
newOut.addQuestion(rec);
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an answer if it is not suppressed.
|
||||
*
|
||||
* @param out
|
||||
* outgoing message
|
||||
* @param in
|
||||
* incoming request
|
||||
* @param rec
|
||||
* DNS record answer
|
||||
* @return outgoing message for the next answer
|
||||
* @exception IOException
|
||||
*/
|
||||
public DNSOutgoing addAnswer(DNSOutgoing out, DNSIncoming in, DNSRecord rec) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
try {
|
||||
newOut.addAnswer(in, rec);
|
||||
} catch (final IOException e) {
|
||||
int flags = newOut.getFlags();
|
||||
boolean multicast = newOut.isMulticast();
|
||||
int maxUDPPayload = newOut.getMaxUDPPayload();
|
||||
int id = newOut.getId();
|
||||
|
||||
newOut.setFlags(flags | DNSConstants.FLAGS_TC);
|
||||
newOut.setId(id);
|
||||
this._jmDNSImpl.send(newOut);
|
||||
|
||||
newOut = new DNSOutgoing(flags, multicast, maxUDPPayload);
|
||||
newOut.addAnswer(in, rec);
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an answer to the message.
|
||||
*
|
||||
* @param out
|
||||
* outgoing message
|
||||
* @param rec
|
||||
* DNS record answer
|
||||
* @param now
|
||||
* @return outgoing message for the next answer
|
||||
* @exception IOException
|
||||
*/
|
||||
public DNSOutgoing addAnswer(DNSOutgoing out, DNSRecord rec, long now) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
try {
|
||||
newOut.addAnswer(rec, now);
|
||||
} catch (final IOException e) {
|
||||
int flags = newOut.getFlags();
|
||||
boolean multicast = newOut.isMulticast();
|
||||
int maxUDPPayload = newOut.getMaxUDPPayload();
|
||||
int id = newOut.getId();
|
||||
|
||||
newOut.setFlags(flags | DNSConstants.FLAGS_TC);
|
||||
newOut.setId(id);
|
||||
this._jmDNSImpl.send(newOut);
|
||||
|
||||
newOut = new DNSOutgoing(flags, multicast, maxUDPPayload);
|
||||
newOut.addAnswer(rec, now);
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an authoritative answer to the message.
|
||||
*
|
||||
* @param out
|
||||
* outgoing message
|
||||
* @param rec
|
||||
* DNS record answer
|
||||
* @return outgoing message for the next answer
|
||||
* @exception IOException
|
||||
*/
|
||||
public DNSOutgoing addAuthoritativeAnswer(DNSOutgoing out, DNSRecord rec) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
try {
|
||||
newOut.addAuthorativeAnswer(rec);
|
||||
} catch (final IOException e) {
|
||||
int flags = newOut.getFlags();
|
||||
boolean multicast = newOut.isMulticast();
|
||||
int maxUDPPayload = newOut.getMaxUDPPayload();
|
||||
int id = newOut.getId();
|
||||
|
||||
newOut.setFlags(flags | DNSConstants.FLAGS_TC);
|
||||
newOut.setId(id);
|
||||
this._jmDNSImpl.send(newOut);
|
||||
|
||||
newOut = new DNSOutgoing(flags, multicast, maxUDPPayload);
|
||||
newOut.addAuthorativeAnswer(rec);
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an additional answer to the record. Omit if there is no room.
|
||||
*
|
||||
* @param out
|
||||
* outgoing message
|
||||
* @param in
|
||||
* incoming request
|
||||
* @param rec
|
||||
* DNS record answer
|
||||
* @return outgoing message for the next answer
|
||||
* @exception IOException
|
||||
*/
|
||||
public DNSOutgoing addAdditionalAnswer(DNSOutgoing out, DNSIncoming in, DNSRecord rec) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
try {
|
||||
newOut.addAdditionalAnswer(in, rec);
|
||||
} catch (final IOException e) {
|
||||
int flags = newOut.getFlags();
|
||||
boolean multicast = newOut.isMulticast();
|
||||
int maxUDPPayload = newOut.getMaxUDPPayload();
|
||||
int id = newOut.getId();
|
||||
|
||||
newOut.setFlags(flags | DNSConstants.FLAGS_TC);
|
||||
newOut.setId(id);
|
||||
this._jmDNSImpl.send(newOut);
|
||||
|
||||
newOut = new DNSOutgoing(flags, multicast, maxUDPPayload);
|
||||
newOut.addAdditionalAnswer(in, rec);
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl.tasks;
|
||||
|
||||
import java.util.Timer;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.impl.JmDNSImpl;
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
|
||||
/**
|
||||
* Periodically removes expired entries from the cache.
|
||||
*/
|
||||
public class RecordReaper extends DNSTask {
|
||||
static Logger logger = Logger.getLogger(RecordReaper.class.getName());
|
||||
|
||||
/**
|
||||
* @param jmDNSImpl
|
||||
*/
|
||||
public RecordReaper(JmDNSImpl jmDNSImpl) {
|
||||
super(jmDNSImpl);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#getName()
|
||||
*/
|
||||
@Override
|
||||
public String getName() {
|
||||
return "RecordReaper(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer)
|
||||
*/
|
||||
@Override
|
||||
public void start(Timer timer) {
|
||||
if (!this.getDns().isCanceling() && !this.getDns().isCanceled()) {
|
||||
timer.schedule(this, DNSConstants.RECORD_REAPER_INTERVAL, DNSConstants.RECORD_REAPER_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (this.getDns().isCanceling() || this.getDns().isCanceled()) {
|
||||
return;
|
||||
}
|
||||
if (logger.isLoggable(Level.FINEST)) {
|
||||
logger.finest(this.getName() + ".run() JmDNS reaping cache");
|
||||
}
|
||||
|
||||
// Remove expired answers from the cache
|
||||
// -------------------------------------
|
||||
this.getDns().cleanCache();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,157 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl.tasks;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.Timer;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.impl.DNSIncoming;
|
||||
import javax.jmdns.impl.DNSOutgoing;
|
||||
import javax.jmdns.impl.DNSQuestion;
|
||||
import javax.jmdns.impl.DNSRecord;
|
||||
import javax.jmdns.impl.JmDNSImpl;
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
|
||||
/**
|
||||
* The Responder sends a single answer for the specified service infos and for the host name.
|
||||
*/
|
||||
public class Responder extends DNSTask {
|
||||
static Logger logger = Logger.getLogger(Responder.class.getName());
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private final DNSIncoming _in;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private final boolean _unicast;
|
||||
|
||||
public Responder(JmDNSImpl jmDNSImpl, DNSIncoming in, int port) {
|
||||
super(jmDNSImpl);
|
||||
this._in = in;
|
||||
this._unicast = (port != DNSConstants.MDNS_PORT);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#getName()
|
||||
*/
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Responder(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString() + " incomming: " + _in;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer)
|
||||
*/
|
||||
@Override
|
||||
public void start(Timer timer) {
|
||||
// According to draft-cheshire-dnsext-multicastdns.txt chapter "7 Responding":
|
||||
// We respond immediately if we know for sure, that we are the only one who can respond to the query.
|
||||
// In all other cases, we respond within 20-120 ms.
|
||||
//
|
||||
// According to draft-cheshire-dnsext-multicastdns.txt chapter "6.2 Multi-Packet Known Answer Suppression":
|
||||
// We respond after 20-120 ms if the query is truncated.
|
||||
|
||||
boolean iAmTheOnlyOne = true;
|
||||
for (DNSQuestion question : _in.getQuestions()) {
|
||||
if (logger.isLoggable(Level.FINEST)) {
|
||||
logger.finest(this.getName() + "start() question=" + question);
|
||||
}
|
||||
iAmTheOnlyOne = question.iAmTheOnlyOne(this.getDns());
|
||||
if (!iAmTheOnlyOne) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
int delay = (iAmTheOnlyOne && !_in.isTruncated()) ? 0 : DNSConstants.RESPONSE_MIN_WAIT_INTERVAL + JmDNSImpl.getRandom().nextInt(DNSConstants.RESPONSE_MAX_WAIT_INTERVAL - DNSConstants.RESPONSE_MIN_WAIT_INTERVAL + 1) - _in.elapseSinceArrival();
|
||||
if (delay < 0) {
|
||||
delay = 0;
|
||||
}
|
||||
if (logger.isLoggable(Level.FINEST)) {
|
||||
logger.finest(this.getName() + "start() Responder chosen delay=" + delay);
|
||||
}
|
||||
if (!this.getDns().isCanceling() && !this.getDns().isCanceled()) {
|
||||
timer.schedule(this, delay);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
this.getDns().respondToQuery(_in);
|
||||
|
||||
// We use these sets to prevent duplicate records
|
||||
Set<DNSQuestion> questions = new HashSet<DNSQuestion>();
|
||||
Set<DNSRecord> answers = new HashSet<DNSRecord>();
|
||||
|
||||
if (this.getDns().isAnnounced()) {
|
||||
try {
|
||||
// Answer questions
|
||||
for (DNSQuestion question : _in.getQuestions()) {
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
logger.finer(this.getName() + "run() JmDNS responding to: " + question);
|
||||
}
|
||||
// for unicast responses the question must be included
|
||||
if (_unicast) {
|
||||
// out.addQuestion(q);
|
||||
questions.add(question);
|
||||
}
|
||||
|
||||
question.addAnswers(this.getDns(), answers);
|
||||
}
|
||||
|
||||
// remove known answers, if the ttl is at least half of the correct value. (See Draft Cheshire chapter 7.1.).
|
||||
long now = System.currentTimeMillis();
|
||||
for (DNSRecord knownAnswer : _in.getAnswers()) {
|
||||
if (knownAnswer.isStale(now)) {
|
||||
answers.remove(knownAnswer);
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
logger.finer(this.getName() + "JmDNS Responder Known Answer Removed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// respond if we have answers
|
||||
if (!answers.isEmpty()) {
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
logger.finer(this.getName() + "run() JmDNS responding");
|
||||
}
|
||||
DNSOutgoing out = new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA, !_unicast, _in.getSenderUDPPayload());
|
||||
out.setId(_in.getId());
|
||||
for (DNSQuestion question : questions) {
|
||||
if (question != null) {
|
||||
out = this.addQuestion(out, question);
|
||||
}
|
||||
}
|
||||
for (DNSRecord answer : answers) {
|
||||
if (answer != null) {
|
||||
out = this.addAnswer(out, _in, answer);
|
||||
|
||||
}
|
||||
}
|
||||
if (!out.isEmpty()) this.getDns().send(out);
|
||||
}
|
||||
// this.cancel();
|
||||
} catch (Throwable e) {
|
||||
logger.log(Level.WARNING, this.getName() + "run() exception ", e);
|
||||
this.getDns().close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
package javax.jmdns.impl.tasks;
|
||||
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
// Licensed under Apache License version 2.0
|
||||
package javax.jmdns.impl.tasks.resolver;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Timer;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.impl.DNSOutgoing;
|
||||
import javax.jmdns.impl.JmDNSImpl;
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
import javax.jmdns.impl.tasks.DNSTask;
|
||||
|
||||
/**
|
||||
* This is the root class for all resolver tasks.
|
||||
*
|
||||
* @author Pierre Frisch
|
||||
*/
|
||||
public abstract class DNSResolverTask extends DNSTask {
|
||||
private static Logger logger = Logger.getLogger(DNSResolverTask.class.getName());
|
||||
|
||||
/**
|
||||
* Counts the number of queries being sent.
|
||||
*/
|
||||
protected int _count = 0;
|
||||
|
||||
/**
|
||||
* @param jmDNSImpl
|
||||
*/
|
||||
public DNSResolverTask(JmDNSImpl jmDNSImpl) {
|
||||
super(jmDNSImpl);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString() + " count: " + _count;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer)
|
||||
*/
|
||||
@Override
|
||||
public void start(Timer timer) {
|
||||
if (!this.getDns().isCanceling() && !this.getDns().isCanceled()) {
|
||||
timer.schedule(this, DNSConstants.QUERY_WAIT_INTERVAL, DNSConstants.QUERY_WAIT_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.util.TimerTask#run()
|
||||
*/
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
if (this.getDns().isCanceling() || this.getDns().isCanceled()) {
|
||||
this.cancel();
|
||||
} else {
|
||||
if (_count++ < 3) {
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
logger.finer(this.getName() + ".run() JmDNS " + this.description());
|
||||
}
|
||||
DNSOutgoing out = new DNSOutgoing(DNSConstants.FLAGS_QR_QUERY);
|
||||
out = this.addQuestions(out);
|
||||
if (this.getDns().isAnnounced()) {
|
||||
out = this.addAnswers(out);
|
||||
}
|
||||
if (!out.isEmpty()) {
|
||||
this.getDns().send(out);
|
||||
}
|
||||
} else {
|
||||
// After three queries, we can quit.
|
||||
this.cancel();
|
||||
}
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
logger.log(Level.WARNING, this.getName() + ".run() exception ", e);
|
||||
this.getDns().recover();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Overridden by subclasses to add questions to the message.<br/>
|
||||
* <b>Note:</b> Because of message size limitation the returned message may be different than the message parameter.
|
||||
*
|
||||
* @param out
|
||||
* outgoing message
|
||||
* @return the outgoing message.
|
||||
* @exception IOException
|
||||
*/
|
||||
protected abstract DNSOutgoing addQuestions(DNSOutgoing out) throws IOException;
|
||||
|
||||
/**
|
||||
* Overridden by subclasses to add questions to the message.<br/>
|
||||
* <b>Note:</b> Because of message size limitation the returned message may be different than the message parameter.
|
||||
*
|
||||
* @param out
|
||||
* outgoing message
|
||||
* @return the outgoing message.
|
||||
* @exception IOException
|
||||
*/
|
||||
protected abstract DNSOutgoing addAnswers(DNSOutgoing out) throws IOException;
|
||||
|
||||
/**
|
||||
* Returns a description of the resolver for debugging
|
||||
*
|
||||
* @return resolver description
|
||||
*/
|
||||
protected abstract String description();
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,107 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl.tasks.resolver;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.jmdns.impl.DNSEntry;
|
||||
import javax.jmdns.impl.DNSOutgoing;
|
||||
import javax.jmdns.impl.DNSQuestion;
|
||||
import javax.jmdns.impl.DNSRecord;
|
||||
import javax.jmdns.impl.JmDNSImpl;
|
||||
import javax.jmdns.impl.ServiceInfoImpl;
|
||||
import javax.jmdns.impl.constants.DNSRecordClass;
|
||||
import javax.jmdns.impl.constants.DNSRecordType;
|
||||
|
||||
/**
|
||||
* The ServiceInfoResolver queries up to three times consecutively for a service info, and then removes itself from the timer.
|
||||
* <p/>
|
||||
* The ServiceInfoResolver will run only if JmDNS is in state ANNOUNCED. REMIND: Prevent having multiple service resolvers for the same info in the timer queue.
|
||||
*/
|
||||
public class ServiceInfoResolver extends DNSResolverTask {
|
||||
|
||||
private final ServiceInfoImpl _info;
|
||||
|
||||
public ServiceInfoResolver(JmDNSImpl jmDNSImpl, ServiceInfoImpl info) {
|
||||
super(jmDNSImpl);
|
||||
this._info = info;
|
||||
info.setDns(this.getDns());
|
||||
this.getDns().addListener(info, DNSQuestion.newQuestion(info.getQualifiedName(), DNSRecordType.TYPE_ANY, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#getName()
|
||||
*/
|
||||
@Override
|
||||
public String getName() {
|
||||
return "ServiceInfoResolver(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.util.TimerTask#cancel()
|
||||
*/
|
||||
@Override
|
||||
public boolean cancel() {
|
||||
// We should not forget to remove the listener
|
||||
boolean result = super.cancel();
|
||||
if (!_info.isPersistent()) {
|
||||
this.getDns().removeListener(_info);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.Resolver#addAnswers(javax.jmdns.impl.DNSOutgoing)
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing addAnswers(DNSOutgoing out) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
if (!_info.hasData()) {
|
||||
long now = System.currentTimeMillis();
|
||||
newOut = this.addAnswer(newOut, (DNSRecord) this.getDns().getCache().getDNSEntry(_info.getQualifiedName(), DNSRecordType.TYPE_SRV, DNSRecordClass.CLASS_IN), now);
|
||||
newOut = this.addAnswer(newOut, (DNSRecord) this.getDns().getCache().getDNSEntry(_info.getQualifiedName(), DNSRecordType.TYPE_TXT, DNSRecordClass.CLASS_IN), now);
|
||||
if (_info.getServer().length() > 0) {
|
||||
for (DNSEntry addressEntry : this.getDns().getCache().getDNSEntryList(_info.getServer(), DNSRecordType.TYPE_A, DNSRecordClass.CLASS_IN)) {
|
||||
newOut = this.addAnswer(newOut, (DNSRecord) addressEntry, now);
|
||||
}
|
||||
for (DNSEntry addressEntry : this.getDns().getCache().getDNSEntryList(_info.getServer(), DNSRecordType.TYPE_AAAA, DNSRecordClass.CLASS_IN)) {
|
||||
newOut = this.addAnswer(newOut, (DNSRecord) addressEntry, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.Resolver#addQuestions(javax.jmdns.impl.DNSOutgoing)
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing addQuestions(DNSOutgoing out) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
if (!_info.hasData()) {
|
||||
newOut = this.addQuestion(newOut, DNSQuestion.newQuestion(_info.getQualifiedName(), DNSRecordType.TYPE_SRV, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
|
||||
newOut = this.addQuestion(newOut, DNSQuestion.newQuestion(_info.getQualifiedName(), DNSRecordType.TYPE_TXT, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
|
||||
if (_info.getServer().length() > 0) {
|
||||
newOut = this.addQuestion(newOut, DNSQuestion.newQuestion(_info.getServer(), DNSRecordType.TYPE_A, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
|
||||
newOut = this.addQuestion(newOut, DNSQuestion.newQuestion(_info.getServer(), DNSRecordType.TYPE_AAAA, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
|
||||
}
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.Resolver#description()
|
||||
*/
|
||||
@Override
|
||||
protected String description() {
|
||||
return "querying service info: " + (_info != null ? _info.getQualifiedName() : "null");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl.tasks.resolver;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.jmdns.ServiceInfo;
|
||||
import javax.jmdns.impl.DNSOutgoing;
|
||||
import javax.jmdns.impl.DNSQuestion;
|
||||
import javax.jmdns.impl.DNSRecord;
|
||||
import javax.jmdns.impl.JmDNSImpl;
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
import javax.jmdns.impl.constants.DNSRecordClass;
|
||||
import javax.jmdns.impl.constants.DNSRecordType;
|
||||
|
||||
/**
|
||||
* The ServiceResolver queries three times consecutively for services of a given type, and then removes itself from the timer.
|
||||
* <p/>
|
||||
* The ServiceResolver will run only if JmDNS is in state ANNOUNCED. REMIND: Prevent having multiple service resolvers for the same type in the timer queue.
|
||||
*/
|
||||
public class ServiceResolver extends DNSResolverTask {
|
||||
|
||||
private final String _type;
|
||||
|
||||
public ServiceResolver(JmDNSImpl jmDNSImpl, String type) {
|
||||
super(jmDNSImpl);
|
||||
this._type = type;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#getName()
|
||||
*/
|
||||
@Override
|
||||
public String getName() {
|
||||
return "ServiceResolver(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.Resolver#addAnswers(javax.jmdns.impl.DNSOutgoing)
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing addAnswers(DNSOutgoing out) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
long now = System.currentTimeMillis();
|
||||
for (ServiceInfo info : this.getDns().getServices().values()) {
|
||||
newOut = this.addAnswer(newOut, new DNSRecord.Pointer(info.getType(), DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE, DNSConstants.DNS_TTL, info.getQualifiedName()), now);
|
||||
// newOut = this.addAnswer(newOut, new DNSRecord.Service(info.getQualifiedName(), DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE, DNSConstants.DNS_TTL, info.getPriority(), info.getWeight(), info.getPort(),
|
||||
// this.getDns().getLocalHost().getName()), now);
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.Resolver#addQuestions(javax.jmdns.impl.DNSOutgoing)
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing addQuestions(DNSOutgoing out) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
newOut = this.addQuestion(newOut, DNSQuestion.newQuestion(_type, DNSRecordType.TYPE_PTR, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
|
||||
// newOut = this.addQuestion(newOut, DNSQuestion.newQuestion(_type, DNSRecordType.TYPE_SRV, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.Resolver#description()
|
||||
*/
|
||||
@Override
|
||||
protected String description() {
|
||||
return "querying service";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl.tasks.resolver;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.jmdns.impl.DNSOutgoing;
|
||||
import javax.jmdns.impl.DNSQuestion;
|
||||
import javax.jmdns.impl.DNSRecord;
|
||||
import javax.jmdns.impl.JmDNSImpl;
|
||||
import javax.jmdns.impl.JmDNSImpl.ServiceTypeEntry;
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
import javax.jmdns.impl.constants.DNSRecordClass;
|
||||
import javax.jmdns.impl.constants.DNSRecordType;
|
||||
|
||||
/**
|
||||
* Helper class to resolve service types.
|
||||
* <p/>
|
||||
* The TypeResolver queries three times consecutively for service types, and then removes itself from the timer.
|
||||
* <p/>
|
||||
* The TypeResolver will run only if JmDNS is in state ANNOUNCED.
|
||||
*/
|
||||
public class TypeResolver extends DNSResolverTask {
|
||||
|
||||
/**
|
||||
* @param jmDNSImpl
|
||||
*/
|
||||
public TypeResolver(JmDNSImpl jmDNSImpl) {
|
||||
super(jmDNSImpl);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#getName()
|
||||
*/
|
||||
@Override
|
||||
public String getName() {
|
||||
return "TypeResolver(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.Resolver#addAnswers(javax.jmdns.impl.DNSOutgoing)
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing addAnswers(DNSOutgoing out) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
long now = System.currentTimeMillis();
|
||||
for (String type : this.getDns().getServiceTypes().keySet()) {
|
||||
ServiceTypeEntry typeEntry = this.getDns().getServiceTypes().get(type);
|
||||
newOut = this.addAnswer(newOut, new DNSRecord.Pointer("_services._dns-sd._udp.local.", DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE, DNSConstants.DNS_TTL, typeEntry.getType()), now);
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.Resolver#addQuestions(javax.jmdns.impl.DNSOutgoing)
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing addQuestions(DNSOutgoing out) throws IOException {
|
||||
return this.addQuestion(out, DNSQuestion.newQuestion("_services._dns-sd._udp.local.", DNSRecordType.TYPE_PTR, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.Resolver#description()
|
||||
*/
|
||||
@Override
|
||||
protected String description() {
|
||||
return "querying type";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
package javax.jmdns.impl.tasks.resolver;
|
||||
|
||||
|
|
@ -0,0 +1,146 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl.tasks.state;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Timer;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.impl.DNSOutgoing;
|
||||
import javax.jmdns.impl.DNSRecord;
|
||||
import javax.jmdns.impl.JmDNSImpl;
|
||||
import javax.jmdns.impl.ServiceInfoImpl;
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
import javax.jmdns.impl.constants.DNSRecordClass;
|
||||
import javax.jmdns.impl.constants.DNSState;
|
||||
|
||||
/**
|
||||
* The Announcer sends an accumulated query of all announces, and advances the state of all serviceInfos, for which it has sent an announce. The Announcer also sends announcements and advances the state of JmDNS itself.
|
||||
* <p/>
|
||||
* When the announcer has run two times, it finishes.
|
||||
*/
|
||||
public class Announcer extends DNSStateTask {
|
||||
static Logger logger = Logger.getLogger(Announcer.class.getName());
|
||||
|
||||
public Announcer(JmDNSImpl jmDNSImpl) {
|
||||
super(jmDNSImpl, defaultTTL());
|
||||
|
||||
this.setTaskState(DNSState.ANNOUNCING_1);
|
||||
this.associate(DNSState.ANNOUNCING_1);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#getName()
|
||||
*/
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Announcer(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString() + " state: " + this.getTaskState();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer)
|
||||
*/
|
||||
@Override
|
||||
public void start(Timer timer) {
|
||||
if (!this.getDns().isCanceling() && !this.getDns().isCanceled()) {
|
||||
timer.schedule(this, DNSConstants.ANNOUNCE_WAIT_INTERVAL, DNSConstants.ANNOUNCE_WAIT_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean cancel() {
|
||||
this.removeAssociation();
|
||||
|
||||
return super.cancel();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#getTaskDescription()
|
||||
*/
|
||||
@Override
|
||||
public String getTaskDescription() {
|
||||
return "announcing";
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#checkRunCondition()
|
||||
*/
|
||||
@Override
|
||||
protected boolean checkRunCondition() {
|
||||
return !this.getDns().isCanceling() && !this.getDns().isCanceled();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#createOugoing()
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing createOugoing() {
|
||||
return new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForDNS(javax.jmdns.impl.DNSOutgoing)
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing buildOutgoingForDNS(DNSOutgoing out) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
for (DNSRecord answer : this.getDns().getLocalHost().answers(DNSRecordClass.CLASS_ANY, DNSRecordClass.UNIQUE, this.getTTL())) {
|
||||
newOut = this.addAnswer(newOut, null, answer);
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForInfo(javax.jmdns.impl.ServiceInfoImpl, javax.jmdns.impl.DNSOutgoing)
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing buildOutgoingForInfo(ServiceInfoImpl info, DNSOutgoing out) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
for (DNSRecord answer : info.answers(DNSRecordClass.CLASS_ANY, DNSRecordClass.UNIQUE, this.getTTL(), this.getDns().getLocalHost())) {
|
||||
newOut = this.addAnswer(newOut, null, answer);
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#recoverTask(java.lang.Throwable)
|
||||
*/
|
||||
@Override
|
||||
protected void recoverTask(Throwable e) {
|
||||
this.getDns().recover();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#advanceTask()
|
||||
*/
|
||||
@Override
|
||||
protected void advanceTask() {
|
||||
this.setTaskState(this.getTaskState().advance());
|
||||
if (!this.getTaskState().isAnnouncing()) {
|
||||
this.cancel();
|
||||
|
||||
this.getDns().startRenewer();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,143 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl.tasks.state;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Timer;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.impl.DNSOutgoing;
|
||||
import javax.jmdns.impl.DNSRecord;
|
||||
import javax.jmdns.impl.JmDNSImpl;
|
||||
import javax.jmdns.impl.ServiceInfoImpl;
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
import javax.jmdns.impl.constants.DNSRecordClass;
|
||||
import javax.jmdns.impl.constants.DNSState;
|
||||
|
||||
/**
|
||||
* The Canceler sends two announces with TTL=0 for the specified services.
|
||||
*/
|
||||
public class Canceler extends DNSStateTask {
|
||||
static Logger logger = Logger.getLogger(Canceler.class.getName());
|
||||
|
||||
public Canceler(JmDNSImpl jmDNSImpl) {
|
||||
super(jmDNSImpl, 0);
|
||||
|
||||
this.setTaskState(DNSState.CANCELING_1);
|
||||
this.associate(DNSState.CANCELING_1);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#getName()
|
||||
*/
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Canceler(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString() + " state: " + this.getTaskState();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer)
|
||||
*/
|
||||
@Override
|
||||
public void start(Timer timer) {
|
||||
timer.schedule(this, 0, DNSConstants.ANNOUNCE_WAIT_INTERVAL);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.util.TimerTask#cancel()
|
||||
*/
|
||||
@Override
|
||||
public boolean cancel() {
|
||||
this.removeAssociation();
|
||||
|
||||
return super.cancel();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#getTaskDescription()
|
||||
*/
|
||||
@Override
|
||||
public String getTaskDescription() {
|
||||
return "canceling";
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#checkRunCondition()
|
||||
*/
|
||||
@Override
|
||||
protected boolean checkRunCondition() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#createOugoing()
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing createOugoing() {
|
||||
return new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForDNS(javax.jmdns.impl.DNSOutgoing)
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing buildOutgoingForDNS(DNSOutgoing out) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
for (DNSRecord answer : this.getDns().getLocalHost().answers(DNSRecordClass.CLASS_ANY, DNSRecordClass.UNIQUE, this.getTTL())) {
|
||||
newOut = this.addAnswer(newOut, null, answer);
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForInfo(javax.jmdns.impl.ServiceInfoImpl, javax.jmdns.impl.DNSOutgoing)
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing buildOutgoingForInfo(ServiceInfoImpl info, DNSOutgoing out) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
for (DNSRecord answer : info.answers(DNSRecordClass.CLASS_ANY, DNSRecordClass.UNIQUE, this.getTTL(), this.getDns().getLocalHost())) {
|
||||
newOut = this.addAnswer(newOut, null, answer);
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#recoverTask(java.lang.Throwable)
|
||||
*/
|
||||
@Override
|
||||
protected void recoverTask(Throwable e) {
|
||||
this.getDns().recover();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#advanceTask()
|
||||
*/
|
||||
@Override
|
||||
protected void advanceTask() {
|
||||
this.setTaskState(this.getTaskState().advance());
|
||||
if (!this.getTaskState().isCanceling()) {
|
||||
cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,188 @@
|
|||
// Licensed under Apache License version 2.0
|
||||
package javax.jmdns.impl.tasks.state;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.ServiceInfo;
|
||||
import javax.jmdns.impl.DNSOutgoing;
|
||||
import javax.jmdns.impl.DNSStatefulObject;
|
||||
import javax.jmdns.impl.JmDNSImpl;
|
||||
import javax.jmdns.impl.ServiceInfoImpl;
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
import javax.jmdns.impl.constants.DNSState;
|
||||
import javax.jmdns.impl.tasks.DNSTask;
|
||||
|
||||
/**
|
||||
* This is the root class for all state tasks. These tasks work with objects that implements the {@link javax.jmdns.impl.DNSStatefulObject} interface and therefore participate in the state machine.
|
||||
*
|
||||
* @author Pierre Frisch
|
||||
*/
|
||||
public abstract class DNSStateTask extends DNSTask {
|
||||
static Logger logger1 = Logger.getLogger(DNSStateTask.class.getName());
|
||||
|
||||
/**
|
||||
* By setting a 0 ttl we effectively expire the record.
|
||||
*/
|
||||
private final int _ttl;
|
||||
|
||||
private static int _defaultTTL = DNSConstants.DNS_TTL;
|
||||
|
||||
/**
|
||||
* The state of the task.
|
||||
*/
|
||||
private DNSState _taskState = null;
|
||||
|
||||
public abstract String getTaskDescription();
|
||||
|
||||
public static int defaultTTL() {
|
||||
return _defaultTTL;
|
||||
}
|
||||
|
||||
/**
|
||||
* For testing only do not use in production.
|
||||
*
|
||||
* @param value
|
||||
*/
|
||||
public static void setDefaultTTL(int value) {
|
||||
_defaultTTL = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param jmDNSImpl
|
||||
* @param ttl
|
||||
*/
|
||||
public DNSStateTask(JmDNSImpl jmDNSImpl, int ttl) {
|
||||
super(jmDNSImpl);
|
||||
_ttl = ttl;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the ttl
|
||||
*/
|
||||
public int getTTL() {
|
||||
return _ttl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Associate the DNS host and the service infos with this task if not already associated and in the same state.
|
||||
*
|
||||
* @param state
|
||||
* target state
|
||||
*/
|
||||
protected void associate(DNSState state) {
|
||||
synchronized (this.getDns()) {
|
||||
this.getDns().associateWithTask(this, state);
|
||||
}
|
||||
for (ServiceInfo serviceInfo : this.getDns().getServices().values()) {
|
||||
((ServiceInfoImpl) serviceInfo).associateWithTask(this, state);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the DNS host and service info association with this task.
|
||||
*/
|
||||
protected void removeAssociation() {
|
||||
// Remove association from host to this
|
||||
synchronized (this.getDns()) {
|
||||
this.getDns().removeAssociationWithTask(this);
|
||||
}
|
||||
|
||||
// Remove associations from services to this
|
||||
for (ServiceInfo serviceInfo : this.getDns().getServices().values()) {
|
||||
((ServiceInfoImpl) serviceInfo).removeAssociationWithTask(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
DNSOutgoing out = this.createOugoing();
|
||||
try {
|
||||
if (!this.checkRunCondition()) {
|
||||
this.cancel();
|
||||
return;
|
||||
}
|
||||
List<DNSStatefulObject> stateObjects = new ArrayList<DNSStatefulObject>();
|
||||
// send probes for JmDNS itself
|
||||
synchronized (this.getDns()) {
|
||||
if (this.getDns().isAssociatedWithTask(this, this.getTaskState())) {
|
||||
logger1.finer(this.getName() + ".run() JmDNS " + this.getTaskDescription() + " " + this.getDns().getName());
|
||||
stateObjects.add(this.getDns());
|
||||
out = this.buildOutgoingForDNS(out);
|
||||
}
|
||||
}
|
||||
// send probes for services
|
||||
for (ServiceInfo serviceInfo : this.getDns().getServices().values()) {
|
||||
ServiceInfoImpl info = (ServiceInfoImpl) serviceInfo;
|
||||
|
||||
synchronized (info) {
|
||||
if (info.isAssociatedWithTask(this, this.getTaskState())) {
|
||||
logger1.fine(this.getName() + ".run() JmDNS " + this.getTaskDescription() + " " + info.getQualifiedName());
|
||||
stateObjects.add(info);
|
||||
out = this.buildOutgoingForInfo(info, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!out.isEmpty()) {
|
||||
logger1.finer(this.getName() + ".run() JmDNS " + this.getTaskDescription() + " #" + this.getTaskState());
|
||||
this.getDns().send(out);
|
||||
|
||||
// Advance the state of objects.
|
||||
this.advanceObjectsState(stateObjects);
|
||||
} else {
|
||||
// Advance the state of objects.
|
||||
this.advanceObjectsState(stateObjects);
|
||||
|
||||
// If we have nothing to send, another timer taskState ahead of us has done the job for us. We can cancel.
|
||||
cancel();
|
||||
return;
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
logger1.log(Level.WARNING, this.getName() + ".run() exception ", e);
|
||||
this.recoverTask(e);
|
||||
}
|
||||
|
||||
this.advanceTask();
|
||||
}
|
||||
|
||||
protected abstract boolean checkRunCondition();
|
||||
|
||||
protected abstract DNSOutgoing buildOutgoingForDNS(DNSOutgoing out) throws IOException;
|
||||
|
||||
protected abstract DNSOutgoing buildOutgoingForInfo(ServiceInfoImpl info, DNSOutgoing out) throws IOException;
|
||||
|
||||
protected abstract DNSOutgoing createOugoing();
|
||||
|
||||
protected void advanceObjectsState(List<DNSStatefulObject> list) {
|
||||
if (list != null) {
|
||||
for (DNSStatefulObject object : list) {
|
||||
synchronized (object) {
|
||||
object.advanceState(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract void recoverTask(Throwable e);
|
||||
|
||||
protected abstract void advanceTask();
|
||||
|
||||
/**
|
||||
* @return the taskState
|
||||
*/
|
||||
protected DNSState getTaskState() {
|
||||
return this._taskState;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param taskState
|
||||
* the taskState to set
|
||||
*/
|
||||
protected void setTaskState(DNSState taskState) {
|
||||
this._taskState = taskState;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,161 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl.tasks.state;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Timer;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.impl.DNSOutgoing;
|
||||
import javax.jmdns.impl.DNSQuestion;
|
||||
import javax.jmdns.impl.DNSRecord;
|
||||
import javax.jmdns.impl.JmDNSImpl;
|
||||
import javax.jmdns.impl.ServiceInfoImpl;
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
import javax.jmdns.impl.constants.DNSRecordClass;
|
||||
import javax.jmdns.impl.constants.DNSRecordType;
|
||||
import javax.jmdns.impl.constants.DNSState;
|
||||
|
||||
/**
|
||||
* The Prober sends three consecutive probes for all service infos that needs probing as well as for the host name. The state of each service info of the host name is advanced, when a probe has been sent for it. When the prober has run three times,
|
||||
* it launches an Announcer.
|
||||
* <p/>
|
||||
* If a conflict during probes occurs, the affected service infos (and affected host name) are taken away from the prober. This eventually causes the prober to cancel itself.
|
||||
*/
|
||||
public class Prober extends DNSStateTask {
|
||||
static Logger logger = Logger.getLogger(Prober.class.getName());
|
||||
|
||||
public Prober(JmDNSImpl jmDNSImpl) {
|
||||
super(jmDNSImpl, defaultTTL());
|
||||
|
||||
this.setTaskState(DNSState.PROBING_1);
|
||||
this.associate(DNSState.PROBING_1);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#getName()
|
||||
*/
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Prober(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString() + " state: " + this.getTaskState();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer)
|
||||
*/
|
||||
@Override
|
||||
public void start(Timer timer) {
|
||||
long now = System.currentTimeMillis();
|
||||
if (now - this.getDns().getLastThrottleIncrement() < DNSConstants.PROBE_THROTTLE_COUNT_INTERVAL) {
|
||||
this.getDns().setThrottle(this.getDns().getThrottle() + 1);
|
||||
} else {
|
||||
this.getDns().setThrottle(1);
|
||||
}
|
||||
this.getDns().setLastThrottleIncrement(now);
|
||||
|
||||
if (this.getDns().isAnnounced() && this.getDns().getThrottle() < DNSConstants.PROBE_THROTTLE_COUNT) {
|
||||
timer.schedule(this, JmDNSImpl.getRandom().nextInt(1 + DNSConstants.PROBE_WAIT_INTERVAL), DNSConstants.PROBE_WAIT_INTERVAL);
|
||||
} else if (!this.getDns().isCanceling() && !this.getDns().isCanceled()) {
|
||||
timer.schedule(this, DNSConstants.PROBE_CONFLICT_INTERVAL, DNSConstants.PROBE_CONFLICT_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean cancel() {
|
||||
this.removeAssociation();
|
||||
|
||||
return super.cancel();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#getTaskDescription()
|
||||
*/
|
||||
@Override
|
||||
public String getTaskDescription() {
|
||||
return "probing";
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#checkRunCondition()
|
||||
*/
|
||||
@Override
|
||||
protected boolean checkRunCondition() {
|
||||
return !this.getDns().isCanceling() && !this.getDns().isCanceled();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#createOugoing()
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing createOugoing() {
|
||||
return new DNSOutgoing(DNSConstants.FLAGS_QR_QUERY);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForDNS(javax.jmdns.impl.DNSOutgoing)
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing buildOutgoingForDNS(DNSOutgoing out) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
newOut.addQuestion(DNSQuestion.newQuestion(this.getDns().getLocalHost().getName(), DNSRecordType.TYPE_ANY, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
|
||||
for (DNSRecord answer : this.getDns().getLocalHost().answers(DNSRecordClass.CLASS_ANY, DNSRecordClass.NOT_UNIQUE, this.getTTL())) {
|
||||
newOut = this.addAuthoritativeAnswer(newOut, answer);
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForInfo(javax.jmdns.impl.ServiceInfoImpl, javax.jmdns.impl.DNSOutgoing)
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing buildOutgoingForInfo(ServiceInfoImpl info, DNSOutgoing out) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
newOut = this.addQuestion(newOut, DNSQuestion.newQuestion(info.getQualifiedName(), DNSRecordType.TYPE_ANY, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
|
||||
// the "unique" flag should be not set here because these answers haven't been proven unique yet this means the record will not exactly match the announcement record
|
||||
newOut = this.addAuthoritativeAnswer(newOut, new DNSRecord.Service(info.getQualifiedName(), DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE, this.getTTL(), info.getPriority(), info.getWeight(), info.getPort(), this.getDns().getLocalHost()
|
||||
.getName()));
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#recoverTask(java.lang.Throwable)
|
||||
*/
|
||||
@Override
|
||||
protected void recoverTask(Throwable e) {
|
||||
this.getDns().recover();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#advanceTask()
|
||||
*/
|
||||
@Override
|
||||
protected void advanceTask() {
|
||||
this.setTaskState(this.getTaskState().advance());
|
||||
if (!this.getTaskState().isProbing()) {
|
||||
cancel();
|
||||
|
||||
this.getDns().startAnnouncer();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,141 @@
|
|||
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl.tasks.state;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Timer;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.jmdns.impl.DNSOutgoing;
|
||||
import javax.jmdns.impl.DNSRecord;
|
||||
import javax.jmdns.impl.JmDNSImpl;
|
||||
import javax.jmdns.impl.ServiceInfoImpl;
|
||||
import javax.jmdns.impl.constants.DNSConstants;
|
||||
import javax.jmdns.impl.constants.DNSRecordClass;
|
||||
import javax.jmdns.impl.constants.DNSState;
|
||||
|
||||
/**
|
||||
* The Renewer is there to send renewal announcement when the record expire for ours infos.
|
||||
*/
|
||||
public class Renewer extends DNSStateTask {
|
||||
static Logger logger = Logger.getLogger(Renewer.class.getName());
|
||||
|
||||
public Renewer(JmDNSImpl jmDNSImpl) {
|
||||
super(jmDNSImpl, defaultTTL());
|
||||
|
||||
this.setTaskState(DNSState.ANNOUNCED);
|
||||
this.associate(DNSState.ANNOUNCED);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#getName()
|
||||
*/
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Renewer(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString() + " state: " + this.getTaskState();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer)
|
||||
*/
|
||||
@Override
|
||||
public void start(Timer timer) {
|
||||
if (!this.getDns().isCanceling() && !this.getDns().isCanceled()) {
|
||||
timer.schedule(this, DNSConstants.ANNOUNCED_RENEWAL_TTL_INTERVAL, DNSConstants.ANNOUNCED_RENEWAL_TTL_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean cancel() {
|
||||
this.removeAssociation();
|
||||
|
||||
return super.cancel();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#getTaskDescription()
|
||||
*/
|
||||
@Override
|
||||
public String getTaskDescription() {
|
||||
return "renewing";
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#checkRunCondition()
|
||||
*/
|
||||
@Override
|
||||
protected boolean checkRunCondition() {
|
||||
return !this.getDns().isCanceling() && !this.getDns().isCanceled();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#createOugoing()
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing createOugoing() {
|
||||
return new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForDNS(javax.jmdns.impl.DNSOutgoing)
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing buildOutgoingForDNS(DNSOutgoing out) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
for (DNSRecord answer : this.getDns().getLocalHost().answers(DNSRecordClass.CLASS_ANY, DNSRecordClass.UNIQUE, this.getTTL())) {
|
||||
newOut = this.addAnswer(newOut, null, answer);
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForInfo(javax.jmdns.impl.ServiceInfoImpl, javax.jmdns.impl.DNSOutgoing)
|
||||
*/
|
||||
@Override
|
||||
protected DNSOutgoing buildOutgoingForInfo(ServiceInfoImpl info, DNSOutgoing out) throws IOException {
|
||||
DNSOutgoing newOut = out;
|
||||
for (DNSRecord answer : info.answers(DNSRecordClass.CLASS_ANY, DNSRecordClass.UNIQUE, this.getTTL(), this.getDns().getLocalHost())) {
|
||||
newOut = this.addAnswer(newOut, null, answer);
|
||||
}
|
||||
return newOut;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#recoverTask(java.lang.Throwable)
|
||||
*/
|
||||
@Override
|
||||
protected void recoverTask(Throwable e) {
|
||||
this.getDns().recover();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see javax.jmdns.impl.tasks.state.DNSStateTask#advanceTask()
|
||||
*/
|
||||
@Override
|
||||
protected void advanceTask() {
|
||||
this.setTaskState(this.getTaskState().advance());
|
||||
if (!this.getTaskState().isAnnounced()) {
|
||||
cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
package javax.jmdns.impl.tasks.state;
|
||||
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
// Copyright 2003-2012 Arthur van Hoff, Rick Blair
|
||||
// Licensed under Apache License version 2.0
|
||||
// Original license LGPL
|
||||
|
||||
package javax.jmdns.impl.util;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
|
||||
/**
|
||||
* Custom thread factory which sets the name to make it easier to identify where the pooled threads were created.
|
||||
*
|
||||
* @author Trejkaz, Pierre Frisch
|
||||
*/
|
||||
public class NamedThreadFactory implements ThreadFactory {
|
||||
private final ThreadFactory _delegate;
|
||||
private final String _namePrefix;
|
||||
|
||||
/**
|
||||
* Constructs the thread factory.
|
||||
*
|
||||
* @param namePrefix a prefix to append to thread names (will be separated from the default thread name by a space.)
|
||||
*/
|
||||
public NamedThreadFactory(String namePrefix) {
|
||||
this._namePrefix = namePrefix;
|
||||
_delegate = Executors.defaultThreadFactory();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Thread newThread(Runnable runnable) {
|
||||
Thread thread = _delegate.newThread(runnable);
|
||||
thread.setName(_namePrefix + ' ' + thread.getName());
|
||||
return thread;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
package javax.jmdns;
|
||||
|
||||
/**
|
||||
* JmDNS is a Java implementation of multi-cast DNS and can be used for service registration and discovery in local area networks. JmDNS is fully compatible with Apple's Bonjour. The project was originally started in December 2002 by Arthur van Hoff
|
||||
* at Strangeberry. In November 2003 the project was moved to SourceForge, and the name was changed from JRendezvous to JmDNS for legal reasons. Many thanks to Stuart Cheshire for help and moral support.
|
||||
* <p>
|
||||
* <a href="http://jmdns.sourceforge.net/">http://jmdns.sourceforge.net/<a>
|
||||
* </p>
|
||||
**/
|
||||
|
After Width: | Height: | Size: 163 B |
|
After Width: | Height: | Size: 208 B |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 18 KiB |