public static String requireValidFilePath(String filePath, boolean mustExist) {
        if (LangUtils.isBlank(filePath)) {
            throw validationError("Path can not be the empty string or null");
        }

        Character ch = containsInvalidCharacters(filePath);
        if (ch != null) {
            throw validationError("Invalid path: (" + filePath + ") contains invalid character: " + ch);
        }

        filePath = URLDecoder.decode(filePath, StandardCharsets.UTF_8);

        // standardize Windows paths from d:/test to d:\\test
        if (isSystemWindows()) {
            filePath = filePath.replace("/", "\\");
        }

        try {
            File file = new File(filePath);
            File parentFile = file.getParentFile();

            if (parentFile == null) {
                throw validationError("Invalid directory, \"" + filePath + "\" is not valid.");
            }
            if (mustExist && !file.exists()) {
                throw validationError("Invalid file, \"" + file + "\" does not exist.");
            }
            if (mustExist && !parentFile.exists()) {
                throw validationError("Invalid directory, file parent directory does not exist.");
            }
            if (mustExist && !parentFile.isDirectory()) {
                throw validationError("Invalid directory, file parent is not a directory.");
            }
            // CVE-2022-31159 Partial Path Traversal Vulnerability
            if (!file.getCanonicalFile().toPath().startsWith(parentFile.getCanonicalFile().toPath())) {
                throw validationError("Invalid directory, \"" + file + "\" does not reside inside specified parent.");
            }
            // SONATYPE-2018-0608 prevent path traversal like "..\..\test"
            if (!file.getCanonicalPath().equals(filePath)) {
                throw validationError("Invalid directory, name does not match the canonical path." );
            }
        }
        catch (IOException ex) {
            throw validationError("Failure to validate directory path: " + ex.getMessage());
        }

        return filePath;
    }
Check the file path to ensure its valid and prevent directory traversal security issues.

@param filePath the file path to test
@param mustExist true if the directory must exist on disk, false if not
@return the updated file path
primefaces/src/main/java/org/primefaces/util/FileUploadUtils.java