aboutsummaryrefslogtreecommitdiffstats
path: root/java/org/direct_bt/BTFactory.java
blob: 13192a92391b5e8e194f3626190579e4147ddf98 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
/**
 * Author: Sven Gothel <sgothel@jausoft.com>
 * Copyright (c) 2020 Gothel Software e.K.
 * Copyright (c) 2020 ZAFENA AB
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package org.direct_bt;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

import org.jau.util.VersionUtil;

/**
 * One stop {@link BTManager} API entry point.
 * <p>
 * Further provides access to certain property settings,
 * see {@link #DEBUG}, {@link #VERBOSE}, {@link #DEFAULT_BTMODE} and {@link BTManager.Settings}.
 * </p>
 */
public class BTFactory {

    /**
     * Identifier names, allowing {@link BTFactory#getBTManager(ImplementationIdentifier)}
     * to initialize the required native libraries and to instantiate the root {@link BTManager} instance.
     * <p>
     * The implementation class must provide the static factory method
     * <pre>
     * public static synchronized BluetoothManager getBluetoothManager() throws BluetoothException { .. }
     * </pre>
     * </p>
     */
    public static class ImplementationIdentifier {
        /**
         * Fully qualified class name for the {@link BTManager} implementation
         * <p>
         * The implementation class must provide the static factory method
         * <pre>
         * public static synchronized BluetoothManager getBluetoothManager() throws BluetoothException { .. }
         * </pre>
         * </p>
         */
        public final String BluetoothManagerClassName;
        /** Native library basename for the implementation native library */
        public final String ImplementationNativeLibraryBasename;
        /** Native library basename for the Java binding native library */
        public final String JavaNativeLibraryBasename;

        public ImplementationIdentifier(final String BluetoothManagerClassName,
                                 final String ImplementationNativeLibraryBasename,
                                 final String JavaNativeLibraryBasename) {
            this.BluetoothManagerClassName = BluetoothManagerClassName;
            this.ImplementationNativeLibraryBasename = ImplementationNativeLibraryBasename;
            this.JavaNativeLibraryBasename = JavaNativeLibraryBasename;
        }

        /**
         * <p>
         * Implementation compares {@link #BluetoothManagerClassName} only for equality.
         * </p>
         * {@inheritDoc}
         */
        @Override
        public boolean equals(final Object other) {
            if( null == other || !(other instanceof ImplementationIdentifier) ) {
                return false;
            }
            final ImplementationIdentifier o = (ImplementationIdentifier)other;
            return BluetoothManagerClassName.equals( o.BluetoothManagerClassName );
        }

        @Override
        public String toString() {
            return "ImplementationIdentifier[class "+BluetoothManagerClassName+
                    ", implLib "+ImplementationNativeLibraryBasename+
                    ", javaLib "+JavaNativeLibraryBasename+"]";
        }
    }

    /**
     * {@link ImplementationIdentifier} for direct_bt implementation: {@value}
     * <p>
     * This value is exposed for convenience, user implementations are welcome.
     * </p>
     */
    public static final ImplementationIdentifier DirectBTImplementationID = new ImplementationIdentifier("jau.direct_bt.DBTManager", "direct_bt", "javadirect_bt");

    private static final List<ImplementationIdentifier> implIDs = new ArrayList<ImplementationIdentifier>();

    /**
     * Manifest's {@link Attributes.Name#SPECIFICATION_VERSION} or {@code null} if not available.
     */
    public static final String getAPIVersion() { return APIVersion; }
    private static String APIVersion;

    /**
     * Manifest's {@link Attributes.Name#IMPLEMENTATION_VERSION} or {@code null} if not available.
     */
    public static final String getImplVersion() { return ImplVersion; }
    private static String ImplVersion;

    /**
     * Verbose logging enabled or disabled.
     * <p>
     * System property {@code org.direct_bt.verbose}, boolean, default {@code false}.
     * </p>
     */
    public static final boolean VERBOSE;

    /**
     * Debug logging enabled or disabled.
     * <p>
     * System property {@code org.direct_bt.debug}, boolean, default {@code false}.
     * </p>
     */
    public static final boolean DEBUG;

    /**
     * True if jaulib {@link org.jau.sys.PlatformProps} has been detected.
     */
    public static final boolean JAULIB_AVAILABLE;

    /**
     * True if jaulib {@link #JAULIB_AVAILABLE} and its {@link org.jau.sys.PlatformProps#USE_TEMP_JAR_CACHE} is true,
     * i.e. the jar cache is available, enabled and in use.
     */
    public static final boolean JAULIB_JARCACHE_USED;

    static {
        {
            final String v = System.getProperty("org.direct_bt.debug", "false");
            DEBUG = Boolean.valueOf(v);
        }
        if( DEBUG ) {
            VERBOSE = true;
        } else  {
            final String v = System.getProperty("org.direct_bt.verbose", "false");
            VERBOSE = Boolean.valueOf(v);
        }
        implIDs.add(DirectBTImplementationID);

        boolean isJaulibAvail = false;
        try {
            isJaulibAvail = null != Class.forName("org.jau.sys.PlatformProps", true /* initializeClazz */, BTFactory.class.getClassLoader());
        } catch( final Throwable t ) {
            if( DEBUG ) {
                System.err.println("BTFactory Caught: "+t.getMessage());
                t.printStackTrace();
            }
        }
        JAULIB_AVAILABLE = isJaulibAvail;

        if( isJaulibAvail ) {
            JAULIB_JARCACHE_USED = org.jau.sys.PlatformProps.USE_TEMP_JAR_CACHE;
        } else {
            JAULIB_JARCACHE_USED = false;
        }
        if( VERBOSE ) {
            System.err.println("Jaulib available: "+JAULIB_AVAILABLE+", JarCache in use: "+JAULIB_JARCACHE_USED);
        }
    }

    private static ImplementationIdentifier initializedID = null;

    public static synchronized void checkInitialized() {
        if( null == initializedID ) {
            throw new IllegalStateException("BluetoothFactory not initialized.");
        }
    }
    public static synchronized boolean isInitialized() {
        return null == initializedID;
    }

    private static synchronized void initLibrary(final ImplementationIdentifier id) {
        if( null != initializedID ) {
            if( id != initializedID ) {
                throw new IllegalStateException("BluetoothFactory already initialized with "+initializedID+", can't override by "+id);
            }
            return;
        }

        final ClassLoader cl = BTFactory.class.getClassLoader();
        boolean libsLoaded = false;
        if( JAULIB_AVAILABLE ) {
            if( JAULIB_JARCACHE_USED ) {
                try {
                    org.jau.pkg.JNIJarLibrary.addNativeJarLibs(new Class<?>[] { BTFactory.class }, null);
                } catch (final Exception e0) {
                    System.err.println("BTFactory Caught "+e0.getClass().getSimpleName()+": "+e0.getMessage()+", while JNILibLoaderBase.addNativeJarLibs(..)");
                    if( DEBUG ) {
                        e0.printStackTrace();
                    }
                }
            }
            try {
                if( null != org.jau.sys.dl.NativeLibrary.open(id.ImplementationNativeLibraryBasename,
                                               true /* searchSystemPath */, false /* searchSystemPathFirst */, cl, true /* global */) )
                {
                    org.jau.sys.JNILibrary.loadLibrary(id.JavaNativeLibraryBasename, false, cl);
                    libsLoaded = true;
                }
            } catch (final Throwable t) {
                System.err.println("Caught "+t.getClass().getSimpleName()+": "+t.getMessage()+", while loading libs..");
                if( DEBUG ) {
                    t.printStackTrace();
                }
            }
            if( DEBUG ) {
                System.err.println("Jaulib: Native libs loaded: "+ libsLoaded);
            }
        }
        if( !libsLoaded ) {
            try {
                final Throwable[] t = { null };
                if( !PlatformToolkit.loadLibrary(id.ImplementationNativeLibraryBasename, cl, t) ) {
                    throw new RuntimeException("Couldn't load native library with basename <"+id.ImplementationNativeLibraryBasename+">", t[0]);
                }
                if( !PlatformToolkit.loadLibrary(id.JavaNativeLibraryBasename, cl, t) ) {
                    throw new RuntimeException("Couldn't load native library with basename <"+id.JavaNativeLibraryBasename+">", t[0]);
                }
            } catch (final Throwable e) {
                System.err.println("Caught "+e.getClass().getSimpleName()+": "+e.getMessage()+", while loading libs (2) ..");
                if( DEBUG ) {
                    e.printStackTrace();
                }
                throw e; // fwd exception - end here
            }
        }

        // Map all Java properties '[org.]direct_bt.*' and 'direct_bt.*' to native environment.
        try {
            if( DEBUG ) {
                System.err.println("BlootoothFactory: Mapping '[org.|jau.]direct_bt.*' properties to native environment");
            }
            final Properties props = AccessController.doPrivileged(new PrivilegedAction<Properties>() {
                  @Override
                  public Properties run() {
                      return System.getProperties();
                  } });

            final Enumeration<?> enums = props.propertyNames();
            while (enums.hasMoreElements()) {
              final String key = (String) enums.nextElement();
              if( key.startsWith("org.direct_bt.") || key.startsWith("jau.direct_bt.") ||
                  key.startsWith("direct_bt.") )
              {
                  final String value = props.getProperty(key);
                  if( DEBUG ) {
                      System.err.println("  <"+key+"> := <"+value+">");
                  }
                  setenv(key, value, true /* overwrite */);
              }
            }
        } catch (final Throwable e) {
            System.err.println("Caught exception while forwarding system properties: "+e.getMessage());
            e.printStackTrace();
        }

        try {
            final Manifest manifest = getManifest(cl, new String[] { "org.direct_bt" } );
            final Attributes mfAttributes = null != manifest ? manifest.getMainAttributes() : null;

            // major.minor must match!
            final String NAPIVersion = getNativeAPIVersion();
            final String JAPIVersion = null != mfAttributes ? mfAttributes.getValue(Attributes.Name.SPECIFICATION_VERSION) : null;
            if ( null != JAPIVersion && JAPIVersion.equals(NAPIVersion) == false) {
                final String[] NAPIVersionCode = NAPIVersion.split("\\D");
                final String[] JAPIVersionCode = JAPIVersion.split("\\D");
                if (JAPIVersionCode[0].equals(NAPIVersionCode[0]) == false) {
                    if (Integer.valueOf(JAPIVersionCode[0]) < Integer.valueOf(NAPIVersionCode[0])) {
                        throw new RuntimeException("Java library "+JAPIVersion+" < native library "+NAPIVersion+". Please update the Java library.");
                    } else {
                        throw new RuntimeException("Native library "+NAPIVersion+" < java library "+JAPIVersion+". Please update the native library.");
                    }
                } else if (JAPIVersionCode[1].equals(NAPIVersionCode[1]) == false) {
                    if (Integer.valueOf(JAPIVersionCode[1]) < Integer.valueOf(NAPIVersionCode[1])) {
                        throw new RuntimeException("Java library "+JAPIVersion+" < native library "+NAPIVersion+". Please update the Java library.");
                    } else {
                        throw new RuntimeException("Native library "+NAPIVersion+" < java library "+JAPIVersion+". Please update the native library.");
                    }
                }
            }
            initializedID = id; // initialized!

            APIVersion = JAPIVersion;
            ImplVersion = null != mfAttributes ? mfAttributes.getValue(Attributes.Name.IMPLEMENTATION_VERSION) : null;
            if( VERBOSE ) {
                System.err.println("direct_bt loaded "+id);
                System.err.println("direct_bt java api version "+JAPIVersion);
                System.err.println("direct_bt native api version "+NAPIVersion);
                if( null != mfAttributes ) {
                    final Attributes.Name[] versionAttributeNames = new Attributes.Name[] {
                            Attributes.Name.SPECIFICATION_TITLE,
                            Attributes.Name.SPECIFICATION_VENDOR,
                            Attributes.Name.SPECIFICATION_VERSION,
                            Attributes.Name.IMPLEMENTATION_TITLE,
                            Attributes.Name.IMPLEMENTATION_VENDOR,
                            Attributes.Name.IMPLEMENTATION_VERSION,
                            new Attributes.Name("Implementation-Commit") };
                    for( final Attributes.Name an : versionAttributeNames ) {
                        System.err.println("  "+an+": "+mfAttributes.getValue(an));
                    }
                } else {
                    System.err.println("  No Manifest available;");
                }
            }
        } catch (final Throwable e) {
            System.err.println("Error querying manifest information.");
            e.printStackTrace();
            throw e; // fwd exception - end here
        }
    }

    private static synchronized BTManager getBTManager(final Class<?> factoryImplClass)
            throws BTException, NoSuchMethodException, SecurityException,
                   IllegalAccessException, IllegalArgumentException, InvocationTargetException
    {
        final Method m = factoryImplClass.getMethod("getManager");
        return (BTManager)m.invoke(null);
    }

    /**
     * Registers a new {@link ImplementationIdentifier} to the internal list.
     * The {@code id} is only added if not registered yet.
     * @param id the {@link ImplementationIdentifier} to register
     * @return {@code true} if the given {@link ImplementationIdentifier} has been newly added,
     * otherwise {@code false}.
     */
    public static synchronized boolean registerImplementationIdentifier(final ImplementationIdentifier id) {
        if( null == id ) {
            return false;
        }
        if( implIDs.contains(id) ) {
            return false;
        }
        return implIDs.add(id);
    }

    /**
     * Returns the matching {@link ImplementationIdentifier} from the internal list or {@code null} if not found.
     * @param fqBluetoothManagerImplementationClassName fully qualified class name for the {@link BTManager} implementation
     */
    public static synchronized ImplementationIdentifier getImplementationIdentifier(final String fqBluetoothManagerImplementationClassName) {
        for(final ImplementationIdentifier id : implIDs) {
            if( id.BluetoothManagerClassName.equals(fqBluetoothManagerImplementationClassName) ) {
                return id;
            }
        }
        return null;
    }

    /**
     * Returns an initialized BluetoothManager instance using the given {@code fqBluetoothManagerImplementationClassName}
     * to lookup a registered {@link ImplementationIdentifier}.
     * <p>
     * If found, method returns {@link #getBTManager(ImplementationIdentifier)}, otherwise {@code null}.
     * </p>
     * <p>
     * The chosen implementation can't be changed within a running implementation, an exception is thrown if tried.
     * </p>
     *
     * @param fqBluetoothManagerImplementationClassName fully qualified class name for the {@link BTManager} implementation
     * @throws BTException
     * @throws NoSuchMethodException
     * @throws SecurityException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     * @throws ClassNotFoundException
     * @see {@link #DBusFactoryImplClassName}
     * @see {@link #DirectBTFactoryImplClassName}
     */
    public static synchronized BTManager getBTManager(final String fqBluetoothManagerImplementationClassName)
            throws BTException, NoSuchMethodException, SecurityException,
                   IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException
    {
        final ImplementationIdentifier id = getImplementationIdentifier(fqBluetoothManagerImplementationClassName);
        if( null != id ) {
            return getBTManager(id);
        }
        return null;
    }

    /**
     * Returns an initialized BluetoothManager instance using the given {@link ImplementationIdentifier}.
     * <p>
     * If the {@link ImplementationIdentifier} has not been {@link #registerImplementationIdentifier(ImplementationIdentifier)},
     * it will be added to the list.
     * </p>
     * <p>
     * The chosen implementation can't be changed within a running implementation, an exception is thrown if tried.
     * </p>
     * @param id the specific {@link ImplementationIdentifier}
     * @throws BTException
     * @throws NoSuchMethodException
     * @throws SecurityException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     * @throws ClassNotFoundException
     * @see {@link #DBusFactoryImplClassName}
     * @see {@link #DirectBTFactoryImplClassName}
     */
    public static synchronized BTManager getBTManager(final ImplementationIdentifier id)
            throws BTException, NoSuchMethodException, SecurityException,
                   IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException
    {
        registerImplementationIdentifier(id);
        initLibrary(id);
        final Class<?> factoryImpl = Class.forName(id.BluetoothManagerClassName);
        return getBTManager(factoryImpl);
    }

    /**
     * Returns an initialized BluetoothManager instance using the DirectBT implementation.
     * <p>
     * Issues {@link #getBTManager(ImplementationIdentifier)} using {@link #DirectBTImplementationID}.
     * </p>
     * <p>
     * The chosen implementation can't be changed within a running implementation, an exception is thrown if tried.
     * </p>
     * @throws BTException
     * @throws NoSuchMethodException
     * @throws SecurityException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     * @throws ClassNotFoundException
     */
    public static synchronized BTManager getDirectBTManager()
            throws BTException, NoSuchMethodException, SecurityException,
                   IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException
    {
        return getBTManager(DirectBTImplementationID);
    }

    /**
     * Preloads the DirectBT native library w/o instantiating BTManager.
     */
    public static synchronized void initDirectBTLibrary() {
        initLibrary(DirectBTImplementationID);
    }

    /**
     * Helper function to retrieve a Manifest instance.
     */
    public static final Manifest getManifest(final ClassLoader cl, final String[] extensions) {
        final Manifest[] extManifests = new Manifest[extensions.length];
        try {
            final Enumeration<URL> resources = cl.getResources("META-INF/MANIFEST.MF");
            while (resources.hasMoreElements()) {
                final URL resURL = resources.nextElement();
                if( DEBUG ) {
                    System.err.println("resource: "+resURL);
                }
                final InputStream is = resURL.openStream();
                final Manifest manifest;
                try {
                    manifest = new Manifest(is);
                } finally {
                    try {
                        is.close();
                    } catch (final IOException e) {}
                }
                final Attributes attributes = manifest.getMainAttributes();
                if(attributes != null) {
                    final String attributesExtName = attributes.getValue( Attributes.Name.EXTENSION_NAME );
                    for(int i=0; i < extensions.length && null == extManifests[i]; i++) {
                        final String extension = extensions[i];
                        if( extension.equals( attributesExtName ) ) {
                            if( 0 == i ) {
                                return manifest; // 1st one has highest prio - done
                            }
                            extManifests[i] = manifest;
                        }
                    }
                }
            }
        } catch (final IOException ex) {
            throw new RuntimeException("Unable to read manifest.", ex);
        }
        for(int i=1; i<extManifests.length; i++) {
            if( null != extManifests[i] ) {
                return extManifests[i];
            }
        }
        return null;
    }

    public static void main(final String args[]) {
        System.err.println("Jaulib: Available "+JAULIB_AVAILABLE+", JarCache in use "+JAULIB_JARCACHE_USED);
        if( JAULIB_AVAILABLE ) {
            System.err.println(VersionUtil.getPlatformInfo());
            System.err.println("Version Info:");
            final DirectBTVersion v = DirectBTVersion.getInstance();
            System.err.println(v);
            System.err.println("");
            System.err.println("Full Manifest:");
            System.err.println(v.getFullManifestInfo(null));
        } else {
            System.err.println("Full Manifest:");
            final Manifest manifest = getManifest(BTFactory.class.getClassLoader(), new String[] { "org.direct_bt" } );
            final Attributes attr = manifest.getMainAttributes();
            final Set<Object> keys = attr.keySet();
            final StringBuilder sb = new StringBuilder();
            for(final Iterator<Object> iter=keys.iterator(); iter.hasNext(); ) {
                final Attributes.Name key = (Attributes.Name) iter.next();
                final String val = attr.getValue(key);
                sb.append(" ");
                sb.append(key);
                sb.append(" = ");
                sb.append(val);
                sb.append(System.lineSeparator());
            }
            System.err.println(sb);
        }
        try {
            final BTManager mngr = getDirectBTManager();
            final List<BTAdapter> adapters = mngr.getAdapters();
            System.err.println("BTManager: adapters "+adapters.size());
            int i=0;
            for(final Iterator<BTAdapter> iter = adapters.iterator(); iter.hasNext(); ++i) {
                System.err.println("BTAdapter["+i+"]: "+iter.next().toString()); // has full toString()
            }
        } catch (BTException | NoSuchMethodException | SecurityException
                | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public native static String getNativeVersion();
    public native static String getNativeAPIVersion();
    private native static void setenv(String name, String value, boolean overwrite);
}

/** \example DBTScanner10.java
 * This Java scanner {@link BTRole::Master} GATT client example uses an event driven workflow
 * and multithreading, i.e. one thread processes each found device when notified.
 * <p>
 * This example represents the recommended utilization of Direct-BT.
 * </p>
 * <p>
 * See `dbt_scanner10.cpp` for invocation examples, since both apps are fully compatible.
 * </p>
 */

/** \example DBTPeripheral00.java
 * This Java peripheral {@link BTRole::Slave} GATT server example uses an event driven workflow.
 * <p>
 * See `dbt_peripheral00.cpp` for invocation examples, since both apps are fully compatible.
 * </p>
 */

/** \example TestDBTClientServer00.java
 * Unit test, trial using actual BT adapter.
 *
 * Basic client and server Bluetooth tests, requiring one BT adapter.
 */

/** \example TestDBTClientServer10.java
 * Unit test, trial using actual BT adapter.
 *
 * Testing a full Bluetooth server and client lifecycle of operations, requiring two BT adapter:
 * - start server advertising
 * - start client discovery and connect to server when discovered
 * - client/server processing of connection when ready
 * - client disconnect
 * - server stop advertising
 * - security-level: NONE, ENC_ONLY freshly-paired and ENC_ONLY pre-paired
 */