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:cc.kave.commons.pointsto.evaluation.ProjectTrainValidateEvaluation.java

public void export(Path dir, ResultExporter exporter) throws IOException {
    exporter.export(dir.resolve("TrainValidate.txt"), getResults().entrySet().stream()
            .flatMap(e -> e.getValue().stream().map(er -> ImmutablePair.of(e.getKey(), er))).map(p -> {
                return new String[] { CoReNames.vm2srcQualifiedType(p.left), p.right.training,
                        p.right.validation, String.format(Locale.US, "%.3f", p.right.score),
                        Integer.toString(p.right.numTrainingUsages),
                        Integer.toString(p.right.numValidationUsages) };
            }));/*from  w  ww  .  j a v a 2 s . c o m*/
}

From source file:io.syndesis.verifier.LocalProcessVerifier.java

private String getConnectorClasspath(Connector connector) throws IOException, InterruptedException {
    byte[] pom = new byte[0]; // TODO: Fix generation to use an Action projectGenerator.generatePom(connector);
    java.nio.file.Path tmpDir = Files.createTempDirectory("syndesis-connector");
    try {//from   w  ww  . j  a  va 2  s.c o  m
        Files.write(tmpDir.resolve("pom.xml"), pom);
        ArrayList<String> args = new ArrayList<>();
        args.add("mvn");
        args.add("org.apache.maven.plugins:maven-dependency-plugin:3.0.0:build-classpath");
        if (localMavenRepoLocation != null) {
            args.add("-Dmaven.repo.local=" + localMavenRepoLocation);
        }
        ProcessBuilder builder = new ProcessBuilder().command(args)
                .redirectError(ProcessBuilder.Redirect.INHERIT).directory(tmpDir.toFile());
        Map<String, String> environment = builder.environment();
        environment.put("MAVEN_OPTS", "-Xmx64M");
        Process mvn = builder.start();
        try {
            String result = parseClasspath(mvn.getInputStream());
            if (mvn.waitFor() != 0) {
                throw new IOException(
                        "Could not get the connector classpath, mvn exit value: " + mvn.exitValue());
            }
            return result;
        } finally {
            mvn.getInputStream().close();
            mvn.getOutputStream().close();
        }
    } finally {
        FileSystemUtils.deleteRecursively(tmpDir.toFile());
    }
}

From source file:io.crate.rest.AdminUIHttpIntegrationTest.java

@Before
public void setup() throws ExecutionException, InterruptedException, IOException {
    Iterable<HttpServerTransport> transports = internalCluster().getInstances(HttpServerTransport.class);
    Iterator<HttpServerTransport> httpTransports = transports.iterator();
    address = ((InetSocketTransportAddress) httpTransports.next().boundAddress().publishAddress()).address();
    // place index file
    final Path indexDirectory = internalCluster().getInstance(Environment.class).libFile().resolve("site");
    Files.createDirectories(indexDirectory);
    final Path indexFile = indexDirectory.resolve("index.html");
    Files.write(indexFile, Collections.singletonList("<h1>Crate Admin</h1>"), Charset.forName("UTF-8"));
}

From source file:com.liferay.sync.engine.util.FileUtilTest.java

@Test
public void testIsIgnoredFilePath() throws Exception {
    Path filePath = Files.createTempDirectory("test");

    for (String ignoredFileName : PropsValues.SYNC_FILE_IGNORE_NAMES) {
        Path ignoredFilePath = filePath.resolve(StringEscapeUtils.unescapeJava(ignoredFileName));

        Assert.assertTrue(FileUtil.isIgnoredFilePath(ignoredFilePath));
    }//from   www  .  j  a  va2s.  co m
}

From source file:com.arturmkrtchyan.kafka.util.TarUnpacker.java

/**
 * Unpack data from the stream to specified directory.
 *
 * @param in        stream with tar data
 * @param outputPath destination path//  www. j ava2  s  .com
 * @return true in case of success, otherwise - false
 */
protected boolean unpack(final TarArchiveInputStream in, final Path outputPath) throws IOException {
    TarArchiveEntry entry;
    while ((entry = in.getNextTarEntry()) != null) {
        final Path entryPath = outputPath.resolve(entry.getName());
        if (entry.isDirectory()) {
            if (!Files.exists(entryPath)) {
                Files.createDirectories(entryPath);
            }
        } else if (entry.isFile()) {
            try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryPath))) {
                IOUtils.copy(in, out);
                setPermissions(entry.getMode(), entryPath);
            }
        }
    }
    return true;
}

From source file:io.undertow.server.handlers.accesslog.AccessLogFileTestCase.java

@Test
public void testLogLotsOfThreads() throws IOException, InterruptedException, ExecutionException {
    Path directory = logDirectory;
    Path logFileName = directory.resolve("server2.log");

    DefaultAccessLogReceiver logReceiver = new DefaultAccessLogReceiver(DefaultServer.getWorker(), directory,
            "server2.");
    CompletionLatchHandler latchHandler;
    DefaultServer.setRootHandler(latchHandler = new CompletionLatchHandler(NUM_REQUESTS * NUM_THREADS,
            new AccessLogHandler(HELLO_HANDLER, logReceiver, "REQ %{i,test-header}",
                    AccessLogFileTestCase.class.getClassLoader())));

    ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
    try {/*from   ww w . ja  v a2s .c  o  m*/

        final List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < NUM_THREADS; ++i) {
            final int threadNo = i;
            futures.add(executor.submit(new Runnable() {
                @Override
                public void run() {
                    TestHttpClient client = new TestHttpClient();
                    try {
                        for (int i = 0; i < NUM_REQUESTS; ++i) {
                            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
                            get.addHeader("test-header", "thread-" + threadNo + "-request-" + i);
                            HttpResponse result = client.execute(get);
                            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                            final String response = HttpClientUtils.readResponse(result);
                            Assert.assertEquals("Hello", response);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        client.getConnectionManager().shutdown();
                    }
                }
            }));
        }
        for (Future<?> future : futures) {
            future.get();
        }

    } finally {
        executor.shutdown();
    }
    latchHandler.await();
    logReceiver.awaitWrittenForTest();
    String completeLog = new String(Files.readAllBytes(logFileName));
    for (int i = 0; i < NUM_THREADS; ++i) {
        for (int j = 0; j < NUM_REQUESTS; ++j) {
            Assert.assertTrue(completeLog.contains("REQ thread-" + i + "-request-" + j));
        }
    }

}

From source file:com.liferay.sync.engine.util.FileUtilTest.java

@Test
public void testRenameFile() throws Exception {
    Path sourceFilePath = Files.createTempFile("test", null);

    Path parentFilePath = sourceFilePath.getParent();

    String sourceFilePathFileName = String.valueOf(sourceFilePath.getFileName());

    Path targetFilePath = parentFilePath.resolve(sourceFilePathFileName.toUpperCase());

    FileUtil.moveFile(sourceFilePath, targetFilePath);

    Path realFilePath = targetFilePath.toRealPath();

    Path realFilePathFileName = realFilePath.getFileName();

    Assert.assertFalse(sourceFilePath.endsWith(realFilePathFileName));
    Assert.assertTrue(targetFilePath.endsWith(realFilePathFileName));
}

From source file:com.netflix.spinnaker.clouddriver.artifacts.ivy.IvyArtifactCredentialsTest.java

private void assertDownloadArtifact(@TempDirectory.TempDir Path tempDir, String ivySettingsXml)
        throws IOException {
    IvyArtifactAccount account = new IvyArtifactAccount();
    account.setSettings(IvySettings.parse(ivySettingsXml));

    Path cache = tempDir.resolve("cache");
    Files.createDirectories(cache);

    Artifact artifact = new Artifact();
    artifact.setReference("com.test:app:1.0");

    assertThat(new IvyArtifactCredentials(account, () -> cache).download(artifact))
            .hasSameContentAs(new ByteArrayInputStream("contents".getBytes(Charsets.UTF_8)));
    assertThat(cache).doesNotExist();/*from   w  w w .  j av a 2  s.  co m*/
}

From source file:io.redlink.solrlib.standalone.SolrServerConnector.java

@Override
@SuppressWarnings("squid:S3776")
protected void init(ExecutorService executorService) throws IOException, SolrServerException {
    Preconditions.checkState(initialized.compareAndSet(false, true));
    Preconditions.checkArgument(Objects.nonNull(solrBaseUrl));

    if (configuration.isDeployCores() && Objects.nonNull(configuration.getSolrHome())) {
        final Path solrHome = configuration.getSolrHome();
        Files.createDirectories(solrHome);
        final Path libDir = solrHome.resolve("lib");
        Files.createDirectories(libDir);

        try (HttpSolrClient solrClient = new HttpSolrClient.Builder(solrBaseUrl).build()) {
            for (SolrCoreDescriptor coreDescriptor : coreDescriptors) {
                final String coreName = coreDescriptor.getCoreName();
                if (availableCores.containsKey(coreName)) {
                    log.warn("CoreName-Clash: {} already initialized. Skipping {}", coreName,
                            coreDescriptor.getClass());
                    continue;
                }/*from  w w w  . j  av a 2 s  .  c o m*/
                final String remoteName = createRemoteName(coreName);

                final Path coreHome = solrHome.resolve(remoteName);
                coreDescriptor.initCoreDirectory(coreHome, libDir);

                final Path corePropertiesFile = coreHome.resolve("core.properties");
                // core.properties is created by the CreateCore-Command.
                Files.deleteIfExists(corePropertiesFile);

                if (coreDescriptor.getNumShards() > 1 || coreDescriptor.getReplicationFactor() > 1) {
                    log.warn("Deploying {} to SolrServerConnector, ignoring config of shards={},replication={}",
                            coreName, coreDescriptor.getNumShards(), coreDescriptor.getReplicationFactor());
                }

                // Create or reload the core
                if (CoreAdminRequest.getStatus(remoteName, solrClient).getStartTime(remoteName) == null) {
                    final CoreAdminResponse adminResponse = CoreAdminRequest.createCore(remoteName,
                            coreHome.toAbsolutePath().toString(), solrClient);
                } else {
                    final CoreAdminResponse adminResponse = CoreAdminRequest.reloadCore(remoteName, solrClient);
                }
                // schedule client-side core init
                final boolean isNewCore = findInNamedList(
                        CoreAdminRequest.getStatus(remoteName, solrClient).getCoreStatus(remoteName), "index",
                        "lastModified") == null;
                scheduleCoreInit(executorService, coreDescriptor, isNewCore);

                availableCores.put(coreName, coreDescriptor);
            }
        }
    } else {
        try (HttpSolrClient solrClient = new HttpSolrClient.Builder(solrBaseUrl).build()) {
            for (SolrCoreDescriptor coreDescriptor : coreDescriptors) {
                final String coreName = coreDescriptor.getCoreName();
                if (availableCores.containsKey(coreName)) {
                    log.warn("CoreName-Clash: {} already initialized. Skipping {}", coreName,
                            coreDescriptor.getClass());
                    continue;
                }
                final String remoteName = createRemoteName(coreName);
                if (CoreAdminRequest.getStatus(remoteName, solrClient).getStartTime(remoteName) == null) {
                    // Core does not exists
                    log.warn("Collection {} (remote: {}) not available in Solr '{}' "
                            + "but deployCores is set to false", coreName, remoteName, solrBaseUrl);
                } else {
                    log.debug("Collection {} exists in Solr '{}' as {}", coreName, solrBaseUrl, remoteName);
                    scheduleCoreInit(executorService, coreDescriptor, false);
                    availableCores.put(coreName, coreDescriptor);
                }
            }
        }
    }
}

From source file:it.tidalwave.bluemarine2.downloader.impl.SimpleHttpCacheStorage.java

/*******************************************************************************************************************
 *
 * //from  ww  w .ja  v a 2 s  .  c  o m
 *
 ******************************************************************************************************************/
/* VisibleForTesting */ boolean isCachedResourcePresent(final @Nonnull String key)
        throws MalformedURLException {
    final Path cachePath = getCacheItemPath(new URL(key));
    final Path cacheHeadersPath = cachePath.resolve(PATH_HEADERS);
    final Path cacheContentPath = cachePath.resolve(PATH_CONTENT);
    log.trace(">>>> probing cached entry at {}", cachePath);

    return exists(cacheHeadersPath) && exists(cacheContentPath);
}