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:at.ac.tuwien.infosys.util.ImageUtil.java

public synchronized Path createImage(Plan deviceComponentBundle, String idPrefix) throws IOException {

    if (idPrefix != null && !idPrefix.isEmpty())
        idPrefix += "_";
    else/*ww  w . j a  v a2  s  .co m*/
        idPrefix = "unknown_";

    this.imageId = idPrefix + UUID.randomUUID().toString();

    logger.info("Building image with id: " + imageId);

    this.zipUtil = new ZipUtil(imageId + ".zip", imageTempDir, workingRepo);

    List<String> componentNames = new ArrayList<String>();

    // create image structure and copy files (artifacts and scripts)
    for (Component component : deviceComponentBundle.getComponents()) {
        Path compParentPath = Files.createDirectories(imageTempDir.resolve(component.getName()));
        componentNames.add(component.getName());

        Path artifactParentPath = Files.createDirectories(compParentPath.resolve("artifacts"));

        Path scriptParentPath = Files.createDirectories(compParentPath.resolve("scripts"));

        for (Resource artifact : component.getBinaries()) {
            Path artifactFile = Files.createFile(artifactParentPath.resolve(artifact.getName()));
            saveFile(artifact.getUri(), artifactFile);
        }

        for (Resource script : component.getScripts()) {
            Path scriptFile = Files.createFile(scriptParentPath.resolve(script.getName()));
            saveFile(script.getUri(), scriptFile);
        }
    }

    // create runlist file and write component-names
    StringBuilder builder = new StringBuilder();
    // boolean firstItem = true;
    for (String componentName : componentNames) {
        // if (!firstItem)
        // builder.append("\n");
        // else
        // firstItem = false;
        // builder.append(componentName);
        builder.append(componentName + "\n");
    }
    Path runlistFile = Files.createFile(imageTempDir.resolve(RUNLIST_FILE));
    Files.write(runlistFile, builder.toString().getBytes());

    // create file and write image-id
    Path idFile = Files.createFile(imageTempDir.resolve(ID_FILE));
    Files.write(idFile, imageId.getBytes());

    // add generic image-run script
    Path globalRunFile = Files.createFile(imageTempDir.resolve(IMAGE_RUN_FILE_NAME));
    saveFile(Config.IMAGE_RUN_SCRIPT, globalRunFile);

    logger.info("Finished building and initiate archiving!");

    // create final image by compressing the contents into a zip
    Path zipFile = zipUtil.createZip();

    logger.info("Finished archiving image: " + zipFile.toString());

    return zipFile;
}

From source file:ru.histone.staticrender.StaticRender.java

public void renderSite(final Path srcDir, final Path dstDir) {
    log.info("Running StaticRender for srcDir={}, dstDir={}", srcDir.toString(), dstDir.toString());
    Path contentDir = srcDir.resolve("content/");
    final Path layoutDir = srcDir.resolve("layouts/");

    FileVisitor<Path> layoutVisitor = new SimpleFileVisitor<Path>() {
        @Override//from  ww  w . ja va2  s.c o  m
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (file.toString().endsWith("." + TEMPLATE_FILE_EXTENSION)) {
                ArrayNode ast = null;
                try {
                    ast = histone.parseTemplateToAST(new FileReader(file.toFile()));
                } catch (HistoneException e) {
                    throw new RuntimeException("Error parsing histone template:" + e.getMessage(), e);
                }

                final String fileName = file.getFileName().toString();
                String layoutId = fileName.substring(0,
                        fileName.length() - TEMPLATE_FILE_EXTENSION.length() - 1);
                layouts.put(layoutId, ast);
                if (log.isDebugEnabled()) {
                    log.debug("Layout found id='{}', file={}", layoutId, file);
                } else {
                    log.info("Layout found id='{}'", layoutId);
                }
            } else {
                final Path relativeFileName = srcDir.resolve("layouts").relativize(Paths.get(file.toUri()));
                final Path resolvedFile = dstDir.resolve(relativeFileName);
                if (!resolvedFile.getParent().toFile().exists()) {
                    Files.createDirectories(resolvedFile.getParent());
                }
                Files.copy(Paths.get(file.toUri()), resolvedFile, StandardCopyOption.REPLACE_EXISTING,
                        LinkOption.NOFOLLOW_LINKS);
            }
            return FileVisitResult.CONTINUE;
        }
    };

    FileVisitor<Path> contentVisitor = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

            Scanner scanner = new Scanner(file, "UTF-8");
            scanner.useDelimiter("-----");

            String meta = null;
            StringBuilder content = new StringBuilder();

            if (!scanner.hasNext()) {
                throw new RuntimeException("Wrong format #1:" + file.toString());
            }

            if (scanner.hasNext()) {
                meta = scanner.next();
            }

            if (scanner.hasNext()) {
                content.append(scanner.next());
                scanner.useDelimiter("\n");
            }

            while (scanner.hasNext()) {
                final String next = scanner.next();
                content.append(next);

                if (scanner.hasNext()) {
                    content.append("\n");
                }
            }

            Map<String, String> metaYaml = (Map<String, String>) yaml.load(meta);

            String layoutId = metaYaml.get("layout");

            if (!layouts.containsKey(layoutId)) {
                throw new RuntimeException(MessageFormat.format("No layout with id='{0}' found", layoutId));
            }

            final Path relativeFileName = srcDir.resolve("content").relativize(Paths.get(file.toUri()));
            final Path resolvedFile = dstDir.resolve(relativeFileName);
            if (!resolvedFile.getParent().toFile().exists()) {
                Files.createDirectories(resolvedFile.getParent());
            }
            Writer output = new FileWriter(resolvedFile.toFile());
            ObjectNode context = jackson.createObjectNode();
            ObjectNode metaNode = jackson.createObjectNode();
            context.put("content", content.toString());
            context.put("meta", metaNode);
            for (String key : metaYaml.keySet()) {
                if (!key.equalsIgnoreCase("content")) {
                    metaNode.put(key, metaYaml.get(key));
                }
            }

            try {
                histone.evaluateAST(layoutDir.toUri().toString(), layouts.get(layoutId), context, output);
                output.flush();
            } catch (HistoneException e) {
                throw new RuntimeException("Error evaluating content: " + e.getMessage(), e);
            } finally {
                output.close();
            }

            return FileVisitResult.CONTINUE;
        }
    };

    try {
        Files.walkFileTree(layoutDir, layoutVisitor);
        Files.walkFileTree(contentDir, contentVisitor);
    } catch (Exception e) {
        throw new RuntimeException("Error during site render", e);
    }
}

From source file:org.elasticsearch.packaging.test.ArchiveTestCase.java

public void test80RelativePathConf() throws IOException {
    assumeThat(installation, is(notNullValue()));

    final Path temp = getTempDir().resolve("esconf-alternate");
    final Path tempConf = temp.resolve("config");

    try {/*  w w  w .  j  av  a 2  s . c om*/
        mkdir(tempConf);
        Stream.of("elasticsearch.yml", "log4j2.properties", "jvm.options")
                .forEach(file -> cp(installation.config(file), tempConf.resolve(file)));

        append(tempConf.resolve("elasticsearch.yml"), "node.name: relative");

        final Shell sh = new Shell();
        Platforms.onLinux(() -> sh.run("chown -R elasticsearch:elasticsearch " + temp));
        Platforms.onWindows(() -> sh.run("$account = New-Object System.Security.Principal.NTAccount 'vagrant'; "
                + "$tempConf = Get-ChildItem '" + temp + "' -Recurse; " + "$tempConf += Get-Item '" + temp
                + "'; " + "$tempConf | ForEach-Object { " + "$acl = Get-Acl $_.FullName; "
                + "$acl.SetOwner($account); " + "Set-Acl $_.FullName $acl " + "}"));

        final Shell serverShell = new Shell(temp);
        serverShell.getEnv().put("ES_PATH_CONF", "config");
        Archives.runElasticsearch(installation, serverShell);

        final String nodesResponse = makeRequest(Request.Get("http://localhost:9200/_nodes"));
        assertThat(nodesResponse, containsString("\"name\":\"relative\""));

        Archives.stopElasticsearch(installation);

    } finally {
        rm(tempConf);
    }
}

From source file:com.facebook.buck.java.JarDirectoryStepTest.java

private Manifest jarDirectoryAndReadManifest(Manifest fromJar, Manifest fromUser, boolean mergeEntries)
        throws IOException {
    // Create a jar with a manifest we'd expect to see merged.
    Path originalJar = folder.newFile("unexpected.jar");
    JarOutputStream ignored = new JarOutputStream(Files.newOutputStream(originalJar), fromJar);
    ignored.close();/*from  w  w w.  ja va2 s . c o m*/

    // Now create the actual manifest
    Path manifestFile = folder.newFile("actual_manfiest.mf");
    try (OutputStream os = Files.newOutputStream(manifestFile)) {
        fromUser.write(os);
    }

    Path tmp = folder.newFolder();
    Path output = tmp.resolve("example.jar");
    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), output,
            ImmutableSortedSet.of(originalJar), /* main class */ null, manifestFile, mergeEntries,
            /* blacklist */ ImmutableSet.<String>of());
    ExecutionContext context = TestExecutionContext.newInstance();
    step.execute(context);

    // Now verify that the created manifest matches the expected one.
    try (JarInputStream jis = new JarInputStream(Files.newInputStream(output))) {
        return jis.getManifest();
    }
}

From source file:com.facebook.buck.zip.ZipStepTest.java

@Test
public void timesAreSanitized() throws IOException {
    Path parent = tmp.newFolder("zipstep");

    // Create a zip file with a file and a directory.
    Path toZip = tmp.newFolder("zipdir");
    Files.createDirectories(toZip.resolve("child"));
    Files.createFile(toZip.resolve("child/file.txt"));
    Path outputZip = parent.resolve("output.zip");
    ZipStep step = new ZipStep(filesystem, outputZip, ImmutableSet.of(), false,
            ZipCompressionLevel.DEFAULT_COMPRESSION_LEVEL, Paths.get("zipdir"));
    assertEquals(0, step.execute(TestExecutionContext.newInstance()).getExitCode());

    // Iterate over each of the entries, expecting to see all zeros in the time fields.
    assertTrue(Files.exists(outputZip));
    Date dosEpoch = new Date(ZipUtil.dosToJavaTime(ZipConstants.DOS_FAKE_TIME));
    try (ZipInputStream is = new ZipInputStream(new FileInputStream(outputZip.toFile()))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            assertEquals(entry.getName(), dosEpoch, new Date(entry.getTime()));
        }//from ww w  .jav a 2s  . c o  m
    }
}

From source file:org.darkware.wpman.config.CollectionConfig.java

/**
 * Fetch the directory to scan for modular config fragments. If no path is explicitly configured,
 * a default configuration is used.//from w  w  w .  ja v  a  2  s  . co  m
 *
 * @return A {@link Path} to the directory to scan for config fragments.
 */
@JsonProperty("policyDir")
public Path getPolicyRoot() {
    if (this.policyRoot == null) {
        Path wpPolicyRoot = this.getWpConfig().getPolicyRoot();
        if (wpPolicyRoot == null)
            throw new RuntimeException("Base WP Policy Dir is null");
        String subdirectory = this.getDefaultPolicySubdirectory();
        return wpPolicyRoot.resolve(subdirectory);
    } else
        return this.policyRoot;
}

From source file:com.facebook.buck.java.JarDirectoryStepTest.java

@Test
public void shouldFailIfMainClassMissing() throws IOException {
    Path zipup = folder.newFolder("zipup");

    Path zip = createZip(zipup.resolve("a.zip"), "com/example/Main.class");

    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(zipup), Paths.get("output.jar"),
            ImmutableSet.of(zip.getFileName()), "com.example.MissingMain", /* manifest file */ null);
    TestConsole console = new TestConsole();
    ExecutionContext context = TestExecutionContext.newBuilder().setConsole(console).build();

    int returnCode = step.execute(context);

    assertEquals(1, returnCode);/*ww  w.j a v  a2 s . c o m*/
    assertEquals("ERROR: Main class com.example.MissingMain does not exist.\n",
            console.getTextWrittenToStdErr());
}

From source file:com.facebook.buck.java.JarDirectoryStepTest.java

@Test
public void shouldNotComplainWhenDuplicateDirectoryNamesAreAdded() throws IOException {
    Path zipup = folder.newFolder();

    Path first = createZip(zipup.resolve("first.zip"), "dir/example.txt", "dir/root1file.txt");
    Path second = createZip(zipup.resolve("second.zip"), "dir/example.txt", "dir/root2file.txt",
            "com/example/Main.class");

    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(zipup), Paths.get("output.jar"),
            ImmutableSet.of(first.getFileName(), second.getFileName()), "com.example.Main",
            /* manifest file */ null);

    ExecutionContext context = TestExecutionContext.newInstance();

    int returnCode = step.execute(context);

    assertEquals(0, returnCode);/*from www . j a va2s .co  m*/

    Path zip = zipup.resolve("output.jar");

    // The three below plus the manifest and Main.class.
    assertZipFileCountIs(5, zip);
    assertZipContains(zip, "dir/example.txt", "dir/root1file.txt", "dir/root2file.txt");
}

From source file:com.facebook.buck.java.JarDirectoryStepTest.java

@Test
public void shouldNotIncludeFilesInBlacklist() throws IOException {
    Path zipup = folder.newFolder();

    Path first = createZip(zipup.resolve("first.zip"), "dir/file1.txt", "dir/file2.txt",
            "com/example/Main.class");

    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(zipup), Paths.get("output.jar"),
            ImmutableSet.of(first.getFileName()), "com.example.Main", /* manifest file */ null,
            /* merge manifests */ true, /* blacklist */ ImmutableSet.of(".*2.*"));

    ExecutionContext context = TestExecutionContext.newInstance();

    int returnCode = step.execute(context);

    assertEquals(0, returnCode);/*from  ww  w  .  j a va 2 s  .  c  o  m*/

    Path zip = zipup.resolve("output.jar");

    // file1.txt, Main.class, plus the manifest.
    assertZipFileCountIs(3, zip);
    assertZipContains(zip, "dir/file1.txt");
    assertZipDoesNotContain(zip, "dir/file2.txt");
}