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

net.sf.jsefa.common.validator.traversal.TraversingComplexValueValidator Maven / Gradle / Ivy

Go to download

JSefa (Java Simple exchange format api) is a simple library for stream-based serialization of java objects to XML, CSV, FLR or any other format and back again using an iterator-style interface independent of the serialization format. The mapping between java object types and types of the serialization format (e. g. xml complex element types) can be defined either by annotating the java classes or programmatically using a simple API. The current implementation supports XML, CSV and FLR - for XML it is based on JSR 173.

The newest version!
/*
 * Copyright 2007 the original author or authors.
 *
 * 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 net.sf.jsefa.common.validator.traversal;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.jsefa.ObjectPathElement;
import net.sf.jsefa.common.accessor.ObjectAccessor;
import net.sf.jsefa.common.mapping.FieldDescriptor;
import net.sf.jsefa.common.util.ReflectionUtil;
import net.sf.jsefa.common.validator.ValidationError;
import net.sf.jsefa.common.validator.ValidationResult;
import net.sf.jsefa.common.validator.Validator;

final class TraversingComplexValueValidator extends TraversingValidator {

    private Validator rootValidator;

    private Map validatorsByFieldNameAndType;

    private List fieldNames;

    private ObjectAccessor objectAccessor;

    private static final ThreadLocal> OBJECT_PATH = new ThreadLocal>();

    void init(Validator rootValidator, Map fieldValidators, ObjectAccessor objectAccessor) {
        if (checkTriviality(rootValidator, fieldValidators)) {
            return;
        }
        this.rootValidator = rootValidator;
        this.objectAccessor = objectAccessor;
        this.validatorsByFieldNameAndType = createValidatorsByFieldNameAndTypeMap(fieldValidators);
        this.fieldNames = createFieldNamesList(fieldValidators);
    }

    /**
     * {@inheritDoc}
     */
    public ValidationResult validate(Object object) {
        if (isTrivial()) {
            return ValidationResult.VALID;
        }
        if (onObjectPath(object)) {
            return ValidationResult.VALID;
        }
        addToObjectPath(object);
        try {
            List errors = new ArrayList();
            if (this.rootValidator != null) {
                errors.addAll(this.rootValidator.validate(object).getErrors());
            }
            for (String fieldName : this.fieldNames) {
                Object fieldValue = this.objectAccessor.getValue(object, fieldName);
                if (fieldValue != null) {
                    Validator fieldValidator = getFieldValidator(fieldName, fieldValue);
                    if (fieldValidator != null) {
                        for (ValidationError error : fieldValidator.validate(fieldValue).getErrors()) {
                            errors.add(createValidationError(error, new ObjectPathElement(object.getClass(),
                                    fieldName)));
                        }
                    }
                }
            }
            return ValidationResult.create(errors);
        } finally {
            removeFromObjectPath(object);
        }
    }

    @SuppressWarnings("unchecked")
    private Validator getFieldValidator(String fieldName, Object fieldValue) {
        Object value = this.validatorsByFieldNameAndType.get(fieldName);
        if (value instanceof Validator) {
            return (Validator) value;
        } else if (value instanceof Map) {
            return ReflectionUtil.getNearest(fieldValue.getClass(), (Map, Validator>) value);
        } else {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    private Map createValidatorsByFieldNameAndTypeMap(
            Map validatorsByFieldDescriptor) {
        Map result = new HashMap();
        for (FieldDescriptor fieldDescriptor : validatorsByFieldDescriptor.keySet()) {
            Map, Validator> map = (Map, Validator>) result.get(fieldDescriptor.getName());
            if (map == null) {
                map = new HashMap, Validator>();
                result.put(fieldDescriptor.getName(), map);
            }
            map.put(fieldDescriptor.getObjectType(), validatorsByFieldDescriptor.get(fieldDescriptor));
        }
        for (String fieldName : result.keySet()) {
            Map, Validator> map = (Map, Validator>) result.get(fieldName);
            if (map.size() == 1) {
                result.put(fieldName, map.values().iterator().next());
            }
        }
        return result;
    }

    private List createFieldNamesList(Map validators) {
        List result = new ArrayList();
        for (FieldDescriptor fieldDescriptor : validators.keySet()) {
            if (!result.contains(fieldDescriptor.getName())) {
                result.add(fieldDescriptor.getName());
            }
        }
        return result;
    }

    private boolean onObjectPath(Object object) {
        List path = TraversingComplexValueValidator.OBJECT_PATH.get();
        return path != null && path.contains(object);
    }

    private void addToObjectPath(Object object) {
        List path = TraversingComplexValueValidator.OBJECT_PATH.get();
        if (path == null) {
            path = new ArrayList();
            TraversingComplexValueValidator.OBJECT_PATH.set(path);
        }
        path.add(object);
    }

    private void removeFromObjectPath(Object object) {
        TraversingComplexValueValidator.OBJECT_PATH.get().remove(object);
    }

    private ValidationError createValidationError(ValidationError validationError, ObjectPathElement prefix) {
        List relativeObjectPath = new ArrayList();
        relativeObjectPath.add(prefix);
        relativeObjectPath.addAll(validationError.getRelativeObjectPath());
        return ValidationError.create(validationError.getErrorCode(), validationError.getErrorText(),
                relativeObjectPath.toArray(new ObjectPathElement[0]));
    }

    private boolean checkTriviality(Validator rootValidator, Map validators) {
        Collection allValidators = new ArrayList(validators.values());
        if (rootValidator != null) {
            allValidators.add(rootValidator);
        }
        return checkTriviality(allValidators);
    }

}