How to fix Sonar error "not construct the path from user-controlled data"?

80 Views Asked by At

I am getting the Sonar error

Change this code to not construct the path from user-controlled data.

Already added a validation before using fileName inside OutputStream.

Below is the code I am using:

if (Util.isValidFileName(fileName)) {
    try (FileOutputStream fo = new FileOutputStream(fileName)) {
    }
}

public static boolean isValidFileName(String filePath) {
    Pattern pattern = Pattern.compile("[/\\:*?\"<>|]");
    if (filePath == null || filePath.trim().isEmpty() || pattern.matcher(filePath).find()) {
        throw new RuntimeException("Invalid file destination path");
    }
    return true;
}

Also tried something like below but getting same Sonar error.

if(!FilenameUtils.getExtension(fileName).contains("exe")) {
    try (FileOutputStream fout = new FileOutputStream(fileName)) {
    }
}

Please suggest how can I add the validation to resolve this sonar error.

0

There are 0 best solutions below