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.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java

@Override
public void copy(UrlTreeMetaData<InputStream> metadata, String dstDir, UrlTreeContext ctx)
        throws BadContentException {

    String srcPathName = metadata.getAbsolutePath();
    Path srcPath = this.generateFileObj(srcPathName);
    Path dstPath = this.generateFileObj(dstDir);

    logger.debug("copy: " + srcPath.toAbsolutePath() + " to " + dstPath.toAbsolutePath());

    try {//from www .  ja v  a 2 s  . c  o  m
        Files.copy(srcPath, dstPath.resolve(srcPath.getFileName()), StandardCopyOption.COPY_ATTRIBUTES,
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new GenericResourceException("cannot copy file", e);
    }
}

From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java

@Override
public void move(UrlTreeMetaData<InputStream> metadata, String dstDir, UrlTreeContext ctx)
        throws BadContentException {

    String srcPathName = metadata.getAbsolutePath();
    Path srcPath = this.generateFileObj(srcPathName);
    Path dstPath = this.generateFileObj(dstDir);

    logger.debug("move: " + srcPath.toAbsolutePath() + " to " + dstPath.toAbsolutePath());

    try {/*from  w ww  . j ava2s  .c  om*/
        Files.move(srcPath, dstPath.resolve(srcPath.getFileName()), StandardCopyOption.ATOMIC_MOVE,
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new GenericResourceException("cannot copy file", e);
    }
}

From source file:com.gooddata.dataset.DatasetService.java

/**
 * Loads dataset into platform. Uploads given dataset and manifest to staging area and triggers ETL pull.
 * The call is asynchronous returning {@link com.gooddata.FutureResult} to let caller wait for results.
 * Uploaded files are deleted from staging area when finished.
 *
 * @param project  project to which dataset belongs
 * @param manifest dataset manifest/*  ww w  . j av  a2  s .  co m*/
 * @param dataset  dataset to upload
 * @return {@link com.gooddata.FutureResult} of the task, which can throw {@link com.gooddata.dataset.DatasetException}
 * in case the ETL pull task fails
 * @throws com.gooddata.dataset.DatasetException if there is a problem to serialize manifest or upload dataset
 */
public FutureResult<Void> loadDataset(final Project project, final DatasetManifest manifest,
        final InputStream dataset) {
    notNull(project, "project");
    notNull(dataset, "dataset");
    notNull(manifest, "manifest");
    final Path dirPath = Paths.get("/", project.getId() + "_" + RandomStringUtils.randomAlphabetic(3), "/");
    try {
        dataStoreService.upload(dirPath.resolve(manifest.getFile()).toString(), dataset);
        final String manifestJson = mapper.writeValueAsString(manifest);
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(manifestJson.getBytes(UTF_8));
        dataStoreService.upload(dirPath.resolve(MANIFEST_FILE_NAME).toString(), inputStream);

        return pullLoad(project, dirPath, manifest.getDataSet());
    } catch (IOException e) {
        throw new DatasetException("Unable to serialize manifest", manifest.getDataSet(), e);
    } catch (DataStoreException | GoodDataRestException | RestClientException e) {
        throw new DatasetException("Unable to load", manifest.getDataSet(), e);
    }
}

From source file:dk.dma.msinm.common.repo.RepositoryService.java

/**
 * Returns a unique file name in the given folder.
 * If the given file name is not unique, a new is constructed
 * by adding a number to the file name/*  w w w . j a  va 2 s .  c  om*/
 * @param folder the folder
 * @param name the file name
 * @return the new unique file
 */
private Path getUniqueFile(Path folder, String name) {
    Path file = folder.resolve(name);
    if (Files.exists(file)) {
        for (int x = 2; true; x++) {
            String fileName = FilenameUtils.removeExtension(name) + " " + x + "."
                    + FilenameUtils.getExtension(name);
            file = folder.resolve(fileName);
            if (!Files.exists(file)) {
                break;
            }
        }
    }
    return file;
}

From source file:com.gitpitch.services.OfflineService.java

private int buildZip(PitchParams pp, Path zipRoot) {

    /*//from w ww.  j av a  2  s . c  o  m
     * Remove PITCHME_ONLINE_MD from zip directory.
     */
    Path onlinePath = zipRoot.resolve(PITCHME_ONLINE_PATH);
    diskService.delete(onlinePath);

    /*
     * CMD: zip -r PITCHME.zip PITCHME
     */
    String[] cmd = { ZIP_CMD, ZIP_QUIET, ZIP_ALL, PITCHME_ZIP, ZIP_ROOT_DIR };

    Path zipWd = diskService.ensure(pp, pp.pitchme);
    return shellService.exec(ZIP_CMD, pp, zipWd, cmd);
}

From source file:it.sonarlint.cli.LanguageTest.java

@Test
public void testRunTwice() throws IOException {
    Path project = sonarlint.deployProject("java-sample");
    int code = sonarlint.run(project);
    assertThat(code).isEqualTo(0);//ww w .  jav  a  2s  .c o m

    assertThat(sonarlint.getOut()).contains("11 issues");
    assertThat(sonarlint.getOut()).contains("1 critical");
    assertThat(sonarlint.getOut()).contains("5 major");
    assertThat(sonarlint.getOut()).contains("5 minor");
    assertThat(sonarlint.getOut()).contains("2 files analyzed");

    FileUtils.deleteDirectory(project.resolve(".sonarlint").toFile());
    code = sonarlint.run(project);
    assertThat(code).isEqualTo(0);

    assertThat(sonarlint.getOut()).contains("11 issues");
    assertThat(sonarlint.getOut()).contains("1 critical");
    assertThat(sonarlint.getOut()).contains("5 major");
    assertThat(sonarlint.getOut()).contains("5 minor");
    assertThat(sonarlint.getOut()).contains("2 files analyzed");
}

From source file:io.syndesis.project.converter.DefaultProjectGeneratorTest.java

@Test
public void testMapper() throws Exception {
    Step step1 = new SimpleStep.Builder().stepKind("endpoint")
            .connection(new Connection.Builder().configuredProperties(map()).build())
            .configuredProperties(map("period", 5000))
            .action(new Action.Builder().connectorId("timer").camelConnectorPrefix("periodic-timer-connector")
                    .camelConnectorGAV("io.syndesis:timer-connector:" + CONNECTORS_VERSION).build())
            .build();/*w  ww .  j a v  a 2 s  .  com*/

    Step step2 = new SimpleStep.Builder().stepKind("mapper").configuredProperties(map("atlasmapping", "{}"))
            .build();

    Step step3 = new SimpleStep.Builder().stepKind("endpoint")
            .connection(new Connection.Builder().configuredProperties(Collections.emptyMap()).build())
            .configuredProperties(map("httpUri", "http://localhost:8080/bye"))
            .action(new Action.Builder().connectorId("http").camelConnectorPrefix("http-post-connector")
                    .camelConnectorGAV("io.syndesis:http-post-connector:" + CONNECTORS_VERSION).build())
            .build();

    GenerateProjectRequest request = new GenerateProjectRequest.Builder().integration(new Integration.Builder()
            .id("test-integration").name("Test Integration").steps(Arrays.asList(step1, step2, step3)).build())
            .connectors(connectors).build();

    ProjectGeneratorProperties generatorProperties = new ProjectGeneratorProperties(mavenProperties);
    generatorProperties.getTemplates().setOverridePath(this.basePath);
    generatorProperties.getTemplates().getAdditionalResources().addAll(this.additionalResources);

    Path runtimePath = generate(request, generatorProperties);
    runtimePath.toFile().deleteOnExit();

    assertFileContents(generatorProperties, runtimePath.resolve("src/main/resources/syndesis.yml"),
            "test-mapper-syndesis.yml");
    assertThat(new String(Files.readAllBytes(runtimePath.resolve("src/main/resources/mapping-step-2.json"))))
            .isEqualTo("{}");
}

From source file:be.samey.io.ServerConn.java

public void connect() throws InterruptedException, IOException {

    /*----------------------------------------------------------------------
     1) create output directory//from  w w  w.ja  v a2s .  c om
     */
    //if the user clicked the checkbox to save the output, then the archive
    //downloaded from the server is saved in the directory specified by the
    //user. If the user does not want to save the output, then the archive
    //is downloaded to a temp folder.
    Path outPath;
    if (cyModel.getSaveFilePath() == null) {
        outPath = Files.createTempDirectory("Cev_archive");
    } else {
        outPath = cyModel.getSaveFilePath();
    }

    String fileExtension = ".tgz";
    String archiveName = cyModel.getTitle();

    Path archivePath = outPath.resolve(archiveName + fileExtension);
    //prevent overwriting the same file if the user forgot to change the
    //title
    if (Files.exists(archivePath)) {
        archivePath = outPath.resolve(archiveName + "_" + CyAppManager.getTimeStamp() + fileExtension);
    }

    /*----------------------------------------------------------------------
     2) Upload user files and settings, download response
     */
    //make multipart entity with user data and settings
    HttpEntity postEntity = makeEntity(cyModel.getBaits(), cyModel.getSpeciesNames(), cyModel.getSpeciesPaths(),
            cyModel.getPCutoff(), cyModel.getNCutoff(), cyModel.getOrthGroupNames(),
            cyModel.getOrthGroupPaths());

    //run the app on the server
    executeAppOnSever(CyModel.URL, postEntity, archivePath);

    /*----------------------------------------------------------------------
     4) Unpack files to temp dir
     */
    //create a temp folder to store the network files
    Path unpackPath = Files.createTempDirectory("Cev_netw");
    //unpack the network files
    Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.GZIP);
    File archive = archivePath.toFile();
    ArchiveStream stream = archiver.stream(archive);
    ArchiveEntry entry;

    Path sifPath = null;
    Path noaPath = null;
    Path edaPath = null;
    Path logPath = null;
    File netwFile;
    while ((entry = stream.getNextEntry()) != null) {
        netwFile = entry.extract(unpackPath.toFile());
        if (netwFile.toString().endsWith(".sif")) {
            sifPath = netwFile.toPath();
        }
        if (netwFile.toString().endsWith(".node.attr")) {
            noaPath = netwFile.toPath();
        }
        if (netwFile.toString().endsWith(".edge.attr")) {
            edaPath = netwFile.toPath();
        }
        if (netwFile.toString().endsWith("_log")) {
            logPath = netwFile.toPath();
        }
    }
    stream.close();

    /*----------------------------------------------------------------------
     5) update corestatus with network paths
     */
    //TODO: sanity checks
    cyModel.setSifPath(sifPath);
    cyModel.setNoaPath(noaPath);
    cyModel.setEdaPath(edaPath);
    cyModel.setLogPath(logPath);

}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

/**
 * Tests the reloading of SSLContext when the trust store is modified. The same store is used as a TrustStore (for the
 * reloadable SSLContext used in the HTTPClient) and as a KeyStore for the MockWebServer
 *//*w ww .  j a  v a  2  s .c om*/
public void testReloadingTrustStore() throws Exception {
    Path tempDir = createTempDir();
    Path trustStorePath = tempDir.resolve("testnode.jks");
    Path updatedTruststorePath = tempDir.resolve("testnode_updated.jks");
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.jks"),
            trustStorePath);
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.jks"),
            updatedTruststorePath);
    MockSecureSettings secureSettings = new MockSecureSettings();
    secureSettings.setString("xpack.ssl.truststore.secure_password", "testnode");
    Settings settings = Settings.builder().put("xpack.ssl.truststore.path", trustStorePath)
            .put("path.home", createTempDir()).setSecureSettings(secureSettings).build();
    Environment env = randomBoolean() ? null : TestEnvironment.newEnvironment(settings);
    // Create the MockWebServer once for both pre and post checks
    try (MockWebServer server = getSslServer(trustStorePath, "testnode")) {
        final Consumer<SSLContext> trustMaterialPreChecks = (context) -> {
            try (CloseableHttpClient client = HttpClients.custom().setSSLContext(context).build()) {
                privilegedConnect(
                        () -> client.execute(new HttpGet("https://localhost:" + server.getPort())).close());
            } catch (Exception e) {
                throw new RuntimeException("Error connecting to the mock server", e);
            }
        };

        final Runnable modifier = () -> {
            try {
                atomicMoveIfPossible(updatedTruststorePath, trustStorePath);
            } catch (Exception e) {
                throw new RuntimeException("failed to modify file", e);
            }
        };

        // Client's truststore doesn't contain the server's certificate anymore so SSLHandshake should fail
        final Consumer<SSLContext> trustMaterialPostChecks = (updatedContext) -> {
            try (CloseableHttpClient client = HttpClients.custom().setSSLContext(updatedContext).build()) {
                SSLHandshakeException sslException = expectThrows(SSLHandshakeException.class,
                        () -> privilegedConnect(() -> client
                                .execute(new HttpGet("https://localhost:" + server.getPort())).close()));
                assertThat(sslException.getCause().getMessage(), containsString("PKIX path building failed"));
            } catch (Exception e) {
                throw new RuntimeException("Error closing CloseableHttpClient", e);
            }
        };
        validateSSLConfigurationIsReloaded(settings, env, trustMaterialPreChecks, modifier,
                trustMaterialPostChecks);
    }
}

From source file:de.tiqsolutions.hdfs.HadoopFileSystemProvider.java

private void remoteCopy(Path source, Path target, CopyOption... options) throws IOException {
    Configuration configuration = getConfiguration();
    Path tmp = target.getParent();
    Path dest = null;/*from   www.  java2s  . c  om*/
    do {
        dest = tmp.resolve(String.format("tmp%s/", System.currentTimeMillis()));
    } while (Files.exists(dest));
    try {
        DistCpOptions distCpOptions = new DistCpOptions(
                Arrays.asList(((HadoopFileSystemPath) source).getPath()),
                ((HadoopFileSystemPath) dest).getPath());
        List<CopyOption> optionList = Arrays.asList(options);

        distCpOptions.setOverwrite(optionList.contains(StandardCopyOption.REPLACE_EXISTING));
        try {
            DistCp distCp = new DistCp(configuration, distCpOptions);
            Job job = distCp.execute();
            job.waitForCompletion(true);
        } catch (Exception e) {
            throw new IOException(e.getLocalizedMessage(), e);
        }
        move(dest.resolve(source.getFileName()), target, options);
    } finally {
        delete(dest, false);
    }

}