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

br.com.esec.icpm.server.validate.WsValidate Maven / Gradle / Ivy

There is a newer version: 1.13.4
Show newest version
package br.com.esec.icpm.server.validate;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.activation.DataHandler;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;

public class WsValidate {

	public static void validate(Object object) throws WsValidateException {
		Class clazz = object.getClass();
		Field[] fields = clazz.getDeclaredFields();

		List failedFieldsName = new ArrayList();
		
		try {
			for (Field field : fields) {
				field.setAccessible(true);
				
				XmlElement elementAnnotation = field.getAnnotation(XmlElement.class);
				if (elementAnnotation != null && (elementAnnotation.required() || elementAnnotation.nillable())) {
					if (isEmpty(object, field)) {
						failedFieldsName.add(elementAnnotation.name());
					}
				}

				XmlAttribute attributeAnnotation = field.getAnnotation(XmlAttribute.class);
				if (attributeAnnotation != null && attributeAnnotation.required()) {
					if (isEmpty(object, field)) {
						failedFieldsName.add(attributeAnnotation.name());
					}
				}

			}
		} catch (IllegalArgumentException e) {
			throw new IllegalStateException();
		} catch (IllegalAccessException e) {
			throw new IllegalStateException();
		}
		
		if (failedFieldsName.size() > 0) {
			throw new WsValidateException(failedFieldsName);
		}
	}

	private static boolean isEmpty(Object object, Field field) throws IllegalAccessException {
		Object value = field.get(object);
		if (value == null)
			return true;
		
		if (value instanceof DataHandler) {
			try {
				if (((DataHandler) value).getInputStream() == null || 
						((DataHandler) value).getInputStream().available() == 0)
					return true;
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		
		return false;
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy