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

com.exactpro.sf.configuration.dictionary.ValidationHelper Maven / Gradle / Ivy

There is a newer version: 3.4.260
Show newest version
/******************************************************************************
 * Copyright 2009-2018 Exactpro (Exactpro Systems Limited)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package com.exactpro.sf.configuration.dictionary;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.exactpro.sf.common.impl.messages.xml.configuration.JavaType;
import com.exactpro.sf.common.messages.structures.IAttributeStructure;
import com.exactpro.sf.common.messages.structures.IDictionaryStructure;
import com.exactpro.sf.common.messages.structures.IFieldStructure;
import com.exactpro.sf.common.messages.structures.IMessageStructure;

public class ValidationHelper {
	
	private static final Logger logger = LoggerFactory.getLogger(ValidationHelper.class);

    public static void checkDuplicates(IMessageStructure message, Collection fields,
			List errors, boolean isMessage, DictionaryValidationErrorLevel level) {
		
		Set names = new HashSet<>();
		
		for (IFieldStructure field : fields) {
			if (names.contains(field.getName())) {
				
				if (isMessage) {
					errors.add(new DictionaryValidationError(field.getName(), null, 
							   "Duplicated message \"" + field.getName() + "\"", level, DictionaryValidationErrorType.ERR_DUPLICATE_NAME));
					
					logger.error("[{}] Duplicated message", field.getName());
					
				} else {
					
					errors.add(new DictionaryValidationError(message == null ? null : message.getName(), field.getName(), 
							   "Duplicated field \"" + field.getName() + "\"", level, DictionaryValidationErrorType.ERR_DUPLICATE_NAME));

                    logger.error("[{}{}] Duplicated field", message != null ? message.getName() + "/" : "", field.getName());
				}
				
			}
			
			names.add(field.getName());
		}
	}
	
	public static boolean checkTypeError(List errors, 
								   IMessageStructure  message, 
								   IFieldStructure    field, 
								   JavaType type, 
								   Object   value, 
								   DictionaryValidationErrorType errType) {
					
		if (!isTypeApplicable(field, type, value)) {
		
			errors.add(new DictionaryValidationError(message == null ? null : message.getName(), field == null? null:field.getName(), 
			"Value \"" + value + "\" is not applicable for " + getJavaTypeLabel(type) + " type",
			DictionaryValidationErrorLevel.FIELD, errType));
		
			return true;
		}
		
		return false;
	}

	public static void checkRequiredField(List errors, IMessageStructure message,
												  String fieldName) {
        if(message.getFields().get(fieldName) == null) {
			errors.add(new DictionaryValidationError(message.getName(), null,
					"Message  \"" + message.getName() + "\" doesn't contain " + fieldName +" field",
					DictionaryValidationErrorLevel.MESSAGE, DictionaryValidationErrorType.ERR_REQUIRED_FIELD));
		}
	}

	/**
	 * Match order and field names in message against order and field names in primaryFields.
	 *
	 * The method assumes that message.getFields() returns Map that contain fields in order in which they are
	 * represented in a dictionary that is validated
	 * @param errors List to add errors found at the check
	 * @param message Actual structure of fields to check its order against specified in @primaryFields
	 * @param primaryFields List of field names in order that must be stand on @message
	 * @param startPosition Start position of field in @message from where order is checked. Must be greater or equal zero
	 */
	public static void checkFieldsOrder(List errors, IMessageStructure message,
										List primaryFields, int startPosition) {
		List fields = new ArrayList<>(message.getFields().keySet());
		if(fields.size() - startPosition < primaryFields.size()) {
			errors.add(new DictionaryValidationError(message.getName(), null,
					"Not enough fields to check order of fields in message \"" + message.getName() + "\"."
					+ " Checking the order of fields from " + startPosition + " index. Number of fields to be validated: "
					+ primaryFields.size() + ". Actual number of fields in message: " + fields.size() +
					". Expected number of fields in message: " + (startPosition + primaryFields.size()),
					DictionaryValidationErrorLevel.MESSAGE, DictionaryValidationErrorType.ERR_VALUES));
			return;
		} else {
			for (int i = 0; i < primaryFields.size(); i++) {
				String actualField = fields.get(startPosition + i);
				String expectedField = primaryFields.get(i);
				if (!actualField.equals(expectedField))
					errors.add(new DictionaryValidationError(message.getName(), actualField,
							"The message " + message.getName() + " must have a field " +
									"" + expectedField + " " + "at index " + (startPosition + i)  + " but has " +
									"the " + actualField + " field",
							DictionaryValidationErrorLevel.MESSAGE, DictionaryValidationErrorType.ERR_VALUES));
			}
		}
	}

	public static void checkRequiredAttribute(List errors, IMessageStructure message,
												  String attributeName) {
		if(!message.getAttributes().containsKey(attributeName)) {
			errors.add(new DictionaryValidationError(message.getName(), null,"Message  \""
					+ message.getName() + "\" doesn't contain " + attributeName +" attribute",
					DictionaryValidationErrorLevel.MESSAGE, DictionaryValidationErrorType.ERR_ATTRIBUTES));
		}
	}

	public static boolean checkRequiredFieldAttribute(List errors, IMessageStructure message,
												   IFieldStructure field, String attributeName) {

		String messageName = message == null ? null : message.getName();
		String fieldName = field.getName();

		if(field.getAttributes().isEmpty()) {
			errors.add(new DictionaryValidationError(messageName, fieldName, "Attributes is null",
					DictionaryValidationErrorLevel.FIELD, DictionaryValidationErrorType.ERR_ATTRIBUTES));

			return false;

		} else if(!field.getAttributes().containsKey(attributeName)) {
			errors.add(new DictionaryValidationError(messageName, fieldName, "Field  \""
					+ fieldName + "\" doesn't contain  " + attributeName +" attribute in "
					+ messageName + " message" ,
					DictionaryValidationErrorLevel.FIELD, DictionaryValidationErrorType.ERR_ATTRIBUTES));

			return false;
		}
		return true;
	}

	public static boolean checkRequiredFieldAttributes(List errors, IMessageStructure message,
												   IFieldStructure field, String... attributes) {
		String messageName = message == null ? null : message.getName();
		String fieldName = field.getName();

		if(field.getAttributes().isEmpty()) {
			errors.add(new DictionaryValidationError(messageName, fieldName, "Attributes is null",
					DictionaryValidationErrorLevel.FIELD, DictionaryValidationErrorType.ERR_ATTRIBUTES));

			return false;
		} else {
			for(String attributeName : attributes) {
				if(!field.getAttributes().containsKey(attributeName)) {
					errors.add(new DictionaryValidationError(messageName, fieldName, "Field  \""
							+ fieldName + "\" doesn't contain  " + attributeName +" attribute in "
							+ messageName + " message" ,
							DictionaryValidationErrorLevel.FIELD, DictionaryValidationErrorType.ERR_ATTRIBUTES));

					return false;
				}
			}
		}
		return true;
	}

	public static void checkRequiredMessageExistence(List errors,
											   IDictionaryStructure dictionary, String messageName) {
        if(dictionary.getMessages().get(messageName) == null) {
			errors.add(new DictionaryValidationError(null, null,
					"Message  \"" + messageName + "\" is missing in dictionary",
					DictionaryValidationErrorLevel.DICTIONARY, DictionaryValidationErrorType.ERR_REQUIRED_FIELD));
		}

	}
	
	public static boolean checkErrorExistByText(List list, String text) {
		
		for (DictionaryValidationError error : list) {
			if (error.getError().equals(text)) {
				return true;
			}
		}
		
		return false;
	}

	public static boolean checkMessageAttributeType(List errors, IMessageStructure message,
													String attributeName, JavaType expectedJavaType,
													Object[] possibleValues) {

		IAttributeStructure messageTypeStructure = message.getAttributes().get(attributeName);

        return checkAttributeType(errors, messageTypeStructure, message, null,
											attributeName, expectedJavaType, possibleValues);
	}

	public static boolean checkFieldAttributeType(List errors, IFieldStructure field,
													String attributeName, JavaType expectedJavaType,
													Object[] possibleValues) {

		IAttributeStructure messageTypeStructure = field.getAttributes().get(attributeName);

        return checkAttributeType(errors, messageTypeStructure, null, field,
											attributeName, expectedJavaType, possibleValues);
	}

	public static boolean checkAttributeType(List errors,
											 IAttributeStructure messageTypeStructure,
											 IMessageStructure message, IFieldStructure field,
											 String attributeName, JavaType expectedJavaType,
											 Object[] possibleValues) {

		String messageName = message == null ? null : message.getName();
		String fieldName = field == null ? null : field.getName();
		String type = message == null ? "Field" : "Message";
		String name = message == null ? fieldName : messageName;

		if (messageTypeStructure == null) {
			errors.add(new DictionaryValidationError(messageName, fieldName,
					type + "  \"" + name
							+ "\" doesn't contain " + attributeName +  " attribute",
					DictionaryValidationErrorLevel.MESSAGE, DictionaryValidationErrorType.ERR_ATTRIBUTES));

			return false;
		}

        if(messageTypeStructure.getType() != expectedJavaType) {
			errors.add(new DictionaryValidationError(messageName, fieldName,
					type + "  \"" + name
							+ "\" contain " + attributeName +  " attribute"
							+ "incorrect type \"" + messageTypeStructure.getType() + "\"",
					DictionaryValidationErrorLevel.MESSAGE, DictionaryValidationErrorType.ERR_ATTRIBUTES));

			return false;
		}

		if(possibleValues != null) {
			for(Object possibleValue : possibleValues) {
				if(possibleValue.equals(messageTypeStructure.getValue())) {
					return true;
				}
			}

			errors.add(new DictionaryValidationError(messageName, fieldName,
					type + "  \"" + name
							+ "\" contain " + attributeName +  " attribute "
							+ "with incorrect value \"" + messageTypeStructure.getValue() + "\"",
					DictionaryValidationErrorLevel.MESSAGE, DictionaryValidationErrorType.ERR_ATTRIBUTES));

			return false;
		}

		return true;
	}
	
	private static boolean isTypeApplicable(IFieldStructure field, JavaType type, Object objValue) {
		
		String value = null;
		
		try {

            if(objValue == null || type == null || !(objValue instanceof String)) {
                return true;
            }

            value = (String)objValue;

            if(value.isEmpty()) {
                return true;
            }
			
			switch (type) {

            case JAVA_LANG_BOOLEAN:

                if(boolValueOf(value) == null) {
                    throw new ClassCastException();
                }
					break;
			
				case JAVA_LANG_BYTE :

                    if(Byte.valueOf(value) == null) {
                        throw new ClassCastException();
                    }
					break;	
			
				case JAVA_LANG_SHORT :

                    if(Short.valueOf(value) == null) {
                        throw new ClassCastException();
                    }
					break;
					
				case JAVA_LANG_INTEGER :

                    if(Integer.valueOf(value) == null) {
                        throw new ClassCastException();
                    }
					break;
					
				case JAVA_LANG_LONG :

                    if(Long.valueOf(value) == null) {
                        throw new ClassCastException();
                    }
					break;
					
				case JAVA_LANG_FLOAT :

                    if(Float.valueOf(value) == null) {
                        throw new ClassCastException();
                    }
					break;
					
				case JAVA_LANG_DOUBLE :

                    if(Double.valueOf(value) == null) {
                        throw new ClassCastException();
                    }
					break;
			
				case JAVA_LANG_CHARACTER :

                    if(value.length() > 1) {
                        throw new ClassCastException();
                    }
					break;
					
				case JAVA_MATH_BIG_DECIMAL :

                    if(BigDecimal.valueOf(Double.valueOf(value)) == null) {
                        throw new ClassCastException();
                    }
					break;
					
				default: break;
			}
			
			return true;
		
		} catch (Exception e) {
			
			logger.error("[{}] Value {} is not applicable for {} type", field == null ? null : field.getName() , value, getJavaTypeLabel(type), e);
			
			return false;
			
		}
	}
	
	private static Boolean boolValueOf(String value) {

        if("Y".equals(value)) {
            return true;
        }

        if("N".equals(value)) {
            return false;
        }

        if(Boolean.valueOf(value)) {
            return true;
        }

        if(!"false".equalsIgnoreCase(value)) {
            return null;
        }
		
		return false;
	}
	
	private static String getJavaTypeLabel(JavaType type) {
        return ClassUtils.getShortClassName(type.value());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy