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:ch.cyberduck.cli.GlobTransferItemFinder.java

@Override
public Set<TransferItem> find(final CommandLine input, final TerminalAction action, final Path remote)
        throws AccessDeniedException {
    if (input.getOptionValues(action.name()).length == 2) {
        final String path = input.getOptionValues(action.name())[1];
        // This only applies to a shell where the glob is not already expanded into multiple arguments
        if (StringUtils.containsAny(path, '*', '?')) {
            final Local directory = LocalFactory.get(FilenameUtils.getFullPath(path));
            if (directory.isDirectory()) {
                final PathMatcher matcher = FileSystems.getDefault()
                        .getPathMatcher(String.format("glob:%s", FilenameUtils.getName(path)));
                final Set<TransferItem> items = new HashSet<TransferItem>();
                for (Local file : directory.list(new NullFilter<String>() {
                    @Override/*from  ww w . java 2  s.c  o  m*/
                    public boolean accept(final String file) {
                        try {
                            return matcher.matches(Paths.get(file));
                        } catch (InvalidPathException e) {
                            log.warn(String.format("Failure obtaining path for file %s", file));
                        }
                        return false;
                    }
                })) {
                    items.add(new TransferItem(new Path(remote, file.getName(), EnumSet.of(Path.Type.file)),
                            file));
                }
                return items;
            }
        }
    }
    return new SingleTransferItemFinder().find(input, action, remote);
}

From source file:us.colloquy.sandbox.FileProcessor.java

@Test
public void listAllUzipedFiles() {
    ///Documents/Tolstoy/diaries
    //System.getProperty("user.home") + "/Documents/Tolstoy/unzipLetters"

    Path pathToLetters = FileSystems.getDefault()
            .getPath(System.getProperty("user.home") + "/Documents/Tolstoy/openDiaries");

    List<Path> results = new ArrayList<>();

    int maxDepth = 6;

    try (Stream<Path> stream = Files.find(pathToLetters, maxDepth, (path, attr) -> {
        return String.valueOf(path).endsWith(".ncx");
    })) {/*from   w w w  .ja va2s  . c om*/

        stream.forEach(results::add);

        //            String joined = stream
        //                    .sorted()
        //                    .map(String::valueOf)
        //                    .collect(Collectors.joining("; "));
        //
        //            System.out.println("\nFound: " + joined);

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("files: " + results.size());

    Set<String> uriList = new TreeSet<>();

    try {

        for (Path res : results) {
            Path parent = res.getParent();

            System.out.println("---------------------------------------------");
            System.out.println(parent.toString());
            //use jsoup to list all files that contain something useful
            Document doc = Jsoup.parse(res.toFile(), "UTF-8");

            for (Element element : doc.getElementsByTag("docTitle")) {
                //Letter letter = new Letter();

                // StringBuilder content = new StringBuilder();

                for (Element child : element.children()) {

                    System.out.println("Title: " + child.text());
                }
            }

            for (Element element : doc.getElementsByTag("navPoint")) {
                //Letter letter = new Letter();

                // StringBuilder content = new StringBuilder();

                for (Element child : element.children()) {
                    String label = child.text();

                    if (StringUtils.isNotEmpty(label)) {
                        if (label.matches("?")) {
                            System.out.println("------------------");
                        }

                        String url = child.getElementsByTag("content").attr("src");

                        if (label.matches(".*\\d{1,3}.*[?--?]+.*") && StringUtils.isNotEmpty(url)) {

                            uriList.add(parent.toString() + File.separator + url.replaceAll("#.*", ""));
                            //                                System.out.println("nav point: " + label + " src " + parent.toString()
                            //                                        + System.lineSeparator() + url.replaceAll("#.*",""));

                        } else {
                            // System.out.println("nav point: " + label + " src " + child.getElementsByTag("content").attr("src"));
                        }

                    }
                }
            }

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

    System.out.println("Size: " + uriList.size());

    for (String uri : uriList) {
        //parse and
        System.out.println(uri);
    }

}

From source file:org.wso2.msf4j.ballerina.Application.java

private static void unzip(String zipFilePath, String destDir) throws IOException {
    BufferedInputStream bis = null;
    FileOutputStream fileOutput = null;
    try (ZipFile file = new ZipFile(zipFilePath)) {
        FileSystem fileSystem = FileSystems.getDefault();
        Enumeration<? extends ZipEntry> entries = file.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                Files.createDirectories(fileSystem.getPath(destDir, entry.getName()));
            } else {
                InputStream is = file.getInputStream(entry);
                bis = new BufferedInputStream(is);
                Path uncompressedFilePath = fileSystem.getPath(destDir, entry.getName());
                Files.createFile(uncompressedFilePath);
                fileOutput = new FileOutputStream(uncompressedFilePath.toString());
                while (bis.available() > 0) {
                    fileOutput.write(bis.read());
                }/*from w  w w.ja va 2 s.  co m*/
                fileOutput.close();
            }
        }
    } finally {
        if (bis != null) {
            IOUtils.closeQuietly(bis);
        }
        if (fileOutput != null) {
            IOUtils.closeQuietly(fileOutput);
        }
    }
}

From source file:ru.xxlabaza.popa.template.TemplaterFacade.java

@SneakyThrows
public String build(String templateName, Map<String, Object> bindings) {
    log.info("Template: '{}', bindings: {}", templateName, bindingsToString(bindings));
    val pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + templateName + extensionsPattern);
    val templatePath = Files.list(templatesFolder).filter(it -> pathMatcher.matches(it.getFileName()))
            .findFirst()/* ww w.j  a  v  a  2s  .  c om*/
            .orElseThrow(
                    () -> new FileNotFoundException(String.format("Template '%s' not found", templateName)))
            .toAbsolutePath();
    val templater = templaters.get(FileSystemUtils.getExstension(templatePath));
    return templater.build(templatesFolder.relativize(templatePath), bindings);
}

From source file:org.apache.hadoop.hbase.client.TestUpdateConfiguration.java

@Test
public void testMasterOnlineConfigChange() throws IOException {
    LOG.debug("Starting the test");
    Path cnfPath = FileSystems.getDefault().getPath("target/test-classes/hbase-site.xml");
    Path cnf2Path = FileSystems.getDefault().getPath("target/test-classes/hbase-site2.xml");
    Path cnf3Path = FileSystems.getDefault().getPath("target/test-classes/hbase-site3.xml");
    // make a backup of hbase-site.xml
    Files.copy(cnfPath, cnf3Path, StandardCopyOption.REPLACE_EXISTING);
    // update hbase-site.xml by overwriting it
    Files.copy(cnf2Path, cnfPath, StandardCopyOption.REPLACE_EXISTING);

    Admin admin = TEST_UTIL.getHBaseAdmin();
    ServerName server = TEST_UTIL.getHBaseCluster().getMaster().getServerName();
    admin.updateConfiguration(server);/*from  w  ww .  j  a  va 2  s  .com*/
    Configuration conf = TEST_UTIL.getMiniHBaseCluster().getMaster().getConfiguration();
    int custom = conf.getInt("hbase.custom.config", 0);
    assertEquals(custom, 1000);
    // restore hbase-site.xml
    Files.copy(cnf3Path, cnfPath, StandardCopyOption.REPLACE_EXISTING);
}

From source file:org.wso2.carbon.uuf.renderablecreator.html.internal.io.HtmlRenderableUpdater.java

public HtmlRenderableUpdater() {
    this.watchingDirectories = new HashSet<>();
    this.watchingRenderables = new ConcurrentHashMap<>();
    try {//  w  w  w . jav  a 2 s.  c  om
        this.watchService = FileSystems.getDefault().newWatchService();
    } catch (IOException e) {
        throw new FileOperationException("Cannot create file watch service.", e);
    }
    this.watchServiceThread = new Thread(this::run, HtmlRenderableUpdater.class.getName() + "-WatchService");
    this.isWatchServiceStopped = false;
}

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

/**
 * Checks if a resource is writable./*from  w  w w. j ava  2s . c  o  m*/
 * @param resource the resource to check.
 * @return true if the resource is writable; false, otherwise.
 */
public static boolean isWritableResource(String resource) {
    final Path path = FileSystems.getDefault().getPath(resource).toAbsolutePath();
    return Files.isWritable(path);
}

From source file:fi.hsl.parkandride.ExportQTypes.java

@Bean
public CommandLineRunner runner() {
    return args -> {
        MetaDataExporter exporter = new MetaDataExporter();
        exporter.setPackageName(PACKAGE_NAME);
        exporter.setInnerClassesForKeys(false);
        exporter.setSpatial(true);// w ww.j a  v  a  2s.com
        exporter.setNamePrefix(NAME_PREFIX);
        exporter.setNamingStrategy(new DefaultNamingStrategy());
        exporter.setTargetFolder(new File(TARGET_FOLDER));
        exporter.setConfiguration(configuration);
        Path packageDir = FileSystems.getDefault().getPath(TARGET_FOLDER, PACKAGE_NAME.replace(".", "/"));
        try (Connection conn = dataSource.getConnection()) {
            deleteOldQTypes(packageDir);
            exporter.export(conn.getMetaData());
            deleteUnusedQTypes(packageDir, "QGeometryColumns.java", "QSchemaVersion.java",
                    "QSpatialRefSys.java");
        }
        System.out.println("Export done");
    };
}

From source file:org.savantbuild.io.tar.TarTools.java

/**
 * Untars a TAR file. This also handles tar.gz files by checking the file extension. If the file extension ends in .gz
 * it will read the tarball through a GZIPInputStream.
 *
 * @param file     The TAR file./*  ww  w  .j  a v  a2s  . c om*/
 * @param to       The directory to untar to.
 * @param useGroup Determines if the group name in the archive is used.
 * @param useOwner Determines if the owner name in the archive is used.
 * @throws IOException If the untar fails.
 */
public static void untar(Path file, Path to, boolean useGroup, boolean useOwner) throws IOException {
    if (Files.notExists(to)) {
        Files.createDirectories(to);
    }

    InputStream is = Files.newInputStream(file);
    if (file.toString().endsWith(".gz")) {
        is = new GZIPInputStream(is);
    }

    try (TarArchiveInputStream tis = new TarArchiveInputStream(is)) {
        TarArchiveEntry entry;
        while ((entry = tis.getNextTarEntry()) != null) {
            Path entryPath = to.resolve(entry.getName());
            if (entry.isDirectory()) {
                // Skip directory entries that don't add any value
                if (entry.getMode() == 0 && entry.getGroupName() == null && entry.getUserName() == null) {
                    continue;
                }

                if (Files.notExists(entryPath)) {
                    Files.createDirectories(entryPath);
                }

                if (entry.getMode() != 0) {
                    Set<PosixFilePermission> permissions = FileTools.toPosixPermissions(entry.getMode());
                    Files.setPosixFilePermissions(entryPath, permissions);
                }

                if (useGroup && entry.getGroupName() != null && !entry.getGroupName().trim().isEmpty()) {
                    GroupPrincipal group = FileSystems.getDefault().getUserPrincipalLookupService()
                            .lookupPrincipalByGroupName(entry.getGroupName());
                    Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setGroup(group);
                }

                if (useOwner && entry.getUserName() != null && !entry.getUserName().trim().isEmpty()) {
                    UserPrincipal user = FileSystems.getDefault().getUserPrincipalLookupService()
                            .lookupPrincipalByName(entry.getUserName());
                    Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setOwner(user);
                }
            } else {
                if (Files.notExists(entryPath.getParent())) {
                    Files.createDirectories(entryPath.getParent());
                }

                if (Files.isRegularFile(entryPath)) {
                    if (Files.size(entryPath) == entry.getSize()) {
                        continue;
                    } else {
                        Files.delete(entryPath);
                    }
                }

                Files.createFile(entryPath);

                try (OutputStream os = Files.newOutputStream(entryPath)) {
                    byte[] ba = new byte[1024];
                    int read;
                    while ((read = tis.read(ba)) != -1) {
                        if (read > 0) {
                            os.write(ba, 0, read);
                        }
                    }
                }

                if (entry.getMode() != 0) {
                    Set<PosixFilePermission> permissions = FileTools.toPosixPermissions(entry.getMode());
                    Files.setPosixFilePermissions(entryPath, permissions);
                }

                if (useGroup && entry.getGroupName() != null && !entry.getGroupName().trim().isEmpty()) {
                    GroupPrincipal group = FileSystems.getDefault().getUserPrincipalLookupService()
                            .lookupPrincipalByGroupName(entry.getGroupName());
                    Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setGroup(group);
                }

                if (useOwner && entry.getUserName() != null && !entry.getUserName().trim().isEmpty()) {
                    UserPrincipal user = FileSystems.getDefault().getUserPrincipalLookupService()
                            .lookupPrincipalByName(entry.getUserName());
                    Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setOwner(user);
                }
            }
        }
    }
}

From source file:org.apache.bookkeeper.bookie.storage.ldb.LocationsIndexRebuildOp.java

public void initiate() throws IOException {
    LOG.info("Starting index rebuilding");

    // Move locations index to a backup directory
    String basePath = Bookie.getCurrentDirectory(conf.getLedgerDirs()[0]).toString();
    Path currentPath = FileSystems.getDefault().getPath(basePath, "locations");
    String timestamp = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(new Date());
    Path backupPath = FileSystems.getDefault().getPath(basePath, "locations.BACKUP-" + timestamp);
    Files.move(currentPath, backupPath);

    LOG.info("Created locations index backup at {}", backupPath);

    long startTime = System.nanoTime();

    EntryLogger entryLogger = new EntryLogger(conf, new LedgerDirsManager(conf, conf.getLedgerDirs(),
            new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())));
    Set<Long> entryLogs = entryLogger.getEntryLogsSet();

    String locationsDbPath = FileSystems.getDefault().getPath(basePath, "locations").toFile().toString();

    Set<Long> activeLedgers = getActiveLedgers(conf, KeyValueStorageRocksDB.factory, basePath);
    LOG.info("Found {} active ledgers in ledger manager", activeLedgers.size());

    KeyValueStorage newIndex = KeyValueStorageRocksDB.factory.newKeyValueStorage(locationsDbPath,
            DbConfigType.Huge, conf);/*from ww  w .  ja va2s. c om*/

    int totalEntryLogs = entryLogs.size();
    int completedEntryLogs = 0;
    LOG.info("Scanning {} entry logs", totalEntryLogs);

    for (long entryLogId : entryLogs) {
        entryLogger.scanEntryLog(entryLogId, new EntryLogScanner() {
            @Override
            public void process(long ledgerId, long offset, ByteBuf entry) throws IOException {
                long entryId = entry.getLong(8);

                // Actual location indexed is pointing past the entry size
                long location = (entryLogId << 32L) | (offset + 4);

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Rebuilding {}:{} at location {} / {}", ledgerId, entryId, location >> 32,
                            location & (Integer.MAX_VALUE - 1));
                }

                // Update the ledger index page
                LongPairWrapper key = LongPairWrapper.get(ledgerId, entryId);
                LongWrapper value = LongWrapper.get(location);
                newIndex.put(key.array, value.array);
            }

            @Override
            public boolean accept(long ledgerId) {
                return activeLedgers.contains(ledgerId);
            }
        });

        ++completedEntryLogs;
        LOG.info("Completed scanning of log {}.log -- {} / {}", Long.toHexString(entryLogId),
                completedEntryLogs, totalEntryLogs);
    }

    newIndex.sync();
    newIndex.close();

    LOG.info("Rebuilding index is done. Total time: {}", DurationFormatUtils
            .formatDurationHMS(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)));
}