Example usage for java.nio.file FileSystems getDefault

List of usage examples for java.nio.file FileSystems getDefault

Introduction

In this page you can find the example usage for java.nio.file FileSystems getDefault.

Prototype

public static FileSystem getDefault() 

Source Link

Document

Returns the default FileSystem .

Usage

From source file:org.jmingo.query.watch.QuerySetWatchService.java

/**
 * Constructor to set event bus./*from   w w w.  j  av a  2s .  c o m*/
 *
 * @param eventBus the event bus
 */
public QuerySetWatchService(EventBus eventBus) {
    try {
        this.eventBus = eventBus;
        LOGGER.debug("create new watch service");
        watchService = FileSystems.getDefault().newWatchService();
        watchEventHandler = new EventBusWatchEventHandler(eventBus, registered);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:cz.muni.fi.pb138.cvmanager.service.PDFgenerator.java

/**
 * By external calling pdflatex function of laTex generates pdf curriculum vitae document from .tex file
 * @param username name of user whose is the CV
 * @return language to export (sk/en)/*from  www  .ja va 2 s .  c o m*/
 * @throws IOException
 * @throws InterruptedException
 * @throws NullPointerException
 */
public InputStream latexToPdf(String username) throws IOException, InterruptedException, NullPointerException {
    ProcessBuilder pb = new ProcessBuilder("pdflatex", username + "_cv.tex", "--output-directory=");
    File file = new File("cvxml/");
    pb.directory(file);
    Process p = pb.start();

    WatchService watcher = FileSystems.getDefault().newWatchService();
    Path dir = Paths.get("cvxml/");
    dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);

    while (true) {
        // wait for a key to be available for 10 seconds
        WatchKey key = watcher.poll(10000L, TimeUnit.MILLISECONDS);
        if (key == null) {
            break;
        }

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

            // get file name
            @SuppressWarnings("unchecked")
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path fileName = ev.context();

            System.out.println(kind.name() + ": " + fileName);
        }

        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }

    System.out.println("end of cycle");

    File pdf = new File("cvxml/" + username + "_cv.pdf");

    return new FileInputStream(pdf);
}

From source file:org.ow2.proactive.scheduler.task.ProgressFileReader.java

boolean start(File workingDir, String filename) {
    try {//from  w ww. j a  v a 2s.c  o  m
        createProgressFile(workingDir, filename);

        watchService = FileSystems.getDefault().newWatchService();

        watchServiceThread = new Thread(new ProgressFileReaderThread(filename));
        watchServiceThread.setName(ProgressFileReaderThread.class.getName());
        watchServiceThread.start();

        progress = 0;

        progressFileDir.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);

        return true;
    } catch (IOException e) {
        logger.warn("Error while creating progress file. Progress will not be reported.", e);
        return false;
    }
}

From source file:org.balloon_project.overflight.task.importer.ImporterFileListener.java

@Override
public void run() {
    // TODO initial import start
    // initial import of existing file
    logger.info("Scanning for files to import");
    File importDir = new File(configuration.getDatabaseImportDirectory());
    if (importDir.exists() && importDir.isDirectory()) {
        for (File file : importDir.listFiles()) {
            if (file.isFile() && file.getPath().endsWith(IndexingTask.N_TRIPLES_EXTENSION)) {
                logger.info("File event: Adding " + file.toString() + " to importer queue");
                importer.startImporting(file);
            }//from  w  ww . j av  a  2s  . c  om
        }
    }

    // starting file watch service for future files
    try {
        String path = configuration.getDatabaseImportDirectory();
        logger.info("Starting import file listener for path " + path);
        Path tmpPath = Paths.get(path);
        WatchService watchService = FileSystems.getDefault().newWatchService();
        tmpPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);

        for (;;) {
            WatchKey key = watchService.take();

            for (WatchEvent event : key.pollEvents()) {
                if (event.kind().name() == "OVERFLOW") {
                    continue;
                } else {
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path filename = ev.context();
                    logger.info("File event: Adding " + filename.toString() + " to importer queue");
                    importer.startImporting(tmpPath.resolve(filename).toFile());
                }
            }

            // 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) {
                break;
            }

        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } finally {
        logger.debug("Stopping import file listener");
    }
}

From source file:org.apache.coheigea.bigdata.knox.ranger.KnoxRangerTest.java

public static void setupLdap() throws Exception {
    String basedir = System.getProperty("basedir");
    if (basedir == null) {
        basedir = new File(".").getCanonicalPath();
    }/*from www . j a v  a 2 s .co m*/
    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
    ldapTransport = new TcpTransport(0);
    ldap = new SimpleLdapDirectoryServer("dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport);
    ldap.start();
}

From source file:de.ingrid.interfaces.csw.tools.FileUtils.java

/**
 * Delete a file or directory specified by a {@link Path}. This method uses
 * the new {@link Files} API and allows to specify a regular expression to
 * remove only files that match that expression.
 * /*  w ww  .  j a va2  s.  c  o m*/
 * @param path
 * @param pattern
 * @throws IOException
 */
public static void deleteRecursive(Path path, final String pattern) throws IOException {

    final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:" + pattern);

    if (!Files.exists(path))
        return;

    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (pattern != null && matcher.matches(file.getFileName())) {
                Files.delete(file);
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            // try to delete the file anyway, even if its attributes
            // could not be read, since delete-only access is
            // theoretically possible
            if (pattern != null && matcher.matches(file.getFileName())) {
                Files.delete(file);
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            if (exc == null) {
                if (matcher.matches(dir.getFileName())) {
                    if (dir.toFile().list().length > 0) {
                        // remove even if not empty
                        FileUtils.deleteRecursive(dir);
                    } else {
                        Files.delete(dir);
                    }
                }
                return FileVisitResult.CONTINUE;
            } else {
                // directory iteration failed; propagate exception
                throw exc;
            }
        }

    });
}

From source file:org.apache.ranger.services.knox.KnoxRangerTest.java

private static void setupLdap() throws Exception {
    String basedir = System.getProperty("basedir");
    if (basedir == null) {
        basedir = new File(".").getCanonicalPath();
    }//  www  . ja v a 2 s . c om
    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
    ldapTransport = new TcpTransport(0);
    ldap = new SimpleLdapDirectoryServer("dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport);
    ldap.start();
}

From source file:org.ng200.openolympus.services.StorageService.java

@PreAuthorize(SecurityExpressionConstants.IS_ADMIN)
public Path createTaskDescriptionFileStorage(Task task) throws IOException {
    final UUID uuid = UUID.randomUUID();
    final String idString = System.currentTimeMillis() + "_" + uuid.toString();
    final Path file = FileSystems.getDefault().getPath(this.storagePath, "tasks", "descriptions", idString);
    FileAccess.createDirectories(file);/*from ww  w  .j a va  2 s. com*/
    FileAccess.createFile(file.resolve("source"));
    task.setDescriptionFile(idString);
    return file;
}

From source file:org.pgptool.gui.tools.fileswatcher.MultipleFilesWatcher.java

private void startWatcher() {
    try {/*  ww w.  j av  a 2  s  .co  m*/
        watcher = FileSystems.getDefault().newWatchService();
        workerThread = buildThreadAndStart();
        dirsExistanceWatcherTask = new RecurringBackgroundTask(dirsExistanceWatcher, 2000);
    } catch (Throwable t) {
        throw new RuntimeException("failed to install watcher", t);
    }
}

From source file:org.apache.ranger.services.hdfs.RangerAdminClientImpl.java

public ServicePolicies getServicePoliciesIfUpdated(long lastKnownVersion, long lastActivationTimeInMillis)
        throws Exception {

    String basedir = System.getProperty("basedir");
    if (basedir == null) {
        basedir = new File(".").getCanonicalPath();
    }//from ww w .  java  2  s .c om
    String hdfsVersion = RangerConfiguration.getInstance().get("hdfs.version", "");

    final String relativePath;
    if (StringUtils.isNotBlank(hdfsVersion)) {
        relativePath = "/src/test/resources/" + hdfsVersion + "/";
    } else {
        relativePath = "/src/test/resources/";
    }

    java.nio.file.Path cachePath = FileSystems.getDefault().getPath(basedir, relativePath + cacheFilename);
    byte[] cacheBytes = Files.readAllBytes(cachePath);

    return gson.fromJson(new String(cacheBytes), ServicePolicies.class);
}