All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sf.aguacate.validator.impl.InputValidatorImpl Maven / Gradle / Ivy

There is a newer version: 0.10.9
Show newest version
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);
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy