### Register USB Drive Listeners in Java Source: https://context7.com/samuelcampos/usbdrivedetector/llms.txt Registers a listener to receive USB device events. Polling starts automatically upon adding the first listener. ```java import net.samuelcampos.usbdrivedetector.USBDeviceDetectorManager; import net.samuelcampos.usbdrivedetector.events.IUSBDriveListener; import net.samuelcampos.usbdrivedetector.events.USBStorageEvent; import net.samuelcampos.usbdrivedetector.events.DeviceEventType; import java.io.IOException; public class DeviceListenerExample { public static void main(String[] args) { USBDeviceDetectorManager manager = new USBDeviceDetectorManager(); // Using lambda expression (IUSBDriveListener is a functional interface) manager.addDriveListener(event -> { if (event.getEventType() == DeviceEventType.CONNECTED) { System.out.println("USB Device Connected!"); System.out.println(" Name: " + event.getStorageDevice().getDeviceName()); System.out.println(" Path: " + event.getStorageDevice().getRootDirectory()); } else if (event.getEventType() == DeviceEventType.REMOVED) { System.out.println("USB Device Removed!"); System.out.println(" Name: " + event.getStorageDevice().getDeviceName()); } }); // Or using a class that implements IUSBDriveListener IUSBDriveListener customListener = new IUSBDriveListener() { @Override public void usbDriveEvent(USBStorageEvent event) { System.out.println("Event received: " + event); } }; manager.addDriveListener(customListener); System.out.println("Listening for USB events... (Press Ctrl+C to exit)"); // Keep application running to receive events try { Thread.sleep(60000); // Listen for 60 seconds } catch (InterruptedException e) { Thread.currentThread().interrupt(); } // Clean up try { manager.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` -------------------------------- ### Add Drive Listener Source: https://context7.com/samuelcampos/usbdrivedetector/llms.txt Registers a listener to receive notifications when USB devices are connected or removed. Polling automatically starts when the first listener is added and uses a background ScheduledExecutorService. ```APIDOC ## addDriveListener(IUSBDriveListener listener) ### Description Registers a listener to receive notifications when USB devices are connected or removed. Polling automatically starts when the first listener is added and uses a background ScheduledExecutorService. ### Method POST ### Endpoint /api/usbdrivedetector/listener ### Parameters #### Query Parameters - **listener** (IUSBDriveListener) - Required - The listener interface to register for USB events. ### Request Example ```java USBDeviceDetectorManager manager = new USBDeviceDetectorManager(); manager.addDriveListener(event -> { if (event.getEventType() == DeviceEventType.CONNECTED) { System.out.println("USB Device Connected!"); System.out.println(" Name: " + event.getStorageDevice().getDeviceName()); System.out.println(" Path: " + event.getStorageDevice().getRootDirectory()); } else if (event.getEventType() == DeviceEventType.REMOVED) { System.out.println("USB Device Removed!"); System.out.println(" Name: " + event.getStorageDevice().getDeviceName()); } }); ``` ### Response #### Success Response (200) - **status** (boolean) - Indicates if the listener was successfully added. #### Response Example ```json { "status": true } ``` ``` -------------------------------- ### Manage USB Devices Source: https://github.com/samuelcampos/usbdrivedetector/blob/master/README.md Initialize the manager to list devices, register event listeners, or unmount specific storage devices. ```java USBDeviceDetectorManager driveDetector = new USBDeviceDetectorManager(); // Display all the USB storage devices currently connected driveDetector.getRemovableDevices().forEach(System.out::println); // Add an event listener to be notified when an USB storage device is connected or removed driveDetector.addDriveListener(System.out::println); // Unmount a device driveDetector.unmountStorageDevice(driveDetector.getRemovableDevices().get(0)); ``` -------------------------------- ### List Connected USB Devices with Details Source: https://context7.com/samuelcampos/usbdrivedetector/llms.txt Retrieves a snapshot of all connected USB devices and prints their system display name, root directory path, device name, device ID, and access permissions. Remember to close the manager to free up resources. ```java import net.samuelcampos.usbdrivedetector.USBDeviceDetectorManager; import net.samuelcampos.usbdrivedetector.USBStorageDevice; public class ListDevicesExample { public static void main(String[] args) { USBDeviceDetectorManager manager = new USBDeviceDetectorManager(); // Get snapshot of all connected USB devices manager.getRemovableDevices().forEach(device -> { System.out.println("Device: " + device.getSystemDisplayName()); System.out.println(" Path: " + device.getRootDirectory().getAbsolutePath()); System.out.println(" Name: " + device.getDeviceName()); System.out.println(" Device ID: " + device.getDevice()); // Check permissions if (device.canRead() && device.canWrite()) { System.out.println(" Status: Read/Write access"); } else if (device.canRead()) { System.out.println(" Status: Read-only access"); } else { System.out.println(" Status: No access"); } }); try { manager.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Initialize and List USB Devices Source: https://context7.com/samuelcampos/usbdrivedetector/llms.txt Initializes the USBDeviceDetectorManager and retrieves a list of currently connected USB storage devices. Ensure to close the manager when done to release resources. ```java import net.samuelcampos.usbdrivedetector.USBDeviceDetectorManager; import net.samuelcampos.usbdrivedetector.USBStorageDevice; import java.io.IOException; import java.util.List; public class USBManagerExample { public static void main(String[] args) { // Create manager with default 5-second polling interval USBDeviceDetectorManager driveDetector = new USBDeviceDetectorManager(); // Or create with custom polling interval (in milliseconds) // USBDeviceDetectorManager driveDetector = new USBDeviceDetectorManager(2000); // Get all currently connected USB storage devices List devices = driveDetector.getRemovableDevices(); System.out.println("Found " + devices.size() + " USB device(s):"); for (USBStorageDevice device : devices) { System.out.println(" - " + device.getDeviceName()); System.out.println(" Root: " + device.getRootDirectory()); System.out.println(" UUID: " + device.getUuid()); System.out.println(" Readable: " + device.canRead()); System.out.println(" Writable: " + device.canWrite()); } // Always close when done to release resources try { driveDetector.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` -------------------------------- ### Implement USB Device Monitoring in Java Source: https://context7.com/samuelcampos/usbdrivedetector/llms.txt A full application implementation using IUSBDriveListener to monitor, list, and unmount USB storage devices. Requires the USBDeviceDetectorManager to be initialized with a polling interval. ```java import net.samuelcampos.usbdrivedetector.USBDeviceDetectorManager; import net.samuelcampos.usbdrivedetector.USBStorageDevice; import net.samuelcampos.usbdrivedetector.events.DeviceEventType; import net.samuelcampos.usbdrivedetector.events.IUSBDriveListener; import net.samuelcampos.usbdrivedetector.events.USBStorageEvent; import java.io.IOException; import java.util.List; import java.util.Scanner; public class USBMonitorApplication implements IUSBDriveListener { private final USBDeviceDetectorManager manager; public USBMonitorApplication() { // Create manager with 2-second polling for responsive detection this.manager = new USBDeviceDetectorManager(2000); } public void start() { System.out.println("USB Monitor Application Started"); System.out.println("================================"); // Display initially connected devices listConnectedDevices(); // Register for events manager.addDriveListener(this); System.out.println("\nMonitoring for USB device changes..."); System.out.println("Commands: 'list' - show devices, 'unmount' - unmount first device, 'quit' - exit\n"); // Simple command loop Scanner scanner = new Scanner(System.in); while (true) { String command = scanner.nextLine().trim().toLowerCase(); switch (command) { case "list": listConnectedDevices(); break; case "unmount": unmountFirstDevice(); break; case "quit": case "exit": shutdown(); return; default: System.out.println("Unknown command: " + command); } } } private void listConnectedDevices() { List devices = manager.getRemovableDevices(); if (devices.isEmpty()) { System.out.println("No USB storage devices connected."); } else { System.out.println("Connected USB devices (" + devices.size() + "):"); for (int i = 0; i < devices.size(); i++) { USBStorageDevice device = devices.get(i); System.out.printf(" [%d] %s (%s)%n", i + 1, device.getDeviceName(), device.getRootDirectory().getAbsolutePath()); } } } private void unmountFirstDevice() { List devices = manager.getRemovableDevices(); if (devices.isEmpty()) { System.out.println("No devices to unmount."); return; } USBStorageDevice device = devices.get(0); System.out.println("Unmounting: " + device.getDeviceName()); try { manager.unmountStorageDevice(device); System.out.println("Successfully unmounted!"); } catch (IOException e) { System.err.println("Failed to unmount: " + e.getMessage()); } } @Override public void usbDriveEvent(USBStorageEvent event) { USBStorageDevice device = event.getStorageDevice(); if (event.getEventType() == DeviceEventType.CONNECTED) { System.out.println("\n[EVENT] Device CONNECTED: " + device.getDeviceName()); System.out.println(" Path: " + device.getRootDirectory().getAbsolutePath()); System.out.println(" UUID: " + device.getUuid()); } else { System.out.println("\n[EVENT] Device REMOVED: " + device.getDeviceName()); } } private void shutdown() { System.out.println("Shutting down..."); try { manager.close(); } catch (IOException e) { System.err.println("Error during shutdown: " + e.getMessage()); } System.out.println("Goodbye!"); } public static void main(String[] args) { new USBMonitorApplication().start(); } } ``` -------------------------------- ### Add Maven Dependency Source: https://github.com/samuelcampos/usbdrivedetector/blob/master/README.md Include the library in a Java project by adding this dependency to the pom.xml file. ```xml net.samuelcampos usbdrivedetector 2.2.1 ``` -------------------------------- ### Access USBStorageDevice Properties in Java Source: https://context7.com/samuelcampos/usbdrivedetector/llms.txt Retrieves metadata and file system permissions for connected USB storage devices. ```java import net.samuelcampos.usbdrivedetector.USBDeviceDetectorManager; import net.samuelcampos.usbdrivedetector.USBStorageDevice; import java.io.File; public class USBStorageDeviceExample { public static void main(String[] args) throws Exception { USBDeviceDetectorManager manager = new USBDeviceDetectorManager(); for (USBStorageDevice device : manager.getRemovableDevices()) { // Get device properties File root = device.getRootDirectory(); String name = device.getDeviceName(); String deviceId = device.getDevice(); String uuid = device.getUuid(); String displayName = device.getSystemDisplayName(); System.out.println("=== USB Device ==="); System.out.println("Display Name: " + displayName); System.out.println("Device Name: " + name); System.out.println("Root Directory: " + root.getAbsolutePath()); System.out.println("Device ID: " + deviceId); System.out.println("UUID: " + uuid); // Check permissions System.out.println("Can Read: " + device.canRead()); System.out.println("Can Write: " + device.canWrite()); System.out.println("Can Execute: " + device.canExecute()); // Access files on the device if (device.canRead()) { File[] files = root.listFiles(); if (files != null) { System.out.println("Files on device: " + files.length); for (File file : files) { System.out.println(" - " + file.getName() + (file.isDirectory() ? "/" : "")); } } } System.out.println(); } manager.close(); } } ``` -------------------------------- ### Add Maven Dependency for USB Drive Detector Source: https://context7.com/samuelcampos/usbdrivedetector/llms.txt Include this dependency in your project's pom.xml to use the USB Drive Detector library. ```xml net.samuelcampos usbdrivedetector 2.2.1 ``` -------------------------------- ### Configure Polling Interval in Java Source: https://context7.com/samuelcampos/usbdrivedetector/llms.txt Adjusts the frequency at which the library checks for USB device changes. Registered listeners will automatically restart with the updated interval. ```java import net.samuelcampos.usbdrivedetector.USBDeviceDetectorManager; import java.io.IOException; public class PollingIntervalExample { public static void main(String[] args) throws IOException { // Start with default 5-second interval USBDeviceDetectorManager manager = new USBDeviceDetectorManager(); // Add a listener to start polling manager.addDriveListener(event -> { System.out.println(System.currentTimeMillis() + ": " + event); }); System.out.println("Polling every 5 seconds (default)..."); sleep(10000); // Change to faster polling (1 second) manager.setPollingInterval(1000); System.out.println("Polling every 1 second..."); sleep(5000); // Change to slower polling (10 seconds) manager.setPollingInterval(10000); System.out.println("Polling every 10 seconds..."); sleep(15000); manager.close(); } private static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } ``` -------------------------------- ### USBStorageDevice Object Source: https://context7.com/samuelcampos/usbdrivedetector/llms.txt Represents a connected USB storage device with properties including root directory, device name, UUID, and permission checking methods. ```APIDOC ## USBStorageDevice ### Description Represents a connected USB storage device with properties including root directory, device name, UUID, and permission checking methods. ### Method N/A (This is a data object) ### Endpoint N/A ### Parameters None ### Request Example ```java import net.samuelcampos.usbdrivedetector.USBDeviceDetectorManager; import net.samuelcampos.usbdrivedetector.USBStorageDevice; import java.io.File; public class USBStorageDeviceExample { public static void main(String[] args) throws Exception { USBDeviceDetectorManager manager = new USBDeviceDetectorManager(); for (USBStorageDevice device : manager.getRemovableDevices()) { // Get device properties File root = device.getRootDirectory(); String name = device.getDeviceName(); String deviceId = device.getDevice(); String uuid = device.getUuid(); String displayName = device.getSystemDisplayName(); System.out.println("=== USB Device ==="); System.out.println("Display Name: " + displayName); System.out.println("Device Name: " + name); System.out.println("Root Directory: " + root.getAbsolutePath()); System.out.println("Device ID: " + deviceId); System.out.println("UUID: " + uuid); // Check permissions System.out.println("Can Read: " + device.canRead()); System.out.println("Can Write: " + device.canWrite()); System.out.println("Can Execute: " + device.canExecute()); // Access files on the device if (device.canRead()) { File[] files = root.listFiles(); if (files != null) { System.out.println("Files on device: " + files.length); for (File file : files) { System.out.println(" - " + file.getName() + (file.isDirectory() ? "/" : "")); } } } System.out.println(); } manager.close(); } } ``` ### Response #### Success Response (200) Represents a USB storage device with the following properties: - **rootDirectory** (File) - The root directory of the USB device. - **deviceName** (String) - The name of the USB device. - **device** (String) - The system identifier for the device. - **uuid** (String) - The UUID of the USB device. - **systemDisplayName** (String) - The display name of the USB device as shown by the system. - **canRead** (boolean) - Indicates if the device is readable. - **canWrite** (boolean) - Indicates if the device is writable. - **canExecute** (boolean) - Indicates if the device is executable. #### Response Example ```json { "rootDirectory": "/path/to/device", "deviceName": "MyUSB", "device": "/dev/sdb1", "uuid": "1234-ABCD", "systemDisplayName": "My USB Drive", "canRead": true, "canWrite": true, "canExecute": false } ``` ``` -------------------------------- ### Unmount USB Storage Device Source: https://context7.com/samuelcampos/usbdrivedetector/llms.txt Safely unmounts a USB storage device. The implementation is OS-specific: uses diskutil on macOS, umount on Linux, and PowerShell on Windows. ```APIDOC ## unmountStorageDevice(USBStorageDevice device) ### Description Safely unmounts a USB storage device. The implementation is OS-specific: uses diskutil on macOS, umount on Linux, and PowerShell on Windows. ### Method POST (Conceptual - actual implementation is within the library) ### Endpoint N/A (This is a library method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **device** (USBStorageDevice) - Required - The USB storage device object to unmount. ### Request Example ```java import net.samuelcampos.usbdrivedetector.USBDeviceDetectorManager; import net.samuelcampos.usbdrivedetector.USBStorageDevice; import java.io.IOException; import java.util.List; public class UnmountExample { public static void main(String[] args) { USBDeviceDetectorManager manager = new USBDeviceDetectorManager(); List devices = manager.getRemovableDevices(); if (devices.isEmpty()) { System.out.println("No USB devices found to unmount."); } else { // Unmount the first available device USBStorageDevice deviceToUnmount = devices.get(0); System.out.println("Attempting to unmount: " + deviceToUnmount.getDeviceName()); try { manager.unmountStorageDevice(deviceToUnmount); System.out.println("Device unmounted successfully!"); } catch (IOException e) { System.err.println("Failed to unmount device: " + e.getMessage()); e.printStackTrace(); } } try { manager.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` ### Response #### Success Response (200) No explicit return value, but the device is unmounted. #### Response Example None ``` -------------------------------- ### Unmount a USB Storage Device in Java Source: https://context7.com/samuelcampos/usbdrivedetector/llms.txt Safely unmounts a connected USB device. The operation is OS-specific and requires handling potential IOExceptions. ```java import net.samuelcampos.usbdrivedetector.USBDeviceDetectorManager; import net.samuelcampos.usbdrivedetector.USBStorageDevice; import java.io.IOException; import java.util.List; public class UnmountExample { public static void main(String[] args) { USBDeviceDetectorManager manager = new USBDeviceDetectorManager(); List devices = manager.getRemovableDevices(); if (devices.isEmpty()) { System.out.println("No USB devices found to unmount."); } else { // Unmount the first available device USBStorageDevice deviceToUnmount = devices.get(0); System.out.println("Attempting to unmount: " + deviceToUnmount.getDeviceName()); try { manager.unmountStorageDevice(deviceToUnmount); System.out.println("Device unmounted successfully!"); } catch (IOException e) { System.err.println("Failed to unmount device: " + e.getMessage()); e.printStackTrace(); } } try { manager.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` -------------------------------- ### Set Polling Interval Source: https://context7.com/samuelcampos/usbdrivedetector/llms.txt Changes the interval at which the library polls for USB device changes. If listeners are already registered, the polling task is automatically restarted with the new interval. ```APIDOC ## setPollingInterval(long pollingInterval) ### Description Changes the interval at which the library polls for USB device changes. If listeners are already registered, the polling task is automatically restarted with the new interval. ### Method POST (Conceptual - actual implementation is within the library) ### Endpoint N/A (This is a library method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **pollingInterval** (long) - Required - The new polling interval in milliseconds. ### Request Example ```java import net.samuelcampos.usbdrivedetector.USBDeviceDetectorManager; import java.io.IOException; public class PollingIntervalExample { public static void main(String[] args) throws IOException { // Start with default 5-second interval USBDeviceDetectorManager manager = new USBDeviceDetectorManager(); // Add a listener to start polling manager.addDriveListener(event -> { System.out.println(System.currentTimeMillis() + ": " + event); }); System.out.println("Polling every 5 seconds (default)..."); sleep(10000); // Change to faster polling (1 second) manager.setPollingInterval(1000); System.out.println("Polling every 1 second..."); sleep(5000); // Change to slower polling (10 seconds) manager.setPollingInterval(10000); System.out.println("Polling every 10 seconds..."); sleep(15000); manager.close(); } private static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } ``` ### Response #### Success Response (200) No explicit return value, but the polling interval is updated. #### Response Example None ``` -------------------------------- ### Shutdown USBDeviceDetectorManager Source: https://github.com/samuelcampos/usbdrivedetector/blob/master/README.md Invoke the close method to terminate the internal ScheduledExecutorService and allow the application to exit. ```java // Shutdown an initialized USBDeviceDetectorManager driveDetector.close(); ``` -------------------------------- ### Remove USB Drive Listeners in Java Source: https://context7.com/samuelcampos/usbdrivedetector/llms.txt Removes a registered listener. Polling stops automatically when the last listener is removed to conserve resources. ```java import net.samuelcampos.usbdrivedetector.USBDeviceDetectorManager; import net.samuelcampos.usbdrivedetector.events.IUSBDriveListener; import java.io.IOException; public class RemoveListenerExample { public static void main(String[] args) throws IOException { USBDeviceDetectorManager manager = new USBDeviceDetectorManager(); // Create a named listener so we can remove it later IUSBDriveListener listener = event -> { System.out.println("Event: " + event.getEventType() + " - " + event.getStorageDevice().getDeviceName()); }; // Add the listener - polling starts boolean added = manager.addDriveListener(listener); System.out.println("Listener added: " + added); // true // Adding same listener again returns false boolean addedAgain = manager.addDriveListener(listener); System.out.println("Listener added again: " + addedAgain); // false // Listen for 10 seconds try { Thread.sleep(10000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } // Remove the listener - polling stops if this was the last listener boolean removed = manager.removeDriveListener(listener); System.out.println("Listener removed: " + removed); // true manager.close(); } } ``` -------------------------------- ### Remove Drive Listener Source: https://context7.com/samuelcampos/usbdrivedetector/llms.txt Removes a previously registered listener. Polling automatically stops when the last listener is removed, conserving system resources. ```APIDOC ## removeDriveListener(IUSBDriveListener listener) ### Description Removes a previously registered listener. Polling automatically stops when the last listener is removed, conserving system resources. ### Method DELETE ### Endpoint /api/usbdrivedetector/listener ### Parameters #### Query Parameters - **listener** (IUSBDriveListener) - Required - The listener interface to remove. ### Request Example ```java USBDeviceDetectorManager manager = new USBDeviceDetectorManager(); IUSBDriveListener listener = event -> { System.out.println("Event: " + event.getEventType() + " - " + event.getStorageDevice().getDeviceName()); }; manager.addDriveListener(listener); // ... later ... boolean removed = manager.removeDriveListener(listener); ``` ### Response #### Success Response (200) - **status** (boolean) - Indicates if the listener was successfully removed. #### Response Example ```json { "status": true } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.