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.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testNonCanonicalPaths() throws InterruptedException, IOException {
    String names[] = { "foo/./", "foo/./bar/", "foo/./bar/baz.cpp", "foo/./bar/baz.h", };

    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        for (String name : names) {
            zip.putArchiveEntry(new ZipArchiveEntry(name));
            zip.closeArchiveEntry();//from  ww w .j  a  v  a 2s . c o m
        }
    }

    Path extractFolder = tmpFolder.newFolder();

    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES);
    for (String name : names) {
        assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve(name)));
    }
    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES);
    for (String name : names) {
        assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve(name)));
    }
}

From source file:com.vmware.photon.controller.common.dcp.helpers.dcp.MultiHostEnvironment.java

/**
 * Generates a unique storage sandbox path.
 * @return//from  ww  w  .java  2  s .  c o  m
 */
protected String generateStorageSandboxPath() {
    Path sandboxPath = FileSystems.getDefault().getPath(System.getProperty("user.home"), STORAGE_PATH_PREFIX,
            UUID.randomUUID().toString());
    return sandboxPath.toAbsolutePath().toString();
}

From source file:org.opencb.opencga.app.cli.CommandExecutor.java

/**
 * This method attempts to load storage configuration from CLI 'conf' parameter, if not exists then loads JAR storage-configuration.yml.
 *
 * @throws IOException If any IO problem occurs
 *///from  w w w .  j  ava 2s .  com
public void loadStorageConfiguration() throws IOException {
    FileUtils.checkDirectory(Paths.get(this.conf));

    // We load configuration file either from app home folder or from the JAR
    Path path = Paths.get(this.conf).resolve("storage-configuration.yml");
    if (path != null && Files.exists(path)) {
        logger.debug("Loading storage configuration from '{}'", path.toAbsolutePath());
        this.storageConfiguration = StorageConfiguration.load(new FileInputStream(path.toFile()));
    } else {
        logger.debug("Loading storage configuration from JAR file");
        this.storageConfiguration = StorageConfiguration.load(
                ClientConfiguration.class.getClassLoader().getResourceAsStream("storage-configuration.yml"));
    }
}

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

/**
 * <b>PHYSICALLY</b> deletes a file (w/o backup)<br>
 * only doing a check if it is not a directory
 * /* w  w  w . j  a  va 2  s  .c  o  m*/
 * @param file
 *          the file to be deleted
 * @return true/false if successful
 */
public static boolean deleteFileSafely(Path file) {
    file = file.toAbsolutePath();
    if (Files.isDirectory(file)) {
        LOGGER.warn("Will not delete file '" + file + "': file is a directory!");
        return false;
    }
    try {
        Files.deleteIfExists(file);
    } catch (Exception e) {
        LOGGER.warn("Could not delete file: " + e.getMessage());
        return false;
    }
    return true;
}

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

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

    conf.properties();//www.ja  v  a 2 s  . c o  m
}

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testExtractBrokenSymlinkWithOwnerExecutePermissions() throws InterruptedException, IOException {
    assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS)));

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("link.txt");
        entry.setUnixMode((int) MostFiles.S_IFLNK);
        String target = "target.txt";
        entry.setSize(target.getBytes(Charsets.UTF_8).length);
        entry.setMethod(ZipEntry.STORED);

        // Mark the file as being executable.
        Set<PosixFilePermission> filePermissions = ImmutableSet.of(PosixFilePermission.OWNER_EXECUTE);

        long externalAttributes = entry.getExternalAttributes()
                + (MorePosixFilePermissions.toMode(filePermissions) << 16);
        entry.setExternalAttributes(externalAttributes);

        zip.putArchiveEntry(entry);//from   w w w .j  av a2 s.  c o m
        zip.write(target.getBytes(Charsets.UTF_8));
        zip.closeArchiveEntry();
    }

    Path extractFolder = tmpFolder.newFolder();

    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE);
    Path link = extractFolder.toAbsolutePath().resolve("link.txt");
    assertTrue(Files.isSymbolicLink(link));
    assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt"));
}

From source file:abfab3d.shapejs.Project.java

public void save(String file) throws IOException {
    EvaluatedScript escript = m_script.getEvaluatedScript();
    Map<String, Parameter> scriptParams = escript.getParamMap();
    Gson gson = JSONParsing.getJSONParser();

    String code = escript.getCode();

    Path workingDirName = Files.createTempDirectory("saveScript");
    String workingDirPath = workingDirName.toAbsolutePath().toString();
    Map<String, Object> params = new HashMap<String, Object>();

    // Write the script to file
    File scriptFile = new File(workingDirPath + "/main.js");
    FileUtils.writeStringToFile(scriptFile, code, "UTF-8");

    // Loop through params and create key/pair entries
    for (Map.Entry<String, Parameter> entry : scriptParams.entrySet()) {
        String name = entry.getKey();
        Parameter pval = entry.getValue();

        if (pval.isDefaultValue())
            continue;

        ParameterType type = pval.getType();

        switch (type) {
        case URI:
            URIParameter urip = (URIParameter) pval;
            String u = (String) urip.getValue();

            //                   System.out.println("*** uri: " + u);
            File f = new File(u);

            String fileName = null;

            // TODO: This is hacky. If the parameter value is a directory, then assume it was
            //       originally a zip file, and its contents were extracted in the directory.
            //       Search for the zip file in the directory and copy that to the working dir.
            if (f.isDirectory()) {
                File[] files = f.listFiles();
                for (int i = 0; i < files.length; i++) {
                    String fname = files[i].getName();
                    if (fname.endsWith(".zip")) {
                        fileName = fname;
                        f = files[i];/*from www .j  ava2  s . com*/
                    }
                }
            } else {
                fileName = f.getName();
            }

            params.put(name, fileName);

            // Copy the file to working directory
            FileUtils.copyFile(f, new File(workingDirPath + "/" + fileName), true);
            break;
        case LOCATION:
            LocationParameter lp = (LocationParameter) pval;
            Vector3d p = lp.getPoint();
            Vector3d n = lp.getNormal();
            double[] point = { p.x, p.y, p.z };
            double[] normal = { n.x, n.y, n.z };
            //                   System.out.println("*** lp: " + java.util.Arrays.toString(point) + ", " + java.util.Arrays.toString(normal));
            Map<String, double[]> loc = new HashMap<String, double[]>();
            loc.put("point", point);
            loc.put("normal", normal);
            params.put(name, loc);
            break;
        case AXIS_ANGLE_4D:
            AxisAngle4dParameter aap = (AxisAngle4dParameter) pval;
            AxisAngle4d a = (AxisAngle4d) aap.getValue();
            params.put(name, a);
            break;
        case DOUBLE:
            DoubleParameter dp = (DoubleParameter) pval;
            Double d = (Double) dp.getValue();
            //                   System.out.println("*** double: " + d);

            params.put(name, d);
            break;
        case INTEGER:
            IntParameter ip = (IntParameter) pval;
            Integer i = ip.getValue();
            //                   System.out.println("*** int: " + pval);
            params.put(name, i);
            break;
        case STRING:
            StringParameter sp = (StringParameter) pval;
            String s = sp.getValue();
            //                   System.out.println("*** string: " + s);
            params.put(name, s);
            break;
        case COLOR:
            ColorParameter cp = (ColorParameter) pval;
            Color c = cp.getValue();
            //                   System.out.println("*** string: " + s);
            params.put(name, c.toHEX());
            break;
        case ENUM:
            EnumParameter ep = (EnumParameter) pval;
            String e = ep.getValue();
            //                   System.out.println("*** string: " + s);
            params.put(name, e);
            break;
        default:
            params.put(name, pval);
        }

    }

    if (params.size() > 0) {
        String paramsJson = gson.toJson(params);
        File paramFile = new File(workingDirPath + "/" + "params.json");
        FileUtils.writeStringToFile(paramFile, paramsJson, "UTF-8");
    }

    File[] files = (new File(workingDirPath)).listFiles();

    FileOutputStream fos = new FileOutputStream(file);
    ZipOutputStream zos = new ZipOutputStream(fos);
    System.out.println("*** Num files to zip: " + files.length);

    try {
        byte[] buffer = new byte[1024];

        for (int i = 0; i < files.length; i++) {
            //                if (files[i].getName().endsWith(".zip")) continue;

            System.out.println("*** Adding file: " + files[i].getName());
            FileInputStream fis = new FileInputStream(files[i]);
            ZipEntry ze = new ZipEntry(files[i].getName());
            zos.putNextEntry(ze);

            int len;
            while ((len = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }

            fis.close();
        }
    } finally {
        zos.closeEntry();
        zos.close();
    }
}

From source file:codes.thischwa.c5c.impl.LocalConnector.java

/**
 * Builds the folder and check it./*w w w  .  j  a va 2 s .c  o  m*/
 *
 * @param backendPath the url path
 * @return the file
 * @throws FilemanagerException the known exception
 */
private Path buildRealPathAndCheck(String backendPath) throws FilemanagerException {
    Path parentFolder = buildRealPath(backendPath);
    if (!Files.exists(parentFolder)) {
        logger.error("Source file not found: {}", parentFolder.toAbsolutePath());
        FilemanagerException.Key key = (Files.isDirectory(parentFolder))
                ? FilemanagerException.Key.DirectoryNotExist
                : FilemanagerException.Key.FileNotExists;
        throw new FilemanagerException(FilemanagerAction.CREATEFOLDER, key,
                parentFolder.getFileName().toString());
    }
    return parentFolder;
}

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 {//ww w  .j av a 2  s  .com
        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 w  w  .  jav  a 2 s  .  com
        Files.move(srcPath, dstPath.resolve(srcPath.getFileName()), StandardCopyOption.ATOMIC_MOVE,
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new GenericResourceException("cannot copy file", e);
    }
}