Example usage for java.nio.file Path isAbsolute

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

Introduction

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

Prototype

boolean isAbsolute();

Source Link

Document

Tells whether or not this path is absolute.

Usage

From source file:org.apache.rya.api.path.PathUtils.java

/**
 * Indicates whether file lives in a secure directory relative to the
 * program's user./*w w  w  . j av a 2 s  .  co m*/
 * @param file {@link Path} to test.
 * @param user {@link UserPrincipal} to test. If {@code null}, defaults to
 * current user.
 * @param symlinkDepth Number of symbolic links allowed.
 * @return {@code true} if file's directory is secure.
 */
public static boolean isInSecureDir(Path file, UserPrincipal user, final int symlinkDepth) {
    if (!file.isAbsolute()) {
        file = file.toAbsolutePath();
    }
    if (symlinkDepth <= 0) {
        // Too many levels of symbolic links
        return false;
    }
    // Get UserPrincipal for specified user and superuser
    final Path fileRoot = file.getRoot();
    if (fileRoot == null) {
        return false;
    }
    final FileSystem fileSystem = Paths.get(fileRoot.toString()).getFileSystem();
    final UserPrincipalLookupService upls = fileSystem.getUserPrincipalLookupService();
    UserPrincipal root = null;
    try {
        if (SystemUtils.IS_OS_UNIX) {
            root = upls.lookupPrincipalByName("root");
        } else {
            root = upls.lookupPrincipalByName("Administrators");
        }
        if (user == null) {
            user = upls.lookupPrincipalByName(System.getProperty("user.name"));
        }
        if (root == null || user == null) {
            return false;
        }
    } catch (final IOException x) {
        return false;
    }
    // If any parent dirs (from root on down) are not secure, dir is not secure
    for (int i = 1; i <= file.getNameCount(); i++) {
        final Path partialPath = Paths.get(fileRoot.toString(), file.subpath(0, i).toString());
        try {
            if (Files.isSymbolicLink(partialPath)) {
                if (!isInSecureDir(Files.readSymbolicLink(partialPath), user, symlinkDepth - 1)) {
                    // Symbolic link, linked-to dir not secure
                    return false;
                }
            } else {
                final UserPrincipal owner = Files.getOwner(partialPath);
                if (!user.equals(owner) && !root.equals(owner)) {
                    // dir owned by someone else, not secure
                    return SystemUtils.IS_OS_UNIX ? false : Files.isWritable(partialPath);
                }
            }
        } catch (final IOException x) {
            return false;
        }
    }
    return true;
}

From source file:org.dataconservancy.dcs.util.UriUtility.java

/**
* Create a URI string for a file in a BagIt bag,
* @param file The file to check.  This doesn't have to be an actual existing file
* @param basedir The directory to make the file URI relative to.  Can be null.  If not null, the basedir must be
*                in the path of the file parameter, or an exception will be thrown
* @return A string representing the URI to the file on the local disk.
* @throws URISyntaxException if there is an error in the URI syntax
*//*from www. ja  v a2s  .co  m*/
public static URI makeBagUriString(File file, File basedir) throws URISyntaxException {
    if (basedir == null) {
        basedir = new File(".");
    }

    Path relativePath = file.toPath();

    if (relativePath.startsWith(basedir.toPath())) {
        relativePath = basedir.toPath().relativize(file.toPath());
    }

    String path = FilenameUtils.separatorsToUnix(relativePath.toString());
    if (relativePath.getNameCount() > 1) {

        Path uriAuthority = relativePath.getName(0);
        Path uriPath = relativePath.subpath(1, relativePath.getNameCount());
        path = FilenameUtils.separatorsToUnix(uriPath.toString());
        if (!uriPath.isAbsolute()) {
            path = "/" + path;
        }

        return new URI(BAG_URI_SCHEME, uriAuthority.toString(), path, null, null);
    }

    return new URI(BAG_URI_SCHEME, path, null, null, null);
}

From source file:org.dataconservancy.packaging.impl.UriUtility.java

/**
 * Create a URI string for a file in a BagIt bag,
 *
 * @param file The file to check. This doesn't have to be an actual existing file
 * @param basedir The directory to make the file URI relative to. Can be null. If not null, the basedir must be in
 *        the path of the file parameter, or an exception will be thrown
 * @return A string representing the URI to the file on the local disk.
 * @throws URISyntaxException if there is an error in the URI syntax
 *//* ww w . j  av a  2 s .c o m*/
public static URI makeBagUriString(final File file, final File basedir) throws URISyntaxException {
    final File dir = basedir == null ? new File(".") : basedir;

    Path relativePath = file.toPath();

    if (relativePath.startsWith(dir.toPath())) {
        relativePath = dir.toPath().relativize(file.toPath());
    }

    String path = FilenameUtils.separatorsToUnix(relativePath.toString());
    if (relativePath.getNameCount() > 1) {

        final Path uriAuthority = relativePath.getName(0);
        final Path uriPath = relativePath.subpath(1, relativePath.getNameCount());
        path = FilenameUtils.separatorsToUnix(uriPath.toString());
        if (!uriPath.isAbsolute()) {
            path = "/" + path;
        }

        return new URI(BAG_URI_SCHEME, uriAuthority.toString(), path, null, null);
    }

    return new URI(BAG_URI_SCHEME, path, null, null, null);
}

From source file:com.github.blindpirate.gogradle.util.IOUtils.java

public static Path ensureDirExistAndWritable(Path path) {
    Assert.isTrue(path.isAbsolute(), "path must be absolute!");
    File dir = path.toFile();//from  w  ww  .  j  a v a  2  s. c o  m
    IOUtils.forceMkdir(dir);
    Assert.isTrue(Files.isWritable(dir.toPath()), "Cannot write to directory:" + path);
    return path;
}

From source file:org.sonar.scanner.scan.ProjectReactorBuilder.java

protected static File resolvePath(File baseDir, String path) {
    Path filePath = Paths.get(path);
    if (!filePath.isAbsolute()) {
        filePath = baseDir.toPath().resolve(path);
    }/* w  ww.j  a  v a2s  . c om*/
    return filePath.normalize().toFile();
}

From source file:illarion.compile.Compiler.java

private static void processPath(@Nonnull final Path path) throws IOException {
    if (Files.isDirectory(path)) {
        return;/*from  www .  j av  a2s  . c  o m*/
    }

    int compileResult = 1;
    for (CompilerType type : CompilerType.values()) {
        if (type.isValidFile(path)) {
            Compile compile = type.getImplementation();
            if (path.isAbsolute()) {
                if (storagePaths.containsKey(type)) {
                    compile.setTargetDir(storagePaths.get(type));
                } else {
                    compile.setTargetDir(path.getParent());
                }
            } else {
                if (storagePaths.containsKey(type)) {
                    Path parent = path.getParent();
                    if (parent == null) {
                        compile.setTargetDir(storagePaths.get(type));
                    } else {
                        compile.setTargetDir(storagePaths.get(type).resolve(parent));
                    }
                } else {
                    Path parent = path.getParent();
                    if (parent == null) {
                        compile.setTargetDir(path.toAbsolutePath().getParent());
                    } else {
                        compile.setTargetDir(parent);
                    }
                }
            }
            compileResult = compile.compileFile(path.toAbsolutePath());
            if (compileResult == 0) {
                break;
            }
        }
    }

    switch (compileResult) {
    case 1:
        LOGGER.info("Skipped file: {}", path.getFileName());
        break;
    case 0:
        return;
    default:
        System.exit(compileResult);
    }
}

From source file:net.pms.configuration.ConfigurableProgramPaths.java

/**
 * Resolves the path in that the existence of the specified {@link Path} is
 * verified. It it doesn't exist and the {@link Path} is relative, an
 * attempt to look it up in the OS {@code PATH}. If a match is found in the
 * OS {@code PATH}, that {@link Path} is returned. If not, the input
 * {@link Path} is returned./* ww  w .  j  av a 2s  .co m*/
 *
 * @param customPath the custom executable {@link Path} to resolve.
 * @return The same instance as {@code customPath} it it exists or a match
 *         isn't found in the OS {@code PATH}, otherwise the {@link Path} to
 *         the matched executable found in the OS {@code PATH}.
 */
@Nullable
public static Path resolveCustomProgramPath(@Nullable Path customPath) {
    if (customPath == null) {
        return null;
    }

    if (!Files.exists(customPath) && !customPath.isAbsolute()) {
        Path osPathCustom = FileUtil.findExecutableInOSPath(customPath);
        if (osPathCustom != null) {
            customPath = osPathCustom;
        }
    }

    return customPath;
}

From source file:Main.java

public static void printDetails(Path p) {
    System.out.println("Details for path: " + p);

    int count = p.getNameCount();
    System.out.println("Name count: " + count);

    for (int i = 0; i < count; i++) {
        Path name = p.getName(i);
        System.out.println("Name at  index   " + i + "  is " + name);
    }/*from  w  w  w  . ja  v  a2s.  co  m*/

    Path parent = p.getParent();
    Path root = p.getRoot();
    Path fileName = p.getFileName();
    System.out.println("Parent: " + parent + ", Root:   " + root + ", File Name: " + fileName);
    System.out.println("Absolute Path: " + p.isAbsolute());
}

From source file:io.cloudslang.content.database.services.databases.MSSqlDatabase.java

private static void validateLibraryPath(String sqlJdbcAuthLibraryPath) {
    final List<String> exceptions = new ArrayList<>();

    if (StringUtils.isEmpty(sqlJdbcAuthLibraryPath)) {
        throw new RuntimeException(EMPTY_DRIVER_PATH_EXCEPTION);
    }//www.  j  a va2  s .co m

    final Path libraryPath = Paths.get(sqlJdbcAuthLibraryPath);

    try {
        if (!libraryPath.equals(libraryPath.toRealPath())) {
            exceptions.add(SYMBOLIC_PATH_EXCEPTION);
        }
        if (!Files.isDirectory(libraryPath)) {
            exceptions.add(INVALID_DIRECTORY_PATH_EXCEPTION);
        }
        if (!libraryPath.isAbsolute()) {
            exceptions.add(DRIVER_PATH_NOT_ABSOLUTE_EXCEPTION);
        }
        if (!libraryPath.equals(libraryPath.normalize())) {
            exceptions.add(NOT_THE_SHORTEST_PATH_EXCEPTION);
        }
    } catch (IOException e) {
        exceptions.add(INVALID_PATH);
    } finally {
        if (exceptions.size() != 0) {
            throw new RuntimeException(join(exceptions, NEW_LINE));
        }
    }
}

From source file:org.jlab.clara.std.services.DataManager.java

private static Path getPath(JSONObject data, String key, String type) {
    Path path = Paths.get(data.getString(key));
    if (path.toString().isEmpty()) {
        throw new IllegalArgumentException("empty " + type + " path");
    }// w  ww .  j av  a 2s . com
    if (!path.isAbsolute()) {
        String msg = String.format("%s path %s is not absolute", type, path);
        throw new IllegalArgumentException(msg);
    }
    if (Files.exists(path) && !Files.isDirectory(path)) {
        String msg = String.format("%s path %s exists but not a directory", type, path);
        throw new IllegalArgumentException(msg);
    }
    return path;
}