Validates if relative path entered in text field points to an existing file.
@param relativeTo path of this file is used to create absolute path from entered in field (see {@link FileExistsValidator}).
556698
public FormInputValidator fileExists (VisValidatableTextField field, FileHandle relativeTo, String errorMsg) {
		FileExistsValidator validator = new FileExistsValidator(relativeTo.file(), errorMsg);
		field.addValidator(validator);
		add(field);
		return validator;

	}
292178
protected function validatePath($path, $relative)
    {
        /*
        path          = path-abempty    ; begins with "/" or is empty
                      / path-absolute   ; begins with "/" but not "//"
                      / path-noscheme   ; begins with a non-colon segment
                      / path-rootless   ; begins with a segment
                      / path-empty      ; zero characters
        path-abempty  = *( "/" segment )
        path-absolute = "/" [ segment-nz *( "/" segment ) ]
        path-noscheme = segment-nz-nc *( "/" segment )
                      ; only used for a relative URI
        path-rootless = segment-nz *( "/" segment )
                      ; only used for an absolute URI
        path-empty    = 0<pchar>
        segment       = *pchar
        segment-nz    = 1*pchar
        segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" )
                      ; non-zero-length segment without any colon ":"
        pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
        unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
        sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
                      / "*" / "+" / "," / ";" / "="
        pct-encoded   = "%" HEXDIG HEXDIG
        */
        $pchar          =   '(?:'.
                                '[-[:alnum:]\\._~!\\$&\'\\(\\)\\*\\+,;=:@]|'.
                                '%[[:xdigit:]]'.
                            ')';
        $segment        = '(?:'.$pchar.'*)';
        $segmentNz      = '(?:'.$pchar.'+)';
        $segmentNzNc    =   '(?:'.
                                '[-[:alnum:]\\._~!\\$&\'\\(\\)\\*\\+,;=@]|'.
                                '%[[:xdigit:]]'.
                            ')+';
        $pathAbempty    = '(?:/'.$segment.')*';
        $pathAbsolute   = '/(?:'.$segmentNz.'(?:/'.$segment.')*)?';
        $pathNoscheme   = $segmentNzNc.'(?:/'.$segment.')*';
        $pathRootless   = $segmentNz.'(?:/'.$segment.')*';
        $pathEmpty      = '(?!'.$pchar.')';

        $pattern = '(?:' . $pathAbempty.'|'.$pathAbsolute;
        if ($relative) {
            $pattern .= '|'.$pathNoscheme;
        } else {
            $pattern .= '|'.$pathRootless;
        }
        $pattern .= '|'.$pathEmpty . ')';

        return (bool) preg_match('#^'.$pattern.'$#Di', $path);
    }
519619
@Override
	public boolean validate(final Problems problems, final String compName, final String text) {
		boolean invalid = text.contains(File.separator) || text.contains(File.pathSeparator);
		if (!invalid && Utilities.isWindows()) {
			invalid = text.contains(":");
		}
		final String result = invalid
				? ValidationBundle.getMessage(IllegalCharactersInFileNameValidator.class, "ERR_INVALID_FILE_NAME", compName, text)
				: null; // NOI18N
		if (result != null) {
			problems.add(result);
		}
		return !invalid;
	}
397246
public static boolean compareFilesByAbsolutePath(final File sourceFile,
		final File fileToCompare)
	{
		return CompareFileExtensions
			.compareFiles(sourceFile, fileToCompare, false, true, true, true, true, true)
			.getAbsolutePathEquality();
	}
350663
def _IsValidPath(message_descriptor, path):
  """"""
  parts = path.split('.')
  last = parts.pop()
  for name in parts:
    field = message_descriptor.fields_by_name[name]
    if (field is None or
        field.label == FieldDescriptor.LABEL_REPEATED or
        field.type != FieldDescriptor.TYPE_MESSAGE):
      return False
    message_descriptor = field.message_type
  return last in message_descriptor.fields_by_name
94990
public static boolean isAbsolutePath(String uri) {
        boolean absolute = false;
        if (uri != null) {
            if (uri.indexOf(":/") != -1) {
                absolute = true;
            } else if (uri.indexOf(":\\") != -1) {
                absolute = true;
            }
        }

        return absolute;
    }
1253739
public static void containsAll(final Path expected, final Path actual) throws IOException {
		final Assertion<Path> exists = existsIn(expected, actual);
		if(Files.exists(expected)) {
			walkFileTree(expected, new SimpleFileVisitor<Path>() {
				@Override
				public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
					assertThat(file, exists);
					return super.visitFile(file, attrs);
				}
			});
		}
	}
1080884
def node_check_for_upload_create(self, relative_path, f):
        """"""
        if not relative_path:
            # we're at the root of the shared directory tree
            relative_path = str()

        # the (absolute) local address of f.
        local_path = path_join(self.local_path, relative_path, f)
        try:
            l_st = os.lstat(local_path)
        except OSError as e:
            """A little background here.
            Sometimes, in big clusters configurations (mail, etc.),
            files could disappear or be moved, suddenly.
            There's nothing to do about it,
            system should be stopped before doing backups.
            Anyway, we log it, and skip it.
            """
            self.logger.error("error while checking {}: {}".format(relative_path, e))
            return

        if local_path in self.exclude_list:
            self.logger.info("Skipping excluded file %s.", local_path)
            return

        # the (absolute) remote address of f.
        remote_path = path_join(self.remote_path, relative_path, f)

        # First case: f is a directory
        if S_ISDIR(l_st.st_mode):
            # we check if the folder exists on the remote side
            # it has to be a folder, otherwise it would have already been
            # deleted
            try:
                self.sftp.stat(remote_path)
            except IOError:  # it doesn't exist yet on remote side
                self.sftp.mkdir(remote_path)

            self._match_modes(remote_path, l_st)

            # now, we should traverse f too (recursion magic!)
            self.check_for_upload_create(path_join(relative_path, f))

        # Second case: f is a symbolic link
        elif S_ISLNK(l_st.st_mode):
            # read the local link
            local_link = os.readlink(local_path)
            absolute_local_link = os.path.realpath(local_link)

            # is it absolute?
            is_absolute = local_link.startswith("/")
            # and does it point inside the shared directory?
            # add trailing slash (security)
            trailing_local_path = path_join(self.local_path, '')
            relpath = os.path.commonprefix(
                [absolute_local_link,
                 trailing_local_path]
            ) == trailing_local_path

            if relpath:
                relative_link = absolute_local_link[len(trailing_local_path):]
            else:
                relative_link = None

            """
            # Refactor them all, be efficient!

            # Case A: absolute link pointing outside shared directory
            #   (we can only update the remote part)
            if is_absolute and not relpath:
                self.create_update_symlink(local_link, remote_path)

            # Case B: absolute link pointing inside shared directory
            #   (we can leave it as it is or fix the prefix to match the one of the remote server)
            elif is_absolute and relpath:
                if self.fix_symlinks:
                    self.create_update_symlink(
                        join(
                            self.remote_path,
                            relative_link,
                        ),
                        remote_path
                    )
                else:
                    self.create_update_symlink(local_link, remote_path)

            # Case C: relative link pointing outside shared directory
            #   (all we can do is try to make the link anyway)
            elif not is_absolute and not relpath:
                self.create_update_symlink(local_link, remote_path)

            # Case D: relative link pointing inside shared directory
            #   (we preserve the relativity and link it!)
            elif not is_absolute and relpath:
                self.create_update_symlink(local_link, remote_path)
            """

            if is_absolute and relpath:
                if self.fix_symlinks:
                    self.create_update_symlink(
                        path_join(
                            self.remote_path,
                            relative_link,
                        ),
                        remote_path
                    )
            else:
                self.create_update_symlink(local_link, remote_path)

        # Third case: regular file
        elif S_ISREG(l_st.st_mode):
            try:
                r_st = self.sftp.lstat(remote_path)
                if self._file_need_upload(l_st, r_st):
                    self.file_upload(local_path, remote_path, l_st)
            except IOError as e:
                if e.errno == errno.ENOENT:
                    self.file_upload(local_path, remote_path, l_st)

        # Anything else.
        else:
            self.logger.warning("Skipping unsupported file %s.", local_path)
1202505
@Override
  public void validate() {
    try {
      currentIfd = 0;
      for (TiffObject o : model.getImageIfds()) {
        currentIfd++;
        IFD ifd = (IFD) o;
        IfdTags metadata = ifd.getMetadata();
        int sft = -1;
        int photo = -1;
        int bps = -1;
        int planar = -1;
        int comp = -1;
        if (metadata.containsTagId(TiffTags.getTagId("SubfileType"))) {
          sft = (int) metadata.get(TiffTags.getTagId("SubfileType")).getFirstNumericValue();
        }
        if (metadata.containsTagId(TiffTags.getTagId("Compression"))) {
          comp = (int) metadata.get(TiffTags.getTagId("Compression")).getFirstNumericValue();
        }
        if (metadata.containsTagId(TiffTags.getTagId("PhotometricInterpretation"))) {
          photo = (int) metadata.get(TiffTags.getTagId("PhotometricInterpretation")).getFirstNumericValue();
        }
        if (metadata.containsTagId(TiffTags.getTagId("BitsPerSample"))) {
          bps = (int) metadata.get(TiffTags.getTagId("BitsPerSample")).getFirstNumericValue();
        }
        if (metadata.containsTagId(TiffTags.getTagId("PlanarConfiguration"))) {
          planar = (int) metadata.get(TiffTags.getTagId("PlanarConfiguration")).getFirstNumericValue();
        }

        int p = profile;

        // Determination of TIFF/IT file type
        if (sft == 1 || sft == -1) {
          if (comp == 1 || comp == 32895) {
            if (photo == 5) {
              if (planar == 1) {
                validateIfdCT(ifd, p);
              } else if (planar == 32768) {
                validateIfdCT(ifd, p);
              } else if (planar == 2) {
                if (bps > 1) {
                  validateIfdCT(ifd, p);
                } else if (bps == 1) {
                  validateIfdSD(ifd, p);
                }
              }
            } else if (photo == 2) {
              if (planar == 1) {
                validateIfdCT(ifd, p);
              } else if (planar == 32768) {
                validateIfdCT(ifd, p);
              } else if (planar == 2) {
                validateIfdCT(ifd, p);
              }
            } else if (photo == 8) {
              if (planar == 1) {
                validateIfdCT(ifd, p);
              } else if (planar == 32768) {
                validateIfdCT(ifd, p);
              } else if (planar == 2) {
                validateIfdCT(ifd, p);
              }
            } else if (photo == 0 || photo == 1) {
              if (bps == 1) {
                validateIfdBP(ifd, p);
              } else if (bps > 1) {
                validateIfdMP(ifd, p);
              }
            }
          } else if (comp == 4) {
            if (photo == 0 || photo == 1) {
              validateIfdBP(ifd, p);
            } else if (photo == 5) {
              validateIfdSD(ifd, p);
            }
          } else if (comp == 7) {
            if (photo == 5) {
              if (planar == 1) {
                validateIfdCT(ifd, p);
              }
            } else if (photo == 2) {
              if (planar == 1) {
                validateIfdCT(ifd, p);
              }
            } else if (photo == 6) {
              if (planar == 1) {
                validateIfdCT(ifd, p);
              }
            } else if (photo == 8) {
              if (planar == 1) {
                validateIfdCT(ifd, p);
              }
            } else if (photo == 0 || photo == 1) {
              if (bps > 1) {
                validateIfdMP(ifd, p);
              }
            }
          } else if (comp == 8) {
            if (photo == 5) {
              if (planar == 1) {
                validateIfdCT(ifd, p);
              } else if (planar == 32768) {
                validateIfdCT(ifd, p);
              } else if (planar == 2) {
                if (bps > 1) {
                  validateIfdCT(ifd, p);
                } else if (bps == 1) {
                  validateIfdSD(ifd, p);
                }
              }
            } else if (photo == 2) {
              if (planar == 1) {
                validateIfdCT(ifd, p);
              } else if (planar == 32768) {
                validateIfdCT(ifd, p);
              } else if (planar == 2) {
                validateIfdCT(ifd, p);
              }
            } else if (photo == 8) {
              if (planar == 1) {
                validateIfdCT(ifd, p);
              } else if (planar == 32768) {
                validateIfdCT(ifd, p);
              } else if (planar == 2) {
                validateIfdCT(ifd, p);
              }
            } else if (photo == 0 || photo == 1) {
              if (bps == 1) {
                validateIfdBP(ifd, p);
              } else if (bps > 1) {
                validateIfdMP(ifd, p);
              }
            }
          } else if (comp == 32896) {
            validateIfdLW(ifd, p);
          } else if (comp == 32897) {
            validateIfdHC(ifd, p);
          } else if (comp == 32898) {
            validateIfdBL(ifd, p);
          } else if (((sft >> 3) & 1) == 1) {
            validateIfdFP(ifd, p);
          }
        }
      }
    } catch (Exception e) {

    }
  }
766152
public static String relativePath(File self, File to) throws IOException {
        String fromPath = self.getCanonicalPath();
        String toPath = to.getCanonicalPath();

        // build the path stack info to compare
        String[] fromPathStack = getPathStack(fromPath);
        String[] toPathStack = getPathStack(toPath);

        if (0 < toPathStack.length && 0 < fromPathStack.length) {
            if (!fromPathStack[0].equals(toPathStack[0])) {
                // not the same device (would be "" on Linux/Unix)

                return getPath(Arrays.asList(toPathStack));
            }
        } else {
            // no comparison possible
            return getPath(Arrays.asList(toPathStack));
        }

        int minLength = Math.min(fromPathStack.length, toPathStack.length);
        int same = 1; // Used outside the for loop

        // get index of parts which are equal
        while (same < minLength && fromPathStack[same].equals(toPathStack[same])) {
            same++;
        }

        List<String> relativePathStack = new ArrayList<String>();

        // if "from" part is longer, fill it up with ".."
        // to reach path which is equal to both paths
        for (int i = same; i < fromPathStack.length; i++) {
            relativePathStack.add("..");
        }

        // fill it up path with parts which were not equal
        relativePathStack.addAll(Arrays.asList(toPathStack).subList(same, toPathStack.length));

        return getPath(relativePathStack);
    }
421275
public static String buildProperPath(String parentPath, String relativePathFromParent) {
        if (relativePathFromParent == null) return null;
        if (parentPath != null) {
            parentPath = parentPath.trim();
        }

        if (relativePathFromParent.startsWith(PATH_CURRENT)) {
            relativePathFromParent = relativePathFromParent.replaceFirst("(./)+", "");
        }

        String path;

        if (relativePathFromParent.startsWith(PATH_ROOT)) { //absolute
            path = relativePathFromParent;
        } else if (relativePathFromParent.startsWith(PATH_PARENT)) {
            while (relativePathFromParent.startsWith(PATH_PARENT)) {
                relativePathFromParent = relativePathFromParent.replaceFirst(PATH_PARENT, "");
                if (relativePathFromParent.startsWith(PATH_CURRENT)) {
                    relativePathFromParent = relativePathFromParent.replaceFirst(PATH_CURRENT, "");
                }
                parentPath = (parentPath == null || parentPath.equals(PATH_ROOT)) ? PATH_ROOT : getParentPath(parentPath);
            }
            path = parentPath + PATH_ROOT + relativePathFromParent;
        } else {
            path = parentPath + PATH_ROOT + relativePathFromParent;
        }

        return path.replaceAll("(/|\\./)+", "$1");
    }
1296664
def _is_relative(path, filename):
  """"""
  return os.path.abspath(os.path.join(path, filename)).startswith(path)
1251161
private boolean validateFilePath(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            throw new IllegalArgumentException("filePath must be a valid filePath within the file system.");
        }

        // Check if the filename exists as a File -- use an absolute file to ensure we have
        // a parent: even if that parent is ${user.dir} ...
        File loc = new File(filePath).getAbsoluteFile();

        return (loc.exists() || loc.getParentFile().exists());
    }
642752
public static String getElementID(final String relativePath) {
        final String fragment = FileUtils.getFragment(relativePath);
        if (fragment != null) {
            if (fragment.lastIndexOf(SLASH) != -1) {
                final String id = fragment.substring(fragment.lastIndexOf(SLASH) + 1);
                return id.isEmpty() ? null : id;
            }
        }
        return null;
    }
225053
public boolean findTopicId(final File absolutePathToFile, final String id) {

        if (!absolutePathToFile.exists()) {
            return false;
        }
        try {
            //load the file
            final DocumentBuilder builder = XMLUtils.getDocumentBuilder();
            builder.setEntityResolver(CatalogUtils.getCatalogResolver());
            final Document root = builder.parse(new InputSource(new FileInputStream(absolutePathToFile)));

            //get root element
            final Element doc = root.getDocumentElement();
            //do BFS
            final Queue<Element> queue = new LinkedList<>();
            queue.offer(doc);
            while (!queue.isEmpty()) {
                final Element pe = queue.poll();
                final NodeList pchildrenList = pe.getChildNodes();
                for (int i = 0; i < pchildrenList.getLength(); i++) {
                    final Node node = pchildrenList.item(i);
                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        queue.offer((Element)node);
                    }
                }
                final String classValue = pe.getAttribute(ATTRIBUTE_NAME_CLASS);
                if (classValue != null && TOPIC_TOPIC.matches(classValue)) {
                    //topic id found
                    if (pe.getAttribute(ATTRIBUTE_NAME_ID).equals(id)) {
                        return true;
                    }
                }
            }
            return false;
        } catch (final RuntimeException e) {
            throw e;
        } catch (final Exception e) {
            logger.error("Failed to read document: " + e.getMessage(), e);
        }
        return false;
    }
1338858
public void initializeRelativePath(ServletRequest request, String relativeTo) 
    {
        if ( relativeTo == null )
        {
            relativeTo = _relativeTo;
        }

        if ( relativeTo == null ) return;

        assert ! relativeTo.endsWith("/") : relativeTo;
        String path = getPath();
         
        // If this is a local (relative) path, prefix it with the given 'relativeTo' path, and save a flag.
        // We save this flag in a local variable because the Forward object may be saved/restored for use again.
        if (! getContextRelative() && ! FileUtils.isAbsoluteURI(path)) {
            assert path.startsWith("/") : path;
            setPath(relativeTo + path);
            setContextRelative(true);
            _outsidePageFlowDirectory = true;
        }
        
        // Store a flag in the request that will prevent another page flow from being initialized implicitly because
        // we're hitting a path within it.  We want to stay in the context of the current page flow.
        if (_outsidePageFlowDirectory) {
            PageFlowRequestWrapper.get(request).setStayInCurrentModule(true);
        }
    }
554429
private boolean checkFileLevelRelativeToRoot(Path filePath, int depth) {
    if (filePath == null) {
      return false;
    }
    Path path = filePath;
    for (int i = 0; i < depth - 1; i++) {
      path = path.getParent();
    }
    if (!path.getName().equals(folderName)) {
      return false;
    }
    return true;
  }