List of usage examples for java.nio.file WatchEvent kind
Kind<T> kind();
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 ww . j a v a 2 s.c o m 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:erigo.filewatch.FileWatch.java
/** * Creates a WatchService and registers the given directory *///from w ww . java 2 s .c o m // FileWatch(Path watchDir, String outputFilename, Path outputDirI) throws IOException { FileWatch(String[] argsI) throws IOException { // // Parse command line arguments // // 1. Setup command line options // Options options = new Options(); // Boolean options (only the flag, no argument) options.addOption("h", "help", false, "Print this message."); options.addOption("a", "adjust_latency", false, "Divide latency results by 2 because test data files are from a recaster (round-trip)."); options.addOption("d", "disp_recaster", false, "Display results when operating in recaster mode."); // Command line options that include an argument Option nextOption = Option.builder("i").argName("watchdir").hasArg().desc( "Directory to watch for incoming test data files (must be an existing directory); default = \"" + DEFAULT_WATCH_DIR + "\".") .build(); options.addOption(nextOption); nextOption = Option.builder("o").argName("outfilename").hasArg() .desc("Name of the output metrics data file; must be a new file.").build(); options.addOption(nextOption); nextOption = Option.builder("p").argName("pollinterval_msec").hasArg().desc( "Watch for new files by polling (don't use Java WatchService); sleep for <pollinterval_msec> (milliseconds) between scans.") .build(); options.addOption(nextOption); nextOption = Option.builder("r").argName("recasterdir").hasArg() .desc("Recast test data files to the specified output directory (must be an existing directory).") .build(); options.addOption(nextOption); nextOption = Option.builder("t").argName("plottitle").hasArg() .desc("Custom title for throughput and latency plots.").build(); options.addOption(nextOption); // // 2. Parse command line options // CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, argsI); } catch (ParseException exp) { // oops, something went wrong System.err.println("Command line argument parsing failed: " + exp.getMessage()); return; } // // 3. Retrieve the command line values // if (line.hasOption("h")) { // Display help message and quit HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(100); formatter.printHelp("FileWatch", options); return; } bAdjustLatencyMetrics = line.hasOption("a"); bOutputResultsInRecastMode = line.hasOption("d"); // Watch directory String watchDirName = line.getOptionValue("i", DEFAULT_WATCH_DIR); Path watchDir = Paths.get(watchDirName); if (!watchDir.toFile().isDirectory()) { System.err.println("\nThe given watch directory does not exist."); System.exit(-1); } // Recaster directory Path outputDirPath = null; String outputDirName = line.getOptionValue("r"); if (outputDirName != null) { outputDirPath = Paths.get(outputDirName); if (!outputDirPath.toFile().isDirectory()) { System.err.println("\nThe given recaster output directory does not exist."); System.exit(-1); } // Make sure watchDir and outputDir aren't the same if (watchDir.toAbsolutePath().compareTo(outputDirPath.toAbsolutePath()) == 0) { System.err.println("\nThe recaster output directory cannot be the same as the watch directory."); System.exit(-1); } bRecast = true; outputDir = outputDirPath.toFile(); } // Output filename String outputFilename = line.getOptionValue("o"); if ((outputFilename == null) && (!bRecast || bOutputResultsInRecastMode)) { System.err.println("\nMust specify the name of the output data file."); System.exit(-1); } if (outputFilename != null) { File outputFile = new File(outputFilename); if (outputFile.isDirectory()) { System.err.println( "\nThe given output data file is the name of a directory; must specify an output filename."); System.exit(-1); } else if (outputFile.isFile()) { System.err.println( "\nThe given output data file is the name of an existing file; must specify a new filename."); System.exit(-1); } } // Use polling to check for new files? String pollIntervalStr = line.getOptionValue("p"); if (pollIntervalStr != null) { try { pollInterval = Integer.parseInt(pollIntervalStr); if ((pollInterval <= 0) || (pollInterval > 1000)) { throw new NumberFormatException("Illegal value"); } } catch (NumberFormatException nfe) { System.err.println("\nPoll interval must be an integer in the range 0 < x <= 1000"); System.exit(-1); } } // Title for the throughput and latency plots customPlotTitle = line.getOptionValue("t", ""); // Make sure "end.txt" doesn't already exist in the directory; this file is our signal // that we're done processing File endFile = new File(watchDir.toFile(), "end.txt"); if (endFile.exists()) { System.err.println("\nMust delete \"" + endFile + "\" before running test."); System.exit(-1); } // If we are recasting, make sure "end.txt" doesn't exist in the output directory either if (outputDirPath != null) { endFile = new File(outputDirPath.toFile(), "end.txt"); if (endFile.exists()) { System.err.println("\nMust delete \"" + endFile + "\" in output directory before running test."); System.exit(-1); } } if (pollInterval > 0) { System.err .println("\nWatching directory \"" + watchDir + "\" for incoming files; using polling method"); processEvents_polling(watchDir.toFile()); } else { // Register the directory with the WatchService // Only collect data for ENTRY_CREATE events. Even if a file is just // copied into a directory, several ENTRY_MODIFY events can be // triggered because the file's content and its parameters (such as // timestamp) are independently set. watchDir.register(watcher, new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_CREATE }, SensitivityWatchEventModifier.HIGH); System.err.println( "\nWatching directory \"" + watchDir + "\" for incoming files; using WatchService events"); processEvents_watchservice(); watcher.close(); } if (!bRecast || bOutputResultsInRecastMode) { System.err.println("\nWrite data to file \"" + outputFilename + "\"..."); } processData(outputFilename); System.err.println( "\nFileWatch received a total of " + num_received_files + " files (not including \"end.txt\")"); System.err .println("In processing, " + num_skipped_files + " files were skipped (due to wrong name format)"); int num_files_processed = num_received_files - num_skipped_files; System.err.println( "Thus, a total of " + num_files_processed + " files with properly formatted names were processed"); System.err.println("\nTest is complete."); }