I am writing simple file validator for my java ee app and I am stack with my class api. I need specific error descriptions, but also I would like to have boolean values indicating whether file is valid or not. Please give me some hints how to do it 'smart'.
package pl.poznan.put.ims.business.attachments;
import java.util.List;
import java.util.ArrayList;
import com.google.inject.Inject;
import pl.poznan.put.ims.business.entities.Attachment;
import pl.poznan.put.ims.business.exceptions.AttachmentValidationException;
import pl.poznan.put.ims.settings.IFileSystemSettings;
public class AttachmentValidator implements IAttachmentValidator
{
IFileSystemSettings messageSettings;
private List<String> errors;
@Inject
public AttachmentValidator(IFileSystemSettings messageSettings)
{
this.messageSettings = messageSettings;
this.errors = new ArrayList<String>();
}
@Override
public boolean validate(List<Attachment> attachments) throws AttachmentValidationException
{
for (Attachment attachment : attachments) {
validate(attachment);
}
if(attachments.size() > messageSettings.getMaxFilesCount())
errors.add("Attachments max number exceeded.");
if(!errors.isEmpty())
throw new AttachmentValidationException(errors);
return true;
}
@Override
public boolean validate(Attachment attachment)
{
boolean isValid = validateLimitExceeded(attachment);
isValid &= validateNull(attachment);
return !isValid;
}
private boolean validateLimitExceeded(Attachment attachment)
{
boolean exceeded = attachment.getFileSize() > messageSettings.getMaxFileSize();
if(exceeded)
errors.add("Max file size limit exceeded. File: " + attachment.getFileDisplayName() + ". Size: "+ attachment.getFileSize()/1024/1024 + "MB.");
return exceeded;
}
private boolean validateNull(Attachment attachment)
{
if(attachment == null) {
errors.add("No attachment.");
return false;
}
return true;
}
@Override
public List<String> getErrors()
{
return errors;
}
@Override
public long getTotalMaxFilesSize() {
return messageSettings.getMaxFilesCount() * messageSettings.getMaxFileSize();
}
}