java.nio.file.FileSystem#newWatchService ( )源码实例Demo

下面列出了java.nio.file.FileSystem#newWatchService ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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);
}
 
源代码2 项目: dragonwell8_jdk   文件: DeleteInterference.java
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
        }
    }
}
 
源代码3 项目: TencentKona-8   文件: DeleteInterference.java
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
        }
    }
}
 
源代码4 项目: openjdk-jdk8u   文件: DeleteInterference.java
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
        }
    }
}
 
源代码5 项目: openjdk-jdk8u-backup   文件: DeleteInterference.java
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
        }
    }
}
 
源代码6 项目: openjdk-jdk9   文件: DeleteInterference.java
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);
        }
    }
}
 
源代码7 项目: jdk8u-jdk   文件: DeleteInterference.java
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
        }
    }
}
 
源代码8 项目: jdk8u_jdk   文件: DeleteInterference.java
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
        }
    }
}
 
源代码9 项目: JVoiceXML   文件: ConfigurationFolderMonitor.java
/**
 * 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);
}
 
源代码10 项目: jimfs   文件: ConfigurationTest.java
@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);
}
 
源代码11 项目: jimfs   文件: ConfigurationTest.java
@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);
}
 
源代码12 项目: openjdk-jdk9   文件: UnixSocketFile.java
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);
    }
}
 
源代码13 项目: LuckPerms   文件: AbstractFileWatcher.java
public AbstractFileWatcher(FileSystem fileSystem, boolean autoRegisterNewSubDirectories) throws IOException {
    this.service = fileSystem.newWatchService();
    this.autoRegisterNewSubDirectories = autoRegisterNewSubDirectories;
}
 
源代码14 项目: DiscordSoundboard   文件: MainWatch.java
@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();
    }
}
 
源代码15 项目: seventh   文件: FileSystemAssetWatcher.java
/**
 * @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);
}
 
源代码16 项目: crate   文件: PutHeadChunkRunnable.java
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);
}