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:com.hygenics.parser.ExistanceChecker.java

public ArrayList<Boolean> checkFilesExist(List<String> fileMatchers, List<String> directories, boolean exists) {
    ArrayList<PathMatcher> matchers = new ArrayList<PathMatcher>();
    for (String glob : fileMatchers) {
        PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + glob);
        matchers.add(matcher);//from ww w .j a va2s . co  m
    }

    ArrayList<Boolean> matches = new ArrayList<Boolean>();
    for (String dir : directories) {

        File dirFile = new File(dir);
        if (dirFile.exists()) {
            File[] files = dirFile.listFiles();
            for (int i = 0; i < files.length; i++) {
                for (PathMatcher matcher : matchers) {
                    matches.add(matcher.matches(files[i].toPath()) == exists);
                }
            }
        } else {
            log.warn("Continuing. Does Not Exist: %s".format(dir));
        }
    }
    return matches;
}

From source file:com.acmutv.ontoqa.tool.io.IOManager.java

/**
 * Appends string on a resource./*w w  w  .j  av  a 2 s  . c  o m*/
 * @param resource the resource to write on.
 * @param string the string to write.
 * @throws IOException when resource cannot be written.
 */
public static void appendResource(String resource, String string) throws IOException {
    Path path = FileSystems.getDefault().getPath(resource).toAbsolutePath();
    Files.write(path, string.getBytes(), StandardOpenOption.APPEND);
}

From source file:com.twosigma.beaker.javash.utils.JavaEvaluator.java

public JavaEvaluator(String id, String sId) {
    shellId = id;//from   www. jav  a 2  s  .com
    sessionId = sId;
    packageId = "com.twosigma.beaker.javash.bkr" + shellId.split("-")[0];
    cps = new ClasspathScanner();
    jac = createJavaAutocomplete(cps);
    classPath = new ArrayList<String>();
    imports = new ArrayList<String>();
    exit = false;
    updateLoader = false;
    currentClassPath = "";
    currentImports = "";
    outDir = FileSystems.getDefault().getPath(System.getenv("beaker_tmp_dir"), "dynclasses", sessionId)
            .toString();
    try {
        (new File(outDir)).mkdirs();
    } catch (Exception e) {
    }
    executor = new BeakerCellExecutor("javash");
    startWorker();
}

From source file:org.kitodo.serviceloader.KitodoServiceLoader.java

/**
 * Loads bean classes and registers them to the FacesContext. Afterwards
 * they can be used in all frontend files
 *///from  w w w.  jav  a 2 s . c om
private void loadBeans() {
    Path moduleFolder = FileSystems.getDefault().getPath(modulePath);
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(moduleFolder, JAR)) {

        for (Path f : stream) {
            try (JarFile jarFile = new JarFile(f.toString())) {

                if (hasFrontendFiles(jarFile)) {

                    Enumeration<JarEntry> e = jarFile.entries();

                    URL[] urls = { new URL("jar:file:" + f.toString() + "!/") };
                    try (URLClassLoader cl = URLClassLoader.newInstance(urls)) {
                        while (e.hasMoreElements()) {
                            JarEntry je = e.nextElement();

                            /*
                             * IMPORTANT: Naming convention: the name of the
                             * java class has to be in upper camel case or
                             * "pascal case" and must be equal to the file
                             * name of the corresponding facelet file
                             * concatenated with the word "Form".
                             *
                             * Example: template filename "sample.xhtml" =>
                             * "SampleForm.java"
                             *
                             * That is the reason for the following check
                             * (e.g. whether the JarEntry name ends with
                             * "Form.class")
                             */
                            if (je.isDirectory() || !je.getName().endsWith("Form.class")) {
                                continue;
                            }

                            String className = je.getName().substring(0, je.getName().length() - 6);
                            className = className.replace('/', '.');
                            Class c = cl.loadClass(className);

                            String beanName = className.substring(className.lastIndexOf('.') + 1).trim();

                            FacesContext facesContext = FacesContext.getCurrentInstance();
                            HttpSession session = (HttpSession) facesContext.getExternalContext()
                                    .getSession(false);

                            session.getServletContext().setAttribute(beanName, c.newInstance());
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error(ERROR, e.getMessage());
    }
}

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

public Path getSolutionFile(final Solution solution) {
    return FileSystems.getDefault().getPath(this.storagePath, "solutions", solution.getFile());
}

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

/**
 * Starts synchronization of the given base path with the registry.
 * <p/>/*w  w w.j av a 2 s  .c o  m*/
 * This method will block till call method {@link CaraCloud#stop() }
 *
 * @throws IOException Thrown when an I/O error occurs
 * @throws InterruptedException Thrown when method stop was called or application will terminate
 * @throws GeneralSecurityException
 */
public void start() throws IOException, InterruptedException, GeneralSecurityException {
    if (client == null) {
        throw new IllegalStateException("Attribute \"client\" must be set.");
    }

    if (basePath == null) {
        throw new IllegalStateException("Attribute \"basePath\" must be set.");
    }

    if (!Files.exists(basePath)) {
        throw new IllegalStateException("Path \"" + basePath + "\" must exists.");
    }

    if (!Files.isDirectory(basePath)) {
        throw new IllegalStateException("Path \"" + basePath + "\" must be a directory/folder.");
    }

    watcher = FileSystems.getDefault().newWatchService();
    registerDefaultWatch(basePath);

    while (!Thread.interrupted()) {
        WatchKey key = watcher.take();
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                Path path = basePath.resolve(event.context().toString());
                createFile(path);
            } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {

            } else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                Path path = basePath.resolve(event.context().toString());
                deleteFile(path);
            } else {
                LOG.error("Unsupported kind: " + event.kind() + ", path: " + event.context());
            }
        }

        key.reset();
    }
}

From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java

/**
 * ???????????ContentsPersister?????./*from  w  ww.ja v  a 2s.  c  om*/
 * 
 * @throws IOException
 */
@PostConstruct
public void init() throws IOException {

    // ????
    List<Path> filePathList = new ArrayList<Path>();

    try {
        // ??
        defaultPath = appConf.getProperty(KEY_DEFULT_PATH);
        FileSystem fs = FileSystems.getDefault();
        defaultDir = fs.getPath(defaultPath);
        filePathList.add(defaultDir);

        // default???
        String[] urls = appConf.getProperty(KEY_CUSTOM_URLS).split(",");
        for (int i = 0, l = urls.length; i < l; i++) {
            Path p = fs.getPath(appConf.getProperty(urls[i] + ".dir"));
            filePathList.add(p);
            customUrlPathMap.put(urls[i], p);
        }
    } catch (Exception e) {
        logger.error(
                "????????????????????????");
        e.printStackTrace();
    }

    // ????
    for (Path p : filePathList) {
        if (!Files.exists(p)) {
            Files.createDirectories(p);
        }
        if (!Files.isDirectory(p)) {
            // ???????????????????
            throw new IllegalArgumentException(
                    "???????????????????"
                            + p);
        }
    }
}

From source file:de.jwi.jfm.FileWrapper.java

public String getAttributes() throws IOException {
    FileSystem fileSystem = FileSystems.getDefault();
    Set<String> fileSystemViews = fileSystem.supportedFileAttributeViews();

    File file = getFile();//from   w  w w .  ja  va 2 s  .c  om
    Path p = file.toPath();

    try {
        if (fileSystemViews.contains("posix")) {
            Set<PosixFilePermission> posixFilePermissions = Files.getPosixFilePermissions(p,
                    LinkOption.NOFOLLOW_LINKS);

            PosixFileAttributes attrs = Files.getFileAttributeView(p, PosixFileAttributeView.class)
                    .readAttributes();

            String owner = attrs.owner().toString();
            String group = attrs.group().toString();

            String permissions = PosixFilePermissions.toString(attrs.permissions());

            String res = String.format("%s %s %s", permissions, owner, group);
            return res;
        } else if (fileSystemViews.contains("dos")) {
            StringWriter sw = new StringWriter();
            DosFileAttributeView attributeView = Files.getFileAttributeView(p, DosFileAttributeView.class);
            DosFileAttributes dosFileAttributes = null;

            dosFileAttributes = attributeView.readAttributes();
            if (dosFileAttributes.isArchive()) {
                sw.append('A');
            }
            if (dosFileAttributes.isHidden()) {
                sw.append('H');
            }
            if (dosFileAttributes.isReadOnly()) {
                sw.append('R');
            }
            if (dosFileAttributes.isSystem()) {
                sw.append('S');
            }

            return sw.toString();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "";
}

From source file:com.spectralogic.ds3cli.command.RecoverGetBulk.java

public CliCommand init(final RecoveryJob job) throws Exception {
    this.bucketName = job.getBucketName();
    this.numberOfThreads = job.getNumberOfThreads();
    this.jobId = job.getId();
    this.directory = job.getDirectory();
    if (Guard.isStringNullOrEmpty(this.directory) || directory.equals(".")) {
        this.outputPath = FileSystems.getDefault().getPath(".");
    } else {/*from   w  w  w  . ja  v  a2  s .  co  m*/
        final Path dirPath = FileSystems.getDefault().getPath(directory);
        this.outputPath = FileSystems.getDefault().getPath(".").resolve(dirPath);
    }
    LOG.info("Output Path = {}", this.outputPath);

    final List<String> prefix = job.getPrefixes();
    if (prefix != null && prefix.size() > 0) {
        this.prefixes = ImmutableList.copyOf(prefix);
    }
    return this;
}

From source file:es.molabs.io.utils.test.FileWatcherRunnableTest.java

@Test
public void testEntryDelete() throws Throwable {
    URL file = getClass().getResource("/es/molabs/io/utils/test/filewatcher/");

    // Creates the file if it does not exist
    File newFile = new File(file.getFile() + File.separator + "test-delete.txt");
    if (!newFile.exists())
        newFile.createNewFile();//from   w  ww  .  j  av  a2s .  com

    WatchService watchService = FileSystems.getDefault().newWatchService();
    FileWatcherHandler handler = Mockito.mock(FileWatcherHandler.class);
    FileWatcherRunnable fileWatcherRunnable = new FileWatcherRunnable(watchService, handler);
    fileWatcherRunnable.addFile(file);
    executor.submit(fileWatcherRunnable);

    // Delete the file
    newFile.delete();

    // Waits the refresh time
    Thread.sleep(fileWatcherRunnable.getRefreshTime() + REFRESH_MARGIN);

    // Checks that the event handler has been called one time      
    Mockito.verify(handler, Mockito.times(1)).entryDelete(Mockito.any());

    // Stops the service
    watchService.close();
}