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:org.exist.xquery.RestBinariesTest.java

/**
 * {@see https://github.com/eXist-db/exist/issues/790#error-case-5}
 *
 * response:stream is used to return Base64 encoded binary.
 *///from  www .j  a  va  2s . co  m
@Test
public void readAndStreamBinarySax() throws IOException, JAXBException {
    final byte[] data = randomData(1024 * 1024); // 1MB
    final Path tmpInFile = createTemporaryFile(data);

    final String query = "import module namespace file = \"http://exist-db.org/xquery/file\";\n"
            + "import module namespace response = \"http://exist-db.org/xquery/response\";\n"
            + "let $bin := file:read-binary('" + tmpInFile.toAbsolutePath().toString() + "')\n"
            + "return response:stream($bin, 'media-type=application/octet-stream')";

    final HttpResponse response = postXquery(query);

    final HttpEntity entity = response.getEntity();
    try (final FastByteArrayOutputStream baos = new FastByteArrayOutputStream()) {
        entity.writeTo(baos);

        assertArrayEquals(Files.readAllBytes(tmpInFile), Base64.decodeBase64(baos.toByteArray()));
    }
}

From source file:org.exist.xquery.RestBinariesTest.java

/**
 * {@see https://github.com/eXist-db/exist/issues/790#error-case-5}
 *
 * response:stream-binary is used to return raw binary.
 *//*  w  w  w.j  ava  2  s. c  o  m*/
@Test
public void readAndStreamBinaryRaw() throws IOException, JAXBException {
    final byte[] data = randomData(1024 * 1024); // 1MB
    final Path tmpInFile = createTemporaryFile(data);

    final String query = "import module namespace file = \"http://exist-db.org/xquery/file\";\n"
            + "import module namespace response = \"http://exist-db.org/xquery/response\";\n"
            + "let $bin := file:read-binary('" + tmpInFile.toAbsolutePath().toString() + "')\n"
            + "return response:stream-binary($bin, 'media-type=application/octet-stream', ())";

    final HttpResponse response = postXquery(query);

    final HttpEntity entity = response.getEntity();
    try (final FastByteArrayOutputStream baos = new FastByteArrayOutputStream()) {
        entity.writeTo(baos);

        assertArrayEquals(Files.readAllBytes(tmpInFile), baos.toByteArray());
    }
}

From source file:org.assertj.examples.PathAssertionsExamples.java

@Test
public void path_assertions() throws Exception {
    assumeTrue(SystemUtils.IS_OS_UNIX);// w  ww . j a va  2  s  .c  o  m

    // Create a regular file, and a symbolic link pointing to it
    final Path existingFile = Paths.get("somefile.txt");
    write(existingFile, "foo".getBytes());
    final Path symlinkToExistingFile = Paths.get("symlink-to-somefile.txt");
    deleteIfExists(symlinkToExistingFile);
    createSymbolicLink(symlinkToExistingFile, existingFile);

    // Create a symbolic link whose target does not exist
    final Path nonExistentPath = Paths.get("nonexistent");
    final Path symlinkToNonExistentPath = Paths.get("symlinkToNonExistentPath");
    deleteIfExists(symlinkToNonExistentPath);
    createSymbolicLink(symlinkToNonExistentPath, nonExistentPath);

    // create directory and symlink to it
    Path dir = Paths.get("target/dir");
    deleteIfExists(dir);
    createDirectory(dir);
    final Path dirSymlink = Paths.get("target", "dirSymlink");
    deleteIfExists(dirSymlink);
    createSymbolicLink(dirSymlink, dir.toAbsolutePath());

    // assertions examples

    assertThat(existingFile).exists();
    assertThat(symlinkToExistingFile).exists();
    assertThat(existingFile).existsNoFollowLinks();
    assertThat(symlinkToNonExistentPath).existsNoFollowLinks();

    assertThat(nonExistentPath).doesNotExist();

    assertThat(existingFile).isRegularFile();
    assertThat(symlinkToExistingFile).isRegularFile();

    assertThat(symlinkToExistingFile).isSymbolicLink();
    assertThat(dirSymlink).isDirectory().isSymbolicLink();
    assertThat(symlinkToNonExistentPath).isSymbolicLink();

    assertThat(dir).isDirectory();
    assertThat(dirSymlink).isDirectory();
    assertThat(dir).hasParent(Paths.get("target")).hasParent(Paths.get("target/dir/..")) // would fail with hasParentRaw
            .hasParentRaw(Paths.get("target"));

    assertThat(existingFile.toRealPath()).isCanonical();

    assertThat(existingFile).hasFileName("somefile.txt");
    assertThat(symlinkToExistingFile).hasFileName("symlink-to-somefile.txt");

    assertThat(Paths.get("/foo/bar")).isAbsolute();
    assertThat(Paths.get("foo/bar")).isRelative();
    assertThat(Paths.get("/usr/lib")).isNormalized();
    assertThat(Paths.get("a/b/c")).isNormalized();
    assertThat(Paths.get("../d")).isNormalized();
    assertThat(Paths.get("/")).hasNoParent();
    assertThat(Paths.get("foo")).hasNoParentRaw();
    assertThat(Paths.get("/usr/lib")).startsWith(Paths.get("/usr")).startsWith(Paths.get("/usr/lib/..")) // would fail with startsWithRaw
            .startsWithRaw(Paths.get("/usr"));
    assertThat(Paths.get("/usr/lib")).endsWith(Paths.get("lib")).endsWith(Paths.get("lib/../lib")) // would fail with endsWithRaw
            .endsWithRaw(Paths.get("lib"));

    assertThat(Paths.get("abc.txt")).isLessThan(Paths.get("xyz.txt"));

    // assertions error examples

    try {
        assertThat(nonExistentPath).exists();
    } catch (AssertionError e) {
        logAssertionErrorMessage("path exists", e);
    }
    try {
        assertThat(nonExistentPath).existsNoFollowLinks();
    } catch (AssertionError e) {
        logAssertionErrorMessage("path existsNoFollowLinks", e);
    }
    try {
        assertThat(symlinkToNonExistentPath).exists();
    } catch (AssertionError e) {
        logAssertionErrorMessage("path exists", e);
    }
    try {
        assertThat(dir).hasParentRaw(Paths.get("target/dir/.."));
    } catch (AssertionError e) {
        logAssertionErrorMessage("path hasParentRaw", e);
    }

    try {
        // fail as symlinkToNonExistentPath exists even if its target does not.
        assertThat(symlinkToNonExistentPath).doesNotExist();
    } catch (AssertionError e) {
        logAssertionErrorMessage("path doesNotExist not following links", e);
    }
    try {
        assertThat(nonExistentPath).exists();
    } catch (AssertionError e) {
        logAssertionErrorMessage("path exists", e);
    }
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * <b>PHYSICALLY</b> deletes a file by moving it to datasource backup folder<br>
 * DS\.backup\&lt;filename&gt;<br>
 * maintaining its originating directory
 * /*  ww w  .  ja  v a 2  s.c om*/
 * @param file
 *          the file to be deleted
 * @param datasource
 *          the data source (for the location of the backup folder)
 * @return true/false if successful
 */
public static boolean deleteFileWithBackup(Path file, String datasource) {
    String fn = file.toAbsolutePath().toString();
    if (!fn.startsWith(datasource)) { // safety
        LOGGER.warn("could not delete file '" + fn + "': datasource '" + datasource + "' does not match");
        return false;
    }
    if (Files.isDirectory(file)) {
        LOGGER.warn("could not delete file '" + fn + "': file is a directory!");
        return false;
    }

    // inject backup path
    fn = fn.replace(datasource, datasource + FileSystems.getDefault().getSeparator() + Constants.BACKUP_FOLDER);

    // backup
    try {
        // create path
        Path backup = Paths.get(fn);
        if (!Files.exists(backup.getParent())) {
            Files.createDirectories(backup.getParent());
        }
        // overwrite backup file by deletion prior
        Files.deleteIfExists(backup);
        return moveFileSafe(file, backup);
    } catch (IOException e) {
        LOGGER.warn("Could not delete file: " + e.getMessage());
        return false;
    }
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * <b>PHYSICALLY</b> deletes a complete directory by moving it to datasource backup folder<br>
 * DS\.backup\&lt;foldername&gt;<br>
 * maintaining its originating directory
 * // ww  w .  j av  a2 s.com
 * @param folder
 *          the folder to be deleted
 * @param datasource
 *          the datasource of this folder
 * @return true/false if successful
 */
public static boolean deleteDirectorySafely(Path folder, String datasource) {
    folder = folder.toAbsolutePath();
    String fn = folder.toAbsolutePath().toString();
    if (!Files.isDirectory(folder)) {
        LOGGER.warn("Will not delete folder '" + folder + "': folder is a file, NOT a directory!");
        return false;
    }
    if (!folder.toString().startsWith(datasource)) { // safety
        LOGGER.warn("Will not delete folder '" + folder + "': datasource '" + datasource + "' does not match");
        return false;
    }

    // inject backup path
    fn = fn.replace(datasource, datasource + FileSystems.getDefault().getSeparator() + Constants.BACKUP_FOLDER);

    // backup
    try {
        // create path
        Path backup = Paths.get(fn);
        if (!Files.exists(backup.getParent())) {
            Files.createDirectories(backup.getParent());
        }
        // overwrite backup file by deletion prior
        deleteDirectoryRecursive(backup);
        return moveDirectorySafe(folder, backup);
    } catch (IOException e) {
        LOGGER.warn("could not delete directory: " + e.getMessage());
        return false;
    }
}

From source file:org.sonarsource.scanner.cli.ConfTest.java

@Test
public void shouldSupportSettingBaseDirFromCli() throws Exception {
    Path projectHome = Paths
            .get(getClass().getResource("ConfTest/shouldLoadModuleConfiguration/project").toURI());
    args.setProperty("project.home", temp.newFolder().getCanonicalPath());
    args.setProperty("sonar.projectBaseDir", projectHome.toAbsolutePath().toString());

    Properties properties = conf.properties();

    assertThat(properties.getProperty("module1.sonar.projectName")).isEqualTo("Module 1");
    assertThat(properties.getProperty("module2.sonar.projectName")).isEqualTo("Module 2");
    assertThat(properties.getProperty("sonar.projectBaseDir")).isEqualTo(projectHome.toString());
}

From source file:io.github.dsheirer.gui.SDRTrunk.java

/**
 * Loads the application properties file from the user's home directory,
 * creating the properties file for the first-time, if necessary
 *///from  w  w w .  j a v a  2  s.c o m
private void loadProperties(Path homePath) {
    Path propsPath = homePath.resolve("SDRTrunk.properties");

    if (!Files.exists(propsPath)) {
        try {
            mLog.info("SDRTrunk - creating application properties file [" + propsPath.toAbsolutePath() + "]");

            Files.createFile(propsPath);
        } catch (IOException e) {
            mLog.error("SDRTrunk - couldn't create application properties " + "file ["
                    + propsPath.toAbsolutePath(), e);
        }
    }

    if (Files.exists(propsPath)) {
        SystemProperties.getInstance().load(propsPath);
    } else {
        mLog.error("SDRTrunk - couldn't find or recreate the SDRTrunk " + "application properties file");
    }
}

From source file:com.nridge.connector.fs.con_fs.core.FileCrawler.java

/**
 * Invoked for a file that could not be visited.
 * Unless overridden, this method re-throws the I/O exception that prevented
 * the file from being visited./*from   w w  w. j av  a2s . c o  m*/
 *
 * @param aPathFile Path file instance.
 * @param anException Identifies an I/O error condition.
 */
@Override
public FileVisitResult visitFileFailed(Path aPathFile, IOException anException) throws IOException {
    Logger appLogger = mAppMgr.getLogger(this, "visitFileFailed");

    String pathFileName = aPathFile.toAbsolutePath().toString();
    appLogger.warn(String.format("%s: %s", pathFileName, anException.getMessage()));

    return FileVisitResult.CONTINUE;
}

From source file:org.sonar.plugins.csharp.CSharpSensorTest.java

@Test
public void endStepAnalysisCalledWhenNoBuildPhaseComputedMetricsArePresent() throws Exception {
    // Setup test folder:
    Path analyzerWorkDirectory = temp.newFolder().toPath();
    Path outputDir = analyzerWorkDirectory.resolve("output-cs");
    Files.createDirectories(outputDir);

    settings.setProperty(CSharpConfiguration.ANALYZER_PROJECT_OUT_PATH_PROPERTY_KEY,
            analyzerWorkDirectory.toAbsolutePath().toString());
    CSharpSensor spy = spy(sensor);//from w  w  w .j av  a  2 s.c om
    spy.executeInternal(tester);
    verify(spy, times(1)).analyze(true, tester);
}

From source file:org.bonitasoft.platform.setup.command.configure.BundleConfigurator.java

String readContentFromFile(Path bonitaXmlFile) throws PlatformException {
    try {//  w  w w . j av  a  2s  .c  om
        return new String(Files.readAllBytes(bonitaXmlFile), StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new PlatformException(
                "Cannot read content of text file " + bonitaXmlFile.toAbsolutePath().toString(), e);
    }
}