Java Code Examples for java.nio.file.FileSystem#newWatchService()

The following examples show how to use java.nio.file.FileSystem#newWatchService() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LogSearchConfigLogFeederLocal.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Override
public void monitorInputConfigChanges(final InputConfigMonitor inputConfigMonitor, final LogLevelFilterMonitor logLevelFilterMonitor, String clusterName) throws Exception {
  final JsonParser parser = new JsonParser();
  final JsonArray globalConfigNode = new JsonArray();
  for (String globalConfigJsonString : inputConfigMonitor.getGlobalConfigJsons()) {
    JsonElement globalConfigJson = parser.parse(globalConfigJsonString);
    globalConfigNode.add(globalConfigJson.getAsJsonObject().get("global"));
    Path filePath = Paths.get(configDir, "global.config.json");
    String strData = InputConfigGson.gson.toJson(globalConfigJson);
    byte[] data = strData.getBytes(StandardCharsets.UTF_8);
    Files.write(filePath, data);
  }

  File[] inputConfigFiles = new File(configDir).listFiles(inputConfigFileFilter);
  if (inputConfigFiles != null) {
    for (File inputConfigFile : inputConfigFiles) {
      tryLoadingInputConfig(inputConfigMonitor, parser, globalConfigNode, inputConfigFile);
    }
  }
  final FileSystem fs = FileSystems.getDefault();
  final WatchService ws = fs.newWatchService();
  Path configPath = Paths.get(configDir);
  LogSearchConfigLocalUpdater updater = new LogSearchConfigLocalUpdater(configPath, ws, inputConfigMonitor, inputFileContentsMap,
    parser, globalConfigNode, serviceNamePattern);
  executorService.submit(updater);
}
 
Example 2
Source File: DeleteInterference.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void openAndCloseWatcher(Path dir) {
    FileSystem fs = FileSystems.getDefault();
    for (int i = 0; i < ITERATIONS_COUNT; i++) {
        try (WatchService watcher = fs.newWatchService()) {
            dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        } catch (IOException ioe) {
            // ignore
        }
    }
}
 
Example 3
Source File: DeleteInterference.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void openAndCloseWatcher(Path dir) {
    FileSystem fs = FileSystems.getDefault();
    for (int i = 0; i < ITERATIONS_COUNT; i++) {
        try (WatchService watcher = fs.newWatchService()) {
            dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        } catch (IOException ioe) {
            // ignore
        }
    }
}
 
Example 4
Source File: DeleteInterference.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void openAndCloseWatcher(Path dir) {
    FileSystem fs = FileSystems.getDefault();
    for (int i = 0; i < ITERATIONS_COUNT; i++) {
        try (WatchService watcher = fs.newWatchService()) {
            dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        } catch (IOException ioe) {
            // ignore
        }
    }
}
 
Example 5
Source File: DeleteInterference.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static void openAndCloseWatcher(Path dir) {
    FileSystem fs = FileSystems.getDefault();
    for (int i = 0; i < ITERATIONS_COUNT; i++) {
        try (WatchService watcher = fs.newWatchService()) {
            dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        } catch (IOException ioe) {
            // ignore
        }
    }
}
 
Example 6
Source File: DeleteInterference.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void openAndCloseWatcher(Path dir) {
    FileSystem fs = FileSystems.getDefault();
    for (int i = 0; i < ITERATIONS_COUNT; i++) {
        out.printf("open %d begin%n", i);
        try (WatchService watcher = fs.newWatchService()) {
            dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        } catch (IOException ioe) {
            // ignore
        } finally {
            out.printf("open %d end%n", i);
        }
    }
}
 
Example 7
Source File: DeleteInterference.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void openAndCloseWatcher(Path dir) {
    FileSystem fs = FileSystems.getDefault();
    for (int i = 0; i < ITERATIONS_COUNT; i++) {
        try (WatchService watcher = fs.newWatchService()) {
            dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        } catch (IOException ioe) {
            // ignore
        }
    }
}
 
Example 8
Source File: DeleteInterference.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void openAndCloseWatcher(Path dir) {
    FileSystem fs = FileSystems.getDefault();
    for (int i = 0; i < ITERATIONS_COUNT; i++) {
        try (WatchService watcher = fs.newWatchService()) {
            dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        } catch (IOException ioe) {
            // ignore
        }
    }
}
 
Example 9
Source File: ConfigurationFolderMonitor.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructs a new object.
 * @param folder the configuration folder
 * @exception IOException
 *            error creating the watcher
 */
public ConfigurationFolderMonitor(final File folder) throws IOException {
    configFolder = folder;
    listeners = new java.util.ArrayList<ConfigurationFileChangedListener>();
    setDaemon(true);
    lock = new Object();
    final FileSystem filesystem = FileSystems.getDefault();
    watcher = filesystem.newWatchService();
    final String canonicalPath = folder.getCanonicalPath();
    final Path path = filesystem.getPath(canonicalPath);
    path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
            StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY);
}
 
Example 10
Source File: ConfigurationTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Test
public void testFileSystemWithDefaultWatchService() throws IOException {
  FileSystem fs = Jimfs.newFileSystem(Configuration.unix());

  WatchService watchService = fs.newWatchService();
  assertThat(watchService).isInstanceOf(PollingWatchService.class);

  PollingWatchService pollingWatchService = (PollingWatchService) watchService;
  assertThat(pollingWatchService.interval).isEqualTo(5);
  assertThat(pollingWatchService.timeUnit).isEqualTo(SECONDS);
}
 
Example 11
Source File: ConfigurationTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Test
public void testFileSystemWithCustomWatchServicePollingInterval() throws IOException {
  FileSystem fs =
      Jimfs.newFileSystem(
          Configuration.unix().toBuilder()
              .setWatchServiceConfiguration(polling(10, MILLISECONDS))
              .build());

  WatchService watchService = fs.newWatchService();
  assertThat(watchService).isInstanceOf(PollingWatchService.class);

  PollingWatchService pollingWatchService = (PollingWatchService) watchService;
  assertThat(pollingWatchService.interval).isEqualTo(10);
  assertThat(pollingWatchService.timeUnit).isEqualTo(MILLISECONDS);
}
 
Example 12
Source File: UnixSocketFile.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
    throws InterruptedException, IOException {

    // Use 'which' to verify that 'nc' is available and skip the test
    // if it is not.
    Process proc = Runtime.getRuntime().exec("which nc");
    InputStream stdout = proc.getInputStream();
    int b = stdout.read();
    proc.destroy();
    if (b == -1) {
        System.err.println("Netcat command unavailable; skipping test.");
        return;
    }

    // Create a new sub-directory of the nominal test directory in which
    // 'nc' will create the socket file.
    String testSubDir = System.getProperty("test.dir", ".")
        + File.separator + TEST_SUB_DIR;
    Path socketTestDir = Paths.get(testSubDir);
    Files.createDirectory(socketTestDir);

    // Set the path of the socket file.
    String socketFilePath = testSubDir + File.separator
        + SOCKET_FILE_NAME;

    // Create a process which executes the nc (netcat) utility to create
    // a socket file at the indicated location.
    FileSystem fs = FileSystems.getDefault();
    try (WatchService ws = fs.newWatchService()) {
        // Watch the test sub-directory to receive notification when an
        // entry, i.e., the socket file, is added to the sub-directory.
        WatchKey wk = socketTestDir.register(ws,
                StandardWatchEventKinds.ENTRY_CREATE);

        // Execute the 'nc' command.
        proc = Runtime.getRuntime().exec(CMD_BASE + " " + socketFilePath);

        // Wait until the socket file is created.
        WatchKey key = ws.take();
        if (key != wk) {
            throw new RuntimeException("Unknown entry created - expected: "
                + wk.watchable() + ", actual: " + key.watchable());
        }
        wk.cancel();
    }

    // Verify that the socket file in fact exists.
    Path socketPath = fs.getPath(socketFilePath);
    if (!Files.exists(socketPath)) {
        throw new RuntimeException("Socket file " + socketFilePath
            + " was not created by \"nc\" command.");
    }

    // Retrieve the most recent access and modification times of the
    // socket file; print the values.
    BasicFileAttributeView attributeView = Files.getFileAttributeView(
            socketPath, BasicFileAttributeView.class);
    BasicFileAttributes oldAttributes = attributeView.readAttributes();
    FileTime oldAccessTime = oldAttributes.lastAccessTime();
    FileTime oldModifiedTime = oldAttributes.lastModifiedTime();
    System.out.println("Old times: " + oldAccessTime
        + " " + oldModifiedTime);

    // Calculate the time to which the access and modification times of the
    // socket file will be changed.
    FileTime newFileTime =
        FileTime.fromMillis(oldAccessTime.toMillis() + 1066);

    try {
        // Set the access and modification times of the socket file.
        attributeView.setTimes(newFileTime, newFileTime, null);

        // Retrieve the updated access and modification times of the
        // socket file; print the values.
        FileTime newAccessTime = null;
        FileTime newModifiedTime = null;
        BasicFileAttributes newAttributes = attributeView.readAttributes();
        newAccessTime = newAttributes.lastAccessTime();
        newModifiedTime = newAttributes.lastModifiedTime();
        System.out.println("New times: " + newAccessTime + " "
            + newModifiedTime);

        // Verify that the updated times have the expected values.
        if ((newAccessTime != null && !newAccessTime.equals(newFileTime))
            || (newModifiedTime != null
                && !newModifiedTime.equals(newFileTime))) {
            throw new RuntimeException("Failed to set correct times.");
        }
    } finally {
        // Destry the process running netcat and delete the socket file.
        proc.destroy();
        Files.delete(socketPath);
    }
}
 
Example 13
Source File: AbstractFileWatcher.java    From LuckPerms with MIT License 4 votes vote down vote up
public AbstractFileWatcher(FileSystem fileSystem, boolean autoRegisterNewSubDirectories) throws IOException {
    this.service = fileSystem.newWatchService();
    this.autoRegisterNewSubDirectories = autoRegisterNewSubDirectories;
}
 
Example 14
Source File: MainWatch.java    From DiscordSoundboard with Apache License 2.0 4 votes vote down vote up
@Async
@SuppressWarnings("unchecked")
public void watchDirectoryPath(Path path) {
    // Sanity check - Check if path is a folder
    try {
        Boolean isFolder = (Boolean) Files.getAttribute(path,
                "basic:isDirectory", NOFOLLOW_LINKS);
        if (!isFolder) {
            throw new IllegalArgumentException("Path: " + path + " is not a folder");
        }
    } catch (IOException e) {
        // Folder does not exists
        e.printStackTrace();
    }

    System.out.println("Watching path: " + path);

    // We obtain the file system of the Path
    FileSystem fs = path.getFileSystem ();

    // We create the new WatchService using the new try() block
    try(WatchService service = fs.newWatchService()) {

        // We register the path to the service
        // We watch for creation events
        path.register(service, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);

        // Start the infinite polling loop
        WatchKey key;
        while(true) {
            key = service.take();

            // Dequeueing events
            Kind<?> kind;
            for(WatchEvent<?> watchEvent : key.pollEvents()) {
                // Get the type of the event
                kind = watchEvent.kind();
                if (kind == ENTRY_CREATE || kind == ENTRY_DELETE || kind == ENTRY_MODIFY) {
                    // A new Path was created 
                    Path newPath = ((WatchEvent<Path>) watchEvent).context();
                    // Output
                    //Mark the observable object as changed.
                    this.setChanged();
                    System.out.println("New path created: " + newPath + " kind of operation: " + kind);
                    
                    notifyObservers(this);
                }
            }

            if(!key.reset()) {
                break; //loop
            }
        }
    } catch(IOException | InterruptedException ioe) {
        ioe.printStackTrace();
    }
}
 
Example 15
Source File: FileSystemAssetWatcher.java    From seventh with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @param dir
 * @throws IOException
 */
public FileSystemAssetWatcher(File dir) throws IOException {
    FileSystem fileSystem = FileSystems.getDefault();
    this.isActive = new AtomicBoolean(false);
    
    this.watchedAssets = new ConcurrentHashMap<File, WatchedAsset<?>>();
    this.pathToWatch = dir.toPath();
    
    this.watchService = fileSystem.newWatchService();
    this.watchThread = new Thread(new Runnable() {
        
        @SuppressWarnings("unchecked")
        @Override
        public void run() {
            while(isActive.get()) {
                try {
                    WatchKey key = watchService.take();
                    if(key.isValid()) {
                        List<WatchEvent<?>> events = key.pollEvents();
                        for(int i = 0; i < events.size(); i++) {
                            WatchEvent<?> event = events.get(i);
                            WatchEvent.Kind<?> kind = event.kind();
                            
                            /* ignore overflow events */
                            if(kind == StandardWatchEventKinds.OVERFLOW) {
                                continue;
                            }
                            
                            /* we are only listening for 'changed' events */
                            WatchEvent<Path> ev = (WatchEvent<Path>)event;
                            Path filename = ev.context();
                                                            
                            /* if we have a registered asset, lets go ahead and notify it */
                            WatchedAsset<?> watchedAsset = watchedAssets.get(new File(pathToWatch.toFile(), filename.toString()));
                            if(watchedAsset != null) {
                                try {
                                    watchedAsset.onAssetChanged();
                                }
                                catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                    
                    key.reset();
                }
                catch (ClosedWatchServiceException e) {
                    break;
                }
                catch (InterruptedException e) {
                    break;
                }
            }
        }
    }, "watcher-thread");
    this.watchThread.setDaemon(true);
    
    this.pathToWatch.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
}
 
Example 16
Source File: PutHeadChunkRunnable.java    From crate with Apache License 2.0 4 votes vote down vote up
private void initWatcher(String directoryToWatch) throws IOException {
    FileSystem fs = FileSystems.getDefault();
    watcher = fs.newWatchService();
    Path path = fs.getPath(directoryToWatch);
    watchKey = path.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
}