Example usage for java.nio.file Path toAbsolutePath

List of usage examples for java.nio.file Path toAbsolutePath

Introduction

In this page you can find the example usage for java.nio.file Path toAbsolutePath.

Prototype

Path toAbsolutePath();

Source Link

Document

Returns a Path object representing the absolute path of this path.

Usage

From source file:com.netflix.spinnaker.clouddriver.artifacts.bitbucket.BitbucketArtifactCredentialsTest.java

@Test
void downloadWithBasicAuthFromFile(@TempDirectory.TempDir Path tempDir,
        @WiremockResolver.Wiremock WireMockServer server) throws IOException {
    Path authFile = tempDir.resolve("auth-file");
    Files.write(authFile, "someuser:somepassw0rd!".getBytes());

    BitbucketArtifactAccount account = new BitbucketArtifactAccount();
    account.setName("my-bitbucket-account");
    account.setUsernamePasswordFile(authFile.toAbsolutePath().toString());

    runTestCase(server, account, m -> m.withBasicAuth("someuser", "somepassw0rd!"));
}

From source file:org.tinymediamanager.core.tvshow.tasks.TvShowUpdateDatasourceTask2.java

/**
 * simple NIO File.listFiles() replacement<br>
 * returns ONLY regular files (NO folders, NO hidden) in specified dir (NOT recursive)
 * /*from  w  ww  .  j  a v a 2  s .  c  o m*/
 * @param directory
 *          the folder to list the files for
 * @return list of files&folders
 */
public static List<Path> listFilesOnly(Path directory) {
    List<Path> fileNames = new ArrayList<>();
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory)) {
        for (Path path : directoryStream) {
            if (Utils.isRegularFile(path)) {
                String fn = path.getFileName().toString().toUpperCase(Locale.ROOT);
                if (!skipFolders.contains(fn) && !fn.matches(skipRegex) && !TvShowModuleManager.SETTINGS
                        .getTvShowSkipFolders().contains(path.toFile().getAbsolutePath())) {
                    fileNames.add(path.toAbsolutePath());
                } else {
                    LOGGER.debug("Skipping: " + path);
                }
            }
        }
    } catch (IOException ex) {
    }
    return fileNames;
}

From source file:org.bonitasoft.platform.setup.command.configure.BundleConfigurator.java

Path getRelativePath(Path pathToRelativize) {
    return rootPath.toAbsolutePath().relativize(pathToRelativize.toAbsolutePath());
}

From source file:com.juancarlosroot.threads.SimulatedUser.java

private void deleteFilesInsideFolder(String folderName) {
    Path currentRelativePath = Paths.get("");
    String s = currentRelativePath.toAbsolutePath().toString();
    File theFolder = new File(s + "/" + folderName);

    try {/*  w  w  w .j a v a  2 s. c  o  m*/
        FileUtils.cleanDirectory(theFolder);
        System.out.println("Se han borrado los archivos de : " + folderName);
    } catch (IOException ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Error al borrar los archivos de : " + folderName);
    }
}

From source file:com.juancarlosroot.threads.SimulatedUser.java

private String createFolder(String folderName) {
    Path currentRelativePath = Paths.get("");
    String s = currentRelativePath.toAbsolutePath().toString();

    File theFolder = new File(s + "/" + folderName);

    if (!theFolder.mkdir()) {
        System.out.println("Ya existe la carpeta : " + s + "/" + folderName);
        deleteFilesInsideFolder(folderName);
    } else {//  w ww.  ja  v  a2  s  .  c  om
        System.out.println("Creacin exitosa : " + s + "/" + folderName);
    }
    return s + "/" + folderName;
}

From source file:com.juancarlosroot.threads.SimulatedUser.java

private void deleteFolder(String folderName) {
    Path currentRelativePath = Paths.get("");
    String s = currentRelativePath.toAbsolutePath().toString();

    Path folderPath = Paths.get(s + "/" + folderName);

    try {/*from   w w w . ja va  2 s.c om*/
        Files.delete(folderPath);
        System.out.println("Carpeta eliminada : " + s + "/" + folderName);
    } catch (IOException ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Error al eliminar carpeta : " + s + "/" + folderName);
    }
}

From source file:com.github.ffremont.microservices.springboot.node.tasks.UninstallTask.java

/**
 * // w w w . j  a  v a2 s. c  o  m
 * @param path
 * @throws IOException 
 */
private void remove(Path path) throws IOException {
    Files.list(path).forEach((Path item) -> {
        try {
            if (Files.isDirectory(item)) {
                this.remove(item);
            } else {
                Files.delete(item);
            }
        } catch (IOException e) {
            LOG.error("Impossible de supprmimer les lments dans " + item.toAbsolutePath(), e);
        }
    });

    Files.delete(path);
}

From source file:com.collaborne.jsonschema.generator.driver.GeneratorDriver.java

/**
 * Create a {@link SchemaLoader} with the provided {@code rootUri} and {@code baseDirectory}.
 *
 * All schemas from {@code schemaFiles} are pre-loaded into the schema loader.
 *
 * @param rootUri/*w  w  w .  ja v a  2  s.c om*/
 * @param baseDirectory
 * @param schemaFiles
 * @return
 * @throws IOException
 */
public SchemaLoader createSchemaLoader(URI rootUri, Path baseDirectory, List<Path> schemaFiles)
        throws IOException {
    URI baseDirectoryUri = baseDirectory.toAbsolutePath().normalize().toUri();

    // We're not adding a path redirection here, because that changes the path of the loaded schemas to the redirected location.
    // FIXME: This really looks like a bug in the SchemaLoader itself!
    URITranslatorConfiguration uriTranslatorConfiguration = URITranslatorConfiguration.newBuilder()
            .setNamespace(rootUri).freeze();

    LoadingConfigurationBuilder loadingConfigurationBuilder = LoadingConfiguration.newBuilder()
            .setURITranslatorConfiguration(uriTranslatorConfiguration);

    // ... instead, we use a custom downloader which executes the redirect
    Map<String, URIDownloader> downloaders = loadingConfigurationBuilder.freeze().getDownloaderMap();
    URIDownloader redirectingDownloader = new URIDownloader() {
        @Override
        public InputStream fetch(URI source) throws IOException {
            URI relativeSourceUri = rootUri.relativize(source);
            if (!relativeSourceUri.isAbsolute()) {
                // Apply the redirect
                source = baseDirectoryUri.resolve(relativeSourceUri);
            }

            URIDownloader wrappedDownloader = downloaders.get(source.getScheme());
            return wrappedDownloader.fetch(source);
        }
    };
    for (Map.Entry<String, URIDownloader> entry : downloaders.entrySet()) {
        loadingConfigurationBuilder.addScheme(entry.getKey(), redirectingDownloader);
    }

    JsonNodeReader reader = new JsonNodeReader(objectMapper);
    for (Path schemaFile : schemaFiles) {
        URI schemaFileUri = schemaFile.toAbsolutePath().normalize().toUri();
        URI relativeSchemaUri = baseDirectoryUri.relativize(schemaFileUri);
        URI schemaUri = rootUri.resolve(relativeSchemaUri);

        logger.info("{}: loading from {}", schemaUri, schemaFile);
        JsonNode schemaNode = reader.fromReader(Files.newBufferedReader(schemaFile));
        // FIXME: (upstream?): the preloaded map is accessed via the "real URI", so we need that one here as well
        //        This smells really wrong, after all we want all these to look like they came from rootUri()
        loadingConfigurationBuilder.preloadSchema(schemaFileUri.toASCIIString(), schemaNode);
    }

    return new SchemaLoader(loadingConfigurationBuilder.freeze());
}

From source file:com.netflix.spinnaker.clouddriver.artifacts.github.GithubArtifactCredentialsTest.java

@Test
void downloadWithBasicAuthFromFile(@TempDirectory.TempDir Path tempDir,
        @WiremockResolver.Wiremock WireMockServer server) throws IOException {
    Path authFile = tempDir.resolve("auth-file");
    Files.write(authFile, "someuser:somepassw0rd!".getBytes());

    GitHubArtifactAccount account = new GitHubArtifactAccount();
    account.setName("my-github-account");
    account.setUsernamePasswordFile(authFile.toAbsolutePath().toString());

    runTestCase(server, account, m -> m.withBasicAuth("someuser", "somepassw0rd!"));
}

From source file:org.discosync.ApplySyncPack.java

/**
 * Apply a syncpack to a target directory.
 *///from w  w  w . jav  a  2s.  c  om
protected void applySyncPack(String syncPackDir, String targetDir) throws SQLException, IOException {

    // read file operations from database
    File fileOpDbFile = new File(syncPackDir, "fileoperations");
    FileOperationDatabase db = new FileOperationDatabase(fileOpDbFile.getAbsolutePath());
    db.open();

    Iterator<FileListEntry> it = db.getFileListOperationIterator();

    Path syncFileBaseDir = Paths.get(syncPackDir, "files");
    String syncFileBaseDirStr = syncFileBaseDir.toAbsolutePath().toString();

    int filesCopied = 0;
    int filesReplaced = 0;
    int filesDeleted = 0;
    long copySize = 0L;
    long deleteSize = 0L;

    // Collect directories during processing.
    List<FileListEntry> directoryOperations = new ArrayList<>();

    // First process all files, then the directories
    while (it.hasNext()) {

        FileListEntry e = it.next();

        // Remember directories
        if (e.isDirectory()) {
            directoryOperations.add(e);
            continue;
        }

        String path = e.getPath();
        Path sourcePath = Paths.get(syncFileBaseDirStr, path); // may not exist
        Path targetPath = Paths.get(targetDir, path); // may not exist

        if (e.getOperation() == FileOperations.COPY) {
            // copy new file, target files should not exist
            if (Files.exists(targetPath)) {
                System.out
                        .println("Error: the file should not exist: " + targetPath.toAbsolutePath().toString());
            } else {
                if (!Files.exists(targetPath.getParent())) {
                    Files.createDirectories(targetPath.getParent());
                }

                Files.copy(sourcePath, targetPath);
                filesCopied++;
                copySize += e.getSize();
            }

        } else if (e.getOperation() == FileOperations.REPLACE) {
            // replace existing file
            if (!Files.exists(targetPath)) {
                System.out.println("Info: the file should exist: " + targetPath.toAbsolutePath().toString());
            }
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            filesReplaced++;
            copySize += e.getSize();

        } else if (e.getOperation() == FileOperations.DELETE) {
            // delete existing file
            if (!Files.exists(targetPath)) {
                System.out.println("Info: the file should exist: " + targetPath.toAbsolutePath().toString());
            } else {
                long fileSize = Files.size(targetPath);
                if (fileSize != e.getSize()) {
                    // show info, delete anyway
                    System.out.println(
                            "Info: the file size is different: " + targetPath.toAbsolutePath().toString());
                }
                deleteSize += fileSize;
                Files.delete(targetPath);
                filesDeleted++;
            }
        }
    }

    db.close();

    // Sort directory list to ensure directories are deleted bottom-up (first /dir1/dir2, then /dir1)
    Collections.sort(directoryOperations, new Comparator<FileListEntry>() {
        @Override
        public int compare(FileListEntry e1, FileListEntry e2) {
            return e2.getPath().compareTo(e1.getPath().toString());
        }
    });

    // Now process directories - create and delete empty directories
    for (FileListEntry e : directoryOperations) {

        String path = e.getPath();
        Path targetPath = Paths.get(targetDir, path); // may not exist

        if (e.getOperation() == FileOperations.COPY) {
            // create directory if needed
            if (!Files.exists(targetPath)) {
                Files.createDirectories(targetPath);
            }
        } else if (e.getOperation() == FileOperations.DELETE) {

            if (!Files.exists(targetPath)) {
                System.out.println(
                        "Info: Directory to DELETE does not exist: " + targetPath.toAbsolutePath().toString());

            } else if (!Files.isDirectory(targetPath, LinkOption.NOFOLLOW_LINKS)) {
                System.out.println("Info: Directory to DELETE is not a directory, but a file: "
                        + targetPath.toAbsolutePath().toString());

            } else if (!Utils.isDirectoryEmpty(targetPath)) {
                System.out.println("Info: Directory to DELETE is not empty, but should be empty: "
                        + targetPath.toAbsolutePath().toString());

            } else {
                // delete directory
                Files.delete(targetPath);
            }
        }
    }

    System.out.println("Apply of syncpack '" + syncPackDir + "' to directory '" + targetDir + "' finished.");
    System.out.println("Files copied  : " + String.format("%,d", filesCopied));
    System.out.println("Files replaced: " + String.format("%,d", filesReplaced));
    System.out.println("Files deleted : " + String.format("%,d", filesDeleted));
    System.out.println("Bytes copied  : " + String.format("%,d", copySize));
    System.out.println("Bytes deleted : " + String.format("%,d", deleteSize));
}