All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.kiwiproject.validation.FilePathValidator Maven / Gradle / Ivy

Go to download

Kiwi is a utility library. We really like Google's Guava, and also use Apache Commons. But if they don't have something we need, and we think it is useful, this is where we put it.

There is a newer version: 4.5.2
Show newest version
package org.kiwiproject.validation;

import static java.util.Objects.isNull;
import static org.kiwiproject.validation.InternalKiwiValidators.containsNulCharacter;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import lombok.extern.slf4j.Slf4j;

import java.nio.file.Path;

/**
 * Validates that a string value is a valid path, exists, and is a regular file (not a directory).
 *
 * @implNote Please read the implementation note in {@link FilePath} regarding the possibility of
 * Path Traversal attacks.
 */
@Slf4j
public class FilePathValidator implements ConstraintValidator {

    private FilePath filePath;

    @Override
    public void initialize(FilePath constraintAnnotation) {
        this.filePath = constraintAnnotation;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (isNull(value)) {
            return filePath.allowNull();
        }

        try {
            var file = Path.of(value).toFile();
            return file.exists() && file.isFile();
        } catch (Exception e) {
            var nulCharacterMessage = containsNulCharacter(value) ? " Path contains Nul character!" : "";
            LOG.warn("Exception thrown validating path.{}", nulCharacterMessage, e);
            return false;
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy