Example usage for java.nio.file Path toAbsolutePath

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

Introduction

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

Prototype

Path toAbsolutePath();

Source Link

Document

Returns a Path object representing the absolute path of this path.

Usage

From source file:com.vmware.photon.controller.deployer.dcp.task.CreateManagementVmTaskService.java

private void processConfigIso(State currentState, VmService.State vmState, HostService.State hostState)
        throws Throwable {

    checkState(hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_GATEWAY));
    checkState(hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_IP));
    checkState(hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_NETMASK));
    checkState(//from w  w w  .ja va 2  s  .  co m
            hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_DNS_SERVER));

    String gateway = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_GATEWAY);
    String ipAddress = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_IP);
    String netmask = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_NETMASK);
    String dnsEndpointList = hostState.metadata
            .get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_DNS_SERVER);
    if (!Strings.isNullOrEmpty(dnsEndpointList)) {
        dnsEndpointList = Stream.of(dnsEndpointList.split(",")).map((dnsServer) -> "DNS=" + dnsServer + "\n")
                .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
    }

    DeployerContext deployerContext = HostUtils.getDeployerContext(this);
    String scriptDirectory = deployerContext.getScriptDirectory();

    String userDataConfigFileContent = new String(
            Files.readAllBytes(Paths.get(scriptDirectory, "user-data.template")), StandardCharsets.UTF_8)
                    .replace("$GATEWAY", gateway)
                    .replace("$ADDRESS", new SubnetUtils(ipAddress, netmask).getInfo().getCidrSignature())
                    .replace("$DNS", dnsEndpointList);

    if (currentState.ntpEndpoint != null) {
        userDataConfigFileContent = userDataConfigFileContent.replace("$NTP", currentState.ntpEndpoint);
    }

    String metadataConfigFileContent = new String(
            Files.readAllBytes(Paths.get(scriptDirectory, "meta-data.template")), StandardCharsets.UTF_8)
                    .replace("$INSTANCE_ID", vmState.name).replace("$LOCAL_HOSTNAME", vmState.name);

    Path vmConfigDirectoryPath = Files.createTempDirectory("iso-" + currentState.vmId).toAbsolutePath();
    Path userDataConfigFilePath = vmConfigDirectoryPath.resolve("user-data.yml");
    Files.write(userDataConfigFilePath, userDataConfigFileContent.getBytes(StandardCharsets.UTF_8));
    Path metadataConfigFilePath = vmConfigDirectoryPath.resolve("meta-data.yml");
    Files.write(metadataConfigFilePath, metadataConfigFileContent.getBytes(StandardCharsets.UTF_8));
    Path isoFilePath = vmConfigDirectoryPath.resolve("config.iso");

    List<String> command = new ArrayList<>();
    command.add("./" + SCRIPT_NAME);
    command.add(isoFilePath.toAbsolutePath().toString());
    command.add(userDataConfigFilePath.toAbsolutePath().toString());
    command.add(metadataConfigFilePath.toAbsolutePath().toString());
    command.add(currentState.serviceConfigDirectory);

    File scriptLogFile = new File(deployerContext.getScriptLogDirectory(), SCRIPT_NAME + "-" + vmState.vmId
            + "-" + ServiceUtils.getIDFromDocumentSelfLink(currentState.documentSelfLink) + ".log");

    ScriptRunner scriptRunner = new ScriptRunner.Builder(command, deployerContext.getScriptTimeoutSec())
            .directory(deployerContext.getScriptDirectory())
            .redirectOutput(ProcessBuilder.Redirect.to(scriptLogFile)).build();

    ListenableFutureTask<Integer> futureTask = ListenableFutureTask.create(scriptRunner);
    HostUtils.getListeningExecutorService(this).submit(futureTask);
    Futures.addCallback(futureTask, new FutureCallback<Integer>() {
        @Override
        public void onSuccess(@javax.validation.constraints.NotNull Integer result) {
            try {
                if (result != 0) {
                    logScriptErrorAndFail(currentState, result, scriptLogFile);
                } else {
                    State patchState = buildPatch(TaskState.TaskStage.STARTED, TaskState.SubStage.ATTACH_ISO,
                            null);
                    patchState.vmConfigDirectory = vmConfigDirectoryPath.toAbsolutePath().toString();
                    TaskUtils.sendSelfPatch(CreateManagementVmTaskService.this, patchState);
                }
            } catch (Throwable t) {
                failTask(t);
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
            failTask(throwable);
        }
    });
}

From source file:de.dal33t.powerfolder.Controller.java

/**
 * Migrate config dir (if necessary) in Windows from user.home to APPDATA.
 * Pre Version 4, the config was in 'user.home'/.PowerFolder.
 * 'APPDATA'/PowerFolder is a more normal Windows location for application
 * data./*w w w . ja  v a 2  s.c  om*/
 *
 * @param unixBaseDir
 *            the old user.home based config directory.
 * @param windowsBaseDir
 *            the preferred APPDATA based config directory.
 */
private static boolean migrateWindowsMiscLocation(Path unixBaseDir, Path windowsBaseDir) {
    if (Files.notExists(windowsBaseDir)) {
        try {
            Files.createDirectories(windowsBaseDir);
        } catch (IOException ioe) {
            log.severe("Failed to create " + windowsBaseDir.toAbsolutePath().toString() + ". " + ioe);
        }
    }
    try {
        PathUtils.recursiveMove(unixBaseDir, windowsBaseDir);
        log.warning("Migrated config from " + unixBaseDir + " to " + windowsBaseDir);
        return true;
    } catch (IOException e) {
        log.warning("Failed to migrate config from " + unixBaseDir + " to " + windowsBaseDir + ". " + e);
        return false;
    }
}

From source file:org.ng200.openolympus.cerberus.executors.JavaExecutor.java

@Override
public ExecutionResult execute(final Path program) throws IOException {

    final Path chrootRoot = this.storage.getPath().resolve("chroot");

    final Path chrootedProgram = chrootRoot.resolve(program.getFileName().toString());

    FileAccess.createDirectories(chrootedProgram);
    FileAccess.copyDirectory(program, chrootedProgram, StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.COPY_ATTRIBUTES);

    final Path outOfMemoryFile = chrootRoot.resolve("outOfMemory");

    final Path policyFile = this.storage.getPath().resolve("olymp.policy");

    try (Stream<Path> paths = FileAccess.walkPaths(storage.getPath())) {
        paths.forEach(path -> {//from  www  .j  av a  2 s. c  o m
            try {
                Files.setPosixFilePermissions(path,
                        new HashSet<PosixFilePermission>(
                                Lists.from(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ,
                                        PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_EXECUTE,
                                        PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE,
                                        PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.OTHERS_READ)));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    this.buildPolicy(chrootRoot, policyFile);

    final CommandLine commandLine = new CommandLine("sudo");
    commandLine.addArgument("olympus_watchdog");

    this.setUpOlrunnerLimits(commandLine);

    commandLine.addArgument("--security=0");
    commandLine.addArgument("--jail=/");

    commandLine.addArgument("--");

    commandLine.addArgument("/usr/bin/java");

    commandLine.addArgument("-classpath");
    commandLine.addArgument(chrootedProgram.toAbsolutePath().toString());
    commandLine.addArgument("-Djava.security.manager");
    commandLine.addArgument("-Djava.security.policy=" + policyFile.toAbsolutePath().toString());

    commandLine.addArgument("-Xmx" + this.getMemoryLimit());
    commandLine.addArgument("-Xms" + this.getMemoryLimit());

    commandLine.addArgument(MessageFormat.format("-XX:OnOutOfMemoryError=touch {0}; echo \"\" > {0}",
            outOfMemoryFile.toAbsolutePath().toString()), false);

    commandLine.addArgument("Main");

    final DefaultExecutor executor = new DefaultExecutor();

    executor.setWatchdog(new ExecuteWatchdog(20000)); // 20 seconds for the
    // sandbox to
    // complete
    executor.setWorkingDirectory(chrootRoot.toFile());

    executor.setStreamHandler(new PumpStreamHandler(this.outputStream, this.errorStream, this.inputStream));
    try {
        executor.execute(commandLine);
    } catch (final IOException e) {
        if (!e.getMessage().toLowerCase().equals("stream closed")) {
            throw e;
        }
    }
    final ExecutionResult readOlrunnerVerdict = this.readOlrunnerVerdict(chrootRoot.resolve("verdict.txt"));

    if (FileAccess.exists(outOfMemoryFile)) {
        readOlrunnerVerdict.setResultType(ExecutionResultType.MEMORY_LIMIT);
    }

    readOlrunnerVerdict.setMemoryPeak(this.getMemoryLimit());

    return readOlrunnerVerdict;
}

From source file:org.elasticsearch.test.ElasticsearchIntegrationTest.java

/**
 * Asserts that there are no files in the specified path
 *//*from w ww  .ja  v a 2 s  . com*/
public void assertPathHasBeenCleared(Path path) throws Exception {
    logger.info("--> checking that [{}] has been cleared", path);
    int count = 0;
    StringBuilder sb = new StringBuilder();
    sb.append("[");
    if (Files.exists(path)) {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
            for (Path file : stream) {
                logger.info("--> found file: [{}]", file.toAbsolutePath().toString());
                if (Files.isDirectory(file)) {
                    assertPathHasBeenCleared(file);
                } else if (Files.isRegularFile(file)) {
                    count++;
                    sb.append(file.toAbsolutePath().toString());
                    sb.append("\n");
                }
            }
        }
    }
    sb.append("]");
    assertThat(count + " files exist that should have been cleaned:\n" + sb.toString(), count, equalTo(0));
}

From source file:de.dal33t.powerfolder.Controller.java

/**
 * Answers the path, where to load/store temp files created by PowerFolder.
 *
 * @return the file base, a directory//from www  . j a  v  a2  s.com
 */
public static Path getTempFilesLocation() {
    Path base = Paths.get(System.getProperty("java.io.tmpdir"));
    if (Files.notExists(base)) {
        try {
            Files.createDirectories(base);
        } catch (IOException ioe) {
            log.warning(
                    "Could not create temp files location '" + base.toAbsolutePath().toString() + "'. " + ioe);
        }
    }
    return base;
}

From source file:org.apache.solr.handler.IndexFetcher.java

/**
 * The tlog files are moved from the tmp dir to the tlog dir as an atomic filesystem operation.
 * A backup of the old directory is maintained. If the directory move fails, it will try to revert back the original
 * tlog directory.//from w w w.j  a  v a 2 s  .  c om
 */
private boolean copyTmpTlogFiles2Tlog(File tmpTlogDir) {
    Path tlogDir = FileSystems.getDefault().getPath(solrCore.getUpdateHandler().getUpdateLog().getLogDir());
    Path backupTlogDir = FileSystems.getDefault().getPath(tlogDir.getParent().toAbsolutePath().toString(),
            tmpTlogDir.getName());

    try {
        Files.move(tlogDir, backupTlogDir, StandardCopyOption.ATOMIC_MOVE);
    } catch (IOException e) {
        SolrException.log(LOG, "Unable to rename: " + tlogDir + " to: " + backupTlogDir, e);
        return false;
    }

    Path src = FileSystems.getDefault().getPath(backupTlogDir.toAbsolutePath().toString(),
            tmpTlogDir.getName());
    try {
        Files.move(src, tlogDir, StandardCopyOption.ATOMIC_MOVE);
    } catch (IOException e) {
        SolrException.log(LOG, "Unable to rename: " + src + " to: " + tlogDir, e);

        // In case of error, try to revert back the original tlog directory
        try {
            Files.move(backupTlogDir, tlogDir, StandardCopyOption.ATOMIC_MOVE);
        } catch (IOException e2) {
            // bad, we were not able to revert back the original tlog directory
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                    "Unable to rename: " + backupTlogDir + " to: " + tlogDir);
        }

        return false;
    }

    return true;
}

From source file:com.qwazr.library.archiver.ArchiverTool.java

public void extract(final Path sourceFile, final Path destDir) throws IOException, ArchiveException {
    try (final InputStream is = new BufferedInputStream(Files.newInputStream(sourceFile))) {
        try (final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(is)) {
            ArchiveEntry entry;//from  w  w w .  j  a  va  2s.  c  om
            while ((entry = in.getNextEntry()) != null) {
                if (!in.canReadEntryData(entry))
                    continue;
                if (entry.isDirectory()) {
                    final Path newDir = destDir.resolve(entry.getName());
                    if (!Files.exists(newDir))
                        Files.createDirectory(newDir);
                    continue;
                }
                if (entry instanceof ZipArchiveEntry)
                    if (((ZipArchiveEntry) entry).isUnixSymlink())
                        continue;
                final Path destFile = destDir.resolve(entry.getName());
                final Path parentDir = destFile.getParent();
                if (!Files.exists(parentDir))
                    Files.createDirectories(parentDir);
                final long entryLastModified = entry.getLastModifiedDate().getTime();
                if (Files.exists(destFile) && Files.isRegularFile(destFile)
                        && Files.getLastModifiedTime(destFile).toMillis() == entryLastModified
                        && entry.getSize() == Files.size(destFile))
                    continue;
                IOUtils.copy(in, destFile);
                Files.setLastModifiedTime(destFile, FileTime.fromMillis(entryLastModified));
            }
        } catch (IOException e) {
            throw new IOException("Unable to extract the archive: " + sourceFile.toAbsolutePath(), e);
        }
    } catch (ArchiveException e) {
        throw new ArchiveException("Unable to extract the archive: " + sourceFile.toAbsolutePath(), e);
    }
}

From source file:fll.web.FullTournamentTest.java

/**
 * Load the teams from testDataConnection.
 * //from   w  ww  .  j  a  v a2 s.  c  o  m
 * @param testDataConnection where to get the teams from
 * @param outputDirectory where to write the teams file, may be null in which
 *          case a temp file will be used
 * @throws IOException
 * @throws SQLException
 * @throws InterruptedException 
 */
private void loadTeams(final Connection testDataConnection, final Tournament sourceTournament,
        final Path outputDirectory) throws IOException, SQLException, InterruptedException {

    final Path teamsFile = outputDirectory.resolve(sanitizeFilename(sourceTournament.getName()) + "_teams.csv");
    // write the teams out to a file
    try (final Writer writer = new FileWriter(teamsFile.toFile())) {
        try (final CSVWriter csvWriter = new CSVWriter(writer)) {
            csvWriter.writeNext(new String[] { "team_name", "team_number", "affiliation", "award_group",
                    "judging_group", "tournament" });
            final Map<Integer, TournamentTeam> sourceTeams = Queries.getTournamentTeams(testDataConnection,
                    sourceTournament.getTournamentID());
            for (final Map.Entry<Integer, TournamentTeam> entry : sourceTeams.entrySet()) {
                final TournamentTeam team = entry.getValue();

                csvWriter.writeNext(new String[] { team.getTeamName(), Integer.toString(team.getTeamNumber()),
                        team.getOrganization(), team.getAwardGroup(), team.getJudgingGroup(),
                        sourceTournament.getName() });
            }
        }
    }

    IntegrationTestUtils.loadPage(selenium, TestUtils.URL_ROOT + "admin/");

    selenium.findElement(By.id("teams_file")).sendKeys(teamsFile.toAbsolutePath().toString());

    selenium.findElement(By.id("upload_teams")).click();

    IntegrationTestUtils.assertNoException(selenium);

    // skip past the filter page
    selenium.findElement(By.id("next")).click();
    IntegrationTestUtils.assertNoException(selenium);

    // team column selection
    new Select(selenium.findElement(By.name("TeamNumber"))).selectByValue("team_number");
    new Select(selenium.findElement(By.name("TeamName"))).selectByValue("team_name");
    new Select(selenium.findElement(By.name("Organization"))).selectByValue("affiliation");
    new Select(selenium.findElement(By.name("tournament"))).selectByValue("tournament");
    new Select(selenium.findElement(By.name("event_division"))).selectByValue("award_group");
    new Select(selenium.findElement(By.name("judging_station"))).selectByValue("judging_group");
    selenium.findElement(By.id("next")).click();
    IntegrationTestUtils.assertNoException(selenium);
    Assert.assertTrue(IntegrationTestUtils.isElementPresent(selenium, By.id("success")));
}

From source file:org.ballerinalang.docgen.docs.BallerinaDocGenerator.java

/**
 * Generates {@link BLangPackage} objects for each Ballerina package from the given ballerina files.
 *
 * @param sourceRoot    points to the folder relative to which package path is given
 * @param packagePath   a {@link Path} object pointing either to a ballerina file or a folder with ballerina files.
 * @param packageFilter comma separated list of package names/patterns to be filtered from the documentation.
 * @param isNative      whether the given packages are native or not.
 * @param offline is offline generation//from   w w  w . j  a v  a  2  s  .  c  o m
 * @return a map of {@link BLangPackage} objects. Key - Ballerina package name Value - {@link BLangPackage}
 * @throws IOException on error.
 */
protected static Map<String, PackageDoc> generatePackageDocsFromBallerina(String sourceRoot, Path packagePath,
        String packageFilter, boolean isNative, boolean offline) throws IOException {

    // find the Module.md file
    Path packageMd;
    Path absolutePkgPath = Paths.get(sourceRoot).resolve(packagePath);
    Optional<Path> o = Files.find(absolutePkgPath, 1, (path, attr) -> {
        Path fileName = path.getFileName();
        if (fileName != null) {
            return fileName.toString().equals(MODULE_CONTENT_FILE);
        }
        return false;
    }).findFirst();

    packageMd = o.isPresent() ? o.get() : null;

    // find the resources of the package
    Path resourcesDirPath = absolutePkgPath.resolve("resources");
    List<Path> resources = new ArrayList<>();
    if (resourcesDirPath.toFile().exists()) {
        resources = Files.walk(resourcesDirPath).filter(path -> !path.equals(resourcesDirPath))
                .collect(Collectors.toList());
    }

    BallerinaDocDataHolder dataHolder = BallerinaDocDataHolder.getInstance();
    if (!isNative) {
        // This is necessary to be true in order to Ballerina to work properly
        System.setProperty("skipNatives", "true");
    }

    BLangPackage bLangPackage;
    CompilerContext context = new CompilerContext();
    CompilerOptions options = CompilerOptions.getInstance(context);
    options.put(CompilerOptionName.PROJECT_DIR, sourceRoot);
    options.put(CompilerOptionName.COMPILER_PHASE, CompilerPhase.TYPE_CHECK.toString());
    options.put(CompilerOptionName.PRESERVE_WHITESPACE, "false");
    options.put(CompilerOptionName.OFFLINE, Boolean.valueOf(offline).toString());
    options.put(CompilerOptionName.EXPERIMENTAL_FEATURES_ENABLED, Boolean.TRUE.toString());

    context.put(SourceDirectory.class, new FileSystemProjectDirectory(Paths.get(sourceRoot)));

    Compiler compiler = Compiler.getInstance(context);

    // TODO: Remove this and the related constants once these are properly handled in the core
    if (absolutePkgPath.endsWith(BAL_BUILTIN.toString())) {
        bLangPackage = loadBuiltInPackage(context);
    } else {
        // compile the given package
        Path fileOrPackageName = packagePath.getFileName();
        bLangPackage = compiler
                .compile(fileOrPackageName == null ? packagePath.toString() : fileOrPackageName.toString());
    }

    if (bLangPackage == null) {
        out.println(String.format("docerina: invalid Ballerina module: %s", packagePath));
    } else {
        String packageName = packageNameToString(bLangPackage.packageID);
        if (isFilteredPackage(packageName, packageFilter)) {
            if (BallerinaDocUtils.isDebugEnabled()) {
                out.println("docerina: module " + packageName + " excluded");
            }
        } else {
            dataHolder.getPackageMap().put(packageName, new PackageDoc(
                    packageMd == null ? null : packageMd.toAbsolutePath(), resources, bLangPackage));
        }
    }
    return dataHolder.getPackageMap();
}

From source file:org.tinymediamanager.core.movie.entities.Movie.java

/**
 * Searches for actor images, and matches them to our "actors", updating the thumb url
 * /*from   w w  w.j  av a  2  s. com*/
 * @deprecated thumbPath is generated dynamic - no need for storage
 */
@Deprecated
public void findActorImages() {
    if (MovieModuleManager.MOVIE_SETTINGS.isWriteActorImages()) {
        // get all files from the actors path
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(getPathNIO())) {
            for (Path path : directoryStream) {
                if (Utils.isRegularFile(path)) {

                    for (MovieActor actor : getActors()) {
                        if (StringUtils.isBlank(actor.getThumbPath())) {
                            // yay, actor with empty image
                            String name = actor.getNameForStorage();
                            if (name.equals(path.getFileName().toString())) {
                                actor.setThumbPath(path.toAbsolutePath().toString());
                            }
                        }
                    }

                }
            }
        } catch (IOException ex) {
        }
    }
}