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:fr.ortolang.diffusion.runtime.engine.task.ImportReferentialEntityTask.java

@Override
public void executeTask(DelegateExecution execution) throws RuntimeEngineTaskException {
    checkParameters(execution);/*  w  w w  .  j  ava2 s . co  m*/
    String referentialPathParam = execution.getVariable(REFERENTIAL_PATH_PARAM_NAME, String.class);
    report = new StringBuilder();

    File referentialPathFile = new File(referentialPathParam);
    if (referentialPathFile.exists()) {

        final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.{json}");
        final Path referentialPath = Paths.get(referentialPathParam);
        try {
            Files.walkFileTree(referentialPath, new FileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path filepath, BasicFileAttributes attrs) throws IOException {
                    Path filename = filepath.getFileName();
                    if (filename != null && matcher.matches(filename)) {

                        File jsonFile = filepath.toFile();
                        String content = StreamUtils.getContent(jsonFile);
                        if (content == null) {
                            //                           LOGGER.log(Level.SEVERE, "Referential entity content is empty for file " + jsonFile);
                            report.append(" - referential entity content is empty for file ").append(jsonFile)
                                    .append("\r\n");
                            partial = true;
                            return FileVisitResult.CONTINUE;
                        }

                        String type = extractField(content, "type");
                        if (type == null) {
                            //                           LOGGER.log(Level.SEVERE, "Referential entity type unknown for file " + jsonFile);
                            report.append(" - referential entity type unknown for file ").append(jsonFile)
                                    .append("\r\n");
                            partial = true;
                            return FileVisitResult.CONTINUE;
                        }

                        String name = jsonFile.getName().substring(0, jsonFile.getName().length() - 5);
                        try {
                            boolean exist = exists(name);

                            if (!exist) {
                                createReferentialEntity(name, type, content);
                                report.append(" + referential entity created : ").append(name).append("\r\n");
                            } else {
                                updateReferentialEntity(name, type, content);
                                report.append(" + referential entity updated : ").append(name).append("\r\n");
                            }
                        } catch (RuntimeEngineTaskException e) {
                            //                           LOGGER.log(Level.SEVERE, "  unable to import referential entity ("+type+") named "+name, e);
                            report.append(" - unable to import referential entity '").append(name)
                                    .append("' : ").append(e.getMessage()).append("\r\n");
                            partial = true;
                            return FileVisitResult.CONTINUE;
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

            });
        } catch (Exception e) {
            //            LOGGER.log(Level.SEVERE, "  unable to import referential : " + referentialPathFile, e);
            report.append("Enable to import referential ").append(referentialPathFile).append(" caused by : ")
                    .append(e.getMessage()).append("\r\n");
            partial = true;
        }

    } else {
        //         LOGGER.log(Level.SEVERE, "Referential folder doesn't exists : " + referentialPathFile);
        report.append("Referential folder doesn't exists at ").append(referentialPathFile).append("\r\n");
        partial = true;
    }

    if (partial) {
        throwRuntimeEngineEvent(RuntimeEngineEvent.createProcessLogEvent(execution.getProcessBusinessKey(),
                "Some entities has not been imported (see trace for detail)"));
    } else {
        throwRuntimeEngineEvent(RuntimeEngineEvent.createProcessLogEvent(execution.getProcessBusinessKey(),
                "All entities imported succesfully"));
    }
    throwRuntimeEngineEvent(RuntimeEngineEvent.createProcessTraceEvent(execution.getProcessBusinessKey(),
            "Report: \r\n" + report.toString(), null));
}

From source file:ch.psi.zmq.receiver.FileReceiver.java

/**
 * Receive ZMQ messages with pilatus-1.0 header type and write the data part
 * to disk/*  w  w w.j a  v a  2  s.  c om*/
 */
public void receive(Integer numImages) {

    try {
        done = false;
        counter = 0;
        counterDropped = 0;
        receive = true;
        context = ZMQ.context(1);
        socket = context.socket(ZMQ.PULL);
        socket.connect("tcp://" + hostname + ":" + port);

        ObjectMapper mapper = new ObjectMapper();
        TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
        };
        String path = "";

        // User lookup service
        UserPrincipalLookupService lookupservice = FileSystems.getDefault().getUserPrincipalLookupService();

        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        perms.add(PosixFilePermission.GROUP_READ);
        perms.add(PosixFilePermission.GROUP_WRITE);

        while (receive) {
            try {
                byte[] message = socket.recv();
                byte[] content = null;
                if (socket.hasReceiveMore()) {
                    content = socket.recv();
                }
                logger.info("Message received: " + new String(message));

                Map<String, Object> h = mapper.readValue(message, typeRef);

                if (!"pilatus-1.0".equals(h.get("htype"))) {
                    logger.warning("Message type [" + h.get("htype") + "] not supported - ignore message");
                    continue;
                }

                String username = (String) h.get("username");

                // Save content to file (in basedir)
                String p = (String) h.get("path");
                if (!p.startsWith("/")) {
                    p = basedir + "/" + p;
                }
                File f = new File(p);
                // if(!f.exists()){
                if (!path.equals(p)) {
                    if (username == null) {
                        logger.info("Create directory " + p + "");
                        f.mkdirs();
                    } else {
                        logger.info("Create directory " + p + " for user " + username);
                        try {
                            Set<PosixFilePermission> permissions = new HashSet<PosixFilePermission>();
                            permissions.add(PosixFilePermission.OWNER_READ);
                            permissions.add(PosixFilePermission.OWNER_WRITE);
                            permissions.add(PosixFilePermission.OWNER_EXECUTE);
                            permissions.add(PosixFilePermission.GROUP_READ);
                            permissions.add(PosixFilePermission.GROUP_WRITE);
                            permissions.add(PosixFilePermission.GROUP_EXECUTE);
                            // username and groupname is the same by
                            // convention
                            mkdir(f, lookupservice.lookupPrincipalByName(username),
                                    lookupservice.lookupPrincipalByGroupName(username), permissions);
                        } catch (IOException e) {
                            throw new RuntimeException("Unable to create directory for user " + username + "",
                                    e);
                        }
                    }
                    path = p;
                }

                File file = new File(f, (String) h.get("filename"));
                logger.finest("Write to " + file.getAbsolutePath());

                try (FileOutputStream s = new FileOutputStream(file)) {
                    s.write(content);
                }

                if (username != null) {
                    Files.setOwner(file.toPath(), lookupservice.lookupPrincipalByName(username));
                    // username and groupname is the same by convention
                    Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class,
                            LinkOption.NOFOLLOW_LINKS)
                            .setGroup(lookupservice.lookupPrincipalByGroupName(username));
                    Files.setPosixFilePermissions(file.toPath(), perms);
                }

                counter++;
                if (numImages != null && numImages == counter) {
                    break;
                }
            } catch (IOException e) {
                logger.log(Level.SEVERE, "", e);
                counterDropped++;
            }
        }

    } catch (Exception e) {
        if (receive) {
            e.printStackTrace();
        }
    }
}

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

private void registerWatcherForFolder(IWatchEventHandler handler, String folder) {
    Path itemsDir = FileSystems.getDefault().getPath(folder);
    try {//from w  w  w .j  ava 2  s  . com
        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:com.basistech.yca.FlatteningConfigFileManager.java

@Activate
public void activate(ComponentContext context) {
    String pathname = (String) context.getProperties().get("configurationDirectory");
    if (pathname == null) {
        throw new RuntimeException(
                "There is no configurationDirectory parameter in com.basistech.yca.FlatteningConfigFileManager.cfg");
    }//  w ww  .j  av  a 2  s .c  om

    configurationDirectory = Paths.get(pathname);
    try {
        watchService = FileSystems.getDefault().newWatchService();
    } catch (IOException e) {
        LOG.error("Failed to create watch service", e);
        throw new RuntimeException("Failed to create watch service");
    }
    try {
        watchKey = configurationDirectory.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    } catch (IOException e) {
        LOG.error("Failed to create watch key for " + configurationDirectory.toAbsolutePath(), e);
        throw new RuntimeException("Failed to create watch key");
    }

    watcherThread = new WatcherThread();
    watcherThread.start();
}

From source file:org.talend.dataprep.dataset.store.content.file.LocalFileContentStore.java

@Override
public void clear() {
    try {/*w w  w .  j  ava2s.c o  m*/
        Path path = FileSystems.getDefault().getPath(storeLocation);
        if (!path.toFile().exists()) {
            return;
        }

        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                // .nfs files are handled by the OS and can be deleted after the visitor started.
                // Exceptions on such files can be safely ignored
                if (file.getFileName().toFile().getName().startsWith(".nfs")) { //$NON-NLS-1$
                    LOGGER.warn("unable to delete {}", file.getFileName(), exc);
                    return FileVisitResult.CONTINUE;
                }
                throw exc;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
                // Skip NFS file content
                if (!file.getFileName().toFile().getName().startsWith(".nfs")) { //$NON-NLS-1$
                    Files.delete(file);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
                if (e == null) {
                    return FileVisitResult.CONTINUE;
                } else {
                    // directory iteration failed
                    throw e;
                }
            }
        });
    } catch (IOException e) {
        LOGGER.error("Unable to clear local data set content.", e);
        throw new TDPException(DataSetErrorCodes.UNABLE_TO_CLEAR_DATASETS, e);
    }
}

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

public String getTaskDescription(final Task task) throws IOException {
    final Path compiled = FileSystems.getDefault().getPath(this.storagePath, "tasks", "descriptions",
            task.getDescriptionFile(), "compiled");

    if (!FileAccess.exists(compiled)) {
        return null;
    }//from www. ja  v  a2 s  .c  o m

    return new String(FileAccess.readAllBytes(compiled), Charset.forName("UTF8"));
}

From source file:org.springframework.integration.file.WatchServiceDirectoryScanner.java

@Override
public synchronized void start() {
    if (!this.running) {
        try {/*from ww w. j  av a 2 s .co m*/
            this.watcher = FileSystems.getDefault().newWatchService();
        } catch (IOException e) {
            logger.error("Failed to create watcher for " + this.directory.toString(), e);
        }
        final Set<File> initialFiles = walkDirectory(this.directory);
        initialFiles.addAll(filesFromEvents());
        this.initialFiles = initialFiles;
        this.running = true;
    }
}

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

public ServiceTags getServiceTagsIfUpdated(long lastKnownVersion, long lastActivationTimeInMillis)
        throws Exception {
    String basedir = System.getProperty("basedir");
    if (basedir == null) {
        basedir = new File(".").getCanonicalPath();
    }/*from  w w w.ja  v  a  2s  .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 + tagFilename);

    byte[] cacheBytes = Files.readAllBytes(cachePath);

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

From source file:com.liferay.sync.engine.service.persistence.SyncFilePersistence.java

public SyncFile fetchByPF_S_First(String parentFilePathName, int state) throws SQLException {

    QueryBuilder<SyncFile, Long> queryBuilder = queryBuilder();

    queryBuilder.limit(1L);//from  ww  w  .  j  ava  2 s.  com

    Where<SyncFile, Long> where = queryBuilder.where();

    FileSystem fileSystem = FileSystems.getDefault();

    parentFilePathName = StringUtils.replace(parentFilePathName + fileSystem.getSeparator(), "\\", "\\\\");

    where.like("filePathName", new SelectArg(parentFilePathName + "%"));

    where.eq("state", state);
    where.ne("uiEvent", SyncFile.UI_EVENT_DELETED_LOCAL);
    where.ne("uiEvent", SyncFile.UI_EVENT_DELETED_REMOTE);
    where.ne("uiEvent", SyncFile.UI_EVENT_TRASHED_LOCAL);
    where.ne("uiEvent", SyncFile.UI_EVENT_TRASHED_REMOTE);

    where.and(6);

    return where.queryForFirst();
}

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

/**
 * Checks if {@code resource} is a directory.
 * @param resource the resource to check.
 * @return true if {@code resource} is a directory; else, otherwise.
 *///  w  w w . ja va  2 s  .co  m
public static boolean isDirectory(String resource) {
    final Path path = FileSystems.getDefault().getPath(resource).toAbsolutePath();
    return Files.isDirectory(path);
}