Example usage for java.nio.file StandardWatchEventKinds ENTRY_DELETE

List of usage examples for java.nio.file StandardWatchEventKinds ENTRY_DELETE

Introduction

In this page you can find the example usage for java.nio.file StandardWatchEventKinds ENTRY_DELETE.

Prototype

WatchEvent.Kind ENTRY_DELETE

To view the source code for java.nio.file StandardWatchEventKinds ENTRY_DELETE.

Click Source Link

Document

Directory entry deleted.

Usage

From source file:io.gravitee.gateway.services.localregistry.LocalApiDefinitionRegistry.java

@Override
protected void doStart() throws Exception {
    if (enabled) {
        super.doStart();

        this.init();

        executor = Executors.newSingleThreadExecutor(r -> new Thread(r, "registry-monitor"));
        executor.execute(() -> {//from w  ww. j  av a2  s  .  c om
            Path registry = Paths.get(registryPath);
            LOGGER.info("Start local registry monitor for directory {}", registry);

            try {
                WatchService watcher = registry.getFileSystem().newWatchService();
                registry.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
                        StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

                while (true) {
                    WatchKey key;
                    try {
                        key = watcher.take();
                    } catch (InterruptedException ex) {
                        return;
                    }

                    for (WatchEvent<?> event : key.pollEvents()) {
                        WatchEvent.Kind<?> kind = event.kind();

                        @SuppressWarnings("unchecked")
                        WatchEvent<Path> ev = (WatchEvent<Path>) event;
                        Path fileName = registry.resolve(ev.context().getFileName());

                        LOGGER.info("An event occurs for file {}: {}", fileName, kind.name());

                        if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                            Api loadedDefinition = loadDefinition(fileName.toFile());
                            Api existingDefinition = definitions.get(fileName);
                            if (existingDefinition != null) {
                                if (apiManager.get(existingDefinition.getId()) != null) {
                                    apiManager.update(loadedDefinition);
                                } else {
                                    apiManager.undeploy(existingDefinition.getId());
                                    definitions.remove(fileName);
                                    apiManager.deploy(loadedDefinition);
                                    definitions.put(fileName, loadedDefinition);
                                }
                            }
                        } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                            Api loadedDefinition = loadDefinition(fileName.toFile());
                            Api existingDefinition = apiManager.get(loadedDefinition.getId());
                            if (existingDefinition != null) {
                                apiManager.update(loadedDefinition);
                            } else {
                                apiManager.deploy(loadedDefinition);
                                definitions.put(fileName, loadedDefinition);
                            }
                        } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                            Api existingDefinition = definitions.get(fileName);
                            if (existingDefinition != null
                                    && apiManager.get(existingDefinition.getId()) != null) {
                                apiManager.undeploy(existingDefinition.getId());
                                definitions.remove(fileName);
                            }
                        }

                        boolean valid = key.reset();
                        if (!valid) {
                            break;
                        }
                    }
                }
            } catch (IOException ioe) {
                LOGGER.error("Unexpected error while looking for PI definitions from filesystem", ioe);
            }
        });
    }
}

From source file:com.aspc.cms.module.SyncResourceApp.java

private void registerDir(final WatchService watchService, final File dir) throws Exception {
    // Folder we are going to watch
    Path p = dir.toPath();//  w  w  w  .  j  av  a 2  s  .c o  m

    p.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY,
            StandardWatchEventKinds.ENTRY_DELETE);

    for (File f : dir.listFiles()) {
        if (f.isDirectory()) {
            registerDir(watchService, f);
        }
    }
}

From source file:com.lukakama.serviio.watchservice.watcher.WatcherRunnable.java

@Override
public void run() {
    try {/* w w w  . ja va2 s. c  o  m*/
        log.info("Watcher started.");

        initialize();

        while (true) {
            checkInterrupted();

            WatchKey watchKey = watcher.poll(CHECK_TIMEOUT, TimeUnit.MILLISECONDS);

            if (watchKey != null) {
                try {
                    log.debug("Received watchKey: {} - {}", watchKey, watchKey.watchable());

                    Path parentPath = (Path) watchKey.watchable();

                    for (WatchEvent<?> event : watchKey.pollEvents()) {
                        checkInterrupted();

                        log.debug("Received event: {} - {}", event.kind(), event.context());

                        if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
                            log.warn("Performing a full scan due loss of native FileSystem tracking data.");

                            // Canceling the old watcher.
                            IOUtils.closeQuietly(watcher);

                            // Clean any pending unaccessible path.
                            unaccessiblePaths.clear();
                            creatingPaths.clear();
                            modifyingPaths.clear();

                            // Re-initialize the monitoring.
                            initialize();

                        } else {
                            Path eventPath = parentPath.resolve((Path) event.context());

                            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                                checkNewPath(eventPath);

                            } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                                if (!unaccessiblePaths.contains(eventPath)) {
                                    if (isPathFullyAccessible(eventPath)) {
                                        handlePathChanged(eventPath);

                                    } else {
                                        unaccessiblePaths.add(eventPath);
                                        modifyingPaths.add(eventPath);

                                        log.debug(
                                                "File unacessible upon modification. Starting monitoring for '{}'.",
                                                eventPath);
                                    }
                                }
                            } else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                                if (unaccessiblePaths.contains(eventPath)) {
                                    unaccessiblePaths.remove(eventPath);

                                    log.debug("Monitored file removed. Canceling monitoring for '{}'.",
                                            eventPath);

                                    if (modifyingPaths.contains(eventPath)) {
                                        modifyingPaths.remove(eventPath);
                                        handlePathRemoved(eventPath);
                                    } else {
                                        creatingPaths.remove(eventPath);
                                    }
                                } else {
                                    handlePathRemoved(eventPath);
                                }
                            }
                        }
                    }

                } finally {
                    watchKey.reset();
                }
            }

            if (!unaccessiblePaths.isEmpty()) {
                checkAccessiblePaths();

            } else if ((updateNotificationTimestamp != -1)
                    && ((System.currentTimeMillis() - updateNotificationTimestamp) > CHECK_TIMEOUT)) {
                // Nothing happened since last update. Resetting the updateTimestamp and requesting a library update on
                // Serviio.
                updateNotificationTimestamp = -1;
                updateServiioReposotories();

            } else if (updateNotificationTimestamp == -1) {
                // No pending path to checks and no pending updates to notify. Check external configuration changes.

                Object newFlagValue = getFieldValue(LibraryManager.getInstance(),
                        "libraryAdditionsCheckerThread");
                if ((configChangeFlag != null) && (newFlagValue != configChangeFlag)) {
                    log.info("Detected configuration change. Restart monitoring.");
                    configChangeFlag = newFlagValue;

                    // Canceling the old watcher.
                    IOUtils.closeQuietly(watcher);

                    // Clean any pending unaccessible path.
                    unaccessiblePaths.clear();
                    creatingPaths.clear();
                    modifyingPaths.clear();

                    // Re-initialize the monitoring.
                    initialize();
                }
            }
        }
    } catch (InterruptedException e) {
        // This thread has been interrupted. Just exit.
        return;

    } finally {
        // Release any bounded resource.
        unaccessiblePaths.clear();
        creatingPaths.clear();
        modifyingPaths.clear();

        IOUtils.closeQuietly(watcher);

        log.info("Watcher stopped.");
    }
}

From source file:de.elomagic.carafile.client.CaraCloud.java

private void registerDefaultWatch(final Path path) throws IOException {
    path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY,
            StandardWatchEventKinds.ENTRY_DELETE);
}

From source file:com.iorga.iraj.servlet.AgglomeratorServlet.java

private long searchAndAppendAfter(final ServletConfig config, final Element agglomerateElement,
        final String scriptSrc, final String pathPrefix, final String pathSuffix, final String urlAttribute,
        long lastModified) throws MalformedURLException, IOException, URISyntaxException {
    if (mode == Mode.DEVELOPMENT) {
        // add a watch for that directory
        final Path path = Paths.get(config.getServletContext().getRealPath(scriptSrc));
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
    }//  w ww  .  j  a va2s . c  om
    final Set<String> childrenPaths = config.getServletContext().getResourcePaths(scriptSrc);
    for (final String path : childrenPaths) {
        if (path.endsWith(pathSuffix)) {
            // add that JS
            final StringBuilder targetScript = new StringBuilder("<");
            targetScript.append(agglomerateElement.tagName());
            // copy all the origin attributes
            for (final Attribute attribute : agglomerateElement.attributes()) {
                final String key = attribute.getKey();
                if (!ATTRIBUTE_NAME.equalsIgnoreCase(key) && !urlAttribute.equalsIgnoreCase(key)
                        && !URL_ATTRIBUTE_ATTRIBUTE_NAME.equalsIgnoreCase(key)) {
                    targetScript.append(" ").append(attribute.html());
                }
            }
            // specify the src path
            final String childUrl = StringUtils.removeStart(path, pathPrefix);
            targetScript.append(" ").append(new Attribute(urlAttribute, childUrl).html()).append(" />");
            agglomerateElement.after(targetScript.toString());
            lastModified = Math.max(
                    config.getServletContext().getResource(childUrl).openConnection().getLastModified(),
                    lastModified);
        } else if (path.endsWith("/")) {
            // it's a directory, recurse search & append
            lastModified = Math.max(searchAndAppendAfter(config, agglomerateElement, path, pathPrefix,
                    pathSuffix, urlAttribute, lastModified), lastModified);
        }
    }
    return lastModified;
}

From source file:ddf.camel.component.catalog.content.ContentProducerDataAccessObjectTest.java

@Test
public void testCreateContentItem() throws Exception {
    File testFile = temporaryFolder.newFile("testCreateContentItem.txt");

    // make sample list of metacard and set of keys
    List<MetacardImpl> metacardList = ImmutableList.of(new MetacardImpl());
    String uri = testFile.toURI().toASCIIString();
    Set<String> keys = new HashSet<>(Collections.singletonList(String.valueOf(DigestUtils.sha1Hex(uri))));

    // mock out responses for create, delete, update
    CreateResponse mockCreateResponse = mock(CreateResponse.class);
    doReturn(metacardList).when(mockCreateResponse).getCreatedMetacards();

    DeleteResponse mockDeleteResponse = mock(DeleteResponse.class);
    doReturn(metacardList).when(mockDeleteResponse).getDeletedMetacards();

    UpdateResponse mockUpdateResponse = mock(UpdateResponse.class);
    doReturn(metacardList).when(mockUpdateResponse).getUpdatedMetacards();

    // setup mockFileSystemPersistenceProvider
    FileSystemPersistenceProvider mockFileSystemPersistenceProvider = mock(FileSystemPersistenceProvider.class);
    doReturn(keys).when(mockFileSystemPersistenceProvider).loadAllKeys();
    doAnswer(invocationOnMock -> keys.remove(invocationOnMock.getArguments()[0]))
            .when(mockFileSystemPersistenceProvider).delete(anyString());
    doReturn("sample").when(mockFileSystemPersistenceProvider).loadFromPersistence(any(String.class));

    // setup mockCatalogFramework
    CatalogFramework mockCatalogFramework = mock(CatalogFramework.class);
    doReturn(mockCreateResponse).when(mockCatalogFramework).create(any(CreateStorageRequest.class));
    doReturn(mockDeleteResponse).when(mockCatalogFramework).delete(any(DeleteRequest.class));

    // setup mockSourceInfo
    SourceInfoResponse mockSourceInfoResponse = mock(SourceInfoResponse.class);
    SourceDescriptor mockSourceDescriptor = mock(SourceDescriptor.class);

    when(mockSourceDescriptor.isAvailable()).thenReturn(true);
    when(mockSourceInfoResponse.getSourceInfo()).thenReturn(Collections.singleton(mockSourceDescriptor));
    when(mockCatalogFramework.getSourceInfo(any(SourceInfoRequest.class))).thenReturn(mockSourceInfoResponse);

    // setup mockComponent
    ContentComponent mockComponent = mock(ContentComponent.class);
    doReturn(mockCatalogFramework).when(mockComponent).getCatalogFramework();

    // setup mockEndpoint
    ContentEndpoint mockEndpoint = mock(ContentEndpoint.class);
    doReturn(mockComponent).when(mockEndpoint).getComponent();

    WatchEvent.Kind<Path> kind;

    String mimeType = "txt";

    Map<String, Object> headers = new HashedMap();
    Map<String, Serializable> attributeOverrides = new HashMap<>();
    attributeOverrides.put("example", ImmutableList.of("something", "something1"));
    attributeOverrides.put("example2", ImmutableList.of("something2"));
    headers.put(Constants.ATTRIBUTE_OVERRIDES_KEY, attributeOverrides);
    headers.put(Constants.STORE_REFERENCE_KEY, uri);

    kind = StandardWatchEventKinds.ENTRY_CREATE;
    contentProducerDataAccessObject.createContentItem(mockFileSystemPersistenceProvider, mockEndpoint, testFile,
            kind, mimeType, headers);/*from  w w  w.j a  va 2s  .  c  om*/
    verify(mockCatalogFramework).create(any(CreateStorageRequest.class));

    kind = StandardWatchEventKinds.ENTRY_MODIFY;
    contentProducerDataAccessObject.createContentItem(mockFileSystemPersistenceProvider, mockEndpoint, testFile,
            kind, mimeType, headers);
    verify(mockCatalogFramework).update(any(UpdateStorageRequest.class));

    kind = StandardWatchEventKinds.ENTRY_DELETE;
    contentProducerDataAccessObject.createContentItem(mockFileSystemPersistenceProvider, mockEndpoint, testFile,
            kind, mimeType, headers);
    verify(mockCatalogFramework).delete(any(DeleteRequest.class));

    contentProducerDataAccessObject.createContentItem(mockFileSystemPersistenceProvider, mockEndpoint, testFile,
            kind, mimeType, headers);
    verify(mockCatalogFramework).delete(any(DeleteRequest.class));
}

From source file:MonitorSaurausRex.MainMenu.java

public boolean MonitorDirectory() {

    Path directory = Paths.get("C:/Users/" + user + "/Documents/");
    try {/*from  www  .j  a  v  a  2 s .c  o  m*/
        WatchService fileSystemWatchService = FileSystems.getDefault().newWatchService();
        WatchKey watchKey = directory.register(fileSystemWatchService, StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);

        testTimer = new TimerTask() {

            @Override
            public void run() {
                checkPause = true;
                test = changeCheck();

                if (test) {
                    testTimer.cancel();
                    System.out.println("Quaritnen sucsessfully activates");
                }
            }

        };

        Timer timer = new Timer();
        timer.schedule(testTimer, 0, 1000);
        while (true) {
            WatchKey watchKeyActual = fileSystemWatchService.take();
            for (WatchEvent<?> event : watchKeyActual.pollEvents()) {

                WatchEvent.Kind<?> eventKind = event.kind();

                if (eventKind == StandardWatchEventKinds.OVERFLOW) {
                    continue;
                }

                WatchEvent<Path> eventPath = (WatchEvent<Path>) event;
                Path fileName = eventPath.context();

                //timerCheck(); ????? 
                //http://stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java
                //  boolean test = false;
                if (checkPause == false) {
                    checkPause = true;
                } else {
                    ChangeCounter++;
                    System.out.println("Event " + eventKind + " occurred on " + fileName);
                }
                if (test)
                    break;
            }
            boolean isReset = watchKeyActual.reset();
            if (!isReset || test) {
                break;
            }
        }

    } catch (IOException | InterruptedException ioe) {
    }

    return true; /// EXIT METHOD
}

From source file:org.codelibs.empros.agent.watcher.file.FileWatcher.java

@Override
@SuppressWarnings("restriction")
public void start() {
    if (started.getAndSet(true)) {
        return;//from www .  j  a v  a2s  . c o  m
    }

    int count = 0;
    while (true) {
        count++;

        final String key = "watchPath" + count;
        final String value = PropertiesUtil.getAsString(FILEWATCHER_PROPERTIES, key, null);
        if (StringUtils.isEmpty(value)) {
            break;
        }

        final File file = new File(value);
        if (!file.isDirectory()) {
            continue;
        }

        final String kindStr = PropertiesUtil.getAsString(FILEWATCHER_PROPERTIES + ".kinds", key,
                "create,modify,delete,overflow");
        final String[] kinds = kindStr.split(",");
        final List<Kind<?>> kindList = new ArrayList<Kind<?>>(4);
        for (final String kind : kinds) {
            if (StringUtils.isNotBlank(kind)) {
                switch (kind.trim()) {
                case "create":
                    kindList.add(StandardWatchEventKinds.ENTRY_CREATE);
                    break;
                case "modify":
                    kindList.add(StandardWatchEventKinds.ENTRY_MODIFY);
                    break;
                case "delete":
                    kindList.add(StandardWatchEventKinds.ENTRY_DELETE);
                    break;
                case "overflow":
                    kindList.add(StandardWatchEventKinds.OVERFLOW);
                    break;
                default:
                    logger.warn("unknown kind: {}", kind);
                    break;
                }
            }
        }

        final String modifierStr = PropertiesUtil.getAsString(FILEWATCHER_PROPERTIES + ".modifiers", key, "");
        final String[] modifiers = modifierStr.split(",");
        final List<WatchEvent.Modifier> modifierList = new ArrayList<WatchEvent.Modifier>(4);
        for (final String modifier : modifiers) {
            if (StringUtils.isNotBlank(modifier)) {
                switch (modifier.trim()) {
                case "fileTree":
                    modifierList.add(com.sun.nio.file.ExtendedWatchEventModifier.FILE_TREE);
                    break;
                default:
                    logger.warn("unknown modifier: {}", modifier);
                    break;
                }
            }
        }

        fileWatcherList
                .add(new FileWatchTask(eventManager, file.toPath(), kindList.toArray(new Kind[kindList.size()]),
                        modifierList.toArray(new WatchEvent.Modifier[modifierList.size()])));

    }

    if (fileWatcherList.isEmpty()) {
        logger.info("Cannot find path setting.");
        // TODO shutdown fook
        return;
    }

    for (final FileWatchTask fileWatchTask : fileWatcherList) {
        fileWatchTask.start();
    }

}

From source file:org.flowerplatform.web.git.GitUtils.java

public void listenForChanges(File file) throws IOException {
    Path path = file.toPath();/*from  w w  w  . j  a v a2  s. c  om*/
    if (file.isDirectory()) {
        WatchService ws = path.getFileSystem().newWatchService();
        path.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_MODIFY);
        WatchKey watch = null;
        while (true) {
            System.out.println("Watching directory: " + file.getPath());
            try {
                watch = ws.take();
            } catch (InterruptedException ex) {
                System.err.println("Interrupted");
            }
            List<WatchEvent<?>> events = watch.pollEvents();
            if (!watch.reset()) {
                break;
            }
            for (WatchEvent<?> event : events) {
                Kind<Path> kind = (Kind<Path>) event.kind();
                Path context = (Path) event.context();
                if (kind.equals(StandardWatchEventKinds.OVERFLOW)) {
                    System.out.println("OVERFLOW");
                } else if (kind.equals(StandardWatchEventKinds.ENTRY_CREATE)) {
                    System.out.println("Created: " + context.getFileName());
                } else if (kind.equals(StandardWatchEventKinds.ENTRY_DELETE)) {
                    System.out.println("Deleted: " + context.getFileName());
                } else if (kind.equals(StandardWatchEventKinds.ENTRY_MODIFY)) {
                    System.out.println("Modified: " + context.getFileName());
                }
            }
        }
    } else {
        System.err.println("Not a directory. Will exit.");
    }
}

From source file:org.siphon.d2js.jshttp.ServerUnitManager.java

public void onFileChanged(WatchEvent<Path> ev, Path file) {
    Kind<Path> kind = ev.kind();
    String filename = file.toString();
    try {/*w  w  w  . j  a  v a 2  s . c om*/
        if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
            if (allD2js.containsKey(filename)) {
                if (logger.isDebugEnabled()) {
                    logger.debug(filename + " dropped");
                }
                ScriptObjectMirror d2js = allD2js.get(filename);
                if (d2js.containsKey("releaseD2js")) {
                    d2js.callMember("releaseD2js");
                }
                allD2js.remove(filename);
                //TODO call releaseD2js?
            }
        } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
            if (allD2js.containsKey(filename)) {
                if (logger.isDebugEnabled()) {
                    logger.debug(filename + " changed");
                }
                ScriptObjectMirror d2js = allD2js.get(filename);
                if (d2js.containsKey("releaseD2js")) {
                    d2js.callMember("releaseD2js");
                }
                allD2js.remove(filename);
            }
        }
    } catch (Exception e) {
        logger.error("file synchronize failed on " + filename + " changed ", e);
    }
}