com.gtcgroup.jped.valid.helper.JpvValidationUtilHelper.java Source code

Java tutorial

Introduction

Here is the source code for com.gtcgroup.jped.valid.helper.JpvValidationUtilHelper.java

Source

/*
 * [Licensed per the Open Source "MIT License".]
 *
 * Copyright (c) 2006 - 2016 by
 * Global Technology Consulting Group, Inc. at
 * http://gtcGroup.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package com.gtcgroup.jped.valid.helper;

import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gtcgroup.jped.core.po.JpcBasicExceptionPO;
import com.gtcgroup.jped.valid.exception.JpvValidationException;
import com.gtcgroup.jped.valid.po.JpvBasicValidatorPO;
import com.gtcgroup.jped.valid.tbd.JpvErrorMessageTBD;
import com.gtcgroup.jped.valid.tbd.JpvErrorMessagesTBD;
import com.gtcgroup.jped.valid.tbd.JpvErrorFieldTBD;

/**
 * This Util Helper class provides convenience methods for validation.
 *
 * <p style="font-family:Verdana; font-size:10px; font-style:italic">
 * Copyright (c) 2006 - 2016 by Global Technology Consulting Group, Inc. at
 * <a href="http://gtcGroup.com">gtcGroup.com </a>.
 * </p>
 *
 * @author Marvin Toll
 * @since v3.0
 */
public class JpvValidationUtilHelper {

    private static final String CLASS_NAME = JpvValidationUtilHelper.class.getSimpleName();

    private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();

    /** The {@link Validator} instance is thread safe and can be cached. */
    private static final Validator VALIDATOR = JpvValidationUtilHelper.VALIDATOR_FACTORY.getValidator();

    /**
     * @param instance
     * @return {@link String}
     */
    public static String convertInstanceToJsonString(final Object instance) {

        final String methodName = "convertInstanceToJsonString";

        String result;
        try {

            final ObjectMapper objectMapper = new ObjectMapper();
            result = objectMapper.writeValueAsString(instance);

        } catch (final Exception e) {
            throw new JpvValidationException(
                    new JpcBasicExceptionPO().setClassName(JpvValidationUtilHelper.CLASS_NAME)
                            .setMethodName(methodName).setMessage("The result."),
                    e);
        }

        return result;
    }

    /**
     * This method performs Java Bean validation.
     *
     * @param <PO>
     * @param <CO>
     * @param validatorPO
     * @return List<JpvErrorMessageTBD>
     */
    public static <PO extends JpvBasicValidatorPO, CO extends JpvErrorMessagesTBD> CO validate(
            final PO validatorPO) {

        // Declare/Initialize
        final Set<ConstraintViolation<Object>> constraintViolationSet = new HashSet<ConstraintViolation<Object>>();
        final Object[] instancesToBeValidated = validatorPO.getInstancesToBeValidated();

        // Validate each instance... more than one error can occur.
        for (final Object instanceToBeValidated : instancesToBeValidated) {

            constraintViolationSet.addAll(
                    JpvValidationUtilHelper.VALIDATOR.validate(instanceToBeValidated, validatorPO.getGroups()));

            // Check for stopping after the first error.
            if (validatorPO.isStopAfterFirstError() && constraintViolationSet.size() > 0) {
                break;
            }
        }

        @SuppressWarnings("unchecked")
        final CO errorMessagesCO = (CO) JpvValidationUtilHelper.convertConstraintViolationsToErrors(validatorPO,
                constraintViolationSet);

        return errorMessagesCO;
    }

    /**
     * @param validatorPO
     * @return {@link JpvErrorMessagesTBD}
     */
    public static JpvErrorMessagesTBD validateDeclarative(final JpvBasicValidatorPO validatorPO) {

        final JpvErrorMessagesTBD errorMessagesTBD = JpvValidationUtilHelper.validate(validatorPO);

        return errorMessagesTBD;
    }

    /**
     * This method converts a set of violations to a list of instances.
     *
     * @param validaterPO
     * @param constraintViolationSet
     * @return ErrorMessageList
     */
    @SuppressWarnings("unchecked")
    protected static JpvErrorMessagesTBD convertConstraintViolationsToErrors(final JpvBasicValidatorPO validaterPO,
            final Set<ConstraintViolation<Object>> constraintViolationSet) {

        // Declare/Initialize
        final JpvErrorMessagesTBD errorMessagesCO = new JpvErrorMessagesTBD();
        JpvErrorMessageTBD errorMessageCO;
        JpvErrorFieldTBD<String, String, String> errorFieldCO;

        // Loop through the violations and convert to errors.
        for (final ConstraintViolation<Object> constraintViolation : constraintViolationSet) {

            // Retrieve values from the constraint instance.
            final String classname = constraintViolation.getLeafBean().getClass().getSimpleName();
            final String fieldname = constraintViolation.getPropertyPath().toString();
            String fieldvalue;

            if (null == constraintViolation.getInvalidValue()) {
                fieldvalue = "null";
            } else {

                fieldvalue = JpvValidationUtilHelper
                        .convertInstanceToJsonString(constraintViolation.getInvalidValue());
            }

            // Populate the error instances.
            errorFieldCO = new JpvErrorFieldTBD<String, String, String>(classname, fieldname, fieldvalue);

            errorMessageCO = new JpvErrorMessageTBD(constraintViolation.getMessage(), Calendar.getInstance());

            errorMessageCO.addErrorField(errorFieldCO);

            errorMessagesCO.addErrorMessage(errorMessageCO);

            if (validaterPO.isStopAfterFirstError()) {

                // One validation processed.
                break;
            }
        }

        return errorMessagesCO;
    }
}