Example usage for java.nio.file Path toString

List of usage examples for java.nio.file Path toString

Introduction

In this page you can find the example usage for java.nio.file Path toString.

Prototype

String toString();

Source Link

Document

Returns the string representation of this path.

Usage

From source file:com.pawandubey.griffin.model.Page.java

/**
 * Creates a Page instance with the parameters.
 *
 * @param title/*from  w w w. j a  va  2 s .c o m*/
 * @param auth
 * @param loc
 * @param cont
 * @param img
 * @param slu
 * @param lay
 * @param tag
 */
public Page(String title, String auth, Path loc, String cont, String img, String slu, String lay,
        List<String> tag) {
    author = auth;
    this.title = title;
    location = loc.toString();
    setContent(cont);
    slug = slu;
    layout = lay;
    tags = tag;
    featuredImage = img;
}

From source file:io.syndesis.git.GitWorkflow.java

/**
 * Updates an existing git repository with the current version of project files.
 *
 * @param remoteGitRepoHttpUrl- the HTML (not ssh) url to a git repository
 * @param repoName              - the name of the git repository
 * @param author                author//w  w w  .  ja  va 2 s  . c  o m
 * @param message-              commit message
 * @param files-                map of file paths along with their content
 * @param credentials-          Git credentials, for example username/password, authToken, personal access token
 */
public void updateFiles(String remoteGitRepoHttpUrl, String repoName, User author, String message,
        Map<String, byte[]> files, UsernamePasswordCredentialsProvider credentials) {

    // create temporary directory
    try {
        Path workingDir = Files.createTempDirectory(Paths.get(gitProperties.getLocalGitRepoPath()), repoName);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created temporary directory {}", workingDir.toString());
        }

        // git clone
        Git git = Git.cloneRepository().setDirectory(workingDir.toFile()).setURI(remoteGitRepoHttpUrl).call();
        writeFiles(workingDir, files);

        commitAndPush(git, authorName(author), author.getEmail(), message, credentials);
        removeWorkingDir(workingDir);
    } catch (IOException | GitAPIException e) {
        throw SyndesisServerException.launderThrowable(e);
    }
}

From source file:com.netflix.spinnaker.halyard.deploy.services.v1.GenerateService.java

/**
 * Generate config for a given deployment.
 *
 * This involves a few steps:// w w w.  j  av  a2s .  com
 *
 *   1. Clear out old config generated in a prior run.
 *   2. Generate configuration using the halconfig as the source of truth, while collecting files needed by
 *      the deployment.
 *
 * @param deploymentName is the deployment whose config to generate
 * @param services is the list of services to generate configs for
 * @return a mapping from components to the profile's required local files.
 */
public ResolvedConfiguration generateConfig(String deploymentName, List<SpinnakerService.Type> services) {
    DaemonTaskHandler.newStage("Generating all Spinnaker profile files and endpoints");
    log.info("Generating config from \"" + halconfigPath + "\" with deploymentName \"" + deploymentName + "\"");
    File spinnakerStaging = halconfigDirectoryStructure.getStagingPath(deploymentName).toFile();
    DeploymentConfiguration deploymentConfiguration = deploymentService
            .getDeploymentConfiguration(deploymentName);

    DaemonTaskHandler.message("Building service endpoints");
    SpinnakerServiceProvider<DeploymentDetails> serviceProvider = serviceProviderFactory
            .create(deploymentConfiguration);
    SpinnakerRuntimeSettings runtimeSettings = serviceProvider.buildRuntimeSettings(deploymentConfiguration);

    // Step 1.
    try {
        FileUtils.deleteDirectory(spinnakerStaging);
    } catch (IOException e) {
        throw new HalException(new ConfigProblemBuilder(Severity.FATAL,
                "Unable to clear old spinnaker config: " + e.getMessage() + ".").build());
    }

    Path userProfilePath = halconfigDirectoryStructure.getUserProfilePath(deploymentName);
    List<String> userProfileNames = aggregateProfilesInPath(userProfilePath.toString(), "");

    // Step 2.
    Map<SpinnakerService.Type, Map<String, Profile>> serviceProfiles = new HashMap<>();
    for (SpinnakerService service : serviceProvider.getServices()) {
        boolean isDesiredService = services.stream().filter(s -> s.equals(service.getType())).count() > 0;

        if (!isDesiredService) {
            continue;
        }

        ServiceSettings settings = runtimeSettings.getServiceSettings(service);
        if (settings == null || !settings.getEnabled()) {
            continue;
        }

        List<Profile> profiles = service.getProfiles(deploymentConfiguration, runtimeSettings);

        String pluralModifier = profiles.size() == 1 ? "" : "s";
        String profileMessage = "Generated " + profiles.size() + " profile" + pluralModifier;
        Map<String, Profile> outputProfiles = processProfiles(spinnakerStaging, profiles);

        List<Profile> customProfiles = userProfileNames.stream()
                .map(s -> (Optional<Profile>) service.customProfile(deploymentConfiguration, runtimeSettings,
                        Paths.get(userProfilePath.toString(), s), s))
                .filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());

        pluralModifier = customProfiles.size() == 1 ? "" : "s";
        profileMessage += " and discovered " + customProfiles.size() + " custom profile" + pluralModifier
                + " for " + service.getCanonicalName();
        DaemonTaskHandler.message(profileMessage);
        outputProfiles.putAll(processProfiles(spinnakerStaging, customProfiles));

        serviceProfiles.put(service.getType(), outputProfiles);
    }

    return new ResolvedConfiguration().setServiceProfiles(serviceProfiles).setRuntimeSettings(runtimeSettings);
}

From source file:com.spectralogic.ds3client.helpers.FileObjectGetter_Test.java

@Test
public void testThatFileReportsAsRegularOnWindows() throws IOException, InterruptedException {
    Assume.assumeTrue(Platform.isWindows());

    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final String A_FILE_NAME = "aFile.txt";

    final AtomicBoolean caughtException = new AtomicBoolean(false);

    try {//from ww  w  . ja v a2 s  .  c om
        Files.createFile(Paths.get(tempDirectory.toString(), A_FILE_NAME));
        new FileObjectGetter(tempDirectory).buildChannel(A_FILE_NAME);
    } catch (final UnrecoverableIOException e) {
        assertTrue(e.getMessage().contains(A_FILE_NAME));
        caughtException.set(true);
    } finally {
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }

    assertFalse(caughtException.get());
}

From source file:com.thoughtworks.go.server.service.plugins.AnalyticsPluginAssetsServiceTest.java

@Test
public void onPluginMetadataUnLoad_shouldClearExistingCacheAssets() throws Exception {
    railsRoot = temporaryFolder.newFolder();
    Path pluginDirPath = Paths.get(railsRoot.getAbsolutePath(), "public", "assets", "plugins", PLUGIN_ID);

    Path path = Paths.get(pluginDirPath.toString(), "foo.txt");
    FileUtils.forceMkdirParent(path.toFile());
    Files.write(path, "hello".getBytes());

    assertTrue(pluginDirPath.toFile().exists());
    assertTrue(path.toFile().exists());// w  w  w.  j  a v  a 2s .com

    when(servletContext.getInitParameter("rails.root")).thenReturn("rails-root");
    when(servletContext.getRealPath("rails-root")).thenReturn(railsRoot.getAbsolutePath());
    when(extension.canHandlePlugin(PLUGIN_ID)).thenReturn(true);

    assetsService.onPluginMetadataRemove(PLUGIN_ID);

    assertFalse(path.toFile().exists());
    assertFalse(pluginDirPath.toFile().exists());
}

From source file:io.pravega.segmentstore.storage.impl.extendeds3.S3FileSystemImpl.java

private void addFileAsObjectToList(Path path, ArrayList<S3Object> list, String bucketName) {
    S3Object object = new S3Object();
    object.setKey(path.toString().replaceFirst(Paths.get(this.baseDir, bucketName).toString(), ""));
    list.add(object);//from w w w  .j  a va2 s .co  m
}

From source file:org.wte4j.ui.server.services.TemplateServiceIntegrationTest.java

@Test
public void saveTemplateData() throws URISyntaxException, IOException {
    Template<TemplateDto> template = createAndPersistTestTemplate();

    TemplateDto dto = new TemplateDto();
    dto.setDocumentName(template.getDocumentName());
    dto.setLanguage(template.getLanguage());

    MappingDto mappingDto = new MappingDto();
    mappingDto.setModelKey("documentName");
    mappingDto.setContentControlKey("template");
    dto.getMapping().add(mappingDto);/*from ww  w . j a v a  2 s .com*/

    Path filePath = Paths.get(getClass().getResource("template.docx").toURI());
    templateService.saveTemplateData(dto, filePath.toString());

    Template<TemplateDto> updatedTemplate = engine.getTemplateRepository().getTemplate("test", "en",
            TemplateDto.class);
    File updatedTemplateFile = File.createTempFile("updated-template", "docx");
    updatedTemplateFile.deleteOnExit();

    updatedTemplate.write(updatedTemplateFile);
    assertTrue(Arrays.equals(Files.readAllBytes(filePath), Files.readAllBytes(updatedTemplateFile.toPath())));
}

From source file:com.github.ffremont.microservices.springboot.node.tasks.InstallTaskTest.java

@Test
public void testRunDetectChecksumOk() throws Exception {
    MicroServiceTask msTask = this.create();

    doNothing().when(mockInstallJarTask).run(anyObject());
    doNothing().when(mockInstallPropertiesTask).run(anyObject());

    Path msVersionFolder = Paths.get(this.nodeBase, msTask.getMs().getName(), msTask.getMs().getVersion());
    Files.createDirectories(msVersionFolder);
    when(helper.targetDirOf(anyObject())).thenReturn(msVersionFolder);

    Path checksumPath = Paths.get(msVersionFolder.toString(), InstallTask.CHECKSUM_FILE_NAME + ".txt");
    Files.write(checksumPath, msTask.getMs().getSha1().getBytes());

    task.run(msTask);/*from   w w w.  j  a  v  a  2s.com*/

    verify(mockInstallJarTask, times(0)).run(anyObject());
    verify(mockInstallPropertiesTask, times(1)).run(anyObject());
}

From source file:io.syndesis.git.GitWorkflow.java

/**
 * Creates a new remote git repository and does the initial commit&push of all the project files
 * the files to it.//  w  ww  .j a v a2  s.  c  o  m
 *
 * @param remoteGitRepoHttpUrl- the HTML (not ssh) url to a git repository
 * @param repoName              - the name of the git repository
 * @param author                author
 * @param message-              commit message
 * @param files-                map of file paths along with their content
 * @param credentials-          Git credentials, for example username/password, authToken, personal access token
 */
public void createFiles(String remoteGitRepoHttpUrl, String repoName, User author, String message,
        Map<String, byte[]> files, UsernamePasswordCredentialsProvider credentials) {

    try {
        // create temporary directory
        Path workingDir = Files.createTempDirectory(Paths.get(gitProperties.getLocalGitRepoPath()), repoName);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created temporary directory {}", workingDir.toString());
        }

        // git init
        Git git = Git.init().setDirectory(workingDir.toFile()).call();
        writeFiles(workingDir, files);

        RemoteAddCommand remoteAddCommand = git.remoteAdd();
        remoteAddCommand.setName("origin");
        remoteAddCommand.setUri(new URIish(remoteGitRepoHttpUrl));
        remoteAddCommand.call();

        commitAndPush(git, authorName(author), author.getEmail(), message, credentials);
        removeWorkingDir(workingDir);
    } catch (IOException | GitAPIException | URISyntaxException e) {
        throw SyndesisServerException.launderThrowable(e);
    }
}

From source file:org.fcrepo.importexport.integration.BagItIT.java

@Test
public void testExportBag() throws Exception {
    final String exampleID = UUID.randomUUID().toString();
    final URI uri = URI.create(serverAddress + exampleID);

    final FcrepoResponse response = create(uri);
    assertEquals(SC_CREATED, response.getStatusCode());
    assertEquals(uri, response.getLocation());

    final Config config = new Config();
    config.setMode("export");
    config.setBaseDirectory(TARGET_DIR + File.separator + exampleID);
    config.setIncludeBinaries(true);//from   w w w .j  a v a2 s  .c  om
    config.setResource(uri);
    config.setPredicates(new String[] { CONTAINS.toString() });
    config.setRdfExtension(DEFAULT_RDF_EXT);
    config.setRdfLanguage(DEFAULT_RDF_LANG);
    config.setUsername(USERNAME);
    config.setPassword(PASSWORD);
    config.setBagProfile(DEFAULT_BAG_PROFILE);
    config.setBagConfigPath("src/test/resources/configs/bagit-config.yml");
    new Exporter(config, clientBuilder).run();

    final Path target = Paths.get(TARGET_DIR, exampleID);
    assertTrue(target.resolve("bagit.txt").toFile().exists());
    assertTrue(target.resolve("manifest-sha1.txt").toFile().exists());

    final Path dataDir = target.resolve("data");
    assertTrue(dataDir.toFile().exists());
    assertTrue(dataDir.toFile().isDirectory());

    final Path resourceFile = Paths.get(dataDir.toString(), uri.getPath() + DEFAULT_RDF_EXT);
    assertTrue(resourceFile.toFile().exists());

    final FcrepoResponse response1 = clientBuilder.build().get(uri).perform();
    final MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
    final byte[] buf = new byte[8192];
    int read = 0;
    while ((read = response1.getBody().read(buf)) != -1) {
        sha1.update(buf, 0, read);
    }

    final String checksum = new String(encodeHex(sha1.digest()));
    final BufferedReader reader = new BufferedReader(
            new FileReader(target.resolve("manifest-sha1.txt").toFile()));
    final String checksumLine = reader.readLine();
    reader.close();
    assertEquals(checksum, checksumLine.split(" ")[0]);
}