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:com.collaborne.jsonschema.generator.pojo.PojoGeneratorSmokeTest.java

@Test
public void runSmokeTestInline() throws IOException, CodeGenerationException {
    // XXX: only really checks #resolve()
    URI rootUri = URI.create("http://example.com/");

    Path outputDirectory = fs.getPath("output");
    generator.setOutputDirectory(outputDirectory);

    SchemaLoader schemas = loadSchema(rootUri, "/schemas/inline.json");
    generator.setSchemaLoader(schemas);/*from   ww w . j  a v a  2  s  .  co m*/

    Mapping rootMapping = new Mapping(URI.create("http://example.com/schemas/inline.json#"),
            new ClassName("com.example.test.schemas", "WithInline"));
    generator.addMapping(rootMapping.getTarget(), rootMapping);

    generator.generate(rootMapping.getTarget());

    Path generatedTypeFile = outputDirectory.resolve("com/example/test/schemas/WithInline.java");
    assertTrue(Files.exists(generatedTypeFile));
}

From source file:de.huberlin.wbi.cuneiform.core.invoc.Invocation.java

@SuppressWarnings("static-method")
public Path getExecutablePath(Path location) {
    return location.resolve(SCRIPT_NAME);
}

From source file:com.android.repository.util.InstallerUtilTest.java

public void testUnzip() throws Exception {
    if (new MockFileOp().isWindows()) {
        // can't run on windows.
        return;/*from  w  w w  .  j  av a  2 s . c  om*/
    }
    // zip needs a real file, so no MockFileOp for us.
    FileOp fop = FileOpUtils.create();

    Path root = Files.createTempDirectory("InstallerUtilTest");
    Path outRoot = Files.createTempDirectory("InstallerUtilTest");
    try {
        Path file1 = root.resolve("foo");
        Files.write(file1, "content".getBytes());
        Path dir1 = root.resolve("bar");
        Files.createDirectories(dir1);
        Path file2 = dir1.resolve("baz");
        Files.write(file2, "content2".getBytes());
        Files.createSymbolicLink(root.resolve("link1"), dir1);
        Files.createSymbolicLink(root.resolve("link2"), file2);

        Path outZip = outRoot.resolve("out.zip");
        try (ZipArchiveOutputStream out = new ZipArchiveOutputStream(outZip.toFile());
                Stream<Path> listing = Files.walk(root)) {
            listing.forEach(path -> {
                try {
                    ZipArchiveEntry archiveEntry = (ZipArchiveEntry) out.createArchiveEntry(path.toFile(),
                            root.relativize(path).toString());
                    out.putArchiveEntry(archiveEntry);
                    if (Files.isSymbolicLink(path)) {
                        archiveEntry.setUnixMode(UnixStat.LINK_FLAG | archiveEntry.getUnixMode());
                        out.write(path.getParent().relativize(Files.readSymbolicLink(path)).toString()
                                .getBytes());
                    } else if (!Files.isDirectory(path)) {
                        out.write(Files.readAllBytes(path));
                    }
                    out.closeArchiveEntry();
                } catch (Exception e) {
                    fail();
                }
            });
        }
        Path unzipped = outRoot.resolve("unzipped");
        Files.createDirectories(unzipped);
        InstallerUtil.unzip(outZip.toFile(), unzipped.toFile(), fop, 1, new FakeProgressIndicator());
        assertEquals("content", new String(Files.readAllBytes(unzipped.resolve("foo"))));
        Path resultDir = unzipped.resolve("bar");
        Path resultFile2 = resultDir.resolve("baz");
        assertEquals("content2", new String(Files.readAllBytes(resultFile2)));
        Path resultLink = unzipped.resolve("link1");
        assertTrue(Files.isDirectory(resultLink));
        assertTrue(Files.isSymbolicLink(resultLink));
        assertTrue(Files.isSameFile(resultLink, resultDir));
        Path resultLink2 = unzipped.resolve("link2");
        assertEquals("content2", new String(Files.readAllBytes(resultLink2)));
        assertTrue(Files.isSymbolicLink(resultLink2));
        assertTrue(Files.isSameFile(resultLink2, resultFile2));
    } finally {
        fop.deleteFileOrFolder(root.toFile());
        fop.deleteFileOrFolder(outRoot.toFile());
    }
}

From source file:com.spectralogic.ds3client.integration.DataIntegrity_Test.java

@Test
public void singleFilePut() throws IOException, URISyntaxException, XmlProcessingException, SignatureException {
    final String bucketName = "single_file_put_test";
    final String book = "beowulf.txt";

    try {/* www  .  ja  v a 2  s. co m*/
        HELPERS.ensureBucketExists(bucketName, envDataPolicyId);

        final Path objPath = ResourceUtils.loadFileResource(Util.RESOURCE_BASE_NAME + book);
        final String digest = DigestUtils.sha256Hex(Files.newInputStream(objPath));
        final Ds3Object obj = new Ds3Object(book, Files.size(objPath));

        final Ds3ClientHelpers.Job putJob = HELPERS.startWriteJob(bucketName, Lists.newArrayList(obj));
        putJob.transfer(new ResourceObjectPutter(Util.RESOURCE_BASE_NAME));

        final Path tempDir = Files.createTempDirectory("ds3_test_");

        final Ds3ClientHelpers.Job getJob = HELPERS.startReadAllJob(bucketName);
        getJob.transfer(new FileObjectGetter(tempDir));

        final String secondDigest = DigestUtils.sha256Hex(Files.newInputStream(tempDir.resolve(book)));
        assertThat(secondDigest, is(equalTo(digest)));
    } finally {
        Util.deleteAllContents(client, bucketName);
    }
}

From source file:com.collaborne.jsonschema.generator.pojo.PojoGeneratorSmokeTest.java

@Test
public void runSmokeTest() throws IOException, CodeGenerationException {
    URI rootUri = URI.create("http://example.com/");

    Path outputDirectory = fs.getPath("output");
    generator.setOutputDirectory(outputDirectory);

    SchemaLoader schemas = loadSchema(rootUri, "/schemas/simple.json");
    generator.setSchemaLoader(schemas);// w w w.  j  av  a  2s  . com

    Mapping rootMapping = new Mapping(URI.create("http://example.com/schemas/simple.json#/definitions/type"),
            new ClassName("com.example.test.schemas", "Type"));
    generator.addMapping(rootMapping.getTarget(), rootMapping);

    generator.generate(rootMapping.getTarget());

    Path generatedTypeFile = outputDirectory.resolve("com/example/test/schemas/Type.java");
    assertTrue(Files.exists(generatedTypeFile));
}

From source file:com.collaborne.jsonschema.generator.pojo.PojoGeneratorSmokeTest.java

@Test
public void runSmokeTestInlineNested() throws IOException, CodeGenerationException {
    // XXX: only really checks #resolve()
    URI rootUri = URI.create("http://example.com/");

    Path outputDirectory = fs.getPath("output");
    generator.setOutputDirectory(outputDirectory);

    SchemaLoader schemas = loadSchema(rootUri, "/schemas/nested-inline.json");
    generator.setSchemaLoader(schemas);/*  w  w  w  . j av a2  s  . c  o  m*/

    Mapping rootMapping = new Mapping(URI.create("http://example.com/schemas/nested-inline.json#"),
            new ClassName("com.example.test.schemas", "WithInline"));
    generator.addMapping(rootMapping.getTarget(), rootMapping);

    generator.generate(rootMapping.getTarget());

    Path generatedTypeFile = outputDirectory.resolve("com/example/test/schemas/WithInline.java");
    assertTrue(Files.exists(generatedTypeFile));
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.Converter.java

/**
 * Saves the html document to a file with .html extension
 *
 * @param document JDOM Document representing the HTML
 * @return written HTML File object//  www.ja  v  a  2 s .co  m
 */
private File saveHtmlFile(Document document) {
    Path tempFilepath = null;

    Path tempDirPath = formulaConverter.getTempDirPath();

    ClassLoader classLoader = getClass().getClassLoader();
    InputStream mainCssIs = classLoader.getResourceAsStream(MAIN_CSS_FILENAME);

    logger.debug("Copying main.css file to temp dir: " + tempDirPath.toAbsolutePath().toString());
    try {
        Files.copy(mainCssIs, tempDirPath.resolve(MAIN_CSS_FILENAME));
    } catch (FileAlreadyExistsException e) {
        // do nothing
    } catch (IOException e) {
        logger.error("could not copy main.css file to temp dir!");
    }

    tempFilepath = tempDirPath.resolve("latex2mobi.html");

    logger.debug("tempFile created at: " + tempFilepath.toAbsolutePath().toString());
    try {
        Files.write(tempFilepath, new XMLOutputter().outputString(document).getBytes(Charset.forName("UTF-8")));

        if (debugMarkupOutput) {
            logger.info("Debug markup will be generated.");
        }

    } catch (IOException e) {
        logger.error("Error writing HTML to temp dir!");
        logger.error(e.getMessage(), e);
    }

    return tempFilepath.toFile();
}

From source file:com.spectralogic.ds3client.integration.DataIntegrity_Test.java

public void sendAndVerifySingleFile(final String bucketName, final String fileName, final long seed,
        final int length) throws IOException, SignatureException, XmlProcessingException {
    try {/* www. ja  v  a2s  . c  o m*/
        HELPERS.ensureBucketExists(bucketName, envDataPolicyId);

        final String digest = DigestUtils.sha256Hex(new RandomDataInputStream(seed, length));
        final Ds3Object obj = new Ds3Object(fileName, length);

        final Ds3ClientHelpers.Job putJob = HELPERS.startWriteJob(bucketName, Lists.newArrayList(obj),
                WriteJobOptions.create()
                        .withMaxUploadSize(PutBulkJobSpectraS3Request.MIN_UPLOAD_SIZE_IN_BYTES));
        putJob.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() {
            @Override
            public SeekableByteChannel buildChannel(final String key) throws IOException {

                final byte[] randomData = IOUtils.toByteArray(new RandomDataInputStream(seed, length));
                final ByteBuffer randomBuffer = ByteBuffer.wrap(randomData);

                final ByteArraySeekableByteChannel channel = new ByteArraySeekableByteChannel(length);
                channel.write(randomBuffer);

                return channel;
            }
        });

        final Path tempDir = Files.createTempDirectory("ds3_test_");

        final Ds3ClientHelpers.Job getJob = HELPERS.startReadAllJob(bucketName);
        getJob.transfer(new FileObjectGetter(tempDir));

        final String secondDigest = DigestUtils.sha256Hex(Files.newInputStream(tempDir.resolve(fileName)));
        assertThat(secondDigest, is(equalTo(digest)));
    } finally {
        Util.deleteAllContents(client, bucketName);
    }
}

From source file:au.org.ands.vocabs.toolkit.provider.harvest.FileHarvestProvider.java

/** Do a harvest. Update the message parameter with the result
 * of the harvest./*w w w  . j  a va2  s  .  co m*/
 * NB: if delete is true, Tomcat must have write access, in order
 * to be able to delete the file successfully. However, a failed
 * deletion will not per se cause the subtask to fail.
 * @param version The version to which access points are to be added.
 * @param format The format of the file(s) to be harvested.
 * @param filePath The path to the file or directory to be harvested.
 * @param outputPath The directory in which to store output files.
 * @param delete True, if successfully harvested files are to be deleted.
 * @param results HashMap representing the result of the harvest.
 * @return True, iff the harvest succeeded.
 */
public final boolean getHarvestFiles(final Version version, final String format, final String filePath,
        final String outputPath, final boolean delete, final HashMap<String, String> results) {
    ToolkitFileUtils.requireDirectory(outputPath);
    Path filePathPath = Paths.get(filePath);
    Path outputPathPath = Paths.get(outputPath);
    if (Files.isDirectory(filePathPath)) {
        logger.debug("Harvesting file(s) from directory " + filePath);
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(filePathPath)) {
            for (Path entry : stream) {
                // Only harvest files. E.g., no recursive
                // directory searching.
                if (Files.isRegularFile(entry)) {
                    logger.debug("Harvesting file:" + entry.toString());
                    Path target = outputPathPath.resolve(entry.getFileName());
                    Files.copy(entry, target, StandardCopyOption.REPLACE_EXISTING);
                    AccessPointUtils.createFileAccessPoint(version, format, target);
                    if (delete) {
                        logger.debug("Deleting file: " + entry.toString());
                        try {
                            Files.delete(entry);
                        } catch (AccessDeniedException e) {
                            logger.error("Unable to delete file: " + entry.toString(), e);
                        }
                    }
                }
            }
        } catch (DirectoryIteratorException | IOException ex) {
            results.put(TaskStatus.EXCEPTION, "Exception in getHarvestFiles while copying file");
            logger.error("Exception in getHarvestFiles while copying file:", ex);
            return false;
        }
    } else {
        logger.debug("Harvesting file: " + filePath);
        try {
            Path target = outputPathPath.resolve(filePathPath.getFileName());
            Files.copy(filePathPath, target, StandardCopyOption.REPLACE_EXISTING);
            AccessPointUtils.createFileAccessPoint(version, format, target);
            if (delete) {
                logger.debug("Deleting file: " + filePathPath.toString());
                try {
                    Files.delete(filePathPath);
                } catch (AccessDeniedException e) {
                    logger.error("Unable to delete file: " + filePathPath.toString(), e);
                }
            }
        } catch (IOException e) {
            results.put(TaskStatus.EXCEPTION, "Exception in getHarvestFiles while copying file");
            logger.error("Exception in getHarvestFiles while copying file:", e);
            return false;
        }
    }
    // If we reached here, success, so return true.
    return true;
}

From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java

@Test
public void testIsSymLinkReturnsTrueForSymLink() throws IOException {
    Path rootPath = tmp.getRoot();
    CreateSymlinksForTests.createSymLink(rootPath.resolve("foo"), rootPath.resolve("bar"));
    assertTrue(filesystem.isSymLink(Paths.get("foo")));
}