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:io.undertow.server.handlers.file.FileHandlerSymlinksTestCase.java

@Test
public void testRelativePathSymlinkFilter() throws IOException, URISyntaxException {
    TestHttpClient client = new TestHttpClient();
    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
    Path newSymlink = rootPath.resolve("newSymlink");

    try {//from  ww w . j av  a2  s .  com
        DefaultServer.setRootHandler(new CanonicalPathHandler().setNext(new PathHandler().addPrefixPath("/path",
                new ResourceHandler(new PathResourceManager(newSymlink, 10485760, true, "innerDir"))
                        .setDirectoryListingEnabled(false).addWelcomeFiles("page.html"))));
        /**
         * This request should return a 200, innerSymlink is a symlink pointed to innerDir
         */
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/innerSymlink/page.html");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:edu.usc.goffish.gofs.util.partitioning.metis.MetisPartitioner.java

@Override
public IPartitioning partition(IIdentifiableVertexGraph<? extends IIdentifiableVertex, ? extends IEdge> graph,
        int numPartitions) throws IOException {
    if (graph == null) {
        throw new IllegalArgumentException();
    }/*from  ww w  . ja  va  2  s .co m*/
    if (numPartitions < 1) {
        throw new IllegalArgumentException();
    }
    if (graph.isDirected()) {
        throw new IllegalArgumentException();
    }

    Path workingDir = Files.createTempDirectory("gofs_metis");
    try {
        // we assume the graph will always require renumbering
        System.out.print("writing metis input file (with renumbering)... ");
        long time = System.currentTimeMillis();

        // write metis input
        Path metisInputPath = workingDir.resolve(DefaultMetisInput);
        long[] renumbering = MetisGraph.writeAndRenumber(graph, Files.newOutputStream(metisInputPath));

        System.out.println("[" + (System.currentTimeMillis() - time) + "ms]");

        // perform partitioning
        Path metisOutputPath = partition(workingDir, metisInputPath, numPartitions);

        System.out.print("loading metis output... ");
        time = System.currentTimeMillis();

        // read metis output
        IPartitioning partitioning = MetisPartitioning.readAndRenumber(Files.newInputStream(metisOutputPath),
                renumbering);

        System.out.println("[" + (System.currentTimeMillis() - time) + "ms]");

        return partitioning;
    } finally {
        FileUtils.deleteQuietly(workingDir.toFile());
    }
}

From source file:com.jejking.hh.nord.corpus.DrucksachenHtmlFetcher.java

/**
* Schedules tasks to fetch all the specified URLs leaving a random duration between the 
* execution of each task. //from  w w w . ja  v a  2  s .  co m
* 
* @param urlsToFetch
* @param storageDirectory
*/
public void fetchUrls(final ImmutableList<URL> urlsToFetch, final Path storageDirectory) {

    Observable<Runnable> tasks = Observable.from(urlsToFetch).filter(new Func1<URL, Boolean>() {

        @Override
        public Boolean call(URL url) {
            String encodedUrl = fileNameFromUrl(url) + ".gz";
            Path filePath = storageDirectory.resolve(encodedUrl);
            // retain only URLs for which we have no record yet so as not to download them twice
            return Files.notExists(filePath, LinkOption.NOFOLLOW_LINKS);
        }

    }).map(new Func1<URL, Runnable>() {
        @Override
        public Runnable call(final URL url) {
            return new Runnable() {

                @Override
                public void run() {

                    try {
                        File target = storageDirectory.resolve(fileNameFromUrl(url) + ".gz").toFile();
                        try (GzipCompressorOutputStream outputStream = new GzipCompressorOutputStream(
                                new BufferedOutputStream(new FileOutputStream(target)))) {
                            Resources.copy(url, outputStream);
                            System.out.println("Copied " + url + " to " + target);
                        }

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

                }
            };

        };
    });

    tasks.subscribe(new Action1<Runnable>() {

        Random random = new Random();
        long cumulativeDelayInSeconds = 0;
        int count = 0;

        @Override
        public void call(Runnable runnable) {
            count++;
            DrucksachenHtmlFetcher.this.scheduledExecutorService.schedule(runnable, cumulativeDelayInSeconds,
                    TimeUnit.SECONDS);
            // at least two seconds, at most 10
            cumulativeDelayInSeconds = cumulativeDelayInSeconds + 2 + random.nextInt(9);
            DrucksachenHtmlFetcher.this.totalDelayHolder[0] = cumulativeDelayInSeconds;
            DrucksachenHtmlFetcher.this.actualCount[0] = count;
        }

    });

    System.out.println("Scheduled " + actualCount[0] + " tasks");
    System.out.println("Estimated duration " + totalDelayHolder[0] + " seconds");

    try {
        this.scheduledExecutorService.shutdown();
        // + 60 to allow task to finish comfortably...
        boolean finishedOK = this.scheduledExecutorService.awaitTermination(this.totalDelayHolder[0] + 60,
                TimeUnit.SECONDS);
        if (finishedOK) {
            System.out.println("Finished all tasks. Scheduled executor service shutdown.");
        } else {
            System.out.println("Executor service shutdown, but not all tasks completed.");
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

From source file:io.undertow.server.handlers.file.FileHandlerSymlinksTestCase.java

@Test
public void testExplicitAccessSymlinkGranted() throws IOException, URISyntaxException {
    TestHttpClient client = new TestHttpClient();
    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
    Path newSymlink = rootPath.resolve("newSymlink");

    try {//w  w  w .ja  v  a  2s  .  com
        DefaultServer.setRootHandler(new CanonicalPathHandler().setNext(new PathHandler().addPrefixPath("/path",
                new ResourceHandler(new PathResourceManager(newSymlink, 10485760, true, "/"))
                        .setDirectoryListingEnabled(false).addWelcomeFiles("page.html"))));
        /**
         * This request should return a 200 code as "/" can be used to grant all symbolic links paths
         */
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/innerSymlink/page.html");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Header[] headers = result.getHeaders("Content-Type");
        Assert.assertEquals("text/html", headers[0].getValue());
        Assert.assertTrue(response, response.contains("A web page"));
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:io.undertow.server.handlers.file.FileHandlerSymlinksTestCase.java

@Test
public void testExplicitAccessSymlinkGrantedUsingSpecificFilters() throws IOException, URISyntaxException {
    TestHttpClient client = new TestHttpClient();
    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
    Path newSymlink = rootPath.resolve("newSymlink");

    try {// w w  w  .  java2 s  .  c om
        DefaultServer.setRootHandler(new CanonicalPathHandler().setNext(new PathHandler().addPrefixPath("/path",
                new ResourceHandler(new PathResourceManager(newSymlink, 10485760, true,
                        rootPath.toAbsolutePath().toString().concat("/newDir")))
                                .setDirectoryListingEnabled(false).addWelcomeFiles("page.html"))));
        /**
         * This request should return a 200 code as rootPath + "/newDir" is used in the safePaths
         */
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/innerSymlink/page.html");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Header[] headers = result.getHeaders("Content-Type");
        Assert.assertEquals("text/html", headers[0].getValue());
        Assert.assertTrue(response, response.contains("A web page"));
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:io.undertow.server.handlers.file.FileHandlerSymlinksTestCase.java

@Test
public void testResourceManagerBaseSymlink() throws IOException, URISyntaxException {
    TestHttpClient client = new TestHttpClient();
    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
    Path newSymlink = rootPath.resolve("newSymlink");

    try {//from  w  w w .  j av  a2 s .c o  m
        DefaultServer.setRootHandler(new CanonicalPathHandler().setNext(new PathHandler().addPrefixPath("/path",
                new ResourceHandler(new PathResourceManager(newSymlink, 10485760, true, ""))
                        .setDirectoryListingEnabled(false).addWelcomeFiles("page.html"))));
        /**
         * This request should return a 200, base is a symlink but it should not be checked in the symlinks filter
         */
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/page.html");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        /**
         * A readResponse() is needed in order to release connection and execute next get.
         */
        HttpClientUtils.readResponse(result);

        /**
         * This request should return a 404 code as rootPath + "/innerSymlink" is not matching in symlinks filter"
         */
        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/innerSymlink/page.html");
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.NOT_FOUND, result.getStatusLine().getStatusCode());
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:io.undertow.server.handlers.file.FileHandlerSymlinksTestCase.java

@Test
public void testExplicitAccessSymlinkDeniedForInsideSymlinks() throws IOException, URISyntaxException {
    TestHttpClient client = new TestHttpClient();
    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
    Path newSymlink = rootPath.resolve("newDir");

    try {//from w  w w.j  av  a 2s  .  co  m
        DefaultServer.setRootHandler(new CanonicalPathHandler().setNext(new PathHandler().addPrefixPath("/path",
                new ResourceHandler(new PathResourceManager(newSymlink, 10485760, true, ""))
                        .setDirectoryListingEnabled(false).addWelcomeFiles("page.html"))));
        /**
         * This request should return a 200 code as not symbolic links on path
         */
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/innerDir/page.html");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Header[] headers = result.getHeaders("Content-Type");
        Assert.assertEquals("text/html", headers[0].getValue());
        Assert.assertTrue(response, response.contains("A web page"));

        /**
         * This request should return a 404 error, followLinks is true, but empty "" safePaths forbids all symbolics paths
         */
        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/innerSymlink/page.html");
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.NOT_FOUND, result.getStatusLine().getStatusCode());

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:io.undertow.server.handlers.file.FileHandlerSymlinksTestCase.java

@Test
public void testExplicitAccessSymlinkGrantedUsingSpecificFiltersWithDirectoryListingEnabled()
        throws IOException, URISyntaxException {

    HttpParams params = new SyncBasicHttpParams();
    DefaultHttpClient.setDefaultHttpParams(params);
    HttpConnectionParams.setSoTimeout(params, 300000);

    TestHttpClient client = new TestHttpClient(params);

    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
    Path newSymlink = rootPath.resolve("newSymlink");

    try {/*from   ww w .  j a  va  2s  .  co  m*/
        DefaultServer.setRootHandler(new PathHandler().addPrefixPath("/path",
                new ResourceHandler(new PathResourceManager(newSymlink, 10485760, true,
                        rootPath.toAbsolutePath().toString().concat("/newDir")))
                                .setDirectoryListingEnabled(false).addWelcomeFiles("page.html")));
        /**
         * This request should return a 200 code as rootPath + "/newDir" is used in the safePaths
         */
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/innerSymlink/.");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Header[] headers = result.getHeaders("Content-Type");
        Assert.assertEquals("text/html", headers[0].getValue());
        Assert.assertTrue(response, response.contains("A web page"));
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.liferay.blade.cli.command.InstallExtensionCommandTest.java

@Test
public void testInstallCustomExtensionTwiceOverwrite() throws Exception {
    String jarName = _sampleCommandJarFile.getName();

    File extensionJar = new File(_extensionsDir, jarName);

    String[] args = { "extension", "install", _sampleCommandJarFile.getAbsolutePath() };

    Path extensionPath = extensionJar.toPath();

    BladeTestResults bladeTestResults = TestUtil.runBlade(_rootDir, _extensionsDir, args);

    String output = bladeTestResults.getOutput();

    _testJarsDiff(_sampleCommandJarFile, extensionJar);

    Assert.assertTrue("Expected output to contain \"successful\"\n" + output, output.contains(" successful"));
    Assert.assertTrue(output.contains(jarName));

    File tempDir = temporaryFolder.newFolder("overwrite");

    Path tempPath = tempDir.toPath();

    Path sampleCommandPath = tempPath.resolve(_sampleCommandJarFile.getName());

    Files.copy(_sampleCommandJarFile.toPath(), sampleCommandPath, StandardCopyOption.COPY_ATTRIBUTES,
            StandardCopyOption.REPLACE_EXISTING);

    File sampleCommandFile = sampleCommandPath.toFile();

    sampleCommandFile.setLastModified(0);

    args = new String[] { "extension", "install", sampleCommandFile.getAbsolutePath() };

    output = _testBladeWithInteractive(_rootDir, _extensionsDir, args, "y");

    _testJarsDiff(sampleCommandFile, extensionJar);

    Assert.assertTrue("Expected output to contain \"Overwrite\"\n" + output, output.contains("Overwrite"));
    boolean assertCorrect = output.contains(" installed successfully");

    if (!assertCorrect) {
        Assert.assertTrue("Expected output to contain \"installed successfully\"\n" + output, assertCorrect);
    }//  ww  w . j a  va2 s .  co m

    File extensionFile = extensionPath.toFile();

    Assert.assertEquals(sampleCommandFile.lastModified(), extensionFile.lastModified());
}

From source file:com.google.cloud.runtimes.builder.buildsteps.docker.StageDockerArtifactBuildStep.java

@Override
protected void doBuild(Path directory, Map<String, String> metadata) throws BuildStepException {
    try {/*from   w  w  w.  j a v a 2  s.  c  o  m*/
        // TODO wrap this in a try block and log a more friendly message if not found
        Path artifact = getArtifact(directory, metadata);
        logger.info("Found artifact {}", artifact);

        // make staging dir
        Path stagingDir = directory.resolve(DOCKER_STAGING_DIR);
        if (Files.exists(stagingDir)) {
            logger.info("Found a docker staging directory in provided sources. Cleaning {}",
                    stagingDir.toString());
            FileUtils.deleteDirectory(stagingDir.toFile());
        }
        Files.createDirectory(stagingDir);
        metadata.put(BuildStepMetadataConstants.DOCKER_STAGING_PATH, stagingDir.toString());

        logger.info("Preparing docker files in {}", stagingDir);

        // copy the artifact into the staging dir
        Files.copy(artifact, stagingDir.resolve(artifact.getFileName()));

        // copy the .dockerignore file into staging dir, if it exists
        Path dockerIgnoreFile = directory.resolve(DOCKER_IGNORE_FILE);
        if (Files.isRegularFile(dockerIgnoreFile)) {
            Files.copy(dockerIgnoreFile, stagingDir.resolve(DOCKER_IGNORE_FILE));
        }

        // Generate dockerfile
        String dockerfile = dockerfileGenerator.generateDockerfile(artifact.getFileName());
        Path dockerFileDest = stagingDir.resolve("Dockerfile");

        try (BufferedWriter writer = Files.newBufferedWriter(dockerFileDest, StandardCharsets.US_ASCII)) {
            writer.write(dockerfile);
        }
    } catch (IOException | ArtifactNotFoundException | TooManyArtifactsException e) {
        throw new BuildStepException(e);
    }
}