net.sf.aguacate.validator.impl.InputValidatorImpl Maven / Gradle / Ivy
package net.sf.aguacate.validator.impl;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import net.sf.aguacate.configuration.field.Field;
import net.sf.aguacate.validator.InputValidationResponse;
import net.sf.aguacate.validator.InputValidator;
import net.sf.aguacate.validator.ValidationConversionResult;
public class InputValidatorImpl implements InputValidator {
private final Field fieldId;
private final Field[] fields;
public InputValidatorImpl(Field fieldId, Map fields) {
this(fieldId, fields.values());
}
public InputValidatorImpl(Field fieldId, Collection fields) {
this(fieldId, fields.toArray(new Field[fields.size()]));
}
public InputValidatorImpl(Field fieldId, Field[] fields) {
this.fieldId = fieldId;
this.fields = fields;
}
@Override
public InputValidationResponse validate(String id, Map body) {
ValidationConversionResult result = fieldId.validateAndConvert(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 (Field field : fields) {
String name = field.getName();
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 = field.validateAndConvert(value);
if (!result.isSuccess()) {
return new InputValidationResponse(null, Collections.singletonMap(name, result));
} else {
context.put(name, result.getValue());
}
}
}
// SUCCESS
return new InputValidationResponse(context, null);
}
}