1
\$\begingroup\$

I need make validation of Multipart file in form class. I wrote custom annotation for form class which validate Multipart file. This code works great, but I don`t know if this is a good approach.

This code validates the Multipart file and shows a message on page if validation is invalid using jsp tag (form:errors cssClass="form-error" path="thumbnail").

I have two form classes: add form, and edit form. This annotation is used in both classes.

This is the form class:

@PostThumbnailValidation(type="edit")
public class EditPostForm {
private Integer id;
@NotEmpty(message = "Enter post name")
private String name;
@NotEmpty(message = "Enter post content")
private String content;
@NotEmpty(message = "Choose post type")
private String type;
private MultipartFile thumbnail;

public EditPostForm(){}

public EditPostForm(PostEntity post){
    this.name = post.getName();
    this.content = post.getContent();
    this.type = post.getType();
    this.id = post.getId();
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getContent() {
    return content;
}

public void setContent(String content) {
    this.content = content;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public MultipartFile getThumbnail() {
    return thumbnail;
}

public void setThumbnail(MultipartFile thumbnail) {
    this.thumbnail = thumbnail;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}
}

This is the annotation implementation class:

public class PostThumbnailValidationImpl implements ConstraintValidator<PostThumbnailValidation, Object> {

private String message;
private final Logger logger = LoggerFactory.getLogger(PostThumbnailValidationImpl.class);
private Class clazz;
MultipartFile thumbnail;
String type;
String formType;
FileValidate validate;
Integer id;
@Autowired
private PostService service;

@Override
public void initialize(PostThumbnailValidation constraintAnnotation) {
    message = constraintAnnotation.message();
    formType = constraintAnnotation.type();

}

@Override
public boolean isValid(Object form, ConstraintValidatorContext context) {
    boolean isValid = false;
    clazz = form.getClass();
    try {
        type = (String) clazz.getMethod("getType").invoke(form);
    } catch (Exception ex) {
        logger.error("Validation Error. Cant get post type from form class. Exeption: " + ex.getMessage());
    }

    try {
        thumbnail = (MultipartFile) clazz.getMethod("getThumbnail").invoke(form);

    } catch (Exception ex) {
        logger.error("Validation Error. Cant get thumbnail from form class. Exeption: " + ex.getMessage());
    }

    if ("edit".equals(formType)) {
        logger.info("Edit post validation form thumbnail.");
        try {
            id = (Integer) clazz.getMethod("getId").invoke(form);
        } catch (Exception ex) {
            logger.error("Validation Error. Cant get post id from form class. Exeption: " + ex.getMessage());
        }
        if ("post".equals(type)) {
            logger.info("Thumbnail is null: " + (thumbnail == null));
            return true;
        }
        if (type.equals(service.findOneOrigin(id).getType()) || !"application/octet-stream".equals(thumbnail.getContentType())) {
            isValid = checkPostType();
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(message).addPropertyNode("thumbnail").addConstraintViolation();
            return isValid;
        }
    }
    logger.info("Add post validation form thumbnail.");
    if ("post".equals(type)) {
        return isValid = true;
    }
    isValid = checkPostType();
    context.disableDefaultConstraintViolation();
    context.buildConstraintViolationWithTemplate(message).addPropertyNode("thumbnail").addConstraintViolation();
    return isValid;
}

private boolean checkPostType() {
    boolean isValid = false;
    logger.info("Check post type.");
    if ("post".equals(type)) {
        logger.info("Thumbnail is null: " + (thumbnail == null));
        return true;
    }
    if (!"application/octet-stream".equals(thumbnail.getContentType())) {
        if (type.equals(getFileType(thumbnail))) {
            return isValid = validateFile(type, thumbnail);
        }
        String result = ("audio".equals(type)) ? "audio file. (MP3)" : "post image. (jpg, png)";
        message = "Choose ".concat(result);
    }
    return isValid;
}

private boolean validateFile(String type, MultipartFile file) {
    if (file == null) {
        return false;
    }
    String fileFormat = file.getContentType().split("/", 2)[1];
    if (type.equals(getFileType(file))) {
        boolean isValid = false;
        if (type.equals("audio")) {
            validate = new AudioFileValidate();
            isValid = validate.validate(file);
        }
        if (type.equals("image")) {
            validate = new ImageFileValidate();
            isValid = validate.validate(file);
        }
        message = validate.getMessage();
        return isValid;
    }
    message = validate.getMessage();
    return false;
}

// This method return file content type.
private String getFileType(MultipartFile file) {
    String type = file.getContentType();
    return type.split("/", 2)[0];
}
}
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to CodeReview! I hope you get some nice answers! \$\endgroup\$
    – Graipher
    Sep 20, 2016 at 9:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.