no.abmu.questionnarie.domain.PostValidator.java Source code

Java tutorial

Introduction

Here is the source code for no.abmu.questionnarie.domain.PostValidator.java

Source

/*
 ****************************************************************************
 *                                                                          *
 *                   (c) Copyright 2006 ABM-utvikling                        *
 *                                                                          *
 * This program is free software; you can redistribute it and/or modify it  *
 * under the terms of the GNU General Public License as published by the    *
 * Free Software Foundation; either version 2 of the License, or (at your   *
 * option) any later version.                                               *
 *                                                                          *
 * This program is distributed in the hope that it will be useful, but      *
 * WITHOUT ANY WARRANTY; without even the implied warranty of               *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General *
 * Public License for more details. http://www.gnu.org/licenses/gpl.html    *
 *                                                                          *
 ****************************************************************************
 */
package no.abmu.questionnarie.domain;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.Errors;

import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Table;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Erik Romson, erik@zenior.no
 * @author $Author:$
 * @version $Rev:$
 * @date $Date:$
 * @copyright ABM-Utvikling
 * @hibernate.class table="FINANCE_POST_VALIDATOR"
 * @hibernate.cache usage="nonstrict-read-write"
 */
@javax.persistence.Entity
//@Table(schema="QUESTIONNARIE")
@Table(name = "QUESTIONNARIE_POST_VALIDATOR")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "postvalidator", discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue("PostValidator")
abstract public class PostValidator implements Entity {

    private static final Log logger = (Log) LogFactory.getLog(PostValidator.class);

    private Long id;

    /**
     * @return
     * @hibernate.id generator-class="increment"
     */
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public abstract boolean supports(Class clazz);

    public abstract void validate(PostData postData, Errors errors);

    protected String getFieldName(PostData postData) {
        if (postData != null) {
            return "fields[" + postData.getCode() + "].value";
        } else {
            return null;
        }
    }

    protected String[] getErrorMessageArguments(int value) {
        return new String[] { Integer.toString(value) };
    }

    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        final PostValidator that = (PostValidator) o;

        if (id != null ? !id.equals(that.id) : that.id != null) {
            return false;
        }

        return true;
    }

    public int hashCode() {
        return super.hashCode();
    }

    /**
     * @hidden
     */
    static public class Factory {
        static String patternStr = "(.+)\\((.+)\\)";
        static Pattern pattern = Pattern.compile(patternStr);

        static public PostValidator newInstance(String str) {
            String className = null;
            String args = null;
            if (str.indexOf("(") == -1) {
                className = str;
            } else if (str.endsWith("()")) {
                className = str.substring(0, str.length() - 2);
            } else {
                Matcher matcher = pattern.matcher(str);

                if (!matcher.matches()) {
                    throw new IllegalArgumentException(
                            "Problem parsing \"" + str + "\" with regex \"" + pattern + "\"");
                }
                className = matcher.group(1);
                args = matcher.group(2);
            }
            try {
                if (args == null) {
                    return (PostValidator) Class.forName(className).newInstance();
                } else {
                    String[] argArr = args.split(",");
                    List input = new ArrayList();
                    for (int i = 0; i < argArr.length; i++) {
                        input.add(String.class);
                    }
                    Object[] objArr = Arrays.asList(argArr).toArray();
                    Constructor constructor = Class.forName(className)
                            .getConstructor((Class[]) input.toArray(new Class[input.size()]));
                    return (PostValidator) constructor.newInstance(objArr);
                }
            } catch (InstantiationException e) {
                String message = "Exception when creating class " + className;
                logger.error(message, e.getCause());
                throw new RuntimeException(message, e.getCause());
            } catch (IllegalAccessException e) {
                String message = "The class " + className + " did not have a public empty contructor";
                logger.error(message, e.getCause());
                throw new RuntimeException(message, e.getCause());
            } catch (ClassNotFoundException e) {
                String message = "The class " + className + " given for creating a validator does not exist, "
                        + "this may be due to that we need to be able to change the input string for more "
                        + " complex validators in the future!!!";
                logger.error(message, e);
                throw new RuntimeException(message, e);
            } catch (NoSuchMethodException e) {
                String message = "There is no constructor that matches " + str
                        + ". Check constructors and classname";
                logger.error(message, e);
                throw new RuntimeException(message, e);
            } catch (InvocationTargetException e) {
                String message = "Problem invocating the contructor given by " + str;
                logger.error(message, e);
                throw new RuntimeException(message, e);
            }
        }
    }
}