List of usage examples for java.nio.file FileSystems getDefault
public static FileSystem getDefault()
From source file:com.spectralogic.ds3cli.command.RecoverGetBulk.java
@Override public CliCommand init(final Arguments args) throws Exception { processCommandOptions(requiredArgs, optionalArgs, args); this.jobId = UUID.fromString(args.getId()); this.bucketName = args.getBucket(); this.numberOfThreads = args.getNumberOfThreads(); this.directory = args.getDirectory(); if (Guard.isStringNullOrEmpty(this.directory) || directory.equals(".")) { this.outputPath = FileSystems.getDefault().getPath("."); } else {//from ww w . ja v a2 s. c o m final Path dirPath = FileSystems.getDefault().getPath(directory); this.outputPath = FileSystems.getDefault().getPath(".").resolve(dirPath); } LOG.info("Output Path = {}", this.outputPath); final String[] prefix = args.getOptionValues(PREFIXES.getOpt()); if (prefix != null && prefix.length > 0) { this.prefixes = ImmutableList.copyOf(prefix); } return this; }
From source file:org.zanata.client.commands.FileMappingRuleHandler.java
/** * Check whether the parsed rule is applicable to a source document. * * @param docNameWithExt/* w w w.j a v a 2s . c om*/ * source document name with extension * @return true if this parsed rule is applicable */ public boolean isApplicable(DocNameWithExt docNameWithExt) { if (Strings.isNullOrEmpty(mappingRule.getPattern())) { return true; } PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + mappingRule.getPattern()); // this will help when docNameWithExt has just file name i.e. // test.odt whereas pattern is defined as **/*.odt File srcFile = new File(opts.getSrcDir(), docNameWithExt.getFullName()); log.debug("trying to match pattern: {} to file: {}", mappingRule.getPattern(), srcFile.getPath()); return matcher.matches(Paths.get(srcFile.getPath())); }
From source file:com.spectralogic.ds3cli.command.PutObject.java
@Override public CliCommand init(final Arguments args) throws Exception { processCommandOptions(requiredArgs, optionalArgs, args); this.priority = args.getPriority(); this.bucketName = args.getBucket(); this.objectName = args.getObjectName(); this.objectPath = FileSystems.getDefault().getPath(this.objectName); this.prefix = args.getPrefix(); this.force = args.isForce(); this.sync = args.isSync(); if (this.sync) { LOG.info("Using sync command"); }// w w w . ja v a2 s .com this.numberOfThreads = args.getNumberOfThreads(); this.metadata = args.getMetadata(); return this; }
From source file:com.iorga.iraj.servlet.AgglomeratorServlet.java
@Override public void init(final ServletConfig config) throws ServletException { super.init(config); if (config.getInitParameter("mode") != null) { mode = Mode.valueOf(config.getInitParameter("mode").toUpperCase()); }/* www .j av a2 s . c o m*/ if (mode == Mode.DEVELOPMENT) { // development mode, activate the watch service try { watchService = FileSystems.getDefault().newWatchService(); } catch (final IOException e) { throw new ServletException("Problem while activating the watch service", e); } } parseResourcesFromMappings(config); if (mode == Mode.DEVELOPMENT) { directoryWatcherThread = new Thread(new DirectoryWatcher(), DirectoryWatcher.class.getName()); directoryWatcherThread.setDaemon(true); directoryWatcherThread.start(); } }
From source file:org.fcrepo.kernel.api.utils.AutoReloadingConfiguration.java
/** * Starts up monitoring of the configuration for changes. *///from w ww . ja v a 2s . co m private void monitorForChanges() { if (monitorRunning) { return; } final Path path = Paths.get(configPath); if (!path.toFile().exists()) { LOGGER.debug("Configuration {} does not exist, disabling monitoring", configPath); return; } final Path directoryPath = path.getParent(); try { final WatchService watchService = FileSystems.getDefault().newWatchService(); directoryPath.register(watchService, ENTRY_MODIFY); monitorThread = new Thread(new Runnable() { @Override public void run() { try { for (;;) { WatchKey key; try { key = watchService.take(); } catch (final InterruptedException e) { LOGGER.debug("Interrupted the configuration monitor thread."); break; } for (final WatchEvent<?> event : key.pollEvents()) { final WatchEvent.Kind<?> kind = event.kind(); if (kind == OVERFLOW) { continue; } // If the configuration file triggered this event, reload it final Path changed = (Path) event.context(); if (changed.equals(path.getFileName())) { LOGGER.info("Configuration {} has been updated, reloading.", path); try { loadConfiguration(); } catch (final IOException e) { LOGGER.error("Failed to reload configuration {}", configPath, e); } } // reset the key final boolean valid = key.reset(); if (!valid) { LOGGER.debug("Monitor of {} is no longer valid", path); break; } } } } finally { try { watchService.close(); } catch (final IOException e) { LOGGER.error("Failed to stop configuration monitor", e); } } monitorRunning = false; } }); } catch (final IOException e) { LOGGER.error("Failed to start configuration monitor", e); } monitorThread.start(); monitorRunning = true; }
From source file:org.jtalks.jcommune.plugin.api.PluginLoader.java
/** * Constructs an instance for loading plugins from passed path to plugins directory. * * @param pluginsFolderPath a path to a folder that contains plugins * @param pluginConfigurationDao to load and save configuration for loaded plugins * @throws java.io.IOException when it's impossible to start tracking changes in plugins folder *///from w w w. j av a 2s .c om public PluginLoader(String pluginsFolderPath, PluginConfigurationDao pluginConfigurationDao) throws IOException { this.pluginConfigurationDao = pluginConfigurationDao; Validate.notEmpty(pluginsFolderPath); this.folder = this.resolveUserHome(pluginsFolderPath); Path path = Paths.get(folder); watchService = FileSystems.getDefault().newWatchService(); watchKey = path.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); }
From source file:com.spectralogic.ds3cli.command.RecoverPutBulk.java
public CliCommand init(final RecoveryJob job) throws Exception { this.bucketName = job.getBucketName(); this.numberOfThreads = job.getNumberOfThreads(); this.jobId = job.getId(); if (Guard.isStringNullOrEmpty(job.getDirectory()) || job.getDirectory().equals(".")) { this.inputDirectory = FileSystems.getDefault().getPath("."); } else {// w ww . jav a 2 s . c om this.inputDirectory = Paths.get(job.getDirectory()); } LOG.info("Input Path = {}", this.inputDirectory); final List<String> prefix = job.getPrefixes(); // only one prefix on put if (prefix != null) { if (prefix.size() == 1) { this.prefix = prefix.get(0); } else { // this really shouldn't happen, but . . . throw new BadArgumentException("Only one prefix allowed on put_bulk"); } } return this; }
From source file:org.wso2.carbon.identity.adaptive.auth.deployer.SiddhiAppDeployer.java
private void startWatching() { if (!Files.exists(rootPath)) { return;//from ww w. ja v a 2 s.c o m } Thread serviceWatcherThread = new Thread(() -> { WatchService watcher; try { watcher = FileSystems.getDefault().newWatchService(); rootPath.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); } catch (IOException e) { log.error("Error registering watcher for path: " + rootPath.toAbsolutePath()); return; } isFileWatcherRunning = true; while (isFileWatcherRunning) { // Wait for key to be signaled WatchKey fileWatcherKey; try { fileWatcherKey = watcher.take(); } catch (InterruptedException e) { if (log.isDebugEnabled()) { log.debug("Watching for siddhi apps deployment folder interrupted.", e); } return; } try { for (WatchEvent<?> event : fileWatcherKey.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == ENTRY_CREATE) { WatchEvent<Path> ev = (WatchEvent<Path>) event; Path appPath = getResolvedPathRelativeToRoot(ev.context()); if (appPath.getFileName().toString().endsWith(SIDDHI_FILE_SUFFIX)) { deploySiddhiApp(appPath); } } else if (kind == ENTRY_DELETE) { WatchEvent<Path> ev = (WatchEvent<Path>) event; Path appPath = getResolvedPathRelativeToRoot(ev.context()); if (appPath.getFileName().toString().endsWith(SIDDHI_FILE_SUFFIX)) { undeploySiddhiApp(appPath); } } else if (kind == ENTRY_MODIFY) { WatchEvent<Path> ev = (WatchEvent<Path>) event; Path appPath = getResolvedPathRelativeToRoot(ev.context()); if (appPath.getFileName().toString().endsWith(SIDDHI_FILE_SUFFIX)) { updateSiddhiApp(appPath); } } } //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 = fileWatcherKey.reset(); if (!valid) { break; } } catch (Exception ex) { log.error("Error while watching deployment folder for siddhiApps.", ex); } } }); serviceWatcherThread.start(); }
From source file:org.apache.logging.log4j.core.appender.rolling.RollingAppenderTempCompressedFilePatternTest.java
@Test public void testAppender() throws Exception { final File dirTmp = new File(DIR_TMP); dirTmp.mkdirs();/* ww w. j a v a2 s .co m*/ try (final WatchService watcher = FileSystems.getDefault().newWatchService()) { WatchKey key = dirTmp.toPath().register(watcher, StandardWatchEventKinds.ENTRY_CREATE); final List<String> messages = new ArrayList<>(); for (int i = 0; i < 500; ++i) { final String message = "This is test message number " + i; messages.add(message); logger.debug(message); if (i % 100 == 0) { Thread.sleep(500); } } if (!loggerContextRule.getLoggerContext().stop(30, TimeUnit.SECONDS)) { System.err.println("Could not stop cleanly " + loggerContextRule + " for " + this); } final File dir = new File(DIR); assertTrue("Directory not created", dir.exists()); final File[] files = dir.listFiles(); assertNotNull(files); int gzippedFiles = 0; for (final File file : files) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream in = null; final FileExtension ext = FileExtension.lookupForFile(file.getName()); try { try (FileInputStream fis = new FileInputStream(file)) { if (ext != null) { gzippedFiles++; try { in = new CompressorStreamFactory() .createCompressorInputStream(ext.name().toLowerCase(), fis); } catch (final CompressorException ce) { ce.printStackTrace(); fail("Error creating intput stream from " + file.toString() + ": " + ce.getMessage()); } } else { in = new FileInputStream(file); } assertNotNull("No input stream for " + file.getName(), in); try { IOUtils.copy(in, baos); } catch (final Exception ex) { ex.printStackTrace(); fail("Unable to decompress " + file.getAbsolutePath()); } } } finally { Closer.close(in); } final String text = new String(baos.toByteArray(), Charset.defaultCharset()); final String[] lines = text.split("[\\r\\n]+"); for (final String line : lines) { messages.remove(line); } } assertTrue("Log messages lost : " + messages.size(), messages.isEmpty()); assertTrue("Files not rolled : " + files.length, files.length > 2); assertTrue("Files gzipped not rolled : " + gzippedFiles, gzippedFiles > 0); int temporaryFilesCreated = 0; key = watcher.take(); for (final WatchEvent<?> event : key.pollEvents()) { final WatchEvent<Path> ev = (WatchEvent<Path>) event; final Path filename = ev.context(); if (filename.toString().endsWith(".tmp")) { temporaryFilesCreated++; } } assertTrue("No temporary file created during compression", temporaryFilesCreated > 0); assertTrue("Temporarys file created not equals to compressed files " + temporaryFilesCreated + "/" + gzippedFiles, gzippedFiles == temporaryFilesCreated); } }