Example usage for java.nio.file WatchEvent kind

List of usage examples for java.nio.file WatchEvent kind

Introduction

In this page you can find the example usage for java.nio.file WatchEvent kind.

Prototype

Kind<T> kind();

Source Link

Document

Returns the event kind.

Usage

From source file:com.mycompany.trafficimportfileconverter2.Main2Controller.java

private void watchForConsumption() throws IOException {
    WatchService watcher = FileSystems.getDefault().newWatchService();

    try {/*from   www  .jav  a 2s.co  m*/
        Path dir = getOutputDir().toPath();
        WatchKey key = dir.register(watcher, ENTRY_DELETE);

        for (;;) {

            if (Thread.interrupted()) {
                key.cancel();
                return;
            }
            try {
                key = watcher.take();
            } catch (InterruptedException x) {
                return;
            }

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

                // This key is registered only
                // for ENTRY_CREATE events,
                // but an OVERFLOW event can
                // occur regardless if events
                // are lost or discarded.
                if (kind == OVERFLOW) {
                    continue;
                }

                //                        // The filename is the
                //                        // context of the event.
                WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path filepath = ev.context();
                String filename = filepath.toString();
                System.out.println("the filename was: " + filename);
                System.out.println(kind);
                Optional<String> res = findFile(filename);
                if (res.isPresent()) {
                    System.out.println("BEFORE REMOVAL: " + myfiles.toString());
                    System.out.println("removing: " + res.get());
                    removeFromFiles(res.get());
                    System.out.println("Removed. Now: " + myfiles.toString());
                    int dpi = findThisDP(res.get());
                    if (-1 != dpi) {
                        UI(() -> {
                            datePickers[dpi].setStyle("-fx-background-color: lightgreen");
                            dayLabels[dpi].setStyle("-fx-background-color: lightgreen");
                        });
                    }
                    log("Wide Orbit CONSUMED: " + filename);

                } else {
                    System.out.println("is present was false for: " + filename);
                    System.out.println(myfiles.toString());
                }
                // Reset the key -- this step is critical if you want to
                // receive further watch events.  If the key is no longer valid,
                // the directory is inaccessible so exit the loop.
                boolean valid = key.reset();
                if (!valid) {
                    return;
                }
                if (myfiles.isEmpty()) {
                    key.cancel();
                    log("ALL WRITTEN FILES CONSUMED.");
                    System.out.println("\n\n\n");

                    return;
                }
            } //end of events
        } //end of infinite loop

    } catch (IOException x) {
        System.err.println(x);
    } finally {
        Thread.currentThread().interrupt();
    }

}

From source file:fi.jumi.core.ipc.dirs.DirectoryObserverTest.java

@Test
public void notices_new_files_even_when_the_notification_event_is_missed_due_to_an_overflow() throws Exception {
    FakeWatchService watchService = new FakeWatchService();
    observer = new DirectoryObserver(directory, noticedFiles::add) {
        @Override//from ww  w  .  j  a  v  a  2  s . c  o  m
        protected WatchService watchDirectory(Path directory, WatchEvent.Kind<?>... events) {
            return watchService;
        }
    };
    startObserver();
    tempDir.newFile("created1");
    tempDir.newFile("created2");

    watchService.publish(new FakeWatchKey().addEvent(ENTRY_CREATE, Paths.get("created1")).addEvent(OVERFLOW));

    assertThat(takeAtLeast(2, noticedFiles), containsFiles("created1", "created2"));
}

From source file:com.skynetcomputing.skynetserver.persistence.FileManager.java

protected void addListener(WatchEvent.Kind<Path> watchKind, Consumer<Path> consumer) {
    watcher.addListener(watchKind, consumer);
}

From source file:org.codice.ddf.catalog.content.monitor.DurableFileConsumer.java

private void createExchangeHelper(File file, WatchEvent.Kind<Path> fileEvent) {
    GenericFile<EventfulFileWrapper> genericFile = new GenericFile<>();
    genericFile.setFile(new EventfulFileWrapper(fileEvent, 1, file.toPath()));
    genericFile.setEndpointPath(endpoint.getConfiguration().getDirectory());
    try {//from   w w w  .  ja va  2  s  . c  om
        genericFile.setAbsoluteFilePath(file.getCanonicalPath());
    } catch (IOException e) {
        LOGGER.warn("Unable to canonicalize {}. Verify location is accessible.", file.toString());
    }
    Exchange exchange = endpoint.createExchange(genericFile);
    exchange.addOnCompletion(new ErrorLoggingSynchronization(file, fileEvent));
    processExchange(exchange);
}

From source file:io.stallion.fileSystem.FileSystemWatcherRunner.java

private void registerWatcherForFolder(IWatchEventHandler handler, String folder) {
    Path itemsDir = FileSystems.getDefault().getPath(folder);
    try {/*from  w  ww.  j a  va 2 s.c  o m*/
        if (new File(itemsDir.toString()).isDirectory()) {
            itemsDir.register(watcher,
                    new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_MODIFY,
                            StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE },
                    SensitivityWatchEventModifier.HIGH);
            Log.fine("Folder registered with watcher {0}", folder);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.mangoo.build.Watcher.java

/**
 *
 * USUALLY THIS IS THE DEFAULT WAY TO REGISTER THE EVENTS:
 *
 * WatchKey watchKey = path.register(//from w ww.  j a va  2  s. c  o  m
 *    watchService,
 *    ENTRY_CREATE,
 *    ENTRY_DELETE,
 *    ENTRY_MODIFY);
 *
 *  BUT THIS IS DAMN SLOW (at least on a Mac)
 *  THEREFORE WE USE EVENTS FROM COM.SUN PACKAGES THAT ARE WAY FASTER
 *  THIS MIGHT BREAK COMPATIBILITY WITH OTHER JDKs
 *   MORE: http://stackoverflow.com/questions/9588737/is-java-7-watchservice-slow-for-anyone-else
 *
 * @param path
 * @throws IOException
 */
private void register(Path path) throws IOException {
    WatchKey watchKey = path.register(watchService,
            new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_CREATE, //NOSONAR
                    StandardWatchEventKinds.ENTRY_MODIFY, //NOSONAR
                    StandardWatchEventKinds.ENTRY_DELETE //NOSONAR
            }, SensitivityWatchEventModifier.HIGH);

    watchKeys.put(watchKey, path);
}

From source file:sf.net.experimaestro.fs.XPMPath.java

@Override
public WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers)
        throws IOException {
    throw new NotImplementedException();
}

From source file:sf.net.experimaestro.fs.XPMPath.java

@Override
public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) throws IOException {
    throw new NotImplementedException();
}

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

public void createContentItem(FileSystemPersistenceProvider fileIdMap, ContentEndpoint endpoint,
        File ingestedFile, WatchEvent.Kind<Path> eventType, String mimeType, Map<String, Object> headers)
        throws SourceUnavailableException, IngestException {
    LOGGER.debug("Creating content item.");

    if (!eventType.equals(ENTRY_DELETE) && ingestedFile == null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Ingested File was null with eventType [{}]. Doing nothing.", eventType.name());
        }// ww  w .  ja  va2  s  .c  om
        return;
    }

    String refKey = (String) headers.get(Constants.STORE_REFERENCE_KEY);
    String safeKey = null;
    String id = null;

    // null if the file is being stored in the content store
    // not null if the file lives outside the content store (external reference)
    if (refKey != null) {
        // guards against impermissible filesystem characters
        safeKey = DigestUtils.sha1Hex(refKey);
        if (fileIdMap.loadAllKeys().contains(safeKey)) {
            id = String.valueOf(fileIdMap.loadFromPersistence(safeKey));
        } else if (!ENTRY_CREATE.equals(eventType)) {
            LOGGER.warn("Unable to look up id for {}, not performing {}", refKey, eventType.name());
            return;
        }
    }
    if (ENTRY_CREATE.equals(eventType)) {
        CreateStorageRequest createRequest = new CreateStorageRequestImpl(
                Collections.singletonList(
                        new ContentItemImpl(uuidGenerator.generateUuid(), Files.asByteSource(ingestedFile),
                                mimeType, ingestedFile.getName(), ingestedFile.length(), null)),
                getProperties(headers));

        CatalogFramework catalogFramework = endpoint.getComponent().getCatalogFramework();

        waitForAvailableSource(catalogFramework);

        CreateResponse createResponse = catalogFramework.create(createRequest);

        if (createResponse != null) {
            List<Metacard> createdMetacards = createResponse.getCreatedMetacards();

            if (safeKey != null) {
                fileIdMap.store(safeKey, createdMetacards.get(0).getId());
            }
            logIds(createdMetacards, "created");
        }
    } else if (ENTRY_MODIFY.equals(eventType)) {
        UpdateStorageRequest updateRequest = new UpdateStorageRequestImpl(
                Collections.singletonList(new ContentItemImpl(id, Files.asByteSource(ingestedFile), mimeType,
                        ingestedFile.getName(), 0, null)),
                getProperties(headers));

        UpdateResponse updateResponse = endpoint.getComponent().getCatalogFramework().update(updateRequest);
        if (updateResponse != null) {
            List<Update> updatedMetacards = updateResponse.getUpdatedMetacards();

            logIds(updatedMetacards.stream().map(Update::getNewMetacard).collect(Collectors.toList()),
                    "updated");
        }
    } else if (ENTRY_DELETE.equals(eventType)) {
        DeleteRequest deleteRequest = new DeleteRequestImpl(id);

        DeleteResponse deleteResponse = endpoint.getComponent().getCatalogFramework().delete(deleteRequest);
        if (deleteResponse != null) {
            List<Metacard> deletedMetacards = deleteResponse.getDeletedMetacards();

            if (safeKey != null) {
                fileIdMap.delete(safeKey);
            }
            logIds(deletedMetacards, "deleted");
        }
    }
}

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

private GenericFileMessage<File> getMockMessage(File testFile) {
    // set the mockGenericFile to return the test file when requested
    GenericFile<File> mockGenericFileFromBody = mock(GenericFile.class);
    doReturn(testFile).when(mockGenericFileFromBody).getFile();

    WatchEvent<Path> mockWatchEvent = mock(WatchEvent.class);

    // mock out the context that links to the file
    Path mockContext = mock(Path.class);
    doReturn(testFile).when(mockContext).toFile();

    // mock out with a sample kind
    WatchEvent.Kind mockKind = mock(WatchEvent.Kind.class);
    doReturn("example").when(mockKind).name();

    // return the kind or context for the mockWatchEvent
    doReturn(mockKind).when(mockWatchEvent).kind();
    doReturn(mockContext).when(mockWatchEvent).context();

    // return the mockWatchEvent when the file is called for
    GenericFile<File> mockGenericFile = mock(GenericFile.class);
    doReturn(mockWatchEvent).when(mockGenericFile).getFile();

    GenericFileMessage mockMessage = mock(GenericFileMessage.class);
    doReturn(mockGenericFileFromBody).when(mockMessage).getBody();
    doReturn(mockGenericFile).when(mockMessage).getGenericFile();

    return mockMessage;
}