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.ethercamp.harmony.service.BlockchainInfoService.java

/**
 * Get free space of disk where project located.
 * Verified on multi disk Windows./*from  w w  w.  j a  v a 2  s.  c om*/
 * Not tested against sym links
 */
private long getFreeDiskSpace() {
    final File currentDir = new File(".");
    for (Path root : FileSystems.getDefault().getRootDirectories()) {
        //            log.debug(root.toAbsolutePath() + " vs current " + currentDir.getAbsolutePath());
        try {
            final FileStore store = Files.getFileStore(root);

            final boolean isCurrentDirBelongsToRoot = Paths.get(currentDir.getAbsolutePath())
                    .startsWith(root.toAbsolutePath());
            if (isCurrentDirBelongsToRoot) {
                final long usableSpace = store.getUsableSpace();
                //                    log.debug("Disk available:" + readableFileSize(usableSpace)
                //                            + ", total:" + readableFileSize(store.getTotalSpace()));
                return usableSpace;
            }
        } catch (IOException e) {
            log.error("Problem querying space: " + e.toString());
        }
    }
    return 0;
}

From source file:com.payex.utils.formatter.FormatExecutor.java

public void executeOnSet(List<Path> filenames) {
    long startClock = System.currentTimeMillis();

    createResourceCollection();//w  w w.j a  va2s .  c om

    List<File> files = new ArrayList<File>();

    for (Path fn : filenames) {
        files.add(new File(fn.toAbsolutePath().toString()));
    }

    int numberOfFiles = files.size();
    // Log log = getLog();
    // log.info("Number of files to be formatted: " + numberOfFiles);

    if (numberOfFiles > 0) {

        ResultCollector rc = new ResultCollector();
        // Properties hashCache = readFileHashCacheFile();

        String basedirPath = getBasedirPath();
        for (int i = 0, n = files.size(); i < n; i++) {
            File file = (File) files.get(i);
            formatFile(file, rc, null, basedirPath);
        }

        long endClock = System.currentTimeMillis();

        log.info("Successfully formatted: " + rc.successCount + " file(s)");
        log.info("Fail to format        : " + rc.failCount + " file(s)");
        log.info("Skipped               : " + rc.skippedCount + " file(s)");
        log.info("Approximate time taken: " + ((endClock - startClock) / 1000) + "s");
    }
}

From source file:modules.GeneralNativeCommandModule.java

protected KeyValueResult extractNative(String command, String options, Path path)
        throws NativeExecutionException {
    if (command == null || command.equals("")) {
        System.err.println("command null at GeneralNativeCommandModule.extractNative()");
        return null;
    }//  ww w.j ava 2  s .com
    CommandLine commandLine = new CommandLine(command);

    if (options != null && !options.equals("")) {
        String[] args = options.split(" ");
        commandLine.addArguments(args);
    }

    if (path != null) {
        commandLine.addArgument(path.toAbsolutePath().toString(), false);
    }
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    GeneralExecutableModuleConfig generalExecutableModuleConfig = getConfig();
    executor.setWatchdog(new ExecuteWatchdog(generalExecutableModuleConfig.timeout));
    if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) {
        executor.setWorkingDirectory(getConfig().workingDirectory);
    }
    try {
        // System.out.println(commandLine);
        executor.execute(commandLine);
    } catch (ExecuteException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.executionResult = outputStream.toString();
        n.exitCode = xs.getExitValue();
        throw n;
    } catch (IOException xs) {
        // System.out.println(commandLine);
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.executionResult = outputStream.toString();
        throw n;
    }
    KeyValueResult t = new KeyValueResult("GeneralNativeCommandResults");
    t.add("fullOutput", outputStream.toString().trim());
    return t;
}

From source file:com.cyc.corpus.nlmpaper.AIMedOpenAccessPaper.java

private Optional<Path> getZipArchive(boolean cached) {
    try {//from  ww  w .ja  va 2s . c  om
        Path cachedFilePath = cachedArchivePath();
        Path parentDirectoryPath = cachedFilePath.getParent();

        // create the parent directory it doesn't already exist
        if (Files.notExists(parentDirectoryPath, LinkOption.NOFOLLOW_LINKS)) {
            Files.createDirectory(parentDirectoryPath);
        }

        // if cached file already exist - return it, no download necessary
        if (cached && Files.exists(cachedFilePath, LinkOption.NOFOLLOW_LINKS)) {
            return Optional.of(cachedFilePath.toAbsolutePath());
        }

        // otherwise, download the file
        URL url = new URL(PROTEINS_URL);
        Files.copy(url.openStream(), cachedFilePath, StandardCopyOption.REPLACE_EXISTING);
        return Optional.of(cachedFilePath.toAbsolutePath());

    } catch (MalformedURLException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }

    return Optional.empty();
}

From source file:modules.NativeProcessMonitoringDaemonModule.java

protected void startNativeMonitor(String command, String options, Path path) throws NativeExecutionException {
    if (command == null || command.equals("")) {
        System.err.println("command null at GeneralNativeCommandModule.extractNative()");
        return;/*  www .j a  va2s.co m*/
    }
    CommandLine commandLine = new CommandLine(command);

    if (options != null && !options.equals("")) {
        String[] args = options.split(" ");
        commandLine.addArguments(args);
    }

    if (path != null) {
        commandLine.addArgument(path.toAbsolutePath().toString(), false);
    }
    executor = new DefaultExecutor();
    esh = new MyExecuteStreamHandler();
    executor.setStreamHandler(esh);

    // GeneralExecutableModuleConfig generalExecutableModuleConfig =
    // getConfig();
    executor.setWatchdog(new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT));
    if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) {
        executor.setWorkingDirectory(getConfig().workingDirectory);
    }

    try {
        // System.out.println("Now execute: " + commandLine);
        executor.execute(commandLine, this);
    } catch (ExecuteException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.exitCode = xs.getExitValue();
        throw n;
    } catch (IOException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        throw n;
    }
    return;
}

From source file:org.ballerinalang.test.service.grpc.sample.GrpcMutualSslWithCertsTest.java

@Test
public void testMutualSSLWithcerts() throws IOException {
    Path balFilePath = Paths.get("src", "test", "resources", "grpc", "clients", "grpc_ssl_client.bal");
    String privateKey = StringEscapeUtils.escapeJava(
            Paths.get("src", "test", "resources", "certsAndKeys", "private.key").toAbsolutePath().toString());
    String publicCert = StringEscapeUtils.escapeJava(
            Paths.get("src", "test", "resources", "certsAndKeys", "public.crt").toAbsolutePath().toString());
    Map<String, String> runtimeParams = new HashMap<>();
    runtimeParams.put("client.certificate.key", privateKey);
    runtimeParams.put("client.public.cert", publicCert);
    registry.initRegistry(runtimeParams, null, null);
    result = BCompileUtil.compile(balFilePath.toAbsolutePath().toString());
    final String serverMsg = "Hello WSO2";
    BValue[] responses = BRunUtil.invoke(result, "testUnarySecuredBlockingWithCerts", new BValue[] {});
    Assert.assertEquals(responses.length, 1);
    Assert.assertTrue(responses[0] instanceof BString);
    BString responseValues = (BString) responses[0];
    Assert.assertEquals(responseValues.stringValue(), serverMsg);
}

From source file:io.seqware.pipeline.whitestar.WhiteStarTest.java

protected static void createAndRunWorkflow(Path settingsFile, boolean metadata) throws Exception, IOException {
    // create a helloworld
    Path tempDir = Files.createTempDirectory("tempTestingDirectory");
    PluginRunner it = new PluginRunner();
    String SEQWARE_VERSION = it.getClass().getPackage().getImplementationVersion();
    Assert.assertTrue("unable to detect seqware version", SEQWARE_VERSION != null);
    Log.info("SeqWare version detected as: " + SEQWARE_VERSION);
    String archetype = "java-workflow";
    String workflow = "seqware-archetype-" + archetype;
    String workflowName = workflow.replace("-", "");
    // generate and install archetypes to local maven repo
    String command = "mvn archetype:generate -DarchetypeCatalog=local -Dpackage=com.seqware.github -DgroupId=com.github.seqware -DarchetypeArtifactId="
            + workflow + " -Dversion=1.0-SNAPSHOT -DarchetypeGroupId=com.github.seqware -DartifactId="
            + workflow + " -Dworkflow-name=" + workflowName + " -B -Dgoals=install";
    String genOutput = ITUtility.runArbitraryCommand(command, 0, tempDir.toFile());
    Log.info(genOutput);//  w w  w  .j  a  v a 2  s  .  com
    // install the workflows to the database and record their information
    File workflowDir = new File(tempDir.toFile(), workflow);
    File targetDir = new File(workflowDir, "target");
    final String workflow_name = "Workflow_Bundle_" + workflowName + "_1.0-SNAPSHOT_SeqWare_" + SEQWARE_VERSION;
    File bundleDir = new File(targetDir, workflow_name);

    Map environment = EnvironmentUtils.getProcEnvironment();
    environment.put("SEQWARE_SETTINGS", settingsFile.toAbsolutePath().toString());

    // save system environment variables
    Map<String, String> env = System.getenv();
    try {
        // override for launching
        Utility.set(environment);
        List<String> cmd = new ArrayList<>();
        cmd.add("bundle");
        cmd.add("launch");
        cmd.add("--dir");
        cmd.add(bundleDir.getAbsolutePath());
        if (!metadata) {
            cmd.add("--no-metadata");
        }
        Main.main(cmd.toArray(new String[cmd.size()]));
    } finally {
        Utility.set(env);
    }

}

From source file:com.aol.advertising.qiao.injector.file.AbstractFileTailer.java

@Override
public void onCreate(Path file) {
    if (file.toFile().equals(this.tailedFile)) {
        // has a new file
        logger.info("new file created => " + file.toAbsolutePath());
        newFileDetected.set(true);/*  w  ww .  j a  va2s  .  co  m*/
    }
}

From source file:org.sonar.scanner.scan.filesystem.MetadataGeneratorTest.java

@Test
public void complete_input_file() throws Exception {
    // file system
    Path baseDir = temp.newFolder().toPath();
    Path srcFile = baseDir.resolve("src/main/java/foo/Bar.java");
    FileUtils.touch(srcFile.toFile());/*from   w  ww.j  a  v  a2s . co m*/
    FileUtils.write(srcFile.toFile(), "single line");

    // status
    when(statusDetection.status("foo", "src/main/java/foo/Bar.java", "6c1d64c0b3555892fe7273e954f6fb5a"))
            .thenReturn(InputFile.Status.ADDED);

    InputFile inputFile = createInputFileWithMetadata(baseDir, "src/main/java/foo/Bar.java");

    assertThat(inputFile.type()).isEqualTo(InputFile.Type.MAIN);
    assertThat(inputFile.file()).isEqualTo(srcFile.toFile());
    assertThat(inputFile.absolutePath()).isEqualTo(PathUtils.sanitize(srcFile.toAbsolutePath().toString()));
    assertThat(inputFile.key()).isEqualTo("struts:src/main/java/foo/Bar.java");
    assertThat(inputFile.relativePath()).isEqualTo("src/main/java/foo/Bar.java");
    assertThat(inputFile.lines()).isEqualTo(1);
}

From source file:com.mweagle.tereus.commands.evaluation.common.LambdaUtils.java

protected void createStableZip(ZipOutputStream zipOS, Path parentDirectory, Path archiveRoot, MessageDigest md)
        throws IOException {
    // Sort & zip files
    final List<Path> childDirectories = new ArrayList<>();
    final List<Path> childFiles = new ArrayList<>();
    DirectoryStream<Path> dirStream = Files.newDirectoryStream(parentDirectory);
    for (Path eachChild : dirStream) {
        if (Files.isDirectory(eachChild)) {
            childDirectories.add(eachChild);
        } else {//from  www .  j  ava 2  s  .  c o m
            childFiles.add(eachChild);
        }
    }
    final int archiveRootLength = archiveRoot.toAbsolutePath().toString().length() + 1;
    childFiles.stream().sorted().forEach(eachPath -> {
        final String zeName = eachPath.toAbsolutePath().toString().substring(archiveRootLength);
        try {
            final ZipEntry ze = new ZipEntry(zeName);
            zipOS.putNextEntry(ze);
            Files.copy(eachPath, zipOS);
            md.update(Files.readAllBytes(eachPath));
            zipOS.closeEntry();
        } catch (IOException ex) {
            throw new RuntimeException(ex.getMessage());
        }
    });

    childDirectories.stream().sorted().forEach(eachPath -> {
        try {
            createStableZip(zipOS, eachPath, archiveRoot, md);
        } catch (IOException ex) {
            throw new RuntimeException(ex.getMessage());
        }
    });
}