com.evasion.common.inputfile.FileValidator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of COMMON Show documentation
Show all versions of COMMON Show documentation
API de l'application modulaire evasion-en-ligne
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.evasion.common.inputfile;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import org.apache.commons.fileupload.FileItem;
/**
*
* @author sebastien.glon
*/
@FacesValidator(value = "fileValidator")
public class FileValidator implements Validator {
/*
* If you want to change the maximum size of the file to be uploaded, you can change the value for MAX_FILE_SIZE
*/
private static final long MAX_FILE_SIZE = 10485760L; // 10MB.
/*
*you can change the extensions of the files to be uploaded
*/
private static final String[] VALID_EXTENSIONS = {"jpg", "jpeg", "gif", "bmp", "png"}; //set valid formats
@Override
public void validate(FacesContext context, UIComponent component, Object value)
throws ValidatorException {
if (value != null) {
final FileItem uploadedFile = (FileItem) value;
final String extension = uploadedFile.getFieldName().substring(uploadedFile.getFieldName().lastIndexOf(".") + 1).toLowerCase();
boolean valid = false;
for (String ext : VALID_EXTENSIONS) {
if (ext.equals(extension)) {
valid = true;
break;
}
}
//check if the extension has been set to valid, if not throw an exception
if (!valid) {
uploadedFile.delete();
throw new ValidatorException(new FacesMessage(String.format(
"Invalid file format, Reqired formats are of " + getValidExtensions())));
}
//check the files size
if (uploadedFile.getSize() > MAX_FILE_SIZE) {
uploadedFile.delete();
throw new ValidatorException(new FacesMessage(String.format(
"File exceeds maximum permitted size of %d Kilo Bytes.", MAX_FILE_SIZE / 1024)));
}
}
}
private String getValidExtensions() {
StringBuilder strExtensions = new StringBuilder();
for (String ext : VALID_EXTENSIONS) {
strExtensions.append(ext).append(" ,");
}
return strExtensions.substring(0, strExtensions.lastIndexOf(" ,"));
}
}