fr.ird.observe.validation.validators.CommentLengthFieldDtoValidator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of common-validation Show documentation
Show all versions of common-validation Show documentation
ObServe Toolkit Common Validation module
package fr.ird.observe.validation.validators;
/*-
* #%L
* ObServe Toolkit :: Common Validation
* %%
* Copyright (C) 2017 - 2019 IRD, Ultreia.io
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* .
* #L%
*/
import com.opensymphony.xwork2.validator.ValidationException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.nuiton.validator.xwork2.field.NuitonFieldValidatorSupport;
import java.util.Objects;
import static io.ultreia.java4all.i18n.I18n.n;
/**
* Created by tchemit on 17/10/2018.
*
* @author Tony Chemit - [email protected]
*/
public class CommentLengthFieldDtoValidator extends NuitonFieldValidatorSupport {
private static final Logger log = LogManager.getLogger(CommentLengthFieldDtoValidator.class);
private int commentLength;
private int maxLength = 1024;
public CommentLengthFieldDtoValidator() {
super.setDefaultMessage(n("observe.validation.comment.too.big") + "##${maxLength}##${commentLength}");
}
@Override
public void setSkip(String skip) {
throw new IllegalStateException("Can't use this parameter!");
}
@Override
protected void validateWhenNotSkip(Object object) throws ValidationException {
String fieldName = Objects.requireNonNull(getFieldName());
String fieldValue = (String) getFieldValue(fieldName, object);
if (fieldValue == null || fieldValue.length() <= maxLength) {
return;
}
commentLength = fieldValue.length();
try {
log.debug(String.format("[%s] Found a comment too big (%s).", getFieldName(), commentLength));
addFieldError(fieldName, object);
} finally {
commentLength = 0;
}
}
@Override
public String getValidatorType() {
return "commentLengthField";
}
public int getCommentLength() {
return commentLength;
}
public int getMaxLength() {
return maxLength;
}
public void setMaxLength(int maxLength) {
this.maxLength = maxLength;
}
}