in digital-document-service/src/main/java/com/epam/digital/data/platform/dgtldcmnt/validator/AllowedUploadedDocumentValidator.java [100:142]
private boolean isDetectedFileContentTypeEqualsToInputContentType(
UploadDocumentDto uploadDocumentDto, ConstraintValidatorContext context) {
log.debug("Validating file content type for process-instance '{}'",
uploadDocumentDto.getRootProcessInstanceId());
final var filename = uploadDocumentDto.getFilename();
final var inputFile = uploadDocumentDto.getFileInputStream();
final String fileContentType;
try {
fileContentType = tika.detect(inputFile, filename);
} catch (IOException e) {
context.buildConstraintViolationWithTemplate(
"Couldn't read the file to detect file content type")
.addPropertyNode("fileInputStream")
.addConstraintViolation()
.disableDefaultConstraintViolation();
return false;
}
final var inputContentType = uploadDocumentDto.getContentType();
final var isDetectedContentTypeEqualsToInputContentType = fileContentType.equals(
inputContentType);
final var isDetectedContentTypeCorrespondsToInputContentType =
DocumentConstants.CORRESPONDED_MEDIA_TYPES
.getOrDefault(inputContentType, Set.of())
.contains(fileContentType);
final var shouldPassSignatureType = !signedFileDetectionEnabled && fileContentType.equals(
DocumentConstants.SIGNATURE_TYPE);
final var isValid = isDetectedContentTypeEqualsToInputContentType
|| isDetectedContentTypeCorrespondsToInputContentType
|| shouldPassSignatureType;
if (!isValid) {
context.buildConstraintViolationWithTemplate(
"Detected file content type doesn't match input content type")
.addPropertyNode("fileInputStream")
.addConstraintViolation()
.disableDefaultConstraintViolation();
}
log.debug("Detected file content type '{}' corresponds to input content-type '{}' - '{}'."
+ "Content type detection for singed files enabled - '{}'",
fileContentType, inputContentType, isValid, signedFileDetectionEnabled);
return isValid;
}