net.sf.aguacate.validator.impl.InputValidatorImpl Maven / Gradle / Ivy
package net.sf.aguacate.validator.impl;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import net.sf.aguacate.model.Field;
import net.sf.aguacate.validator.InputValidationResponse;
import net.sf.aguacate.validator.InputValidator;
import net.sf.aguacate.validator.ValidationConversionResult;
import net.sf.aguacate.validator.ValidatorConverter;
public class InputValidatorImpl implements InputValidator {
private final ValidatorConverter validatorConverter;
private final Field fieldId;
private final Map fields;
public InputValidatorImpl(ValidatorConverter validatorConverter, Field fieldId, Map fields) {
this.validatorConverter = validatorConverter;
this.fieldId = fieldId;
this.fields = fields;
}
@Override
public InputValidationResponse validate(String id, Map body) {
ValidationConversionResult result = validatorConverter.validateConvert(fieldId, id);
String name = fieldId.getName();
if (result.isSuccess()) {
Map context = new HashMap<>();
context.put(name, result.getValue());
return validate0(context, body);
} else {
return new InputValidationResponse(null, Collections.singletonMap(name, result));
}
}
@Override
public InputValidationResponse validate(Map body) {
return validate0(new HashMap<>(), body);
}
InputValidationResponse validate0(Map context, Map body) {
for (Map.Entry entry : fields.entrySet()) {
String name = entry.getKey();
Field field = entry.getValue();
Object value = body.get(name);
if (value == null) {
if (!field.isOptional()) {
// missing parameter
return new InputValidationResponse(null,
Collections.singletonMap(name, new ValidationConversionResult("Missing parameter")));
}
} else {
ValidationConversionResult result = validatorConverter.validateConvert(field, value);
if (!result.isSuccess()) {
return new InputValidationResponse(null, Collections.singletonMap(name, result));
} else {
context.put(name, result.getValue());
}
}
}
// SUCCESS
return new InputValidationResponse(context, null);
}
}