Example usage for java.nio.file Path resolve

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

Introduction

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

Prototype

default Path resolve(String other) 

Source Link

Document

Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the #resolve(Path) resolve method.

Usage

From source file:org.elasticsearch.plugins.PluginManagerIT.java

public void testLocalPluginInstallWithBinOnly_7152() throws Exception {
    String pluginName = "fake-plugin";
    Path pluginDir = createTempDir().resolve(pluginName);
    // create bin/tool
    Files.createDirectories(pluginDir.resolve("bin"));
    Files.createFile(pluginDir.resolve("bin").resolve("tool"));
    ;//from  w ww . j av a2 s  . com
    String pluginUrl = createPlugin(pluginDir, "description", "fake desc", "name", "fake-plugin", "version",
            "1.0", "elasticsearch.version", Version.CURRENT.toString(), "java.version",
            System.getProperty("java.specification.version"), "jvm", "true", "classname", "FakePlugin");

    Path binDir = environment.binFile();
    Path pluginBinDir = binDir.resolve(pluginName);

    assertStatusOk(String.format(Locale.ROOT, "install %s --verbose", pluginUrl));
    assertThatPluginIsListed(pluginName);
    assertDirectoryExists(pluginBinDir);
}

From source file:io.fabric8.profiles.Profiles.java

/**
 * @param target       is the directory where resulting materialized profile configuration will be written to.
 * @param profileNames a list of profile names that will be combined to create the materialized profile.
 *///from   w ww . j  ava2 s  .c o m
public void materialize(Path target, String... profileNames) throws IOException {
    ArrayList<String> profileSearchOrder = new ArrayList<>();
    for (String profileName : profileNames) {
        collectProfileNames(profileSearchOrder, profileName);
    }

    HashSet<String> files = new HashSet<>();
    for (String profileName : profileSearchOrder) {
        files.addAll(listFiles(profileName));
    }

    System.out.println("profile search order" + profileSearchOrder);
    System.out.println("files: " + files);
    for (String file : files) {
        try (InputStream is = materializeFile(file, profileSearchOrder)) {
            Files.copy(is, target.resolve(file), StandardCopyOption.REPLACE_EXISTING);
        }
    }

}

From source file:ddf.test.itests.platform.TestPlatform.java

private Path getExportSubDirectory(String... paths) {
    Path directory = getExportDirectory().resolve("etc");

    for (String path : paths) {
        directory = directory.resolve(path);
    }// w w  w.  j av a2s. com

    return directory;
}

From source file:fr.gael.dhus.sync.impl.ODataProductSynchronizer.java

/** Downloads a product. */
private void downloadProduct(Product p) throws IOException, InterruptedException {
    // Creates a client producer that produces HTTP Basic auth aware clients
    HttpAsyncClientProducer cliprod = new HttpAsyncClientProducer() {
        @Override/*from  w w w  . j a v  a  2  s  . c  o m*/
        public CloseableHttpAsyncClient generateClient() {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
                    new UsernamePasswordCredentials(serviceUser, servicePass));
            CloseableHttpAsyncClient res = HttpAsyncClients.custom()
                    .setDefaultCredentialsProvider(credsProvider).build();
            res.start();
            return res;
        }
    };

    // Asks the Incoming manager for a download path
    Path dir = Paths.get(INCOMING_MANAGER.getNewIncomingPath().toURI());
    Path tmp_pd = dir.resolve(p.getIdentifier() + ".part"); // Temporary names
    Path tmp_ql = dir.resolve(p.getIdentifier() + "-ql.part");
    Path tmp_tn = dir.resolve(p.getIdentifier() + "-tn.part");
    // These files will be moved once download is complete

    InterruptibleHttpClient http_client = new InterruptibleHttpClient(cliprod);
    DownloadResult pd_res = null, ql_res = null, tn_res = null;
    try {
        long delta = System.currentTimeMillis();
        pd_res = downloadValidateRename(http_client, tmp_pd, p.getOrigin());
        logODataPerf(p.getOrigin(), System.currentTimeMillis() - delta);

        // Sets download info in the product (not written in the db here)
        p.setPath(pd_res.data.toUri().toURL());
        p.setDownloadablePath(pd_res.data.toString());
        p.setDownloadableType(pd_res.dataType);
        p.setDownloadableSize(pd_res.dataSize);

        // Downloads and sets the quicklook and thumbnail (if any)
        if (p.getQuicklookFlag()) {
            // Failing at downloading a quicklook must not abort the download!
            try {
                ql_res = downloadValidateRename(http_client, tmp_ql, p.getQuicklookPath());
                p.setQuicklookPath(ql_res.data.toString());
                p.setQuicklookSize(ql_res.dataSize);
            } catch (IOException ex) {
                LOGGER.error("Failed to download quicklook at " + p.getQuicklookPath(), ex);
            }
        }
        if (p.getThumbnailFlag()) {
            // Failing at downloading a thumbnail must not abort the download!
            try {
                tn_res = downloadValidateRename(http_client, tmp_tn, p.getThumbnailPath());
                p.setThumbnailPath(tn_res.data.toString());
                p.setThumbnailSize(tn_res.dataSize);
            } catch (IOException ex) {
                LOGGER.error("Failed to download thumbnail at " + p.getThumbnailPath(), ex);
            }
        }
    } catch (Exception ex) {
        // Removes downloaded files if an error occured
        if (pd_res != null) {
            Files.delete(pd_res.data);
        }
        if (ql_res != null) {
            Files.delete(ql_res.data);
        }
        if (tn_res != null) {
            Files.delete(tn_res.data);
        }
        throw ex;
    }
}

From source file:facs.utils.Billing.java

/**
 * Helper method. copies files and directories from source to target source and target can be
 * created via the command: FileSystems.getDefault().getPath(String path, ... String more) or
 * Paths.get(String path, ... String more) Note: overrides existing folders
 * /*from w ww. ja  va  2  s  .c  o  m*/
 * @param source
 * @param target
 * @return true if copying was successful
 */
public boolean copy(final Path source, final Path target) {
    try {
        Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {

                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        Path targetdir = target.resolve(source.relativize(dir));
                        try {
                            Files.copy(dir, targetdir, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
                        } catch (FileAlreadyExistsException e) {
                            if (!Files.isDirectory(targetdir)) {
                                throw e;
                            }
                        }

                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        Files.copy(file, target.resolve(source.relativize(file)));
                        return FileVisitResult.CONTINUE;

                    }

                });
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testExtractWeirdIndex() throws InterruptedException, IOException {

    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        zip.putArchiveEntry(new ZipArchiveEntry("foo/bar/baz"));
        zip.write(DUMMY_FILE_CONTENTS, 0, DUMMY_FILE_CONTENTS.length);
        zip.closeArchiveEntry();/*from   w  ww  .j  a v a  2 s. c o m*/
        zip.putArchiveEntry(new ZipArchiveEntry("foo/"));
        zip.closeArchiveEntry();
        zip.putArchiveEntry(new ZipArchiveEntry("qux/"));
        zip.closeArchiveEntry();
    }

    Path extractFolder = tmpFolder.newFolder();
    ImmutableList<Path> result = ArchiveFormat.ZIP.getUnarchiver().extractArchive(
            new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES);
    assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo")));
    assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo/bar/baz")));

    assertEquals(ImmutableList.of(extractFolder.resolve("foo/bar/baz")), result);
}

From source file:io.github.swagger2markup.MarkdownConverterTest.java

@Test
public void testWithSeparatedDefinitions() throws IOException, URISyntaxException {
    //Given/* w w  w  .  java 2  s. c o m*/
    Path file = Paths.get(MarkdownConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/markdown/generated");
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withSeparatedDefinitions()
            .withMarkupLanguage(MarkupLanguage.MARKDOWN).build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);

    //Then
    String[] files = outputDirectory.toFile().list();
    expectedFiles.add("definitions");
    assertThat(files).hasSize(5).containsAll(expectedFiles);

    Path definitionsDirectory = outputDirectory.resolve("definitions");
    String[] definitions = definitionsDirectory.toFile().list();
    assertThat(definitions).hasSize(5)
            .containsAll(asList("Category.md", "Order.md", "Pet.md", "Tag.md", "User.md"));
}

From source file:io.github.swagger2markup.MarkdownConverterTest.java

@Test
public void testHandlesComposition() throws IOException, URISyntaxException {
    //Given/*from   w ww.ja  v  a 2s. c  o  m*/
    Path file = Paths.get(MarkdownConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/markdown/generated");
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withSeparatedDefinitions()
            .withMarkupLanguage(MarkupLanguage.MARKDOWN).build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);

    // Then
    String[] files = outputDirectory.toFile().list();
    expectedFiles.add("definitions");
    assertThat(files).hasSize(5).containsAll(expectedFiles);
    Path definitionsDirectory = outputDirectory.resolve("definitions");
    verifyMarkdownContainsFieldsInTables(definitionsDirectory.resolve("User.md").toFile(),
            ImmutableMap.<String, Set<String>>builder().put("User", ImmutableSet.of("id", "username",
                    "firstName", "lastName", "email", "password", "phone", "userStatus")).build());

}

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testExcludedEntriesNotExtracted() throws IOException {
    try (ZipArchive zipArchive = new ZipArchive(this.zipFile, true)) {
        zipArchive.add("1.bin", DUMMY_FILE_CONTENTS);
        zipArchive.add("subdir/2.bin", DUMMY_FILE_CONTENTS);
        zipArchive.addDir("emptydir");
    }//from   ww  w.  j ava  2s. c o  m

    ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(tmpFolder.getRoot());

    Path extractFolder = tmpFolder.newFolder();
    ImmutableSet<Path> result = ArchiveFormat.ZIP.getUnarchiver().extractArchive(zipFile.toAbsolutePath(),
            filesystem, extractFolder, Optional.empty(), new PatternsMatcher(ImmutableSet.of("subdir/2.bin")),
            ExistingFileMode.OVERWRITE);
    assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("1.bin")));
    assertTrue(Files.isDirectory(extractFolder.toAbsolutePath().resolve("emptydir")));
    assertEquals(ImmutableSet.of(extractFolder.resolve("1.bin")), result);
}

From source file:com.github.podd.resources.test.DataReferenceAttachResourceImplTest.java

/**
 * Given the path to a resource containing an incomplete File Reference object, this method
 * constructs a complete File Reference and returns it as an RDF/XML string.
 *
 * @param fragmentSource//w  w w  .  j  a  v  a2 s.c o m
 *            Location of resource containing incomplete File Reference
 * @return String containing RDF statements
 */
private String buildFileReferenceString(final String fragmentSource, final RDFFormat format,
        final Path testDirectory) throws Exception {
    // read the fragment's RDF statements into a Model
    final InputStream inputStream = this.getClass().getResourceAsStream(fragmentSource);
    final Model model = Rio.parse(inputStream, "", format);

    // path to be set as part of the file reference
    final Path completePath = testDirectory.resolve(TestConstants.TEST_REMOTE_FILE_NAME);
    Files.copy(
            this.getClass().getResourceAsStream(
                    TestConstants.TEST_REMOTE_FILE_PATH + "/" + TestConstants.TEST_REMOTE_FILE_NAME),
            completePath, StandardCopyOption.REPLACE_EXISTING);

    final Resource aliasUri = model.filter(null, PODD.PODD_BASE_HAS_ALIAS, null).subjects().iterator().next();
    model.add(aliasUri, PODD.PODD_BASE_HAS_FILE_PATH,
            ValueFactoryImpl.getInstance().createLiteral(testDirectory.toAbsolutePath().toString()));
    model.add(aliasUri, PODD.PODD_BASE_HAS_FILENAME,
            ValueFactoryImpl.getInstance().createLiteral(TestConstants.TEST_REMOTE_FILE_NAME));

    // get a String representation of the statements in the Model
    final StringWriter out = new StringWriter();
    Rio.write(model, out, format);

    return out.toString();
}